xref: /linux/kernel/bpf/verifier.c (revision 02d3452bdd80cf645694110128db2ed67da96490)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/count_zeros.h>
9 #include <linux/kernel.h>
10 #include <linux/types.h>
11 #include <linux/slab.h>
12 #include <linux/bpf.h>
13 #include <linux/btf.h>
14 #include <linux/bpf_verifier.h>
15 #include <linux/filter.h>
16 #include <net/netlink.h>
17 #include <linux/file.h>
18 #include <linux/vmalloc.h>
19 #include <linux/stringify.h>
20 #include <linux/bsearch.h>
21 #include <linux/sort.h>
22 #include <linux/perf_event.h>
23 #include <linux/ctype.h>
24 #include <linux/error-injection.h>
25 #include <linux/bpf_lsm.h>
26 #include <linux/security.h>
27 #include <linux/verification.h>
28 #include <linux/keyctl.h>
29 #include <linux/btf_ids.h>
30 #include <linux/poison.h>
31 #include <linux/module.h>
32 #include <linux/cpumask.h>
33 #include <linux/cnum.h>
34 #include <linux/gcd.h>
35 #include <linux/unaligned.h>
36 #include <linux/bpf_mem_alloc.h>
37 #include <net/xdp.h>
38 #include <linux/trace_events.h>
39 #include <linux/kallsyms.h>
40 
41 #include "diagnostics.h"
42 #include "disasm.h"
43 
44 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
45 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
46 	[_id] = & _name ## _verifier_ops,
47 #define BPF_MAP_TYPE(_id, _ops)
48 #define BPF_LINK_TYPE(_id, _name)
49 #include <linux/bpf_types.h>
50 #undef BPF_PROG_TYPE
51 #undef BPF_MAP_TYPE
52 #undef BPF_LINK_TYPE
53 };
54 
55 enum bpf_features {
56 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
57 	BPF_FEAT_STREAMS	     = 1,
58 	__MAX_BPF_FEAT,
59 };
60 
61 struct bpf_mem_alloc bpf_global_percpu_ma;
62 static bool bpf_global_percpu_ma_set;
63 
64 /* bpf_check() is a static code analyzer that walks eBPF program
65  * instruction by instruction and updates register/stack state.
66  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
67  *
68  * The first pass is depth-first-search to check that the program is a DAG.
69  * It rejects the following programs:
70  * - larger than BPF_MAXINSNS insns
71  * - if loop is present (detected via back-edge)
72  * - unreachable insns exist (shouldn't be a forest. program = one function)
73  * - out of bounds or malformed jumps
74  * The second pass is all possible path descent from the 1st insn.
75  * Since it's analyzing all paths through the program, the length of the
76  * analysis is limited to 64k insn, which may be hit even if total number of
77  * insn is less then 4K, but there are too many branches that change stack/regs.
78  * Number of 'branches to be analyzed' is limited to 1k
79  *
80  * On entry to each instruction, each register has a type, and the instruction
81  * changes the types of the registers depending on instruction semantics.
82  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
83  * copied to R1.
84  *
85  * All registers are 64-bit.
86  * R0 - return register
87  * R1-R5 argument passing registers
88  * R6-R9 callee saved registers
89  * R10 - frame pointer read-only
90  *
91  * At the start of BPF program the register R1 contains a pointer to bpf_context
92  * and has type PTR_TO_CTX.
93  *
94  * Verifier tracks arithmetic operations on pointers in case:
95  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
96  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
97  * 1st insn copies R10 (which has FRAME_PTR) type into R1
98  * and 2nd arithmetic instruction is pattern matched to recognize
99  * that it wants to construct a pointer to some element within stack.
100  * So after 2nd insn, the register R1 has type PTR_TO_STACK
101  * (and -20 constant is saved for further stack bounds checking).
102  * Meaning that this reg is a pointer to stack plus known immediate constant.
103  *
104  * Most of the time the registers have SCALAR_VALUE type, which
105  * means the register has some value, but it's not a valid pointer.
106  * (like pointer plus pointer becomes SCALAR_VALUE type)
107  *
108  * When verifier sees load or store instructions the type of base register
109  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
110  * four pointer types recognized by check_mem_access() function.
111  *
112  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
113  * and the range of [ptr, ptr + map's value_size) is accessible.
114  *
115  * registers used to pass values to function calls are checked against
116  * function argument constraints.
117  *
118  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
119  * It means that the register type passed to this function must be
120  * PTR_TO_STACK and it will be used inside the function as
121  * 'pointer to map element key'
122  *
123  * For example the argument constraints for bpf_map_lookup_elem():
124  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
125  *   .arg1_type = ARG_CONST_MAP_PTR,
126  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
127  *
128  * ret_type says that this function returns 'pointer to map elem value or null'
129  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
130  * 2nd argument should be a pointer to stack, which will be used inside
131  * the helper function as a pointer to map element key.
132  *
133  * On the kernel side the helper function looks like:
134  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
135  * {
136  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
137  *    void *key = (void *) (unsigned long) r2;
138  *    void *value;
139  *
140  *    here kernel can access 'key' and 'map' pointers safely, knowing that
141  *    [key, key + map->key_size) bytes are valid and were initialized on
142  *    the stack of eBPF program.
143  * }
144  *
145  * Corresponding eBPF program may look like:
146  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
147  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
148  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
149  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
150  * here verifier looks at prototype of map_lookup_elem() and sees:
151  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
152  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
153  *
154  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
155  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
156  * and were initialized prior to this call.
157  * If it's ok, then verifier allows this BPF_CALL insn and looks at
158  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
159  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
160  * returns either pointer to map value or NULL.
161  *
162  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
163  * insn, the register holding that pointer in the true branch changes state to
164  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
165  * branch. See check_cond_jmp_op().
166  *
167  * After the call R0 is set to return type of the function and registers R1-R5
168  * are set to NOT_INIT to indicate that they are no longer readable.
169  *
170  * The following reference types represent a potential reference to a kernel
171  * resource which, after first being allocated, must be checked and freed by
172  * the BPF program:
173  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
174  *
175  * When the verifier sees a helper call return a reference type, it allocates a
176  * pointer id for the reference and stores it in the current function state.
177  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
178  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
179  * passes through a NULL-check conditional. For the branch wherein the state is
180  * changed to CONST_IMM, the verifier releases the reference.
181  *
182  * For each helper function that allocates a reference, such as
183  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
184  * bpf_sk_release(). When a reference type passes into the release function,
185  * the verifier also releases the reference. If any unchecked or unreleased
186  * reference remains at the end of the program, the verifier rejects it.
187  */
188 
189 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
190 struct bpf_verifier_stack_elem {
191 	/* verifier state is 'st'
192 	 * before processing instruction 'insn_idx'
193 	 * and after processing instruction 'prev_insn_idx'
194 	 */
195 	struct bpf_verifier_state st;
196 	int insn_idx;
197 	int prev_insn_idx;
198 	struct bpf_verifier_stack_elem *next;
199 	/* length of verifier log at the time this state was pushed on stack */
200 	u32 log_pos;
201 	u64 diag_log_pos;
202 };
203 
204 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
205 #define BPF_COMPLEXITY_LIMIT_STATES	64
206 
207 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
208 
209 #define BPF_PRIV_STACK_MIN_SIZE		64
210 
211 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
212 static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
213 static int release_reference_nomark(struct bpf_verifier_env *env, int id);
214 static int release_reference(struct bpf_verifier_env *env, int id);
215 static int invalidate_reference(struct bpf_verifier_env *env, int id);
216 static u32 reg_lifetime_id(struct bpf_verifier_env *env,
217 			   const struct bpf_reg_state *reg);
218 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
219 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env);
220 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
221 static bool is_tracing_prog_type(enum bpf_prog_type type);
222 static int ref_set_non_owning(struct bpf_verifier_env *env,
223 			      struct bpf_reg_state *reg);
224 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
225 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
226 static bool in_rcu_callback(struct bpf_verifier_env *env);
227 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
228 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
229 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
230 
231 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
232 			      struct bpf_map *map,
233 			      bool unpriv, bool poison)
234 {
235 	unpriv |= bpf_map_ptr_unpriv(aux);
236 	aux->map_ptr_state.unpriv = unpriv;
237 	aux->map_ptr_state.poison = poison;
238 	aux->map_ptr_state.map_ptr = map;
239 }
240 
241 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
242 {
243 	bool poisoned = bpf_map_key_poisoned(aux);
244 
245 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
246 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
247 }
248 
249 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
250 {
251 	ref_obj->id = reg->id;
252 	ref_obj->parent_id = reg->parent_id;
253 	ref_obj->cnt++;
254 }
255 
256 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
257 {
258 	if (ref_obj->cnt > 1) {
259 		verifier_bug(env, "function expects only one referenced object but got %d\n",
260 			     ref_obj->cnt);
261 		return -EFAULT;
262 	}
263 
264 	return 0;
265 }
266 
267 struct bpf_kfunc_meta {
268 	struct btf *btf;
269 	const struct btf_type *proto;
270 	const char *name;
271 	const u32 *flags;
272 	s32 id;
273 };
274 
275 struct btf *btf_vmlinux;
276 
277 typedef struct argno {
278 	int argno;
279 } argno_t;
280 
281 static argno_t argno_from_reg(u32 regno)
282 {
283 	return (argno_t){ .argno = regno };
284 }
285 
286 static argno_t argno_from_arg(u32 arg)
287 {
288 	return (argno_t){ .argno = -arg };
289 }
290 
291 static int reg_from_argno(argno_t a)
292 {
293 	if (a.argno >= 0)
294 		return a.argno;
295 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
296 		return -a.argno;
297 	return -1;
298 }
299 
300 static int arg_from_argno(argno_t a)
301 {
302 	if (a.argno < 0)
303 		return -a.argno;
304 	return -1;
305 }
306 
307 static int arg_idx_from_argno(argno_t a)
308 {
309 	return arg_from_argno(a) - 1;
310 }
311 
312 /* Normalize helper register numbers and kfunc argument numbers to ABI slots. */
313 static u32 arg_slot_from_argno(argno_t a)
314 {
315 	return abs(a.argno) - 1;
316 }
317 
318 static const char *btf_type_name(const struct btf *btf, u32 id)
319 {
320 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
321 }
322 
323 static DEFINE_MUTEX(bpf_verifier_lock);
324 static DEFINE_MUTEX(btf_vmlinux_lock);
325 static DEFINE_MUTEX(bpf_percpu_ma_lock);
326 
327 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
328 {
329 	struct bpf_verifier_env *env = private_data;
330 	va_list args;
331 
332 	if (!bpf_verifier_log_needed(&env->log))
333 		return;
334 
335 	va_start(args, fmt);
336 	bpf_verifier_vlog(&env->log, fmt, args);
337 	va_end(args);
338 }
339 
340 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
341 				   struct bpf_reg_state *reg,
342 				   struct bpf_retval_range range, const char *ctx,
343 				   const char *reg_name)
344 {
345 	bool unknown = true;
346 
347 	verbose(env, "%s the register %s has", ctx, reg_name);
348 	if (reg_smin(reg) > S64_MIN) {
349 		verbose(env, " smin=%lld", reg_smin(reg));
350 		unknown = false;
351 	}
352 	if (reg_smax(reg) < S64_MAX) {
353 		verbose(env, " smax=%lld", reg_smax(reg));
354 		unknown = false;
355 	}
356 	if (unknown)
357 		verbose(env, " unknown scalar value");
358 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
359 }
360 
361 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
362 {
363 	enum bpf_reg_type type;
364 
365 	type = reg->type;
366 	if (type_may_be_null(type))
367 		return false;
368 
369 	/*
370 	 * The types below guarantee a non-NULL base, an unbounded offset can
371 	 * still wrap base + offset to zero.
372 	 */
373 	if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF)
374 		return false;
375 
376 	type = base_type(type);
377 	return type == PTR_TO_SOCKET ||
378 		type == PTR_TO_TCP_SOCK ||
379 		type == PTR_TO_XDP_SOCK ||
380 		type == PTR_TO_BUF ||
381 		type == PTR_TO_MAP_VALUE ||
382 		type == PTR_TO_MAP_KEY ||
383 		type == PTR_TO_SOCK_COMMON ||
384 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
385 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
386 		type == CONST_PTR_TO_MAP;
387 }
388 
389 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
390 {
391 	struct btf_record *rec = NULL;
392 	struct btf_struct_meta *meta;
393 
394 	if (reg->type == PTR_TO_MAP_VALUE) {
395 		rec = reg->map_ptr->record;
396 	} else if (type_is_ptr_alloc_obj(reg->type)) {
397 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
398 		if (meta)
399 			rec = meta->record;
400 	}
401 	return rec;
402 }
403 
404 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
405 {
406 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
407 
408 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
409 }
410 
411 static const struct btf_type *subprog_ret_type(struct bpf_verifier_env *env, int subprog)
412 {
413 	const struct btf_type *func, *func_proto;
414 	const struct btf *btf = env->prog->aux->btf;
415 	u32 btf_id;
416 
417 	if (!btf || !env->prog->aux->func_info)
418 		return NULL;
419 
420 	btf_id = env->prog->aux->func_info[subprog].type_id;
421 
422 	/* Both already validated by prepare_btf_func() at prog load. */
423 	func = btf_type_by_id(btf, btf_id);
424 	func_proto = btf_type_by_id(btf, func->type);
425 
426 	return btf_type_skip_modifiers(btf, func_proto->type, NULL);
427 }
428 
429 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
430 {
431 	const struct btf_type *type = subprog_ret_type(env, subprog);
432 
433 	return type && btf_type_is_void(type);
434 }
435 
436 static u32 ret_regs_cnt(u32 size)
437 {
438 	return size > 8 && size <= 16 ? 2 : 1;
439 }
440 
441 /* Registers holding a function return value, in order. See ret_regs_cnt(). */
442 static const int ret_regs[] = { BPF_REG_0, BPF_REG_2 };
443 
444 static int bpf_compute_subprog_ret_regs(struct bpf_verifier_env *env)
445 {
446 	const struct btf *btf = env->prog->aux->btf;
447 	const struct btf_type *type;
448 	int subprog;
449 	u32 size;
450 
451 	if (!env->prog->jit_requested || bpf_prog_is_offloaded(env->prog->aux))
452 		return 0;
453 
454 	/*
455 	 * Skip the main program: its return value is the program's exit code,
456 	 * read out of R0, so it never uses the register pair. An extension does
457 	 * have a real prototype for subprog 0, but btf_check_func_type_match()
458 	 * refuses to replace a function returning more than 8 bytes.
459 	 */
460 	for (subprog = 1; subprog < env->subprog_cnt; subprog++) {
461 		type = subprog_ret_type(env, subprog);
462 		if (!type || btf_type_is_void(type))
463 			continue;
464 		if (verifier_bug_if(IS_ERR(btf_resolve_size(btf, type, &size)), env,
465 				    "cannot size return type of subprog %d", subprog))
466 			return -EFAULT;
467 		if (ret_regs_cnt(size) > 1) {
468 			subprog_info(env, subprog)->ret_reg_pair = true;
469 			env->prog->jit_required = 1;
470 		}
471 	}
472 
473 	return 0;
474 }
475 
476 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)
477 {
478 	struct bpf_func_info *info;
479 
480 	if (!env->prog->aux->func_info)
481 		return "";
482 
483 	info = &env->prog->aux->func_info[subprog];
484 	return btf_type_name(env->prog->aux->btf, info->type_id);
485 }
486 
487 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
488 {
489 	struct bpf_subprog_info *info = subprog_info(env, subprog);
490 
491 	info->is_cb = true;
492 	info->is_async_cb = true;
493 	info->is_exception_cb = true;
494 }
495 
496 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
497 {
498 	return subprog_info(env, subprog)->is_exception_cb;
499 }
500 
501 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
502 {
503 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
504 }
505 
506 static bool type_is_rdonly_mem(u32 type)
507 {
508 	return type & MEM_RDONLY;
509 }
510 
511 static bool is_acquire_function(enum bpf_func_id func_id,
512 				const struct bpf_map *map)
513 {
514 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515 
516 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
517 	    func_id == BPF_FUNC_sk_lookup_udp ||
518 	    func_id == BPF_FUNC_skc_lookup_tcp ||
519 	    func_id == BPF_FUNC_ringbuf_reserve ||
520 	    func_id == BPF_FUNC_kptr_xchg)
521 		return true;
522 
523 	if (func_id == BPF_FUNC_map_lookup_elem &&
524 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
525 	     map_type == BPF_MAP_TYPE_SOCKHASH))
526 		return true;
527 
528 	return false;
529 }
530 
531 static bool is_ptr_cast_function(enum bpf_func_id func_id)
532 {
533 	return func_id == BPF_FUNC_tcp_sock ||
534 		func_id == BPF_FUNC_sk_fullsock ||
535 		func_id == BPF_FUNC_skc_to_tcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
537 		func_id == BPF_FUNC_skc_to_udp6_sock ||
538 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
539 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
540 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
541 }
542 
543 static bool is_sync_callback_calling_kfunc(u32 btf_id);
544 static bool is_async_callback_calling_kfunc(u32 btf_id);
545 static bool is_call_rcu_kfunc(u32 btf_id);
546 static bool is_callback_calling_kfunc(u32 btf_id);
547 
548 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
549 static bool is_task_work_add_kfunc(u32 func_id);
550 
551 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
552 {
553 	return func_id == BPF_FUNC_for_each_map_elem ||
554 	       func_id == BPF_FUNC_find_vma ||
555 	       func_id == BPF_FUNC_loop ||
556 	       func_id == BPF_FUNC_user_ringbuf_drain;
557 }
558 
559 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
560 {
561 	return func_id == BPF_FUNC_timer_set_callback;
562 }
563 
564 static bool is_callback_calling_function(enum bpf_func_id func_id)
565 {
566 	return is_sync_callback_calling_function(func_id) ||
567 	       is_async_callback_calling_function(func_id);
568 }
569 
570 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
571 {
572 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
573 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
574 }
575 
576 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
577 {
578 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
579 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
580 }
581 
582 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
583 {
584 	/* bpf_timer callbacks are never sleepable. */
585 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
586 		return false;
587 
588 	/* bpf_call_rcu and bpf_call_rcu_tasks_trace callbacks are never sleepable. */
589 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && is_call_rcu_kfunc(insn->imm))
590 		return false;
591 
592 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
593 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
594 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
595 		return true;
596 
597 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
598 	return false;
599 }
600 
601 /* From here on the maps of the program count it as a sleepable user. */
602 static void mark_sleepable_async_cb(struct bpf_verifier_env *env)
603 {
604 	int i;
605 
606 	if (bpf_prog_runs_sleepable(env->prog))
607 		return;
608 
609 	env->prog->aux->sleepable_async_cb = true;
610 	for (i = 0; i < env->used_map_cnt; i++)
611 		atomic64_inc(&env->used_maps[i]->sleepable_refcnt);
612 }
613 
614 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
615 {
616 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
617 }
618 
619 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
620 {
621 	int allocated_slots = bpf_stack_nr_slots(state);
622 
623 	/*
624 	 * We need to check that slots between [spi - nr_slots + 1, spi] are
625 	 * within [0, allocated_stack).
626 	 *
627 	 * Please note that the spi grows downwards. For example, a dynptr
628 	 * takes the size of two stack slots; the first slot will be at
629 	 * spi and the second slot will be at spi - 1.
630 	 */
631 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
632 }
633 
634 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
635 			          const char *obj_kind, int nr_slots)
636 {
637 	int off, spi;
638 
639 	if (!tnum_is_const(reg->var_off)) {
640 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
641 		return -EINVAL;
642 	}
643 
644 	off = reg->var_off.value;
645 	if (off >= 0 || off % BPF_REG_SIZE) {
646 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
647 		return -EINVAL;
648 	}
649 
650 	spi = bpf_get_spi(off);
651 	if (spi + 1 < nr_slots) {
652 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
653 		return -EINVAL;
654 	}
655 
656 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
657 		return -ERANGE;
658 	return spi;
659 }
660 
661 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
662 {
663 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
664 }
665 
666 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
667 {
668 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
669 }
670 
671 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
672 {
673 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
674 }
675 
676 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
677 {
678 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
679 	case DYNPTR_TYPE_LOCAL:
680 		return BPF_DYNPTR_TYPE_LOCAL;
681 	case DYNPTR_TYPE_RINGBUF:
682 		return BPF_DYNPTR_TYPE_RINGBUF;
683 	case DYNPTR_TYPE_SKB:
684 		return BPF_DYNPTR_TYPE_SKB;
685 	case DYNPTR_TYPE_XDP:
686 		return BPF_DYNPTR_TYPE_XDP;
687 	case DYNPTR_TYPE_SKB_META:
688 		return BPF_DYNPTR_TYPE_SKB_META;
689 	case DYNPTR_TYPE_FILE:
690 		return BPF_DYNPTR_TYPE_FILE;
691 	default:
692 		return BPF_DYNPTR_TYPE_INVALID;
693 	}
694 }
695 
696 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
697 {
698 	switch (type) {
699 	case BPF_DYNPTR_TYPE_LOCAL:
700 		return DYNPTR_TYPE_LOCAL;
701 	case BPF_DYNPTR_TYPE_RINGBUF:
702 		return DYNPTR_TYPE_RINGBUF;
703 	case BPF_DYNPTR_TYPE_SKB:
704 		return DYNPTR_TYPE_SKB;
705 	case BPF_DYNPTR_TYPE_XDP:
706 		return DYNPTR_TYPE_XDP;
707 	case BPF_DYNPTR_TYPE_SKB_META:
708 		return DYNPTR_TYPE_SKB_META;
709 	case BPF_DYNPTR_TYPE_FILE:
710 		return DYNPTR_TYPE_FILE;
711 	default:
712 		return 0;
713 	}
714 }
715 
716 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
717 {
718 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
719 }
720 
721 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
722 			      enum bpf_dynptr_type type,
723 			      bool first_slot, int id, int parent_id);
724 
725 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
726 				   struct bpf_reg_state *sreg1,
727 				   struct bpf_reg_state *sreg2,
728 				   enum bpf_dynptr_type type, int parent_id)
729 {
730 	int id = ++env->id_gen;
731 
732 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
733 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
734 }
735 
736 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
737 			       struct bpf_reg_state *reg,
738 			       enum bpf_dynptr_type type)
739 {
740 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
741 }
742 
743 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
744 				        struct bpf_func_state *state, int spi);
745 
746 static int destroy_dynptrs_in_stack_slots(struct bpf_verifier_env *env,
747 					  struct bpf_func_state *state,
748 					  int first_spi, int last_spi)
749 {
750 	int spi, err;
751 
752 	for (spi = first_spi; spi <= last_spi; spi++) {
753 		err = destroy_if_dynptr_stack_slot(env, state, spi);
754 		if (err)
755 			return err;
756 	}
757 
758 	return 0;
759 }
760 
761 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
762 				   enum bpf_arg_type arg_type, int insn_idx,
763 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
764 {
765 	struct bpf_func_state *state = bpf_func(env, reg);
766 	int spi, i, err, parent_id = 0;
767 	enum bpf_dynptr_type type;
768 
769 	spi = dynptr_get_spi(env, reg);
770 	if (spi < 0)
771 		return spi;
772 
773 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
774 	 * hence we need to destroy dynptrs in both slots,
775 	 * to ensure that for the following example:
776 	 *	[d1][d1][d2][d2]
777 	 * spi    3   2   1   0
778 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
779 	 * case they do belong to same dynptr, second call won't see slot_type
780 	 * as STACK_DYNPTR and will simply skip destruction.
781 	 */
782 	err = destroy_dynptrs_in_stack_slots(env, state, spi - 1, spi);
783 	if (err)
784 		return err;
785 
786 	for (i = 0; i < BPF_REG_SIZE; i++) {
787 		bpf_stack_slot(state, spi)->slot_type[i] = STACK_DYNPTR;
788 		bpf_stack_slot(state, spi - 1)->slot_type[i] = STACK_DYNPTR;
789 	}
790 
791 	type = arg_to_dynptr_type(arg_type);
792 	if (type == BPF_DYNPTR_TYPE_INVALID)
793 		return -EINVAL;
794 
795 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
796 		err = validate_ref_obj(env, ref_obj);
797 		if (err)
798 			return err;
799 
800 		/* All non-clone constructors take their backing object in R1. */
801 		parent_id = reg_lifetime_id(env, &cur_regs(env)[BPF_REG_1]);
802 
803 		if (dynptr_type_referenced(type)) {
804 			int id;
805 
806 			/*
807 			 * Create an intermediate reference that tracks the referenced
808 			 * object for the referenced dynptr. Freeing a referenced dynptr
809 			 * through helpers/kfuncs will invalidate all clones.
810 			 */
811 			id = acquire_reference(env, insn_idx, parent_id);
812 			if (id < 0)
813 				return id;
814 
815 			parent_id = id;
816 		}
817 	} else { /* bpf_dynptr_clone() */
818 		parent_id = dynptr->parent_id;
819 	}
820 
821 	mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr,
822 			       &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id);
823 
824 	return 0;
825 }
826 
827 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
828 {
829 	int i;
830 
831 	for (i = 0; i < BPF_REG_SIZE; i++) {
832 		stack[0].slot_type[i] = STACK_INVALID;
833 		stack[1].slot_type[i] = STACK_INVALID;
834 	}
835 
836 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
837 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
838 }
839 
840 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
841 {
842 	struct bpf_func_state *state = bpf_func(env, reg);
843 	int spi;
844 
845 	spi = dynptr_get_spi(env, reg);
846 	if (spi < 0)
847 		return spi;
848 
849 	/*
850 	 * For referenced dynptr, release the parent ref which cascades to
851 	 * all clones and derived slices. For non-referenced dynptr, only
852 	 * the dynptr and slices derived from it will be invalidated.
853 	 */
854 	reg = &bpf_stack_slot(state, spi)->spilled_ptr;
855 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
856 				      ? reg->parent_id
857 				      : reg->id);
858 }
859 
860 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
861 			       struct bpf_reg_state *reg);
862 
863 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
864 {
865 	if (!env->allow_ptr_leaks)
866 		bpf_mark_reg_not_init(env, reg);
867 	else
868 		__mark_reg_unknown(env, reg);
869 }
870 
871 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
872 {
873 	struct bpf_stack_state *stack;
874 	struct bpf_func_state *state;
875 	struct bpf_reg_state *reg;
876 	int ref_cnt = 0;
877 
878 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
879 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
880 			continue;
881 		if (!stack->spilled_ptr.dynptr.first_slot)
882 			continue;
883 		if (stack->spilled_ptr.parent_id == v_parent_id)
884 			ref_cnt++;
885 	}));
886 
887 	return ref_cnt;
888 }
889 
890 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
891 				        struct bpf_func_state *state, int spi)
892 {
893 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
894 	int err = 0;
895 
896 	/* We always ensure that STACK_DYNPTR is never set partially,
897 	 * hence just checking for slot_type[0] is enough. This is
898 	 * different for STACK_SPILL, where it may be only set for
899 	 * 1 byte, so code has to use is_spilled_reg.
900 	 */
901 	if (slot->slot_type[0] != STACK_DYNPTR)
902 		return 0;
903 
904 	/* Reposition spi to first slot */
905 	if (!slot->spilled_ptr.dynptr.first_slot) {
906 		spi = spi + 1;
907 		slot = bpf_stack_slot(state, spi);
908 	}
909 
910 	/*
911 	 * A referenced dynptr can be overwritten only if there is at
912 	 * least one other dynptr sharing the same virtual ref parent,
913 	 * ensuring the reference can still be properly released.
914 	 */
915 	if (dynptr_type_referenced(slot->spilled_ptr.dynptr.type) &&
916 	    dynptr_ref_cnt(env, slot->spilled_ptr.parent_id) <= 1) {
917 		verbose(env, "cannot overwrite referenced dynptr\n");
918 		bpf_diag_res(
919 			env, env->insn_idx, "referenced dynptr overwrite",
920 			"This stack slot contains a dynptr that owns or protects a referenced resource. Overwriting the last dynptr for that resource would lose the verifier-tracked release path.",
921 			"Release or clone the dynptr so another live dynptr still tracks the referenced resource before overwriting this stack slot.");
922 		return -EINVAL;
923 	}
924 
925 	/* Invalidate the dynptr and any derived slices */
926 	err = release_reference(env, slot->spilled_ptr.id);
927 	if (!err) {
928 		mark_stack_slot_scratched(env, spi);
929 		mark_stack_slot_scratched(env, spi - 1);
930 	}
931 
932 	return err;
933 }
934 
935 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
936 {
937 	int spi;
938 
939 	if (reg->type == CONST_PTR_TO_DYNPTR)
940 		return false;
941 
942 	spi = dynptr_get_spi(env, reg);
943 
944 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
945 	 * error because this just means the stack state hasn't been updated yet.
946 	 * We will do check_mem_access to check and update stack bounds later.
947 	 */
948 	if (spi < 0 && spi != -ERANGE)
949 		return false;
950 
951 	/* We don't need to check if the stack slots are marked by previous
952 	 * dynptr initializations because we allow overwriting existing unreferenced
953 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
954 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
955 	 * touching are completely destructed before we reinitialize them for a new
956 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
957 	 * instead of delaying it until the end where the user will get "Unreleased
958 	 * reference" error.
959 	 */
960 	return true;
961 }
962 
963 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
964 {
965 	struct bpf_func_state *state = bpf_func(env, reg);
966 	struct bpf_stack_state *slot;
967 	int i, spi;
968 
969 	/* This already represents first slot of initialized bpf_dynptr.
970 	 *
971 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
972 	 * check_func_arg_reg_off's logic, so we don't need to check its
973 	 * offset and alignment.
974 	 */
975 	if (reg->type == CONST_PTR_TO_DYNPTR)
976 		return true;
977 
978 	spi = dynptr_get_spi(env, reg);
979 	if (spi < 0)
980 		return false;
981 	slot = bpf_stack_slot(state, spi);
982 	if (!slot->spilled_ptr.dynptr.first_slot)
983 		return false;
984 
985 	for (i = 0; i < BPF_REG_SIZE; i++) {
986 		if (slot->slot_type[i] != STACK_DYNPTR ||
987 		    bpf_stack_slot(state, spi - 1)->slot_type[i] != STACK_DYNPTR)
988 			return false;
989 	}
990 
991 	return true;
992 }
993 
994 static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
995 {
996 	struct bpf_func_state *state;
997 	int spi;
998 
999 	if (reg->type == CONST_PTR_TO_DYNPTR)
1000 		return reg->dynptr.type;
1001 
1002 	spi = dynptr_get_spi(env, reg);
1003 	if (spi < 0)
1004 		return BPF_DYNPTR_TYPE_INVALID;
1005 	state = bpf_func(env, reg);
1006 	return bpf_stack_slot(state, spi)->spilled_ptr.dynptr.type;
1007 }
1008 
1009 static bool dynptr_write_changes_pkt_data(enum bpf_dynptr_type type)
1010 {
1011 	return type == BPF_DYNPTR_TYPE_SKB || type == BPF_DYNPTR_TYPE_SKB_META;
1012 }
1013 
1014 /* The data of the other types is contiguous: bpf_dynptr_slice() does not use the buffer. */
1015 static bool dynptr_slice_may_be_buffer(enum bpf_dynptr_type type)
1016 {
1017 	return type != BPF_DYNPTR_TYPE_LOCAL && type != BPF_DYNPTR_TYPE_RINGBUF &&
1018 	       type != BPF_DYNPTR_TYPE_SKB_META;
1019 }
1020 
1021 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1022 				    enum bpf_arg_type arg_type)
1023 {
1024 	/*
1025 	 * ARG_PTR_TO_DYNPTR without a type flag takes any type of dynptr.
1026 	 * Test the flags rather than the whole arg_type, which may carry
1027 	 * unrelated ones such as PTR_MAYBE_NULL.
1028 	 */
1029 	if (!(arg_type & DYNPTR_TYPE_FLAG_MASK))
1030 		return true;
1031 
1032 	return dynptr_reg_type(env, reg) == arg_to_dynptr_type(arg_type);
1033 }
1034 
1035 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1036 
1037 static bool in_rcu_cs(struct bpf_verifier_env *env);
1038 
1039 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta);
1040 
1041 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1042 				 struct bpf_call_arg_meta *meta,
1043 				 struct bpf_reg_state *reg, int insn_idx,
1044 				 struct btf *btf, u32 btf_id, int nr_slots)
1045 {
1046 	struct bpf_func_state *state = bpf_func(env, reg);
1047 	int spi, i, j, id;
1048 
1049 	spi = iter_get_spi(env, reg, nr_slots);
1050 	if (spi < 0)
1051 		return spi;
1052 
1053 	id = acquire_reference(env, insn_idx, 0);
1054 	if (id < 0)
1055 		return id;
1056 
1057 	for (i = 0; i < nr_slots; i++) {
1058 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1059 		struct bpf_reg_state *st = &slot->spilled_ptr;
1060 
1061 		__mark_reg_known_zero(st);
1062 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1063 		if (is_kfunc_rcu_protected(meta)) {
1064 			if (in_rcu_cs(env))
1065 				st->type |= MEM_RCU;
1066 			else
1067 				st->type |= PTR_UNTRUSTED;
1068 		}
1069 		st->id = i == 0 ? id : 0;
1070 		st->iter.btf = btf;
1071 		st->iter.btf_id = btf_id;
1072 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1073 		st->iter.depth = 0;
1074 
1075 		for (j = 0; j < BPF_REG_SIZE; j++)
1076 			slot->slot_type[j] = STACK_ITER;
1077 
1078 		mark_stack_slot_scratched(env, spi - i);
1079 	}
1080 
1081 	return 0;
1082 }
1083 
1084 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1085 				   struct bpf_reg_state *reg, int nr_slots)
1086 {
1087 	struct bpf_func_state *state = bpf_func(env, reg);
1088 	int spi, i, j, err;
1089 
1090 	spi = iter_get_spi(env, reg, nr_slots);
1091 	if (spi < 0)
1092 		return spi;
1093 
1094 	for (i = 0; i < nr_slots; i++) {
1095 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1096 		struct bpf_reg_state *st = &slot->spilled_ptr;
1097 
1098 		if (i == 0) {
1099 			err = release_reference(env, st->id);
1100 			if (err)
1101 				return err;
1102 		}
1103 
1104 		bpf_mark_reg_not_init(env, st);
1105 
1106 		for (j = 0; j < BPF_REG_SIZE; j++)
1107 			slot->slot_type[j] = STACK_INVALID;
1108 
1109 		mark_stack_slot_scratched(env, spi - i);
1110 	}
1111 
1112 	return 0;
1113 }
1114 
1115 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1116 				     struct bpf_reg_state *reg, int nr_slots)
1117 {
1118 	struct bpf_func_state *state = bpf_func(env, reg);
1119 	int spi, i, j;
1120 
1121 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1122 	 * will do check_mem_access to check and update stack bounds later, so
1123 	 * return true for that case.
1124 	 */
1125 	spi = iter_get_spi(env, reg, nr_slots);
1126 	if (spi == -ERANGE)
1127 		return true;
1128 	if (spi < 0)
1129 		return false;
1130 
1131 	for (i = 0; i < nr_slots; i++) {
1132 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1133 
1134 		for (j = 0; j < BPF_REG_SIZE; j++)
1135 			if (slot->slot_type[j] == STACK_ITER)
1136 				return false;
1137 	}
1138 
1139 	return true;
1140 }
1141 
1142 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1143 				   struct btf *btf, u32 btf_id, int nr_slots)
1144 {
1145 	struct bpf_func_state *state = bpf_func(env, reg);
1146 	int spi, i, j;
1147 
1148 	spi = iter_get_spi(env, reg, nr_slots);
1149 	if (spi < 0)
1150 		return -EINVAL;
1151 
1152 	for (i = 0; i < nr_slots; i++) {
1153 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1154 		struct bpf_reg_state *st = &slot->spilled_ptr;
1155 
1156 		if (st->type & PTR_UNTRUSTED)
1157 			return -EPROTO;
1158 		/* only main (first) slot has id set */
1159 		if (i == 0 && !st->id)
1160 			return -EINVAL;
1161 		if (i != 0 && st->id)
1162 			return -EINVAL;
1163 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1164 			return -EINVAL;
1165 
1166 		for (j = 0; j < BPF_REG_SIZE; j++)
1167 			if (slot->slot_type[j] != STACK_ITER)
1168 				return -EINVAL;
1169 	}
1170 
1171 	return 0;
1172 }
1173 
1174 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1175 static int release_irq_state(struct bpf_verifier_env *env, int id);
1176 
1177 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1178 				     struct bpf_call_arg_meta *meta,
1179 				     struct bpf_reg_state *reg, int insn_idx,
1180 				     int kfunc_class)
1181 {
1182 	struct bpf_func_state *state = bpf_func(env, reg);
1183 	struct bpf_stack_state *slot;
1184 	struct bpf_reg_state *st;
1185 	int spi, i, id;
1186 
1187 	spi = irq_flag_get_spi(env, reg);
1188 	if (spi < 0)
1189 		return spi;
1190 
1191 	id = acquire_irq_state(env, insn_idx);
1192 	if (id < 0)
1193 		return id;
1194 
1195 	slot = bpf_stack_slot(state, spi);
1196 	st = &slot->spilled_ptr;
1197 
1198 	__mark_reg_known_zero(st);
1199 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1200 	st->id = id;
1201 	st->irq.kfunc_class = kfunc_class;
1202 
1203 	for (i = 0; i < BPF_REG_SIZE; i++)
1204 		slot->slot_type[i] = STACK_IRQ_FLAG;
1205 
1206 	mark_stack_slot_scratched(env, spi);
1207 	return 0;
1208 }
1209 
1210 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1211 				      int kfunc_class)
1212 {
1213 	struct bpf_func_state *state = bpf_func(env, reg);
1214 	struct bpf_stack_state *slot;
1215 	struct bpf_reg_state *st;
1216 	int spi, i, err;
1217 
1218 	spi = irq_flag_get_spi(env, reg);
1219 	if (spi < 0)
1220 		return spi;
1221 
1222 	slot = bpf_stack_slot(state, spi);
1223 	st = &slot->spilled_ptr;
1224 
1225 	if (st->irq.kfunc_class != kfunc_class) {
1226 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1227 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1228 		const char *reason;
1229 
1230 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1231 			flag_kfunc, used_kfunc);
1232 		reason = bpf_diag_fmt(env,
1233 				      "This IRQ flag was saved by %s IRQ kfuncs, but the restore call "
1234 			"belongs to the %s IRQ kfunc family. Save and restore operations "
1235 			"must use the same family.",
1236 			flag_kfunc, used_kfunc);
1237 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore mismatch", reason,
1238 			     "Restore the flag with the matching IRQ restore kfunc for the save "
1239 			     "operation that created it.",
1240 			     bpf_diag_irq_depth(env->cur_state));
1241 		return -EINVAL;
1242 	}
1243 
1244 	err = release_irq_state(env, st->id);
1245 	WARN_ON_ONCE(err && err != -EACCES);
1246 	if (err) {
1247 		int insn_idx = 0;
1248 
1249 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1250 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1251 				insn_idx = env->cur_state->refs[i].insn_idx;
1252 				break;
1253 			}
1254 		}
1255 
1256 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1257 			env->cur_state->active_irq_id, insn_idx);
1258 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore out of order",
1259 			     "IRQ-disabled regions must be restored in last-in, first-out order, "
1260 			     "but this restore does not match the currently active IRQ flag.",
1261 			     "Restore nested IRQ flags in the reverse order they were saved.",
1262 			     bpf_diag_irq_depth(env->cur_state));
1263 		return err;
1264 	}
1265 
1266 	bpf_mark_reg_not_init(env, st);
1267 
1268 	for (i = 0; i < BPF_REG_SIZE; i++)
1269 		slot->slot_type[i] = STACK_INVALID;
1270 
1271 	mark_stack_slot_scratched(env, spi);
1272 	return 0;
1273 }
1274 
1275 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1276 {
1277 	struct bpf_func_state *state = bpf_func(env, reg);
1278 	struct bpf_stack_state *slot;
1279 	int spi, i;
1280 
1281 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1282 	 * will do check_mem_access to check and update stack bounds later, so
1283 	 * return true for that case.
1284 	 */
1285 	spi = irq_flag_get_spi(env, reg);
1286 	if (spi == -ERANGE)
1287 		return true;
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	slot = bpf_stack_slot(state, spi);
1292 
1293 	for (i = 0; i < BPF_REG_SIZE; i++)
1294 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1295 			return false;
1296 	return true;
1297 }
1298 
1299 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1300 {
1301 	struct bpf_func_state *state = bpf_func(env, reg);
1302 	struct bpf_stack_state *slot;
1303 	struct bpf_reg_state *st;
1304 	int spi, i;
1305 
1306 	spi = irq_flag_get_spi(env, reg);
1307 	if (spi < 0)
1308 		return -EINVAL;
1309 
1310 	slot = bpf_stack_slot(state, spi);
1311 	st = &slot->spilled_ptr;
1312 
1313 	if (!st->id)
1314 		return -EINVAL;
1315 
1316 	for (i = 0; i < BPF_REG_SIZE; i++)
1317 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1318 			return -EINVAL;
1319 	return 0;
1320 }
1321 
1322 /* Check if given stack slot is "special":
1323  *   - spilled register state (STACK_SPILL);
1324  *   - dynptr state (STACK_DYNPTR);
1325  *   - iter state (STACK_ITER).
1326  *   - irq flag state (STACK_IRQ_FLAG)
1327  */
1328 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1329 {
1330 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1331 
1332 	switch (type) {
1333 	case STACK_SPILL:
1334 	case STACK_DYNPTR:
1335 	case STACK_ITER:
1336 	case STACK_IRQ_FLAG:
1337 		return true;
1338 	case STACK_INVALID:
1339 	case STACK_POISON:
1340 	case STACK_MISC:
1341 	case STACK_ZERO:
1342 		return false;
1343 	default:
1344 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1345 		return true;
1346 	}
1347 }
1348 
1349 /* The reg state of a pointer or a bounded scalar was saved when
1350  * it was spilled to the stack.
1351  */
1352 
1353 /*
1354  * Mark stack slot as STACK_MISC, unless it is already:
1355  * - STACK_INVALID, in which case they are equivalent.
1356  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1357  * - STACK_POISON, which truly forbids access to the slot.
1358  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1359  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1360  * unnecessary as both are considered equivalent when loading data and pruning,
1361  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1362  * slots.
1363  */
1364 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1365 {
1366 	if (*stype == STACK_ZERO)
1367 		return;
1368 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1369 		return;
1370 	*stype = STACK_MISC;
1371 }
1372 
1373 static void scrub_spilled_slot(u8 *stype)
1374 {
1375 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1376 		*stype = STACK_MISC;
1377 }
1378 
1379 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1380  * small to hold src. This is different from krealloc since we don't want to preserve
1381  * the contents of dst.
1382  *
1383  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1384  * not be allocated.
1385  */
1386 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1387 {
1388 	size_t alloc_bytes;
1389 	void *orig = dst;
1390 	size_t bytes;
1391 
1392 	if (ZERO_OR_NULL_PTR(src))
1393 		goto out;
1394 
1395 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1396 		return NULL;
1397 
1398 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1399 	dst = krealloc(orig, alloc_bytes, flags);
1400 	if (!dst) {
1401 		kfree(orig);
1402 		return NULL;
1403 	}
1404 
1405 	memcpy(dst, src, bytes);
1406 out:
1407 	return dst ? dst : ZERO_SIZE_PTR;
1408 }
1409 
1410 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1411  * small to hold new_n items. new items are zeroed out if the array grows.
1412  *
1413  * Contrary to krealloc_array, does not free arr if new_n is zero.
1414  */
1415 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1416 {
1417 	size_t alloc_size;
1418 	void *new_arr;
1419 
1420 	if (!new_n || old_n == new_n)
1421 		goto out;
1422 
1423 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1424 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1425 	if (!new_arr) {
1426 		kfree(arr);
1427 		return NULL;
1428 	}
1429 	arr = new_arr;
1430 
1431 	if (new_n > old_n)
1432 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1433 
1434 out:
1435 	return arr ? arr : ZERO_SIZE_PTR;
1436 }
1437 
1438 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1439 {
1440 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1441 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1442 	if (!dst->refs)
1443 		return -ENOMEM;
1444 
1445 	dst->acquired_refs = src->acquired_refs;
1446 	dst->active_locks = src->active_locks;
1447 	dst->active_preempt_locks = src->active_preempt_locks;
1448 	dst->active_rcu_locks = src->active_rcu_locks;
1449 	dst->active_irq_id = src->active_irq_id;
1450 	dst->active_lock_id = src->active_lock_id;
1451 	dst->active_lock_ptr = src->active_lock_ptr;
1452 	return 0;
1453 }
1454 
1455 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1456 {
1457 	size_t n = bpf_stack_nr_slots(src);
1458 
1459 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1460 				GFP_KERNEL_ACCOUNT);
1461 	if (!dst->stack)
1462 		return -ENOMEM;
1463 
1464 	dst->allocated_stack = src->allocated_stack;
1465 
1466 	/* copy stack args state */
1467 	n = src->out_stack_arg_cnt;
1468 	if (n) {
1469 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1470 						 sizeof(struct bpf_reg_state),
1471 						 GFP_KERNEL_ACCOUNT);
1472 		if (!dst->stack_arg_regs)
1473 			return -ENOMEM;
1474 	}
1475 
1476 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1477 	return 0;
1478 }
1479 
1480 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1481 {
1482 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1483 				    sizeof(struct bpf_reference_state));
1484 	if (!state->refs)
1485 		return -ENOMEM;
1486 
1487 	state->acquired_refs = n;
1488 	return 0;
1489 }
1490 
1491 /* Possibly update state->allocated_stack to be at least size bytes. Also
1492  * possibly update the function's high-water mark in its bpf_subprog_info.
1493  */
1494 int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1495 {
1496 	size_t old_n = bpf_stack_nr_slots(state), n;
1497 
1498 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1499 	size = round_up(size, BPF_REG_SIZE);
1500 	n = size / BPF_REG_SIZE;
1501 
1502 	if (old_n >= n)
1503 		return 0;
1504 
1505 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1506 	if (!state->stack)
1507 		return -ENOMEM;
1508 
1509 	state->allocated_stack = size;
1510 
1511 	/* update known max for given subprogram */
1512 	if (env->subprog_info[state->subprogno].stack_depth < size)
1513 		env->subprog_info[state->subprogno].stack_depth = size;
1514 
1515 	return 0;
1516 }
1517 
1518 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1519 				struct bpf_func_state *state, int cnt)
1520 {
1521 	size_t old_n = state->out_stack_arg_cnt;
1522 
1523 	if (old_n >= cnt)
1524 		return 0;
1525 
1526 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1527 					      sizeof(struct bpf_reg_state));
1528 	if (!state->stack_arg_regs)
1529 		return -ENOMEM;
1530 
1531 	state->out_stack_arg_cnt = cnt;
1532 	return 0;
1533 }
1534 
1535 /* Acquire a pointer id from the env and update the state->refs to include
1536  * this new pointer reference.
1537  * On success, returns a valid pointer id to associate with the register
1538  * On failure, returns a negative errno.
1539  */
1540 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1541 {
1542 	struct bpf_verifier_state *state = env->cur_state;
1543 	int new_ofs = state->acquired_refs;
1544 	int err;
1545 
1546 	err = resize_reference_state(state, state->acquired_refs + 1);
1547 	if (err)
1548 		return NULL;
1549 	state->refs[new_ofs].insn_idx = insn_idx;
1550 
1551 	return &state->refs[new_ofs];
1552 }
1553 
1554 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1555 {
1556 	struct bpf_reference_state *s;
1557 
1558 	s = acquire_reference_state(env, insn_idx);
1559 	if (!s)
1560 		return -ENOMEM;
1561 	s->type = REF_TYPE_PTR;
1562 	s->id = ++env->id_gen;
1563 	s->parent_id = parent_id;
1564 	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
1565 	return s->id;
1566 }
1567 
1568 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1569 			      int id, void *ptr)
1570 {
1571 	struct bpf_verifier_state *state = env->cur_state;
1572 	struct bpf_reference_state *s;
1573 
1574 	s = acquire_reference_state(env, insn_idx);
1575 	if (!s)
1576 		return -ENOMEM;
1577 	s->type = type;
1578 	s->id = id;
1579 	s->ptr = ptr;
1580 
1581 	state->active_locks++;
1582 	state->active_lock_id = id;
1583 	state->active_lock_ptr = ptr;
1584 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_LOCK, true,
1585 				state->active_locks);
1586 	return 0;
1587 }
1588 
1589 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1590 {
1591 	struct bpf_verifier_state *state = env->cur_state;
1592 	struct bpf_reference_state *s;
1593 
1594 	s = acquire_reference_state(env, insn_idx);
1595 	if (!s)
1596 		return -ENOMEM;
1597 	s->type = REF_TYPE_IRQ;
1598 	s->id = ++env->id_gen;
1599 
1600 	state->active_irq_id = s->id;
1601 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true,
1602 				bpf_diag_irq_depth(state));
1603 	return s->id;
1604 }
1605 
1606 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1607 {
1608 	int last_idx;
1609 	size_t rem;
1610 
1611 	/* IRQ state requires the relative ordering of elements remaining the
1612 	 * same, since it relies on the refs array to behave as a stack, so that
1613 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1614 	 * the array instead of swapping the final element into the deleted idx.
1615 	 */
1616 	last_idx = state->acquired_refs - 1;
1617 	rem = state->acquired_refs - idx - 1;
1618 	if (last_idx && idx != last_idx)
1619 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1620 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1621 	state->acquired_refs--;
1622 	return;
1623 }
1624 
1625 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1626 {
1627 	int i;
1628 
1629 	for (i = 0; i < state->acquired_refs; i++) {
1630 		if (state->refs[i].type != REF_TYPE_PTR)
1631 			continue;
1632 		if (state->refs[i].id == id)
1633 			return true;
1634 	}
1635 
1636 	return false;
1637 }
1638 
1639 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1640 {
1641 	return find_reference_state(env->cur_state, reg->id);
1642 }
1643 
1644 static u32 reg_lifetime_id(struct bpf_verifier_env *env,
1645 			   const struct bpf_reg_state *reg)
1646 {
1647 	return reg_is_referenced(env, reg) ? reg->id : reg->parent_id;
1648 }
1649 
1650 static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr)
1651 {
1652 	struct bpf_verifier_state *state = env->cur_state;
1653 	void *prev_ptr = NULL;
1654 	u32 prev_id = 0;
1655 	int i;
1656 
1657 	for (i = 0; i < state->acquired_refs; i++) {
1658 		if (state->refs[i].type == type && state->refs[i].id == id &&
1659 		    state->refs[i].ptr == ptr) {
1660 			release_reference_state(state, i);
1661 			state->active_locks--;
1662 			/* Reassign active lock (id, ptr). */
1663 			state->active_lock_id = prev_id;
1664 			state->active_lock_ptr = prev_ptr;
1665 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_LOCK,
1666 						false, state->active_locks);
1667 			return 0;
1668 		}
1669 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1670 			prev_id = state->refs[i].id;
1671 			prev_ptr = state->refs[i].ptr;
1672 		}
1673 	}
1674 	return -EINVAL;
1675 }
1676 
1677 static int release_irq_state(struct bpf_verifier_env *env, int id)
1678 {
1679 	struct bpf_verifier_state *state = env->cur_state;
1680 	u32 prev_id = 0;
1681 	int i;
1682 
1683 	if (id != state->active_irq_id)
1684 		return -EACCES;
1685 
1686 	for (i = 0; i < state->acquired_refs; i++) {
1687 		if (state->refs[i].type != REF_TYPE_IRQ)
1688 			continue;
1689 		if (state->refs[i].id == id) {
1690 			release_reference_state(state, i);
1691 			state->active_irq_id = prev_id;
1692 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ,
1693 						false, bpf_diag_irq_depth(state));
1694 			return 0;
1695 		} else {
1696 			prev_id = state->refs[i].id;
1697 		}
1698 	}
1699 	return -EINVAL;
1700 }
1701 
1702 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1703 						   int id, void *ptr)
1704 {
1705 	int i;
1706 
1707 	for (i = 0; i < state->acquired_refs; i++) {
1708 		struct bpf_reference_state *s = &state->refs[i];
1709 
1710 		if (!(s->type & type))
1711 			continue;
1712 
1713 		if (s->id == id && s->ptr == ptr)
1714 			return s;
1715 	}
1716 	return NULL;
1717 }
1718 
1719 static void free_func_state(struct bpf_func_state *state)
1720 {
1721 	if (!state)
1722 		return;
1723 	kfree(state->loop_stack);
1724 	kfree(state->stack_arg_regs);
1725 	kfree(state->stack);
1726 	kfree(state);
1727 }
1728 
1729 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1730 {
1731 	kfree(state->jmp_history);
1732 	state->jmp_history = NULL;
1733 	state->jmp_history_cnt = 0;
1734 }
1735 
1736 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1737 			    bool free_self)
1738 {
1739 	int i;
1740 
1741 	for (i = 0; i <= state->curframe; i++) {
1742 		free_func_state(state->frame[i]);
1743 		state->frame[i] = NULL;
1744 	}
1745 	kfree(state->refs);
1746 	bpf_clear_jmp_history(state);
1747 	if (free_self)
1748 		kfree(state);
1749 }
1750 
1751 /* copy verifier state from src to dst growing dst stack space
1752  * when necessary to accommodate larger src stack
1753  */
1754 static int copy_func_state(struct bpf_func_state *dst,
1755 			   const struct bpf_func_state *src)
1756 {
1757 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1758 	/* Instruction accounting is path-local, not part of verifier state. */
1759 	dst->insns_subtotal = 0;
1760 	dst->loop_stack = copy_array(dst->loop_stack, src->loop_stack, src->loop_stack_cnt,
1761 				     sizeof(*src->loop_stack), GFP_KERNEL_ACCOUNT);
1762 	if (!dst->loop_stack)
1763 		return -ENOMEM;
1764 	return copy_stack_state(dst, src);
1765 }
1766 
1767 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1768 			   const struct bpf_verifier_state *src)
1769 {
1770 	struct bpf_func_state *dst;
1771 	int i, err;
1772 
1773 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1774 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1775 					  GFP_KERNEL_ACCOUNT);
1776 	if (!dst_state->jmp_history)
1777 		return -ENOMEM;
1778 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1779 
1780 	/* if dst has more stack frames then src frame, free them, this is also
1781 	 * necessary in case of exceptional exits using bpf_throw.
1782 	 */
1783 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1784 		free_func_state(dst_state->frame[i]);
1785 		dst_state->frame[i] = NULL;
1786 	}
1787 	err = copy_reference_state(dst_state, src);
1788 	if (err)
1789 		return err;
1790 	dst_state->speculative = src->speculative;
1791 	dst_state->in_sleepable = src->in_sleepable;
1792 	dst_state->unwound = src->unwound;
1793 	dst_state->curframe = src->curframe;
1794 	dst_state->branches = src->branches;
1795 	dst_state->parent = src->parent;
1796 	dst_state->first_insn_idx = src->first_insn_idx;
1797 	dst_state->last_insn_idx = src->last_insn_idx;
1798 	dst_state->dfs_depth = src->dfs_depth;
1799 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1800 	dst_state->may_goto_depth = src->may_goto_depth;
1801 	dst_state->equal_state = src->equal_state;
1802 	for (i = 0; i <= src->curframe; i++) {
1803 		dst = dst_state->frame[i];
1804 		if (!dst) {
1805 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1806 			if (!dst)
1807 				return -ENOMEM;
1808 			dst_state->frame[i] = dst;
1809 		}
1810 		err = copy_func_state(dst, src->frame[i]);
1811 		if (err)
1812 			return err;
1813 	}
1814 	return 0;
1815 }
1816 
1817 static u32 state_htab_size(struct bpf_verifier_env *env)
1818 {
1819 	return env->prog->len;
1820 }
1821 
1822 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1823 {
1824 	struct bpf_verifier_state *cur = env->cur_state;
1825 	struct bpf_func_state *state = cur->frame[cur->curframe];
1826 
1827 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1828 }
1829 
1830 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1831 {
1832 	int fr;
1833 
1834 	if (a->curframe != b->curframe)
1835 		return false;
1836 
1837 	for (fr = a->curframe; fr >= 0; fr--)
1838 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1839 			return false;
1840 
1841 	return true;
1842 }
1843 
1844 void bpf_free_backedges(struct bpf_scc_visit *visit)
1845 {
1846 	struct bpf_scc_backedge *backedge, *next;
1847 
1848 	for (backedge = visit->backedges; backedge; backedge = next) {
1849 		bpf_free_verifier_state(&backedge->state, false);
1850 		next = backedge->next;
1851 		kfree(backedge);
1852 	}
1853 	visit->backedges = NULL;
1854 }
1855 
1856 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1857 		     int *insn_idx, bool pop_log)
1858 {
1859 	struct bpf_verifier_state *cur = env->cur_state;
1860 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1861 	int err;
1862 
1863 	if (env->head == NULL)
1864 		return -ENOENT;
1865 
1866 	if (cur) {
1867 		err = bpf_copy_verifier_state(cur, &head->st);
1868 		if (err)
1869 			return err;
1870 		bpf_diag_event_log_restore(env, head->diag_log_pos);
1871 	}
1872 	if (pop_log)
1873 		bpf_vlog_reset(&env->log, head->log_pos);
1874 	if (insn_idx)
1875 		*insn_idx = head->insn_idx;
1876 	if (prev_insn_idx)
1877 		*prev_insn_idx = head->prev_insn_idx;
1878 	elem = head->next;
1879 	bpf_free_verifier_state(&head->st, false);
1880 	kfree(head);
1881 	env->head = elem;
1882 	env->stack_size--;
1883 	return 0;
1884 }
1885 
1886 static bool error_recoverable_with_nospec(int err)
1887 {
1888 	/* Should only return true for non-fatal errors that are allowed to
1889 	 * occur during speculative verification. For these we can insert a
1890 	 * nospec and the program might still be accepted. Do not include
1891 	 * something like ENOMEM because it is likely to re-occur for the next
1892 	 * architectural path once it has been recovered-from in all speculative
1893 	 * paths.
1894 	 */
1895 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1896 }
1897 
1898 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1899 					     int insn_idx, int prev_insn_idx,
1900 					     bool speculative)
1901 {
1902 	struct bpf_verifier_state *cur = env->cur_state;
1903 	struct bpf_verifier_stack_elem *elem;
1904 	int err;
1905 
1906 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1907 	if (!elem)
1908 		return ERR_PTR(-ENOMEM);
1909 
1910 	elem->insn_idx = insn_idx;
1911 	elem->prev_insn_idx = prev_insn_idx;
1912 	elem->next = env->head;
1913 	elem->log_pos = env->log.end_pos;
1914 	elem->diag_log_pos = bpf_diag_event_log_save(env);
1915 	env->head = elem;
1916 	env->stack_size++;
1917 	err = bpf_copy_verifier_state(&elem->st, cur);
1918 	if (err)
1919 		return ERR_PTR(-ENOMEM);
1920 	elem->st.speculative |= speculative;
1921 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1922 		verbose(env, "The sequence of %d jumps is too complex.\n",
1923 			env->stack_size);
1924 		return ERR_PTR(-E2BIG);
1925 	}
1926 	if (elem->st.parent) {
1927 		++elem->st.parent->branches;
1928 		/* WARN_ON(branches > 2) technically makes sense here,
1929 		 * but
1930 		 * 1. speculative states will bump 'branches' for non-branch
1931 		 * instructions
1932 		 * 2. is_state_visited() heuristics may decide not to create
1933 		 * a new state for a sequence of branches and all such current
1934 		 * and cloned states will be pointing to a single parent state
1935 		 * which might have large 'branches' count.
1936 		 */
1937 	}
1938 	return &elem->st;
1939 }
1940 
1941 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1942 {
1943 	char *buf = env->tmp_arg_name;
1944 	int len = sizeof(env->tmp_arg_name);
1945 	int arg, regno = reg_from_argno(argno);
1946 
1947 	if (regno >= 0) {
1948 		snprintf(buf, len, "R%d", regno);
1949 	} else {
1950 		arg = arg_from_argno(argno);
1951 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1952 	}
1953 
1954 	return buf;
1955 }
1956 
1957 static const int caller_saved[CALLER_SAVED_REGS] = {
1958 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1959 };
1960 
1961 static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
1962 					 struct bpf_reg_state *regs)
1963 {
1964 	int i;
1965 
1966 	for (i = 1; i < CALLER_SAVED_REGS; i++) {
1967 		bpf_diag_record_scrub(env, &regs[caller_saved[i]],
1968 				      BPF_DIAG_MOD_CALLER_SAVED);
1969 	}
1970 }
1971 
1972 static void reg_step_reset(struct bpf_reg_state *reg)
1973 {
1974 	reg->base = 0;
1975 	reg->step = 1;
1976 }
1977 
1978 static void scalar_step_add(struct bpf_reg_state *dst_reg,
1979 			    const struct bpf_reg_state *a,
1980 			    const struct bpf_reg_state *b)
1981 {
1982 	const struct bpf_reg_state *reg;
1983 	s64 amount, tmp;
1984 
1985 	if (tnum_is_const(b->var_off)) {
1986 		reg = a;
1987 		amount = (s64)b->var_off.value;
1988 	} else if (tnum_is_const(a->var_off)) {
1989 		reg = b;
1990 		amount = (s64)a->var_off.value;
1991 	} else {
1992 		reg_step_reset(dst_reg);
1993 		return;
1994 	}
1995 
1996 	/*
1997 	 * Let x be a possible signed value of the register,
1998 	 * d = amount, s = reg->step, and b = reg->base.
1999 	 * Then x mod s = b, with s > 0 and 0 <= b < s.
2000 	 * If the addition causes signed underflow, the resulting value
2001 	 * is x + d + 2**64.
2002 	 *
2003 	 * Taking the result modulo s and substituting x mod s = b gives:
2004 	 *   (x + d + 2**64) mod s = (b + d + (2**64 mod s)) mod s      (1)
2005 	 * Keeping reg->step = s and updating reg->base to (b + d) mod s
2006 	 * requires (1) to equal (b + d) mod s, which holds if and only
2007 	 * if 2**64 mod s = 0.
2008 	 * Signed overflow subtracts 2**64 and has the same requirement.
2009 	 *
2010 	 * Conservatively reset the stride if either wrap is possible.
2011 	 */
2012 	if (check_add_overflow(reg_smin(reg), amount, &tmp) ||
2013 	    check_add_overflow(reg_smax(reg), amount, &tmp)) {
2014 		reg_step_reset(dst_reg);
2015 		return;
2016 	}
2017 
2018 	dst_reg->base = (reg->base + imod(amount, reg->step)) % reg->step;
2019 	dst_reg->step = reg->step;
2020 }
2021 
2022 static void scalar_step_scale(struct bpf_reg_state *dst_reg, u64 amount)
2023 {
2024 	u16 step;
2025 	s64 tmp;
2026 
2027 	/*
2028 	 * Using the same notation as scalar_step_add(), with d > 0,
2029 	 * the scaled value satisfies (x * d) mod (s * d) = b * d.
2030 	 * If the multiplication wraps, its signed result can be represented
2031 	 * as x * d - n * 2**64 for some nonzero integer n.
2032 	 *
2033 	 * Taking the result modulo s * d gives:
2034 	 *   (x * d - n * 2**64) mod (s * d) =
2035 	 *   (b * d - (n * 2**64 mod (s * d))) mod (s * d)              (1)
2036 	 * Updating dst_reg->base to b * d and dst_reg->step to s * d
2037 	 * requires (1) to equal b * d, which holds if and only if
2038 	 * n * 2**64 mod (s * d) = 0.
2039 	 *
2040 	 * Conservatively reset the stride if a wrap is possible.
2041 	 */
2042 	if (amount == 0 || check_mul_overflow(dst_reg->step, amount, &step) ||
2043 	    check_mul_overflow(reg_smin(dst_reg), (s64)amount, &tmp) ||
2044 	    check_mul_overflow(reg_smax(dst_reg), (s64)amount, &tmp)) {
2045 		reg_step_reset(dst_reg);
2046 		return;
2047 	}
2048 	/*
2049 	 * The above established that `step = dst_reg->step * amount`
2050 	 * does not overflow, therefore the base < step invariant holds
2051 	 * after assignments below.
2052 	 */
2053 	dst_reg->base = dst_reg->base * amount;
2054 	dst_reg->step = step;
2055 }
2056 
2057 /*
2058  * Let x be a possible signed value of the register,
2059  * s = reg->step, and b = reg->base.
2060  * Then x mod s = b, with s > 0 and 0 <= b < s.
2061  * Truncating to N bits and then zero- or sign-extending x
2062  * is equivalent to computing x + k * 2**N for some integer k.
2063  * For example, sign-extending the low 8 bits of x = 255 can
2064  * be expressed as 255 - 2**8 = -1.
2065  *
2066  * Taking the result modulo s and substituting x mod s = b gives:
2067  *   (x + k * 2**N) mod s = (b + (k * 2**N mod s)) mod s
2068  * Keeping reg->base = b and reg->step = s requires this to equal b,
2069  * which holds if and only if k * 2**N mod s = 0.
2070  * Continuing the example with s = 3 and b = 0, we have 255 mod 3 = 0,
2071  * but (-1) mod 3 = 2, so the original base and step no longer hold.
2072  *
2073  * Conservatively reset the stride unless all possible values fit in
2074  * the range where the conversion leaves them unchanged.
2075  * Call before updating the register's bounds. Requires 0 < bits < 64.
2076  */
2077 static void reg_step_check_unsigned(struct bpf_reg_state *reg, u32 bits)
2078 {
2079 	if (reg_umax(reg) >= (1ULL << bits))
2080 		reg_step_reset(reg);
2081 }
2082 
2083 /* This helper doesn't clear reg->id */
2084 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2085 {
2086 	reg->var_off = tnum_const(imm);
2087 	reg->r64 = cnum64_from_urange(imm, imm);
2088 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2089 	reg_step_reset(reg);
2090 }
2091 
2092 /* Mark the unknown part of a register (variable offset or scalar value) as
2093  * known to have the value @imm.
2094  */
2095 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	/* Clear off and union(map_ptr, range) */
2098 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2099 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2100 	reg->id = 0;
2101 	reg->parent_id = 0;
2102 	reg->map_uid = 0;
2103 	___mark_reg_known(reg, imm);
2104 }
2105 
2106 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
2107 {
2108 	__mark_reg_known(reg, imm);
2109 	reg->type = SCALAR_VALUE;
2110 }
2111 
2112 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2115 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2116 }
2117 
2118 /* Mark the 'variable offset' part of a register as zero.  This should be
2119  * used only on registers holding a pointer type.
2120  */
2121 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2122 {
2123 	__mark_reg_known(reg, 0);
2124 }
2125 
2126 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2127 {
2128 	__mark_reg_known(reg, 0);
2129 	reg->type = SCALAR_VALUE;
2130 	/* all scalars are assumed imprecise initially (unless unprivileged,
2131 	 * in which case everything is forced to be precise)
2132 	 */
2133 	reg->precise = !env->bpf_capable;
2134 }
2135 
2136 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2137 				struct bpf_reg_state *regs, u32 regno)
2138 {
2139 	__mark_reg_known_zero(regs + regno);
2140 }
2141 
2142 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2143 			      bool first_slot, int id, int parent_id)
2144 {
2145 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2146 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2147 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2148 	 */
2149 	__mark_reg_known_zero(reg);
2150 	reg->type = CONST_PTR_TO_DYNPTR;
2151 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2152 	reg->id = id;
2153 	reg->parent_id = parent_id;
2154 	reg->dynptr.type = type;
2155 	reg->dynptr.first_slot = first_slot;
2156 }
2157 
2158 /*
2159  * Refine the return type of the bpf_map_lookup_elem() for special map types:
2160  * map-in-map, xskmap, sockmap and sockhash.
2161  */
2162 static void refine_map_lookup_value(struct bpf_reg_state *reg)
2163 {
2164 	enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL;
2165 	const struct bpf_map *map = reg->map_ptr;
2166 
2167 	if (map->inner_map_meta) {
2168 		reg->type = CONST_PTR_TO_MAP | maybe_null;
2169 		reg->map_ptr = map->inner_map_meta;
2170 		/*
2171 		 * transfer reg's id which is unique for every map_lookup_elem
2172 		 * as UID of the inner map.
2173 		 */
2174 		reg->map_uid = reg->id;
2175 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2176 		reg->type = PTR_TO_XDP_SOCK | maybe_null;
2177 		reg->map_uid = 0;
2178 	} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2179 		   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2180 		reg->type = PTR_TO_SOCKET | maybe_null;
2181 		reg->map_uid = 0;
2182 	}
2183 }
2184 
2185 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2186 {
2187 	reg->type &= ~PTR_MAYBE_NULL;
2188 }
2189 
2190 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2191 				struct btf_field_graph_root *ds_head)
2192 {
2193 	__mark_reg_known(&regs[regno], ds_head->node_offset);
2194 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2195 	regs[regno].btf = ds_head->btf;
2196 	regs[regno].btf_id = ds_head->value_btf_id;
2197 }
2198 
2199 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2200 {
2201 	return type_is_pkt_pointer(reg->type);
2202 }
2203 
2204 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2205 {
2206 	return reg_is_pkt_pointer(reg) ||
2207 	       reg->type == PTR_TO_PACKET_END;
2208 }
2209 
2210 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2211 {
2212 	return base_type(reg->type) == PTR_TO_MEM &&
2213 	       (reg->type &
2214 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2215 }
2216 
2217 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2218 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2219 				    enum bpf_reg_type which)
2220 {
2221 	/* The register can already have a range from prior markings.
2222 	 * This is fine as long as it hasn't been advanced from its
2223 	 * origin.
2224 	 */
2225 	return reg->type == which &&
2226 	       reg->id == 0 &&
2227 	       tnum_equals_const(reg->var_off, 0);
2228 }
2229 
2230 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2231 {
2232 	reg->r32 = CNUM32_UNBOUNDED;
2233 }
2234 
2235 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2236 {
2237 	reg->r64 = CNUM64_UNBOUNDED;
2238 }
2239 
2240 /* Reset the min/max bounds of a register */
2241 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2242 {
2243 	__mark_reg64_unbounded(reg);
2244 	__mark_reg32_unbounded(reg);
2245 }
2246 
2247 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
2248 {
2249 	__mark_reg64_unbounded(reg);
2250 	reg->var_off = tnum_unknown;
2251 }
2252 
2253 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
2254 {
2255 	__mark_reg32_unbounded(reg);
2256 	reg->var_off = tnum_unknown;
2257 }
2258 
2259 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
2260 {
2261 	tnum = tnum_subreg(tnum);
2262 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
2263 		/* min signed is max(sign bit) | min(other bits) */
2264 		/* max signed is min(sign bit) | max(other bits) */
2265 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
2266 					  tnum.value | (tnum.mask & S32_MAX));
2267 	else
2268 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
2269 }
2270 
2271 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
2272 {
2273 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
2274 		/* min signed is max(sign bit) | min(other bits) */
2275 		/* max signed is min(sign bit) | max(other bits) */
2276 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
2277 					  tnum.value | (tnum.mask & S64_MAX));
2278 	else
2279 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
2280 }
2281 
2282 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2283 {
2284 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
2285 }
2286 
2287 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2288 {
2289 	u64 tnum_next, tmax;
2290 	bool umin_in_tnum;
2291 
2292 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2293 
2294 	/* Check if u64 and tnum overlap in a single value */
2295 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2296 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2297 	tmax = reg->var_off.value | reg->var_off.mask;
2298 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2299 		/* The u64 range and the tnum only overlap in umin.
2300 		 * u64:  ---[xxxxxx]-----
2301 		 * tnum: --xx----------x-
2302 		 */
2303 		___mark_reg_known(reg, reg_umin(reg));
2304 	} else if (!umin_in_tnum && tnum_next == tmax) {
2305 		/* The u64 range and the tnum only overlap in the maximum value
2306 		 * represented by the tnum, called tmax.
2307 		 * u64:  ---[xxxxxx]-----
2308 		 * tnum: xx-----x--------
2309 		 */
2310 		___mark_reg_known(reg, tmax);
2311 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2312 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2313 		/* The u64 range and the tnum only overlap in between umin
2314 		 * (excluded) and umax.
2315 		 * u64:  ---[xxxxxx]-----
2316 		 * tnum: xx----x-------x-
2317 		 */
2318 		___mark_reg_known(reg, tnum_next);
2319 	}
2320 }
2321 
2322 static void __update_reg_bounds(struct bpf_reg_state *reg)
2323 {
2324 	__update_reg32_bounds(reg);
2325 	__update_reg64_bounds(reg);
2326 }
2327 
2328 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2329 {
2330 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2331 }
2332 
2333 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2334 {
2335 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2336 }
2337 
2338 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2339 {
2340 	deduce_bounds_32_from_64(reg);
2341 	deduce_bounds_64_from_32(reg);
2342 }
2343 
2344 /* Attempts to improve var_off based on unsigned min/max information */
2345 static void __reg_bound_offset(struct bpf_reg_state *reg)
2346 {
2347 	struct tnum var64_off = tnum_intersect(reg->var_off,
2348 					       tnum_range(reg_umin(reg),
2349 							  reg_umax(reg)));
2350 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2351 					       tnum_range(reg_u32_min(reg),
2352 							  reg_u32_max(reg)));
2353 	u32 trailing_zero_bits;
2354 	u16 base = reg->base;
2355 	u16 step = reg->step;
2356 
2357 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2358 
2359 	if (base == 0)
2360 		trailing_zero_bits = count_trailing_zeros(step);
2361 	else
2362 		trailing_zero_bits = min(count_trailing_zeros(base),
2363 					 count_trailing_zeros(step));
2364 	reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
2365 }
2366 
2367 static void __update_bounds_from_step(struct bpf_reg_state *reg)
2368 {
2369 	reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
2370 	deduce_bounds_32_from_64(reg);
2371 }
2372 
2373 static bool range_bounds_violation(struct bpf_reg_state *reg);
2374 
2375 static void reg_bounds_sync(struct bpf_reg_state *reg)
2376 {
2377 	/* If the input reg_state is invalid, we can exit early */
2378 	if (range_bounds_violation(reg))
2379 		return;
2380 	/* We might have learned new bounds from the var_off. */
2381 	__update_reg_bounds(reg);
2382 	/* We might have learned something about the sign bit. */
2383 	__reg_deduce_bounds(reg);
2384 	__reg_deduce_bounds(reg);
2385 	/* We might have learned some bits from the bounds. */
2386 	__reg_bound_offset(reg);
2387 	/* Intersecting with the old var_off might have improved our bounds
2388 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2389 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2390 	 */
2391 	__update_reg_bounds(reg);
2392 	/*
2393 	 * Both tnum and base+step define a sequence of points,
2394 	 * potentially w/o intersection, or intersecting after N
2395 	 * tnum_step()'s, where N can be large. On the other hand,
2396 	 * step+base *must* be in sync with r64 in order for
2397 	 * array traversal logic starting at reg_smin() to be sound.
2398 	 * Hence, place this as a final step in the reg_bounds_sync().
2399 	 */
2400 	__update_bounds_from_step(reg);
2401 }
2402 
2403 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2404 {
2405 	if (!tnum_is_const(reg->var_off))
2406 		return false;
2407 
2408 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2409 }
2410 
2411 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2412 {
2413 	if (!tnum_subreg_is_const(reg->var_off))
2414 		return false;
2415 
2416 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2417 }
2418 
2419 static bool range_bounds_violation(struct bpf_reg_state *reg)
2420 {
2421 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2422 }
2423 
2424 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2425 				   struct bpf_reg_state *reg, const char *ctx)
2426 {
2427 	const char *msg;
2428 
2429 	if (range_bounds_violation(reg)) {
2430 		msg = "range bounds violation";
2431 		goto out;
2432 	}
2433 
2434 	if (const_tnum_range_mismatch(reg)) {
2435 		msg = "const tnum out of sync with range bounds";
2436 		goto out;
2437 	}
2438 
2439 	if (const_tnum_range_mismatch_32(reg)) {
2440 		msg = "const subreg tnum out of sync with range bounds";
2441 		goto out;
2442 	}
2443 
2444 	if (reg->step == 0 || reg->base >= reg->step) {
2445 		msg = "invalid base/step";
2446 		goto out;
2447 	}
2448 
2449 	return 0;
2450 out:
2451 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2452 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u",
2453 		     ctx, msg,
2454 		     reg->r64.base, reg->r64.size,
2455 		     reg->r32.base, reg->r32.size,
2456 		     reg->var_off.value, reg->var_off.mask,
2457 		     reg->base, reg->step);
2458 	if (env->test_reg_invariants)
2459 		return -EFAULT;
2460 	__mark_reg_unbounded(reg);
2461 	reg_step_reset(reg);
2462 	return 0;
2463 }
2464 
2465 /* Mark a register as having a completely unknown (scalar) value. */
2466 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2467 {
2468 	memset(reg, 0, sizeof(*reg));
2469 	reg->type = SCALAR_VALUE;
2470 	reg->var_off = tnum_unknown;
2471 	__mark_reg_unbounded(reg);
2472 	reg_step_reset(reg);
2473 }
2474 
2475 /* Mark a register as having a completely unknown (scalar) value,
2476  * initialize .precise as true when not bpf capable.
2477  */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	bpf_mark_reg_unknown_imprecise(reg);
2482 	reg->precise = !env->bpf_capable;
2483 }
2484 
2485 static void mark_reg_unknown(struct bpf_verifier_env *env,
2486 			     struct bpf_reg_state *regs, u32 regno)
2487 {
2488 	__mark_reg_unknown(env, regs + regno);
2489 }
2490 
2491 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2492 				struct bpf_reg_state *regs,
2493 				u32 regno,
2494 				s32 s32_min,
2495 				s32 s32_max)
2496 {
2497 	struct bpf_reg_state *reg = regs + regno;
2498 
2499 	reg_set_srange32(reg,
2500 			 max_t(s32, reg_s32_min(reg), s32_min),
2501 			 min_t(s32, reg_s32_max(reg), s32_max));
2502 	reg_set_srange64(reg,
2503 			 max_t(s64, reg_smin(reg), s32_min),
2504 			 min_t(s64, reg_smax(reg), s32_max));
2505 
2506 	reg_bounds_sync(reg);
2507 
2508 	return reg_bounds_sanity_check(env, reg, "s32_range");
2509 }
2510 
2511 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2512 			   struct bpf_reg_state *reg)
2513 {
2514 	__mark_reg_unknown(env, reg);
2515 	reg->type = NOT_INIT;
2516 }
2517 
2518 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2519 			   struct bpf_reg_state *regs, u32 regno,
2520 			   enum bpf_reg_type reg_type,
2521 			   struct btf *btf, u32 btf_id,
2522 			   enum bpf_type_flag flag)
2523 {
2524 	switch (reg_type) {
2525 	case SCALAR_VALUE:
2526 		mark_reg_unknown(env, regs, regno);
2527 		return 0;
2528 	case PTR_TO_BTF_ID:
2529 		mark_reg_known_zero(env, regs, regno);
2530 		regs[regno].type = PTR_TO_BTF_ID | flag;
2531 		regs[regno].btf = btf;
2532 		regs[regno].btf_id = btf_id;
2533 		if (type_may_be_null(flag))
2534 			regs[regno].id = ++env->id_gen;
2535 		return 0;
2536 	case PTR_TO_MEM:
2537 		mark_reg_known_zero(env, regs, regno);
2538 		regs[regno].type = PTR_TO_MEM | flag;
2539 		regs[regno].mem_size = 0;
2540 		return 0;
2541 	default:
2542 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2543 		return -EFAULT;
2544 	}
2545 }
2546 
2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 			   struct bpf_func_state *state)
2549 {
2550 	struct bpf_reg_state *regs = state->regs;
2551 	int i;
2552 
2553 	for (i = 0; i < MAX_BPF_REG; i++) {
2554 		bpf_mark_reg_not_init(env, &regs[i]);
2555 	}
2556 
2557 	/* frame pointer */
2558 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2559 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2560 	regs[BPF_REG_FP].frameno = state->frameno;
2561 }
2562 
2563 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2564 {
2565 	/*
2566 	 * return_32bit is set to false by default and set explicitly
2567 	 * by the caller when necessary.
2568 	 */
2569 	return (struct bpf_retval_range){ minval, maxval, false };
2570 }
2571 
2572 static void init_func_state(struct bpf_verifier_env *env,
2573 			    struct bpf_func_state *state,
2574 			    int callsite, int frameno, int subprogno)
2575 {
2576 	state->callsite = callsite;
2577 	state->frameno = frameno;
2578 	bpf_diag_init_frame(env, state);
2579 	state->subprogno = subprogno;
2580 	state->callback_ret_range = retval_range(0, 0);
2581 	init_reg_state(env, state);
2582 	mark_verifier_state_scratched(env);
2583 }
2584 
2585 /* Similar to push_stack(), but for async callbacks */
2586 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2587 						int insn_idx, int prev_insn_idx,
2588 						int subprog, bool is_sleepable)
2589 {
2590 	struct bpf_verifier_stack_elem *elem;
2591 	struct bpf_func_state *frame;
2592 
2593 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2594 	if (!elem)
2595 		return ERR_PTR(-ENOMEM);
2596 
2597 	elem->insn_idx = insn_idx;
2598 	elem->prev_insn_idx = prev_insn_idx;
2599 	elem->next = env->head;
2600 	elem->log_pos = env->log.end_pos;
2601 	elem->diag_log_pos = bpf_diag_event_log_save(env);
2602 	env->head = elem;
2603 	env->stack_size++;
2604 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2605 		verbose(env,
2606 			"The sequence of %d jumps is too complex for async cb.\n",
2607 			env->stack_size);
2608 		return ERR_PTR(-E2BIG);
2609 	}
2610 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2611 	 * The caller state doesn't matter.
2612 	 * This is async callback. It starts in a fresh stack.
2613 	 * Initialize it similar to do_check_common().
2614 	 */
2615 	elem->st.branches = 1;
2616 	elem->st.in_sleepable = is_sleepable;
2617 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2618 	if (!frame)
2619 		return ERR_PTR(-ENOMEM);
2620 	init_func_state(env, frame,
2621 			BPF_MAIN_FUNC /* callsite */,
2622 			0 /* frameno within this callchain */,
2623 			subprog /* subprog number within this prog */);
2624 	elem->st.frame[0] = frame;
2625 	return &elem->st;
2626 }
2627 
2628 /* Find subprogram that contains instruction at 'off' */
2629 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2630 {
2631 	struct bpf_subprog_info *vals = env->subprog_info;
2632 	int l, r, m;
2633 
2634 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2635 		return NULL;
2636 
2637 	l = 0;
2638 	r = env->subprog_cnt - 1;
2639 	while (l < r) {
2640 		m = l + (r - l + 1) / 2;
2641 		if (vals[m].start <= off)
2642 			l = m;
2643 		else
2644 			r = m - 1;
2645 	}
2646 	return &vals[l];
2647 }
2648 
2649 /* Find subprogram that starts exactly at 'off' */
2650 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2651 {
2652 	struct bpf_subprog_info *p;
2653 
2654 	p = bpf_find_containing_subprog(env, off);
2655 	if (!p || p->start != off)
2656 		return -ENOENT;
2657 	return p - env->subprog_info;
2658 }
2659 
2660 static int add_subprog(struct bpf_verifier_env *env, int off)
2661 {
2662 	struct bpf_subprog_info *subprog = env->subprog_info;
2663 	int insn_cnt = env->prog->len;
2664 	int i;
2665 
2666 	if (off >= insn_cnt || off < 0) {
2667 		verbose(env, "call to invalid destination\n");
2668 		return -EINVAL;
2669 	}
2670 	i = bpf_find_subprog(env, off);
2671 	if (i >= 0)
2672 		return i;
2673 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2674 		verbose(env, "too many subprograms\n");
2675 		return -E2BIG;
2676 	}
2677 	/*
2678 	 * Determine subprog starts. The end is one before the next starts.
2679 	 * The array stays sorted: subprogs that start after 'off' move up.
2680 	 */
2681 	for (i = env->subprog_cnt++; i > 0 && subprog[i - 1].start > off; i--)
2682 		subprog[i] = subprog[i - 1];
2683 	subprog[i] = (struct bpf_subprog_info){ .start = off, .exit_idx = U32_MAX };
2684 	return i;
2685 }
2686 
2687 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2688 {
2689 	struct bpf_prog_aux *aux = env->prog->aux;
2690 	struct btf *btf = aux->btf;
2691 	const struct btf_type *t;
2692 	u32 main_btf_id, id;
2693 	const char *name;
2694 	int ret, i;
2695 
2696 	/* Non-zero func_info_cnt implies valid btf */
2697 	if (!aux->func_info_cnt)
2698 		return 0;
2699 	main_btf_id = aux->func_info[0].type_id;
2700 
2701 	t = btf_type_by_id(btf, main_btf_id);
2702 	if (!t) {
2703 		verbose(env, "invalid btf id for main subprog in func_info\n");
2704 		return -EINVAL;
2705 	}
2706 
2707 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2708 	if (IS_ERR(name)) {
2709 		ret = PTR_ERR(name);
2710 		/* If there is no tag present, there is no exception callback */
2711 		if (ret == -ENOENT)
2712 			ret = 0;
2713 		else if (ret == -EEXIST)
2714 			verbose(env, "multiple exception callback tags for main subprog\n");
2715 		return ret;
2716 	}
2717 
2718 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2719 	if (ret < 0) {
2720 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2721 		return ret;
2722 	}
2723 	id = ret;
2724 	t = btf_type_by_id(btf, id);
2725 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2726 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2727 		return -EINVAL;
2728 	}
2729 	ret = 0;
2730 	for (i = 0; i < aux->func_info_cnt; i++) {
2731 		if (aux->func_info[i].type_id != id)
2732 			continue;
2733 		ret = aux->func_info[i].insn_off;
2734 		/* Further func_info and subprog checks will also happen
2735 		 * later, so assume this is the right insn_off for now.
2736 		 */
2737 		if (!ret) {
2738 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2739 			ret = -EINVAL;
2740 		}
2741 	}
2742 	if (!ret) {
2743 		verbose(env, "exception callback type id not found in func_info\n");
2744 		ret = -EINVAL;
2745 	}
2746 	return ret;
2747 }
2748 
2749 #define MAX_KFUNC_BTFS	256
2750 
2751 struct bpf_kfunc_btf {
2752 	struct btf *btf;
2753 	struct module *module;
2754 	u16 offset;
2755 };
2756 
2757 struct bpf_kfunc_btf_tab {
2758 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2759 	u32 nr_descs;
2760 };
2761 
2762 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2763 {
2764 	const struct bpf_kfunc_desc *d0 = a;
2765 	const struct bpf_kfunc_desc *d1 = b;
2766 
2767 	/* func_id is not greater than BTF_MAX_TYPE */
2768 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2769 }
2770 
2771 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2772 {
2773 	const struct bpf_kfunc_btf *d0 = a;
2774 	const struct bpf_kfunc_btf *d1 = b;
2775 
2776 	return d0->offset - d1->offset;
2777 }
2778 
2779 static struct bpf_kfunc_desc *
2780 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2781 {
2782 	struct bpf_kfunc_desc desc = {
2783 		.func_id = func_id,
2784 		.offset = offset,
2785 	};
2786 	struct bpf_kfunc_desc_tab *tab;
2787 
2788 	tab = prog->aux->kfunc_tab;
2789 	return bsearch(&desc, tab->descs, tab->nr_base_descs,
2790 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2791 }
2792 
2793 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2794 		       u16 desc_idx, u8 **func_addr)
2795 {
2796 	struct bpf_kfunc_desc_tab *tab;
2797 	const struct bpf_kfunc_desc *desc;
2798 
2799 	tab = prog->aux->kfunc_tab;
2800 	if (desc_idx >= tab->nr_descs)
2801 		return -EFAULT;
2802 	desc = &tab->descs[desc_idx];
2803 	if (desc->func_id != func_id)
2804 		return -EFAULT;
2805 
2806 	*func_addr = (u8 *)desc->addr;
2807 	return 0;
2808 }
2809 
2810 #define BPF_FD_SLOT_BTF	1UL
2811 
2812 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map)
2813 {
2814 	slot->val = (unsigned long)map;
2815 }
2816 
2817 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf)
2818 {
2819 	slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF;
2820 }
2821 
2822 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot)
2823 {
2824 	if (slot.val & BPF_FD_SLOT_BTF)
2825 		return NULL;
2826 	return (struct bpf_map *)slot.val;
2827 }
2828 
2829 static struct btf *fd_slot_btf(struct bpf_fd_array slot)
2830 {
2831 	if (!(slot.val & BPF_FD_SLOT_BTF))
2832 		return NULL;
2833 	return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF);
2834 }
2835 
2836 static struct btf *
2837 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx)
2838 {
2839 	struct btf *btf;
2840 
2841 	if (idx >= env->fd_array_cnt) {
2842 		verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n",
2843 			idx, env->fd_array_cnt);
2844 		return ERR_PTR(-EINVAL);
2845 	}
2846 	btf = fd_slot_btf(env->fd_array[idx]);
2847 	if (!btf) {
2848 		verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx);
2849 		return ERR_PTR(-EINVAL);
2850 	}
2851 	btf_get(btf);
2852 	return btf;
2853 }
2854 
2855 static struct btf *
2856 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx)
2857 {
2858 	struct btf *btf;
2859 	int btf_fd;
2860 
2861 	if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw,
2862 				    (size_t)idx * sizeof(btf_fd), sizeof(btf_fd)))
2863 		return ERR_PTR(-EFAULT);
2864 	btf = btf_get_by_fd(btf_fd);
2865 	if (IS_ERR(btf)) {
2866 		verbose(env, "invalid module BTF fd specified\n");
2867 		return btf;
2868 	}
2869 	return btf;
2870 }
2871 
2872 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx)
2873 {
2874 	if (env->signature) {
2875 		verbose(env, "signed program cannot bind any BTF\n");
2876 		return ERR_PTR(-EACCES);
2877 	}
2878 	if (env->fd_array)
2879 		return fd_array_get_btf_continuous(env, idx);
2880 	if (!bpfptr_is_null(env->fd_array_raw))
2881 		return fd_array_get_btf_sparse(env, idx);
2882 
2883 	verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2884 	return ERR_PTR(-EPROTO);
2885 }
2886 
2887 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2888 					 s16 offset)
2889 {
2890 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2891 	struct bpf_kfunc_btf_tab *tab;
2892 	struct bpf_kfunc_btf *b;
2893 	struct module *mod;
2894 	struct btf *btf;
2895 
2896 	tab = env->prog->aux->kfunc_btf_tab;
2897 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2898 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2899 	if (!b) {
2900 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2901 			verbose(env, "too many different module BTFs\n");
2902 			return ERR_PTR(-E2BIG);
2903 		}
2904 
2905 		btf = fd_array_get_btf(env, offset);
2906 		if (IS_ERR(btf))
2907 			return btf;
2908 		if (!btf_is_module(btf)) {
2909 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2910 			btf_put(btf);
2911 			return ERR_PTR(-EINVAL);
2912 		}
2913 
2914 		mod = btf_try_get_module(btf);
2915 		if (!mod) {
2916 			btf_put(btf);
2917 			return ERR_PTR(-ENXIO);
2918 		}
2919 
2920 		b = &tab->descs[tab->nr_descs++];
2921 		b->btf = btf;
2922 		b->module = mod;
2923 		b->offset = offset;
2924 
2925 		/* sort() reorders entries by value, so b may no longer point
2926 		 * to the right entry after this
2927 		 */
2928 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2929 		     kfunc_btf_cmp_by_off, NULL);
2930 	} else {
2931 		btf = b->btf;
2932 	}
2933 
2934 	return btf;
2935 }
2936 
2937 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2938 {
2939 	if (!tab)
2940 		return;
2941 
2942 	while (tab->nr_descs--) {
2943 		module_put(tab->descs[tab->nr_descs].module);
2944 		btf_put(tab->descs[tab->nr_descs].btf);
2945 	}
2946 	kfree(tab);
2947 }
2948 
2949 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2950 {
2951 	if (offset) {
2952 		if (offset < 0) {
2953 			/* In the future, this can be allowed to increase limit
2954 			 * of fd index into fd_array, interpreted as u16.
2955 			 */
2956 			verbose(env, "negative offset disallowed for kernel module function call\n");
2957 			return ERR_PTR(-EINVAL);
2958 		}
2959 
2960 		return __find_kfunc_desc_btf(env, offset);
2961 	}
2962 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2963 }
2964 
2965 static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset)
2966 {
2967 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2968 	struct bpf_kfunc_btf_tab *tab;
2969 	struct bpf_kfunc_btf *b;
2970 
2971 	if (!offset)
2972 		return btf_vmlinux ?: ERR_PTR(-ENOENT);
2973 	if (offset < 0)
2974 		return ERR_PTR(-EINVAL);
2975 
2976 	tab = env->prog->aux->kfunc_btf_tab;
2977 	if (!tab)
2978 		return ERR_PTR(-ENOENT);
2979 
2980 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2981 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2982 	return b ? b->btf : ERR_PTR(-ENOENT);
2983 }
2984 
2985 #define KF_IMPL_SUFFIX "_impl"
2986 
2987 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2988 						    struct btf *btf,
2989 						    const char *func_name)
2990 {
2991 	const struct btf_type *func;
2992 	char buf[KSYM_NAME_LEN];
2993 	s32 impl_id;
2994 	int len;
2995 
2996 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2997 	if (len < 0 || len >= sizeof(buf)) {
2998 		bpf_log(log, "function name %s%s is too long\n",
2999 			func_name, KF_IMPL_SUFFIX);
3000 		return NULL;
3001 	}
3002 
3003 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
3004 	if (impl_id <= 0) {
3005 		bpf_log(log, "cannot find function %s in BTF\n", buf);
3006 		return NULL;
3007 	}
3008 
3009 	func = btf_type_by_id(btf, impl_id);
3010 
3011 	return btf_type_by_id(btf, func->type);
3012 }
3013 
3014 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
3015 			    s32 func_id,
3016 			    s16 offset,
3017 			    struct bpf_kfunc_meta *kfunc)
3018 {
3019 	const struct btf_type *func, *func_proto;
3020 	const char *func_name;
3021 	u32 *kfunc_flags;
3022 	struct btf *btf;
3023 
3024 	if (func_id <= 0) {
3025 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
3026 		return -EINVAL;
3027 	}
3028 
3029 	btf = find_kfunc_desc_btf(env, offset);
3030 	if (IS_ERR(btf)) {
3031 		verbose(env, "failed to find BTF for kernel function\n");
3032 		return PTR_ERR(btf);
3033 	}
3034 
3035 	/*
3036 	 * Note that kfunc_flags may be NULL at this point, which
3037 	 * means that we couldn't find func_id in any relevant
3038 	 * kfunc_id_set. This most likely indicates an invalid kfunc
3039 	 * call.  However we don't fail with an error here,
3040 	 * and let the caller decide what to do with NULL kfunc->flags.
3041 	 */
3042 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
3043 
3044 	func = btf_type_by_id(btf, func_id);
3045 	if (!func || !btf_type_is_func(func)) {
3046 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
3047 		return -EINVAL;
3048 	}
3049 
3050 	func_name = btf_name_by_offset(btf, func->name_off);
3051 
3052 	/*
3053 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
3054 	 * can be found through the counterpart _impl kfunc.
3055 	 */
3056 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
3057 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
3058 	else
3059 		func_proto = btf_type_by_id(btf, func->type);
3060 
3061 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3062 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
3063 			func_id);
3064 		return -EINVAL;
3065 	}
3066 
3067 	memset(kfunc, 0, sizeof(*kfunc));
3068 	kfunc->btf = btf;
3069 	kfunc->id = func_id;
3070 	kfunc->name = func_name;
3071 	kfunc->proto = func_proto;
3072 	kfunc->flags = kfunc_flags;
3073 
3074 	return 0;
3075 }
3076 
3077 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3078 			       const struct btf_func_model *fm, struct bpf_func_proto *proto);
3079 
3080 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
3081 {
3082 	struct bpf_call_arg_meta meta;
3083 	struct bpf_kfunc_btf_tab *btf_tab;
3084 	struct btf_func_model func_model;
3085 	struct bpf_kfunc_desc_tab *tab;
3086 	struct bpf_prog_aux *prog_aux;
3087 	struct bpf_kfunc_meta kfunc;
3088 	struct bpf_kfunc_desc *desc;
3089 	unsigned long addr;
3090 	int err;
3091 
3092 	prog_aux = env->prog->aux;
3093 	tab = prog_aux->kfunc_tab;
3094 	btf_tab = prog_aux->kfunc_btf_tab;
3095 	if (!tab) {
3096 		if (!btf_vmlinux) {
3097 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3098 			return -ENOTSUPP;
3099 		}
3100 
3101 		if (!env->prog->jit_requested) {
3102 			verbose(env, "JIT is required for calling kernel function\n");
3103 			return -ENOTSUPP;
3104 		}
3105 
3106 		if (!bpf_jit_supports_kfunc_call()) {
3107 			verbose(env, "JIT does not support calling kernel function\n");
3108 			return -ENOTSUPP;
3109 		}
3110 
3111 		if (!env->prog->gpl_compatible) {
3112 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3113 			return -EINVAL;
3114 		}
3115 
3116 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
3117 		if (!tab)
3118 			return -ENOMEM;
3119 		prog_aux->kfunc_tab = tab;
3120 	}
3121 
3122 	env->prog->jit_required = 1;
3123 
3124 	/* func_id == 0 is always invalid, but instead of returning an error, be
3125 	 * conservative and wait until the code elimination pass before returning
3126 	 * error, so that invalid calls that get pruned out can be in BPF programs
3127 	 * loaded from userspace.  It is also required that offset be untouched
3128 	 * for such calls.
3129 	 */
3130 	if (!func_id && !offset)
3131 		return 0;
3132 
3133 	if (!btf_tab && offset) {
3134 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
3135 		if (!btf_tab)
3136 			return -ENOMEM;
3137 		prog_aux->kfunc_btf_tab = btf_tab;
3138 	}
3139 
3140 	if (find_kfunc_desc(env->prog, func_id, offset))
3141 		return 0;
3142 
3143 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
3144 		verbose(env, "too many different kernel function calls\n");
3145 		return -E2BIG;
3146 	}
3147 	if (tab->nr_descs != tab->nr_base_descs) {
3148 		verifier_bug(env, "unexpected specialized func desc found (%d descs, %d base descs)",
3149 			     tab->nr_descs, tab->nr_base_descs);
3150 		return -EFAULT;
3151 	}
3152 
3153 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
3154 	if (err)
3155 		return err;
3156 
3157 	addr = kallsyms_lookup_name(kfunc.name);
3158 	if (!addr) {
3159 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
3160 		return -EINVAL;
3161 	}
3162 
3163 	if (bpf_dev_bound_kfunc_id(func_id)) {
3164 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3165 		if (err)
3166 			return err;
3167 	}
3168 
3169 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
3170 	if (err)
3171 		return err;
3172 	if (func_model.ret_size > 8) {
3173 		if (kfunc.flags && (*kfunc.flags & KF_FASTCALL)) {
3174 			verbose(env, "kfunc %s with >8-byte return is not supported with KF_FASTCALL\n",
3175 				kfunc.name);
3176 			return -EOPNOTSUPP;
3177 		}
3178 		if (!bpf_jit_supports_kfunc_ret_reg_pair()) {
3179 			verbose(env, "kfunc %s with >8-byte return is not supported by JIT\n",
3180 				kfunc.name);
3181 			return -EOPNOTSUPP;
3182 		}
3183 	}
3184 
3185 	memset(&meta, 0, sizeof(meta));
3186 	meta.btf = kfunc.btf;
3187 	meta.func_id = kfunc.id;
3188 	meta.func_proto = kfunc.proto;
3189 	meta.func_name = kfunc.name;
3190 	meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;
3191 
3192 	tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT);
3193 	if (!tab)
3194 		return -ENOMEM;
3195 	prog_aux->kfunc_tab = tab;
3196 
3197 	desc = &tab->descs[tab->nr_descs];
3198 	memset(desc, 0, sizeof(*desc));
3199 
3200 	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
3201 	if (err)
3202 		return err;
3203 
3204 	desc->func_id = func_id;
3205 	desc->offset = offset;
3206 	desc->addr = addr;
3207 	desc->func_model = func_model;
3208 	tab->nr_descs++;
3209 	tab->nr_base_descs++;
3210 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
3211 	     kfunc_desc_cmp_by_id_off, NULL);
3212 	return 0;
3213 }
3214 
3215 static int add_subprogs(struct bpf_verifier_env *env)
3216 {
3217 	struct bpf_subprog_info *subprog = env->subprog_info;
3218 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3219 	struct bpf_insn *insn = env->prog->insnsi;
3220 	const char *operation, *suggestion;
3221 
3222 	/* Add entry function. */
3223 	ret = add_subprog(env, 0);
3224 	if (ret)
3225 		return ret;
3226 
3227 	for (i = 0; i < insn_cnt; i++, insn++) {
3228 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
3229 			continue;
3230 
3231 		if (!env->bpf_capable) {
3232 			if (bpf_pseudo_func(insn)) {
3233 				operation = "BPF function reference";
3234 				suggestion = "Load this program with the required capability, or avoid BPF function references in unprivileged programs.";
3235 			} else {
3236 				operation = "BPF-to-BPF function call";
3237 				suggestion = "Load this program with the required capability, or avoid BPF-to-BPF function calls in unprivileged programs.";
3238 			}
3239 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3240 			bpf_diag_policy(
3241 				env, i, operation,
3242 				"loading or calling other BPF functions requires CAP_BPF or CAP_SYS_ADMIN",
3243 				suggestion);
3244 			return -EPERM;
3245 		}
3246 
3247 		ret = add_subprog(env, i + insn->imm + 1);
3248 		if (ret < 0)
3249 			return ret;
3250 	}
3251 
3252 	/*
3253 	 * func_info describes all functions of the program. Those that are
3254 	 * referenced only from data, e.g. from a table of functions to be
3255 	 * called via callx, are not seen by the loop above. They are possible
3256 	 * callees that have to be known upfront as well.
3257 	 */
3258 	if (env->bpf_capable) {
3259 		struct bpf_prog_aux *aux = env->prog->aux;
3260 
3261 		for (i = 1; i < aux->func_info_cnt; i++) {
3262 			ret = add_subprog(env, aux->func_info[i].insn_off);
3263 			if (ret < 0)
3264 				return ret;
3265 		}
3266 	}
3267 
3268 	ret = bpf_find_exception_callback_insn_off(env);
3269 	if (ret < 0)
3270 		return ret;
3271 	ex_cb_insn = ret;
3272 
3273 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3274 	 * marked using BTF decl tag to serve as the exception callback.
3275 	 */
3276 	if (ex_cb_insn) {
3277 		ret = add_subprog(env, ex_cb_insn);
3278 		if (ret < 0)
3279 			return ret;
3280 		for (i = 1; i < env->subprog_cnt; i++) {
3281 			if (env->subprog_info[i].start != ex_cb_insn)
3282 				continue;
3283 			env->exception_callback_subprog = i;
3284 			bpf_mark_subprog_exc_cb(env, i);
3285 			break;
3286 		}
3287 	}
3288 
3289 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3290 	 * logic. 'subprog_cnt' should not be increased.
3291 	 */
3292 	subprog[env->subprog_cnt].start = insn_cnt;
3293 
3294 	if (env->log.level & BPF_LOG_LEVEL2)
3295 		for (i = 0; i < env->subprog_cnt; i++)
3296 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3297 
3298 	return 0;
3299 }
3300 
3301 static int add_kfuncs(struct bpf_verifier_env *env)
3302 {
3303 	struct bpf_insn *insn = env->prog->insnsi;
3304 	int i, ret, insn_cnt = env->prog->len;
3305 
3306 	for (i = 0; i < insn_cnt; i++, insn++) {
3307 		if (!bpf_pseudo_kfunc_call(insn))
3308 			continue;
3309 
3310 		if (!env->bpf_capable) {
3311 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3312 			bpf_diag_policy(
3313 				env, i, "kernel function call",
3314 				"calling kernel functions requires CAP_BPF or CAP_SYS_ADMIN",
3315 				"Load this program with the required capability, or avoid kernel function calls in unprivileged programs.");
3316 			return -EPERM;
3317 		}
3318 
3319 		ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
3320 		if (ret < 0)
3321 			return ret;
3322 	}
3323 
3324 	return 0;
3325 }
3326 
3327 static void find_subprog_properties(struct bpf_verifier_env *env)
3328 {
3329 	struct bpf_subprog_info *subprog = env->subprog_info;
3330 	struct bpf_insn *insn = env->prog->insnsi;
3331 	int cur_subprog;
3332 
3333 	for (cur_subprog = 0; cur_subprog < env->subprog_cnt; cur_subprog++) {
3334 		int i;
3335 
3336 		for (i = subprog[cur_subprog].start;
3337 		     i < subprog[cur_subprog + 1].start; i++) {
3338 			u8 code = insn[i].code;
3339 
3340 			if (code == (BPF_JMP | BPF_CALL) &&
3341 			    insn[i].src_reg == 0 &&
3342 			    insn[i].imm == BPF_FUNC_tail_call) {
3343 				subprog[cur_subprog].has_tail_call = true;
3344 				subprog[cur_subprog].tail_call_reachable = true;
3345 			}
3346 			if (BPF_CLASS(code) == BPF_LD &&
3347 			    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3348 				subprog[cur_subprog].has_ld_abs = true;
3349 			if (bpf_is_callx(&insn[i]))
3350 				env->has_callx = true;
3351 		}
3352 	}
3353 }
3354 
3355 static int check_subprogs(struct bpf_verifier_env *env)
3356 {
3357 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3358 	struct bpf_subprog_info *subprog = env->subprog_info;
3359 	struct bpf_insn *insn = env->prog->insnsi;
3360 	int insn_cnt = env->prog->len;
3361 
3362 	/* now check that all jumps are within the same subprog */
3363 	subprog_start = subprog[cur_subprog].start;
3364 	subprog_end = subprog[cur_subprog + 1].start;
3365 	for (i = 0; i < insn_cnt; i++) {
3366 		u8 code = insn[i].code;
3367 
3368 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3369 			goto next;
3370 		if (BPF_OP(code) == BPF_CALL)
3371 			goto next;
3372 		if (BPF_OP(code) == BPF_EXIT) {
3373 			subprog[cur_subprog].exit_idx = i;
3374 			goto next;
3375 		}
3376 		if (insn_is_gotox(&insn[i]))
3377 			goto next;
3378 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3379 		if (off < subprog_start || off >= subprog_end) {
3380 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3381 			bpf_diag_program_structure(
3382 				env, i, "jump out of range",
3383 				"Keep branch targets within the same subprogram, or use an explicit subprogram call.",
3384 				"Instruction %d jumps to instruction %d, but subprogram %d only contains instructions %d through %d. "
3385 				"A branch target must stay inside the same subprogram.",
3386 				i, off, cur_subprog, subprog_start, subprog_end - 1);
3387 			return -EINVAL;
3388 		}
3389 next:
3390 		if (i == subprog_end - 1) {
3391 			/*
3392 			 * To avoid fall-through from one subprog into another,
3393 			 * the last insn of the subprog should be either exit
3394 			 * or unconditional jump back or bpf_throw call.
3395 			 */
3396 			if (code != (BPF_JMP | BPF_EXIT) &&
3397 			    code != (BPF_JMP32 | BPF_JA) &&
3398 			    code != (BPF_JMP | BPF_JA) &&
3399 			    !insn_is_gotox(&insn[i])) {
3400 				verbose(env, "last insn is not an exit or jmp\n");
3401 				bpf_diag_program_structure(
3402 					env, i, "subprogram can fall through",
3403 					"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
3404 					"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
3405 					cur_subprog, i);
3406 				return -EINVAL;
3407 			}
3408 			subprog_start = subprog_end;
3409 			cur_subprog++;
3410 			if (cur_subprog < env->subprog_cnt)
3411 				subprog_end = subprog[cur_subprog + 1].start;
3412 		}
3413 	}
3414 	return 0;
3415 }
3416 
3417 /*
3418  * The callee of callx is known to the main verification pass only, which
3419  * records the 'caller' -> 'callee' edge of the call graph for the checks
3420  * that follow it: absence of recursion and the maximum stack depth.
3421  */
3422 static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee)
3423 {
3424 	u32 cnt = env->subprog_cnt;
3425 
3426 	if (!env->callx_edges) {
3427 		env->callx_edges = kvcalloc(BITS_TO_LONGS(cnt * cnt), sizeof(long),
3428 					    GFP_KERNEL_ACCOUNT);
3429 		if (!env->callx_edges)
3430 			return -ENOMEM;
3431 	}
3432 	__set_bit(caller * cnt + callee, env->callx_edges);
3433 	return 0;
3434 }
3435 
3436 /*
3437  * Return the first subprog with the number >= 'from' that 'caller' calls
3438  * via callx, or -1 when there is none.
3439  */
3440 static int next_callx_callee(struct bpf_verifier_env *env, int caller, int from)
3441 {
3442 	u32 cnt = env->subprog_cnt;
3443 	unsigned long bit, end = (caller + 1) * cnt;
3444 
3445 	if (!env->callx_edges || from >= cnt)
3446 		return -1;
3447 	bit = find_next_bit(env->callx_edges, end, caller * cnt + from);
3448 	return bit < end ? bit - caller * cnt : -1;
3449 }
3450 
3451 /*
3452  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
3453  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
3454  * address. So unwind_goto has to follow the call and nothing may jump to it.
3455  */
3456 static int check_unwind_insns(struct bpf_verifier_env *env)
3457 {
3458 	struct bpf_insn *insn = env->prog->insnsi;
3459 	bool seen = false;
3460 	int i;
3461 
3462 	for (i = 0; i < env->prog->len; i++, insn++) {
3463 		if (bpf_is_unwind_exit(insn)) {
3464 			bpf_find_containing_subprog(env, i)->can_unwind = true;
3465 			seen = true;
3466 		}
3467 		if (!bpf_is_unwind_goto(insn))
3468 			continue;
3469 		seen = true;
3470 		if (!i || !(bpf_pseudo_call(insn - 1) || bpf_is_callx(insn - 1))) {
3471 			verbose(env, "unwind_goto at insn %d doesn't follow a call of a subprog\n",
3472 				i);
3473 			return -EINVAL;
3474 		}
3475 		if (bpf_is_jump_target(env, i)) {
3476 			verbose(env, "jump to unwind_goto at insn %d\n", i);
3477 			return -EINVAL;
3478 		}
3479 	}
3480 	if (!seen)
3481 		return 0;
3482 	if (!bpf_jit_supports_unwind() || bpf_prog_is_offloaded(env->prog->aux)) {
3483 		verbose(env, "JIT does not support unwinding\n");
3484 		return -ENOTSUPP;
3485 	}
3486 	env->prog->jit_required = 1;
3487 	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind;
3488 	return 0;
3489 }
3490 
3491 /*
3492  * Sort subprogs in topological order so that leaf subprogs come first and
3493  * their callers come later. This is a DFS post-order traversal of the call
3494  * graph. Scan only reachable instructions (those in the computed postorder) of
3495  * the current subprog to discover callees (direct subprogs and sync
3496  * callbacks).
3497  *
3498  * The callees of callx are not known before the main verification pass.
3499  * When callx is used the sort is repeated after it with the recorded callx
3500  * edges added to the call graph to reject recursion through indirect calls.
3501  */
3502 static int sort_subprogs_topo(struct bpf_verifier_env *env)
3503 {
3504 	struct bpf_subprog_info *si = env->subprog_info;
3505 	int *insn_postorder = env->cfg.insn_postorder;
3506 	struct bpf_insn *insn = env->prog->insnsi;
3507 	int cnt = env->subprog_cnt;
3508 	int *dfs_stack = NULL;
3509 	int top = 0, order = 0;
3510 	int i, ret = 0;
3511 	u8 *color = NULL;
3512 
3513 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
3514 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
3515 	if (!color || !dfs_stack) {
3516 		ret = -ENOMEM;
3517 		goto out;
3518 	}
3519 
3520 	/*
3521 	 * DFS post-order traversal.
3522 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
3523 	 */
3524 	for (i = 0; i < cnt; i++) {
3525 		if (color[i])
3526 			continue;
3527 		color[i] = 1;
3528 		dfs_stack[top++] = i;
3529 
3530 		while (top > 0) {
3531 			int cur = dfs_stack[top - 1];
3532 			int po_start = si[cur].postorder_start;
3533 			int po_end = si[cur + 1].postorder_start;
3534 			bool pushed = false;
3535 			int j;
3536 
3537 			for (j = po_start; j < po_end; j++) {
3538 				int idx = insn_postorder[j];
3539 				int callee;
3540 
3541 				if (bpf_is_callx(&insn[idx])) {
3542 					/* find a callee that is not explored yet */
3543 					callee = -1;
3544 					do {
3545 						callee = next_callx_callee(env, cur, callee + 1);
3546 					} while (callee >= 0 && color[callee] == 2);
3547 					if (callee < 0)
3548 						continue;
3549 				} else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) {
3550 					callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
3551 					if (callee < 0) {
3552 						ret = -EFAULT;
3553 						goto out;
3554 					}
3555 				} else {
3556 					continue;
3557 				}
3558 				if (color[callee] == 2)
3559 					continue;
3560 				if (color[callee] == 1) {
3561 					if (bpf_pseudo_func(&insn[idx]))
3562 						continue;
3563 					verbose(env, "recursive call from %s() to %s()\n",
3564 						bpf_subprog_name(env, cur),
3565 						bpf_subprog_name(env, callee));
3566 					bpf_diag_program_structure(
3567 						env, idx, "recursive subprogram call",
3568 						"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
3569 						"This bpf2bpf call would make the subprogram call graph recursive. "
3570 						"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
3571 					ret = -EINVAL;
3572 					goto out;
3573 				}
3574 				color[callee] = 1;
3575 				dfs_stack[top++] = callee;
3576 				pushed = true;
3577 				break;
3578 			}
3579 
3580 			if (!pushed) {
3581 				color[cur] = 2;
3582 				env->subprog_topo_order[order++] = cur;
3583 				top--;
3584 			}
3585 		}
3586 	}
3587 
3588 	if (env->log.level & BPF_LOG_LEVEL2)
3589 		for (i = 0; i < cnt; i++)
3590 			verbose(env, "topo_order[%d] = %s\n",
3591 				i, bpf_subprog_name(env, env->subprog_topo_order[i]));
3592 out:
3593 	kvfree(dfs_stack);
3594 	kvfree(color);
3595 	return ret;
3596 }
3597 
3598 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
3599 				       int spi, int nr_slots)
3600 {
3601 	int i;
3602 
3603 	for (i = 0; i < nr_slots; i++)
3604 		mark_stack_slot_scratched(env, spi - i);
3605 }
3606 
3607 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3608 			   enum bpf_reg_arg_type t)
3609 {
3610 	struct bpf_reg_state *reg;
3611 
3612 	mark_reg_scratched(env, regno);
3613 
3614 	reg = &regs[regno];
3615 	if (t == SRC_OP) {
3616 		/* check whether register used as source operand can be read */
3617 		if (reg->type == NOT_INIT) {
3618 			verbose(env, "R%d !read_ok\n", regno);
3619 			bpf_diag_unreadable_reg(env, env->insn_idx, regno);
3620 			return -EACCES;
3621 		}
3622 		/* We don't need to worry about FP liveness because it's read-only */
3623 		if (regno == BPF_REG_FP)
3624 			return 0;
3625 
3626 		return 0;
3627 	} else {
3628 		/* check whether register used as dest operand can be written to */
3629 		if (regno == BPF_REG_FP) {
3630 			verbose(env, "frame pointer is read only\n");
3631 			return -EACCES;
3632 		}
3633 		if (t == DST_OP)
3634 			mark_reg_unknown(env, regs, regno);
3635 	}
3636 	return 0;
3637 }
3638 
3639 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3640 			 enum bpf_reg_arg_type t)
3641 {
3642 	struct bpf_verifier_state *vstate = env->cur_state;
3643 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3644 
3645 	return __check_reg_arg(env, state->regs, regno, t);
3646 }
3647 
3648 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3649 {
3650 	env->insn_aux_data[idx].indirect_target = true;
3651 }
3652 
3653 static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)
3654 {
3655 	env->insn_aux_data[idx].non_stack_access = true;
3656 }
3657 
3658 /* Layout of one packed linked register in the jump history, see linked_regs_pack() */
3659 #define LR_FRAMENO_BITS	4
3660 #define LR_INDEX_BITS	11
3661 #define LR_FRAMENO_MASK	((1u << LR_FRAMENO_BITS) - 1)
3662 #define LR_IS_REG	BIT(LR_FRAMENO_BITS)
3663 #define LR_INDEX_OFF	(LR_FRAMENO_BITS + 1)
3664 #define LR_INDEX_MASK	((1u << LR_INDEX_BITS) - 1)
3665 #define LINKED_REGS_MAX	BPF_LINKED_REGS_MAX
3666 
3667 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3668 static_assert(MAX_BPF_REG <= (1 << LR_INDEX_BITS));
3669 static_assert(MAX_BPF_STACK_SLOTS <= (1 << LR_INDEX_BITS));
3670 static_assert(LR_INDEX_OFF + LR_INDEX_BITS <= 16);
3671 
3672 struct linked_reg {
3673 	u8 frameno;
3674 	union {
3675 		u16 spi;
3676 		u16 regno;
3677 	};
3678 	bool is_reg;
3679 };
3680 
3681 struct linked_regs {
3682 	int cnt;
3683 	struct linked_reg entries[LINKED_REGS_MAX];
3684 };
3685 
3686 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3687 {
3688 	if (s->cnt < LINKED_REGS_MAX)
3689 		return &s->entries[s->cnt++];
3690 
3691 	return NULL;
3692 }
3693 
3694 /*
3695  * Pack linked registers for a jump history entry, one u16 each:
3696  * - 4 bits frameno
3697  * - 1 bit  is_reg
3698  * - 11 bits register or stack slot index
3699  */
3700 static void linked_regs_pack(const struct linked_regs *s, u16 *packed)
3701 {
3702 	int i;
3703 
3704 	for (i = 0; i < s->cnt; ++i) {
3705 		const struct linked_reg *e = &s->entries[i];
3706 
3707 		packed[i] = e->frameno | (e->is_reg ? LR_IS_REG : 0) | (e->spi << LR_INDEX_OFF);
3708 	}
3709 }
3710 
3711 static void linked_regs_unpack(const struct bpf_jmp_history_entry *hist, struct linked_regs *s)
3712 {
3713 	int i;
3714 
3715 	s->cnt = hist->linked_regs_cnt;
3716 	for (i = 0; i < s->cnt; ++i) {
3717 		struct linked_reg *e = &s->entries[i];
3718 		u16 packed = hist->linked_regs[i];
3719 
3720 		e->frameno = packed & LR_FRAMENO_MASK;
3721 		e->is_reg  = packed & LR_IS_REG;
3722 		e->spi     = (packed >> LR_INDEX_OFF) & LR_INDEX_MASK;
3723 	}
3724 }
3725 
3726 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3727 {
3728 	const struct btf_type *func;
3729 	struct btf *desc_btf;
3730 
3731 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3732 		return NULL;
3733 
3734 	desc_btf = find_kfunc_desc_btf_cached(data, insn->off);
3735 	if (IS_ERR(desc_btf))
3736 		return "<error>";
3737 
3738 	func = btf_type_by_id(desc_btf, insn->imm);
3739 	if (!func || !btf_type_is_func(func))
3740 		return "<error>";
3741 	return btf_name_by_offset(desc_btf, func->name_off);
3742 }
3743 
3744 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3745 {
3746 	const struct bpf_insn_cbs cbs = {
3747 		.cb_call	= bpf_disasm_kfunc_name,
3748 		.cb_print	= verbose,
3749 		.private_data	= env,
3750 	};
3751 
3752 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3753 }
3754 
3755 /* If any register R in hist->linked_regs is marked as precise in bt,
3756  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3757  */
3758 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3759 {
3760 	struct linked_regs linked_regs;
3761 	bool some_precise = false;
3762 	int i;
3763 
3764 	if (!hist || !hist->linked_regs_cnt)
3765 		return;
3766 
3767 	linked_regs_unpack(hist, &linked_regs);
3768 	for (i = 0; i < linked_regs.cnt; ++i) {
3769 		struct linked_reg *e = &linked_regs.entries[i];
3770 
3771 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3772 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3773 			some_precise = true;
3774 			break;
3775 		}
3776 	}
3777 
3778 	if (!some_precise)
3779 		return;
3780 
3781 	for (i = 0; i < linked_regs.cnt; ++i) {
3782 		struct linked_reg *e = &linked_regs.entries[i];
3783 
3784 		if (e->is_reg)
3785 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3786 		else
3787 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3788 	}
3789 }
3790 
3791 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3792 {
3793 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3794 }
3795 
3796 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3797  * desired reg and stack masks across all relevant frames
3798  */
3799 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3800 				      struct bpf_verifier_state *starting_state)
3801 {
3802 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3803 }
3804 
3805 /* check if register is a constant scalar value */
3806 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3807 {
3808 	return reg->type == SCALAR_VALUE &&
3809 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3810 }
3811 
3812 /* assuming is_reg_const() is true, return constant value of a register */
3813 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3814 {
3815 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3816 }
3817 
3818 static bool is_pointer_regtype(enum bpf_reg_type type)
3819 {
3820 	return type != SCALAR_VALUE && type != NOT_INIT;
3821 }
3822 
3823 static bool __is_pointer_value(bool allow_ptr_leaks,
3824 			       const struct bpf_reg_state *reg)
3825 {
3826 	if (allow_ptr_leaks)
3827 		return false;
3828 
3829 	return reg->type != SCALAR_VALUE;
3830 }
3831 
3832 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3833 					struct bpf_reg_state *src_reg)
3834 {
3835 	if (src_reg->type != SCALAR_VALUE)
3836 		return;
3837 	/*
3838 	 * The verifier is processing rX = rY insn and
3839 	 * rY->id has special linked register already.
3840 	 * Cleared it, since multiple rX += const are not supported.
3841 	 */
3842 	if (src_reg->id & BPF_ADD_CONST)
3843 		clear_scalar_id(src_reg);
3844 	/*
3845 	 * Ensure that src_reg has a valid ID that will be copied to
3846 	 * dst_reg and then will be used by sync_linked_regs() to
3847 	 * propagate min/max range.
3848 	 */
3849 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3850 		src_reg->id = ++env->id_gen;
3851 }
3852 
3853 static void save_register_state(struct bpf_verifier_env *env,
3854 				struct bpf_func_state *state,
3855 				int spi, struct bpf_reg_state *reg,
3856 				int size)
3857 {
3858 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3859 	int i;
3860 
3861 	bpf_diag_mod_begin(env, &slot->spilled_ptr, reg, BPF_DIAG_MOD_SPILL);
3862 	slot->spilled_ptr = *reg;
3863 
3864 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3865 		slot->slot_type[i - 1] = STACK_SPILL;
3866 
3867 	/* size < 8 bytes spill */
3868 	for (; i; i--)
3869 		mark_stack_slot_misc(env, &slot->slot_type[i - 1]);
3870 
3871 	bpf_diag_mod_end(env);
3872 }
3873 
3874 static bool is_bpf_st_mem(struct bpf_insn *insn)
3875 {
3876 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3877 }
3878 
3879 static int get_reg_width(struct bpf_reg_state *reg)
3880 {
3881 	return fls64(reg_umax(reg));
3882 }
3883 
3884 /* See comment for mark_fastcall_pattern_for_call() */
3885 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3886 					  struct bpf_func_state *state, int insn_idx, int off)
3887 {
3888 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3889 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3890 	int i;
3891 
3892 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3893 		return;
3894 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3895 	 * from something that is not a part of the fastcall pattern,
3896 	 * disable fastcall rewrites for current subprogram by setting
3897 	 * fastcall_stack_off to a value smaller than any possible offset.
3898 	 */
3899 	subprog->fastcall_stack_off = S16_MIN;
3900 	/* reset fastcall aux flags within subprogram,
3901 	 * happens at most once per subprogram
3902 	 */
3903 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3904 		aux[i].fastcall_spills_num = 0;
3905 		aux[i].fastcall_pattern = 0;
3906 	}
3907 }
3908 
3909 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3910 {
3911 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3912 	int i;
3913 
3914 	/* regular write of data into stack destroys any spilled ptr */
3915 	slot->spilled_ptr.type = NOT_INIT;
3916 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3917 	if (is_stack_slot_special(slot))
3918 		for (i = 0; i < BPF_REG_SIZE; i++)
3919 			scrub_spilled_slot(&slot->slot_type[i]);
3920 }
3921 
3922 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3923  * stack boundary and alignment are checked in check_mem_access()
3924  */
3925 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3926 				       /* stack frame we're writing to */
3927 				       struct bpf_func_state *state,
3928 				       int off, int size, int value_regno,
3929 				       int insn_idx)
3930 {
3931 	struct bpf_func_state *cur; /* state of the current function */
3932 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3933 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3934 	struct bpf_reg_state *reg = NULL;
3935 	int insn_flags = INSN_F_STACK_ACCESS;
3936 	int hist_spi = spi, hist_frame = state->frameno;
3937 	struct bpf_stack_state *ss = bpf_stack_slot(state, spi);
3938 
3939 	/*
3940 	 * caller checked that off % size == 0 and -env->stack_limit <= off < 0,
3941 	 * so it's aligned access and [off, off + size) are within stack limits
3942 	 */
3943 	if (!env->allow_ptr_leaks &&
3944 	    bpf_is_spilled_reg(ss) &&
3945 	    !bpf_is_spilled_scalar_reg(ss) &&
3946 	    size != BPF_REG_SIZE) {
3947 		const char *reason;
3948 
3949 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3950 		reason = bpf_diag_fmt(env,
3951 				      "This store writes %d bytes at stack offset %d into a stack slot that currently holds a spilled pointer. "
3952 			"Partial writes to spilled pointers are rejected because they can corrupt pointer metadata and leak kernel pointers.",
3953 			size, off);
3954 		bpf_diag_memory(
3955 			env, insn_idx, "stack spill corruption", reason,
3956 			"Write the full 8-byte spilled pointer slot, or use a separate stack slot for scalar data before overwriting only part of it.");
3957 		return -EACCES;
3958 	}
3959 
3960 	cur = env->cur_state->frame[env->cur_state->curframe];
3961 	if (value_regno >= 0)
3962 		reg = &cur->regs[value_regno];
3963 	if (!env->bypass_spec_v4) {
3964 		bool sanitize = reg && is_pointer_regtype(reg->type);
3965 
3966 		for (i = 0; i < size; i++) {
3967 			u8 type = ss->slot_type[(slot - i) %
3968 							      BPF_REG_SIZE];
3969 
3970 			if (type != STACK_MISC && type != STACK_ZERO) {
3971 				sanitize = true;
3972 				break;
3973 			}
3974 		}
3975 
3976 		if (sanitize)
3977 			env->insn_aux_data[insn_idx].nospec_result = true;
3978 	}
3979 
3980 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3981 	if (err)
3982 		return err;
3983 
3984 	mark_stack_slot_scratched(env, spi);
3985 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3986 		bool reg_value_fits;
3987 
3988 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3989 		/* Make sure that reg had an ID to build a relation on spill. */
3990 		if (reg_value_fits)
3991 			assign_scalar_id_before_mov(env, reg);
3992 		save_register_state(env, state, spi, reg, size);
3993 		/* Break the relation on a narrowing spill. */
3994 		if (!reg_value_fits)
3995 			clear_scalar_id(&ss->spilled_ptr);
3996 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3997 		   env->bpf_capable) {
3998 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3999 
4000 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4001 		__mark_reg_known(tmp_reg, insn->imm);
4002 		tmp_reg->type = SCALAR_VALUE;
4003 		save_register_state(env, state, spi, tmp_reg, size);
4004 	} else if (reg && is_pointer_regtype(reg->type)) {
4005 		/* register containing pointer is being spilled into stack */
4006 		if (size != BPF_REG_SIZE) {
4007 			verbose_linfo(env, insn_idx, "; ");
4008 			verbose(env, "invalid size of register spill\n");
4009 			return -EACCES;
4010 		}
4011 		if (state != cur && reg->type == PTR_TO_STACK) {
4012 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4013 			return -EINVAL;
4014 		}
4015 		save_register_state(env, state, spi, reg, size);
4016 	} else {
4017 		u8 type = STACK_MISC;
4018 
4019 		if (bpf_is_spilled_reg(ss))
4020 			bpf_diag_record_scrub(env, &ss->spilled_ptr,
4021 					      BPF_DIAG_MOD_WRITE);
4022 		scrub_special_slot(state, spi);
4023 
4024 		/* when we zero initialize stack slots mark them as such */
4025 		if ((reg && bpf_register_is_null(reg)) ||
4026 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4027 			/* STACK_ZERO case happened because register spill
4028 			 * wasn't properly aligned at the stack slot boundary,
4029 			 * so it's not a register spill anymore; force
4030 			 * originating register to be precise to make
4031 			 * STACK_ZERO correct for subsequent states
4032 			 */
4033 			err = mark_chain_precision(env, value_regno);
4034 			if (err)
4035 				return err;
4036 			type = STACK_ZERO;
4037 		}
4038 
4039 		/* Mark slots affected by this stack write. */
4040 		for (i = 0; i < size; i++)
4041 			ss->slot_type[(slot - i) % BPF_REG_SIZE] = type;
4042 		insn_flags = 0; /* not a register spill */
4043 	}
4044 
4045 	if (insn_flags)
4046 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4047 					    hist_spi, hist_frame, NULL, 0);
4048 	return 0;
4049 }
4050 
4051 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
4052  * known to contain a variable offset.
4053  * This function checks whether the write is permitted and conservatively
4054  * tracks the effects of the write, considering that each stack slot in the
4055  * dynamic range is potentially written to.
4056  *
4057  * 'value_regno' can be -1, meaning that an unknown value is being written to
4058  * the stack.
4059  *
4060  * Spilled pointers in range are not marked as written because we don't know
4061  * what's going to be actually written. This means that read propagation for
4062  * future reads cannot be terminated by this write.
4063  *
4064  * For privileged programs, uninitialized stack slots are considered
4065  * initialized by this write (even though we don't know exactly what offsets
4066  * are going to be written to). The idea is that we don't want the verifier to
4067  * reject future reads that access slots written to through variable offsets.
4068  */
4069 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4070 				     /* func where register points to */
4071 				     struct bpf_func_state *state,
4072 				     struct bpf_reg_state *ptr_reg, int off, int size,
4073 				     int value_regno, int insn_idx)
4074 {
4075 	struct bpf_func_state *cur; /* state of the current function */
4076 	int min_off, max_off;
4077 	int i, err;
4078 	struct bpf_reg_state *value_reg = NULL;
4079 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4080 	bool writing_zero = false;
4081 	/* set if the fact that we're writing a zero is used to let any
4082 	 * stack slots remain STACK_ZERO
4083 	 */
4084 	bool zero_used = false;
4085 
4086 	cur = env->cur_state->frame[env->cur_state->curframe];
4087 	min_off = reg_smin(ptr_reg) + off;
4088 	max_off = reg_smax(ptr_reg) + off + size;
4089 	if (value_regno >= 0)
4090 		value_reg = &cur->regs[value_regno];
4091 	if ((value_reg && bpf_register_is_null(value_reg)) ||
4092 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4093 		writing_zero = true;
4094 
4095 	err = destroy_dynptrs_in_stack_slots(env, state, bpf_get_spi(max_off - 1),
4096 					     bpf_get_spi(min_off));
4097 	if (err)
4098 		return err;
4099 
4100 	/* Variable offset writes destroy any spilled pointers in range. */
4101 	for (i = min_off; i < max_off; i++) {
4102 		struct bpf_stack_state *ss;
4103 		u8 new_type, *stype;
4104 		int slot, spi;
4105 
4106 		slot = -i - 1;
4107 		spi = slot / BPF_REG_SIZE;
4108 		ss = bpf_stack_slot(state, spi);
4109 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
4110 		mark_stack_slot_scratched(env, spi);
4111 
4112 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4113 			/* Reject the write if range we may write to has not
4114 			 * been initialized beforehand. If we didn't reject
4115 			 * here, the ptr status would be erased below (even
4116 			 * though not all slots are actually overwritten),
4117 			 * possibly opening the door to leaks.
4118 			 *
4119 			 * We do however catch STACK_INVALID case below, and
4120 			 * only allow reading possibly uninitialized memory
4121 			 * later for CAP_PERFMON, as the write may not happen to
4122 			 * that slot.
4123 			 */
4124 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4125 				insn_idx, i);
4126 			return -EINVAL;
4127 		}
4128 
4129 		/* If writing_zero and the spi slot contains a spill of value 0,
4130 		 * maintain the spill type.
4131 		 */
4132 		if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) {
4133 			struct bpf_reg_state *spill_reg = &ss->spilled_ptr;
4134 
4135 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4136 				zero_used = true;
4137 				continue;
4138 			}
4139 		}
4140 
4141 		/*
4142 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
4143 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
4144 		 * and valid program is rejected by check_stack_read_fixed_off()
4145 		 * with obscure "invalid size of register fill" message.
4146 		 */
4147 		scrub_special_slot(state, spi);
4148 
4149 		/* Update the slot type. */
4150 		new_type = STACK_MISC;
4151 		if (writing_zero && *stype == STACK_ZERO) {
4152 			new_type = STACK_ZERO;
4153 			zero_used = true;
4154 		}
4155 		/* If the slot is STACK_INVALID, we check whether it's OK to
4156 		 * pretend that it will be initialized by this write. The slot
4157 		 * might not actually be written to, and so if we mark it as
4158 		 * initialized future reads might leak uninitialized memory.
4159 		 * For privileged programs, we will accept such reads to slots
4160 		 * that may or may not be written because, if we're reject
4161 		 * them, the error would be too confusing.
4162 		 * Conservatively, treat STACK_POISON in a similar way.
4163 		 */
4164 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
4165 		    !env->allow_uninit_stack) {
4166 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4167 					insn_idx, i);
4168 			return -EINVAL;
4169 		}
4170 		*stype = new_type;
4171 	}
4172 	if (zero_used) {
4173 		/* backtracking doesn't work for STACK_ZERO yet. */
4174 		err = mark_chain_precision(env, value_regno);
4175 		if (err)
4176 			return err;
4177 	}
4178 	bpf_diag_record_scrub_stack(env, state, min_off, max_off,
4179 				    BPF_DIAG_MOD_VAR_WRITE);
4180 	return 0;
4181 }
4182 
4183 /* When register 'dst_regno' is assigned some values from stack[min_off,
4184  * max_off), we set the register's type according to the types of the
4185  * respective stack slots. If all the stack values are known to be zeros, then
4186  * so is the destination reg. Otherwise, the register is considered to be
4187  * SCALAR. This function does not deal with register filling; the caller must
4188  * ensure that all spilled registers in the stack range have been marked as
4189  * read.
4190  *
4191  * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered
4192  * zero bytes. In that case, mark the contributing stack slots precise so
4193  * pruning cannot reuse a zero-spill state for a later non-zero spill state.
4194  *
4195  * Returns an error if precision backtracking fails.
4196  */
4197 static int mark_reg_stack_read(struct bpf_verifier_env *env,
4198 			       /* func where src register points to */
4199 			       struct bpf_func_state *ptr_state,
4200 			       int min_off, int max_off, int dst_regno)
4201 {
4202 	struct bpf_verifier_state *vstate = env->cur_state;
4203 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4204 	int i, slot, spi;
4205 	u8 *stype;
4206 	int zeros = 0, zero_spills = 0;
4207 
4208 	for (i = min_off; i < max_off; i++) {
4209 		slot = -i - 1;
4210 		spi = slot / BPF_REG_SIZE;
4211 		mark_stack_slot_scratched(env, spi);
4212 		stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4213 		if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) {
4214 			zeros++;
4215 			continue;
4216 		}
4217 		if (stype[slot % BPF_REG_SIZE] == STACK_SPILL &&
4218 		    bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) {
4219 			zero_spills++;
4220 			zeros++;
4221 			continue;
4222 		}
4223 		break;
4224 	}
4225 	if (zeros == max_off - min_off) {
4226 		/* Any access_size read into register is zero extended,
4227 		 * so the whole register == const_zero.
4228 		 */
4229 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4230 		if (zero_spills) {
4231 			for (i = min_off; i < max_off; i++) {
4232 				slot = -i - 1;
4233 				spi = slot / BPF_REG_SIZE;
4234 				stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4235 				if (stype[slot % BPF_REG_SIZE] == STACK_SPILL)
4236 					bpf_bt_set_frame_slot(&env->bt, ptr_state->frameno, spi);
4237 			}
4238 			return mark_chain_precision_batch(env, env->cur_state);
4239 		}
4240 	} else {
4241 		/* have read misc data from the stack */
4242 		mark_reg_unknown(env, state->regs, dst_regno);
4243 	}
4244 
4245 	return 0;
4246 }
4247 
4248 static void bpf_diag_stack_read_invalid(struct bpf_verifier_env *env, int off, int i, int size,
4249 					enum bpf_stack_slot_type type)
4250 {
4251 	const char *problem, *reason, *suggestion, *kind;
4252 
4253 	if (type == STACK_INVALID) {
4254 		reason = bpf_diag_fmt(
4255 			env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range is uninitialized on this path. "
4256 			"Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.",
4257 			size, off, i);
4258 		bpf_diag_memory(
4259 			env, env->insn_idx, "uninitialized stack read", reason,
4260 			"Initialize every byte in the stack range before reading it, adjust the offset and size so the read covers only initialized bytes, "
4261 			"or load with CAP_PERFMON if uninitialized stack reads are intended.");
4262 		return;
4263 	}
4264 
4265 	switch (type) {
4266 	case STACK_DYNPTR:
4267 		kind = "dynptr";
4268 		suggestion = "Use dynptr helpers or kfuncs to access the object represented by the dynptr instead of reading the dynptr state directly.";
4269 		break;
4270 	case STACK_ITER:
4271 		kind = "iterator";
4272 		suggestion = "Use iterator kfuncs to advance or destroy the iterator instead of reading its state directly.";
4273 		break;
4274 	case STACK_IRQ_FLAG:
4275 		kind = "IRQ flag";
4276 		suggestion = "Pass the saved IRQ flag to the matching restore kfunc instead of reading its state directly.";
4277 		break;
4278 	default:
4279 		return;
4280 	}
4281 
4282 	problem = bpf_diag_fmt(env, "direct read of %s stack state", kind);
4283 	reason = bpf_diag_fmt(
4284 		env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range belongs to verifier-managed %s state. "
4285 		"This state has an opaque representation that BPF programs cannot read directly.",
4286 		size, off, i, kind);
4287 	bpf_diag_memory(env, env->insn_idx, problem, reason, suggestion);
4288 }
4289 
4290 /* Read the stack at 'off' and put the results into the register indicated by
4291  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4292  * spilled reg.
4293  *
4294  * 'dst_regno' can be -1, meaning that the read value is not going to a
4295  * register.
4296  *
4297  * The access is assumed to be within the current stack bounds.
4298  */
4299 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4300 				      /* func where src register points to */
4301 				      struct bpf_func_state *reg_state,
4302 				      int off, int size, int dst_regno)
4303 {
4304 	struct bpf_verifier_state *vstate = env->cur_state;
4305 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4306 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4307 	struct bpf_reg_state *reg;
4308 	u8 *stype, type;
4309 	int err;
4310 	int insn_flags = INSN_F_STACK_ACCESS;
4311 	int hist_spi = spi, hist_frame = reg_state->frameno;
4312 	struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi);
4313 
4314 	stype = ss->slot_type;
4315 	reg = &ss->spilled_ptr;
4316 
4317 	mark_stack_slot_scratched(env, spi);
4318 
4319 	/*
4320 	 * Refine the in-progress load record's origin to the source stack slot.
4321 	 */
4322 	if (dst_regno >= 0)
4323 		bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE);
4324 
4325 	if (bpf_is_spilled_reg(ss)) {
4326 		u8 spill_size = bpf_spill_size(ss);
4327 
4328 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4329 			if (reg->type != SCALAR_VALUE) {
4330 				verbose_linfo(env, env->insn_idx, "; ");
4331 				verbose(env, "invalid size of register fill\n");
4332 				return -EACCES;
4333 			}
4334 
4335 			if (size <= spill_size &&
4336 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4337 				if (dst_regno < 0)
4338 					return 0;
4339 
4340 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
4341 				    get_reg_width(reg) <= 32)
4342 					/* Ensure stack slot has an ID to build a relation
4343 					 * with the destination register on fill.
4344 					 */
4345 					assign_scalar_id_before_mov(env, reg);
4346 				state->regs[dst_regno] = *reg;
4347 
4348 				/* Break the relation on a narrowing fill.
4349 				 * coerce_reg_to_size will adjust the boundaries.
4350 				 */
4351 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4352 					clear_scalar_id(&state->regs[dst_regno]);
4353 			} else {
4354 				int spill_cnt = 0, zero_cnt = 0;
4355 
4356 				for (i = 0; i < size; i++) {
4357 					type = stype[(slot - i) % BPF_REG_SIZE];
4358 					if (type == STACK_SPILL) {
4359 						spill_cnt++;
4360 						continue;
4361 					}
4362 					if (type == STACK_MISC)
4363 						continue;
4364 					if (type == STACK_ZERO) {
4365 						zero_cnt++;
4366 						continue;
4367 					}
4368 					if (type == STACK_INVALID && env->allow_uninit_stack)
4369 						continue;
4370 					if (type == STACK_POISON) {
4371 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4372 							off, i, size);
4373 					} else {
4374 						verbose(env, "invalid read from stack off %d+%d size %d\n",
4375 							off, i, size);
4376 						bpf_diag_stack_read_invalid(env, off, i, size, type);
4377 					}
4378 					return -EACCES;
4379 				}
4380 
4381 				if (dst_regno < 0)
4382 					return 0;
4383 
4384 				if (spill_cnt == size &&
4385 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4386 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4387 					/* this IS register fill, so keep insn_flags */
4388 				} else if (zero_cnt == size) {
4389 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4390 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4391 					insn_flags = 0; /* not restoring original register state */
4392 				} else {
4393 					err = mark_reg_stack_read(env, reg_state, off, off + size,
4394 								  dst_regno);
4395 					if (err)
4396 						return err;
4397 					insn_flags = 0; /* not restoring original register state */
4398 				}
4399 			}
4400 		} else if (dst_regno >= 0) {
4401 			/* restore register state from stack */
4402 			if (env->bpf_capable)
4403 				/* Ensure stack slot has an ID to build a relation
4404 				 * with the destination register on fill.
4405 				 */
4406 				assign_scalar_id_before_mov(env, reg);
4407 			state->regs[dst_regno] = *reg;
4408 			/* mark reg as written since spilled pointer state likely
4409 			 * has its liveness marks cleared by is_state_visited()
4410 			 * which resets stack/reg liveness for state transitions
4411 			 */
4412 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4413 			/* If dst_regno==-1, the caller is asking us whether
4414 			 * it is acceptable to use this value as a SCALAR_VALUE
4415 			 * (e.g. for XADD).
4416 			 * We must not allow unprivileged callers to do that
4417 			 * with spilled pointers.
4418 			 */
4419 			verbose(env, "leaking pointer from stack off %d\n",
4420 				off);
4421 			return -EACCES;
4422 		}
4423 	} else {
4424 		for (i = 0; i < size; i++) {
4425 			type = stype[(slot - i) % BPF_REG_SIZE];
4426 			if (type == STACK_MISC)
4427 				continue;
4428 			if (type == STACK_ZERO)
4429 				continue;
4430 			if (type == STACK_INVALID && env->allow_uninit_stack)
4431 				continue;
4432 			if (type == STACK_POISON) {
4433 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4434 					off, i, size);
4435 			} else {
4436 				verbose(env, "invalid read from stack off %d+%d size %d\n",
4437 					off, i, size);
4438 				bpf_diag_stack_read_invalid(env, off, i, size, type);
4439 			}
4440 			return -EACCES;
4441 		}
4442 		if (dst_regno >= 0) {
4443 			err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4444 			if (err)
4445 				return err;
4446 		}
4447 		insn_flags = 0; /* we are not restoring spilled register */
4448 	}
4449 	if (insn_flags)
4450 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4451 					    hist_spi, hist_frame, NULL, 0);
4452 	return 0;
4453 }
4454 
4455 enum bpf_access_src {
4456 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4457 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4458 };
4459 
4460 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4461 					 argno_t argno, int off, int access_size,
4462 					 bool zero_size_allowed,
4463 					 enum bpf_access_type type,
4464 					 struct bpf_call_arg_meta *meta);
4465 
4466 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4467 {
4468 	return cur_regs(env) + regno;
4469 }
4470 
4471 /* Read the stack at 'reg + off' and put the result into the register
4472  * 'dst_regno'.
4473  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
4474  * but not its variable offset.
4475  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4476  *
4477  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4478  * filling registers (i.e. reads of spilled register cannot be detected when
4479  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4480  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
4481  * offset; for a fixed offset check_stack_read_fixed_off should be used
4482  * instead.
4483  */
4484 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4485 				    argno_t ptr_argno, int off, int size, int dst_regno)
4486 {
4487 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
4488 	int err;
4489 	int min_off, max_off;
4490 
4491 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4492 	 */
4493 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
4494 					    false, BPF_READ, NULL);
4495 	if (err)
4496 		return err;
4497 
4498 	min_off = reg_smin(reg) + off;
4499 	max_off = reg_smax(reg) + off;
4500 	err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size,
4501 				  dst_regno);
4502 	if (err)
4503 		return err;
4504 	return 0;
4505 }
4506 
4507 /* check_stack_read dispatches to check_stack_read_fixed_off or
4508  * check_stack_read_var_off.
4509  *
4510  * The caller must ensure that the offset falls within the allocated stack
4511  * bounds.
4512  *
4513  * 'dst_regno' is a register which will receive the value from the stack. It
4514  * can be -1, meaning that the read value is not going to a register.
4515  */
4516 static int check_stack_read(struct bpf_verifier_env *env,
4517 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
4518 			    int dst_regno)
4519 {
4520 	struct bpf_func_state *state = bpf_func(env, reg);
4521 	int err;
4522 	/* Some accesses are only permitted with a static offset. */
4523 	bool var_off = !tnum_is_const(reg->var_off);
4524 
4525 	/* The offset is required to be static when reads don't go to a
4526 	 * register, in order to not leak pointers (see
4527 	 * check_stack_read_fixed_off).
4528 	 */
4529 	if (dst_regno < 0 && var_off) {
4530 		const char *reason;
4531 		char tn_buf[48];
4532 
4533 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4534 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4535 			tn_buf, off, size);
4536 		reason = bpf_diag_fmt(
4537 			env, "The instruction would access the stack through variable offset %s plus fixed offset %d and size %d. "
4538 			"This stack access requires a constant stack offset and a precise initialized range.",
4539 			tn_buf, off, size);
4540 		bpf_diag_memory(
4541 			env, env->insn_idx, "variable-offset stack access", reason,
4542 			"Use a fixed stack offset for the instruction, selecting the target stack slot on separate control-flow paths if necessary.");
4543 		return -EACCES;
4544 	}
4545 	/* Variable offset is prohibited for unprivileged mode for simplicity
4546 	 * since it requires corresponding support in Spectre masking for stack
4547 	 * ALU. See also retrieve_ptr_limit(). The check in
4548 	 * check_stack_access_for_ptr_arithmetic() called by
4549 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4550 	 * with variable offsets, therefore no check is required here. Further,
4551 	 * just checking it here would be insufficient as speculative stack
4552 	 * writes could still lead to unsafe speculative behaviour.
4553 	 */
4554 	if (!var_off) {
4555 		off += reg->var_off.value;
4556 		err = check_stack_read_fixed_off(env, state, off, size,
4557 						 dst_regno);
4558 	} else {
4559 		/* Variable offset stack reads need more conservative handling
4560 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4561 		 * branch.
4562 		 */
4563 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
4564 					       dst_regno);
4565 	}
4566 	return err;
4567 }
4568 
4569 /*
4570  * An access through a slice that may be the buffer on the stack, see bpf_reg_state::buf, is
4571  * not seen as an access to the stack. That's fine as long as nothing is tracked in the buffer.
4572  * The output of helpers and kfuncs is not tracked. Here an insn stores to [min_off, max_off)
4573  * of frame @frameno, a dynptr, an iterator or irq flags are made there, or the frame is gone.
4574  */
4575 static void invalidate_stack_slices(struct bpf_verifier_env *env, u32 frameno,
4576 				    int min_off, int max_off)
4577 {
4578 	struct bpf_func_state *state;
4579 	struct bpf_reg_state *reg;
4580 
4581 	if (!env->seen_stack_slice)
4582 		return;
4583 
4584 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
4585 		if (base_type(reg->type) != PTR_TO_MEM || !reg->buf.size ||
4586 		    reg->buf.frameno != frameno || reg->buf.off >= max_off ||
4587 		    reg->buf.off + (int)reg->buf.size <= min_off)
4588 			continue;
4589 		bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_SLICE_BUF);
4590 		mark_reg_invalid(env, reg);
4591 	}));
4592 }
4593 
4594 /* check_stack_write dispatches to check_stack_write_fixed_off or
4595  * check_stack_write_var_off.
4596  *
4597  * 'reg' is the register used as a pointer into the stack.
4598  * 'value_regno' is the register whose value we're writing to the stack. It can
4599  * be -1, meaning that we're not writing from a register.
4600  *
4601  * The caller must ensure that the offset falls within the maximum stack size.
4602  */
4603 static int check_stack_write(struct bpf_verifier_env *env,
4604 			     struct bpf_reg_state *reg, int off, int size,
4605 			     int value_regno, int insn_idx)
4606 {
4607 	struct bpf_func_state *state = bpf_func(env, reg);
4608 	int min_off = reg_smin(reg) + off;
4609 	int max_off = reg_smax(reg) + off + size;
4610 	int err;
4611 
4612 	if (tnum_is_const(reg->var_off)) {
4613 		off += reg->var_off.value;
4614 		err = check_stack_write_fixed_off(env, state, off, size,
4615 						  value_regno, insn_idx);
4616 	} else {
4617 		/* Variable offset stack reads need more conservative handling
4618 		 * than fixed offset ones.
4619 		 */
4620 		err = check_stack_write_var_off(env, state,
4621 						reg, off, size,
4622 						value_regno, insn_idx);
4623 	}
4624 	/* After the write is modelled: the insn may store a slice to its own buffer. */
4625 	invalidate_stack_slices(env, state->frameno, min_off, max_off);
4626 	return err;
4627 }
4628 
4629 /*
4630  * Write a value to the outgoing stack arg area.
4631  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4632  */
4633 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4634 				 int off, struct bpf_reg_state *value_reg)
4635 {
4636 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4637 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4638 	int spi = -off / BPF_REG_SIZE - 1;
4639 	struct bpf_reg_state *arg;
4640 	int err;
4641 
4642 	if (spi >= max_stack_arg_regs) {
4643 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4644 			off, max_stack_arg_regs);
4645 		return -EINVAL;
4646 	}
4647 
4648 	err = grow_stack_arg_slots(env, state, spi + 1);
4649 	if (err)
4650 		return err;
4651 
4652 	/* Track the max outgoing stack arg slot count. */
4653 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4654 		subprog->max_out_stack_arg_cnt = spi + 1;
4655 
4656 	arg = &state->stack_arg_regs[spi];
4657 	bpf_diag_mod_begin(env, arg, value_reg, BPF_DIAG_MOD_WRITE);
4658 
4659 	if (value_reg) {
4660 		state->stack_arg_regs[spi] = *value_reg;
4661 	} else {
4662 		/* BPF_ST: store immediate, treat as scalar */
4663 		arg->type = SCALAR_VALUE;
4664 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4665 	}
4666 	bpf_diag_mod_end(env);
4667 	state->no_stack_arg_load = true;
4668 	return bpf_push_jmp_history(env, env->cur_state,
4669 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4670 }
4671 
4672 /*
4673  * Read a value from the incoming stack arg area.
4674  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4675  */
4676 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4677 				int off, int dst_regno)
4678 {
4679 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4680 	struct bpf_verifier_state *vstate = env->cur_state;
4681 	int spi = off / BPF_REG_SIZE - 1;
4682 	struct bpf_func_state *caller, *cur;
4683 	struct bpf_reg_state *arg;
4684 
4685 	if (state->no_stack_arg_load) {
4686 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4687 		return -EINVAL;
4688 	}
4689 
4690 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4691 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4692 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4693 		return -EACCES;
4694 	}
4695 
4696 	caller = vstate->frame[vstate->curframe - 1];
4697 	arg = bpf_get_spilled_stack_arg(spi, caller);
4698 	if (!arg) {
4699 		verbose(env, "invalid read from uninitialized stack arg off %d\n", off);
4700 		return -EACCES;
4701 	}
4702 
4703 	cur = vstate->frame[vstate->curframe];
4704 	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
4705 	cur->regs[dst_regno] = *arg;
4706 	bpf_diag_mod_end(env);
4707 	return bpf_push_jmp_history(env, env->cur_state,
4708 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4709 }
4710 
4711 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4712 {
4713 	struct bpf_func_state *caller = cur_func(env);
4714 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4715 
4716 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4717 	return mark_chain_precision_batch(env, env->cur_state);
4718 }
4719 
4720 static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)
4721 {
4722 	int regno = reg_from_argno(argno);
4723 
4724 	if (regno >= 0)
4725 		return mark_chain_precision(env, regno);
4726 	return mark_stack_arg_precision(env, arg_idx_from_argno(argno));
4727 }
4728 
4729 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4730 				     int nargs, const char *callee_name, const struct btf *btf,
4731 				     const struct btf_param *args)
4732 {
4733 	int i, spi;
4734 
4735 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4736 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4737 		if (spi >= caller->out_stack_arg_cnt ||
4738 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4739 			const char *arg_name = NULL;
4740 
4741 			if (args && args[i].name_off)
4742 				arg_name = btf_name_by_offset(btf, args[i].name_off);
4743 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4744 				nargs, spi + 1);
4745 			bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi,
4746 						  callee_name, arg_name);
4747 			return -EFAULT;
4748 		}
4749 	}
4750 
4751 	return 0;
4752 }
4753 
4754 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4755 					      struct bpf_reg_state *regs, int arg)
4756 {
4757 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4758 		return &regs[arg + 1];
4759 
4760 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4761 }
4762 
4763 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4764 				 int off, int size, enum bpf_access_type type)
4765 {
4766 	struct bpf_map *map = reg->map_ptr;
4767 	u32 cap = bpf_map_flags_to_cap(map);
4768 
4769 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4770 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4771 			map->value_size, reg_smin(reg) + off, size);
4772 		return -EACCES;
4773 	}
4774 
4775 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4776 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4777 			map->value_size, reg_smin(reg) + off, size);
4778 		return -EACCES;
4779 	}
4780 
4781 	return 0;
4782 }
4783 
4784 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4785 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4786 			      int off, int size, u32 mem_size,
4787 			      bool zero_size_allowed)
4788 {
4789 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4790 
4791 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4792 		return 0;
4793 
4794 	switch (reg->type) {
4795 	case PTR_TO_MAP_KEY:
4796 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4797 			mem_size, off, size);
4798 		break;
4799 	case PTR_TO_MAP_VALUE:
4800 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4801 			mem_size, off, size);
4802 		break;
4803 	case PTR_TO_PACKET:
4804 	case PTR_TO_PACKET_META:
4805 	case PTR_TO_PACKET_END:
4806 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4807 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4808 		break;
4809 	case PTR_TO_CTX:
4810 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4811 			mem_size, off, size);
4812 		break;
4813 	case PTR_TO_MEM:
4814 	default:
4815 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4816 			mem_size, off, size);
4817 	}
4818 
4819 	return -EACCES;
4820 }
4821 
4822 /* check read/write into a memory region with possible variable offset */
4823 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4824 				   int off, int size, u32 mem_size,
4825 				   bool zero_size_allowed)
4826 {
4827 	const char *proof = "";
4828 	const char *start;
4829 	s64 max_start, max_end;
4830 	int err;
4831 
4832 	/* We may have adjusted the register pointing to memory region, so we
4833 	 * need to try adding each of min_value and max_value to off
4834 	 * to make sure our theoretical access will be safe.
4835 	 *
4836 	 * The minimum value is only important with signed
4837 	 * comparisons where we can't assume the floor of a
4838 	 * value is 0.  If we are using signed variables for our
4839 	 * index'es we need to make sure that whatever we use
4840 	 * will have a set floor within our range.
4841 	 */
4842 	if (reg_smin(reg) < 0 &&
4843 	    (reg_smin(reg) == S64_MIN ||
4844 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4845 	      reg_smin(reg) + off < 0)) {
4846 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4847 			reg_arg_name(env, argno));
4848 		err = -EACCES;
4849 		if (bpf_diag_enabled(env)) {
4850 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4851 			proof = bpf_diag_fmt(
4852 				env, "the minimal bound for a memory access is a negative value: %s",
4853 				start);
4854 		}
4855 		goto report_error;
4856 	}
4857 
4858 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4859 				 mem_size, zero_size_allowed);
4860 	if (err) {
4861 		verbose(env, "%s min value is outside of the allowed memory range\n",
4862 			reg_arg_name(env, argno));
4863 		if (bpf_diag_enabled(env)) {
4864 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4865 			proof = bpf_diag_fmt(
4866 				env, "the minimal bound for a memory access is %s and is outside of the object of size %u",
4867 				start, mem_size);
4868 		}
4869 		goto report_error;
4870 	}
4871 
4872 	/* If we haven't set a max value then we need to bail since we can't be
4873 	 * sure we won't do bad things.
4874 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4875 	 */
4876 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4877 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4878 			reg_arg_name(env, argno));
4879 		err = -EACCES;
4880 		if (bpf_diag_enabled(env))
4881 			proof = bpf_diag_fmt(
4882 				env, "the maximal bound for a memory access is %llu and exceeds maximum allowed offset of %u",
4883 				reg_umax(reg), BPF_MAX_VAR_OFF);
4884 		goto report_error;
4885 	}
4886 
4887 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4888 				 mem_size, zero_size_allowed);
4889 	if (err) {
4890 		verbose(env, "%s max value is outside of the allowed memory range\n",
4891 			reg_arg_name(env, argno));
4892 		if (bpf_diag_enabled(env)) {
4893 			max_start = (s64)reg_umax(reg) + off;
4894 			max_end = max_start + size;
4895 			proof = bpf_diag_fmt(
4896 				env, "the maximal bound for a memory access is %lld: start %lld + access_size %d, beyond object_size %u",
4897 				max_end, max_start, size, mem_size);
4898 		}
4899 		goto report_error;
4900 	}
4901 
4902 	return 0;
4903 
4904 report_error:
4905 	bpf_diag_mem_bounds(env, env->insn_idx, reg_from_argno(argno),
4906 			    reg_arg_name(env, argno), reg_type_str(env, reg->type), proof,
4907 			    off, size, mem_size, reg);
4908 	return err;
4909 }
4910 
4911 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4912 			       const struct bpf_reg_state *reg, argno_t argno,
4913 			       bool fixed_off_ok)
4914 {
4915 	/* Access to this pointer-typed register or passing it to a helper
4916 	 * is only allowed in its original, unmodified form.
4917 	 */
4918 
4919 	if (!tnum_is_const(reg->var_off)) {
4920 		char tn_buf[48];
4921 
4922 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4923 		verbose(env, "variable %s access var_off=%s disallowed\n",
4924 			reg_type_str(env, reg->type), tn_buf);
4925 		return -EACCES;
4926 	}
4927 
4928 	if (reg_smin(reg) < 0) {
4929 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4930 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4931 		return -EACCES;
4932 	}
4933 
4934 	if (!fixed_off_ok && reg->var_off.value != 0) {
4935 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4936 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4937 		bpf_diag_invalid_deref(env, env->insn_idx, reg_from_argno(argno),
4938 				       reg_arg_name(env, argno), reg,
4939 					      BPF_DIAG_DEREF_MODIFIED_PTR, reg->var_off.value);
4940 		return -EACCES;
4941 	}
4942 
4943 	return 0;
4944 }
4945 
4946 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4947 		             const struct bpf_reg_state *reg, int regno)
4948 {
4949 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4950 }
4951 
4952 static int map_kptr_match_type(struct bpf_verifier_env *env,
4953 			       struct btf_field *kptr_field,
4954 			       struct bpf_reg_state *reg, u32 regno)
4955 {
4956 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4957 	int perm_flags;
4958 	const char *reg_name = "";
4959 
4960 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4961 		goto bad_type;
4962 
4963 	if (btf_is_kernel(reg->btf)) {
4964 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4965 
4966 		/* Only unreferenced case accepts untrusted pointers */
4967 		if (kptr_field->type == BPF_KPTR_UNREF)
4968 			perm_flags |= PTR_UNTRUSTED;
4969 	} else {
4970 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4971 		if (kptr_field->type == BPF_KPTR_PERCPU)
4972 			perm_flags |= MEM_PERCPU;
4973 	}
4974 
4975 	if (type_flag(reg->type) & ~perm_flags)
4976 		goto bad_type;
4977 
4978 	/*
4979 	 * A BPF_KPTR_PERCPU field is read back as MEM_PERCPU, so the value
4980 	 * stored in it must carry the same flag.
4981 	 */
4982 	if ((kptr_field->type == BPF_KPTR_PERCPU) != !!(reg->type & MEM_PERCPU))
4983 		goto bad_type;
4984 
4985 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4986 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4987 
4988 	/* For ref_ptr case, release function check should ensure we get one
4989 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4990 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4991 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4992 	 * reg->id is not needed here.
4993 	 */
4994 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4995 		return -EACCES;
4996 
4997 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4998 	 * we also need to take into account the reg->var_off.
4999 	 *
5000 	 * We want to support cases like:
5001 	 *
5002 	 * struct foo {
5003 	 *         struct bar br;
5004 	 *         struct baz bz;
5005 	 * };
5006 	 *
5007 	 * struct foo *v;
5008 	 * v = func();	      // PTR_TO_BTF_ID
5009 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
5010 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
5011 	 *                    // first member type of struct after comparison fails
5012 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
5013 	 *                    // to match type
5014 	 *
5015 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
5016 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5017 	 * the struct to match type against first member of struct, i.e. reject
5018 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5019 	 * strict mode to true for type match.
5020 	 */
5021 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
5022 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5023 				  kptr_field->type != BPF_KPTR_UNREF,
5024 				  !type_is_alloc(reg->type)))
5025 		goto bad_type;
5026 	return 0;
5027 bad_type:
5028 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5029 		reg_type_str(env, reg->type), reg_name);
5030 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5031 	if (kptr_field->type == BPF_KPTR_UNREF)
5032 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5033 			targ_name);
5034 	else
5035 		verbose(env, "\n");
5036 	return -EINVAL;
5037 }
5038 
5039 static bool in_sleepable(struct bpf_verifier_env *env)
5040 {
5041 	return env->cur_state->in_sleepable;
5042 }
5043 
5044 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5045  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5046  */
5047 static bool in_rcu_cs(struct bpf_verifier_env *env)
5048 {
5049 	return env->cur_state->active_rcu_locks ||
5050 	       env->cur_state->active_preempt_locks ||
5051 	       env->cur_state->active_locks ||
5052 	       env->cur_state->active_irq_id ||
5053 	       !in_sleepable(env);
5054 }
5055 
5056 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5057 BTF_SET_START(rcu_protected_types)
5058 #ifdef CONFIG_NET
5059 BTF_ID(struct, prog_test_ref_kfunc)
5060 #endif
5061 #ifdef CONFIG_CGROUPS
5062 BTF_ID(struct, cgroup)
5063 #endif
5064 #ifdef CONFIG_BPF_JIT
5065 BTF_ID(struct, bpf_cpumask)
5066 #endif
5067 BTF_ID(struct, task_struct)
5068 #ifdef CONFIG_BPF_CRYPTO
5069 BTF_ID(struct, bpf_crypto_ctx)
5070 #endif
5071 #ifdef CONFIG_INET
5072 BTF_ID(struct, bpf_ksock)
5073 #endif
5074 BTF_SET_END(rcu_protected_types)
5075 
5076 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5077 {
5078 	if (!btf_is_kernel(btf))
5079 		return true;
5080 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5081 }
5082 
5083 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5084 {
5085 	struct btf_struct_meta *meta;
5086 
5087 	if (btf_is_kernel(kptr_field->kptr.btf))
5088 		return NULL;
5089 
5090 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5091 				    kptr_field->kptr.btf_id);
5092 
5093 	return meta ? meta->record : NULL;
5094 }
5095 
5096 static bool rcu_safe_kptr(const struct btf_field *field)
5097 {
5098 	const struct btf_field_kptr *kptr = &field->kptr;
5099 
5100 	return field->type == BPF_KPTR_PERCPU ||
5101 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5102 }
5103 
5104 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5105 {
5106 	struct btf_record *rec;
5107 	u32 ret;
5108 
5109 	ret = PTR_MAYBE_NULL;
5110 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5111 		ret |= MEM_RCU;
5112 		if (kptr_field->type == BPF_KPTR_PERCPU)
5113 			ret |= MEM_PERCPU;
5114 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5115 			ret |= MEM_ALLOC;
5116 
5117 		rec = kptr_pointee_btf_record(kptr_field);
5118 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5119 			ret |= NON_OWN_REF;
5120 	} else {
5121 		ret |= PTR_UNTRUSTED;
5122 	}
5123 
5124 	return ret;
5125 }
5126 
5127 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5128 			    struct btf_field *field)
5129 {
5130 	struct bpf_reg_state *reg;
5131 	const struct btf_type *t;
5132 
5133 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5134 	mark_reg_known_zero(env, cur_regs(env), regno);
5135 	reg = reg_state(env, regno);
5136 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5137 	reg->mem_size = t->size;
5138 	reg->id = ++env->id_gen;
5139 
5140 	return 0;
5141 }
5142 
5143 static int check_map_kptr_access(struct bpf_verifier_env *env,
5144 				 int value_regno, int insn_idx,
5145 				 struct btf_field *kptr_field)
5146 {
5147 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5148 	int class = BPF_CLASS(insn->code);
5149 	struct bpf_reg_state *val_reg;
5150 	int ret;
5151 
5152 	/* Things we already checked for in check_map_access and caller:
5153 	 *  - Reject cases where variable offset may touch kptr
5154 	 *  - size of access (must be BPF_DW)
5155 	 *  - tnum_is_const(reg->var_off)
5156 	 *  - kptr_field->offset == off + reg->var_off.value
5157 	 */
5158 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5159 	if (BPF_MODE(insn->code) != BPF_MEM) {
5160 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5161 		return -EACCES;
5162 	}
5163 
5164 	/* We only allow loading referenced kptr, since it will be marked as
5165 	 * untrusted, similar to unreferenced kptr.
5166 	 */
5167 	if (class != BPF_LDX &&
5168 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5169 		verbose(env, "store to referenced kptr disallowed\n");
5170 		return -EACCES;
5171 	}
5172 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5173 		verbose(env, "store to uptr disallowed\n");
5174 		return -EACCES;
5175 	}
5176 
5177 	if (class == BPF_LDX) {
5178 		if (kptr_field->type == BPF_UPTR)
5179 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5180 
5181 		/* We can simply mark the value_regno receiving the pointer
5182 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5183 		 */
5184 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5185 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5186 				      btf_ld_kptr_type(env, kptr_field));
5187 		if (ret < 0)
5188 			return ret;
5189 	} else if (class == BPF_STX) {
5190 		val_reg = reg_state(env, value_regno);
5191 		if (bpf_register_is_null(val_reg)) {
5192 			/*
5193 			 * This store is valid only because the scalar is known to be
5194 			 * zero. Mark it precise so another scalar cannot be pruned
5195 			 * against this state.
5196 			 */
5197 			return mark_chain_precision(env, value_regno);
5198 		}
5199 		if (map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5200 			return -EACCES;
5201 	} else if (class == BPF_ST) {
5202 		if (insn->imm) {
5203 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5204 				kptr_field->offset);
5205 			return -EACCES;
5206 		}
5207 	} else {
5208 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5209 		return -EACCES;
5210 	}
5211 	return 0;
5212 }
5213 
5214 /*
5215  * Return the size of the memory region accessible from a pointer to map value.
5216  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
5217  */
5218 static u32 map_mem_size(const struct bpf_map *map)
5219 {
5220 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5221 		return map->max_entries * sizeof(long);
5222 
5223 	return map->value_size;
5224 }
5225 
5226 /* check read/write into a map element with possible variable offset */
5227 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
5228 			    int off, int size, bool zero_size_allowed,
5229 			    enum bpf_access_src src)
5230 {
5231 	struct bpf_map *map = reg->map_ptr;
5232 	u32 mem_size = map_mem_size(map);
5233 	struct btf_record *rec;
5234 	int err, i;
5235 
5236 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
5237 	if (err)
5238 		return err;
5239 
5240 	if (IS_ERR_OR_NULL(map->record))
5241 		return 0;
5242 	rec = map->record;
5243 	for (i = 0; i < rec->cnt; i++) {
5244 		struct btf_field *field = &rec->fields[i];
5245 		u32 p = field->offset;
5246 
5247 		/* If any part of a field  can be touched by load/store, reject
5248 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5249 		 * it is sufficient to check x1 < y2 && y1 < x2.
5250 		 */
5251 		if (reg_smin(reg) + off < p + field->size &&
5252 		    p < reg_umax(reg) + off + size) {
5253 			switch (field->type) {
5254 			case BPF_KPTR_UNREF:
5255 			case BPF_KPTR_REF:
5256 			case BPF_KPTR_PERCPU:
5257 			case BPF_UPTR:
5258 				if (src != ACCESS_DIRECT) {
5259 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5260 						btf_field_type_name(field->type));
5261 					return -EACCES;
5262 				}
5263 				if (!tnum_is_const(reg->var_off)) {
5264 					verbose(env, "%s access cannot have variable offset\n",
5265 						btf_field_type_name(field->type));
5266 					return -EACCES;
5267 				}
5268 				if (p != off + reg->var_off.value) {
5269 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5270 						btf_field_type_name(field->type),
5271 						p, off + reg->var_off.value);
5272 					return -EACCES;
5273 				}
5274 				if (size != bpf_size_to_bytes(BPF_DW)) {
5275 					verbose(env, "%s access size must be BPF_DW\n",
5276 						btf_field_type_name(field->type));
5277 					return -EACCES;
5278 				}
5279 				break;
5280 			default:
5281 				verbose(env, "%s cannot be accessed directly by load/store\n",
5282 					btf_field_type_name(field->type));
5283 				return -EACCES;
5284 			}
5285 		}
5286 	}
5287 	return 0;
5288 }
5289 
5290 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5291 			       const struct bpf_call_arg_meta *meta,
5292 			       enum bpf_access_type t)
5293 {
5294 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5295 
5296 	switch (prog_type) {
5297 	/* Program types only with direct read access go here! */
5298 	case BPF_PROG_TYPE_LWT_IN:
5299 	case BPF_PROG_TYPE_LWT_OUT:
5300 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5301 	case BPF_PROG_TYPE_SK_REUSEPORT:
5302 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5303 	case BPF_PROG_TYPE_CGROUP_SKB:
5304 		if (t == BPF_WRITE)
5305 			return false;
5306 		fallthrough;
5307 
5308 	/* Program types with direct read + write access go here! */
5309 	case BPF_PROG_TYPE_SCHED_CLS:
5310 	case BPF_PROG_TYPE_SCHED_ACT:
5311 	case BPF_PROG_TYPE_XDP:
5312 	case BPF_PROG_TYPE_LWT_XMIT:
5313 	case BPF_PROG_TYPE_SK_SKB:
5314 	case BPF_PROG_TYPE_SK_MSG:
5315 		if (meta && !meta->btf && meta->func_id)
5316 			return meta->fn->pkt_access;
5317 
5318 		if (t == BPF_WRITE)
5319 			env->seen_direct_write = true;
5320 		return true;
5321 
5322 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5323 		if (t == BPF_WRITE)
5324 			env->seen_direct_write = true;
5325 
5326 		return true;
5327 
5328 	default:
5329 		return false;
5330 	}
5331 }
5332 
5333 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
5334 			       int size, bool zero_size_allowed)
5335 {
5336 	int err;
5337 
5338 	if (reg->range < 0) {
5339 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
5340 		return -EINVAL;
5341 	}
5342 
5343 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
5344 	if (err)
5345 		return err;
5346 
5347 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5348 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
5349 	 * otherwise find_good_pkt_pointers would have refused to set range info
5350 	 * that __check_mem_access would have rejected this pkt access.
5351 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
5352 	 */
5353 	env->prog->aux->max_pkt_offset =
5354 		max_t(u32, env->prog->aux->max_pkt_offset,
5355 		      off + reg_umax(reg) + size - 1);
5356 
5357 	return 0;
5358 }
5359 
5360 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
5361 {
5362 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
5363 }
5364 
5365 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5366 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5367 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
5368 {
5369 	if (env->ops->is_valid_access &&
5370 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
5371 		/* A non zero info.ctx_field_size indicates that this field is a
5372 		 * candidate for later verifier transformation to load the whole
5373 		 * field and then apply a mask when accessed with a narrower
5374 		 * access than actual ctx access size. A zero info.ctx_field_size
5375 		 * will only allow for whole field access and rejects any other
5376 		 * type of narrower access.
5377 		 */
5378 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
5379 			if (info->ref_id &&
5380 			    !find_reference_state(env->cur_state, info->ref_id)) {
5381 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
5382 					off);
5383 				return -EACCES;
5384 			}
5385 		} else {
5386 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
5387 		}
5388 		/* remember the offset of last byte accessed in ctx */
5389 		if (env->prog->aux->max_ctx_offset < off + size)
5390 			env->prog->aux->max_ctx_offset = off + size;
5391 		return 0;
5392 	}
5393 
5394 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5395 	return -EACCES;
5396 }
5397 
5398 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
5399 			    int off, int access_size, enum bpf_access_type t,
5400 			    struct bpf_insn_access_aux *info)
5401 {
5402 	/*
5403 	 * Program types that don't rewrite ctx accesses can safely
5404 	 * dereference ctx pointers with fixed offsets.
5405 	 */
5406 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
5407 	bool fixed_off_ok = !env->ops->convert_ctx_access;
5408 	int err;
5409 
5410 	if (var_off_ok)
5411 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
5412 	else
5413 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
5414 	if (err)
5415 		return err;
5416 	off += reg_umax(reg);
5417 
5418 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
5419 	if (err)
5420 		verbose_linfo(env, insn_idx, "; ");
5421 	return err;
5422 }
5423 
5424 static int check_flow_keys_access(struct bpf_verifier_env *env,
5425 				  struct bpf_reg_state *reg, argno_t argno,
5426 				  int off, int size)
5427 {
5428 	/* Only a constant offset is allowed here; fold it into off. */
5429 	if (!tnum_is_const(reg->var_off)) {
5430 		char tn_buf[48];
5431 
5432 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5433 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
5434 			reg_arg_name(env, argno), off, tn_buf);
5435 		return -EACCES;
5436 	}
5437 	off += reg->var_off.value;
5438 
5439 	if (size < 0 || off < 0 ||
5440 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5441 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5442 			off, size);
5443 		return -EACCES;
5444 	}
5445 	return 0;
5446 }
5447 
5448 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5449 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
5450 			     enum bpf_access_type t)
5451 {
5452 	struct bpf_insn_access_aux info = {};
5453 	bool valid;
5454 
5455 	if (reg_smin(reg) < 0) {
5456 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5457 			reg_arg_name(env, argno));
5458 		return -EACCES;
5459 	}
5460 
5461 	switch (reg->type) {
5462 	case PTR_TO_SOCK_COMMON:
5463 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5464 		break;
5465 	case PTR_TO_SOCKET:
5466 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5467 		break;
5468 	case PTR_TO_TCP_SOCK:
5469 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5470 		break;
5471 	case PTR_TO_XDP_SOCK:
5472 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5473 		break;
5474 	default:
5475 		valid = false;
5476 	}
5477 
5478 	if (valid) {
5479 		env->insn_aux_data[insn_idx].ctx_field_size =
5480 			info.ctx_field_size;
5481 		return 0;
5482 	}
5483 
5484 	verbose(env, "%s invalid %s access off=%d size=%d\n",
5485 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
5486 
5487 	return -EACCES;
5488 }
5489 
5490 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5491 {
5492 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5493 }
5494 
5495 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5496 {
5497 	const struct bpf_reg_state *reg = reg_state(env, regno);
5498 
5499 	return reg->type == PTR_TO_CTX;
5500 }
5501 
5502 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5503 {
5504 	const struct bpf_reg_state *reg = reg_state(env, regno);
5505 
5506 	return type_is_sk_pointer(reg->type);
5507 }
5508 
5509 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5510 {
5511 	const struct bpf_reg_state *reg = reg_state(env, regno);
5512 
5513 	return type_is_pkt_pointer(reg->type);
5514 }
5515 
5516 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5517 {
5518 	const struct bpf_reg_state *reg = reg_state(env, regno);
5519 
5520 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5521 	return reg->type == PTR_TO_FLOW_KEYS;
5522 }
5523 
5524 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5525 {
5526 	const struct bpf_reg_state *reg = reg_state(env, regno);
5527 
5528 	return reg->type == PTR_TO_ARENA;
5529 }
5530 
5531 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno,
5532 			       struct bpf_insn *insn)
5533 {
5534 	const struct bpf_reg_state *reg = reg_state(env, regno);
5535 
5536 	/*
5537 	 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the
5538 	 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load
5539 	 * with no exception table entry, so a fault (e.g. NULL deref) crashes
5540 	 * the kernel instead of being handled. Reject the source pointer types
5541 	 * that would have needed that protection, the remaining ones stay
5542 	 * allowed.
5543 	 */
5544 	return insn->imm == BPF_LOAD_ACQ && bpf_may_fault_on_deref(reg->type);
5545 }
5546 
5547 /* Return false if @regno contains a pointer whose type isn't supported for
5548  * atomic instruction @insn.
5549  */
5550 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
5551 			       struct bpf_insn *insn)
5552 {
5553 	if (is_ctx_reg(env, regno))
5554 		return false;
5555 	if (is_pkt_reg(env, regno))
5556 		return false;
5557 	if (is_flow_key_reg(env, regno))
5558 		return false;
5559 	if (is_sk_reg(env, regno))
5560 		return false;
5561 	if (is_arena_reg(env, regno))
5562 		return bpf_jit_supports_insn(insn, true);
5563 	if (is_load_acq_unsafe(env, regno, insn))
5564 		return false;
5565 	return true;
5566 }
5567 
5568 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5569 #ifdef CONFIG_NET
5570 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5571 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5572 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5573 #endif
5574 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5575 };
5576 
5577 static bool is_trusted_reg_type(struct bpf_verifier_env *env,
5578 				const struct bpf_reg_state *reg,
5579 				enum bpf_reg_type type)
5580 {
5581 	/* A referenced register is always trusted. */
5582 	if (reg_is_referenced(env, reg))
5583 		return true;
5584 
5585 	/* Types listed in the reg2btf_ids are always trusted */
5586 	if (reg2btf_ids[base_type(type)] &&
5587 	    !bpf_type_has_unsafe_modifiers(type))
5588 		return true;
5589 
5590 	/* If a register is not referenced, it is trusted if it has the
5591 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5592 	 * other type modifiers may be safe, but we elect to take an opt-in
5593 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5594 	 * not.
5595 	 *
5596 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5597 	 * for whether a register is trusted.
5598 	 */
5599 	return type_flag(type) & BPF_REG_TRUSTED_MODIFIERS &&
5600 	       !bpf_type_has_unsafe_modifiers(type);
5601 }
5602 
5603 static bool is_trusted_reg(struct bpf_verifier_env *env,
5604 			   const struct bpf_reg_state *reg)
5605 {
5606 	return is_trusted_reg_type(env, reg, reg->type);
5607 }
5608 
5609 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5610 {
5611 	return reg->type & MEM_RCU;
5612 }
5613 
5614 static void clear_trusted_flags(enum bpf_type_flag *flag)
5615 {
5616 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5617 }
5618 
5619 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5620 				   const struct bpf_reg_state *reg,
5621 				   int off, int size, bool strict)
5622 {
5623 	struct tnum reg_off;
5624 	int ip_align;
5625 
5626 	/* Byte size accesses are always allowed. */
5627 	if (!strict || size == 1)
5628 		return 0;
5629 
5630 	/* For platforms that do not have a Kconfig enabling
5631 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5632 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5633 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5634 	 * to this code only in strict mode where we want to emulate
5635 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5636 	 * unconditional IP align value of '2'.
5637 	 */
5638 	ip_align = 2;
5639 
5640 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
5641 	if (!tnum_is_aligned(reg_off, size)) {
5642 		char tn_buf[48];
5643 
5644 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5645 		verbose(env,
5646 			"misaligned packet access off %d+%s+%d size %d\n",
5647 			ip_align, tn_buf, off, size);
5648 		return -EACCES;
5649 	}
5650 
5651 	return 0;
5652 }
5653 
5654 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5655 				       const struct bpf_reg_state *reg,
5656 				       const char *pointer_desc,
5657 				       int off, int size, bool strict)
5658 {
5659 	struct tnum reg_off;
5660 
5661 	/* Byte size accesses are always allowed. */
5662 	if (!strict || size == 1)
5663 		return 0;
5664 
5665 	reg_off = tnum_add(reg->var_off, tnum_const(off));
5666 	if (!tnum_is_aligned(reg_off, size)) {
5667 		char tn_buf[48];
5668 
5669 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5670 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
5671 			pointer_desc, tn_buf, off, size);
5672 		return -EACCES;
5673 	}
5674 
5675 	return 0;
5676 }
5677 
5678 static int check_ptr_alignment(struct bpf_verifier_env *env,
5679 			       const struct bpf_reg_state *reg, int off,
5680 			       int size, bool strict_alignment_once)
5681 {
5682 	bool strict = env->strict_alignment || strict_alignment_once;
5683 	const char *pointer_desc = "";
5684 
5685 	switch (reg->type) {
5686 	case PTR_TO_PACKET:
5687 	case PTR_TO_PACKET_META:
5688 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5689 		 * right in front, treat it the very same way.
5690 		 */
5691 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5692 	case PTR_TO_FLOW_KEYS:
5693 		pointer_desc = "flow keys ";
5694 		break;
5695 	case PTR_TO_MAP_KEY:
5696 		pointer_desc = "key ";
5697 		break;
5698 	case PTR_TO_MAP_VALUE:
5699 		pointer_desc = "value ";
5700 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5701 			strict = true;
5702 		break;
5703 	case PTR_TO_CTX:
5704 		pointer_desc = "context ";
5705 		break;
5706 	case PTR_TO_STACK:
5707 		pointer_desc = "stack ";
5708 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5709 		 * and check_stack_read_fixed_off() relies on stack accesses being
5710 		 * aligned.
5711 		 */
5712 		strict = true;
5713 		break;
5714 	case PTR_TO_SOCKET:
5715 		pointer_desc = "sock ";
5716 		break;
5717 	case PTR_TO_SOCK_COMMON:
5718 		pointer_desc = "sock_common ";
5719 		break;
5720 	case PTR_TO_TCP_SOCK:
5721 		pointer_desc = "tcp_sock ";
5722 		break;
5723 	case PTR_TO_XDP_SOCK:
5724 		pointer_desc = "xdp_sock ";
5725 		break;
5726 	case PTR_TO_ARENA:
5727 		return 0;
5728 	default:
5729 		break;
5730 	}
5731 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5732 					   strict);
5733 }
5734 
5735 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5736 {
5737 	if (!bpf_jit_supports_private_stack())
5738 		return NO_PRIV_STACK;
5739 
5740 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5741 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5742 	 * explicitly.
5743 	 */
5744 	switch (prog->type) {
5745 	case BPF_PROG_TYPE_KPROBE:
5746 	case BPF_PROG_TYPE_TRACEPOINT:
5747 	case BPF_PROG_TYPE_PERF_EVENT:
5748 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5749 		return PRIV_STACK_ADAPTIVE;
5750 	case BPF_PROG_TYPE_TRACING:
5751 	case BPF_PROG_TYPE_LSM:
5752 	case BPF_PROG_TYPE_STRUCT_OPS:
5753 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5754 			return PRIV_STACK_ADAPTIVE;
5755 		fallthrough;
5756 	default:
5757 		break;
5758 	}
5759 
5760 	return NO_PRIV_STACK;
5761 }
5762 
5763 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5764 {
5765 	if (env->prog->jit_requested)
5766 		return round_up(stack_depth, 16);
5767 
5768 	/* round up to 32-bytes, since this is granularity
5769 	 * of interpreter stack size
5770 	 */
5771 	return round_up(max_t(u32, stack_depth, 1), 32);
5772 }
5773 
5774 /* temporary state used for call frame depth calculation */
5775 struct bpf_subprog_call_depth_info {
5776 	int ret_insn; /* caller instruction where we return to. */
5777 	int caller; /* caller subprogram idx */
5778 	int frame; /* # of consecutive static call stack frames on top of stack */
5779 	int callx_insn; /* callx instruction whose callees are being walked */
5780 	int callx_next; /* next callee of callx_insn to walk */
5781 	bool via_callx; /* the subprogram is entered via callx */
5782 };
5783 
5784 /* starting from main bpf function walk all instructions of the function
5785  * and recursively walk all callees that given function can call.
5786  * Ignore jump and exit insns.
5787  */
5788 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5789 					 struct bpf_subprog_call_depth_info *dinfo,
5790 					 bool priv_stack_supported)
5791 {
5792 	struct bpf_subprog_info *subprog = env->subprog_info;
5793 	struct bpf_insn *insn = env->prog->insnsi;
5794 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5795 	bool tail_call_reachable = false;
5796 	int total;
5797 	int tmp;
5798 
5799 	/* no caller idx */
5800 	dinfo[idx].caller = -1;
5801 	dinfo[idx].via_callx = false;
5802 
5803 	i = subprog[idx].start;
5804 	if (!priv_stack_supported)
5805 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5806 process_func:
5807 	dinfo[idx].callx_insn = -1;
5808 	if (subprog[idx].has_ld_abs) {
5809 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5810 			if (subprog[tmp].is_cb) {
5811 				verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
5812 				return -EINVAL;
5813 			}
5814 		}
5815 	}
5816 
5817 	/* protect against potential stack overflow that might happen when
5818 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5819 	 * depth for such case down to 256 so that the worst case scenario
5820 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5821 	 * 8k).
5822 	 *
5823 	 * To get the idea what might happen, see an example:
5824 	 * func1 -> sub rsp, 128
5825 	 *  subfunc1 -> sub rsp, 256
5826 	 *  tailcall1 -> add rsp, 256
5827 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5828 	 *   subfunc2 -> sub rsp, 64
5829 	 *   subfunc22 -> sub rsp, 128
5830 	 *   tailcall2 -> add rsp, 128
5831 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5832 	 *
5833 	 * tailcall will unwind the current stack frame but it will not get rid
5834 	 * of caller's stack as shown on the example above.
5835 	 */
5836 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5837 		verbose(env,
5838 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5839 			depth);
5840 		return -EACCES;
5841 	}
5842 
5843 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5844 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5845 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5846 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5847 	} else if (priv_stack_supported) {
5848 		/* Request private stack support only if the subprog stack
5849 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5850 		 * avoid jit penalty if the stack usage is small.
5851 		 */
5852 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5853 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5854 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5855 	}
5856 
5857 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5858 		if (subprog_depth > env->max_stack_depth)
5859 			env->max_stack_depth = subprog_depth;
5860 		if (subprog_depth > env->stack_limit) {
5861 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5862 				idx, subprog_depth);
5863 			return -EACCES;
5864 		}
5865 	} else {
5866 		depth += subprog_depth;
5867 		if (depth > env->max_stack_depth)
5868 			env->max_stack_depth = depth;
5869 		if (depth > env->stack_limit) {
5870 			total = 0;
5871 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5872 				total++;
5873 
5874 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5875 				total, depth);
5876 			return -EACCES;
5877 		}
5878 	}
5879 continue_func:
5880 	subprog_end = subprog[idx + 1].start;
5881 	for (; i < subprog_end; i++) {
5882 		int next_insn, sidx;
5883 
5884 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off &&
5885 		    bpf_is_throw_kfunc(insn + i)) {
5886 			bool err = false;
5887 
5888 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5889 				if (subprog[tmp].is_cb) {
5890 					err = true;
5891 					break;
5892 				}
5893 			}
5894 			if (!err)
5895 				continue;
5896 			verbose(env,
5897 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5898 				i, idx);
5899 			return -EINVAL;
5900 		}
5901 
5902 		if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i)) {
5903 			/*
5904 			 * Walk the callees and the callbacks recorded by
5905 			 * the main verification pass one by one, returning to
5906 			 * this insn after each.
5907 			 */
5908 			if (dinfo[idx].callx_insn != i) {
5909 				dinfo[idx].callx_insn = i;
5910 				dinfo[idx].callx_next = 0;
5911 			}
5912 			sidx = next_callx_callee(env, idx, dinfo[idx].callx_next);
5913 			if (sidx < 0)
5914 				continue;
5915 			dinfo[idx].callx_next = sidx + 1;
5916 			dinfo[idx].ret_insn = i;
5917 			next_insn = subprog[sidx].start;
5918 		} else if (bpf_pseudo_call(insn + i) || bpf_pseudo_func(insn + i)) {
5919 			/* find the callee */
5920 			next_insn = i + insn[i].imm + 1;
5921 			sidx = bpf_find_subprog(env, next_insn);
5922 			if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5923 				return -EFAULT;
5924 			if (subprog[sidx].is_async_cb) {
5925 				/* async callbacks don't increase bpf prog stack size unless called directly */
5926 				if (!bpf_pseudo_call(insn + i))
5927 					continue;
5928 				if (subprog[sidx].is_exception_cb) {
5929 					verbose(env, "insn %d cannot call exception cb directly", i);
5930 					return -EINVAL;
5931 				}
5932 			}
5933 			/* remember insn to return to */
5934 			dinfo[idx].ret_insn = i + 1;
5935 		} else {
5936 			continue;
5937 		}
5938 
5939 		/*
5940 		 * sort_subprogs_topo() tolerates cycles in the call graph that
5941 		 * go through the address of a function being taken, since it
5942 		 * doesn't know what it is taken for. Such cycle is a recursion
5943 		 * unless it's an async callback, which are skipped above.
5944 		 * The main verification pass limits the depth of the recursion,
5945 		 * but it doesn't follow calls of global functions.
5946 		 */
5947 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5948 			if (tmp != sidx)
5949 				continue;
5950 			verbose(env, "recursive call from %s() to %s()\n",
5951 				bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx));
5952 			bpf_diag_program_structure(
5953 				env, i, "recursive subprogram call",
5954 				"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
5955 				"This call or callback would make the subprogram call graph recursive. "
5956 				"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
5957 			return -EINVAL;
5958 		}
5959 
5960 		/* store caller info for after we return from callee */
5961 		dinfo[idx].frame = frame;
5962 
5963 		/* push caller idx into callee's dinfo */
5964 		dinfo[sidx].caller = idx;
5965 		dinfo[sidx].via_callx = bpf_is_callx(insn + i);
5966 
5967 		i = next_insn;
5968 
5969 		idx = sidx;
5970 		if (!priv_stack_supported)
5971 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5972 
5973 		/* sync tail_call_reachable with callee state on entry */
5974 		tail_call_reachable = subprog[idx].has_tail_call;
5975 
5976 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5977 		if (frame >= MAX_CALL_FRAMES) {
5978 			verbose(env, "the call stack of %d frames is too deep !\n",
5979 				frame);
5980 			return -E2BIG;
5981 		}
5982 		goto process_func;
5983 	}
5984 	/* if tail call got detected across bpf2bpf calls then mark each of the
5985 	 * currently present subprog frames as tail call reachable subprogs;
5986 	 * this info will be utilized by JIT so that we will be preserving the
5987 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5988 	 */
5989 	if (tail_call_reachable) {
5990 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5991 			if (subprog[tmp].is_cb) {
5992 				verbose(env, "cannot tail call within callback\n");
5993 				return -EINVAL;
5994 			}
5995 			if (subprog[tmp].stack_arg_cnt) {
5996 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5997 				return -EINVAL;
5998 			}
5999 			/*
6000 			 * JITs pass tail call counter in a register that is
6001 			 * not available when the callee is called via callx.
6002 			 */
6003 			if (dinfo[tmp].via_callx) {
6004 				verbose(env, "tail_calls are not allowed in functions called via callx\n");
6005 				return -EINVAL;
6006 			}
6007 			subprog[tmp].tail_call_reachable = true;
6008 		}
6009 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
6010 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
6011 		return -EINVAL;
6012 	}
6013 
6014 	if (subprog[0].tail_call_reachable)
6015 		env->prog->aux->tail_call_reachable = true;
6016 
6017 	/* end of for() loop means the last insn of the 'subprog'
6018 	 * was reached. Doesn't matter whether it was JA or EXIT
6019 	 */
6020 	if (frame == 0 && dinfo[idx].caller < 0)
6021 		return 0;
6022 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6023 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6024 
6025 	/* pop caller idx from callee */
6026 	idx = dinfo[idx].caller;
6027 
6028 	/* retrieve caller state from its frame */
6029 	frame = dinfo[idx].frame;
6030 	i = dinfo[idx].ret_insn;
6031 
6032 	/* reset tail_call_reachable to the parent's actual state */
6033 	tail_call_reachable = subprog[idx].tail_call_reachable;
6034 
6035 	goto continue_func;
6036 }
6037 
6038 static int check_max_stack_depth(struct bpf_verifier_env *env)
6039 {
6040 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6041 	struct bpf_subprog_call_depth_info *dinfo;
6042 	struct bpf_subprog_info *si = env->subprog_info;
6043 	bool priv_stack_supported;
6044 	int ret;
6045 
6046 	dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
6047 	if (!dinfo)
6048 		return -ENOMEM;
6049 
6050 	for (int i = 0; i < env->subprog_cnt; i++) {
6051 		if (si[i].has_tail_call) {
6052 			priv_stack_mode = NO_PRIV_STACK;
6053 			break;
6054 		}
6055 	}
6056 
6057 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6058 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6059 
6060 	/* All async_cb subprogs use normal kernel stack. If a particular
6061 	 * subprog appears in both main prog and async_cb subtree, that
6062 	 * subprog will use normal kernel stack to avoid potential nesting.
6063 	 * The reverse subprog traversal ensures when main prog subtree is
6064 	 * checked, the subprogs appearing in async_cb subtrees are already
6065 	 * marked as using normal kernel stack, so stack size checking can
6066 	 * be done properly.
6067 	 */
6068 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6069 		if (!i || si[i].is_async_cb) {
6070 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6071 			ret = check_max_stack_depth_subprog(env, i, dinfo,
6072 					priv_stack_supported);
6073 			if (ret < 0) {
6074 				kvfree(dinfo);
6075 				return ret;
6076 			}
6077 		}
6078 	}
6079 
6080 	for (int i = 0; i < env->subprog_cnt; i++) {
6081 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6082 			env->prog->aux->jits_use_priv_stack = true;
6083 			break;
6084 		}
6085 	}
6086 
6087 	kvfree(dinfo);
6088 
6089 	return 0;
6090 }
6091 
6092 static int __check_buffer_access(struct bpf_verifier_env *env,
6093 				 const char *buf_info,
6094 				 const struct bpf_reg_state *reg,
6095 				 argno_t argno, int off, int size,
6096 				 u32 *access_end)
6097 {
6098 	s64 start;
6099 
6100 	if (!tnum_is_const(reg->var_off)) {
6101 		char tn_buf[48];
6102 
6103 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6104 		verbose(env,
6105 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
6106 			reg_arg_name(env, argno), off, tn_buf);
6107 		return -EACCES;
6108 	}
6109 
6110 	start = (s64)reg->var_off.value + off;
6111 	if (start < 0) {
6112 		verbose(env,
6113 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
6114 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
6115 		return -EACCES;
6116 	}
6117 
6118 	*access_end = start + size;
6119 	return 0;
6120 }
6121 
6122 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6123 				  const struct bpf_reg_state *reg,
6124 				  argno_t argno, int off, int size)
6125 {
6126 	u32 access_end;
6127 	int err;
6128 
6129 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
6130 	if (err)
6131 		return err;
6132 
6133 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
6134 
6135 	return 0;
6136 }
6137 
6138 static int check_buffer_access(struct bpf_verifier_env *env,
6139 			       const struct bpf_reg_state *reg,
6140 			       argno_t argno, int off, int size,
6141 			       bool zero_size_allowed,
6142 			       u32 *max_access, bool write)
6143 {
6144 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6145 	struct bpf_prog_aux *aux = env->prog->aux;
6146 	u32 access_end;
6147 	int err;
6148 
6149 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
6150 	if (err)
6151 		return err;
6152 
6153 	*max_access = max(access_end, *max_access);
6154 	if (write && size) {
6155 		if (!aux->max_rdwr_write || access_end - size < aux->min_rdwr_write)
6156 			aux->min_rdwr_write = access_end - size;
6157 		aux->max_rdwr_write = max(access_end, aux->max_rdwr_write);
6158 	}
6159 
6160 	return 0;
6161 }
6162 
6163 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6164 static void zext_32_to_64(struct bpf_reg_state *reg)
6165 {
6166 	reg_step_check_unsigned(reg, 32);
6167 	reg->var_off = tnum_subreg(reg->var_off);
6168 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
6169 }
6170 
6171 /* truncate register to smaller size (in bytes)
6172  * must be called with size < BPF_REG_SIZE
6173  */
6174 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6175 {
6176 	u64 mask = (1ULL << (size * 8)) - 1;
6177 
6178 	reg_step_check_unsigned(reg, size * 8);
6179 
6180 	/* clear high bits in bit representation */
6181 	reg->var_off = tnum_cast(reg->var_off, size);
6182 
6183 	/* fix arithmetic bounds */
6184 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
6185 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
6186 	else
6187 		reg_set_urange64(reg, 0, mask);
6188 
6189 	/* If size is smaller than 32bit register the 32bit register
6190 	 * values are also truncated so we push 64-bit bounds into
6191 	 * 32-bit bounds. Above were truncated < 32-bits already.
6192 	 */
6193 	if (size < 4)
6194 		__mark_reg32_unbounded(reg);
6195 
6196 	reg_bounds_sync(reg);
6197 }
6198 
6199 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6200 {
6201 	if (size == 1) {
6202 		reg_set_srange64(reg, S8_MIN, S8_MAX);
6203 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6204 	} else if (size == 2) {
6205 		reg_set_srange64(reg, S16_MIN, S16_MAX);
6206 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6207 	} else {
6208 		/* size == 4 */
6209 		reg_set_srange64(reg, S32_MIN, S32_MAX);
6210 		reg_set_srange32(reg, S32_MIN, S32_MAX);
6211 	}
6212 	reg->var_off = tnum_unknown;
6213 }
6214 
6215 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6216 {
6217 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6218 	u64 top_smax_value, top_smin_value;
6219 	u64 num_bits = size * 8;
6220 	s64 limit = 1LL << (num_bits - 1);
6221 	struct cnum32 r32;
6222 
6223 	/* If every value fits the signed N-bit range sign extension is a noop. */
6224 	if (reg_smin(reg) >= -limit && reg_smax(reg) < limit)
6225 		return;
6226 
6227 	/* See commen at reg_step_check_unsigned(). */
6228 	reg_step_reset(reg);
6229 
6230 	if (tnum_is_const(reg->var_off)) {
6231 		u64_cval = reg->var_off.value;
6232 		if (size == 1)
6233 			reg->var_off = tnum_const((s8)u64_cval);
6234 		else if (size == 2)
6235 			reg->var_off = tnum_const((s16)u64_cval);
6236 		else
6237 			/* size == 4 */
6238 			reg->var_off = tnum_const((s32)u64_cval);
6239 
6240 		u64_cval = reg->var_off.value;
6241 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
6242 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
6243 		return;
6244 	}
6245 
6246 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
6247 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
6248 
6249 	if (top_smax_value != top_smin_value)
6250 		goto out;
6251 
6252 	/* find the s64_min and s64_min after sign extension */
6253 	if (size == 1) {
6254 		init_s64_max = (s8)reg_smax(reg);
6255 		init_s64_min = (s8)reg_smin(reg);
6256 	} else if (size == 2) {
6257 		init_s64_max = (s16)reg_smax(reg);
6258 		init_s64_min = (s16)reg_smin(reg);
6259 	} else {
6260 		init_s64_max = (s32)reg_smax(reg);
6261 		init_s64_min = (s32)reg_smin(reg);
6262 	}
6263 
6264 	s64_max = max(init_s64_max, init_s64_min);
6265 	s64_min = min(init_s64_max, init_s64_min);
6266 
6267 	/* both of s64_max/s64_min positive or negative */
6268 	if ((s64_max >= 0) == (s64_min >= 0)) {
6269 		reg_set_srange64(reg, s64_min, s64_max);
6270 		reg_set_srange32(reg, s64_min, s64_max);
6271 		reg->var_off = tnum_range(s64_min, s64_max);
6272 		return;
6273 	}
6274 
6275 out:
6276 	r32 = reg->r32;
6277 	set_sext64_default_val(reg, size);
6278 	/* the low 32 bits fit, they do not change */
6279 	if (cnum32_smin(r32) >= -limit && cnum32_smax(r32) < limit) {
6280 		reg->r32 = r32;
6281 		reg->r64 = cnum64_from_srange(cnum32_smin(r32), cnum32_smax(r32));
6282 	}
6283 }
6284 
6285 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6286 {
6287 	if (size == 1)
6288 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6289 	else
6290 		/* size == 2 */
6291 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6292 	reg->var_off = tnum_subreg(tnum_unknown);
6293 }
6294 
6295 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6296 {
6297 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6298 	u32 top_smax_value, top_smin_value;
6299 	u32 num_bits = size * 8;
6300 
6301 	/*
6302 	 * If value fits the non-negative half of the signed N-bit range,
6303 	 * sign extension is a noop.
6304 	 */
6305 	if (reg_umax(reg) < (1ULL << (num_bits - 1)))
6306 		return;
6307 
6308 	/* See comment at reg_step_check_unsigned(). */
6309 	reg_step_reset(reg);
6310 
6311 	if (tnum_is_const(reg->var_off)) {
6312 		u32_val = reg->var_off.value;
6313 		if (size == 1)
6314 			reg->var_off = tnum_const((s8)u32_val);
6315 		else
6316 			reg->var_off = tnum_const((s16)u32_val);
6317 
6318 		u32_val = reg->var_off.value;
6319 		reg_set_srange32(reg, u32_val, u32_val);
6320 		return;
6321 	}
6322 
6323 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
6324 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
6325 
6326 	if (top_smax_value != top_smin_value)
6327 		goto out;
6328 
6329 	/* find the s32_min and s32_min after sign extension */
6330 	if (size == 1) {
6331 		init_s32_max = (s8)reg_s32_max(reg);
6332 		init_s32_min = (s8)reg_s32_min(reg);
6333 	} else {
6334 		/* size == 2 */
6335 		init_s32_max = (s16)reg_s32_max(reg);
6336 		init_s32_min = (s16)reg_s32_min(reg);
6337 	}
6338 	s32_max = max(init_s32_max, init_s32_min);
6339 	s32_min = min(init_s32_max, init_s32_min);
6340 
6341 	if ((s32_min >= 0) == (s32_max >= 0)) {
6342 		reg_set_srange32(reg, s32_min, s32_max);
6343 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6344 		return;
6345 	}
6346 
6347 out:
6348 	set_sext32_default_val(reg, size);
6349 }
6350 
6351 bool bpf_map_is_rdonly(const struct bpf_map *map)
6352 {
6353 	/* A map is considered read-only if the following condition are true:
6354 	 *
6355 	 * 1) BPF program side cannot change any of the map content. The
6356 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6357 	 *    and was set at map creation time.
6358 	 * 2) The map value(s) have been initialized from user space by a
6359 	 *    loader and then "frozen", such that no new map update/delete
6360 	 *    operations from syscall side are possible for the rest of
6361 	 *    the map's lifetime from that point onwards.
6362 	 * 3) Any parallel/pending map update/delete operations from syscall
6363 	 *    side have been completed. Only after that point, it's safe to
6364 	 *    assume that map value(s) are immutable.
6365 	 */
6366 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6367 	       READ_ONCE(map->frozen) &&
6368 	       !bpf_map_write_active(map);
6369 }
6370 
6371 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6372 			bool is_ldsx)
6373 {
6374 	void *ptr;
6375 	u64 addr;
6376 	int err;
6377 
6378 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY || map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
6379 		return -EINVAL;
6380 	err = map->ops->map_direct_value_addr(map, &addr, off);
6381 	if (err)
6382 		return err;
6383 	ptr = (void *)(long)addr + off;
6384 
6385 	switch (size) {
6386 	case sizeof(u8):
6387 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6388 		break;
6389 	case sizeof(u16):
6390 		*val = is_ldsx ? (s64)get_unaligned((s16 *)ptr) : (u64)get_unaligned((u16 *)ptr);
6391 		break;
6392 	case sizeof(u32):
6393 		*val = is_ldsx ? (s64)get_unaligned((s32 *)ptr) : (u64)get_unaligned((u32 *)ptr);
6394 		break;
6395 	case sizeof(u64):
6396 		*val = get_unaligned((u64 *)ptr);
6397 		break;
6398 	default:
6399 		return -EINVAL;
6400 	}
6401 	return 0;
6402 }
6403 
6404 static int cmp_func_ptrs(const void *_a, const void *_b)
6405 {
6406 	const struct bpf_func_ptr *a = _a, *b = _b;
6407 
6408 	if (a->map != b->map)
6409 		return a->map < b->map ? -1 : 1;
6410 	if (a->map_off != b->map_off)
6411 		return a->map_off < b->map_off ? -1 : 1;
6412 	return 0;
6413 }
6414 
6415 /* Find the first pointer to a function at or after 'off' in the value of 'map' */
6416 static u32 func_ptr_lower_bound(struct bpf_verifier_env *env, const struct bpf_map *map, u64 off)
6417 {
6418 	u32 l = 0, r = env->func_ptr_cnt, m;
6419 	struct bpf_func_ptr *p;
6420 
6421 	while (l < r) {
6422 		m = l + (r - l) / 2;
6423 		p = &env->func_ptrs[m];
6424 		if (p->map < map || (p->map == map && p->map_off < off))
6425 			l = m + 1;
6426 		else
6427 			r = m;
6428 	}
6429 	return l;
6430 }
6431 
6432 /*
6433  * Return pointers to functions that overlap with 'size' bytes at offset 'off'
6434  * of the value of 'map' and their number in 'cnt'.
6435  */
6436 struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env,
6437 					     const struct bpf_map *map,
6438 					     u64 off, u64 size, u32 *cnt)
6439 {
6440 	u32 first, last;
6441 
6442 	*cnt = 0;
6443 	if (!env->func_ptr_cnt || !size)
6444 		return NULL;
6445 
6446 	/* a pointer that starts up to 7 bytes before 'off' overlaps too */
6447 	first = func_ptr_lower_bound(env, map, off >= sizeof(u64) ? off - sizeof(u64) + 1 : 0);
6448 	last = func_ptr_lower_bound(env, map, off + size);
6449 	if (first >= last)
6450 		return NULL;
6451 
6452 	*cnt = last - first;
6453 	return &env->func_ptrs[first];
6454 }
6455 
6456 /* Return all pointers to functions in the value of 'map' */
6457 struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
6458 				       const struct bpf_map *map, u32 *cnt)
6459 {
6460 	return bpf_map_range_func_ptrs(env, map, 0, (u64)map->value_size, cnt);
6461 }
6462 
6463 /* instructions [off, off + len) replaced the instruction at 'off' */
6464 void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len)
6465 {
6466 	struct bpf_func_ptr *p;
6467 	u32 i;
6468 
6469 	if (len <= 1)
6470 		return;
6471 
6472 	for (i = 0; i < env->func_ptr_cnt; i++) {
6473 		p = &env->func_ptrs[i];
6474 		if (p->xlated_off <= off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6475 			continue;
6476 		p->xlated_off += len - 1;
6477 	}
6478 }
6479 
6480 /*
6481  * Instructions [off, off + len) are about to be removed. It's called before
6482  * the starts of subprogs are adjusted. A subprog is gone when all of its
6483  * instructions are. Otherwise, e.g. when its first instruction is a nop,
6484  * it starts where the removed instructions did.
6485  */
6486 void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
6487 {
6488 	struct bpf_func_ptr *p;
6489 	int subprog;
6490 	u32 i;
6491 
6492 	for (i = 0; i < env->func_ptr_cnt; i++) {
6493 		p = &env->func_ptrs[i];
6494 		if (p->xlated_off < off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6495 			continue;
6496 		if (p->xlated_off >= off + len) {
6497 			p->xlated_off -= len;
6498 			continue;
6499 		}
6500 		subprog = bpf_find_subprog(env, p->xlated_off);
6501 		if (subprog > 0 && env->subprog_info[subprog + 1].start > off + len)
6502 			p->xlated_off = off;
6503 		else
6504 			p->xlated_off = BPF_FUNC_PTR_DELETED;
6505 	}
6506 }
6507 
6508 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6509 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6510 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6511 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6512 
6513 /*
6514  * Allow list few fields as RCU trusted or full trusted.
6515  * This logic doesn't allow mix tagging and will be removed once GCC supports
6516  * btf_type_tag.
6517  */
6518 
6519 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6520 BTF_TYPE_SAFE_RCU(struct task_struct) {
6521 	const cpumask_t *cpus_ptr;
6522 	struct css_set __rcu *cgroups;
6523 	struct task_struct __rcu *real_parent;
6524 	struct task_struct *group_leader;
6525 };
6526 
6527 BTF_TYPE_SAFE_RCU(struct cgroup) {
6528 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6529 	struct kernfs_node *kn;
6530 };
6531 
6532 BTF_TYPE_SAFE_RCU(struct css_set) {
6533 	struct cgroup *dfl_cgrp;
6534 };
6535 
6536 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
6537 	struct cgroup *cgroup;
6538 };
6539 
6540 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6541 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6542 	struct file __rcu *exe_file;
6543 #ifdef CONFIG_MEMCG
6544 	struct task_struct __rcu *owner;
6545 #endif
6546 };
6547 
6548 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6549  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6550  */
6551 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6552 	struct sock *sk;
6553 };
6554 
6555 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6556 	struct sock *sk;
6557 };
6558 
6559 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6560 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6561 	struct seq_file *seq;
6562 };
6563 
6564 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6565 	struct bpf_iter_meta *meta;
6566 	struct task_struct *task;
6567 };
6568 
6569 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6570 	struct file *file;
6571 };
6572 
6573 BTF_TYPE_SAFE_TRUSTED(struct file) {
6574 	struct inode *f_inode;
6575 };
6576 
6577 /*
6578  * The pointer fields in the sched_ext ops argument containers are pinned by the
6579  * callers for the duration of the ops calls and are never NULL.
6580  */
6581 BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) {
6582 #ifdef CONFIG_EXT_GROUP_SCHED
6583 	struct cgroup *cgroup;
6584 #endif
6585 };
6586 
6587 BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) {
6588 	struct task_struct *task;
6589 };
6590 
6591 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) {
6592 	struct sched_ext_ops *ops;
6593 };
6594 
6595 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) {
6596 	struct sched_ext_ops *ops;
6597 };
6598 
6599 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
6600 	struct inode *d_inode;
6601 };
6602 
6603 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm) {
6604 	struct mm_struct *mm;
6605 };
6606 
6607 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6608 	struct sock *sk;
6609 };
6610 
6611 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
6612 	struct mm_struct *vm_mm;
6613 	struct file *vm_file;
6614 };
6615 
6616 static bool type_is_rcu(struct bpf_verifier_env *env,
6617 			struct bpf_reg_state *reg,
6618 			const char *field_name, u32 btf_id)
6619 {
6620 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6621 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6622 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6623 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
6624 
6625 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6626 }
6627 
6628 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6629 				struct bpf_reg_state *reg,
6630 				const char *field_name, u32 btf_id)
6631 {
6632 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6633 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6634 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6635 
6636 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6637 }
6638 
6639 static bool type_is_trusted(struct bpf_verifier_env *env,
6640 			    struct bpf_reg_state *reg,
6641 			    const char *field_name, u32 btf_id)
6642 {
6643 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6644 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6645 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6646 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6647 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args));
6648 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args));
6649 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args));
6650 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args));
6651 
6652 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6653 }
6654 
6655 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6656 				    struct bpf_reg_state *reg,
6657 				    const char *field_name, u32 btf_id)
6658 {
6659 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6660 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
6661 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm));
6662 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
6663 
6664 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6665 					  "__safe_trusted_or_null");
6666 }
6667 
6668 /*
6669  * The member holds the kernel address of arena memory, which the rewritten
6670  * load turns into an arena pointer, see arena_member_fixup(). NULL needs no
6671  * tracking, PTR_TO_ARENA covers it.
6672  */
6673 static int check_arena_member_load(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
6674 				   int value_regno, enum bpf_type_flag flag, const char *tname,
6675 				   const char *field_name)
6676 {
6677 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx];
6678 	struct bpf_insn *insn;
6679 
6680 	/* a helper reading the member as bytes needs no rewrite */
6681 	if (value_regno < 0)
6682 		return 0;
6683 	if (!env->prog->aux->arena) {
6684 		verbose(env,
6685 			"arena pointer member %s of struct %s requires a program with an associated arena\n",
6686 			field_name, tname);
6687 		return -EINVAL;
6688 	}
6689 	/* only a plain load or an acquire load is rewritten */
6690 	insn = &env->prog->insnsi[env->insn_idx];
6691 	if (BPF_CLASS(insn->code) != BPF_LDX &&
6692 	    !(insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW) && insn->imm == BPF_LOAD_ACQ)) {
6693 		verbose(env,
6694 			"arena pointer member %s of struct %s can only be read with a plain or an acquire load\n",
6695 			field_name, tname);
6696 		return -EACCES;
6697 	}
6698 
6699 	aux->arena_member = true;
6700 	if (flag & PTR_MAYBE_NULL)
6701 		aux->arena_member_nullable = true;
6702 	mark_reg_unknown(env, regs, value_regno);
6703 	regs[value_regno].type = PTR_TO_ARENA;
6704 	return 0;
6705 }
6706 
6707 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6708 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6709 				   argno_t argno, int off, int size,
6710 				   enum bpf_access_type atype,
6711 				   int value_regno)
6712 {
6713 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6714 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6715 	const char *field_name = NULL;
6716 	enum bpf_type_flag flag = 0;
6717 	u32 btf_id = 0;
6718 	s64 min_off;
6719 	int ret;
6720 
6721 	if (!env->allow_ptr_leaks) {
6722 		verbose(env,
6723 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6724 			tname);
6725 		return -EPERM;
6726 	}
6727 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6728 		verbose(env,
6729 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6730 			tname);
6731 		return -EINVAL;
6732 	}
6733 
6734 	if (check_add_overflow(reg_smin(reg), off, &min_off)) {
6735 		verbose(env,
6736 			"%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n",
6737 			reg_arg_name(env, argno), tname, reg_smin(reg), off);
6738 		return -EACCES;
6739 	}
6740 
6741 	if (min_off < 0) {
6742 		verbose(env,
6743 			"%s is ptr_%s invalid negative access: off=%lld\n",
6744 			reg_arg_name(env, argno), tname, min_off);
6745 		return -EACCES;
6746 	}
6747 
6748 	if (reg->type & MEM_USER) {
6749 		verbose(env,
6750 			"%s is ptr_%s access user memory\n",
6751 			reg_arg_name(env, argno), tname);
6752 		return -EACCES;
6753 	}
6754 
6755 	if (reg->type & MEM_PERCPU) {
6756 		verbose(env,
6757 			"%s is ptr_%s access percpu memory\n",
6758 			reg_arg_name(env, argno), tname);
6759 		return -EACCES;
6760 	}
6761 
6762 	if (atype != BPF_READ && bpf_may_fault_on_deref(reg->type)) {
6763 		verbose(env, "only read is supported\n");
6764 		return -EACCES;
6765 	}
6766 
6767 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6768 		if (!tnum_is_const(reg->var_off)) {
6769 			char tn_buf[48];
6770 
6771 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6772 			verbose(env,
6773 				"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6774 				reg_arg_name(env, argno), tname, off, tn_buf);
6775 			return -EACCES;
6776 		}
6777 
6778 		off += reg->var_off.value;
6779 
6780 		if (!btf_is_kernel(reg->btf)) {
6781 			verifier_bug(env, "reg->btf must be kernel btf");
6782 			return -EFAULT;
6783 		}
6784 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6785 		if (ret < 0)
6786 			verbose(env,
6787 				"%s cannot write into ptr_%s at off=%d size=%d\n",
6788 				reg_arg_name(env, argno), tname, off, size);
6789 	} else {
6790 		/* Writes are permitted with default btf_struct_access for
6791 		 * program allocated objects (which always have id > 0).
6792 		 */
6793 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6794 			verbose(env, "only read is supported\n");
6795 			return -EACCES;
6796 		}
6797 
6798 		/*
6799 		 * A fault-prone allocated object may still be read through a
6800 		 * BPF_PROBE_MEM load after its lifetime protection ends. Writes
6801 		 * through such pointers were rejected above.
6802 		 */
6803 		if (type_is_alloc(reg->type) && !bpf_may_fault_on_deref(reg->type) &&
6804 		    !type_is_non_owning_ref(reg->type) &&
6805 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
6806 			verifier_bug(env, "allocated object must have a referenced id");
6807 			return -EFAULT;
6808 		}
6809 
6810 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6811 	}
6812 
6813 	if (ret < 0)
6814 		return ret;
6815 
6816 	if (ret == PTR_TO_ARENA)
6817 		return check_arena_member_load(env, regs, value_regno, flag, tname, field_name);
6818 
6819 	if (ret != PTR_TO_BTF_ID) {
6820 		/* just mark; */
6821 
6822 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6823 		/* If this is an untrusted pointer, all pointers formed by walking it
6824 		 * also inherit the untrusted flag.
6825 		 */
6826 		flag = PTR_UNTRUSTED;
6827 
6828 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
6829 		/* By default any pointer obtained from walking a trusted pointer is no
6830 		 * longer trusted, unless the field being accessed has explicitly been
6831 		 * marked as inheriting its parent's state of trust (either full or RCU).
6832 		 * For example:
6833 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6834 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6835 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6836 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6837 		 *
6838 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6839 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6840 		 */
6841 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6842 			flag |= PTR_TRUSTED;
6843 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6844 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6845 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6846 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6847 				/* ignore __rcu tag and mark it MEM_RCU */
6848 				flag |= MEM_RCU;
6849 			} else if (flag & MEM_RCU ||
6850 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6851 				/* __rcu tagged pointers can be NULL */
6852 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6853 
6854 				/* We always trust them */
6855 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6856 				    flag & PTR_UNTRUSTED)
6857 					flag &= ~PTR_UNTRUSTED;
6858 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6859 				/* keep as-is */
6860 			} else {
6861 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6862 				clear_trusted_flags(&flag);
6863 			}
6864 		} else {
6865 			/*
6866 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6867 			 * aggressively mark as untrusted otherwise such
6868 			 * pointers will be plain PTR_TO_BTF_ID without flags
6869 			 * and will be allowed to be passed into helpers for
6870 			 * compat reasons.
6871 			 */
6872 			flag = PTR_UNTRUSTED;
6873 		}
6874 	} else {
6875 		/* Old compat. Deprecated */
6876 		clear_trusted_flags(&flag);
6877 	}
6878 
6879 	/*
6880 	 * A __nullable member only matters where NULL would otherwise be
6881 	 * assumed away, which is anywhere but on a plain or an untrusted
6882 	 * pointer: those are probed on a dereference, which tolerates NULL, and
6883 	 * the BTF_TYPE_SAFE_*_OR_NULL lists never applied to them either. A
6884 	 * per-CPU pointer counts, per_cpu_ptr() does not check for NULL.
6885 	 */
6886 	if (bpf_may_fault_on_deref(PTR_TO_BTF_ID | (flag & ~PTR_MAYBE_NULL)))
6887 		flag &= ~PTR_MAYBE_NULL;
6888 
6889 	if (atype == BPF_READ && value_regno >= 0) {
6890 		u32 parent_id = reg_lifetime_id(env, reg);
6891 
6892 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6893 		if (ret < 0)
6894 			return ret;
6895 		if ((regs[value_regno].type & PTR_TRUSTED) &&
6896 		    !(regs[value_regno].type & (MEM_RCU | MEM_PERCPU | MEM_USER)))
6897 			regs[value_regno].parent_id = parent_id;
6898 	}
6899 
6900 	return 0;
6901 }
6902 
6903 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6904 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6905 				   argno_t argno, int off, int size,
6906 				   enum bpf_access_type atype,
6907 				   int value_regno)
6908 {
6909 	struct bpf_map *map = reg->map_ptr;
6910 	struct bpf_reg_state map_reg;
6911 	enum bpf_type_flag flag = 0;
6912 	const struct btf_type *t;
6913 	const char *tname;
6914 	u32 btf_id;
6915 	int ret;
6916 
6917 	if (!btf_vmlinux) {
6918 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6919 		return -ENOTSUPP;
6920 	}
6921 
6922 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6923 		verbose(env, "map_ptr access not supported for map type %d\n",
6924 			map->map_type);
6925 		return -ENOTSUPP;
6926 	}
6927 
6928 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6929 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6930 
6931 	if (!env->allow_ptr_leaks) {
6932 		verbose(env,
6933 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6934 			tname);
6935 		return -EPERM;
6936 	}
6937 
6938 	if (off < 0) {
6939 		verbose(env, "%s is %s invalid negative access: off=%d\n",
6940 			reg_arg_name(env, argno), tname, off);
6941 		return -EACCES;
6942 	}
6943 
6944 	if (atype != BPF_READ) {
6945 		verbose(env, "only read from %s is supported\n", tname);
6946 		return -EACCES;
6947 	}
6948 
6949 	/* Simulate access to a PTR_TO_BTF_ID */
6950 	memset(&map_reg, 0, sizeof(map_reg));
6951 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
6952 			      btf_vmlinux, *map->ops->map_btf_id, 0);
6953 	if (ret < 0)
6954 		return ret;
6955 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6956 	if (ret < 0)
6957 		return ret;
6958 
6959 	if (value_regno >= 0) {
6960 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6961 		if (ret < 0)
6962 			return ret;
6963 	}
6964 
6965 	return 0;
6966 }
6967 
6968 /*
6969  * Check that the stack access at the given offset is within bounds. The
6970  * maximum valid offset is -1.
6971  *
6972  * The minimum valid offset is -env->stack_limit for writes, and
6973  * -state->allocated_stack for reads.
6974  */
6975 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6976                                           s64 off,
6977                                           struct bpf_func_state *state,
6978                                           enum bpf_access_type t)
6979 {
6980 	int min_valid_off;
6981 
6982 	if (t == BPF_WRITE || env->allow_uninit_stack)
6983 		min_valid_off = -(int)env->stack_limit;
6984 	else
6985 		min_valid_off = -state->allocated_stack;
6986 
6987 	if (off < min_valid_off || off > -1)
6988 		return -EACCES;
6989 	return 0;
6990 }
6991 
6992 /* Check that the stack access at 'regno + off' falls within the maximum stack
6993  * bounds.
6994  *
6995  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6996  */
6997 static int check_stack_access_within_bounds(
6998 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6999 		argno_t argno, int off, int access_size,
7000 		enum bpf_access_type type)
7001 {
7002 	struct bpf_func_state *state = bpf_func(env, reg);
7003 	s64 min_off, max_off;
7004 	int err;
7005 	char *err_extra;
7006 
7007 	if (type == BPF_READ)
7008 		err_extra = " read from";
7009 	else
7010 		err_extra = " write to";
7011 
7012 	if (tnum_is_const(reg->var_off)) {
7013 		min_off = (s64)reg->var_off.value + off;
7014 		max_off = min_off + access_size;
7015 	} else {
7016 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
7017 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
7018 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
7019 				err_extra, reg_arg_name(env, argno));
7020 			return -EACCES;
7021 		}
7022 		min_off = reg_smin(reg) + off;
7023 		max_off = reg_smax(reg) + off + access_size;
7024 	}
7025 
7026 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7027 	if (!err && max_off > 0)
7028 		err = -EINVAL; /* out of stack access into non-negative offsets */
7029 	if (!err && access_size < 0)
7030 		/* access_size should not be negative (or overflow an int); others checks
7031 		 * along the way should have prevented such an access.
7032 		 */
7033 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7034 
7035 	if (err) {
7036 		if (tnum_is_const(reg->var_off)) {
7037 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
7038 				err_extra, reg_arg_name(env, argno), min_off, access_size);
7039 		} else {
7040 			char tn_buf[48];
7041 
7042 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7043 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
7044 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
7045 		}
7046 		return err;
7047 	}
7048 
7049 	/*
7050 	 * Every stack access passes through here, including buffers passed to
7051 	 * helpers and kfuncs and accesses into a caller's frame, so check the
7052 	 * fastcall contract of the frame that owns the slots once for all of
7053 	 * them. Zero-sized accesses touch no stack and keep the rewrite enabled.
7054 	 */
7055 	if (access_size)
7056 		check_fastcall_stack_contract(env, state, env->insn_idx, min_off);
7057 
7058 	/* Note that there is no stack access with offset zero, so the needed stack
7059 	 * size is -min_off, not -min_off+1.
7060 	 */
7061 	return bpf_grow_stack_state(env, state, -min_off /* size */);
7062 }
7063 
7064 static bool get_func_retval_range(struct bpf_prog *prog,
7065 				  struct bpf_retval_range *range)
7066 {
7067 	if (prog->type == BPF_PROG_TYPE_LSM &&
7068 		prog->expected_attach_type == BPF_LSM_MAC &&
7069 		!bpf_lsm_get_retval_range(prog, range)) {
7070 		return true;
7071 	}
7072 	return false;
7073 }
7074 
7075 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
7076 {
7077 	struct bpf_reg_state fake_reg;
7078 
7079 	if (!val)
7080 		return;
7081 
7082 	fake_reg.type = SCALAR_VALUE;
7083 	__mark_reg_known(&fake_reg, val);
7084 
7085 	scalar_step_add(dst_reg, dst_reg, &fake_reg);
7086 	scalar32_min_max_add(dst_reg, &fake_reg);
7087 	scalar_min_max_add(dst_reg, &fake_reg);
7088 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
7089 
7090 	reg_bounds_sync(dst_reg);
7091 }
7092 
7093 /* there is no support for callx in the interpreter */
7094 static int require_callx_jit(struct bpf_verifier_env *env)
7095 {
7096 	if (!env->prog->jit_requested) {
7097 		verbose(env, "JIT is required to use callx\n");
7098 		return -EOPNOTSUPP;
7099 	}
7100 	if (!bpf_jit_supports_callx()) {
7101 		verbose(env, "JIT doesn't support callx\n");
7102 		return -EOPNOTSUPP;
7103 	}
7104 	env->prog->jit_required = true;
7105 	return 0;
7106 }
7107 
7108 static void mark_reg_func_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
7109 			      int regno, int subprog)
7110 {
7111 	mark_reg_known_zero(env, regs, regno);
7112 	regs[regno].type = PTR_TO_FUNC;
7113 	regs[regno].subprogno = subprog;
7114 }
7115 
7116 /* a read from a table of functions branches into that many states at most */
7117 #define BPF_MAX_FUNC_PTR_TARGETS 64
7118 /* and that many pointers at most are next to what is read at variable offset */
7119 #define BPF_MAX_FUNC_PTR_RANGE 4096
7120 
7121 /* Count up to 'limit' offsets in [min_off, max_off] that the read is possible at */
7122 static u32 count_read_offsets(struct tnum offs, u64 min_off, u64 max_off, u32 limit)
7123 {
7124 	u64 o = min_off, next;
7125 	u32 cnt = 0;
7126 
7127 	if (!tnum_in(offs, tnum_const(o))) {
7128 		next = tnum_step(offs, o);
7129 		if (next <= o)
7130 			return 0;
7131 		o = next;
7132 	}
7133 	while (o <= max_off && cnt < limit) {
7134 		cnt++;
7135 		next = tnum_step(offs, o);
7136 		if (next <= o)
7137 			break;
7138 		o = next;
7139 	}
7140 	return cnt;
7141 }
7142 
7143 /*
7144  * A read from a frozen read-only map that has pointers to functions, see
7145  * resolve_func_ptrs(). The bounds and var_off of the offset tell where the read
7146  * is possible at, e.g. var_off is the stride of the elements of an array.
7147  * A read of exactly one pointer yields PTR_TO_FUNC. When the offset is variable
7148  * and only pointers can be read, which is how an element of a table of
7149  * functions is loaded, the verification continues with each of them. Other
7150  * reads that overlap with a pointer are rejected, because their result is not
7151  * known until the program is jitted.
7152  *
7153  * Return -ENOENT if there are no pointers to functions in the bytes that are read.
7154  */
7155 static int check_func_ptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
7156 			       int size, int value_regno)
7157 {
7158 	u64 min_off = reg_umin(reg) + off, max_off = reg_umax(reg) + off;
7159 	struct tnum offs = tnum_add(reg->var_off, tnum_const(off));
7160 	struct bpf_reg_state *regs = cur_regs(env);
7161 	struct bpf_map *map = reg->map_ptr;
7162 	struct bpf_verifier_state *branch;
7163 	int subprog, targets[BPF_MAX_FUNC_PTR_TARGETS];
7164 	struct bpf_func_ptr *ptrs;
7165 	u32 i, cnt, n = 0;
7166 	u64 o, lo, hi;
7167 	int err;
7168 
7169 	ptrs = bpf_map_range_func_ptrs(env, map, min_off, max_off - min_off + size, &cnt);
7170 	if (!ptrs)
7171 		return -ENOENT;
7172 	if (cnt > BPF_MAX_FUNC_PTR_RANGE)
7173 		goto overlap;
7174 
7175 	for (i = 0; i < cnt; i++) {
7176 		/* the offsets at which the read overlaps with the pointer */
7177 		lo = ptrs[i].map_off >= size ? ptrs[i].map_off - size + 1 : 0;
7178 		lo = max(lo, min_off);
7179 		hi = min(ptrs[i].map_off + sizeof(u64) - 1, max_off);
7180 		for (o = lo; o <= hi; o++) {
7181 			if (!tnum_in(offs, tnum_const(o)))
7182 				continue;
7183 			if (o != ptrs[i].map_off || size != sizeof(u64) || value_regno < 0)
7184 				goto overlap;
7185 			if (n == BPF_MAX_FUNC_PTR_TARGETS) {
7186 				verbose(env, "read from map '%s' may yield more than %d pointers to functions\n",
7187 					map->name, BPF_MAX_FUNC_PTR_TARGETS);
7188 				return -E2BIG;
7189 			}
7190 			subprog = bpf_find_subprog(env, ptrs[i].xlated_off);
7191 			if (verifier_bug_if(subprog <= 0, env,
7192 					    "no function at insn %u for map '%s' offset %u",
7193 					    ptrs[i].xlated_off, map->name, ptrs[i].map_off))
7194 				return -EFAULT;
7195 			targets[n++] = subprog;
7196 		}
7197 	}
7198 	/* pointers are next to what is read, e.g. the data of an array of vtables */
7199 	if (!n)
7200 		return -ENOENT;
7201 	/* either every offset that the read is possible at is a pointer or none */
7202 	if (count_read_offsets(offs, min_off, max_off, n + 1) != n)
7203 		goto overlap;
7204 
7205 	/* the map has the offset of the function until the program is jitted */
7206 	err = require_callx_jit(env);
7207 	if (err)
7208 		return err;
7209 
7210 	for (i = 0; i < n - 1; i++) {
7211 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx,
7212 				    env->cur_state->speculative);
7213 		if (IS_ERR(branch))
7214 			return PTR_ERR(branch);
7215 		mark_reg_func_ptr(env, branch->frame[branch->curframe]->regs, value_regno,
7216 				  targets[i]);
7217 	}
7218 	mark_reg_func_ptr(env, regs, value_regno, targets[n - 1]);
7219 	return 0;
7220 
7221 overlap:
7222 	verbose(env, "read of %d bytes at offset [%llu,%llu] of map '%s' overlaps with a pointer to a function\n",
7223 		size, min_off, max_off, map->name);
7224 	return -EACCES;
7225 }
7226 
7227 static int check_map_mem_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
7228 			      int bpf_size, int value_regno, bool is_ldsx)
7229 {
7230 	struct bpf_reg_state *regs = cur_regs(env);
7231 	int size = bpf_size_to_bytes(bpf_size);
7232 	struct bpf_map *map = reg->map_ptr;
7233 	int err;
7234 
7235 	switch (map->map_type) {
7236 	case BPF_MAP_TYPE_INSN_ARRAY:
7237 		if (bpf_size != BPF_DW) {
7238 			verbose(env, "Invalid read of %d bytes from insn_array\n", size);
7239 			return -EACCES;
7240 		}
7241 		regs[value_regno] = *reg;
7242 		add_scalar_to_reg(&regs[value_regno], off);
7243 		regs[value_regno].type = PTR_TO_INSN;
7244 		return 0;
7245 	case BPF_MAP_TYPE_PERCPU_ARRAY:
7246 		goto reg_unknown;
7247 	default:
7248 		break;
7249 	}
7250 
7251 	if (env->func_ptr_cnt) {
7252 		err = check_func_ptr_read(env, reg, off, size, value_regno);
7253 		if (err != -ENOENT)
7254 			return err;
7255 	}
7256 
7257 	/* If map is read-only, track its contents as scalars. */
7258 	if (tnum_is_const(reg->var_off) &&
7259 	    bpf_map_is_rdonly(map) &&
7260 	    map->ops->map_direct_value_addr) {
7261 		int map_off = off + reg->var_off.value;
7262 		u64 val = 0;
7263 
7264 		err = bpf_map_direct_read(map, map_off, size, &val, is_ldsx);
7265 		if (err)
7266 			return err;
7267 
7268 		regs[value_regno].type = SCALAR_VALUE;
7269 		__mark_reg_known(&regs[value_regno], val);
7270 		return 0;
7271 	}
7272 
7273 reg_unknown:
7274 	mark_reg_unknown(env, regs, value_regno);
7275 	return 0;
7276 }
7277 
7278 /* check whether memory at (regno + off) is accessible for t = (read | write)
7279  * if t==write, value_regno is a register which value is stored into memory
7280  * if t==read, value_regno is a register which will receive the value from memory
7281  * if t==write && value_regno==-1, some unknown value is stored into memory
7282  * if t==read && value_regno==-1, don't care what we read from memory
7283  */
7284 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
7285 			    int off, int bpf_size, enum bpf_access_type t,
7286 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7287 {
7288 	struct bpf_reg_state *regs = cur_regs(env);
7289 	enum bpf_reg_type ptr_type = reg->type;
7290 	int size, err = 0;
7291 
7292 	size = bpf_size_to_bytes(bpf_size);
7293 	if (size < 0)
7294 		return size;
7295 
7296 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7297 	if (err)
7298 		return err;
7299 
7300 	if (reg->type == PTR_TO_MAP_KEY) {
7301 		if (t == BPF_WRITE) {
7302 			verbose(env, "write to change key %s not allowed\n",
7303 				reg_arg_name(env, argno));
7304 			return -EACCES;
7305 		}
7306 
7307 		err = check_mem_region_access(env, reg, argno, off, size,
7308 					      reg->map_ptr->key_size, false);
7309 		if (err)
7310 			return err;
7311 		if (value_regno >= 0)
7312 			mark_reg_unknown(env, regs, value_regno);
7313 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7314 		struct btf_field *kptr_field = NULL;
7315 
7316 		if (t == BPF_WRITE && value_regno >= 0 &&
7317 		    is_pointer_value(env, value_regno)) {
7318 			verbose(env, "R%d leaks addr into map\n", value_regno);
7319 			return -EACCES;
7320 		}
7321 		err = check_map_access_type(env, reg, off, size, t);
7322 		if (err)
7323 			return err;
7324 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
7325 		if (err)
7326 			return err;
7327 		if (tnum_is_const(reg->var_off))
7328 			kptr_field = btf_record_find(reg->map_ptr->record,
7329 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7330 		if (kptr_field) {
7331 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
7332 		} else if (t == BPF_READ && value_regno >= 0) {
7333 			err = check_map_mem_read(env, reg, off, bpf_size, value_regno, is_ldsx);
7334 		}
7335 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7336 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7337 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7338 
7339 		if (type_may_be_null(reg->type)) {
7340 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7341 				reg_type_str(env, reg->type));
7342 			bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7343 					       reg_arg_name(env, argno), reg,
7344 						      BPF_DIAG_DEREF_NULLABLE_PTR, 0);
7345 			return -EACCES;
7346 		}
7347 
7348 		if (t == BPF_WRITE && rdonly_mem) {
7349 			verbose(env, "%s cannot write into %s\n",
7350 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7351 			return -EACCES;
7352 		}
7353 
7354 		if (t == BPF_WRITE && value_regno >= 0 &&
7355 		    is_pointer_value(env, value_regno)) {
7356 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7357 			return -EACCES;
7358 		}
7359 
7360 		if (rdonly_untrusted && !env->allow_ptr_leaks) {
7361 			verbose(env, "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7362 				reg_type_str(env, reg->type));
7363 			bpf_diag_policy(env, insn_idx, "read from untrusted read-only memory",
7364 					"the access requires CAP_PERFMON",
7365 					"Load the program with CAP_PERFMON, or avoid dereferencing untrusted pointers.");
7366 			return -EPERM;
7367 		}
7368 
7369 		/*
7370 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7371 		 * instructions, hence no need to check bounds in that case.
7372 		 */
7373 		if (!rdonly_untrusted)
7374 			err = check_mem_region_access(env, reg, argno, off, size,
7375 						      reg->mem_size, false);
7376 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7377 			mark_reg_unknown(env, regs, value_regno);
7378 	} else if (reg->type == PTR_TO_CTX) {
7379 		struct bpf_insn_access_aux info = {
7380 			.reg_type = SCALAR_VALUE,
7381 			.is_ldsx = is_ldsx,
7382 			.log = &env->log,
7383 		};
7384 		struct bpf_retval_range range;
7385 
7386 		if (t == BPF_WRITE && value_regno >= 0 &&
7387 		    is_pointer_value(env, value_regno)) {
7388 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7389 			return -EACCES;
7390 		}
7391 
7392 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
7393 		if (!err && t == BPF_READ && value_regno >= 0) {
7394 			/* ctx access returns either a scalar, or a
7395 			 * PTR_TO_PACKET[_META,_END]. In the latter
7396 			 * case, we know the offset is zero.
7397 			 */
7398 			if (info.reg_type == SCALAR_VALUE) {
7399 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7400 					mark_reg_unknown(env, regs, value_regno);
7401 					err = __mark_reg_s32_range(env, regs, value_regno,
7402 								   range.minval, range.maxval);
7403 					if (err)
7404 						return err;
7405 				} else {
7406 					mark_reg_unknown(env, regs, value_regno);
7407 				}
7408 			} else {
7409 				mark_reg_known_zero(env, regs,
7410 						    value_regno);
7411 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7412 					regs[value_regno].btf = info.btf;
7413 					regs[value_regno].btf_id = info.btf_id;
7414 					regs[value_regno].id = info.ref_id;
7415 				} else if (base_type(info.reg_type) == PTR_TO_MEM) {
7416 					regs[value_regno].mem_size = info.mem_size;
7417 				}
7418 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
7419 					regs[value_regno].id = ++env->id_gen;
7420 			}
7421 			regs[value_regno].type = info.reg_type;
7422 		}
7423 
7424 	} else if (reg->type == PTR_TO_STACK) {
7425 		/* Basic bounds checks. */
7426 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
7427 		if (err)
7428 			return err;
7429 
7430 		if (t == BPF_READ)
7431 			err = check_stack_read(env, reg, argno, off, size,
7432 					       value_regno);
7433 		else
7434 			err = check_stack_write(env, reg, off, size,
7435 						value_regno, insn_idx);
7436 	} else if (reg_is_pkt_pointer(reg)) {
7437 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7438 			verbose(env, "cannot write into packet\n");
7439 			return -EACCES;
7440 		}
7441 		if (t == BPF_WRITE && value_regno >= 0 &&
7442 		    is_pointer_value(env, value_regno)) {
7443 			verbose(env, "R%d leaks addr into packet\n",
7444 				value_regno);
7445 			return -EACCES;
7446 		}
7447 		err = check_packet_access(env, reg, argno, off, size, false);
7448 		if (!err && t == BPF_READ && value_regno >= 0)
7449 			mark_reg_unknown(env, regs, value_regno);
7450 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7451 		if (t == BPF_WRITE && value_regno >= 0 &&
7452 		    is_pointer_value(env, value_regno)) {
7453 			verbose(env, "R%d leaks addr into flow keys\n",
7454 				value_regno);
7455 			return -EACCES;
7456 		}
7457 
7458 		err = check_flow_keys_access(env, reg, argno, off, size);
7459 		if (!err && t == BPF_READ && value_regno >= 0)
7460 			mark_reg_unknown(env, regs, value_regno);
7461 	} else if (type_is_sk_pointer(reg->type)) {
7462 		if (t == BPF_WRITE) {
7463 			verbose(env, "%s cannot write into %s\n",
7464 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7465 			return -EACCES;
7466 		}
7467 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
7468 		if (!err && value_regno >= 0)
7469 			mark_reg_unknown(env, regs, value_regno);
7470 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7471 		err = check_tp_buffer_access(env, reg, argno, off, size);
7472 		if (!err && t == BPF_READ && value_regno >= 0)
7473 			mark_reg_unknown(env, regs, value_regno);
7474 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7475 		   !type_may_be_null(reg->type)) {
7476 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
7477 					      value_regno);
7478 	} else if (reg->type == CONST_PTR_TO_MAP) {
7479 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
7480 					      value_regno);
7481 	} else if (base_type(reg->type) == PTR_TO_BUF &&
7482 		   !type_may_be_null(reg->type)) {
7483 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7484 		u32 *max_access;
7485 
7486 		if (rdonly_mem) {
7487 			if (t == BPF_WRITE) {
7488 				verbose(env, "%s cannot write into %s\n",
7489 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7490 				return -EACCES;
7491 			}
7492 			max_access = &env->prog->aux->max_rdonly_access;
7493 		} else {
7494 			max_access = &env->prog->aux->max_rdwr_access;
7495 		}
7496 
7497 		err = check_buffer_access(env, reg, argno, off, size, false,
7498 					  max_access, t == BPF_WRITE);
7499 
7500 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7501 			mark_reg_unknown(env, regs, value_regno);
7502 	} else if (reg->type == PTR_TO_ARENA) {
7503 		if (t == BPF_READ && value_regno >= 0)
7504 			mark_reg_unknown(env, regs, value_regno);
7505 	} else {
7506 		enum bpf_diag_invalid_deref_kind kind = BPF_DIAG_DEREF_INVALID_PTR;
7507 
7508 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7509 			reg_type_str(env, reg->type));
7510 		if (reg->type == SCALAR_VALUE)
7511 			kind = BPF_DIAG_DEREF_SCALAR;
7512 		else if (type_may_be_null(reg->type))
7513 			kind = BPF_DIAG_DEREF_NULLABLE_PTR;
7514 		bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7515 				       reg_arg_name(env, argno), reg, kind, 0);
7516 		return -EACCES;
7517 	}
7518 
7519 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7520 	    regs[value_regno].type == SCALAR_VALUE) {
7521 		if (!is_ldsx) {
7522 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7523 			coerce_reg_to_size(&regs[value_regno], size);
7524 		} else {
7525 			/*
7526 			 * Sign-extension can change the register value relative
7527 			 * to a scalar it is linked with by id (e.g. a zero-
7528 			 * extending fill of the same spilled stack slot), thus
7529 			 * drop the shared id in that case.
7530 			 */
7531 			bool no_sext = reg_umax(&regs[value_regno]) <
7532 					(1ULL << (size * BITS_PER_BYTE - 1));
7533 
7534 			coerce_reg_to_size_sx(&regs[value_regno], size);
7535 			if (!no_sext)
7536 				clear_scalar_id(&regs[value_regno]);
7537 		}
7538 	}
7539 
7540 	if (!err && bpf_is_mem_insn(&env->prog->insnsi[insn_idx]) && ptr_type != PTR_TO_STACK)
7541 		mark_non_stack_access(env, insn_idx);
7542 
7543 	return err;
7544 }
7545 
7546 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7547 			     bool allow_trust_mismatch);
7548 
7549 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7550 			  bool strict_alignment_once, bool is_ldsx,
7551 			  bool allow_trust_mismatch, const char *ctx)
7552 {
7553 	struct bpf_verifier_state *vstate = env->cur_state;
7554 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7555 	struct bpf_reg_state *regs = cur_regs(env);
7556 	enum bpf_reg_type src_reg_type;
7557 	int err;
7558 
7559 	/* Handle stack arg read */
7560 	if (is_stack_arg_ldx(insn)) {
7561 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7562 		if (err)
7563 			return err;
7564 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
7565 	}
7566 
7567 	/* check src operand */
7568 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7569 	if (err)
7570 		return err;
7571 
7572 	/* check dst operand */
7573 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7574 	if (err)
7575 		return err;
7576 
7577 	src_reg_type = regs[insn->src_reg].type;
7578 
7579 	/*
7580 	 * check_stack_read_fixed_off() may refine the modification's origin to
7581 	 * the source stack slot.
7582 	 */
7583 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
7584 	err = check_mem_access(env, env->insn_idx, regs + insn->src_reg,
7585 			       argno_from_reg(insn->src_reg), insn->off,
7586 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7587 			       strict_alignment_once, is_ldsx);
7588 	/*
7589 	 * Paths through a kernel struct pointer and through other pointers
7590 	 * may share the insn, see save_aux_ptr_type(). Record a load that did
7591 	 * not produce an arena pointer from an __arena member, the only load
7592 	 * through a kernel struct pointer that does, next to the one
7593 	 * check_arena_member_load() records, so that arena_member_fixup() can
7594 	 * tell when the paths disagree.
7595 	 */
7596 	if (!err && !(base_type(src_reg_type) == PTR_TO_BTF_ID &&
7597 		      regs[insn->dst_reg].type == PTR_TO_ARENA))
7598 		env->insn_aux_data[env->insn_idx].non_arena_load = true;
7599 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7600 				       allow_trust_mismatch);
7601 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7602 	if (!err)
7603 		bpf_diag_mod_end(env);
7604 
7605 	return err;
7606 }
7607 
7608 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7609 			   bool strict_alignment_once)
7610 {
7611 	struct bpf_verifier_state *vstate = env->cur_state;
7612 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7613 	struct bpf_reg_state *regs = cur_regs(env);
7614 	enum bpf_reg_type dst_reg_type;
7615 	int err;
7616 
7617 	/* Handle stack arg write */
7618 	if (is_stack_arg_stx(insn)) {
7619 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
7620 		if (err)
7621 			return err;
7622 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
7623 	}
7624 
7625 	/* check src1 operand */
7626 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7627 	if (err)
7628 		return err;
7629 
7630 	/* check src2 operand */
7631 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7632 	if (err)
7633 		return err;
7634 
7635 	dst_reg_type = regs[insn->dst_reg].type;
7636 
7637 	/* Check if (dst_reg + off) is writeable. */
7638 	err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg,
7639 			       argno_from_reg(insn->dst_reg), insn->off,
7640 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7641 			       strict_alignment_once, false);
7642 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7643 
7644 	return err;
7645 }
7646 
7647 static int check_atomic_rmw(struct bpf_verifier_env *env,
7648 			    struct bpf_insn *insn)
7649 {
7650 	struct bpf_reg_state *dst_reg;
7651 	int load_reg;
7652 	int err;
7653 
7654 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7655 		verbose(env, "invalid atomic operand size\n");
7656 		return -EINVAL;
7657 	}
7658 
7659 	/* check src1 operand */
7660 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7661 	if (err)
7662 		return err;
7663 
7664 	/* check src2 operand */
7665 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7666 	if (err)
7667 		return err;
7668 
7669 	if (insn->imm == BPF_CMPXCHG) {
7670 		/* Check comparison of R0 with memory location */
7671 		const u32 aux_reg = BPF_REG_0;
7672 
7673 		err = check_reg_arg(env, aux_reg, SRC_OP);
7674 		if (err)
7675 			return err;
7676 
7677 		if (is_pointer_value(env, aux_reg)) {
7678 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7679 			return -EACCES;
7680 		}
7681 	}
7682 
7683 	if (is_pointer_value(env, insn->src_reg)) {
7684 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7685 		return -EACCES;
7686 	}
7687 
7688 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7689 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7690 			insn->dst_reg,
7691 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7692 		return -EACCES;
7693 	}
7694 
7695 	load_reg = bpf_atomic_load_reg(insn);
7696 	if (load_reg >= 0) {
7697 		/* check and record load of old value */
7698 		err = check_reg_arg(env, load_reg, DST_OP);
7699 		if (err)
7700 			return err;
7701 	}
7702 
7703 	dst_reg = cur_regs(env) + insn->dst_reg;
7704 
7705 	/* Check whether we can read the memory, with second call for fetch
7706 	 * case to simulate the register fill.
7707 	 */
7708 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7709 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7710 	if (!err && load_reg >= 0) {
7711 		bpf_diag_mod_begin(env, cur_regs(env) + load_reg, NULL, BPF_DIAG_MOD_WRITE);
7712 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
7713 				       insn->off, BPF_SIZE(insn->code),
7714 				       BPF_READ, load_reg, true, false);
7715 		if (!err)
7716 			bpf_diag_mod_end(env);
7717 	}
7718 	if (err)
7719 		return err;
7720 
7721 	err = save_aux_ptr_type(env, dst_reg->type, false);
7722 	if (err)
7723 		return err;
7724 	/* Check whether we can write into the same memory. */
7725 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7726 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7727 	if (err)
7728 		return err;
7729 	return 0;
7730 }
7731 
7732 static int check_atomic_load(struct bpf_verifier_env *env,
7733 			     struct bpf_insn *insn)
7734 {
7735 	int err;
7736 
7737 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7738 	if (err)
7739 		return err;
7740 
7741 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7742 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7743 			insn->src_reg,
7744 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7745 		return -EACCES;
7746 	}
7747 
7748 	return check_load_mem(env, insn, true, false, false, "atomic_load");
7749 }
7750 
7751 static int check_atomic_store(struct bpf_verifier_env *env,
7752 			      struct bpf_insn *insn)
7753 {
7754 	int err;
7755 
7756 	err = check_store_reg(env, insn, true);
7757 	if (err)
7758 		return err;
7759 
7760 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7761 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7762 			insn->dst_reg,
7763 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7764 		return -EACCES;
7765 	}
7766 
7767 	return 0;
7768 }
7769 
7770 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7771 {
7772 	switch (insn->imm) {
7773 	case BPF_ADD:
7774 	case BPF_ADD | BPF_FETCH:
7775 	case BPF_AND:
7776 	case BPF_AND | BPF_FETCH:
7777 	case BPF_OR:
7778 	case BPF_OR | BPF_FETCH:
7779 	case BPF_XOR:
7780 	case BPF_XOR | BPF_FETCH:
7781 	case BPF_XCHG:
7782 	case BPF_CMPXCHG:
7783 		return check_atomic_rmw(env, insn);
7784 	case BPF_LOAD_ACQ:
7785 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7786 			verbose(env,
7787 				"64-bit load-acquires are only supported on 64-bit arches\n");
7788 			return -EOPNOTSUPP;
7789 		}
7790 		return check_atomic_load(env, insn);
7791 	case BPF_STORE_REL:
7792 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7793 			verbose(env,
7794 				"64-bit store-releases are only supported on 64-bit arches\n");
7795 			return -EOPNOTSUPP;
7796 		}
7797 		return check_atomic_store(env, insn);
7798 	default:
7799 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7800 			insn->imm);
7801 		return -EINVAL;
7802 	}
7803 }
7804 
7805 /* When register 'regno' is used to read the stack (either directly or through
7806  * a helper function) make sure that it's within stack boundary and, depending
7807  * on the access type and privileges, that all elements of the stack are
7808  * initialized.
7809  *
7810  * All registers that have been spilled on the stack in the slots within the
7811  * read offsets are marked as read.
7812  */
7813 static int check_stack_range_initialized(
7814 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
7815 		int access_size, bool zero_size_allowed,
7816 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7817 {
7818 	struct bpf_func_state *state = bpf_func(env, reg);
7819 	int err, min_off, max_off, i, j, slot, spi;
7820 	/* Some accesses can write anything into the stack, others are
7821 	 * read-only.
7822 	 */
7823 	bool clobber = type == BPF_WRITE;
7824 	/*
7825 	 * Negative access_size signals global subprog arg check where
7826 	 * STACK_POISON slots are acceptable. static stack liveness
7827 	 * might have determined that subprog doesn't read them,
7828 	 * but BTF based global subprog validation isn't accurate enough.
7829 	 */
7830 	bool allow_poison = access_size < 0 || clobber;
7831 	u32 arg_slot = arg_slot_from_argno(argno);
7832 	bool uninit = clobber && meta && arg_slot < MAX_BPF_FUNC_ARGS &&
7833 		      (meta->arg_raw_mem.mask & BIT(arg_slot));
7834 	bool raw_mode = uninit && env->allow_uninit_stack &&
7835 			!(meta->arg_raw_mem.var_size_mask & BIT(arg_slot));
7836 
7837 	access_size = abs(access_size);
7838 
7839 	if (access_size == 0 && !zero_size_allowed) {
7840 		verbose(env, "invalid zero-sized read\n");
7841 		return -EACCES;
7842 	}
7843 
7844 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
7845 	if (err)
7846 		return err;
7847 
7848 	if (tnum_is_const(reg->var_off)) {
7849 		min_off = max_off = reg->var_off.value + off;
7850 	} else {
7851 		/* Variable offset is prohibited for unprivileged mode for
7852 		 * simplicity since it requires corresponding support in
7853 		 * Spectre masking for stack ALU.
7854 		 * See also retrieve_ptr_limit().
7855 		 */
7856 		if (!env->bypass_spec_v1) {
7857 			char tn_buf[48];
7858 
7859 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7860 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
7861 				reg_arg_name(env, argno), tn_buf);
7862 			return -EACCES;
7863 		}
7864 		/*
7865 		 * The call may touch any byte in the possible range, but does not
7866 		 * definitely initialize all of it. Fall back to ordinary stack checks.
7867 		 */
7868 		raw_mode = false;
7869 
7870 		min_off = reg_smin(reg) + off;
7871 		max_off = reg_smax(reg) + off;
7872 	}
7873 
7874 	/* Unprivileged outputs retain each byte's initialization state. */
7875 	if (raw_mode) {
7876 		meta->arg_raw_mem.size[arg_slot] = access_size;
7877 		return 0;
7878 	}
7879 
7880 	for (i = min_off; i < max_off + access_size; i++) {
7881 		struct bpf_stack_state *ss;
7882 		u8 *stype;
7883 
7884 		slot = -i - 1;
7885 		spi = slot / BPF_REG_SIZE;
7886 		if (state->allocated_stack <= slot) {
7887 			verbose(env, "allocated_stack too small\n");
7888 			return -EFAULT;
7889 		}
7890 
7891 		ss = bpf_stack_slot(state, spi);
7892 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
7893 		if (*stype == STACK_MISC)
7894 			goto mark;
7895 		if ((*stype == STACK_ZERO) ||
7896 		    (*stype == STACK_INVALID && (uninit || env->allow_uninit_stack))) {
7897 			if (clobber && (*stype != STACK_INVALID || env->allow_uninit_stack)) {
7898 				/* helper can write anything into the stack */
7899 				*stype = STACK_MISC;
7900 			}
7901 			goto mark;
7902 		}
7903 
7904 		/*
7905 		 * Only the bytes marked STACK_SPILL hold the spilled register.
7906 		 * The rest of a narrowly spilled slot keeps its previous type
7907 		 * and must be initialized on its own.
7908 		 */
7909 		if (*stype == STACK_SPILL &&
7910 		    (ss->spilled_ptr.type == SCALAR_VALUE ||
7911 		     env->allow_ptr_leaks)) {
7912 			if (clobber) {
7913 				__mark_reg_unknown(env, &ss->spilled_ptr);
7914 				for (j = 0; j < BPF_REG_SIZE; j++)
7915 					scrub_spilled_slot(&ss->slot_type[j]);
7916 			}
7917 			goto mark;
7918 		}
7919 
7920 		if (*stype == STACK_POISON) {
7921 			if (allow_poison) {
7922 				if (uninit && env->allow_uninit_stack)
7923 					*stype = STACK_MISC;
7924 				goto mark;
7925 			}
7926 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
7927 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7928 		} else if (tnum_is_const(reg->var_off)) {
7929 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
7930 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7931 		} else {
7932 			char tn_buf[48];
7933 
7934 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7935 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
7936 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
7937 		}
7938 		return -EACCES;
7939 mark:
7940 		;
7941 	}
7942 	return 0;
7943 }
7944 
7945 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7946 				   argno_t argno, int access_size,
7947 				   enum bpf_access_type access_type, bool zero_size_allowed,
7948 				   struct bpf_call_arg_meta *meta, bool *known_memory)
7949 {
7950 	struct bpf_reg_state *regs = cur_regs(env);
7951 	u32 *max_access;
7952 
7953 	if (known_memory)
7954 		*known_memory = true;
7955 
7956 	switch (base_type(reg->type)) {
7957 	case PTR_TO_PACKET:
7958 	case PTR_TO_PACKET_META:
7959 		if (!may_access_direct_pkt_data(env, meta, access_type)) {
7960 			verbose(env, "function access to the packet is not allowed\n");
7961 			return -EACCES;
7962 		}
7963 		return check_packet_access(env, reg, argno, 0, access_size,
7964 					   zero_size_allowed);
7965 	case PTR_TO_MAP_KEY:
7966 		if (access_type == BPF_WRITE) {
7967 			verbose(env, "%s cannot write into %s\n",
7968 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7969 			return -EACCES;
7970 		}
7971 		return check_mem_region_access(env, reg, argno, 0, access_size,
7972 					       reg->map_ptr->key_size, false);
7973 	case PTR_TO_MAP_VALUE:
7974 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY && !env->allow_ptr_leaks) {
7975 			verbose(env, "%s leaks addr from insn_array\n", reg_arg_name(env, argno));
7976 			return -EACCES;
7977 		}
7978 		if (check_map_access_type(env, reg, 0, access_size, access_type))
7979 			return -EACCES;
7980 		return check_map_access(env, reg, argno, 0, access_size,
7981 					zero_size_allowed, ACCESS_HELPER);
7982 	case PTR_TO_MEM:
7983 		if (type_is_rdonly_mem(reg->type)) {
7984 			if (access_type == BPF_WRITE) {
7985 				verbose(env, "%s cannot write into %s\n",
7986 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7987 				return -EACCES;
7988 			}
7989 		}
7990 		return check_mem_region_access(env, reg, argno, 0,
7991 					       access_size, reg->mem_size,
7992 					       zero_size_allowed);
7993 	case PTR_TO_BUF:
7994 		if (type_is_rdonly_mem(reg->type)) {
7995 			if (access_type == BPF_WRITE) {
7996 				verbose(env, "%s cannot write into %s\n",
7997 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7998 				return -EACCES;
7999 			}
8000 
8001 			max_access = &env->prog->aux->max_rdonly_access;
8002 		} else {
8003 			max_access = &env->prog->aux->max_rdwr_access;
8004 		}
8005 		return check_buffer_access(env, reg, argno, 0,
8006 					   access_size, zero_size_allowed,
8007 					   max_access, access_type == BPF_WRITE);
8008 	case PTR_TO_STACK:
8009 		return check_stack_range_initialized(
8010 				env, reg,
8011 				argno, 0, access_size,
8012 				zero_size_allowed, access_type, meta);
8013 	case PTR_TO_BTF_ID:
8014 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
8015 					       access_size, access_type, -1);
8016 	case PTR_TO_CTX:
8017 		/* Only permit reading or writing syscall context using helper calls. */
8018 		if (is_var_ctx_off_allowed(env->prog)) {
8019 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
8020 							  zero_size_allowed);
8021 			if (err)
8022 				return err;
8023 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
8024 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
8025 			return 0;
8026 		}
8027 		fallthrough;
8028 	default: /* scalar_value or invalid ptr */
8029 		/* Allow zero-byte read from NULL, regardless of pointer type */
8030 		if (zero_size_allowed && access_size == 0 &&
8031 		    bpf_register_is_null(reg))
8032 			return 0;
8033 		if (known_memory && base_type(reg->type) != PTR_TO_CTX)
8034 			*known_memory = false;
8035 
8036 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
8037 			reg_type_str(env, reg->type));
8038 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8039 		return -EACCES;
8040 	}
8041 }
8042 
8043 enum bpf_mem_size_failure {
8044 	BPF_MEM_SIZE_FAIL_NONE,
8045 	BPF_MEM_SIZE_FAIL_MEMORY,
8046 	BPF_MEM_SIZE_FAIL_SIZE,
8047 };
8048 
8049 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8050  * size.
8051  *
8052  * @mem_reg contains the pointer, @size_reg contains the access size.
8053  */
8054 static int check_mem_size_reg(struct bpf_verifier_env *env,
8055 			      struct bpf_reg_state *mem_reg,
8056 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
8057 			      argno_t size_argno, u32 access_type,
8058 			      bool zero_size_allowed,
8059 			      struct bpf_call_arg_meta *meta,
8060 			      enum bpf_mem_size_failure *failure)
8061 {
8062 	int err = 0;
8063 
8064 	if (failure)
8065 		*failure = BPF_MEM_SIZE_FAIL_NONE;
8066 
8067 	/* This is used to refine r0 return value bounds for helpers
8068 	 * that enforce this value as an upper bound on return values.
8069 	 * See do_refine_retval_range() for helpers that can refine
8070 	 * the return value. C type of helper is u32 so we pull register
8071 	 * bound from umax_value however, if negative verifier errors
8072 	 * out. Only upper bounds can be learned because retval is an
8073 	 * int type and negative retvals are allowed.
8074 	 */
8075 	meta->msize_max_value = reg_umax(size_reg);
8076 
8077 	/*
8078 	 * Check variable ranges byte by byte instead of using raw mode. Keep the
8079 	 * MEM_UNINIT annotation so invalid bytes are accepted without marking them
8080 	 * initialized when the caller cannot read uninitialized stack memory.
8081 	 */
8082 	if (!tnum_is_const(size_reg->var_off))
8083 		meta->arg_raw_mem.var_size_mask |= BIT(arg_slot_from_argno(mem_argno));
8084 
8085 	if (reg_smin(size_reg) < 0) {
8086 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
8087 			reg_arg_name(env, size_argno));
8088 		err = -EACCES;
8089 		goto size_error;
8090 	}
8091 
8092 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
8093 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
8094 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
8095 		err = -EACCES;
8096 		goto size_error;
8097 	}
8098 
8099 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
8100 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8101 			reg_arg_name(env, size_argno));
8102 		err = -EACCES;
8103 		goto size_error;
8104 	}
8105 
8106 	if (access_type & BPF_READ)
8107 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
8108 					      BPF_READ, zero_size_allowed, meta, NULL);
8109 	if (!err && access_type & BPF_WRITE)
8110 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
8111 					      BPF_WRITE, zero_size_allowed, meta, NULL);
8112 	if (err && failure)
8113 		*failure = BPF_MEM_SIZE_FAIL_MEMORY;
8114 
8115 	if (!err)
8116 		err = mark_arg_precision(env, size_argno);
8117 
8118 	return err;
8119 
8120 size_error:
8121 	if (failure)
8122 		*failure = BPF_MEM_SIZE_FAIL_SIZE;
8123 	return err;
8124 }
8125 
8126 static bool is_subprog(const struct bpf_call_arg_meta *meta)
8127 {
8128 	return meta->btf && !meta->func_id;
8129 }
8130 
8131 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8132 			 argno_t argno, u32 mem_size, enum bpf_access_type access_type,
8133 			 struct bpf_call_arg_meta *meta, bool *known_memory)
8134 {
8135 	int size, err = 0;
8136 
8137 	if (bpf_register_is_null(reg))
8138 		return mark_arg_precision(env, argno);
8139 	if (known_memory)
8140 		*known_memory = true;
8141 
8142 	if (mem_size > S32_MAX) {
8143 		verbose(env, "%s memory size %u is too large\n",
8144 			reg_arg_name(env, argno), mem_size);
8145 		return -EACCES;
8146 	}
8147 
8148 	/*
8149 	 * Only a global subprog may read poisoned stack slots:
8150 	 * its static stack liveness proved the callee body skips them.
8151 	 */
8152 	size = (is_subprog(meta) &&
8153 		base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size;
8154 
8155 	if (access_type & BPF_READ)
8156 		err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta,
8157 					      known_memory);
8158 	if (!err && (access_type & BPF_WRITE))
8159 		err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta,
8160 					      known_memory);
8161 
8162 	return err;
8163 }
8164 
8165 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8166 					argno_t argno, struct ret_mem_desc *ret_mem)
8167 {
8168 	int regno = reg_from_argno(argno);
8169 	int err;
8170 
8171 	if (ret_mem->found) {
8172 		verifier_bug(env, "only one allocation size argument permitted");
8173 		return -EFAULT;
8174 	}
8175 
8176 	if (!tnum_is_const(reg->var_off)) {
8177 		verbose(env, "%s is not a const\n", reg_arg_name(env, argno));
8178 		return -EINVAL;
8179 	}
8180 
8181 	if (reg->var_off.value > U32_MAX) {
8182 		verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno));
8183 		return -EINVAL;
8184 	}
8185 
8186 	if (regno >= 0)
8187 		err = mark_chain_precision(env, regno);
8188 	else
8189 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8190 	if (err)
8191 		return err;
8192 
8193 	ret_mem->size = reg->var_off.value;
8194 	ret_mem->found = true;
8195 
8196 	return 0;
8197 }
8198 
8199 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8200 			     argno_t argno, struct bpf_call_arg_meta *meta)
8201 {
8202 	int regno = reg_from_argno(argno);
8203 	int err;
8204 
8205 	if (meta->arg_constant.found) {
8206 		verifier_bug(env, "only one constant argument permitted");
8207 		return -EFAULT;
8208 	}
8209 
8210 	if (!tnum_is_const(reg->var_off)) {
8211 		verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno));
8212 		return -EINVAL;
8213 	}
8214 
8215 	if (regno >= 0)
8216 		err = mark_chain_precision(env, regno);
8217 	else
8218 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8219 	if (err < 0)
8220 		return err;
8221 
8222 	meta->arg_constant.found = true;
8223 	meta->arg_constant.value = reg->var_off.value;
8224 
8225 	return 0;
8226 }
8227 
8228 enum {
8229 	PROCESS_SPIN_LOCK = (1 << 0),
8230 	PROCESS_RES_LOCK  = (1 << 1),
8231 	PROCESS_LOCK_IRQ  = (1 << 2),
8232 };
8233 
8234 /* Implementation details:
8235  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8236  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8237  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8238  * Two separate bpf_obj_new will also have different reg->id.
8239  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8240  * clears reg->id after value_or_null->value transition, since the verifier only
8241  * cares about the range of access to valid map value pointer and doesn't care
8242  * about actual address of the map element.
8243  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8244  * reg->id > 0 after value_or_null->value transition. By doing so
8245  * two bpf_map_lookups will be considered two different pointers that
8246  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8247  * returned from bpf_obj_new.
8248  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8249  * dead-locks.
8250  * Since only one bpf_spin_lock is allowed the checks are simpler than
8251  * reg_is_refcounted() logic. The verifier needs to remember only
8252  * one spin_lock instead of array of acquired_refs.
8253  * env->cur_state->active_locks remembers which map value element or allocated
8254  * object got locked and clears it after bpf_spin_unlock.
8255  */
8256 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
8257 {
8258 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8259 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8260 	struct bpf_verifier_state *cur = env->cur_state;
8261 	struct bpf_reference_state *lock;
8262 	bool is_const = tnum_is_const(reg->var_off);
8263 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8264 	u64 val = reg->var_off.value;
8265 	struct bpf_map *map = NULL;
8266 	struct btf *btf = NULL;
8267 	struct btf_record *rec;
8268 	u32 spin_lock_off;
8269 	int err;
8270 
8271 	if (!is_const) {
8272 		verbose(env,
8273 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
8274 			reg_arg_name(env, argno), lock_str);
8275 		return -EINVAL;
8276 	}
8277 	if (reg->type == PTR_TO_MAP_VALUE) {
8278 		map = reg->map_ptr;
8279 		if (!map->btf) {
8280 			verbose(env,
8281 				"map '%s' has to have BTF in order to use %s_lock\n",
8282 				map->name, lock_str);
8283 			return -EINVAL;
8284 		}
8285 	} else {
8286 		btf = reg->btf;
8287 	}
8288 
8289 	rec = reg_btf_record(reg);
8290 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8291 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8292 			map ? map->name : "kptr", lock_str);
8293 		return -EINVAL;
8294 	}
8295 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8296 	if (spin_lock_off != val) {
8297 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8298 			val, lock_str, spin_lock_off);
8299 		return -EINVAL;
8300 	}
8301 	if (is_lock) {
8302 		void *ptr;
8303 		int type;
8304 
8305 		if (map)
8306 			ptr = map;
8307 		else
8308 			ptr = btf;
8309 
8310 		if (!is_res_lock && cur->active_locks) {
8311 			lock = find_lock_state(cur, REF_TYPE_LOCK, 0, NULL);
8312 			if (lock) {
8313 				verbose(env,
8314 					"Locking two bpf_spin_locks are not allowed\n");
8315 				bpf_diag_lock(
8316 					env, env->insn_idx, "nested spin lock",
8317 					"This path already holds a bpf_spin_lock. The verifier allows only one regular BPF spin lock at a time.",
8318 					"Unlock the current bpf_spin_lock before taking another one.", lock);
8319 				return -EINVAL;
8320 			}
8321 		} else if (is_res_lock && cur->active_locks) {
8322 			lock = find_lock_state(cur, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
8323 					       reg->id, ptr);
8324 			if (lock) {
8325 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8326 				bpf_diag_lock(
8327 					env, env->insn_idx, "recursive resource spin lock",
8328 					"This path already holds the same resource spin lock. Taking it again would deadlock.",
8329 					"Avoid reacquiring the same resource spin lock before it is unlocked.", lock);
8330 				return -EINVAL;
8331 			}
8332 		}
8333 
8334 		if (is_res_lock && is_irq)
8335 			type = REF_TYPE_RES_LOCK_IRQ;
8336 		else if (is_res_lock)
8337 			type = REF_TYPE_RES_LOCK;
8338 		else
8339 			type = REF_TYPE_LOCK;
8340 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8341 		if (err < 0) {
8342 			verbose(env, "Failed to acquire lock state\n");
8343 			return err;
8344 		}
8345 	} else {
8346 		void *ptr;
8347 		int type;
8348 
8349 		if (map)
8350 			ptr = map;
8351 		else
8352 			ptr = btf;
8353 
8354 		if (!cur->active_locks) {
8355 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8356 			bpf_diag_res(
8357 				env, env->insn_idx, "unlock without lock",
8358 				"This unlock operation has no matching active lock on the current path.",
8359 				"Take the matching lock before this unlock, or remove the unmatched unlock path.");
8360 			return -EINVAL;
8361 		}
8362 
8363 		if (is_res_lock && is_irq)
8364 			type = REF_TYPE_RES_LOCK_IRQ;
8365 		else if (is_res_lock)
8366 			type = REF_TYPE_RES_LOCK;
8367 		else
8368 			type = REF_TYPE_LOCK;
8369 
8370 		lock = find_lock_state(cur, type, reg->id, ptr);
8371 		if (!lock) {
8372 			verbose(env, "%s_unlock of different lock\n", lock_str);
8373 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8374 					       cur->active_lock_ptr);
8375 			bpf_diag_lock(
8376 				env, env->insn_idx, "unlock of a different lock",
8377 				"This unlock does not match any active lock with the same tracked identity on the current path.",
8378 				"Unlock the same lock object that was most recently acquired.", lock);
8379 			return -EINVAL;
8380 		}
8381 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8382 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8383 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8384 					       cur->active_lock_ptr);
8385 			bpf_diag_lock(
8386 				env, env->insn_idx, "unlock out of order",
8387 				"Locks must be released in last-in, first-out order, but this unlock does not match the currently active lock.",
8388 				"Release nested locks in the reverse order they were acquired.", lock);
8389 			return -EINVAL;
8390 		}
8391 		if (release_lock_state(env, type, reg->id, ptr)) {
8392 			verbose(env, "%s_unlock of different lock\n", lock_str);
8393 			bpf_diag_lock(
8394 				env, env->insn_idx, "unlock of a different lock",
8395 				"The verifier could not release a lock state matching this unlock operation.",
8396 				"Pass the same lock object and lock kind that were used for the matching lock operation.",
8397 				lock);
8398 			return -EINVAL;
8399 		}
8400 		/*
8401 		 * Invalidate non-owning refs before RCU demotion clears their
8402 		 * NON_OWN_REF flag.
8403 		 */
8404 		invalidate_non_owning_refs(env);
8405 
8406 		if (!in_rcu_cs(env))
8407 			invalidate_rcu_protected_refs(env);
8408 	}
8409 	return 0;
8410 }
8411 
8412 /* Check if @regno is a pointer to a specific field in a map value */
8413 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8414 				   enum btf_field_type field_type,
8415 				   struct bpf_map_desc *map_desc)
8416 {
8417 	bool is_const = tnum_is_const(reg->var_off);
8418 	struct bpf_map *map = reg->map_ptr;
8419 	u64 val = reg->var_off.value;
8420 	const char *struct_name = btf_field_type_name(field_type);
8421 	int field_off = -1;
8422 
8423 	if (!is_const) {
8424 		verbose(env,
8425 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
8426 			reg_arg_name(env, argno), struct_name);
8427 		return -EINVAL;
8428 	}
8429 	if (!map->btf) {
8430 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8431 			struct_name);
8432 		return -EINVAL;
8433 	}
8434 	if (!btf_record_has_field(map->record, field_type)) {
8435 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8436 		return -EINVAL;
8437 	}
8438 	switch (field_type) {
8439 	case BPF_TIMER:
8440 		field_off = map->record->timer_off;
8441 		break;
8442 	case BPF_TASK_WORK:
8443 		field_off = map->record->task_work_off;
8444 		break;
8445 	case BPF_RCU_HEAD:
8446 		field_off = map->record->rcu_head_off;
8447 		break;
8448 	case BPF_WORKQUEUE:
8449 		field_off = map->record->wq_off;
8450 		break;
8451 	default:
8452 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8453 		return -EINVAL;
8454 	}
8455 	if (field_off != val) {
8456 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8457 			val, struct_name, field_off);
8458 		return -EINVAL;
8459 	}
8460 	if (map_desc->ptr) {
8461 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
8462 		return -EFAULT;
8463 	}
8464 	map_desc->uid = reg->map_uid;
8465 	map_desc->ptr = map;
8466 	return 0;
8467 }
8468 
8469 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8470 			      struct bpf_map_desc *map)
8471 {
8472 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8473 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8474 		return -EOPNOTSUPP;
8475 	}
8476 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
8477 }
8478 
8479 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8480 			     struct bpf_call_arg_meta *meta)
8481 {
8482 	struct bpf_reg_state *reg = reg_state(env, regno);
8483 	struct btf_field *kptr_field;
8484 	struct bpf_map *map_ptr;
8485 	struct btf_record *rec;
8486 	u32 kptr_off;
8487 
8488 	if (type_is_ptr_alloc_obj(reg->type)) {
8489 		rec = reg_btf_record(reg);
8490 	} else { /* PTR_TO_MAP_VALUE */
8491 		map_ptr = reg->map_ptr;
8492 		if (!map_ptr->btf) {
8493 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8494 				map_ptr->name);
8495 			return -EINVAL;
8496 		}
8497 		rec = map_ptr->record;
8498 		meta->map.ptr = map_ptr;
8499 	}
8500 
8501 	if (!tnum_is_const(reg->var_off)) {
8502 		verbose(env,
8503 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8504 			regno);
8505 		return -EINVAL;
8506 	}
8507 
8508 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8509 		verbose(env, "R%d has no valid kptr\n", regno);
8510 		return -EINVAL;
8511 	}
8512 
8513 	kptr_off = reg->var_off.value;
8514 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8515 	if (!kptr_field) {
8516 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8517 		return -EACCES;
8518 	}
8519 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8520 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8521 		return -EACCES;
8522 	}
8523 	meta->kptr_field = kptr_field;
8524 	return 0;
8525 }
8526 
8527 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
8528 			      const char *call_name, const char *reason, const char *suggestion);
8529 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
8530 						 argno_t argno, const char *call_name,
8531 						 const char *suggestion, const char *fmt, ...);
8532 
8533 /*
8534  * Validate dynptr arguments for helper, kfunc and subprog.
8535  *
8536  * @meta carries the dynptr and referenced-object state. The dynptr is populated
8537  * when the argument is tagged with MEM_UNINIT (i.e., the dynptr argument that
8538  * will be constructed) and consumed when the argument is expected to be an
8539  * initialized dynptr. The reference tracks the parent object (e.g., file or skb
8540  * in qdisc program) when constructing a dynptr.
8541  *
8542  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8543  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8544  *
8545  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8546  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8547  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8548  *
8549  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
8550  * dynptr points to. At the first level, the verifier will make sure a
8551  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
8552  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
8553  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
8554  * and checked dynamically during runtime.
8555  */
8556 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8557 			       argno_t argno, int insn_idx, enum bpf_arg_type arg_type,
8558 			       struct bpf_call_arg_meta *meta)
8559 {
8560 	int spi, err = 0;
8561 
8562 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8563 	 *		 constructing a mutable bpf_dynptr object.
8564 	 *
8565 	 *		 Currently, this is only possible with PTR_TO_STACK
8566 	 *		 pointing to a region of at least 16 bytes which doesn't
8567 	 *		 contain an existing bpf_dynptr.
8568 	 *
8569 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
8570 	 *		  destroyed.
8571 	 *
8572 	 *  None       - Points to a initialized dynptr that cannot be
8573 	 *		 reinitialized or destroyed. However, the view of the
8574 	 *		 dynptr and the memory it points to may be mutated.
8575 	 */
8576 	if (arg_type & MEM_UNINIT) {
8577 		int i;
8578 
8579 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8580 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8581 			bpf_diag_res(
8582 				env, insn_idx, "dynptr is already initialized",
8583 				"This function constructs a dynptr and requires an uninitialized dynptr stack slot, but the selected slot already holds dynptr state.",
8584 				"Use a fresh stack dynptr slot, or release/destroy the existing dynptr before reusing the slot.");
8585 			return -EINVAL;
8586 		}
8587 
8588 		/* we write BPF_DW bits (8 bytes) at a time */
8589 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8590 			err = check_mem_access(env, insn_idx, reg, argno,
8591 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8592 			if (err)
8593 				return err;
8594 		}
8595 
8596 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx,
8597 					      &meta->ref_obj, &meta->dynptr);
8598 	} else /* OBJ_RELEASE and None case from above */ {
8599 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8600 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
8601 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
8602 			bpf_diag_res(
8603 				env, insn_idx, "const dynptr release",
8604 				"This release operation was given a const dynptr. Const dynptr values are verifier-provided views and cannot be released by the program.",
8605 				"Release only mutable dynptrs that the program initialized or reserved.");
8606 			return -EINVAL;
8607 		}
8608 
8609 		if (!is_dynptr_reg_valid_init(env, reg)) {
8610 			verbose(env, "Expected an initialized dynptr as %s\n",
8611 				reg_arg_name(env, argno));
8612 			bpf_diag_res(
8613 				env, insn_idx, "uninitialized dynptr use",
8614 				"This operation requires an initialized dynptr, but the stack slot does not currently hold a valid dynptr on this path.",
8615 				"Initialize the dynptr on every path before this call, and avoid overwriting or releasing it before this use.");
8616 			return -EINVAL;
8617 		}
8618 
8619 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
8620 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
8621 			enum bpf_dynptr_type expected_type = arg_to_dynptr_type(arg_type);
8622 			enum bpf_dynptr_type actual_type = dynptr_reg_type(env, reg);
8623 
8624 			verbose(env, "Expected a dynptr of type %s as %s\n",
8625 				dynptr_type_str(expected_type), reg_arg_name(env, argno));
8626 			bpf_diag_call_arg_fmt(
8627 				env, insn_idx, argno, meta->func_name,
8628 				"Use a dynptr constructor that matches this operation, or call an operation that accepts the dynptr's current type.",
8629 				"the dynptr is initialized with backing object type %s, but this operation expects dynptr type %s",
8630 				dynptr_type_str(actual_type), dynptr_type_str(expected_type));
8631 			return -EINVAL;
8632 		}
8633 
8634 		if (reg->type != CONST_PTR_TO_DYNPTR) {
8635 			struct bpf_func_state *state = bpf_func(env, reg);
8636 
8637 			spi = dynptr_get_spi(env, reg);
8638 			if (spi < 0)
8639 				return spi;
8640 
8641 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
8642 
8643 			reg = &bpf_stack_slot(state, spi)->spilled_ptr;
8644 		}
8645 
8646 		meta->dynptr.type = reg->dynptr.type;
8647 		meta->dynptr.id = reg->id;
8648 		meta->dynptr.parent_id = reg->parent_id;
8649 	}
8650 	return err;
8651 }
8652 
8653 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta)
8654 {
8655 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8656 }
8657 
8658 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta)
8659 {
8660 	return meta->kfunc_flags & KF_ITER_NEW;
8661 }
8662 
8663 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta)
8664 {
8665 	return meta->kfunc_flags & KF_ITER_DESTROY;
8666 }
8667 
8668 static bool iter_next_borrows_struct(struct bpf_call_arg_meta *meta)
8669 {
8670 	const struct btf_type *t;
8671 
8672 	if (!(meta->kfunc_flags & KF_ITER_NEXT) ||
8673 	    (meta->kfunc_flags & (KF_ITER_RET_INDEPENDENT | KF_ACQUIRE)))
8674 		return false;
8675 
8676 	t = btf_type_skip_modifiers(meta->btf, meta->func_proto->type, NULL);
8677 	if (!t || !btf_type_is_ptr(t))
8678 		return false;
8679 	t = btf_type_skip_modifiers(meta->btf, t->type, NULL);
8680 	return t && __btf_type_is_struct(t);
8681 }
8682 
8683 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx,
8684 			      const struct btf_param *arg)
8685 {
8686 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8687 	 * kfunc is iter state pointer
8688 	 */
8689 	if (is_iter_kfunc(meta))
8690 		return arg_idx == 0;
8691 
8692 	/* iter passed as an argument to a generic kfunc */
8693 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8694 }
8695 
8696 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8697 			    u32 arg, argno_t argno, int insn_idx,
8698 			    struct bpf_call_arg_meta *meta)
8699 {
8700 	struct bpf_func_state *state = bpf_func(env, reg);
8701 	const struct btf_type *t;
8702 	int spi, err, i, nr_slots, btf_id;
8703 
8704 	if (reg->type != PTR_TO_STACK) {
8705 		verbose(env, "%s expected pointer to an iterator on stack\n",
8706 			reg_arg_name(env, argno));
8707 		bpf_diag_call_arg_fmt(
8708 			env, insn_idx, argno, meta->func_name,
8709 			"Pass the address of a stack iterator object for iterator new, next, and destroy calls.",
8710 			"iterator state must live in verifier-tracked stack memory, but %s is %s",
8711 			reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type));
8712 		return -EINVAL;
8713 	}
8714 
8715 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8716 	 * ensures struct convention, so we wouldn't need to do any BTF
8717 	 * validation here. But given iter state can be passed as a parameter
8718 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8719 	 * conservative here.
8720 	 */
8721 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg);
8722 	if (btf_id < 0) {
8723 		verbose(env, "expected valid iter pointer as %s\n",
8724 			reg_arg_name(env, argno));
8725 		bpf_diag_call_arg(
8726 			env, insn_idx, argno, meta->func_name,
8727 			"the function expects a recognized iterator state pointer, but this argument does not match a valid iterator type",
8728 			"Pass the exact iterator state type expected by this function.");
8729 		return -EINVAL;
8730 	}
8731 	t = btf_type_by_id(meta->btf, btf_id);
8732 	nr_slots = t->size / BPF_REG_SIZE;
8733 
8734 	if (is_iter_new_kfunc(meta)) {
8735 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8736 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8737 			verbose(env, "expected uninitialized iter_%s as %s\n",
8738 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8739 			bpf_diag_res(
8740 				env, insn_idx, "iterator is already initialized",
8741 				"Iterator creation requires an uninitialized iterator stack object, but this stack range already contains iterator state.",
8742 				"Use a fresh iterator stack slot, or destroy the existing iterator before reusing the slot.");
8743 			return -EINVAL;
8744 		}
8745 
8746 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8747 			err = check_mem_access(env, insn_idx, reg, argno,
8748 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8749 			if (err)
8750 				return err;
8751 		}
8752 
8753 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8754 		if (err)
8755 			return err;
8756 	} else {
8757 		/* iter_next() or iter_destroy(), as well as any kfunc
8758 		 * accepting iter argument, expect initialized iter state
8759 		 */
8760 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8761 		switch (err) {
8762 		case 0:
8763 			break;
8764 		case -EINVAL:
8765 			verbose(env, "expected an initialized iter_%s as %s\n",
8766 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8767 			bpf_diag_res(
8768 				env, insn_idx, "uninitialized iterator use",
8769 				"This iterator operation requires an initialized iterator state object, but the stack range does not contain a live iterator on this path.",
8770 				"Call the matching iterator new kfunc on every path before calling next or destroy, and do not destroy the iterator before this use.");
8771 			return err;
8772 		case -EPROTO:
8773 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8774 			bpf_diag_ctx_required(
8775 				env, insn_idx, meta->func_name, BPF_DIAG_CONTEXT_RCU,
8776 				"Wrap iterator use in bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
8777 			return err;
8778 		default:
8779 			return err;
8780 		}
8781 
8782 		spi = iter_get_spi(env, reg, nr_slots);
8783 		if (spi < 0)
8784 			return spi;
8785 
8786 		mark_stack_slots_scratched(env, spi, nr_slots);
8787 
8788 		/* remember meta->iter info for process_iter_next_call() */
8789 		meta->iter.spi = spi;
8790 		meta->iter.frameno = reg->frameno;
8791 		update_ref_obj(&meta->ref_obj, &bpf_stack_slot(state, spi)->spilled_ptr);
8792 
8793 		/* The iterator stays. What was borrowed from the previous element goes. */
8794 		if (iter_next_borrows_struct(meta)) {
8795 			err = invalidate_reference(env, meta->ref_obj.id);
8796 			if (err)
8797 				return err;
8798 		}
8799 
8800 		if (is_iter_destroy_kfunc(meta)) {
8801 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8802 			if (err)
8803 				return err;
8804 		}
8805 	}
8806 
8807 	return 0;
8808 }
8809 
8810 /* Look for a previous loop entry at insn_idx: nearest parent state
8811  * stopped at insn_idx with callsites matching those in cur->frame.
8812  */
8813 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8814 						  struct bpf_verifier_state *cur,
8815 						  int insn_idx)
8816 {
8817 	struct bpf_verifier_state_list *sl;
8818 	struct bpf_verifier_state *st;
8819 	struct list_head *pos, *head;
8820 
8821 	/* Explored states are pushed in stack order, most recent states come first */
8822 	head = bpf_explored_state(env, insn_idx);
8823 	list_for_each(pos, head) {
8824 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8825 		/* If st->branches != 0 state is a part of current DFS verification path,
8826 		 * hence cur & st for a loop.
8827 		 */
8828 		st = &sl->state;
8829 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8830 		    st->dfs_depth < cur->dfs_depth)
8831 			return st;
8832 	}
8833 
8834 	return NULL;
8835 }
8836 
8837 /*
8838  * Check if scalar registers are exact for the purpose of not widening.
8839  * More lenient than regs_exact()
8840  */
8841 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
8842 				    const struct bpf_reg_state *rcur)
8843 {
8844 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
8845 }
8846 
8847 static void maybe_widen_reg(struct bpf_verifier_env *env,
8848 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
8849 {
8850 	if (rold->type != SCALAR_VALUE)
8851 		return;
8852 	if (rold->type != rcur->type)
8853 		return;
8854 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
8855 		return;
8856 	__mark_reg_unknown(env, rcur);
8857 }
8858 
8859 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8860 				   struct bpf_verifier_state *old,
8861 				   struct bpf_verifier_state *cur)
8862 {
8863 	struct bpf_func_state *fold, *fcur;
8864 	int i, fr, num_slots;
8865 
8866 	for (fr = old->curframe; fr >= 0; fr--) {
8867 		fold = old->frame[fr];
8868 		fcur = cur->frame[fr];
8869 
8870 		for (i = 0; i < MAX_BPF_REG; i++)
8871 			maybe_widen_reg(env,
8872 					&fold->regs[i],
8873 					&fcur->regs[i]);
8874 
8875 		num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur));
8876 		for (i = 0; i < num_slots; i++) {
8877 			struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i);
8878 			struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i);
8879 
8880 			if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss))
8881 				continue;
8882 
8883 			maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr);
8884 		}
8885 	}
8886 	return 0;
8887 }
8888 
8889 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8890 						 struct bpf_call_arg_meta *meta)
8891 {
8892 	int iter_frameno = meta->iter.frameno;
8893 	int iter_spi = meta->iter.spi;
8894 
8895 	return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr;
8896 }
8897 
8898 /* process_iter_next_call() is called when verifier gets to iterator's next
8899  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8900  * to it as just "iter_next()" in comments below.
8901  *
8902  * BPF verifier relies on a crucial contract for any iter_next()
8903  * implementation: it should *eventually* return NULL, and once that happens
8904  * it should keep returning NULL. That is, once iterator exhausts elements to
8905  * iterate, it should never reset or spuriously return new elements.
8906  *
8907  * With the assumption of such contract, process_iter_next_call() simulates
8908  * a fork in the verifier state to validate loop logic correctness and safety
8909  * without having to simulate infinite amount of iterations.
8910  *
8911  * In current state, we first assume that iter_next() returned NULL and
8912  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8913  * conditions we should not form an infinite loop and should eventually reach
8914  * exit.
8915  *
8916  * Besides that, we also fork current state and enqueue it for later
8917  * verification. In a forked state we keep iterator state as ACTIVE
8918  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8919  * also bump iteration depth to prevent erroneous infinite loop detection
8920  * later on (see iter_active_depths_differ() comment for details). In this
8921  * state we assume that we'll eventually loop back to another iter_next()
8922  * calls (it could be in exactly same location or in some other instruction,
8923  * it doesn't matter, we don't make any unnecessary assumptions about this,
8924  * everything revolves around iterator state in a stack slot, not which
8925  * instruction is calling iter_next()). When that happens, we either will come
8926  * to iter_next() with equivalent state and can conclude that next iteration
8927  * will proceed in exactly the same way as we just verified, so it's safe to
8928  * assume that loop converges. If not, we'll go on another iteration
8929  * simulation with a different input state, until all possible starting states
8930  * are validated or we reach maximum number of instructions limit.
8931  *
8932  * This way, we will either exhaustively discover all possible input states
8933  * that iterator loop can start with and eventually will converge, or we'll
8934  * effectively regress into bounded loop simulation logic and either reach
8935  * maximum number of instructions if loop is not provably convergent, or there
8936  * is some statically known limit on number of iterations (e.g., if there is
8937  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8938  *
8939  * Iteration convergence logic in is_state_visited() relies on exact
8940  * states comparison, which ignores read and precision marks.
8941  * This is necessary because read and precision marks are not finalized
8942  * while in the loop. Exact comparison might preclude convergence for
8943  * simple programs like below:
8944  *
8945  *     i = 0;
8946  *     while(iter_next(&it))
8947  *       i++;
8948  *
8949  * At each iteration step i++ would produce a new distinct state and
8950  * eventually instruction processing limit would be reached.
8951  *
8952  * To avoid such behavior speculatively forget (widen) range for
8953  * imprecise scalar registers, if those registers were not precise at the
8954  * end of the previous iteration and do not match exactly.
8955  *
8956  * This is a conservative heuristic that allows to verify wide range of programs,
8957  * however it precludes verification of programs that conjure an
8958  * imprecise value on the first loop iteration and use it as precise on a second.
8959  * For example, the following safe program would fail to verify:
8960  *
8961  *     struct bpf_num_iter it;
8962  *     int arr[10];
8963  *     int i = 0, a = 0;
8964  *     bpf_iter_num_new(&it, 0, 10);
8965  *     while (bpf_iter_num_next(&it)) {
8966  *       if (a == 0) {
8967  *         a = 1;
8968  *         i = 7; // Because i changed verifier would forget
8969  *                // it's range on second loop entry.
8970  *       } else {
8971  *         arr[i] = 42; // This would fail to verify.
8972  *       }
8973  *     }
8974  *     bpf_iter_num_destroy(&it);
8975  */
8976 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8977 				  struct bpf_call_arg_meta *meta)
8978 {
8979 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8980 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8981 	struct bpf_reg_state *cur_iter, *queued_iter;
8982 
8983 	BTF_TYPE_EMIT(struct bpf_iter);
8984 
8985 	cur_iter = get_iter_from_state(cur_st, meta);
8986 
8987 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8988 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8989 		verifier_bug(env, "unexpected iterator state %d (%s)",
8990 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8991 		return -EFAULT;
8992 	}
8993 
8994 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8995 		/* Because iter_next() call is a checkpoint is_state_visitied()
8996 		 * should guarantee parent state with same call sites and insn_idx.
8997 		 */
8998 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8999 		    !same_callsites(cur_st->parent, cur_st)) {
9000 			verifier_bug(env, "bad parent state for iter next call");
9001 			return -EFAULT;
9002 		}
9003 		/* Note cur_st->parent in the call below, it is necessary to skip
9004 		 * checkpoint created for cur_st by is_state_visited()
9005 		 * right at this instruction.
9006 		 */
9007 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9008 		/* branch out active iter state */
9009 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9010 		if (IS_ERR(queued_st))
9011 			return PTR_ERR(queued_st);
9012 
9013 		queued_iter = get_iter_from_state(queued_st, meta);
9014 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9015 		queued_iter->iter.depth++;
9016 		if (prev_st)
9017 			widen_imprecise_scalars(env, prev_st, queued_st);
9018 
9019 		queued_fr = queued_st->frame[queued_st->curframe];
9020 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9021 	}
9022 
9023 	/* switch to DRAINED state, but keep the depth unchanged */
9024 	/* mark current iter state as drained and assume returned NULL */
9025 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9026 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9027 
9028 	return 0;
9029 }
9030 
9031 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9032 {
9033 	return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO;
9034 }
9035 
9036 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9037 {
9038 	/*
9039 	 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw
9040 	 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be
9041 	 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized().
9042 	 */
9043 	return (base_type(type) == ARG_PTR_TO_MEM ||
9044 		base_type(type) == ARG_PTR_TO_MAP_VALUE) &&
9045 	       type & MEM_UNINIT;
9046 }
9047 
9048 static bool arg_type_is_release(enum bpf_arg_type type)
9049 {
9050 	return type & OBJ_RELEASE;
9051 }
9052 
9053 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9054 {
9055 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9056 }
9057 
9058 /*
9059  * An argument that only ever takes a scalar, so a zero register passed to it
9060  * is a value rather than a NULL pointer.
9061  */
9062 static bool arg_type_is_scalar(enum bpf_arg_type type)
9063 {
9064 	switch (base_type(type)) {
9065 	case ARG_SCALAR:
9066 	case ARG_CONST_SCALAR:
9067 	case ARG_MEM_SIZE:
9068 	case ARG_MEM_SIZE_OR_ZERO:
9069 	case ARG_CONST_MEM_SIZE:
9070 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9071 		return true;
9072 	default:
9073 		return false;
9074 	}
9075 }
9076 
9077 /*
9078  * A helper has no BTF and a nonzero function ID. A kfunc has both, while a
9079  * BPF subprogram has BTF and a zero function ID.
9080  */
9081 static bool is_helper(const struct bpf_call_arg_meta *meta)
9082 {
9083 	return !meta->btf && meta->func_id;
9084 }
9085 
9086 static bool is_helper_call(const struct bpf_call_arg_meta *meta, enum bpf_func_id func_id)
9087 {
9088 	return is_helper(meta) && meta->func_id == func_id;
9089 }
9090 
9091 static bool is_kfunc(const struct bpf_call_arg_meta *meta)
9092 {
9093 	return meta->btf && meta->func_id;
9094 }
9095 
9096 static bool is_kfunc_call(const struct bpf_call_arg_meta *meta, u32 btf_id)
9097 {
9098 	return is_kfunc(meta) && meta->func_id == btf_id;
9099 }
9100 
9101 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9102 				const struct bpf_call_arg_meta *meta,
9103 				enum bpf_arg_type *arg_type)
9104 {
9105 	if (!meta->map.ptr) {
9106 		/* kernel subsystem misconfigured verifier */
9107 		verifier_bug(env, "invalid map_ptr to access map->type");
9108 		return -EFAULT;
9109 	}
9110 
9111 	switch (meta->map.ptr->map_type) {
9112 	case BPF_MAP_TYPE_SOCKMAP:
9113 	case BPF_MAP_TYPE_SOCKHASH:
9114 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9115 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9116 		} else {
9117 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9118 			return -EINVAL;
9119 		}
9120 		break;
9121 	case BPF_MAP_TYPE_BLOOM_FILTER:
9122 		if (is_helper_call(meta, BPF_FUNC_map_peek_elem))
9123 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9124 		break;
9125 	default:
9126 		break;
9127 	}
9128 	return 0;
9129 }
9130 
9131 static int resolve_func_arg_type(struct bpf_verifier_env *env,
9132 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
9133 				 struct bpf_call_arg_meta *meta,
9134 				 enum bpf_arg_type *arg_type, u32 *arg_size);
9135 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9136 				     argno_t argno, enum bpf_arg_type arg_type,
9137 				     const struct btf *arg_btf, u32 arg_btf_id,
9138 				     struct bpf_call_arg_meta *meta, int insn_idx);
9139 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf,
9140 					const struct btf_param *arg);
9141 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9142 					  const struct btf_param *arg,
9143 					  const char *name);
9144 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta);
9145 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta);
9146 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta);
9147 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta);
9148 static bool is_bpf_obj_drop_kfunc(u32 func_id);
9149 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id);
9150 static bool is_bpf_rbtree_add_kfunc(u32 func_id);
9151 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta);
9152 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);
9153 static int process_irq_flag(struct bpf_verifier_env *env,
9154 			    struct bpf_reg_state *reg, argno_t argno,
9155 			    struct bpf_call_arg_meta *meta);
9156 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9157 					   struct bpf_reg_state *reg,
9158 					   argno_t argno,
9159 					   struct bpf_call_arg_meta *meta);
9160 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9161 					     struct bpf_reg_state *reg,
9162 					     argno_t argno,
9163 					     struct bpf_call_arg_meta *meta);
9164 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9165 					   struct bpf_reg_state *reg,
9166 					   argno_t argno,
9167 					   struct bpf_call_arg_meta *meta);
9168 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9169 					     struct bpf_reg_state *reg,
9170 					     argno_t argno,
9171 					     struct bpf_call_arg_meta *meta);
9172 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env);
9173 
9174 struct bpf_reg_types {
9175 	const enum bpf_reg_type types[10];
9176 	u32 *btf_id;
9177 };
9178 
9179 static const struct bpf_reg_types sock_types = {
9180 	.types = {
9181 		PTR_TO_SOCK_COMMON,
9182 		PTR_TO_SOCKET,
9183 		PTR_TO_TCP_SOCK,
9184 		PTR_TO_XDP_SOCK,
9185 	},
9186 };
9187 
9188 #ifdef CONFIG_NET
9189 static const struct bpf_reg_types btf_id_sock_common_types = {
9190 	.types = {
9191 		PTR_TO_SOCK_COMMON,
9192 		PTR_TO_SOCKET,
9193 		PTR_TO_TCP_SOCK,
9194 		PTR_TO_XDP_SOCK,
9195 		PTR_TO_BTF_ID,
9196 		PTR_TO_BTF_ID | PTR_TRUSTED,
9197 	},
9198 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9199 };
9200 #endif
9201 
9202 static const struct bpf_reg_types mem_types = {
9203 	.types = {
9204 		PTR_TO_STACK,
9205 		PTR_TO_PACKET,
9206 		PTR_TO_PACKET_META,
9207 		PTR_TO_MAP_KEY,
9208 		PTR_TO_MAP_VALUE,
9209 		PTR_TO_MEM,
9210 		PTR_TO_MEM | MEM_RINGBUF,
9211 		PTR_TO_BUF,
9212 		PTR_TO_BTF_ID | PTR_TRUSTED,
9213 		PTR_TO_CTX,
9214 	},
9215 };
9216 
9217 static const struct bpf_reg_types map_value_or_alloc_obj_types = {
9218 	.types = {
9219 		PTR_TO_MAP_VALUE,
9220 		PTR_TO_BTF_ID | MEM_ALLOC,
9221 	}
9222 };
9223 
9224 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9225 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9226 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9227 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9228 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9229 static const struct bpf_reg_types btf_ptr_types = {
9230 	.types = {
9231 		PTR_TO_BTF_ID,
9232 		PTR_TO_BTF_ID | PTR_TRUSTED,
9233 		PTR_TO_BTF_ID | MEM_RCU,
9234 	},
9235 };
9236 static const struct bpf_reg_types percpu_btf_ptr_types = {
9237 	.types = {
9238 		PTR_TO_BTF_ID | MEM_PERCPU,
9239 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9240 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9241 	}
9242 };
9243 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9244 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9245 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9246 static const struct bpf_reg_types map_value_types = { .types = { PTR_TO_MAP_VALUE } };
9247 static const struct bpf_reg_types arena_types = {
9248 	.types = {
9249 		PTR_TO_ARENA,
9250 		SCALAR_VALUE,
9251 	}
9252 };
9253 static const struct bpf_reg_types ctx_out_types = {
9254 	.types = { PTR_TO_MEM | MEM_RDONLY | PTR_TRUSTED },
9255 };
9256 
9257 static const struct bpf_reg_types alloc_obj_drop_types = {
9258 	.types = {
9259 		PTR_TO_BTF_ID | MEM_ALLOC,
9260 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU,
9261 	}
9262 };
9263 
9264 static const struct bpf_reg_types alloc_obj_types = {
9265 	.types = {
9266 		PTR_TO_BTF_ID | MEM_ALLOC,
9267 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU,
9268 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9269 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9270 	}
9271 };
9272 
9273 static const struct bpf_reg_types kptr_xchg_dest_types = {
9274 	.types = {
9275 		PTR_TO_MAP_VALUE,
9276 		PTR_TO_BTF_ID | MEM_ALLOC,
9277 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9278 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9279 	}
9280 };
9281 static const struct bpf_reg_types dynptr_types = {
9282 	.types = {
9283 		PTR_TO_STACK,
9284 		CONST_PTR_TO_DYNPTR,
9285 	}
9286 };
9287 
9288 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9289 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9290 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9291 	[ARG_MEM_SIZE]			= &scalar_types,
9292 	[ARG_MEM_SIZE_OR_ZERO]		= &scalar_types,
9293 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9294 	[ARG_SCALAR]			= &scalar_types,
9295 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9296 	[ARG_PTR_TO_CTX]		= &context_types,
9297 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9298 #ifdef CONFIG_NET
9299 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9300 #endif
9301 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9302 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9303 	[ARG_PTR_TO_SPIN_LOCK]		= &map_value_or_alloc_obj_types,
9304 	[ARG_PTR_TO_MEM]		= &mem_types,
9305 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9306 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9307 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9308 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9309 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9310 	[ARG_PTR_TO_TIMER]		= &map_value_types,
9311 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9312 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9313 	[ARG_CONST_SCALAR]		= &scalar_types,
9314 	[ARG_CONST_MEM_SIZE]		= &scalar_types,
9315 	[ARG_PTR_TO_ALLOC_BTF_ID]	= &alloc_obj_drop_types,
9316 	[ARG_PTR_TO_REFCOUNTED_KPTR]	= &alloc_obj_types,
9317 	[ARG_PTR_TO_ITER]		= &stack_ptr_types,
9318 	[ARG_PTR_TO_LIST_HEAD]		= &map_value_or_alloc_obj_types,
9319 	[ARG_PTR_TO_LIST_NODE]		= &alloc_obj_types,
9320 	[ARG_PTR_TO_RB_ROOT]		= &map_value_or_alloc_obj_types,
9321 	[ARG_PTR_TO_RB_NODE]		= &alloc_obj_types,
9322 	[ARG_PTR_TO_RES_SPIN_LOCK]	= &map_value_or_alloc_obj_types,
9323 	[ARG_PTR_TO_WORKQUEUE]		= &map_value_types,
9324 	[ARG_PTR_TO_TASK_WORK]		= &map_value_types,
9325 	[ARG_PTR_TO_RCU_HEAD]		= &map_value_types,
9326 	[ARG_PTR_TO_IRQ_FLAG]		= &stack_ptr_types,
9327 	[ARG_PTR_TO_ARENA]		= &arena_types,
9328 	[ARG_PTR_TO_CTX_OUT]		= &ctx_out_types,
9329 };
9330 
9331 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
9332 			      const char *call_name, const char *reason,
9333 			      const char *suggestion)
9334 {
9335 	int arg = arg_from_argno(argno);
9336 	int regno = reg_from_argno(argno);
9337 	int stack_slot = -1;
9338 
9339 	if (arg < 0 && regno >= BPF_REG_1 && regno <= BPF_REG_5)
9340 		arg = regno;
9341 	if (arg > MAX_BPF_FUNC_REG_ARGS)
9342 		stack_slot = arg - MAX_BPF_FUNC_REG_ARGS - 1;
9343 
9344 	bpf_diag_call_type(env, insn_idx, arg, regno, stack_slot,
9345 			   call_name && *call_name ? call_name : "call",
9346 			   reg_arg_name(env, argno), reason, suggestion);
9347 }
9348 
9349 static const char *bpf_diag_arg_name(struct bpf_verifier_env *env, argno_t argno)
9350 {
9351 	return bpf_diag_fmt(env, "%s", reg_arg_name(env, argno));
9352 }
9353 
9354 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
9355 						 argno_t argno, const char *call_name,
9356 						 const char *suggestion, const char *fmt, ...)
9357 {
9358 	const char *reason;
9359 	va_list args;
9360 
9361 	va_start(args, fmt);
9362 	reason = bpf_diag_vfmt(env, fmt, args);
9363 	va_end(args);
9364 
9365 	bpf_diag_call_arg(env, insn_idx, argno, call_name, reason, suggestion);
9366 }
9367 
9368 static int check_func_arg_nullability(struct bpf_verifier_env *env,
9369 				      struct bpf_reg_state *reg, u32 arg, argno_t argno,
9370 				      enum bpf_arg_type arg_type,
9371 				      struct bpf_call_arg_meta *meta, int insn_idx)
9372 {
9373 	const char *expected_type = "pointer";
9374 
9375 	if (arg_type_is_scalar(arg_type) || type_may_be_null(arg_type) ||
9376 	    (!bpf_register_is_null(reg) && !type_may_be_null(reg->type)))
9377 		return 0;
9378 
9379 	if (meta->btf) {
9380 		u32 arg_btf_id;
9381 
9382 		arg_btf_id = btf_params(meta->func_proto)[arg].type;
9383 		expected_type = bpf_diag_fmt(env, "value of type %s",
9384 					     bpf_diag_fmt_btf_type(env, meta->btf, arg_btf_id));
9385 	}
9386 
9387 	verbose(env, "Possibly NULL pointer passed to trusted %s\n",
9388 		reg_arg_name(env, argno));
9389 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9390 			      "Add a NULL check and make the call only on the non-NULL path.",
9391 			      "the pointer may be NULL, but this call requires a non-NULL %s",
9392 			      expected_type);
9393 	return -EACCES;
9394 }
9395 
9396 static int check_func_arg_release(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9397 				  u32 arg, argno_t argno, enum bpf_arg_type arg_type,
9398 				  struct bpf_call_arg_meta *meta, int insn_idx)
9399 {
9400 	const char *expected_type = "pointer";
9401 
9402 	if (!arg_type_is_release(arg_type))
9403 		return 0;
9404 
9405 	if (arg_type_is_dynptr(arg_type) || reg_is_referenced(env, reg) ||
9406 	    bpf_register_is_null(reg))
9407 		return 0;
9408 
9409 	verbose(env, "release function %s expects referenced PTR_TO_BTF_ID passed to %s\n",
9410 		meta->func_name, reg_arg_name(env, argno));
9411 
9412 	if (is_kfunc(meta)) {
9413 		const struct btf_param *btf_arg;
9414 		const struct btf_type *t;
9415 		u32 ref_id;
9416 
9417 		btf_arg = &btf_params(meta->func_proto)[arg];
9418 		ref_id = btf_arg->type;
9419 		t = btf_type_skip_modifiers(meta->btf, btf_arg->type, NULL);
9420 		if (btf_type_is_ptr(t))
9421 			btf_type_skip_modifiers(meta->btf, t->type, &ref_id);
9422 		expected_type = bpf_diag_fmt(env, "value of type %s",
9423 					     bpf_diag_fmt_btf_type(env, meta->btf, ref_id));
9424 	}
9425 
9426 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9427 			      bpf_diag_fmt(env, "Pass the resource-owning %s returned by the matching acquire call, or avoid the release function after ownership has already been transferred or released.",
9428 					   expected_type),
9429 			      "release functions require a value that owns a live resource returned by a matching acquire function");
9430 	return -EINVAL;
9431 }
9432 
9433 static const char *bpf_diag_expected_reg_types(struct bpf_verifier_env *env,
9434 					       const enum bpf_reg_type *types, int count)
9435 {
9436 	size_t len = 0, size = 1;
9437 	char *buf;
9438 	int i;
9439 
9440 	for (i = 0; i < count; i++)
9441 		size += strlen(reg_type_str(env, types[i])) + (i ? 2 : 0);
9442 
9443 	buf = bpf_diag_fmt_buf(env, size);
9444 	if (!buf)
9445 		return "";
9446 
9447 	for (i = 0; i < count; i++)
9448 		len += scnprintf(buf + len, size - len, "%s%s", i ? ", " : "",
9449 				 reg_type_str(env, types[i]));
9450 	return buf;
9451 }
9452 
9453 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
9454 			  enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
9455 {
9456 	enum bpf_reg_type expected, type = reg->type;
9457 	const struct bpf_reg_types *compatible;
9458 	const char *actual, *accepted;
9459 	int i, j;
9460 
9461 	compatible = compatible_reg_types[base_type(arg_type)];
9462 	if (!compatible) {
9463 		verifier_bug(env, "unsupported arg type %d", arg_type);
9464 		return -EFAULT;
9465 	}
9466 	if (is_kfunc(meta) && base_type(arg_type) == ARG_PTR_TO_BTF_ID &&
9467 	    (base_type(type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(type)]))
9468 		goto found;
9469 
9470 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9471 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9472 	 *
9473 	 * Same for MAYBE_NULL:
9474 	 *
9475 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9476 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9477 	 *
9478 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9479 	 *
9480 	 * Therefore we fold these flags depending on the arg_type before comparison.
9481 	 */
9482 	if (arg_type & MEM_RDONLY)
9483 		type &= ~MEM_RDONLY;
9484 	if (arg_type & PTR_MAYBE_NULL)
9485 		type &= ~PTR_MAYBE_NULL;
9486 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9487 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9488 	/* Allow allocated memory for BTF-defined ARG_PTR_TO_MEM but not helpers. */
9489 	if (!is_helper(meta) && base_type(arg_type) == ARG_PTR_TO_MEM &&
9490 	    type_is_ptr_alloc_obj(type))
9491 		type = PTR_TO_MEM;
9492 
9493 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9494 	if (is_helper_call(meta, BPF_FUNC_kptr_xchg) && type_is_alloc(type) &&
9495 	    reg_from_argno(argno) == BPF_REG_2) {
9496 		type &= ~MEM_ALLOC;
9497 		type &= ~MEM_PERCPU;
9498 	}
9499 
9500 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9501 		expected = compatible->types[i];
9502 		if (expected == NOT_INIT)
9503 			break;
9504 
9505 		if (type == expected)
9506 			goto found;
9507 	}
9508 
9509 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
9510 	for (j = 0; j + 1 < i; j++)
9511 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9512 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9513 	actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type));
9514 	accepted = bpf_diag_expected_reg_types(env, compatible->types, i);
9515 	bpf_diag_call_arg_fmt(env, env->insn_idx, argno, meta->func_name,
9516 			      bpf_diag_fmt(env, "Pass %s.", bpf_diag_arg_type_plain(arg_type)),
9517 			      "it has type %s, but this argument accepts %s",
9518 			      actual, accepted);
9519 	return -EACCES;
9520 
9521 found:
9522 	return 0;
9523 }
9524 
9525 static struct btf_field *
9526 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9527 {
9528 	struct btf_field *field;
9529 	struct btf_record *rec;
9530 
9531 	rec = reg_btf_record(reg);
9532 	if (!rec)
9533 		return NULL;
9534 
9535 	field = btf_record_find(rec, off, fields);
9536 	if (!field)
9537 		return NULL;
9538 
9539 	return field;
9540 }
9541 
9542 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9543 				  const struct bpf_reg_state *reg, argno_t argno,
9544 				  enum bpf_arg_type arg_type)
9545 {
9546 	u32 type = reg->type;
9547 
9548 	/* When referenced register is passed to release function, its fixed
9549 	 * offset must be 0.
9550 	 *
9551 	 * We will check arg_type_is_release reg has id when storing
9552 	 * meta->release_regno.
9553 	 */
9554 	if (arg_type_is_release(arg_type)) {
9555 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9556 		 * may not directly point to the object being released, but to
9557 		 * dynptr pointing to such object, which might be at some offset
9558 		 * on the stack. In that case, we simply to fallback to the
9559 		 * default handling.
9560 		 */
9561 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9562 			return 0;
9563 
9564 		/* Doing check_ptr_off_reg check for the offset will catch this
9565 		 * because fixed_off_ok is false, but checking here allows us
9566 		 * to give the user a better error message.
9567 		 */
9568 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
9569 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
9570 				reg_arg_name(env, argno));
9571 			return -EINVAL;
9572 		}
9573 	}
9574 
9575 	switch (type) {
9576 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9577 	case PTR_TO_STACK:
9578 	case PTR_TO_PACKET:
9579 	case PTR_TO_PACKET_META:
9580 	case PTR_TO_MAP_KEY:
9581 	case PTR_TO_MAP_VALUE:
9582 	case PTR_TO_MEM:
9583 	case PTR_TO_MEM | MEM_RDONLY:
9584 	case PTR_TO_MEM | MEM_RINGBUF:
9585 	case PTR_TO_BUF:
9586 	case PTR_TO_BUF | MEM_RDONLY:
9587 	case PTR_TO_ARENA:
9588 	case SCALAR_VALUE:
9589 		return 0;
9590 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9591 	 * fixed offset.
9592 	 */
9593 	case PTR_TO_BTF_ID:
9594 	case PTR_TO_BTF_ID | MEM_ALLOC:
9595 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9596 	case PTR_TO_BTF_ID | MEM_RCU:
9597 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9598 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9599 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9600 		 * its fixed offset must be 0. bpf_refcount_acquire() returns the
9601 		 * pointer it was given while incrementing the refcount at the
9602 		 * refcount field offset, so it needs a zero offset too. In the
9603 		 * other cases, fixed offset can be non-zero. var_off always must
9604 		 * be 0 for PTR_TO_BTF_ID, hence we still need to do checks
9605 		 * instead of returning.
9606 		 */
9607 		return __check_ptr_off_reg(env, reg, argno,
9608 					   base_type(arg_type) != ARG_PTR_TO_REFCOUNTED_KPTR);
9609 	case PTR_TO_CTX:
9610 		/*
9611 		 * Allow fixed and variable offsets for syscall context, but
9612 		 * only when the argument is passed as memory, not ctx,
9613 		 * otherwise we may get modified ctx in tail called programs and
9614 		 * global subprogs (that may act as extension prog hooks).
9615 		 */
9616 		if (base_type(arg_type) != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
9617 			return 0;
9618 		fallthrough;
9619 	default:
9620 		return __check_ptr_off_reg(env, reg, argno, false);
9621 	}
9622 }
9623 
9624 static int check_arg_const_str(struct bpf_verifier_env *env,
9625 			       struct bpf_reg_state *reg, argno_t argno)
9626 {
9627 	struct bpf_map *map = reg->map_ptr;
9628 	int err;
9629 	int map_off;
9630 	u64 map_addr;
9631 	char *str_ptr;
9632 	u32 cnt;
9633 
9634 	if (reg->type != PTR_TO_MAP_VALUE)
9635 		return -EINVAL;
9636 
9637 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9638 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
9639 			reg_arg_name(env, argno));
9640 		return -EACCES;
9641 	}
9642 
9643 	if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
9644 		verbose(env, "%s points to percpu_array map which cannot be used as const string\n",
9645 			reg_arg_name(env, argno));
9646 		return -EACCES;
9647 	}
9648 
9649 	if (!bpf_map_is_rdonly(map)) {
9650 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
9651 		return -EACCES;
9652 	}
9653 
9654 	if (!tnum_is_const(reg->var_off)) {
9655 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
9656 		return -EACCES;
9657 	}
9658 
9659 	if (!map->ops->map_direct_value_addr) {
9660 		verbose(env, "no direct value access support for this map type\n");
9661 		return -EACCES;
9662 	}
9663 
9664 	err = check_map_access(env, reg, argno, 0,
9665 			       map->value_size - reg->var_off.value, false,
9666 			       ACCESS_HELPER);
9667 	if (err)
9668 		return err;
9669 
9670 	map_off = reg->var_off.value;
9671 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9672 	if (err) {
9673 		verbose(env, "direct value access on string failed\n");
9674 		return err;
9675 	}
9676 
9677 	str_ptr = (char *)(long)(map_addr);
9678 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9679 		verbose(env, "string is not zero-terminated\n");
9680 		return -EINVAL;
9681 	}
9682 	/* the bytes of a pointer to a function are not known until the program is jitted */
9683 	if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) {
9684 		verbose(env, "string overlaps with a pointer to a function\n");
9685 		return -EACCES;
9686 	}
9687 	return 0;
9688 }
9689 
9690 /* Returns constant key value in `value` if possible, else negative error */
9691 static int get_constant_map_key(struct bpf_verifier_env *env,
9692 				struct bpf_reg_state *key,
9693 				u32 key_size,
9694 				s64 *value)
9695 {
9696 	struct bpf_func_state *state = bpf_func(env, key);
9697 	struct bpf_stack_state *ss;
9698 	struct bpf_reg_state *reg;
9699 	int slot, spi, off;
9700 	int spill_size = 0;
9701 	int zero_size = 0;
9702 	int stack_off;
9703 	int i, err;
9704 	u8 *stype;
9705 
9706 	if (!env->bpf_capable)
9707 		return -EOPNOTSUPP;
9708 	if (key->type != PTR_TO_STACK)
9709 		return -EOPNOTSUPP;
9710 	if (!tnum_is_const(key->var_off))
9711 		return -EOPNOTSUPP;
9712 
9713 	stack_off = key->var_off.value;
9714 	slot = -stack_off - 1;
9715 	spi = slot / BPF_REG_SIZE;
9716 	off = slot % BPF_REG_SIZE;
9717 	ss = bpf_stack_slot(state, spi);
9718 	stype = ss->slot_type;
9719 
9720 	/* First handle precisely tracked STACK_ZERO */
9721 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9722 		zero_size++;
9723 	if (zero_size >= key_size) {
9724 		*value = 0;
9725 		return 0;
9726 	}
9727 
9728 	/* Check that stack contains a scalar spill of expected size */
9729 	if (!bpf_is_spilled_scalar_reg(ss))
9730 		return -EOPNOTSUPP;
9731 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9732 		spill_size++;
9733 	if (spill_size != key_size)
9734 		return -EOPNOTSUPP;
9735 
9736 	reg = &ss->spilled_ptr;
9737 	if (!tnum_is_const(reg->var_off))
9738 		/* Stack value not statically known */
9739 		return -EOPNOTSUPP;
9740 
9741 	/* We are relying on a constant value. So mark as precise
9742 	 * to prevent pruning on it.
9743 	 */
9744 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
9745 	err = mark_chain_precision_batch(env, env->cur_state);
9746 	if (err < 0)
9747 		return err;
9748 
9749 	*value = reg->var_off.value;
9750 	return 0;
9751 }
9752 
9753 static bool can_elide_value_nullness(const struct bpf_map *map);
9754 
9755 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9756 			       argno_t argno, struct bpf_call_arg_meta *meta)
9757 {
9758 	/* Use map_uid (which is unique id of inner map) to reject:
9759 	 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9760 	 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9761 	 * if (inner_map1 && inner_map2) {
9762 	 *     timer = bpf_map_lookup_elem(inner_map1);
9763 	 *     if (timer)
9764 	 *         // mismatch would have been allowed
9765 	 *         bpf_timer_init(timer, inner_map2);
9766 	 * }
9767 	 *
9768 	 * Comparing map_ptr is enough to distinguish normal and outer maps.
9769 	 */
9770 	if (meta->map.ptr &&
9771 	    (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) {
9772 		argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1);
9773 		struct btf_record *rec = meta->map.ptr->record;
9774 		const char *obj_name = "workqueue";
9775 
9776 		if (rec->timer_off >= 0)
9777 			obj_name = "timer";
9778 		else if (rec->task_work_off >= 0)
9779 			obj_name = "bpf_task_work";
9780 		else if (rec->rcu_head_off >= 0)
9781 			obj_name = "bpf_rcu_head";
9782 
9783 		verbose(env, "%s pointer in %s map_uid=%d ",
9784 			obj_name, reg_arg_name(env, obj_argno), meta->map.uid);
9785 		verbose(env, "doesn't match map pointer in %s map_uid=%d\n",
9786 			reg_arg_name(env, argno), reg->map_uid);
9787 		return -EINVAL;
9788 	}
9789 
9790 	meta->map.ptr = reg->map_ptr;
9791 	meta->map.uid = reg->map_uid;
9792 	return 0;
9793 }
9794 
9795 /*
9796  * MEM_WRITE alone denotes an input/output buffer. MEM_UNINIT marks an output
9797  * whose incoming contents are not read.
9798  */
9799 static enum bpf_access_type func_arg_access_type(enum bpf_arg_type arg_type)
9800 {
9801 	if (!(arg_type & MEM_WRITE))
9802 		return BPF_READ;
9803 	if (arg_type & MEM_UNINIT)
9804 		return BPF_WRITE;
9805 	return BPF_READ | BPF_WRITE;
9806 }
9807 
9808 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,
9809 			  struct bpf_call_arg_meta *meta,
9810 			  int insn_idx)
9811 {
9812 	const struct btf_param *btf_arg = is_kfunc(meta) ?
9813 					  &btf_params(meta->func_proto)[arg] : NULL;
9814 	const struct bpf_func_proto *fn = meta->fn;
9815 	struct bpf_func_state *caller = cur_func(env);
9816 	struct bpf_reg_state *regs = cur_regs(env);
9817 	argno_t argno = argno_from_arg(slot + 1);
9818 	struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, slot);
9819 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9820 	int regno = reg_from_argno(argno);
9821 	u32 arg_size = arg_type & MEM_FIXED_SIZE ? fn->arg_size[arg] : 0;
9822 	u32 key_size;
9823 	int err = 0;
9824 
9825 	if (arg_type == ARG_PTR_TO_PROG_AUX) {
9826 		cur_aux(env)->arg_prog = regno;
9827 		return 0;
9828 	}
9829 
9830 	if (arg_type == ARG_IGNORE)
9831 		return 0;
9832 
9833 	if (regno >= 0) {
9834 		err = check_reg_arg(env, regno, SRC_OP);
9835 		if (err)
9836 			return err;
9837 	}
9838 
9839 	/* Preserve the legacy helper behavior for privileged pointer leaks. */
9840 	if (arg_type == ARG_ANYTHING) {
9841 		if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
9842 			verbose(env, "%s leaks addr into helper function\n",
9843 				reg_arg_name(env, argno));
9844 			return -EACCES;
9845 		}
9846 		return 0;
9847 	}
9848 
9849 	err = resolve_func_arg_type(env, reg, arg, argno, meta, &arg_type, &arg_size);
9850 	if (err)
9851 		return err;
9852 
9853 	/*
9854 	 * A slice of a packet is packet data under another name. A helper which
9855 	 * may reallocate the packet must not go on reading from the old one.
9856 	 */
9857 	if (is_helper(meta) && reg_is_dynptr_slice_pkt(reg) &&
9858 	    bpf_helper_changes_pkt_data(meta->func_id)) {
9859 		verbose(env, "function access to the packet is not allowed\n");
9860 		return -EACCES;
9861 	}
9862 
9863 	if (arg_type_is_raw_mem(arg_type))
9864 		meta->arg_raw_mem.mask |= BIT(slot);
9865 
9866 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) {
9867 		err = mark_arg_precision(env, argno);
9868 		if (err)
9869 			return err;
9870 		return 0;
9871 	}
9872 
9873 	err = check_func_arg_nullability(env, reg, arg, argno, arg_type, meta, insn_idx);
9874 	if (err)
9875 		return err;
9876 
9877 	err = check_reg_type(env, reg, argno, arg_type, meta);
9878 	if (err)
9879 		return err;
9880 
9881 	err = check_func_arg_reg_off(env, reg, argno, arg_type);
9882 	if (err)
9883 		return err;
9884 
9885 	err = check_func_arg_release(env, reg, arg, argno, arg_type, meta, insn_idx);
9886 	if (err)
9887 		return err;
9888 
9889 	if (reg_is_referenced(env, reg))
9890 		update_ref_obj(&meta->ref_obj, reg);
9891 
9892 	switch (base_type(arg_type)) {
9893 	case ARG_CONST_SCALAR:
9894 		err = process_const_arg(env, reg, argno, meta);
9895 		if (err < 0) {
9896 			if (err == -EINVAL)
9897 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9898 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
9899 						      "the function requires this scalar argument to be a verifier-known constant, but %s is variable on this path",
9900 						      reg_arg_name(env, argno));
9901 			return err;
9902 		}
9903 		break;
9904 	case ARG_SCALAR:
9905 		break;
9906 	case ARG_CONST_MAP_PTR:
9907 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9908 		err = process_map_ptr_arg(env, reg, argno, meta);
9909 		if (err)
9910 			return err;
9911 		break;
9912 	case ARG_PTR_TO_MAP_KEY:
9913 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9914 		 * check that [key, key + map->key_size) are within
9915 		 * stack limits and initialized
9916 		 */
9917 		if (!meta->map.ptr) {
9918 			/* in function declaration map_ptr must come before
9919 			 * map_key, so that it's verified and known before
9920 			 * we have to check map_key here. Otherwise it means
9921 			 * that kernel subsystem misconfigured verifier
9922 			 */
9923 			verifier_bug(env, "invalid map_ptr to access map->key");
9924 			return -EFAULT;
9925 		}
9926 		key_size = meta->map.ptr->key_size;
9927 		err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, meta,
9928 					      NULL);
9929 		if (err)
9930 			return err;
9931 		if (can_elide_value_nullness(meta->map.ptr)) {
9932 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9933 			if (err < 0) {
9934 				meta->const_map_key = -1;
9935 				if (err == -EOPNOTSUPP)
9936 					err = 0;
9937 				else
9938 					return err;
9939 			}
9940 		}
9941 		break;
9942 	case ARG_PTR_TO_MAP_VALUE:
9943 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
9944 			return 0;
9945 
9946 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9947 		 * check [value, value + map->value_size) validity
9948 		 */
9949 		if (!meta->map.ptr) {
9950 			/* kernel subsystem misconfigured verifier */
9951 			verifier_bug(env, "invalid map_ptr to access map->value");
9952 			return -EFAULT;
9953 		}
9954 
9955 		err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size,
9956 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9957 					      false, meta, NULL);
9958 		break;
9959 	case ARG_PTR_TO_BTF_ID:
9960 	case ARG_PTR_TO_BTF_ID_SOCK_COMMON:
9961 	{
9962 		const u32 *arg_btf_id = fn->arg_btf_id[arg];
9963 		const struct btf *arg_btf = is_kfunc(meta) ? meta->btf : btf_vmlinux;
9964 		enum bpf_reg_type reg_type;
9965 
9966 		if (!meta->btf) {
9967 			const struct bpf_reg_types *compatible;
9968 
9969 			if (base_type(reg->type) != PTR_TO_BTF_ID)
9970 				break;
9971 
9972 			if (is_helper_call(meta, BPF_FUNC_kptr_xchg))
9973 				return map_kptr_match_type(env, meta->kptr_field, reg, regno) ?
9974 				       -EACCES : 0;
9975 
9976 			if (!arg_btf_id) {
9977 				compatible = compatible_reg_types[base_type(arg_type)];
9978 				if (!compatible->btf_id) {
9979 					verifier_bug(env, "missing arg compatible BTF ID");
9980 					return -EFAULT;
9981 				}
9982 				arg_btf_id = compatible->btf_id;
9983 			}
9984 			if (arg_btf_id == BPF_PTR_POISON) {
9985 				verbose(env, "verifier internal error:");
9986 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
9987 					reg_arg_name(env, argno));
9988 				return -EACCES;
9989 			}
9990 		}
9991 
9992 		reg_type = reg->type & ~(arg_type & PTR_MAYBE_NULL);
9993 		if ((arg_type & PTR_TRUSTED) &&
9994 		    (!is_trusted_reg_type(env, reg, reg_type) ||
9995 		     bpf_type_has_unsafe_modifiers(reg_type))) {
9996 			if (!(arg_type & MEM_RCU)) {
9997 				const char *actual_type, *arg_name, *expected_type;
9998 
9999 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
10000 				verbose(env, "%s must be referenced or trusted\n",
10001 					reg_arg_name(env, argno));
10002 				arg_name = reg_arg_name(env, argno);
10003 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
10004 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10005 						      "Pass a pointer acquired from a verifier-tracked source, or call this function only inside the required protection if it accepts RCU pointers.",
10006 						      "the function requires a trusted or resource-owning pointer to %s, but %s is %s",
10007 						      expected_type, arg_name, actual_type);
10008 				return -EINVAL;
10009 			}
10010 			if (!is_rcu_reg(reg)) {
10011 				const char *actual_type, *arg_name, *expected_type;
10012 
10013 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
10014 				verbose(env, "%s must be a rcu pointer\n",
10015 					reg_arg_name(env, argno));
10016 				arg_name = reg_arg_name(env, argno);
10017 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
10018 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10019 						      "Use this function with a pointer that is valid in an RCU read lock region.",
10020 						      "the function requires an RCU-protected pointer to %s, but %s is %s",
10021 						      expected_type, arg_name, actual_type);
10022 				return -EINVAL;
10023 			}
10024 		}
10025 
10026 		err = process_arg_ptr_to_btf_id(env, reg, argno, arg_type, arg_btf,
10027 						*arg_btf_id, meta, insn_idx);
10028 		if (err < 0)
10029 			return err;
10030 		break;
10031 	}
10032 	case ARG_PTR_TO_PERCPU_BTF_ID:
10033 		if (!reg->btf_id) {
10034 			verbose(env, "Helper has invalid btf_id in %s\n", reg_arg_name(env, argno));
10035 			return -EACCES;
10036 		}
10037 		meta->ret_btf = reg->btf;
10038 		meta->ret_btf_id = reg->btf_id;
10039 		break;
10040 	case ARG_PTR_TO_SPIN_LOCK:
10041 		if (in_rbtree_lock_required_cb(env)) {
10042 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
10043 			return -EACCES;
10044 		}
10045 		if (is_helper_call(meta, BPF_FUNC_spin_lock)) {
10046 			err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK);
10047 			if (err)
10048 				return err;
10049 		} else if (is_helper_call(meta, BPF_FUNC_spin_unlock)) {
10050 			err = process_spin_lock(env, reg, argno, 0);
10051 			if (err)
10052 				return err;
10053 		} else {
10054 			verifier_bug(env, "spin lock arg on unexpected helper");
10055 			return -EFAULT;
10056 		}
10057 		break;
10058 	case ARG_PTR_TO_TIMER:
10059 		err = process_timer_func(env, reg, argno, &meta->map);
10060 		if (err)
10061 			return err;
10062 		break;
10063 	case ARG_PTR_TO_CTX:
10064 		if (is_bpf_cast_to_kern_ctx_kfunc(meta)) {
10065 			err = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10066 			if (err < 0)
10067 				return -EINVAL;
10068 			meta->ret_btf_id = err;
10069 		}
10070 		break;
10071 	case ARG_PTR_TO_ARENA:
10072 		break;
10073 	case ARG_PTR_TO_ALLOC_BTF_ID:
10074 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
10075 			if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
10076 				verbose(env, "%s expected for bpf_obj_drop()\n",
10077 					reg_arg_name(env, argno));
10078 				return -EINVAL;
10079 			}
10080 		} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
10081 			if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
10082 				verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
10083 					reg_arg_name(env, argno));
10084 				return -EINVAL;
10085 			}
10086 		}
10087 		if (!reg_is_referenced(env, reg)) {
10088 			verbose(env, "allocated object must be referenced\n");
10089 			bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10090 					      "Pass the owned object pointer before it is released or transferred.",
10091 					      "the allocated object pointer in %s must still carry verifier-tracked ownership, but this pointer no longer owns a live resource",
10092 					      reg_arg_name(env, argno));
10093 			return -EINVAL;
10094 		}
10095 		if (meta->btf == btf_vmlinux) {
10096 			meta->arg_btf = reg->btf;
10097 			meta->arg_btf_id = reg->btf_id;
10098 		}
10099 		break;
10100 	case ARG_PTR_TO_FUNC:
10101 		meta->subprogno = reg->subprogno;
10102 		break;
10103 	case ARG_PTR_TO_MEM:
10104 	{
10105 		enum bpf_access_type access_type;
10106 		bool known_memory;
10107 
10108 		/* The access to this pointer is only checked when we hit the
10109 		 * next is_mem_size argument below.
10110 		 */
10111 		if (!(arg_type & MEM_FIXED_SIZE))
10112 			break;
10113 
10114 		access_type = func_arg_access_type(arg_type);
10115 
10116 		err = check_mem_reg(env, reg, argno, arg_size, access_type, meta, &known_memory);
10117 		if (err < 0) {
10118 			if (known_memory)
10119 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10120 					"Pass memory with at least the required number of accessible bytes and suitable read or write access.",
10121 					"the function expects %u bytes of memory, but the verifier cannot prove that %s provides a range of that size with the required read or write access",
10122 					arg_size,
10123 					bpf_diag_reg_type_plain(env, reg->type));
10124 			else
10125 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10126 					"Pass stack, map, context, or other verifier-known memory of the expected type and size, not an integer cast to a pointer.",
10127 					"the function expects %u bytes of memory, but it is %s and not verifier-known memory",
10128 					arg_size,
10129 					bpf_diag_reg_type_plain(env, reg->type));
10130 			return err;
10131 		}
10132 		/*
10133 		 * PTR_TO_PACKET gets passed as PTR_TO_MEM, preventing us from adjusting
10134 		 * bounds tracking information.
10135 		 */
10136 		if (is_subprog(meta) && meta->subprog_may_change_pkt &&
10137 		    (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))) {
10138 			verbose(env,
10139 				"cannot pass packet pointer %s to %s(): function may change packet data\n",
10140 				reg_arg_name(env, argno), meta->func_name);
10141 			return -EINVAL;
10142 		}
10143 		if (arg_type & MEM_ALIGNED)
10144 			err = check_ptr_alignment(env, reg, 0, arg_size, true);
10145 		break;
10146 	}
10147 	case ARG_CONST_MEM_SIZE:
10148 		err = process_const_arg(env, reg, argno, meta);
10149 		if (err < 0) {
10150 			if (err == -EINVAL)
10151 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10152 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
10153 						      "the function requires this memory size to be a verifier-known constant, but %s is variable on this path",
10154 						      reg_arg_name(env, argno));
10155 			return err;
10156 		}
10157 		fallthrough;
10158 	case ARG_MEM_SIZE:
10159 	case ARG_MEM_SIZE_OR_ZERO:
10160 	{
10161 		struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, prev_slot);
10162 		argno_t buff_argno = argno_from_arg(prev_slot + 1);
10163 		enum bpf_mem_size_failure failure;
10164 		const char *buff_arg, *size_arg;
10165 		bool zero_size_allowed;
10166 		u32 access_type;
10167 
10168 		if (meta->btf && bpf_register_is_null(buff_reg))
10169 			break;
10170 
10171 		access_type = func_arg_access_type(fn->arg_type[arg - 1]);
10172 
10173 		zero_size_allowed = meta->btf || base_type(arg_type) == ARG_MEM_SIZE_OR_ZERO;
10174 
10175 		err = check_mem_size_reg(env, buff_reg, reg, buff_argno, argno,
10176 					 access_type, zero_size_allowed, meta, &failure);
10177 		if (!err)
10178 			break;
10179 
10180 		buff_arg = bpf_diag_arg_name(env, buff_argno);
10181 		size_arg = bpf_diag_arg_name(env, argno);
10182 		verbose(env, "%s and ", reg_arg_name(env, buff_argno));
10183 		verbose(env, "%s memory, len pair leads to invalid memory access\n",
10184 			reg_arg_name(env, argno));
10185 		if (failure == BPF_MEM_SIZE_FAIL_MEMORY) {
10186 			bpf_diag_call_arg_fmt(env, insn_idx, buff_argno, meta->func_name,
10187 					      "Pass a stack, map, context, or other verifier-known memory pointer, and keep the paired length within that object.",
10188 					      "it is the memory pointer in a memory/length pair with %s, but %s does not provide a verifier-accessible range of the requested length",
10189 					      size_arg, buff_arg);
10190 		} else if (failure == BPF_MEM_SIZE_FAIL_SIZE) {
10191 			if (reg_smin(reg) < 0)
10192 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10193 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
10194 					"the memory size in %s may be negative because its signed minimum is %lld",
10195 					size_arg, reg_smin(reg));
10196 			else if (!zero_size_allowed && reg_umin(reg) == 0)
10197 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10198 					"Ensure the memory size is non-zero before this call.",
10199 					"the memory size in %s may be zero, but the function requires a non-zero size",
10200 					size_arg);
10201 			else
10202 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10203 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
10204 					"the memory size in %s may reach %llu bytes, but variable memory accesses must stay below %u bytes",
10205 					size_arg, reg_umax(reg), BPF_MAX_VAR_SIZ);
10206 		}
10207 		break;
10208 	}
10209 	case ARG_PTR_TO_DYNPTR: {
10210 		if (is_bpf_dynptr_clone_kfunc(meta) &&
10211 		    (arg_type & MEM_UNINIT)) {
10212 			enum bpf_dynptr_type parent_type = meta->dynptr.type;
10213 
10214 			if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10215 				verifier_bug(env, "no dynptr type for parent of clone");
10216 				return -EFAULT;
10217 			}
10218 
10219 			arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10220 		}
10221 
10222 		err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, meta);
10223 		if (err)
10224 			return err;
10225 		if (!arg && is_kfunc_dynptr_write(meta))
10226 			meta->dynptr_write_type = meta->dynptr.type;
10227 		break;
10228 	}
10229 	case ARG_PTR_TO_ITER:
10230 		if (is_bpf_iter_css_task_new_kfunc(meta) &&
10231 		    !check_css_task_iter_allowlist(env)) {
10232 			verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
10233 			return -EINVAL;
10234 		}
10235 		err = process_iter_arg(env, reg, arg, argno, insn_idx, meta);
10236 		if (err < 0)
10237 			return err;
10238 		break;
10239 	case ARG_PTR_TO_LIST_HEAD:
10240 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10241 		    !reg_is_referenced(env, reg)) {
10242 			verbose(env, "allocated object must be referenced\n");
10243 			return -EINVAL;
10244 		}
10245 		err = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
10246 		if (err < 0)
10247 			return err;
10248 		break;
10249 	case ARG_PTR_TO_RB_ROOT:
10250 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10251 		    !reg_is_referenced(env, reg)) {
10252 			verbose(env, "allocated object must be referenced\n");
10253 			return -EINVAL;
10254 		}
10255 		err = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
10256 		if (err < 0)
10257 			return err;
10258 		break;
10259 	case ARG_PTR_TO_LIST_NODE:
10260 		if (!(is_kfunc_arg_nonown_allowed(meta->btf, btf_arg) &&
10261 		      type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg))) {
10262 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10263 				verbose(env, "%s expected pointer to allocated object\n",
10264 					reg_arg_name(env, argno));
10265 				return -EINVAL;
10266 			}
10267 			if (!reg_is_referenced(env, reg)) {
10268 				verbose(env, "allocated object must be referenced\n");
10269 				return -EINVAL;
10270 			}
10271 		}
10272 		err = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
10273 		if (err < 0)
10274 			return err;
10275 		break;
10276 	case ARG_PTR_TO_RB_NODE:
10277 		if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
10278 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10279 				verbose(env, "%s expected pointer to allocated object\n",
10280 					reg_arg_name(env, argno));
10281 				return -EINVAL;
10282 			}
10283 			if (!reg_is_referenced(env, reg)) {
10284 				verbose(env, "allocated object must be referenced\n");
10285 				return -EINVAL;
10286 			}
10287 		} else {
10288 			if (!type_is_non_owning_ref(reg->type) &&
10289 			    !reg_is_referenced(env, reg)) {
10290 				verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n",
10291 					meta->func_name);
10292 				return -EINVAL;
10293 			}
10294 			if (in_rbtree_lock_required_cb(env)) {
10295 				verbose(env, "%s not allowed in rbtree cb\n", meta->func_name);
10296 				return -EINVAL;
10297 			}
10298 		}
10299 		err = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
10300 		if (err < 0)
10301 			return err;
10302 		break;
10303 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
10304 		if (meta->btf && is_kfunc_arg_scalar_with_name(meta->btf, btf_arg,
10305 							       "rdonly_buf_size"))
10306 			meta->r0_rdonly = true;
10307 		err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem);
10308 		if (err < 0) {
10309 			if (meta->btf && err == -EINVAL)
10310 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10311 						      "Pass a verifier-known constant size for this function's buffer argument.",
10312 						      "the function uses this argument as a return-buffer size, but %s is invalid or variable on this path",
10313 						      reg_arg_name(env, argno));
10314 			return err;
10315 		}
10316 		break;
10317 	case ARG_PTR_TO_REFCOUNTED_KPTR:
10318 	{
10319 		struct btf_record *rec;
10320 
10321 		if (!type_is_non_owning_ref(reg->type) && reg_is_referenced(env, reg))
10322 			meta->arg_owning_ref = true;
10323 
10324 		rec = reg_btf_record(reg);
10325 		if (!rec) {
10326 			verifier_bug(env, "Couldn't find btf_record");
10327 			return -EFAULT;
10328 		}
10329 
10330 		if (rec->refcount_off < 0) {
10331 			verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
10332 				reg_arg_name(env, argno));
10333 			return -EINVAL;
10334 		}
10335 
10336 		meta->arg_btf = reg->btf;
10337 		meta->arg_btf_id = reg->btf_id;
10338 		break;
10339 	}
10340 	case ARG_PTR_TO_CONST_STR:
10341 	{
10342 		err = check_arg_const_str(env, reg, argno);
10343 		if (err)
10344 			return err;
10345 		break;
10346 	}
10347 	case ARG_PTR_TO_WORKQUEUE:
10348 		err = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
10349 		if (err < 0)
10350 			return err;
10351 		break;
10352 	case ARG_PTR_TO_TASK_WORK:
10353 		err = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
10354 		if (err < 0)
10355 			return err;
10356 		break;
10357 	case ARG_PTR_TO_RCU_HEAD:
10358 		err = check_map_field_pointer(env, reg, argno, BPF_RCU_HEAD, &meta->map);
10359 		if (err < 0)
10360 			return err;
10361 		break;
10362 	case ARG_PTR_TO_IRQ_FLAG:
10363 		err = process_irq_flag(env, reg, argno, meta);
10364 		if (err < 0)
10365 			return err;
10366 		break;
10367 	case ARG_PTR_TO_CTX_OUT:
10368 		if (reg->mem_size != arg_size) {
10369 			verbose(env, "%s expected %u bytes of ctx-provided memory, got %u\n",
10370 				reg_arg_name(env, argno), arg_size, reg->mem_size);
10371 			return -EINVAL;
10372 		}
10373 		break;
10374 	case ARG_PTR_TO_RES_SPIN_LOCK:
10375 	{
10376 		int flags;
10377 
10378 		if (in_rbtree_lock_required_cb(env)) {
10379 			verbose(env, "can't res_spin_{lock,unlock} in rbtree cb\n");
10380 			return -EACCES;
10381 		}
10382 
10383 		flags = get_bpf_res_spin_lock_kfunc_flags(meta);
10384 		if (!flags)
10385 			return -EFAULT;
10386 		err = process_spin_lock(env, reg, argno, flags);
10387 		if (err < 0)
10388 			return err;
10389 		break;
10390 	}
10391 	case ARG_KPTR_XCHG_DEST:
10392 		err = process_kptr_func(env, regno, meta);
10393 		if (err)
10394 			return err;
10395 		break;
10396 	}
10397 
10398 	return err;
10399 }
10400 
10401 /*
10402  * The slots a parameter takes, from its BTF type. This has to agree with
10403  * btf_func_model_arg_slots(), which answers the same from the size the
10404  * func model recorded, or the verifier would check an argument at a slot
10405  * the JIT does not place it at.
10406  */
10407 static u32 btf_arg_slots(const struct btf_type *t)
10408 {
10409 	if (btf_type_is_int(t) || btf_type_is_struct(t))
10410 		return (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE;
10411 	return 1;
10412 }
10413 
10414 static u32 btf_proto_slots(const struct btf *btf, const struct btf_type *func_proto)
10415 {
10416 	const struct btf_param *args = btf_params(func_proto);
10417 	u32 i, nargs = btf_type_vlen(func_proto), slots_used = 0;
10418 
10419 	for (i = 0; i < nargs; i++)
10420 		slots_used += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
10421 
10422 	return slots_used;
10423 }
10424 
10425 /* The argument slot @slot holds an eightbyte of a by-value argument. */
10426 static int check_arg_extra_slot(struct bpf_verifier_env *env, struct bpf_func_state *caller,
10427 				u32 slot, struct bpf_call_arg_meta *meta)
10428 {
10429 	struct bpf_reg_state *reg = get_func_arg_reg(caller, cur_regs(env), slot);
10430 	argno_t argno = argno_from_arg(slot + 1);
10431 	int regno = reg_from_argno(argno);
10432 	int err;
10433 
10434 	if (regno >= 0) {
10435 		err = check_reg_arg(env, regno, SRC_OP);
10436 		if (err)
10437 			return err;
10438 	}
10439 
10440 	return check_reg_type(env, reg, argno, ARG_SCALAR, meta);
10441 }
10442 
10443 static int check_func_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10444 			   int insn_idx)
10445 {
10446 	u32 slot = 0, prev_slot = 0, proto_slots, nslots;
10447 	struct bpf_func_state *caller = cur_func(env);
10448 	const struct btf_param *args = NULL;
10449 	u32 arg, nargs = MAX_BPF_FUNC_REG_ARGS;
10450 	int err;
10451 
10452 	if (meta->btf) {
10453 		args = btf_params(meta->func_proto);
10454 		nargs = btf_type_vlen(meta->func_proto);
10455 	}
10456 
10457 	/*
10458 	 * A by-value argument of more than one eightbyte takes a slot per
10459 	 * eightbyte, so the slots a call occupies are no longer its parameter
10460 	 * count. Only a proto whose parameters take a slot each can name the
10461 	 * argument a stack slot belongs to.
10462 	 */
10463 	proto_slots = meta->btf ? btf_proto_slots(meta->btf, meta->func_proto) : nargs;
10464 
10465 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
10466 		err = check_outgoing_stack_args(env, caller, proto_slots, meta->func_name,
10467 						meta->btf, proto_slots == nargs ? args : NULL);
10468 		if (err)
10469 			return err;
10470 	}
10471 
10472 	for (arg = 0; arg < nargs; arg++, prev_slot = slot, slot += nslots) {
10473 		const struct btf_type *t;
10474 		u32 k;
10475 
10476 		nslots = 1;
10477 		if (args) {
10478 			t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
10479 			nslots = btf_arg_slots(t);
10480 		}
10481 
10482 		if (meta->fn->arg_type[arg] == ARG_UNUSED)
10483 			break;
10484 		err = check_func_arg(env, arg, slot, prev_slot, meta, insn_idx);
10485 		if (err)
10486 			return err;
10487 
10488 		/*
10489 		 * check_func_arg() took the first slot. A parameter of more
10490 		 * than one eightbyte is always a scalar, so every slot it
10491 		 * takes beyond the first holds one too.
10492 		 */
10493 		for (k = 1; k < nslots; k++) {
10494 			err = check_arg_extra_slot(env, caller, slot + k, meta);
10495 			if (err)
10496 				return err;
10497 		}
10498 	}
10499 
10500 	return 0;
10501 }
10502 
10503 static int mark_raw_stack(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10504 			  int insn_idx)
10505 {
10506 	struct bpf_func_state *caller = cur_func(env);
10507 	u32 slot;
10508 	int i, err;
10509 
10510 	/*
10511 	 * Validate every argument before initializing outputs: an input argument
10512 	 * may alias an output buffer. Use the normal stack-write checks to discard
10513 	 * stale spills and preserve the rules for special stack objects.
10514 	 */
10515 	for (slot = 0; slot < MAX_BPF_FUNC_ARGS; slot++) {
10516 		struct bpf_reg_state *reg;
10517 
10518 		if (!meta->arg_raw_mem.size[slot])
10519 			continue;
10520 		reg = get_func_arg_reg(caller, cur_regs(env), slot);
10521 
10522 		/*
10523 		 * check_stack_range_initialized() checked the range, its offset is a constant.
10524 		 * Not check_stack_write(): unknown bytes in its buffer leave a dynptr slice valid.
10525 		 */
10526 		for (i = 0; i < meta->arg_raw_mem.size[slot]; i++) {
10527 			err = check_stack_write_fixed_off(env, bpf_func(env, reg),
10528 							  reg->var_off.value + i, 1, -1, insn_idx);
10529 			if (err)
10530 				return err;
10531 		}
10532 	}
10533 
10534 	return 0;
10535 }
10536 
10537 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
10538 {
10539 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
10540 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10541 	const char *afname = env->prog->aux->attach_func_name;
10542 
10543 	if (func_id != BPF_FUNC_map_update_elem &&
10544 	    func_id != BPF_FUNC_map_delete_elem)
10545 		return false;
10546 
10547 	/* It's not possible to get access to a locked struct sock in these
10548 	 * contexts, so updating is safe.
10549 	 */
10550 	switch (type) {
10551 	case BPF_PROG_TYPE_TRACING:
10552 		if (eatype == BPF_TRACE_ITER &&
10553 		    !strcmp(afname + strlen(BPF_ITER_FUNC_PREFIX), "sockmap"))
10554 			return true;
10555 		break;
10556 	case BPF_PROG_TYPE_SOCK_OPS:
10557 		/* map_update allowed only via dedicated helpers with event type checks */
10558 		if (func_id == BPF_FUNC_map_delete_elem)
10559 			return true;
10560 		break;
10561 	case BPF_PROG_TYPE_SK_REUSEPORT:
10562 	case BPF_PROG_TYPE_SK_LOOKUP:
10563 		return true;
10564 	default:
10565 		break;
10566 	}
10567 
10568 	verbose(env, "cannot update sockmap in this context\n");
10569 	return false;
10570 }
10571 
10572 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10573 {
10574 	return env->prog->jit_requested &&
10575 	       bpf_jit_supports_subprog_tailcalls();
10576 }
10577 
10578 /*
10579  * Is rcu_read_lock_held() true at run time? Unlike for in_rcu_cs(), disabled
10580  * preemption or interrupts will not do.
10581  */
10582 static bool has_rcu_read_lock(struct bpf_verifier_env *env)
10583 {
10584 	struct bpf_verifier_state *state = env->cur_state;
10585 
10586 	if (state->active_rcu_locks || in_rcu_callback(env))
10587 		return true;
10588 	if (in_sleepable(env))
10589 		return false;
10590 	return !env->no_rcu_read_lock || state->frame[0]->in_async_callback_fn;
10591 }
10592 
10593 /* May the map be used outside of an RCU read side critical section? */
10594 static bool map_needs_no_rcu(const struct bpf_map *map)
10595 {
10596 	switch (map->map_type) {
10597 	case BPF_MAP_TYPE_HASH:
10598 	case BPF_MAP_TYPE_RHASH:
10599 	case BPF_MAP_TYPE_LRU_HASH:
10600 	case BPF_MAP_TYPE_ARRAY:
10601 	case BPF_MAP_TYPE_PERCPU_HASH:
10602 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10603 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10604 	case BPF_MAP_TYPE_LPM_TRIE:
10605 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10606 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10607 	case BPF_MAP_TYPE_RINGBUF:
10608 	case BPF_MAP_TYPE_USER_RINGBUF:
10609 	case BPF_MAP_TYPE_INODE_STORAGE:
10610 	case BPF_MAP_TYPE_SK_STORAGE:
10611 	case BPF_MAP_TYPE_TASK_STORAGE:
10612 	case BPF_MAP_TYPE_CGRP_STORAGE:
10613 	case BPF_MAP_TYPE_QUEUE:
10614 	case BPF_MAP_TYPE_STACK:
10615 	case BPF_MAP_TYPE_ARENA:
10616 	case BPF_MAP_TYPE_INSN_ARRAY:
10617 	case BPF_MAP_TYPE_PROG_ARRAY:
10618 	case BPF_MAP_TYPE_BLOOM_FILTER:
10619 		return true;
10620 	default:
10621 		return false;
10622 	}
10623 }
10624 
10625 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10626 					struct bpf_map *map, int func_id)
10627 {
10628 	if (!map)
10629 		return 0;
10630 
10631 	/*
10632 	 * check_map_prog_compatibility() asks the program.  That misses the
10633 	 * sleepable callback of another program, and an inner map.  They may
10634 	 * use any map under the RCU read lock.  Disabled preemption or
10635 	 * interrupts will not do: the maps ask for rcu_read_lock_held().
10636 	 */
10637 	if (!has_rcu_read_lock(env) && !map_needs_no_rcu(map)) {
10638 		verbose(env, "map '%s' needs bpf_rcu_read_lock() in sleepable context\n",
10639 			map->name);
10640 		return -EINVAL;
10641 	}
10642 
10643 	/* We need a two way check, first is from map perspective ... */
10644 	switch (map->map_type) {
10645 	case BPF_MAP_TYPE_PROG_ARRAY:
10646 		if (func_id != BPF_FUNC_tail_call)
10647 			goto error;
10648 		break;
10649 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10650 		if (func_id != BPF_FUNC_perf_event_read &&
10651 		    func_id != BPF_FUNC_perf_event_output &&
10652 		    func_id != BPF_FUNC_skb_output &&
10653 		    func_id != BPF_FUNC_perf_event_read_value &&
10654 		    func_id != BPF_FUNC_xdp_output)
10655 			goto error;
10656 		break;
10657 	case BPF_MAP_TYPE_RINGBUF:
10658 		if (func_id != BPF_FUNC_ringbuf_output &&
10659 		    func_id != BPF_FUNC_ringbuf_reserve &&
10660 		    func_id != BPF_FUNC_ringbuf_query &&
10661 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10662 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10663 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10664 			goto error;
10665 		break;
10666 	case BPF_MAP_TYPE_USER_RINGBUF:
10667 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10668 			goto error;
10669 		break;
10670 	case BPF_MAP_TYPE_STACK_TRACE:
10671 		if (func_id != BPF_FUNC_get_stackid)
10672 			goto error;
10673 		break;
10674 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10675 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10676 		    func_id != BPF_FUNC_current_task_under_cgroup)
10677 			goto error;
10678 		break;
10679 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10680 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10681 		if (func_id != BPF_FUNC_get_local_storage)
10682 			goto error;
10683 		break;
10684 	case BPF_MAP_TYPE_DEVMAP:
10685 	case BPF_MAP_TYPE_DEVMAP_HASH:
10686 		if (func_id != BPF_FUNC_redirect_map &&
10687 		    func_id != BPF_FUNC_map_lookup_elem)
10688 			goto error;
10689 		break;
10690 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10691 	 * appear.
10692 	 */
10693 	case BPF_MAP_TYPE_CPUMAP:
10694 		if (func_id != BPF_FUNC_redirect_map)
10695 			goto error;
10696 		break;
10697 	case BPF_MAP_TYPE_XSKMAP:
10698 		if (func_id != BPF_FUNC_redirect_map &&
10699 		    func_id != BPF_FUNC_map_lookup_elem)
10700 			goto error;
10701 		break;
10702 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10703 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10704 		if (func_id != BPF_FUNC_map_lookup_elem)
10705 			goto error;
10706 		break;
10707 	case BPF_MAP_TYPE_SOCKMAP:
10708 		if (func_id != BPF_FUNC_sk_redirect_map &&
10709 		    func_id != BPF_FUNC_sock_map_update &&
10710 		    func_id != BPF_FUNC_msg_redirect_map &&
10711 		    func_id != BPF_FUNC_sk_select_reuseport &&
10712 		    func_id != BPF_FUNC_map_lookup_elem &&
10713 		    !may_update_sockmap(env, func_id))
10714 			goto error;
10715 		break;
10716 	case BPF_MAP_TYPE_SOCKHASH:
10717 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10718 		    func_id != BPF_FUNC_sock_hash_update &&
10719 		    func_id != BPF_FUNC_msg_redirect_hash &&
10720 		    func_id != BPF_FUNC_sk_select_reuseport &&
10721 		    func_id != BPF_FUNC_map_lookup_elem &&
10722 		    !may_update_sockmap(env, func_id))
10723 			goto error;
10724 		break;
10725 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10726 		if (func_id != BPF_FUNC_sk_select_reuseport)
10727 			goto error;
10728 		break;
10729 	case BPF_MAP_TYPE_QUEUE:
10730 	case BPF_MAP_TYPE_STACK:
10731 		if (func_id != BPF_FUNC_map_peek_elem &&
10732 		    func_id != BPF_FUNC_map_pop_elem &&
10733 		    func_id != BPF_FUNC_map_push_elem)
10734 			goto error;
10735 		break;
10736 	case BPF_MAP_TYPE_SK_STORAGE:
10737 		if (func_id != BPF_FUNC_sk_storage_get &&
10738 		    func_id != BPF_FUNC_sk_storage_delete &&
10739 		    func_id != BPF_FUNC_kptr_xchg)
10740 			goto error;
10741 		break;
10742 	case BPF_MAP_TYPE_INODE_STORAGE:
10743 		if (func_id != BPF_FUNC_inode_storage_get &&
10744 		    func_id != BPF_FUNC_inode_storage_delete &&
10745 		    func_id != BPF_FUNC_kptr_xchg)
10746 			goto error;
10747 		break;
10748 	case BPF_MAP_TYPE_TASK_STORAGE:
10749 		if (func_id != BPF_FUNC_task_storage_get &&
10750 		    func_id != BPF_FUNC_task_storage_delete &&
10751 		    func_id != BPF_FUNC_kptr_xchg)
10752 			goto error;
10753 		break;
10754 	case BPF_MAP_TYPE_CGRP_STORAGE:
10755 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10756 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10757 		    func_id != BPF_FUNC_kptr_xchg)
10758 			goto error;
10759 		break;
10760 	case BPF_MAP_TYPE_BLOOM_FILTER:
10761 		if (func_id != BPF_FUNC_map_peek_elem &&
10762 		    func_id != BPF_FUNC_map_push_elem)
10763 			goto error;
10764 		break;
10765 	case BPF_MAP_TYPE_INSN_ARRAY:
10766 		goto error;
10767 	default:
10768 		break;
10769 	}
10770 
10771 	/* ... and second from the function itself. */
10772 	switch (func_id) {
10773 	case BPF_FUNC_tail_call:
10774 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10775 			goto error;
10776 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
10777 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10778 			return -EINVAL;
10779 		}
10780 		break;
10781 	case BPF_FUNC_perf_event_read:
10782 	case BPF_FUNC_perf_event_output:
10783 	case BPF_FUNC_perf_event_read_value:
10784 	case BPF_FUNC_skb_output:
10785 	case BPF_FUNC_xdp_output:
10786 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10787 			goto error;
10788 		break;
10789 	case BPF_FUNC_ringbuf_output:
10790 	case BPF_FUNC_ringbuf_reserve:
10791 	case BPF_FUNC_ringbuf_query:
10792 	case BPF_FUNC_ringbuf_reserve_dynptr:
10793 	case BPF_FUNC_ringbuf_submit_dynptr:
10794 	case BPF_FUNC_ringbuf_discard_dynptr:
10795 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10796 			goto error;
10797 		break;
10798 	case BPF_FUNC_user_ringbuf_drain:
10799 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10800 			goto error;
10801 		break;
10802 	case BPF_FUNC_get_stackid:
10803 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10804 			goto error;
10805 		break;
10806 	case BPF_FUNC_current_task_under_cgroup:
10807 	case BPF_FUNC_skb_under_cgroup:
10808 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10809 			goto error;
10810 		break;
10811 	case BPF_FUNC_redirect_map:
10812 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10813 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10814 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10815 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10816 			goto error;
10817 		break;
10818 	case BPF_FUNC_sk_redirect_map:
10819 	case BPF_FUNC_msg_redirect_map:
10820 	case BPF_FUNC_sock_map_update:
10821 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10822 			goto error;
10823 		break;
10824 	case BPF_FUNC_sk_redirect_hash:
10825 	case BPF_FUNC_msg_redirect_hash:
10826 	case BPF_FUNC_sock_hash_update:
10827 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10828 			goto error;
10829 		break;
10830 	case BPF_FUNC_get_local_storage:
10831 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10832 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10833 			goto error;
10834 		break;
10835 	case BPF_FUNC_sk_select_reuseport:
10836 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10837 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10838 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10839 			goto error;
10840 		break;
10841 	case BPF_FUNC_map_pop_elem:
10842 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10843 		    map->map_type != BPF_MAP_TYPE_STACK)
10844 			goto error;
10845 		break;
10846 	case BPF_FUNC_map_peek_elem:
10847 	case BPF_FUNC_map_push_elem:
10848 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10849 		    map->map_type != BPF_MAP_TYPE_STACK &&
10850 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10851 			goto error;
10852 		break;
10853 	case BPF_FUNC_map_lookup_percpu_elem:
10854 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10855 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10856 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10857 			goto error;
10858 		break;
10859 	case BPF_FUNC_sk_storage_get:
10860 	case BPF_FUNC_sk_storage_delete:
10861 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10862 			goto error;
10863 		break;
10864 	case BPF_FUNC_inode_storage_get:
10865 	case BPF_FUNC_inode_storage_delete:
10866 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10867 			goto error;
10868 		break;
10869 	case BPF_FUNC_task_storage_get:
10870 	case BPF_FUNC_task_storage_delete:
10871 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10872 			goto error;
10873 		break;
10874 	case BPF_FUNC_cgrp_storage_get:
10875 	case BPF_FUNC_cgrp_storage_delete:
10876 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10877 			goto error;
10878 		break;
10879 	default:
10880 		break;
10881 	}
10882 
10883 	return 0;
10884 error:
10885 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10886 		map->map_type, func_id_name(func_id), func_id);
10887 	return -EINVAL;
10888 }
10889 
10890 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10891 {
10892 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10893 	bool has_size = fn->arg_size[arg] != 0;
10894 	bool is_next_size = false;
10895 
10896 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10897 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10898 
10899 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10900 		return is_next_size;
10901 
10902 	return has_size == is_next_size || is_next_size == is_fixed;
10903 }
10904 
10905 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10906 {
10907 	/* bpf_xxx(..., buf, len) call will access 'len'
10908 	 * bytes from memory 'buf'. Both arg types need
10909 	 * to be paired, so make sure there's no buggy
10910 	 * helper function specification.
10911 	 */
10912 	if (arg_type_is_mem_size(fn->arg1_type) ||
10913 	    check_args_pair_invalid(fn, 0) ||
10914 	    check_args_pair_invalid(fn, 1) ||
10915 	    check_args_pair_invalid(fn, 2) ||
10916 	    check_args_pair_invalid(fn, 3) ||
10917 	    check_args_pair_invalid(fn, 4))
10918 		return false;
10919 
10920 	return true;
10921 }
10922 
10923 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10924 {
10925 	int i;
10926 
10927 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10928 		if (fn->arg_type[i] == ARG_UNUSED)
10929 			break;
10930 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10931 			return !!fn->arg_btf_id[i];
10932 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10933 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10934 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10935 		    /* arg_btf_id and arg_size are in a union. */
10936 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10937 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10938 			return false;
10939 	}
10940 
10941 	return true;
10942 }
10943 
10944 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
10945 {
10946 	int i;
10947 
10948 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10949 		enum bpf_arg_type arg_type = fn->arg_type[i];
10950 
10951 		if (arg_type == ARG_UNUSED)
10952 			break;
10953 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
10954 			continue;
10955 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
10956 			return false;
10957 	}
10958 
10959 	return true;
10960 }
10961 
10962 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
10963 {
10964 	int i;
10965 
10966 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10967 		enum bpf_arg_type arg_type = fn->arg_type[i];
10968 
10969 		if (arg_type == ARG_UNUSED)
10970 			break;
10971 		if (arg_type_is_release(arg_type)) {
10972 			if (meta->release_regno)
10973 				return false;
10974 			meta->release_regno = i + 1;
10975 		}
10976 	}
10977 
10978 	return true;
10979 }
10980 
10981 static bool check_arg_prog_aux(struct bpf_verifier_env *env,
10982 			       const struct bpf_func_proto *proto)
10983 {
10984 	bool seen = false;
10985 	argno_t argno;
10986 	u32 i;
10987 
10988 	for (i = 0; i < ARRAY_SIZE(proto->arg_type); i++) {
10989 		if (proto->arg_type[i] == ARG_UNUSED)
10990 			break;
10991 		if (proto->arg_type[i] != ARG_PTR_TO_PROG_AUX)
10992 			continue;
10993 
10994 		if (seen) {
10995 			verifier_bug(env, "Only 1 prog->aux argument supported");
10996 			return false;
10997 		}
10998 
10999 		argno = argno_from_arg(i + 1);
11000 		if (reg_from_argno(argno) < 0) {
11001 			verbose(env, "%s prog->aux cannot be a stack argument\n",
11002 				reg_arg_name(env, argno));
11003 			return false;
11004 		}
11005 
11006 		seen = true;
11007 	}
11008 
11009 	return true;
11010 }
11011 
11012 static int check_func_proto(struct bpf_verifier_env *env, const struct bpf_func_proto *fn,
11013 			    struct bpf_call_arg_meta *meta)
11014 {
11015 	return check_arg_prog_aux(env, fn) &&
11016 	       check_arg_pair_ok(fn) &&
11017 	       check_mem_arg_rw_flag_ok(fn) &&
11018 	       check_proto_release_reg(fn, meta) &&
11019 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
11020 }
11021 
11022 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
11023  * are now invalid, so turn them into unknown SCALAR_VALUE.
11024  *
11025  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
11026  * since these slices point to packet data.
11027  */
11028 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
11029 {
11030 	struct bpf_func_state *state;
11031 	struct bpf_reg_state *reg;
11032 
11033 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11034 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) {
11035 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_PKT_DATA_CHANGE);
11036 			mark_reg_invalid(env, reg);
11037 		}
11038 	}));
11039 }
11040 
11041 static bool holds_pkt_pointers(struct bpf_verifier_env *env)
11042 {
11043 	struct bpf_func_state *state;
11044 	struct bpf_reg_state *reg;
11045 	bool ret = false;
11046 
11047 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11048 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
11049 			ret = true;
11050 	}));
11051 
11052 	return ret;
11053 }
11054 
11055 enum {
11056 	AT_PKT_END = -1,
11057 	BEYOND_PKT_END = -2,
11058 };
11059 
11060 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
11061 {
11062 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11063 	struct bpf_reg_state *reg = &state->regs[regn];
11064 
11065 	if (reg->type != PTR_TO_PACKET)
11066 		/* PTR_TO_PACKET_META is not supported yet */
11067 		return;
11068 
11069 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
11070 	 * How far beyond pkt_end it goes is unknown.
11071 	 * if (!range_open) it's the case of pkt >= pkt_end
11072 	 * if (range_open) it's the case of pkt > pkt_end
11073 	 * hence this pointer is at least 1 byte bigger than pkt_end
11074 	 */
11075 	if (range_open)
11076 		reg->range = BEYOND_PKT_END;
11077 	else
11078 		reg->range = AT_PKT_END;
11079 }
11080 
11081 static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
11082 {
11083 	int i;
11084 
11085 	for (i = 0; i < state->acquired_refs; i++) {
11086 		if (state->refs[i].type != REF_TYPE_PTR)
11087 			continue;
11088 		if (state->refs[i].id == id) {
11089 			release_reference_state(state, i);
11090 			return 0;
11091 		}
11092 	}
11093 	return -EINVAL;
11094 }
11095 
11096 static int release_reference_nomark(struct bpf_verifier_env *env, int id)
11097 {
11098 	int err;
11099 
11100 	err = __release_reference_nomark(env->cur_state, id);
11101 	if (!err)
11102 		bpf_diag_record_ref_release(env, env->insn_idx, id);
11103 	return err;
11104 }
11105 
11106 static int idstack_push(struct bpf_idmap *idmap, u32 id)
11107 {
11108 	int i;
11109 
11110 	if (!id)
11111 		return 0;
11112 
11113 	for (i = 0; i < idmap->cnt; i++)
11114 		if (idmap->map[i].old == id)
11115 			return 0;
11116 
11117 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
11118 		return -EFAULT;
11119 
11120 	idmap->map[idmap->cnt++].old = id;
11121 	return 0;
11122 }
11123 
11124 static int idstack_pop(struct bpf_idmap *idmap)
11125 {
11126 	if (!idmap->cnt)
11127 		return 0;
11128 
11129 	return idmap->map[--idmap->cnt].old;
11130 }
11131 
11132 /* Invalidate id and objects derived from it iteratively in a DFS manner */
11133 static int invalidate_reference(struct bpf_verifier_env *env, int id)
11134 {
11135 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
11136 	struct bpf_verifier_state *vstate = env->cur_state;
11137 	struct bpf_idmap *idstack = &env->idmap_scratch;
11138 	struct bpf_stack_state *stack;
11139 	struct bpf_func_state *state;
11140 	struct bpf_reg_state *reg;
11141 	int i, err;
11142 
11143 	idstack->cnt = 0;
11144 	err = idstack_push(idstack, id);
11145 	if (err)
11146 		return err;
11147 
11148 	while ((id = idstack_pop(idstack))) {
11149 		/*
11150 		 * Child references are inaccessible after parent is released,
11151 		 * any child references that exist at this point are a leak.
11152 		 */
11153 		for (i = 0; i < vstate->acquired_refs; i++) {
11154 			if (vstate->refs[i].type != REF_TYPE_PTR)
11155 				continue;
11156 			if (vstate->refs[i].parent_id != id)
11157 				continue;
11158 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
11159 				vstate->refs[i].id, vstate->refs[i].insn_idx);
11160 			return -EINVAL;
11161 		}
11162 
11163 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
11164 			if (reg->id != id && reg->parent_id != id)
11165 				continue;
11166 
11167 			/* Free objects derived from the current object */
11168 			if (reg->parent_id == id) {
11169 				err = idstack_push(idstack, reg->id);
11170 				if (err)
11171 					return err;
11172 			}
11173 
11174 			/*
11175 			 * A dynptr occupies two stack slots that invalidate_dynptr()
11176 			 * clears together. Record both scrubs before invalidating it.
11177 			 */
11178 			if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) {
11179 				struct bpf_stack_state *dyn_stack = stack;
11180 
11181 				if (reg->dynptr.first_slot)
11182 					dyn_stack--;
11183 				bpf_diag_record_scrub(env, &dyn_stack[0].spilled_ptr,
11184 						      BPF_DIAG_MOD_REF_RELEASE);
11185 				bpf_diag_record_scrub(env, &dyn_stack[1].spilled_ptr,
11186 						      BPF_DIAG_MOD_REF_RELEASE);
11187 				invalidate_dynptr(env, dyn_stack);
11188 				continue;
11189 			}
11190 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_REF_RELEASE);
11191 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
11192 				mark_reg_invalid(env, reg);
11193 		}));
11194 	}
11195 
11196 	return 0;
11197 }
11198 
11199 static int release_reference(struct bpf_verifier_env *env, int id)
11200 {
11201 	if (find_reference_state(env->cur_state, id))
11202 		WARN_ON_ONCE(release_reference_nomark(env, id));
11203 
11204 	return invalidate_reference(env, id);
11205 }
11206 
11207 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
11208 {
11209 	struct bpf_func_state *unused;
11210 	struct bpf_reg_state *reg;
11211 
11212 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11213 		if (type_is_non_owning_ref(reg->type)) {
11214 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_NON_OWN_REF);
11215 			mark_reg_invalid(env, reg);
11216 		}
11217 	}));
11218 }
11219 
11220 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
11221 {
11222 	struct bpf_stack_state *stack;
11223 	struct bpf_func_state *state;
11224 	struct bpf_reg_state *reg;
11225 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
11226 
11227 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
11228 		if (reg->type & MEM_RCU) {
11229 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
11230 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL | NON_OWN_REF);
11231 			reg->type |= PTR_UNTRUSTED;
11232 			bpf_diag_mod_end(env);
11233 		}
11234 	}));
11235 }
11236 
11237 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
11238 {
11239 	struct bpf_func_state *state;
11240 	struct bpf_reg_state *reg;
11241 	int err;
11242 
11243 	err = release_reference_nomark(env, id);
11244 	if (err)
11245 		return err;
11246 
11247 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11248 		if (reg->id != id)
11249 			continue;
11250 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11251 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
11252 			if (!type_may_be_null(reg->type))
11253 				reg->id = 0;
11254 			reg->type &= ~MEM_ALLOC;
11255 			reg->type |= MEM_RCU;
11256 			bpf_diag_mod_end(env);
11257 		}
11258 	}));
11259 
11260 	return err;
11261 }
11262 
11263 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
11264 				    struct bpf_reg_state *regs)
11265 {
11266 	int i;
11267 
11268 	bpf_diag_record_caller_saved(env, regs);
11269 
11270 	/* after the call registers r0 - r5 were scratched */
11271 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11272 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
11273 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
11274 	}
11275 }
11276 
11277 static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,
11278 					   struct bpf_func_state *state)
11279 {
11280 	int i, nslots = state->out_stack_arg_cnt;
11281 
11282 	for (i = 0; i < nslots; i++) {
11283 		bpf_diag_record_scrub(env, &state->stack_arg_regs[i], BPF_DIAG_MOD_CALLER_SAVED);
11284 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
11285 	}
11286 }
11287 
11288 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
11289 				   struct bpf_func_state *caller,
11290 				   struct bpf_func_state *callee,
11291 				   int insn_idx);
11292 
11293 static int set_callee_state(struct bpf_verifier_env *env,
11294 			    struct bpf_func_state *caller,
11295 			    struct bpf_func_state *callee, int insn_idx);
11296 
11297 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
11298 			    set_callee_state_fn set_callee_state_cb,
11299 			    struct bpf_verifier_state *state)
11300 {
11301 	struct bpf_func_state *caller, *callee;
11302 	int err;
11303 
11304 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
11305 		verbose(env, "the call stack of %d frames is too deep\n",
11306 			state->curframe + 2);
11307 		return -E2BIG;
11308 	}
11309 
11310 	if (state->frame[state->curframe + 1]) {
11311 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
11312 		return -EFAULT;
11313 	}
11314 
11315 	caller = state->frame[state->curframe];
11316 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
11317 	if (!callee)
11318 		return -ENOMEM;
11319 	state->frame[state->curframe + 1] = callee;
11320 
11321 	/* callee cannot access r0, r6 - r9 for reading and has to write
11322 	 * into its own stack before reading from it.
11323 	 * callee can read/write into caller's stack
11324 	 */
11325 	init_func_state(env, callee,
11326 			/* remember the callsite, it will be used by bpf_exit */
11327 			callsite,
11328 			state->curframe + 1 /* frameno within this callchain */,
11329 			subprog /* subprog number within this prog */);
11330 	err = set_callee_state_cb(env, caller, callee, callsite);
11331 	if (err)
11332 		goto err_out;
11333 
11334 	/* only increment it after check_reg_arg() finished */
11335 	state->curframe++;
11336 
11337 	return 0;
11338 
11339 err_out:
11340 	free_func_state(callee);
11341 	state->frame[state->curframe + 1] = NULL;
11342 	return err;
11343 }
11344 
11345 static void gen_subprog_arg_proto(const struct bpf_subprog_info *sub, const struct btf *btf,
11346 				  const struct btf_type *func_proto, struct bpf_func_proto *proto)
11347 {
11348 	const struct btf_param *args = btf_params(func_proto);
11349 	u32 arg, slot = 0;
11350 
11351 	memset(proto, 0, sizeof(*proto));
11352 	for (arg = 0; arg < btf_type_vlen(func_proto); arg++) {
11353 		enum bpf_arg_type arg_type = sub->args[slot].arg_type;
11354 		const struct btf_type *t;
11355 
11356 		if (arg_type & PTR_UNTRUSTED) {
11357 			/*
11358 			 * An __arg_untrusted argument accepts any caller value. The
11359 			 * callee treats it as read-only and uses probe-read instructions
11360 			 * to protect against invalid memory access.
11361 			 */
11362 			arg_type = ARG_IGNORE;
11363 		} else if (base_type(arg_type) == ARG_PTR_TO_ARENA) {
11364 			arg_type |= PTR_MAYBE_NULL;
11365 		} else if (base_type(arg_type) == ARG_PTR_TO_MEM) {
11366 			proto->arg_size[arg] = sub->args[slot].mem_size;
11367 			arg_type |= MEM_FIXED_SIZE | MEM_WRITE;
11368 		} else if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
11369 			proto->arg_btf_id[arg] = &sub->args[slot].btf_id;
11370 		}
11371 		proto->arg_type[arg] = arg_type;
11372 		t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
11373 		slot += btf_arg_slots(t);
11374 	}
11375 }
11376 
11377 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, struct btf *btf)
11378 {
11379 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
11380 	struct bpf_func_state *caller = cur_func(env);
11381 	const struct btf_type *func, *func_proto;
11382 	struct bpf_call_arg_meta meta;
11383 	struct bpf_func_proto *fn;
11384 	int ret, err;
11385 	u32 i;
11386 
11387 	memset(&meta, 0, sizeof(meta));
11388 	meta.btf = btf;
11389 	meta.subprog_may_change_pkt = sub->changes_pkt_data;
11390 	meta.func_name = bpf_subprog_name(env, subprog);
11391 
11392 	ret = btf_prepare_func_args(env, subprog);
11393 	if (ret) {
11394 		if (bpf_in_stack_arg_cnt(sub) > 0) {
11395 			err = check_outgoing_stack_args(env, caller, sub->arg_slot_cnt,
11396 							bpf_subprog_name(env, subprog),
11397 							NULL, NULL);
11398 			if (err)
11399 				return err;
11400 		}
11401 		return ret;
11402 	}
11403 
11404 	func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id);
11405 	func_proto = btf_type_by_id(btf, func->type);
11406 
11407 	fn = &env->bpf_subprog_scratch;
11408 	gen_subprog_arg_proto(sub, btf, func_proto, fn);
11409 	meta.fn = fn;
11410 	meta.func_proto = func_proto;
11411 
11412 	/*
11413 	 * Check if all register arguments declared in BTF are initialized.
11414 	 * If they aren't the BTF is unreliable.
11415 	 */
11416 	if (!bpf_subprog_is_global(env, subprog)) {
11417 		for (i = 0; i < min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++)
11418 			if (caller->regs[BPF_REG_1 + i].type == NOT_INIT)
11419 				return -EINVAL;
11420 	}
11421 	return check_func_args(env, &meta, env->insn_idx);
11422 }
11423 
11424 /*
11425  * Check that call-site argument states match a subprog's BTF signature.
11426  *
11427  * Returns:
11428  * EFAULT - there is a verifier bug. Abort verification.
11429  * Other errors - there is a type mismatch or BTF is not available.
11430  * 0 - BTF matches with what bpf_reg_state expects.
11431  */
11432 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog)
11433 {
11434 	struct bpf_prog *prog = env->prog;
11435 	struct btf *btf = prog->aux->btf;
11436 	u32 btf_id;
11437 	int err;
11438 
11439 	if (!prog->aux->func_info)
11440 		return -EINVAL;
11441 
11442 	btf_id = prog->aux->func_info[subprog].type_id;
11443 	if (!btf_id)
11444 		return -EFAULT;
11445 
11446 	if (prog->aux->func_info_aux[subprog].unreliable)
11447 		return -EINVAL;
11448 
11449 	err = btf_check_func_arg_match(env, subprog, btf);
11450 	/* Compiler optimizations can remove arguments from static functions
11451 	 * or mismatched type can be passed into a global function.
11452 	 * In such cases mark the function as unreliable from BTF point of view.
11453 	 */
11454 	if (err)
11455 		prog->aux->func_info_aux[subprog].unreliable = true;
11456 	return err;
11457 }
11458 
11459 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11460 			      int insn_idx, int subprog,
11461 			      set_callee_state_fn set_callee_state_cb)
11462 {
11463 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
11464 	struct bpf_func_state *caller, *callee;
11465 	int err;
11466 
11467 	caller = state->frame[state->curframe];
11468 	err = btf_check_subprog_call(env, subprog);
11469 	if (err == -EFAULT)
11470 		return err;
11471 	if (bpf_in_stack_arg_cnt(&env->subprog_info[subprog])) {
11472 		verbose(env, "callback subprog cannot have stack args\n");
11473 		return -EINVAL;
11474 	}
11475 
11476 	/* set_callee_state is used for direct subprog calls, but we are
11477 	 * interested in validating only BPF helpers that can call subprogs as
11478 	 * callbacks
11479 	 */
11480 	env->subprog_info[subprog].is_cb = true;
11481 	if (bpf_pseudo_kfunc_call(insn) &&
11482 	    !is_callback_calling_kfunc(insn->imm)) {
11483 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
11484 			     func_id_name(insn->imm), insn->imm);
11485 		return -EFAULT;
11486 	} else if (!bpf_pseudo_kfunc_call(insn) &&
11487 		   !is_callback_calling_function(insn->imm)) { /* helper */
11488 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
11489 			     func_id_name(insn->imm), insn->imm);
11490 		return -EFAULT;
11491 	}
11492 
11493 	if (bpf_is_async_callback_calling_insn(insn)) {
11494 		struct bpf_verifier_state *async_cb;
11495 
11496 		/* there is no real recursion here. timer and workqueue callbacks are async */
11497 		/* there is no cgroup to take the storage from */
11498 		if (env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_SHARED] ||
11499 		    env->prog->aux->cgroup_storage[BPF_CGROUP_STORAGE_PERCPU]) {
11500 			verbose(env, "async callback in a program with cgroup storage\n");
11501 			return -EINVAL;
11502 		}
11503 		env->subprog_info[subprog].is_async_cb = true;
11504 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
11505 					 insn_idx, subprog,
11506 					 is_async_cb_sleepable(env, insn));
11507 		if (IS_ERR(async_cb))
11508 			return PTR_ERR(async_cb);
11509 		if (is_async_cb_sleepable(env, insn))
11510 			mark_sleepable_async_cb(env);
11511 		callee = async_cb->frame[0];
11512 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
11513 
11514 		/* Convert bpf_timer_set_callback() args into timer callback args */
11515 		err = set_callee_state_cb(env, caller, callee, insn_idx);
11516 		if (err)
11517 			return err;
11518 
11519 		return 0;
11520 	}
11521 
11522 	/*
11523 	 * The address of the callback might be taken in another function or
11524 	 * read from a map, see check_func_ptr_read(). Like with callx it's
11525 	 * known here what is called.
11526 	 */
11527 	err = record_callx_edge(env, caller->subprogno, subprog);
11528 	if (err)
11529 		return err;
11530 
11531 	if (!bpf_pseudo_kfunc_call(insn) &&
11532 	    (insn->imm == BPF_FUNC_loop || insn->imm == BPF_FUNC_for_each_map_elem))
11533 		env->subprog_info[subprog].is_loop_cb = true;
11534 	else
11535 		env->subprog_info[subprog].is_called = true;
11536 
11537 	/* for callback functions enqueue entry to callback and
11538 	 * proceed with next instruction within current frame.
11539 	 */
11540 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
11541 	if (IS_ERR(callback_state))
11542 		return PTR_ERR(callback_state);
11543 
11544 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
11545 			       callback_state);
11546 	if (err)
11547 		return err;
11548 
11549 	callback_state->callback_unroll_depth++;
11550 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
11551 	caller->callback_depth = 0;
11552 	return 0;
11553 }
11554 
11555 static int process_bpf_exit_full(struct bpf_verifier_env *env,
11556 				 bool *do_print_state, bool exception_exit);
11557 
11558 /*
11559  * Call of a static subprog. The callee is verified in the context of
11560  * the caller, hence set up a new frame and continue from the first
11561  * instruction of the callee.
11562  */
11563 static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
11564 				  int *insn_idx)
11565 {
11566 	struct bpf_verifier_state *state = env->cur_state;
11567 	struct bpf_subprog_info *caller_info;
11568 	u16 callee_incoming, stack_arg_cnt;
11569 	struct bpf_func_state *caller;
11570 	int err;
11571 
11572 	caller = state->frame[state->curframe];
11573 	env->subprog_info[subprog].is_called = true;
11574 
11575 	/*
11576 	 * Track caller's total stack arg count (incoming + max outgoing).
11577 	 * This is needed so the JIT knows how much stack arg space to allocate.
11578 	 */
11579 	caller_info = &env->subprog_info[caller->subprogno];
11580 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
11581 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
11582 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
11583 		caller_info->stack_arg_cnt = stack_arg_cnt;
11584 
11585 	/*
11586 	 * For regular function entry setup new frame and continue
11587 	 * from that frame.
11588 	 */
11589 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
11590 	if (err)
11591 		return err;
11592 
11593 	bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11594 	clear_caller_saved_regs(env, caller->regs);
11595 
11596 	/* and go analyze first insn of the callee */
11597 	*insn_idx = env->subprog_info[subprog].start - 1;
11598 
11599 	if (env->log.level & BPF_LOG_LEVEL) {
11600 		verbose(env, "caller:\n");
11601 		print_verifier_state(env, state, caller->frameno, true);
11602 		verbose(env, "callee:\n");
11603 		print_verifier_state(env, state, state->curframe, true);
11604 	}
11605 
11606 	return 0;
11607 }
11608 
11609 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11610 			   int *insn_idx)
11611 {
11612 	struct bpf_verifier_state *state = env->cur_state;
11613 	struct bpf_func_state *caller;
11614 	int err, subprog, target_insn;
11615 	u32 i, nregs;
11616 
11617 	target_insn = *insn_idx + insn->imm + 1;
11618 	subprog = bpf_find_subprog(env, target_insn);
11619 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
11620 			    target_insn))
11621 		return -EFAULT;
11622 
11623 	caller = state->frame[state->curframe];
11624 	err = btf_check_subprog_call(env, subprog);
11625 	if (err == -EFAULT)
11626 		return err;
11627 	if (bpf_subprog_is_global(env, subprog)) {
11628 		struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog);
11629 		const char *sub_name = bpf_subprog_name(env, subprog);
11630 		const char *operation;
11631 		bool returns_void;
11632 
11633 		if (env->cur_state->active_locks) {
11634 			verbose(env, "global function calls are not allowed while holding a lock,\n"
11635 				     "use static function instead\n");
11636 			operation = bpf_diag_fmt(env, "global function %s()", sub_name);
11637 			bpf_diag_ctx_active(env, *insn_idx, operation, BPF_DIAG_CONTEXT_LOCK,
11638 					    "Release the lock before calling the global function, or use a static function instead.");
11639 			return -EINVAL;
11640 		}
11641 
11642 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
11643 			const char *suggestion;
11644 
11645 			verbose(env, "sleepable global function %s() called in %s\n",
11646 				sub_name, non_sleepable_context_description(env));
11647 			if (in_sleepable(env))
11648 				suggestion = "Move the call outside the critical section, or use a non-sleepable function.";
11649 			else
11650 				suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable function.";
11651 			operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name);
11652 			bpf_diag_ctx_forbidden(env, *insn_idx, operation, suggestion);
11653 			return -EINVAL;
11654 		}
11655 
11656 		if (err) {
11657 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
11658 				subprog, sub_name);
11659 			return err;
11660 		}
11661 
11662 		if (env->log.level & BPF_LOG_LEVEL)
11663 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
11664 				subprog, sub_name);
11665 		if (in_sleepable_context(env))
11666 			sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = true;
11667 		else if (has_rcu_read_lock(env))
11668 			sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = true;
11669 		else
11670 			sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = true;
11671 		returns_void = subprog_returns_void(env, subprog);
11672 		if (env->subprog_info[subprog].changes_pkt_data)
11673 			clear_all_pkt_pointers(env);
11674 		if (returns_void)
11675 			bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11676 		else
11677 			bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
11678 		clear_caller_saved_regs(env, caller->regs);
11679 		invalidate_outgoing_stack_args(env, cur_func(env));
11680 		/*
11681 		 * What the callers of a global function hold is not known
11682 		 * while it is verified.
11683 		 */
11684 		if (!env->subprog_info[subprog].changes_pkt_data &&
11685 		    (state->frame[0]->subprogno || holds_pkt_pointers(env)))
11686 			sub_aux->called_with_pkt_ptrs = true;
11687 
11688 		/*
11689 		 * A non-void global function returns a 64-bit SCALAR_VALUE in
11690 		 * R0, or a >8 byte SCALAR_VALUE in the R0:R2 register pair.
11691 		 */
11692 		if (!returns_void) {
11693 			nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
11694 			mark_reg_unknown(env, caller->regs, ret_regs[0]);
11695 			bpf_diag_mod_end(env);
11696 			for (i = 1; i < nregs; i++) {
11697 				bpf_diag_mod_begin(env, &caller->regs[ret_regs[i]], NULL,
11698 						   BPF_DIAG_MOD_WRITE);
11699 				mark_reg_unknown(env, caller->regs, ret_regs[i]);
11700 				bpf_diag_mod_end(env);
11701 			}
11702 		}
11703 
11704 		if (env->subprog_info[subprog].can_unwind) {
11705 			struct bpf_verifier_state *branch;
11706 
11707 			if (!bpf_is_unwind_goto(insn + 1)) {
11708 				verbose(env, "no unwind_goto after the call of %s()\n", sub_name);
11709 				return -EINVAL;
11710 			}
11711 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
11712 			if (IS_ERR(branch))
11713 				return PTR_ERR(branch);
11714 			branch->unwound = true;
11715 		}
11716 
11717 		if (env->subprog_info[subprog].might_throw) {
11718 			struct bpf_verifier_state *branch;
11719 
11720 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
11721 			if (IS_ERR(branch)) {
11722 				verbose(env, "failed to push state for global subprog exception path\n");
11723 				return PTR_ERR(branch);
11724 			}
11725 			return process_bpf_exit_full(env, NULL, true);
11726 		}
11727 
11728 		/* continue with next insn after call */
11729 		return 0;
11730 	}
11731 
11732 	return check_static_func_call(env, subprog, insn_idx);
11733 }
11734 
11735 /*
11736  * callx dst_reg: call a bpf subprog whose address is in dst_reg.
11737  *
11738  * The address of a subprog is either loaded into a register by ld_imm64 with
11739  * src_reg == BPF_PSEUDO_FUNC, or it is read from a frozen read-only map, see
11740  * resolve_func_ptrs(). Both are possible for static subprogs only. Hence all
11741  * possible callees of callx are discovered by add_subprogs() and are reachable
11742  * in the control flow graph before the main verification pass begins.
11743  * PTR_TO_FUNC register identifies the callee, so from here on callx is verified
11744  * as a direct call of that static subprog.
11745  */
11746 static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn,
11747 			    int *insn_idx)
11748 {
11749 	struct bpf_func_state *caller = cur_func(env);
11750 	struct bpf_reg_state *reg;
11751 	const char *reason;
11752 	int err, subprog;
11753 
11754 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11755 	if (err)
11756 		return err;
11757 
11758 	reg = reg_state(env, insn->dst_reg);
11759 	if (reg->type != PTR_TO_FUNC) {
11760 		verbose(env, "R%d has type %s, expected func\n", insn->dst_reg,
11761 			reg_type_str(env, reg->type));
11762 		reason = bpf_diag_fmt(
11763 			env, "R%d holds %s, but callx can only call through the address of a static BPF function.",
11764 			insn->dst_reg, bpf_diag_reg_type_plain(env, reg->type));
11765 		bpf_diag_register_type(
11766 			env, *insn_idx, insn->dst_reg, "indirect call through a non-function pointer", reason,
11767 			"Load the address of a static BPF function into the register before callx.");
11768 		return -EACCES;
11769 	}
11770 
11771 	/*
11772 	 * Arithmetic on PTR_TO_FUNC is allowed, but only unmodified address
11773 	 * of a subprog can be called.
11774 	 */
11775 	err = check_ptr_off_reg(env, reg, insn->dst_reg);
11776 	if (err)
11777 		return err;
11778 
11779 	/* the callx is valid, but only a JIT can execute it */
11780 	err = require_callx_jit(env);
11781 	if (err)
11782 		return err;
11783 
11784 	/* PTR_TO_FUNC is a pointer to a static subprog */
11785 	subprog = reg->subprogno;
11786 	err = btf_check_subprog_call(env, subprog);
11787 	if (err == -EFAULT)
11788 		return err;
11789 
11790 	err = record_callx_edge(env, caller->subprogno, subprog);
11791 	if (err)
11792 		return err;
11793 
11794 	return check_static_func_call(env, subprog, insn_idx);
11795 }
11796 
11797 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
11798 				   struct bpf_func_state *caller,
11799 				   struct bpf_func_state *callee)
11800 {
11801 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
11802 	 *      void *callback_ctx, u64 flags);
11803 	 * callback_fn(struct bpf_map *map, void *key, void *value,
11804 	 *      void *callback_ctx);
11805 	 */
11806 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11807 
11808 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11809 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11810 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11811 	callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid;
11812 
11813 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11814 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11815 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11816 	callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid;
11817 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11818 
11819 	/* pointer to stack or null */
11820 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
11821 
11822 	/* unused */
11823 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11824 	return 0;
11825 }
11826 
11827 static int set_callee_state(struct bpf_verifier_env *env,
11828 			    struct bpf_func_state *caller,
11829 			    struct bpf_func_state *callee, int insn_idx)
11830 {
11831 	int i;
11832 
11833 	/* copy r1 - r5 args that callee can access.  The copy includes parent
11834 	 * pointers, which connects us up to the liveness chain
11835 	 */
11836 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
11837 		callee->regs[i] = caller->regs[i];
11838 	return 0;
11839 }
11840 
11841 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
11842 				       struct bpf_func_state *caller,
11843 				       struct bpf_func_state *callee,
11844 				       int insn_idx)
11845 {
11846 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
11847 	struct bpf_map *map;
11848 	int err;
11849 
11850 	/* valid map_ptr and poison value does not matter */
11851 	map = insn_aux->map_ptr_state.map_ptr;
11852 	if (!map->ops->map_set_for_each_callback_args ||
11853 	    !map->ops->map_for_each_callback) {
11854 		verbose(env, "callback function not allowed for map\n");
11855 		return -ENOTSUPP;
11856 	}
11857 
11858 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
11859 	if (err)
11860 		return err;
11861 
11862 	switch (map->map_type) {
11863 	case BPF_MAP_TYPE_HASH:
11864 	case BPF_MAP_TYPE_PERCPU_HASH:
11865 	case BPF_MAP_TYPE_LRU_HASH:
11866 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11867 	case BPF_MAP_TYPE_RHASH:
11868 		/* Hash tables run the callback under rcu_read_lock(). */
11869 		callee->in_rcu_callback_fn = true;
11870 		break;
11871 	default:
11872 		break;
11873 	}
11874 
11875 	callee->in_callback_fn = true;
11876 	callee->callback_ret_range = retval_range(0, 1);
11877 	return 0;
11878 }
11879 
11880 static int set_loop_callback_state(struct bpf_verifier_env *env,
11881 				   struct bpf_func_state *caller,
11882 				   struct bpf_func_state *callee,
11883 				   int insn_idx)
11884 {
11885 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
11886 	 *	    u64 flags);
11887 	 * callback_fn(u64 index, void *callback_ctx);
11888 	 */
11889 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
11890 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11891 
11892 	/* unused */
11893 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11894 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11895 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11896 
11897 	callee->in_callback_fn = true;
11898 	callee->callback_ret_range = retval_range(0, 1);
11899 	return 0;
11900 }
11901 
11902 static int set_timer_callback_state(struct bpf_verifier_env *env,
11903 				    struct bpf_func_state *caller,
11904 				    struct bpf_func_state *callee,
11905 				    int insn_idx)
11906 {
11907 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
11908 	u32 map_uid = caller->regs[BPF_REG_1].map_uid;
11909 
11910 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
11911 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11912 	 */
11913 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11914 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11915 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11916 	callee->regs[BPF_REG_1].map_uid = map_uid;
11917 
11918 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11919 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11920 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11921 	callee->regs[BPF_REG_2].map_uid = map_uid;
11922 
11923 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11924 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11925 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11926 	callee->regs[BPF_REG_3].map_uid = map_uid;
11927 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11928 
11929 	/* unused */
11930 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11931 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11932 	callee->in_async_callback_fn = true;
11933 	callee->callback_ret_range = retval_range(0, 0);
11934 	return 0;
11935 }
11936 
11937 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
11938 				       struct bpf_func_state *caller,
11939 				       struct bpf_func_state *callee,
11940 				       int insn_idx)
11941 {
11942 	/* bpf_find_vma(struct task_struct *task, u64 addr,
11943 	 *               void *callback_fn, void *callback_ctx, u64 flags)
11944 	 * (callback_fn)(struct task_struct *task,
11945 	 *               struct vm_area_struct *vma, void *callback_ctx);
11946 	 */
11947 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11948 
11949 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
11950 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11951 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
11952 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
11953 
11954 	/* pointer to stack or null */
11955 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
11956 
11957 	/* unused */
11958 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11959 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11960 	callee->in_callback_fn = true;
11961 	/* bpf_find_vma() runs the callback under mmap_lock and RCU. */
11962 	callee->in_rcu_callback_fn = true;
11963 	callee->callback_ret_range = retval_range(0, 1);
11964 	return 0;
11965 }
11966 
11967 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
11968 					   struct bpf_func_state *caller,
11969 					   struct bpf_func_state *callee,
11970 					   int insn_idx)
11971 {
11972 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
11973 	 *			  callback_ctx, u64 flags);
11974 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
11975 	 */
11976 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
11977 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
11978 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11979 
11980 	/* unused */
11981 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11982 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11983 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11984 
11985 	callee->in_callback_fn = true;
11986 	callee->callback_ret_range = retval_range(0, 1);
11987 	return 0;
11988 }
11989 
11990 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
11991 					 struct bpf_func_state *caller,
11992 					 struct bpf_func_state *callee,
11993 					 int insn_idx)
11994 {
11995 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
11996 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
11997 	 *
11998 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
11999 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
12000 	 * by this point, so look at 'root'
12001 	 */
12002 	struct btf_field *field;
12003 
12004 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
12005 				      caller->regs[BPF_REG_1].var_off.value,
12006 				      BPF_RB_ROOT);
12007 	if (!field || !field->graph_root.value_btf_id)
12008 		return -EFAULT;
12009 
12010 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
12011 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
12012 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
12013 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
12014 
12015 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
12016 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
12017 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
12018 	callee->in_callback_fn = true;
12019 	callee->callback_ret_range = retval_range(0, 1);
12020 	return 0;
12021 }
12022 
12023 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
12024 						 struct bpf_func_state *caller,
12025 						 struct bpf_func_state *callee,
12026 						 int insn_idx)
12027 {
12028 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
12029 	u32 map_uid = caller->regs[BPF_REG_3].map_uid;
12030 
12031 	/*
12032 	 * callback_fn(struct bpf_map *map, void *key, void *value);
12033 	 */
12034 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
12035 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
12036 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
12037 	callee->regs[BPF_REG_1].map_uid = map_uid;
12038 
12039 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
12040 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
12041 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
12042 	callee->regs[BPF_REG_2].map_uid = map_uid;
12043 
12044 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
12045 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
12046 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
12047 	callee->regs[BPF_REG_3].map_uid = map_uid;
12048 	callee->regs[BPF_REG_3].id = ++env->id_gen;
12049 
12050 	/* unused */
12051 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
12052 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
12053 	callee->in_async_callback_fn = true;
12054 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
12055 	return 0;
12056 }
12057 
12058 static int set_rcu_callback_state(struct bpf_verifier_env *env,
12059 				  struct bpf_func_state *caller,
12060 				  struct bpf_func_state *callee,
12061 				  int insn_idx)
12062 {
12063 	struct bpf_map *map_ptr = caller->regs[BPF_REG_2].map_ptr;
12064 	u32 map_uid = caller->regs[BPF_REG_2].map_uid;
12065 
12066 	/*
12067 	 * callback_fn(struct bpf_map *map, void *key, void *value);
12068 	 */
12069 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
12070 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
12071 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
12072 	callee->regs[BPF_REG_1].map_uid = map_uid;
12073 
12074 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
12075 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
12076 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
12077 	callee->regs[BPF_REG_2].map_uid = map_uid;
12078 
12079 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
12080 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
12081 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
12082 	callee->regs[BPF_REG_3].map_uid = map_uid;
12083 
12084 	/* unused */
12085 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
12086 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
12087 	callee->in_async_callback_fn = true;
12088 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
12089 	return 0;
12090 }
12091 
12092 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
12093 
12094 static void account_processed_insn(struct bpf_verifier_env *env)
12095 {
12096 	struct bpf_func_state *frame = cur_func(env);
12097 
12098 	env->insn_processed++;
12099 	frame->insns_subtotal++;
12100 	env->subprog_info[frame->subprogno].insns_self++;
12101 }
12102 
12103 static void account_processed_insns(struct bpf_verifier_env *env,
12104 				    struct bpf_func_state *callee,
12105 				    struct bpf_func_state *caller)
12106 {
12107 	u32 insns;
12108 
12109 	if (!callee)
12110 		return;
12111 
12112 	insns = callee->insns_subtotal;
12113 
12114 	env->subprog_info[callee->subprogno].insns_total += insns;
12115 	if (caller)
12116 		caller->insns_subtotal += insns;
12117 	callee->insns_subtotal = 0;
12118 }
12119 
12120 static void account_current_path(struct bpf_verifier_env *env)
12121 {
12122 	struct bpf_verifier_state *state = env->cur_state;
12123 	int frame;
12124 
12125 	for (frame = state->curframe; frame >= 0; frame--)
12126 		account_processed_insns(env, state->frame[frame],
12127 					frame ? state->frame[frame - 1] : NULL);
12128 }
12129 
12130 /*
12131  * Are we currently verifying the callback for an rbtree kfunc that must
12132  * be called with a lock held, or one of that callback's subprogs? If so,
12133  * no need to complain about an unreleased lock.
12134  */
12135 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
12136 {
12137 	struct bpf_verifier_state *state = env->cur_state;
12138 	struct bpf_insn *insn = env->prog->insnsi;
12139 	struct bpf_func_state *callee;
12140 	int kfunc_btf_id;
12141 	u32 frame;
12142 
12143 	for (frame = state->curframe; frame; frame--) {
12144 		callee = state->frame[frame];
12145 		if (!callee->in_callback_fn)
12146 			continue;
12147 
12148 		kfunc_btf_id = insn[callee->callsite].imm;
12149 		if (is_rbtree_lock_required_kfunc(kfunc_btf_id))
12150 			return true;
12151 	}
12152 
12153 	return false;
12154 }
12155 
12156 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
12157 {
12158 	if (range.return_32bit)
12159 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
12160 	else
12161 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
12162 }
12163 
12164 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
12165 {
12166 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
12167 	struct bpf_func_state *caller, *callee;
12168 	struct bpf_reg_state *r0;
12169 	bool in_callback_fn;
12170 	u32 i, nregs;
12171 	int err;
12172 
12173 	callee = state->frame[state->curframe];
12174 	r0 = &callee->regs[BPF_REG_0];
12175 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
12176 	for (i = 0; i < nregs; i++) {
12177 		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
12178 			continue;
12179 		/* technically it's ok to return caller's stack pointer
12180 		 * (or caller's caller's pointer) back to the caller,
12181 		 * since these pointers are valid. Only current stack
12182 		 * pointer will be invalid as soon as function exits,
12183 		 * but let's be conservative
12184 		 */
12185 		verbose(env, "cannot return stack pointer to the caller\n");
12186 		return -EINVAL;
12187 	}
12188 
12189 	caller = state->frame[state->curframe - 1];
12190 	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx])) {
12191 		/* the helper or the kfunc that called it doesn't expect that */
12192 		if (callee->in_callback_fn) {
12193 			verbose(env, "callback cannot unwind\n");
12194 			return -EINVAL;
12195 		}
12196 		if (!bpf_is_unwind_goto(&env->prog->insnsi[callee->callsite + 1])) {
12197 			verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
12198 				callee->callsite);
12199 			return -EINVAL;
12200 		}
12201 		state->unwound = true;
12202 	}
12203 	if (callee->in_callback_fn) {
12204 		if (r0->type != SCALAR_VALUE) {
12205 			verbose(env, "R0 not a scalar value\n");
12206 			return -EACCES;
12207 		}
12208 
12209 		/* we are going to rely on register's precise value */
12210 		err = mark_chain_precision(env, BPF_REG_0);
12211 		if (err)
12212 			return err;
12213 
12214 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
12215 		if (!retval_range_within(callee->callback_ret_range, r0)) {
12216 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
12217 					       "At callback return", "R0");
12218 			return -EINVAL;
12219 		}
12220 		if (!bpf_calls_callback(env, callee->callsite)) {
12221 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
12222 				     *insn_idx, callee->callsite);
12223 			return -EFAULT;
12224 		}
12225 	} else {
12226 		/*
12227 		 * return to the caller whatever the callee had in the
12228 		 * return register(s)
12229 		 */
12230 		for (i = 0; i < nregs; i++) {
12231 			u32 regno = ret_regs[i];
12232 
12233 			bpf_diag_mod_begin(env, &caller->regs[regno], &callee->regs[regno],
12234 					   BPF_DIAG_MOD_WRITE);
12235 			caller->regs[regno] = callee->regs[regno];
12236 			bpf_diag_mod_end(env);
12237 		}
12238 	}
12239 
12240 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
12241 	err = destroy_dynptrs_in_stack_slots(env, callee, 0,
12242 					     callee->allocated_stack / BPF_REG_SIZE - 1);
12243 	if (err)
12244 		return err;
12245 	invalidate_stack_slices(env, callee->frameno, INT_MIN, 0);
12246 
12247 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
12248 	 * there function call logic would reschedule callback visit. If iteration
12249 	 * converges is_state_visited() would prune that visit eventually.
12250 	 */
12251 	in_callback_fn = callee->in_callback_fn;
12252 	if (in_callback_fn)
12253 		*insn_idx = callee->callsite;
12254 	else
12255 		*insn_idx = callee->callsite + 1;
12256 
12257 	if (env->log.level & BPF_LOG_LEVEL) {
12258 		verbose(env, "returning from callee:\n");
12259 		print_verifier_state(env, state, callee->frameno, true);
12260 		verbose(env, "to caller at %d:\n", *insn_idx);
12261 		print_verifier_state(env, state, caller->frameno, true);
12262 	}
12263 	account_processed_insns(env, callee, caller);
12264 	/* clear everything in the callee. In case of exceptional exits using
12265 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
12266 	free_func_state(callee);
12267 	state->frame[state->curframe--] = NULL;
12268 	invalidate_outgoing_stack_args(env, caller);
12269 
12270 	/* for callbacks widen imprecise scalars to make programs like below verify:
12271 	 *
12272 	 *   struct ctx { int i; }
12273 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
12274 	 *   ...
12275 	 *   struct ctx = { .i = 0; }
12276 	 *   bpf_loop(100, cb, &ctx, 0);
12277 	 *
12278 	 * This is similar to what is done in process_iter_next_call() for open
12279 	 * coded iterators.
12280 	 */
12281 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
12282 	if (prev_st) {
12283 		err = widen_imprecise_scalars(env, prev_st, state);
12284 		if (err)
12285 			return err;
12286 	}
12287 	return 0;
12288 }
12289 
12290 static int do_refine_retval_range(struct bpf_verifier_env *env,
12291 				  struct bpf_reg_state *regs, int ret_type,
12292 				  int func_id,
12293 				  struct bpf_call_arg_meta *meta)
12294 {
12295 	struct bpf_retval_range range;
12296 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
12297 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12298 
12299 	if (ret_type != RET_INTEGER)
12300 		return 0;
12301 
12302 	switch (func_id) {
12303 	case BPF_FUNC_get_stack:
12304 	case BPF_FUNC_get_task_stack:
12305 	case BPF_FUNC_probe_read_str:
12306 	case BPF_FUNC_probe_read_kernel_str:
12307 	case BPF_FUNC_probe_read_user_str:
12308 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
12309 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
12310 		reg_bounds_sync(ret_reg);
12311 		break;
12312 	case BPF_FUNC_get_smp_processor_id:
12313 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
12314 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
12315 		reg_bounds_sync(ret_reg);
12316 		break;
12317 	case BPF_FUNC_get_retval:
12318 		/*
12319 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
12320 		 * CGROUP_GETSOCKOPT type.
12321 		 */
12322 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
12323 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
12324 			break;
12325 
12326 		/* It is what the previous struct bpf_tcp_ops returned, any int */
12327 		if (prog_type == BPF_PROG_TYPE_STRUCT_OPS)
12328 			break;
12329 
12330 		if (prog_type == BPF_PROG_TYPE_LSM &&
12331 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
12332 			if (!env->prog->aux->attach_func_proto->type)
12333 				break;
12334 			bpf_lsm_get_retval_range(env->prog, &range);
12335 		} else {
12336 			range.minval = -MAX_ERRNO;
12337 			range.maxval = 0;
12338 		}
12339 
12340 		reg_set_srange64(ret_reg, range.minval, range.maxval);
12341 		reg_set_srange32(ret_reg, range.minval, range.maxval);
12342 		reg_bounds_sync(ret_reg);
12343 		break;
12344 	}
12345 
12346 	return reg_bounds_sanity_check(env, ret_reg, "retval");
12347 }
12348 
12349 static int
12350 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12351 		int func_id, int insn_idx)
12352 {
12353 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12354 	struct bpf_map *map = meta->map.ptr;
12355 
12356 	if (func_id != BPF_FUNC_tail_call &&
12357 	    func_id != BPF_FUNC_map_lookup_elem &&
12358 	    func_id != BPF_FUNC_map_update_elem &&
12359 	    func_id != BPF_FUNC_map_delete_elem &&
12360 	    func_id != BPF_FUNC_map_push_elem &&
12361 	    func_id != BPF_FUNC_map_pop_elem &&
12362 	    func_id != BPF_FUNC_map_peek_elem &&
12363 	    func_id != BPF_FUNC_for_each_map_elem &&
12364 	    func_id != BPF_FUNC_redirect_map &&
12365 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
12366 		return 0;
12367 
12368 	if (map == NULL) {
12369 		verifier_bug(env, "expected map for helper call");
12370 		return -EFAULT;
12371 	}
12372 
12373 	/* In case of read-only, some additional restrictions
12374 	 * need to be applied in order to prevent altering the
12375 	 * state of the map from program side.
12376 	 */
12377 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
12378 	    (func_id == BPF_FUNC_map_delete_elem ||
12379 	     func_id == BPF_FUNC_map_update_elem ||
12380 	     func_id == BPF_FUNC_map_push_elem ||
12381 	     func_id == BPF_FUNC_map_pop_elem)) {
12382 		verbose(env, "write into map forbidden\n");
12383 		return -EACCES;
12384 	}
12385 
12386 	if (!aux->map_ptr_state.map_ptr)
12387 		bpf_map_ptr_store(aux, meta->map.ptr,
12388 				  !meta->map.ptr->bypass_spec_v1, false);
12389 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
12390 		bpf_map_ptr_store(aux, meta->map.ptr,
12391 				  !meta->map.ptr->bypass_spec_v1, true);
12392 	return 0;
12393 }
12394 
12395 static int
12396 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12397 		int func_id, int insn_idx)
12398 {
12399 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12400 	struct bpf_reg_state *reg;
12401 	struct bpf_map *map = meta->map.ptr;
12402 	u64 val, max;
12403 	int err;
12404 
12405 	if (func_id != BPF_FUNC_tail_call)
12406 		return 0;
12407 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
12408 		verbose(env, "expected prog array map for tail call");
12409 		return -EINVAL;
12410 	}
12411 
12412 	reg = reg_state(env, BPF_REG_3);
12413 	val = reg->var_off.value;
12414 	max = map->max_entries;
12415 
12416 	if (!(is_reg_const(reg, false) && val < max)) {
12417 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12418 		return 0;
12419 	}
12420 
12421 	err = mark_chain_precision(env, BPF_REG_3);
12422 	if (err)
12423 		return err;
12424 	if (bpf_map_key_unseen(aux))
12425 		bpf_map_key_store(aux, val);
12426 	else if (!bpf_map_key_poisoned(aux) &&
12427 		  bpf_map_key_immediate(aux) != val)
12428 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12429 	return 0;
12430 }
12431 
12432 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
12433 {
12434 	struct bpf_verifier_state *state = env->cur_state;
12435 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12436 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
12437 	bool refs_lingering = false;
12438 	int i;
12439 
12440 	if (!exception_exit && cur_func(env)->frameno)
12441 		return 0;
12442 
12443 	for (i = 0; i < state->acquired_refs; i++) {
12444 		if (state->refs[i].type != REF_TYPE_PTR)
12445 			continue;
12446 		/* Allow struct_ops programs to return a referenced kptr back to
12447 		 * kernel. Type checks are performed later in check_return_code.
12448 		 */
12449 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
12450 		    reg->id == state->refs[i].id)
12451 			continue;
12452 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
12453 			state->refs[i].id, state->refs[i].insn_idx);
12454 		bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx);
12455 		refs_lingering = true;
12456 	}
12457 	return refs_lingering ? -EINVAL : 0;
12458 }
12459 
12460 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
12461 {
12462 	int err;
12463 
12464 	if (check_lock && env->cur_state->active_locks) {
12465 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
12466 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_LOCK,
12467 				    "Release the BPF spin lock before this operation on every path.");
12468 		return -EINVAL;
12469 	}
12470 
12471 	err = check_reference_leak(env, exception_exit);
12472 	if (err) {
12473 		verbose(env, "%s would lead to reference leak\n", prefix);
12474 		return err;
12475 	}
12476 
12477 	if (check_lock && env->cur_state->active_irq_id) {
12478 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
12479 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_IRQ,
12480 				    "Restore the saved IRQ state before this operation on every path.");
12481 		return -EINVAL;
12482 	}
12483 
12484 	if (check_lock && env->cur_state->active_rcu_locks) {
12485 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
12486 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_RCU,
12487 				    "Call bpf_rcu_read_unlock() before this operation on every path.");
12488 		return -EINVAL;
12489 	}
12490 
12491 	if (check_lock && env->cur_state->active_preempt_locks) {
12492 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
12493 		bpf_diag_ctx_active(
12494 			env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_PREEMPT,
12495 			"Call bpf_preempt_enable() before this operation on every path.");
12496 		return -EINVAL;
12497 	}
12498 
12499 	return 0;
12500 }
12501 
12502 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
12503 				   struct bpf_reg_state *regs)
12504 {
12505 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
12506 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
12507 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
12508 	struct bpf_bprintf_data data = {};
12509 	int err, fmt_map_off, num_args;
12510 	u64 fmt_addr;
12511 	char *fmt;
12512 
12513 	/* data must be an array of u64 */
12514 	if (data_len_reg->var_off.value % 8)
12515 		return -EINVAL;
12516 	num_args = data_len_reg->var_off.value / 8;
12517 
12518 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
12519 	 * and map_direct_value_addr is set.
12520 	 */
12521 	fmt_map_off = fmt_reg->var_off.value;
12522 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
12523 						  fmt_map_off);
12524 	if (err) {
12525 		verbose(env, "failed to retrieve map value address\n");
12526 		return -EFAULT;
12527 	}
12528 	fmt = (char *)(long)fmt_addr + fmt_map_off;
12529 
12530 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
12531 	 * can focus on validating the format specifiers.
12532 	 */
12533 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
12534 	if (err < 0)
12535 		verbose(env, "Invalid format string\n");
12536 
12537 	return err;
12538 }
12539 
12540 static int check_get_func_ip(struct bpf_verifier_env *env)
12541 {
12542 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12543 	int func_id = BPF_FUNC_get_func_ip;
12544 
12545 	if (type == BPF_PROG_TYPE_TRACING) {
12546 		if (!bpf_prog_has_trampoline(env->prog)) {
12547 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
12548 				func_id_name(func_id), func_id);
12549 			return -ENOTSUPP;
12550 		}
12551 		return 0;
12552 	} else if (type == BPF_PROG_TYPE_KPROBE) {
12553 		return 0;
12554 	}
12555 
12556 	verbose(env, "func %s#%d not supported for program type %d\n",
12557 		func_id_name(func_id), func_id, type);
12558 	return -ENOTSUPP;
12559 }
12560 
12561 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
12562 {
12563 	return &env->insn_aux_data[env->insn_idx];
12564 }
12565 
12566 /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */
12567 static int loop_flag_is_zero(struct bpf_verifier_env *env)
12568 {
12569 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
12570 	int err;
12571 
12572 	if (!bpf_register_is_null(reg))
12573 		return 0;
12574 
12575 	err = mark_chain_precision(env, BPF_REG_4);
12576 	if (err)
12577 		return err;
12578 	return 1;
12579 }
12580 
12581 static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
12582 {
12583 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
12584 	int flag_is_zero;
12585 
12586 	if (!state->initialized) {
12587 		flag_is_zero = loop_flag_is_zero(env);
12588 		if (flag_is_zero < 0)
12589 			return flag_is_zero;
12590 		state->initialized = 1;
12591 		state->fit_for_inline = flag_is_zero;
12592 		state->callback_subprogno = subprogno;
12593 		return 0;
12594 	}
12595 
12596 	if (!state->fit_for_inline)
12597 		return 0;
12598 
12599 	flag_is_zero = loop_flag_is_zero(env);
12600 	if (flag_is_zero < 0)
12601 		return flag_is_zero;
12602 	state->fit_for_inline = (flag_is_zero &&
12603 				 state->callback_subprogno == subprogno);
12604 	return 0;
12605 }
12606 
12607 /* Returns whether or not the given map can potentially elide
12608  * lookup return value nullness check. This is possible if the key
12609  * is statically known.
12610  */
12611 static bool can_elide_value_nullness(const struct bpf_map *map)
12612 {
12613 	if (map->map_flags & BPF_F_INNER_MAP)
12614 		return false;
12615 
12616 	switch (map->map_type) {
12617 	case BPF_MAP_TYPE_ARRAY:
12618 	case BPF_MAP_TYPE_PERCPU_ARRAY:
12619 		return true;
12620 	default:
12621 		return false;
12622 	}
12623 }
12624 
12625 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
12626 			 const struct bpf_func_proto **ptr)
12627 {
12628 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
12629 		return -ERANGE;
12630 
12631 	if (!env->ops->get_func_proto)
12632 		return -EINVAL;
12633 
12634 	*ptr = env->ops->get_func_proto(func_id, env->prog);
12635 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
12636 }
12637 
12638 /* Is any frame on the current path a callback that runs under RCU? */
12639 static bool in_rcu_callback(struct bpf_verifier_env *env)
12640 {
12641 	struct bpf_verifier_state *state = env->cur_state;
12642 	int i;
12643 
12644 	for (i = 0; i <= state->curframe; i++)
12645 		if (state->frame[i]->in_rcu_callback_fn)
12646 			return true;
12647 	return false;
12648 }
12649 
12650 /* Check if we're in a sleepable context. */
12651 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
12652 {
12653 	return !in_rcu_cs(env) && !in_rcu_callback(env);
12654 }
12655 
12656 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
12657 {
12658 	if (in_sleepable(env)) {
12659 		if (env->cur_state->active_rcu_locks)
12660 			return "rcu_read_lock region";
12661 		if (env->cur_state->active_preempt_locks)
12662 			return "non-preemptible region";
12663 		if (env->cur_state->active_irq_id)
12664 			return "IRQ-disabled region";
12665 		if (env->cur_state->active_locks)
12666 			return "lock region";
12667 		return "callback running under rcu_read_lock";
12668 	}
12669 	return "non-sleepable prog";
12670 }
12671 
12672 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
12673 		       bool convert_rcu, bool release_dynptr)
12674 {
12675 	int err = -EINVAL;
12676 
12677 	if (bpf_register_is_null(reg))
12678 		return 0;
12679 
12680 	if (release_dynptr)
12681 		err = unmark_stack_slots_dynptr(env, reg);
12682 	else if (convert_rcu)
12683 		err = ref_convert_alloc_rcu_protected(env, reg->id);
12684 	else if (reg_is_referenced(env, reg))
12685 		err = release_reference(env, reg->id);
12686 
12687 	return err;
12688 }
12689 
12690 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12691 			     int *insn_idx_p)
12692 {
12693 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12694 	bool returns_cpu_specific_alloc_ptr = false;
12695 	const struct bpf_func_proto *fn = NULL;
12696 	enum bpf_return_type ret_type;
12697 	enum bpf_type_flag ret_flag;
12698 	struct bpf_reg_state *regs;
12699 	struct bpf_call_arg_meta meta;
12700 	const char *operation;
12701 	int insn_idx = *insn_idx_p;
12702 	bool changes_data;
12703 	int i, err, func_id;
12704 
12705 	/* find function prototype */
12706 	func_id = insn->imm;
12707 	err = bpf_get_helper_proto(env, insn->imm, &fn);
12708 	if (err == -ERANGE) {
12709 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
12710 		return -EINVAL;
12711 	}
12712 
12713 	if (err) {
12714 		verbose(env, "program of this type cannot use helper %s#%d\n",
12715 			func_id_name(func_id), func_id);
12716 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12717 		bpf_diag_policy(
12718 			env, insn_idx, operation, "this program type does not allow the helper",
12719 			"Use a helper allowed for this program type, or move the logic to a compatible program type.");
12720 		return err;
12721 	}
12722 
12723 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
12724 	if (!env->prog->gpl_compatible && fn->gpl_only) {
12725 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
12726 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12727 		bpf_diag_policy(
12728 			env, insn_idx, operation,
12729 			"this helper is restricted to GPL-compatible programs",
12730 			"Use a GPL-compatible license, or replace the helper with one that is available to non-GPL programs.");
12731 		return -EINVAL;
12732 	}
12733 
12734 	if (fn->allowed && !fn->allowed(env->prog)) {
12735 		verbose(env, "helper call is not allowed in probe\n");
12736 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12737 		bpf_diag_policy(
12738 			env, insn_idx, operation,
12739 			"the helper-specific policy callback rejected this program",
12740 			"Use the helper only from an allowed attach point or program configuration.");
12741 		return -EINVAL;
12742 	}
12743 
12744 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
12745 	changes_data = bpf_helper_changes_pkt_data(func_id);
12746 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
12747 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
12748 		return -EFAULT;
12749 	}
12750 
12751 	memset(&meta, 0, sizeof(meta));
12752 
12753 	err = check_func_proto(env, fn, &meta);
12754 	if (err) {
12755 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
12756 		return err;
12757 	}
12758 
12759 	if (fn->might_sleep && !in_sleepable_context(env)) {
12760 		const char *suggestion;
12761 
12762 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
12763 			non_sleepable_context_description(env));
12764 		if (in_sleepable(env))
12765 			suggestion = "Move the helper call outside the critical section, or use a non-sleepable helper.";
12766 		else
12767 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable helper.";
12768 		operation = bpf_diag_fmt(env, "sleepable helper %s#%d",
12769 					 func_id_name(func_id), func_id);
12770 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
12771 		return -EINVAL;
12772 	}
12773 
12774 	/* Track non-sleepable context for helpers. */
12775 	if (!in_sleepable_context(env))
12776 		env->insn_aux_data[insn_idx].non_sleepable = true;
12777 
12778 	meta.func_id = func_id;
12779 	meta.func_name = func_id_name(func_id);
12780 	meta.fn = fn;
12781 	err = check_func_args(env, &meta, insn_idx);
12782 	if (err)
12783 		return err;
12784 
12785 	err = record_func_map(env, &meta, func_id, insn_idx);
12786 	if (err)
12787 		return err;
12788 
12789 	err = record_func_key(env, &meta, func_id, insn_idx);
12790 	if (err)
12791 		return err;
12792 
12793 	regs = cur_regs(env);
12794 
12795 	err = mark_raw_stack(env, &meta, insn_idx);
12796 	if (err)
12797 		return err;
12798 
12799 	if (meta.release_regno) {
12800 		struct bpf_reg_state *reg = &regs[meta.release_regno];
12801 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
12802 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
12803 
12804 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
12805 		if (err)
12806 			return err;
12807 	}
12808 
12809 	switch (func_id) {
12810 	case BPF_FUNC_tail_call:
12811 		err = check_resource_leak(env, false, true, "tail_call");
12812 		if (err)
12813 			return err;
12814 		break;
12815 	case BPF_FUNC_get_local_storage:
12816 		/* check that flags argument in get_local_storage(map, flags) is 0,
12817 		 * this is required because get_local_storage() can't return an error.
12818 		 */
12819 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
12820 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
12821 			return -EINVAL;
12822 		}
12823 		err = mark_chain_precision(env, BPF_REG_2);
12824 		if (err)
12825 			return err;
12826 		break;
12827 	case BPF_FUNC_for_each_map_elem:
12828 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12829 					 set_map_elem_callback_state);
12830 		break;
12831 	case BPF_FUNC_timer_set_callback:
12832 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12833 					 set_timer_callback_state);
12834 		break;
12835 	case BPF_FUNC_find_vma:
12836 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12837 					 set_find_vma_callback_state);
12838 		break;
12839 	case BPF_FUNC_snprintf:
12840 		err = check_bpf_snprintf_call(env, regs);
12841 		break;
12842 	case BPF_FUNC_loop:
12843 		err = update_loop_inline_state(env, meta.subprogno);
12844 		if (err)
12845 			return err;
12846 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
12847 		 * is finished, thus mark it precise.
12848 		 */
12849 		err = mark_chain_precision(env, BPF_REG_1);
12850 		if (err)
12851 			return err;
12852 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
12853 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12854 						 set_loop_callback_state);
12855 		} else {
12856 			cur_func(env)->callback_depth = 0;
12857 			if (env->log.level & BPF_LOG_LEVEL2)
12858 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
12859 					env->cur_state->curframe);
12860 		}
12861 		break;
12862 	case BPF_FUNC_dynptr_from_mem:
12863 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
12864 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
12865 				reg_type_str(env, regs[BPF_REG_1].type));
12866 			return -EACCES;
12867 		}
12868 		break;
12869 	case BPF_FUNC_set_retval:
12870 	{
12871 		struct bpf_retval_range range = {
12872 			.minval = -MAX_ERRNO,
12873 			.maxval = 0,
12874 			.return_32bit = true
12875 		};
12876 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
12877 
12878 		if (r1->type != SCALAR_VALUE) {
12879 			verbose(env, "R1 is not a scalar\n");
12880 			return -EINVAL;
12881 		}
12882 
12883 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
12884 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
12885 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
12886 			break;
12887 
12888 		if (prog_type == BPF_PROG_TYPE_LSM &&
12889 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
12890 			if (!env->prog->aux->attach_func_proto->type) {
12891 				/* Make sure programs that attach to void
12892 				 * hooks don't try to modify return value.
12893 				 */
12894 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12895 				return -EINVAL;
12896 			}
12897 			bpf_lsm_get_retval_range(env->prog, &range);
12898 		}
12899 
12900 		err = mark_chain_precision(env, BPF_REG_1);
12901 		if (err)
12902 			return err;
12903 
12904 		if (!retval_range_within(range, r1)) {
12905 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
12906 			return -EINVAL;
12907 		}
12908 
12909 		break;
12910 	}
12911 	case BPF_FUNC_dynptr_write:
12912 	{
12913 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
12914 
12915 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
12916 			return -EFAULT;
12917 
12918 		if (dynptr_write_changes_pkt_data(dynptr_type))
12919 			/* this will trigger clear_all_pkt_pointers(), which will
12920 			 * invalidate all dynptr slices associated with the skb
12921 			 */
12922 			changes_data = true;
12923 
12924 		break;
12925 	}
12926 	case BPF_FUNC_per_cpu_ptr:
12927 	case BPF_FUNC_this_cpu_ptr:
12928 	{
12929 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
12930 		const struct btf_type *type;
12931 
12932 		if (reg->type & MEM_RCU) {
12933 			type = btf_type_by_id(reg->btf, reg->btf_id);
12934 			if (!type || !btf_type_is_struct(type)) {
12935 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
12936 				return -EFAULT;
12937 			}
12938 			returns_cpu_specific_alloc_ptr = true;
12939 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
12940 		}
12941 		break;
12942 	}
12943 	case BPF_FUNC_user_ringbuf_drain:
12944 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12945 					 set_user_ringbuf_callback_state);
12946 		break;
12947 	}
12948 
12949 	if (err)
12950 		return err;
12951 
12952 	/* reset caller saved regs */
12953 	bpf_diag_record_caller_saved(env, regs);
12954 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
12955 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12956 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
12957 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12958 	}
12959 	invalidate_outgoing_stack_args(env, cur_func(env));
12960 
12961 	/* update return register (already marked as written above) */
12962 	ret_type = fn->ret_type;
12963 	ret_flag = type_flag(ret_type);
12964 
12965 	switch (base_type(ret_type)) {
12966 	case RET_INTEGER:
12967 		/* sets type to SCALAR_VALUE */
12968 		mark_reg_unknown(env, regs, BPF_REG_0);
12969 		break;
12970 	case RET_VOID:
12971 		regs[BPF_REG_0].type = NOT_INIT;
12972 		break;
12973 	case RET_PTR_TO_MAP_VALUE:
12974 		/* There is no offset yet applied, variable or fixed */
12975 		mark_reg_known_zero(env, regs, BPF_REG_0);
12976 		/* remember map_ptr, so that check_map_access()
12977 		 * can check 'value_size' boundary of memory access
12978 		 * to map element returned from bpf_map_lookup_elem()
12979 		 */
12980 		if (meta.map.ptr == NULL) {
12981 			verifier_bug(env, "unexpected null map_ptr");
12982 			return -EFAULT;
12983 		}
12984 
12985 		if (func_id == BPF_FUNC_map_lookup_elem &&
12986 		    can_elide_value_nullness(meta.map.ptr) &&
12987 		    meta.const_map_key >= 0 &&
12988 		    meta.const_map_key < meta.map.ptr->max_entries)
12989 			ret_flag &= ~PTR_MAYBE_NULL;
12990 
12991 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
12992 		regs[BPF_REG_0].map_uid = meta.map.uid;
12993 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
12994 		if (type_may_be_null(ret_flag) ||
12995 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
12996 			regs[BPF_REG_0].id = ++env->id_gen;
12997 		}
12998 		/* requires regs[BPF_REG_0].id to be set because of the map-in-map case */
12999 		refine_map_lookup_value(&regs[BPF_REG_0]);
13000 		break;
13001 	case RET_PTR_TO_SOCKET:
13002 		mark_reg_known_zero(env, regs, BPF_REG_0);
13003 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
13004 		break;
13005 	case RET_PTR_TO_SOCK_COMMON:
13006 		mark_reg_known_zero(env, regs, BPF_REG_0);
13007 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
13008 		break;
13009 	case RET_PTR_TO_TCP_SOCK:
13010 		mark_reg_known_zero(env, regs, BPF_REG_0);
13011 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
13012 		break;
13013 	case RET_PTR_TO_MEM:
13014 		mark_reg_known_zero(env, regs, BPF_REG_0);
13015 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
13016 		regs[BPF_REG_0].mem_size = meta.ret_mem.size;
13017 		break;
13018 	case RET_PTR_TO_MEM_OR_BTF_ID:
13019 	{
13020 		const struct btf_type *t;
13021 
13022 		mark_reg_known_zero(env, regs, BPF_REG_0);
13023 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
13024 		if (!btf_type_is_struct(t)) {
13025 			u32 tsize;
13026 			const struct btf_type *ret;
13027 			const char *tname;
13028 
13029 			/* resolve the type size of ksym. */
13030 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
13031 			if (IS_ERR(ret)) {
13032 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
13033 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
13034 					tname, PTR_ERR(ret));
13035 				return -EINVAL;
13036 			}
13037 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
13038 			regs[BPF_REG_0].mem_size = tsize;
13039 		} else {
13040 			if (returns_cpu_specific_alloc_ptr) {
13041 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
13042 			} else {
13043 				/* MEM_RDONLY may be carried from ret_flag, but it
13044 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
13045 				 * it will confuse the check of PTR_TO_BTF_ID in
13046 				 * check_mem_access().
13047 				 */
13048 				ret_flag &= ~MEM_RDONLY;
13049 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
13050 			}
13051 
13052 			regs[BPF_REG_0].btf = meta.ret_btf;
13053 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
13054 		}
13055 		break;
13056 	}
13057 	case RET_PTR_TO_BTF_ID:
13058 	{
13059 		struct btf *ret_btf;
13060 		int ret_btf_id;
13061 
13062 		mark_reg_known_zero(env, regs, BPF_REG_0);
13063 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
13064 		if (func_id == BPF_FUNC_kptr_xchg) {
13065 			ret_btf = meta.kptr_field->kptr.btf;
13066 			ret_btf_id = meta.kptr_field->kptr.btf_id;
13067 			if (!btf_is_kernel(ret_btf)) {
13068 				regs[BPF_REG_0].type |= MEM_ALLOC;
13069 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
13070 					regs[BPF_REG_0].type |= MEM_PERCPU;
13071 			}
13072 		} else {
13073 			if (fn->ret_btf_id == BPF_PTR_POISON) {
13074 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
13075 					     func_id_name(func_id));
13076 				return -EFAULT;
13077 			}
13078 			ret_btf = btf_vmlinux;
13079 			ret_btf_id = *fn->ret_btf_id;
13080 		}
13081 		if (ret_btf_id == 0) {
13082 			verbose(env, "invalid return type %u of func %s#%d\n",
13083 				base_type(ret_type), func_id_name(func_id),
13084 				func_id);
13085 			return -EINVAL;
13086 		}
13087 		regs[BPF_REG_0].btf = ret_btf;
13088 		regs[BPF_REG_0].btf_id = ret_btf_id;
13089 		break;
13090 	}
13091 	default:
13092 		verbose(env, "unknown return type %u of func %s#%d\n",
13093 			base_type(ret_type), func_id_name(func_id), func_id);
13094 		return -EINVAL;
13095 	}
13096 
13097 	if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id)
13098 		regs[BPF_REG_0].id = ++env->id_gen;
13099 
13100 	if (is_ptr_cast_function(func_id) &&
13101 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
13102 		struct bpf_verifier_state *branch;
13103 		struct bpf_reg_state *r0;
13104 
13105 		err = validate_ref_obj(env, &meta.ref_obj);
13106 		if (err)
13107 			return err;
13108 
13109 		bpf_diag_mod_end(env);
13110 
13111 		/*
13112 		 * In order for a release of any of the original or cast pointers
13113 		 * to invalidate all other pointers, reuse the same reference id for
13114 		 * the cast result.
13115 		 * This reference id can't be used for nullness propagation,
13116 		 * as cast might return NULL for a non-NULL input.
13117 		 * Hence, explore the NULL case as a separate branch.
13118 		 */
13119 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13120 		if (IS_ERR(branch))
13121 			return PTR_ERR(branch);
13122 
13123 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
13124 		__mark_reg_known_zero(r0);
13125 		r0->type = SCALAR_VALUE;
13126 
13127 		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
13128 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
13129 		regs[BPF_REG_0].id = meta.ref_obj.id;
13130 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
13131 		int id = acquire_reference(env, insn_idx, 0);
13132 
13133 		if (id < 0)
13134 			return id;
13135 
13136 		regs[BPF_REG_0].id = id;
13137 	}
13138 
13139 	if (func_id == BPF_FUNC_dynptr_data)
13140 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
13141 
13142 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
13143 	if (err)
13144 		return err;
13145 
13146 	bpf_diag_mod_end(env);
13147 
13148 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
13149 	if (err)
13150 		return err;
13151 
13152 	if ((func_id == BPF_FUNC_get_stack ||
13153 	     func_id == BPF_FUNC_get_task_stack) &&
13154 	    !env->prog->has_callchain_buf) {
13155 		const char *err_str;
13156 
13157 #ifdef CONFIG_PERF_EVENTS
13158 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
13159 		err_str = "cannot get callchain buffer for func %s#%d\n";
13160 #else
13161 		err = -ENOTSUPP;
13162 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
13163 #endif
13164 		if (err) {
13165 			verbose(env, err_str, func_id_name(func_id), func_id);
13166 			return err;
13167 		}
13168 
13169 		env->prog->has_callchain_buf = true;
13170 	}
13171 
13172 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
13173 		env->prog->call_get_stack = true;
13174 
13175 	if (func_id == BPF_FUNC_get_func_ip) {
13176 		if (check_get_func_ip(env))
13177 			return -ENOTSUPP;
13178 		env->prog->call_get_func_ip = true;
13179 	}
13180 
13181 	if (func_id == BPF_FUNC_tail_call) {
13182 		if (env->cur_state->curframe) {
13183 			struct bpf_verifier_state *branch;
13184 
13185 			/*
13186 			 * A taken tail call is modeled as a return from the current
13187 			 * frame. A callback frame cannot be left that way because
13188 			 * prepare_func_exit() would apply its return contract to the
13189 			 * unknown R0 synthesized below. Stack-depth validation rejects
13190 			 * this construct anyway.
13191 			 */
13192 			if (cur_func(env)->in_callback_fn) {
13193 				verbose(env, "cannot tail call within callback\n");
13194 				return -EINVAL;
13195 			}
13196 			mark_reg_scratched(env, BPF_REG_0);
13197 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13198 			if (IS_ERR(branch))
13199 				return PTR_ERR(branch);
13200 			clear_all_pkt_pointers(env);
13201 			mark_reg_unknown(env, regs, BPF_REG_0);
13202 			err = prepare_func_exit(env, &env->insn_idx);
13203 			if (err)
13204 				return err;
13205 			env->insn_idx--;
13206 		} else {
13207 			changes_data = false;
13208 		}
13209 	}
13210 
13211 	if (changes_data)
13212 		clear_all_pkt_pointers(env);
13213 	return 0;
13214 }
13215 
13216 /*
13217  * Mark the register(s) holding a @size byte kfunc return value as unknown
13218  * scalars and return how many registers that took. Both halves of a register
13219  * pair are treated the same way.
13220  *
13221  * R0 is written in the diagnostic modification scope the caller opened before
13222  * the caller-saved scrub, since R0 gets no scrub record of its own and that
13223  * scope is what carries its pre-call value into the history. A scope tracks a
13224  * single register and does not nest, so close it before recording the rest of
13225  * the return value. A value that fits in R0 leaves the caller's scope open for
13226  * the caller to close, so a later write to R0 still lands in it.
13227  */
13228 static u32 mark_kfunc_ret_regs(struct bpf_verifier_env *env,
13229 			       struct bpf_reg_state *regs, u32 size)
13230 {
13231 	u32 i, nregs = ret_regs_cnt(size);
13232 
13233 	mark_reg_unknown(env, regs, ret_regs[0]);
13234 	if (nregs == 1)
13235 		return nregs;
13236 
13237 	bpf_diag_mod_end(env);
13238 	for (i = 1; i < nregs; i++) {
13239 		bpf_diag_mod_begin(env, &regs[ret_regs[i]], NULL, BPF_DIAG_MOD_WRITE);
13240 		mark_reg_unknown(env, regs, ret_regs[i]);
13241 		bpf_diag_mod_end(env);
13242 	}
13243 
13244 	return nregs;
13245 }
13246 
13247 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta)
13248 {
13249 	return meta->kfunc_flags & KF_ACQUIRE;
13250 }
13251 
13252 static bool is_kfunc_release(struct bpf_call_arg_meta *meta)
13253 {
13254 	return meta->kfunc_flags & KF_RELEASE;
13255 }
13256 
13257 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta)
13258 {
13259 	return meta->kfunc_flags & KF_DESTRUCTIVE;
13260 }
13261 
13262 static bool is_kfunc_perfmon(struct bpf_call_arg_meta *meta)
13263 {
13264 	return meta->kfunc_flags & KF_PERFMON;
13265 }
13266 
13267 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta)
13268 {
13269 	return meta->kfunc_flags & KF_RCU;
13270 }
13271 
13272 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta)
13273 {
13274 	return meta->kfunc_flags & KF_RCU_PROTECTED;
13275 }
13276 
13277 static bool is_kfunc_arg_mem_size(const struct btf *btf,
13278 				  const struct btf_param *arg)
13279 {
13280 	const struct btf_type *t;
13281 
13282 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13283 	if (!btf_type_is_scalar(t))
13284 		return false;
13285 
13286 	return btf_param_match_suffix(btf, arg, "__sz");
13287 }
13288 
13289 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
13290 					const struct btf_param *arg)
13291 {
13292 	const struct btf_type *t;
13293 
13294 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13295 	if (!btf_type_is_scalar(t))
13296 		return false;
13297 
13298 	return btf_param_match_suffix(btf, arg, "__szk");
13299 }
13300 
13301 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
13302 {
13303 	return btf_param_match_suffix(btf, arg, "__k");
13304 }
13305 
13306 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
13307 {
13308 	return btf_param_match_suffix(btf, arg, "__ign");
13309 }
13310 
13311 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
13312 {
13313 	return btf_param_match_suffix(btf, arg, "__map");
13314 }
13315 
13316 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg)
13317 {
13318 	return btf_param_match_suffix(btf, arg, "__const_map");
13319 }
13320 
13321 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
13322 {
13323 	return btf_param_match_suffix(btf, arg, "__alloc");
13324 }
13325 
13326 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
13327 {
13328 	return btf_param_match_suffix(btf, arg, "__uninit");
13329 }
13330 
13331 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
13332 {
13333 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
13334 }
13335 
13336 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
13337 {
13338 	return btf_param_match_suffix(btf, arg, "__nullable") ||
13339 	       btf_param_match_suffix(btf, arg, "__arena");
13340 }
13341 
13342 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
13343 {
13344 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
13345 }
13346 
13347 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
13348 {
13349 	return btf_param_match_suffix(btf, arg, "__str");
13350 }
13351 
13352 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
13353 {
13354 	return btf_param_match_suffix(btf, arg, "__irq_flag");
13355 }
13356 
13357 static bool is_kfunc_arg_ctx_out(const struct btf *btf, const struct btf_param *arg)
13358 {
13359 	return btf_param_match_suffix(btf, arg, "__ctx_out");
13360 }
13361 
13362 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg)
13363 {
13364 	return btf_param_match_suffix(btf, arg, "__arena__nullable") ||
13365 	       btf_param_match_suffix(btf, arg, "__arena");
13366 }
13367 
13368 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
13369 					  const struct btf_param *arg,
13370 					  const char *name)
13371 {
13372 	int len, target_len = strlen(name);
13373 	const char *param_name;
13374 
13375 	param_name = btf_name_by_offset(btf, arg->name_off);
13376 	if (str_is_empty(param_name))
13377 		return false;
13378 	len = strlen(param_name);
13379 	if (len != target_len)
13380 		return false;
13381 	if (strcmp(param_name, name))
13382 		return false;
13383 
13384 	return true;
13385 }
13386 
13387 enum {
13388 	KF_ARG_DYNPTR_ID,
13389 	KF_ARG_LIST_HEAD_ID,
13390 	KF_ARG_LIST_NODE_ID,
13391 	KF_ARG_RB_ROOT_ID,
13392 	KF_ARG_RB_NODE_ID,
13393 	KF_ARG_WORKQUEUE_ID,
13394 	KF_ARG_RES_SPIN_LOCK_ID,
13395 	KF_ARG_TASK_WORK_ID,
13396 	KF_ARG_PROG_AUX_ID,
13397 	KF_ARG_TIMER_ID,
13398 	KF_ARG_RCU_HEAD_ID
13399 };
13400 
13401 BTF_ID_LIST(kf_arg_btf_ids)
13402 BTF_ID(struct, bpf_dynptr)
13403 BTF_ID(struct, bpf_list_head)
13404 BTF_ID(struct, bpf_list_node)
13405 BTF_ID(struct, bpf_rb_root)
13406 BTF_ID(struct, bpf_rb_node)
13407 BTF_ID(struct, bpf_wq)
13408 BTF_ID(struct, bpf_res_spin_lock)
13409 BTF_ID(struct, bpf_task_work)
13410 BTF_ID(struct, bpf_prog_aux)
13411 BTF_ID(struct, bpf_timer)
13412 BTF_ID(struct, bpf_rcu_head)
13413 
13414 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
13415 				    const struct btf_param *arg, int type)
13416 {
13417 	const struct btf_type *t;
13418 	u32 res_id;
13419 
13420 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13421 	if (!t)
13422 		return false;
13423 	if (!btf_type_is_ptr(t))
13424 		return false;
13425 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
13426 	if (!t)
13427 		return false;
13428 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
13429 }
13430 
13431 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
13432 {
13433 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
13434 }
13435 
13436 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
13437 {
13438 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
13439 }
13440 
13441 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
13442 {
13443 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
13444 }
13445 
13446 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
13447 {
13448 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
13449 }
13450 
13451 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
13452 {
13453 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
13454 }
13455 
13456 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
13457 {
13458 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
13459 }
13460 
13461 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
13462 {
13463 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
13464 }
13465 
13466 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
13467 {
13468 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
13469 }
13470 
13471 static bool is_kfunc_arg_rcu_head(const struct btf *btf, const struct btf_param *arg)
13472 {
13473 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RCU_HEAD_ID);
13474 }
13475 
13476 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
13477 {
13478 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
13479 }
13480 
13481 static bool is_rbtree_node_type(const struct btf_type *t)
13482 {
13483 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
13484 }
13485 
13486 static bool is_list_node_type(const struct btf_type *t)
13487 {
13488 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
13489 }
13490 
13491 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
13492 				  const struct btf_param *arg)
13493 {
13494 	const struct btf_type *t;
13495 
13496 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
13497 	if (!t)
13498 		return false;
13499 
13500 	return true;
13501 }
13502 
13503 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
13504 {
13505 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
13506 }
13507 
13508 /*
13509  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
13510  *   - the _impl prototype with full arg list (meta->func_proto)
13511  *   - the BPF API prototype w/o implicit args (func->type in BTF)
13512  * To determine whether an argument is implicit, we compare its position
13513  * against the number of arguments in the prototype w/o implicit args.
13514  */
13515 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx)
13516 {
13517 	const struct btf_type *func, *func_proto;
13518 	u32 argn;
13519 
13520 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
13521 		return false;
13522 
13523 	func = btf_type_by_id(meta->btf, meta->func_id);
13524 	func_proto = btf_type_by_id(meta->btf, func->type);
13525 	argn = btf_type_vlen(func_proto);
13526 
13527 	return argn <= arg_idx;
13528 }
13529 
13530 #define BTF_MEMBER_MAX_DEPTH	4
13531 #define BTF_MEMBER_PATH_LEN	64
13532 
13533 struct btf_member_path {
13534 	const struct btf_member *member[BTF_MEMBER_MAX_DEPTH];
13535 	bool in_array[BTF_MEMBER_MAX_DEPTH];
13536 	const struct btf_type *bad_type;
13537 	int depth;
13538 	bool too_deep;
13539 };
13540 
13541 static bool btf_member_kind_allowed(const struct btf *btf, const struct btf_type *t,
13542 				    u32 member_kinds)
13543 {
13544 	if ((member_kinds & BTF_MEMBER_SCALAR) && btf_type_is_scalar(t))
13545 		return true;
13546 	if ((member_kinds & BTF_MEMBER_ARENA_PTR) && btf_type_is_arena_ptr(btf, t))
13547 		return true;
13548 	return false;
13549 }
13550 
13551 /*
13552  * Returns true if every member of struct @t is of a kind listed in
13553  * @member_kinds, 4 levels of nesting allowed. An array member counts as its
13554  * element type.
13555  */
13556 static bool btf_struct_member_walk(struct bpf_verifier_env *env, const struct btf *btf,
13557 				   const struct btf_type *t, u32 member_kinds, int rec,
13558 				   struct btf_member_path *path)
13559 {
13560 	const struct btf_type *member_type;
13561 	const struct btf_member *member;
13562 	bool in_array;
13563 	u32 i;
13564 
13565 	if (!btf_type_is_struct(t))
13566 		return false;
13567 
13568 	for_each_member(i, t, member) {
13569 		const struct btf_array *array;
13570 
13571 		in_array = false;
13572 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
13573 		/*
13574 		 * Every element of an array is laid out in the value being
13575 		 * returned, so an array counts as its element type however many
13576 		 * dimensions deep that is.
13577 		 */
13578 		while (btf_type_is_array(member_type)) {
13579 			array = btf_array(member_type);
13580 			if (!array->nelems) {
13581 				member_type = NULL;
13582 				goto bad_member;
13583 			}
13584 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
13585 			in_array = true;
13586 		}
13587 		if (btf_type_is_struct(member_type)) {
13588 			if (rec >= BTF_MEMBER_MAX_DEPTH - 1) {
13589 				verbose(env, "max struct nesting depth exceeded\n");
13590 				if (path)
13591 					path->too_deep = true;
13592 				return false;
13593 			}
13594 			if (!btf_struct_member_walk(env, btf, member_type, member_kinds,
13595 						    rec + 1, path))
13596 				goto bad_path;
13597 			continue;
13598 		}
13599 		if (!btf_member_kind_allowed(btf, member_type, member_kinds))
13600 			goto bad_member;
13601 	}
13602 	return true;
13603 
13604 bad_member:
13605 	if (path) {
13606 		path->depth = rec + 1;
13607 		path->bad_type = member_type;
13608 	}
13609 bad_path:
13610 	if (path && path->depth) {
13611 		path->member[rec] = member;
13612 		path->in_array[rec] = in_array;
13613 	}
13614 	return false;
13615 }
13616 
13617 bool btf_struct_is_composed_of(struct bpf_verifier_env *env,
13618 			       const struct btf *btf,
13619 			       const struct btf_type *t, u32 member_kinds)
13620 {
13621 	return btf_struct_member_walk(env, btf, t, member_kinds, 0, NULL);
13622 }
13623 
13624 static bool btf_type_is_scalar_struct(struct bpf_verifier_env *env,
13625 				      const struct btf *btf,
13626 				      const struct btf_type *t)
13627 {
13628 	return btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR);
13629 }
13630 
13631 static int resolve_func_arg_type(struct bpf_verifier_env *env,
13632 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
13633 				 struct bpf_call_arg_meta *meta,
13634 				 enum bpf_arg_type *arg_type, u32 *arg_size)
13635 {
13636 	const struct btf_param *args;
13637 	const struct btf_type *ref_t, *resolve_ret;
13638 	const struct btf *btf;
13639 	const char *ref_tname;
13640 	u32 ref_id;
13641 
13642 	if (base_type(*arg_type) == ARG_PTR_TO_MAP_VALUE)
13643 		return resolve_map_arg_type(env, meta, arg_type);
13644 
13645 	if (base_type(*arg_type) != ARG_PTR_TO_BTF_ID)
13646 		return 0;
13647 
13648 	/*
13649 	 * A kfunc that releases an object, or that takes a reference to one,
13650 	 * needs the object itself: memory of the program cannot stand in for it.
13651 	 */
13652 	if (!is_kfunc(meta) || arg_type_is_release(*arg_type) ||
13653 	    is_kfunc_acquire(meta) ||
13654 	    base_type(reg->type) == PTR_TO_BTF_ID ||
13655 	    reg2btf_ids[base_type(reg->type)])
13656 		return 0;
13657 
13658 	args = btf_params(meta->func_proto);
13659 	ref_id = *meta->fn->arg_btf_id[arg];
13660 	btf = is_kfunc_arg_map(meta->btf, &args[arg]) ? btf_vmlinux : meta->btf;
13661 	ref_t = btf_type_skip_modifiers(btf, ref_id, &ref_id);
13662 	ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13663 
13664 	/*
13665 	 * A kfunc that takes a projection type (ie. xdp_md) casts it to the
13666 	 * underlying type. So memory of the program cannot stand in for it,
13667 	 * even if the projection type holds only scalars. A struct without
13668 	 * members (ie. iou_ctx) is a handle for an object of another type.
13669 	 */
13670 	if (btf_is_projection_type(ref_tname) ||
13671 	    !btf_type_is_scalar_struct(env, btf, ref_t) ||
13672 	    !btf_type_vlen(ref_t))
13673 		return 0;
13674 
13675 	resolve_ret = btf_resolve_size(btf, ref_t, arg_size);
13676 	if (IS_ERR(resolve_ret)) {
13677 		verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
13678 			reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname,
13679 			PTR_ERR(resolve_ret));
13680 		return -EINVAL;
13681 	}
13682 	*arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE |
13683 		    (*arg_type & (PTR_MAYBE_NULL | MEM_UNINIT));
13684 
13685 	return 0;
13686 }
13687 
13688 static void btf_member_path_str(const struct btf *btf, const struct btf_member_path *path,
13689 				char *buf, size_t buf_sz)
13690 {
13691 	size_t len = 0;
13692 	int i;
13693 
13694 	buf[0] = '\0';
13695 	for (i = 0; i < path->depth; i++) {
13696 		const char *name = btf_name_by_offset(btf, path->member[i]->name_off);
13697 
13698 		/* An anonymous struct or union has no name to spell. */
13699 		if (!name || !name[0])
13700 			continue;
13701 		len += scnprintf(buf + len, buf_sz - len, "%s%s", len ? "." : "", name);
13702 		if (path->in_array[i])
13703 			len += scnprintf(buf + len, buf_sz - len, "[]");
13704 	}
13705 }
13706 
13707 enum special_kfunc_type {
13708 	KF_bpf_obj_new_impl,
13709 	KF_bpf_obj_new,
13710 	KF_bpf_obj_drop_impl,
13711 	KF_bpf_obj_drop,
13712 	KF_bpf_refcount_acquire_impl,
13713 	KF_bpf_refcount_acquire,
13714 	KF_bpf_list_push_front_impl,
13715 	KF_bpf_list_push_front,
13716 	KF_bpf_list_push_back_impl,
13717 	KF_bpf_list_push_back,
13718 	KF_bpf_list_add,
13719 	KF_bpf_list_pop_front,
13720 	KF_bpf_list_pop_back,
13721 	KF_bpf_list_del,
13722 	KF_bpf_list_front,
13723 	KF_bpf_list_back,
13724 	KF_bpf_list_is_first,
13725 	KF_bpf_list_is_last,
13726 	KF_bpf_list_empty,
13727 	KF_bpf_cast_to_kern_ctx,
13728 	KF_bpf_rdonly_cast,
13729 	KF_bpf_rcu_read_lock,
13730 	KF_bpf_rcu_read_unlock,
13731 	KF_bpf_rbtree_remove,
13732 	KF_bpf_rbtree_add_impl,
13733 	KF_bpf_rbtree_add,
13734 	KF_bpf_rbtree_first,
13735 	KF_bpf_rbtree_root,
13736 	KF_bpf_rbtree_left,
13737 	KF_bpf_rbtree_right,
13738 	KF_bpf_dynptr_from_skb,
13739 	KF_bpf_dynptr_from_xdp,
13740 	KF_bpf_dynptr_from_skb_meta,
13741 	KF_bpf_xdp_pull_data,
13742 	KF_bpf_dynptr_slice,
13743 	KF_bpf_dynptr_slice_rdwr,
13744 	KF_bpf_dynptr_clone,
13745 	KF_bpf_percpu_obj_new_impl,
13746 	KF_bpf_percpu_obj_new,
13747 	KF_bpf_percpu_obj_drop_impl,
13748 	KF_bpf_percpu_obj_drop,
13749 	KF_bpf_throw,
13750 	KF_bpf_wq_set_callback,
13751 	KF_bpf_preempt_disable,
13752 	KF_bpf_preempt_enable,
13753 	KF_bpf_iter_css_task_new,
13754 	KF_bpf_session_cookie,
13755 	KF_bpf_get_kmem_cache,
13756 	KF_bpf_local_irq_save,
13757 	KF_bpf_local_irq_restore,
13758 	KF_bpf_iter_num_new,
13759 	KF_bpf_iter_num_next,
13760 	KF_bpf_iter_num_destroy,
13761 	KF_bpf_set_dentry_xattr,
13762 	KF_bpf_remove_dentry_xattr,
13763 	KF_bpf_res_spin_lock,
13764 	KF_bpf_res_spin_unlock,
13765 	KF_bpf_res_spin_lock_irqsave,
13766 	KF_bpf_res_spin_unlock_irqrestore,
13767 	KF_bpf_dynptr_from_file,
13768 	KF_bpf_dynptr_file_discard,
13769 	KF___bpf_trap,
13770 	KF_bpf_task_work_schedule_signal,
13771 	KF_bpf_task_work_schedule_resume,
13772 	KF_bpf_call_rcu,
13773 	KF_bpf_call_rcu_tasks_trace,
13774 	KF_bpf_arena_alloc_pages,
13775 	KF_bpf_arena_free_pages,
13776 	KF_bpf_session_is_return,
13777 };
13778 
13779 BTF_ID_LIST(special_kfunc_list)
13780 BTF_ID(func, bpf_obj_new_impl)
13781 BTF_ID(func, bpf_obj_new)
13782 BTF_ID(func, bpf_obj_drop_impl)
13783 BTF_ID(func, bpf_obj_drop)
13784 BTF_ID(func, bpf_refcount_acquire_impl)
13785 BTF_ID(func, bpf_refcount_acquire)
13786 BTF_ID(func, bpf_list_push_front_impl)
13787 BTF_ID(func, bpf_list_push_front)
13788 BTF_ID(func, bpf_list_push_back_impl)
13789 BTF_ID(func, bpf_list_push_back)
13790 BTF_ID(func, bpf_list_add)
13791 BTF_ID(func, bpf_list_pop_front)
13792 BTF_ID(func, bpf_list_pop_back)
13793 BTF_ID(func, bpf_list_del)
13794 BTF_ID(func, bpf_list_front)
13795 BTF_ID(func, bpf_list_back)
13796 BTF_ID(func, bpf_list_is_first)
13797 BTF_ID(func, bpf_list_is_last)
13798 BTF_ID(func, bpf_list_empty)
13799 BTF_ID(func, bpf_cast_to_kern_ctx)
13800 BTF_ID(func, bpf_rdonly_cast)
13801 BTF_ID(func, bpf_rcu_read_lock)
13802 BTF_ID(func, bpf_rcu_read_unlock)
13803 BTF_ID(func, bpf_rbtree_remove)
13804 BTF_ID(func, bpf_rbtree_add_impl)
13805 BTF_ID(func, bpf_rbtree_add)
13806 BTF_ID(func, bpf_rbtree_first)
13807 BTF_ID(func, bpf_rbtree_root)
13808 BTF_ID(func, bpf_rbtree_left)
13809 BTF_ID(func, bpf_rbtree_right)
13810 #ifdef CONFIG_NET
13811 BTF_ID(func, bpf_dynptr_from_skb)
13812 BTF_ID(func, bpf_dynptr_from_xdp)
13813 BTF_ID(func, bpf_dynptr_from_skb_meta)
13814 BTF_ID(func, bpf_xdp_pull_data)
13815 #else
13816 BTF_ID_UNUSED
13817 BTF_ID_UNUSED
13818 BTF_ID_UNUSED
13819 BTF_ID_UNUSED
13820 #endif
13821 BTF_ID(func, bpf_dynptr_slice)
13822 BTF_ID(func, bpf_dynptr_slice_rdwr)
13823 BTF_ID(func, bpf_dynptr_clone)
13824 BTF_ID(func, bpf_percpu_obj_new_impl)
13825 BTF_ID(func, bpf_percpu_obj_new)
13826 BTF_ID(func, bpf_percpu_obj_drop_impl)
13827 BTF_ID(func, bpf_percpu_obj_drop)
13828 BTF_ID(func, bpf_throw)
13829 BTF_ID(func, bpf_wq_set_callback)
13830 BTF_ID(func, bpf_preempt_disable)
13831 BTF_ID(func, bpf_preempt_enable)
13832 #ifdef CONFIG_CGROUPS
13833 BTF_ID(func, bpf_iter_css_task_new)
13834 #else
13835 BTF_ID_UNUSED
13836 #endif
13837 #ifdef CONFIG_BPF_EVENTS
13838 BTF_ID(func, bpf_session_cookie)
13839 #else
13840 BTF_ID_UNUSED
13841 #endif
13842 BTF_ID(func, bpf_get_kmem_cache)
13843 BTF_ID(func, bpf_local_irq_save)
13844 BTF_ID(func, bpf_local_irq_restore)
13845 BTF_ID(func, bpf_iter_num_new)
13846 BTF_ID(func, bpf_iter_num_next)
13847 BTF_ID(func, bpf_iter_num_destroy)
13848 #ifdef CONFIG_BPF_LSM
13849 BTF_ID(func, bpf_set_dentry_xattr)
13850 BTF_ID(func, bpf_remove_dentry_xattr)
13851 #else
13852 BTF_ID_UNUSED
13853 BTF_ID_UNUSED
13854 #endif
13855 BTF_ID(func, bpf_res_spin_lock)
13856 BTF_ID(func, bpf_res_spin_unlock)
13857 BTF_ID(func, bpf_res_spin_lock_irqsave)
13858 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
13859 BTF_ID(func, bpf_dynptr_from_file)
13860 BTF_ID(func, bpf_dynptr_file_discard)
13861 BTF_ID(func, __bpf_trap)
13862 BTF_ID(func, bpf_task_work_schedule_signal)
13863 BTF_ID(func, bpf_task_work_schedule_resume)
13864 BTF_ID(func, bpf_call_rcu)
13865 BTF_ID(func, bpf_call_rcu_tasks_trace)
13866 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
13867 BTF_ID(func, bpf_arena_alloc_pages)
13868 BTF_ID(func, bpf_arena_free_pages)
13869 #else
13870 BTF_ID_UNUSED
13871 BTF_ID_UNUSED
13872 #endif
13873 #ifdef CONFIG_BPF_EVENTS
13874 BTF_ID(func, bpf_session_is_return)
13875 #else
13876 BTF_ID_UNUSED
13877 #endif
13878 
13879 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta)
13880 {
13881 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]);
13882 }
13883 
13884 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta)
13885 {
13886 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_clone]);
13887 }
13888 
13889 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta)
13890 {
13891 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_iter_css_task_new]);
13892 }
13893 
13894 static bool is_bpf_obj_new_kfunc(u32 func_id)
13895 {
13896 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
13897 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
13898 }
13899 
13900 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
13901 {
13902 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
13903 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
13904 }
13905 
13906 static bool is_bpf_obj_drop_kfunc(u32 func_id)
13907 {
13908 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
13909 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
13910 }
13911 
13912 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
13913 {
13914 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
13915 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
13916 }
13917 
13918 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
13919 {
13920 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
13921 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
13922 }
13923 
13924 static bool is_bpf_list_push_kfunc(u32 func_id)
13925 {
13926 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
13927 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13928 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
13929 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13930 	       func_id == special_kfunc_list[KF_bpf_list_add];
13931 }
13932 
13933 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
13934 {
13935 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
13936 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
13937 }
13938 
13939 static bool is_call_rcu_kfunc(u32 func_id)
13940 {
13941 	return func_id == special_kfunc_list[KF_bpf_call_rcu] ||
13942 	       func_id == special_kfunc_list[KF_bpf_call_rcu_tasks_trace];
13943 }
13944 
13945 static bool is_task_work_add_kfunc(u32 func_id)
13946 {
13947 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
13948 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
13949 }
13950 
13951 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta)
13952 {
13953 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
13954 		return false;
13955 
13956 	return meta->kfunc_flags & KF_RET_NULL;
13957 }
13958 
13959 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta)
13960 {
13961 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_lock]);
13962 }
13963 
13964 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta)
13965 {
13966 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_unlock]);
13967 }
13968 
13969 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta)
13970 {
13971 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_disable]);
13972 }
13973 
13974 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta)
13975 {
13976 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_enable]);
13977 }
13978 
13979 /* These write to what their first argument, a dynptr, points to */
13980 BTF_SET_START(dynptr_write_kfuncs)
13981 BTF_ID(func, bpf_dynptr_copy)
13982 BTF_ID(func, bpf_dynptr_memset)
13983 #ifdef CONFIG_BPF_EVENTS
13984 BTF_ID(func, bpf_probe_read_user_dynptr)
13985 BTF_ID(func, bpf_probe_read_kernel_dynptr)
13986 BTF_ID(func, bpf_probe_read_user_str_dynptr)
13987 BTF_ID(func, bpf_probe_read_kernel_str_dynptr)
13988 BTF_ID(func, bpf_copy_from_user_dynptr)
13989 BTF_ID(func, bpf_copy_from_user_str_dynptr)
13990 BTF_ID(func, bpf_copy_from_user_task_dynptr)
13991 BTF_ID(func, bpf_copy_from_user_task_str_dynptr)
13992 #endif
13993 BTF_SET_END(dynptr_write_kfuncs)
13994 
13995 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)
13996 {
13997 	return meta->btf == btf_vmlinux &&
13998 	       btf_id_set_contains(&dynptr_write_kfuncs, meta->func_id);
13999 }
14000 
14001 /*
14002  * A write through the dynptr of an skb may reallocate its head. Before the
14003  * arguments are checked nobody knows what kind of dynptr it is.
14004  */
14005 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta)
14006 {
14007 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_xdp_pull_data]) ||
14008 	       is_kfunc_dynptr_write(meta);
14009 }
14010 
14011 static u32 kfunc_abi_slots(const struct btf_func_model *fm)
14012 {
14013 	const struct bpf_jit_arg_abi *abi = bpf_jit_arg_abi();
14014 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
14015 	u32 i, nslots, slots = 0;
14016 
14017 	for (i = 0; i < fm->nr_args; i++)
14018 		slots += btf_func_model_arg_slots(fm, i);
14019 
14020 	if (!abi)
14021 		return slots;
14022 
14023 	nslots = bpf_jit_place_args(abi, fm, pos_of_slot);
14024 	for (i = 0; i < nslots; i++)
14025 		if (pos_of_slot[i] + 1 > slots)
14026 			slots = pos_of_slot[i] + 1;
14027 
14028 	return slots;
14029 }
14030 
14031 static u32 __btf_func_arg_align(const struct btf *btf, const struct btf_type *t, int rec)
14032 {
14033 	const struct btf_member *member;
14034 	const struct btf_type *mt;
14035 	u32 align, i;
14036 
14037 	while (btf_type_is_array(t))
14038 		t = btf_type_skip_modifiers(btf, btf_array(t)->type, NULL);
14039 
14040 	if (btf_type_is_int(t))
14041 		return t->size > BPF_REG_SIZE ? t->size : BPF_REG_SIZE;
14042 	if (!btf_type_is_struct(t))
14043 		return BPF_REG_SIZE;
14044 	if (rec >= BTF_MEMBER_MAX_DEPTH)
14045 		return 0;
14046 
14047 	for_each_member(i, t, member) {
14048 		mt = btf_type_skip_modifiers(btf, member->type, NULL);
14049 		align = __btf_func_arg_align(btf, mt, rec + 1);
14050 		if (!align)
14051 			return 0;
14052 		if (align > BPF_REG_SIZE)
14053 			return 2 * BPF_REG_SIZE;
14054 	}
14055 	return BPF_REG_SIZE;
14056 }
14057 
14058 u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t)
14059 {
14060 	return __btf_func_arg_align(btf, t, 0);
14061 }
14062 
14063 static int
14064 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
14065 		   const struct btf_param *args, int arg, int nargs, u32 slot,
14066 		   struct bpf_func_proto *proto)
14067 {
14068 	const struct btf_type *t, *ref_t = NULL, *resolve_ret;
14069 	const u32 *ref_id_ptr = NULL;
14070 	argno_t argno = argno_from_arg(slot + 1);
14071 	const char *ref_tname = NULL;
14072 	u32 ref_id, type_size;
14073 	int arg_type;
14074 
14075 	proto->arg_btf_id[arg] = NULL;
14076 
14077 	if (is_kfunc_arg_prog_aux(meta->btf, &args[arg]))
14078 		return ARG_PTR_TO_PROG_AUX;
14079 
14080 	if (is_kfunc_arg_ignore(meta->btf, &args[arg]) || is_kfunc_arg_implicit(meta, arg))
14081 		return ARG_IGNORE;
14082 
14083 	t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
14084 
14085 	/* Scalar arguments are classified from their BTF suffix/name alone. */
14086 	if (btf_type_is_scalar(t)) {
14087 		if (is_kfunc_arg_constant(meta->btf, &args[arg]))
14088 			return ARG_CONST_SCALAR;
14089 		if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg]))
14090 			return ARG_CONST_MEM_SIZE;
14091 		if (is_kfunc_arg_mem_size(meta->btf, &args[arg]))
14092 			return ARG_MEM_SIZE;
14093 		if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") ||
14094 		    is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size"))
14095 			return ARG_CONST_ALLOC_SIZE_OR_ZERO;
14096 		return ARG_SCALAR;
14097 	}
14098 
14099 	if (btf_type_is_struct(t)) {
14100 		if (!t->size || t->size > 2 * BPF_REG_SIZE) {
14101 			verbose(env,
14102 				"%s type %s has size %u, only 1 to %d bytes "
14103 				"can be passed by value\n",
14104 				reg_arg_name(env, argno), btf_type_str(t), t->size,
14105 				2 * BPF_REG_SIZE);
14106 			return -EINVAL;
14107 		}
14108 		if (!btf_type_is_scalar_struct(env, meta->btf, t)) {
14109 			verbose(env, "%s type %s is not composed of scalars\n",
14110 				reg_arg_name(env, argno), btf_type_str(t));
14111 			return -EINVAL;
14112 		}
14113 		return ARG_SCALAR;
14114 	}
14115 
14116 	if (!btf_type_is_ptr(t)) {
14117 		verbose(env, "Unrecognized %s type %s\n",
14118 			reg_arg_name(env, argno), btf_type_str(t));
14119 		return -EINVAL;
14120 	}
14121 	/* Keep a pointer to the BTF field containing the resolved referent ID. */
14122 	ref_id_ptr = &t->type;
14123 	ref_t = btf_type_skip_modifiers(meta->btf, *ref_id_ptr, &ref_id);
14124 	while (*ref_id_ptr != ref_id)
14125 		ref_id_ptr = &btf_type_by_id(meta->btf, *ref_id_ptr)->type;
14126 	ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
14127 
14128 	/* In this function, we verify the kfunc's BTF as per the argument type,
14129 	 * leaving the rest of the verification with respect to the register
14130 	 * type to our caller. When a set of conditions hold in the BTF type of
14131 	 * arguments, we resolve it to a known bpf_arg_type.
14132 	 */
14133 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]) ||
14134 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_is_return]) ||
14135 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_cookie]))
14136 		arg_type = ARG_PTR_TO_CTX;
14137 	else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
14138 		arg_type = ARG_PTR_TO_CTX;
14139 	else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
14140 		arg_type = ARG_PTR_TO_ALLOC_BTF_ID;
14141 	else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
14142 		arg_type = ARG_PTR_TO_REFCOUNTED_KPTR;
14143 	else if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) {
14144 		arg_type = ARG_PTR_TO_DYNPTR;
14145 
14146 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb]))
14147 			arg_type |= DYNPTR_TYPE_SKB;
14148 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_xdp]))
14149 			arg_type |= DYNPTR_TYPE_XDP;
14150 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb_meta]))
14151 			arg_type |= DYNPTR_TYPE_SKB_META;
14152 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_file]) ||
14153 			 is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_file_discard]))
14154 			/* OBJ_RELEASE for the latter comes from KF_RELEASE below */
14155 			arg_type |= DYNPTR_TYPE_FILE;
14156 	} else if (is_kfunc_arg_iter(meta, arg, &args[arg]))
14157 		arg_type = ARG_PTR_TO_ITER;
14158 	else if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
14159 		arg_type = ARG_PTR_TO_LIST_HEAD;
14160 	else if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
14161 		arg_type = ARG_PTR_TO_LIST_NODE;
14162 	else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
14163 		arg_type = ARG_PTR_TO_RB_ROOT;
14164 	else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
14165 		arg_type = ARG_PTR_TO_RB_NODE;
14166 	else if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
14167 		arg_type = ARG_PTR_TO_CONST_STR;
14168 	else if (is_kfunc_arg_const_map(meta->btf, &args[arg]))
14169 		arg_type = ARG_CONST_MAP_PTR;
14170 	else if (is_kfunc_arg_map(meta->btf, &args[arg]))
14171 		arg_type = ARG_PTR_TO_BTF_ID;
14172 	else if (is_kfunc_arg_wq(meta->btf, &args[arg]))
14173 		arg_type = ARG_PTR_TO_WORKQUEUE;
14174 	else if (is_kfunc_arg_timer(meta->btf, &args[arg]))
14175 		arg_type = ARG_PTR_TO_TIMER;
14176 	else if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
14177 		arg_type = ARG_PTR_TO_TASK_WORK;
14178 	else if (is_kfunc_arg_rcu_head(meta->btf, &args[arg]))
14179 		arg_type = ARG_PTR_TO_RCU_HEAD;
14180 	else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
14181 		arg_type = ARG_PTR_TO_IRQ_FLAG;
14182 	else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
14183 		arg_type = ARG_PTR_TO_RES_SPIN_LOCK;
14184 	else if (is_kfunc_arg_ctx_out(meta->btf, &args[arg])) {
14185 		if (!btf_type_is_scalar(ref_t)) {
14186 			verbose(env, "%s __ctx_out argument must point to a scalar\n",
14187 				reg_arg_name(env, argno));
14188 			return -EINVAL;
14189 		}
14190 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
14191 		if (IS_ERR(resolve_ret)) {
14192 			verbose(env,
14193 				"%s reference type('%s %s') size cannot be determined: %ld\n",
14194 				reg_arg_name(env, argno), btf_type_str(ref_t),
14195 				ref_tname, PTR_ERR(resolve_ret));
14196 			return -EINVAL;
14197 		}
14198 		proto->arg_size[arg] = type_size;
14199 		arg_type = ARG_PTR_TO_CTX_OUT | MEM_FIXED_SIZE;
14200 	} else if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
14201 		arg_type = ARG_PTR_TO_FUNC;
14202 	else if (is_kfunc_arg_arena(meta->btf, &args[arg])) {
14203 		if (!bpf_jit_supports_arena_args()) {
14204 			verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n",
14205 				meta->func_name);
14206 			return -ENOTSUPP;
14207 		}
14208 		if (!env->prog->aux->arena) {
14209 			verbose(env,
14210 				"%s arena pointer requires a program with an associated arena\n",
14211 				reg_arg_name(env, argno));
14212 			return -EINVAL;
14213 		}
14214 		if (reg_from_argno(argno) < 0) {
14215 			verbose(env, "%s arena pointer cannot be a stack argument\n",
14216 				reg_arg_name(env, argno));
14217 			return -EINVAL;
14218 		}
14219 		/*
14220 		 * Both suffixes accept a constant zero. The function model determines
14221 		 * whether the JIT rebases it to the arena base or preserves NULL.
14222 		 * The common nullable path below records that verifier property.
14223 		 */
14224 		arg_type = ARG_PTR_TO_ARENA;
14225 	} else if (arg + 1 < nargs &&
14226 		 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) ||
14227 		  is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) {
14228 		if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) &&
14229 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
14230 			verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n",
14231 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
14232 			return -EINVAL;
14233 		}
14234 		arg_type = ARG_PTR_TO_MEM | MEM_WRITE;
14235 	} else if (btf_type_is_struct(ref_t))
14236 		/* A pointer to a struct without a size argument is classified as ARG_PTR_TO_BTF_ID */
14237 		arg_type = ARG_PTR_TO_BTF_ID;
14238 	else {
14239 		/*
14240 		 * Otherwise this is a fixed-size memory buffer supported by
14241 		 * check_helper_mem_access(): a pointer to a scalar or a struct of
14242 		 * scalars. The access size is derived from the pointed-to BTF type.
14243 		 */
14244 		if (!btf_type_is_scalar(ref_t) &&
14245 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
14246 			verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n",
14247 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
14248 			return -EINVAL;
14249 		}
14250 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
14251 		if (IS_ERR(resolve_ret)) {
14252 			verbose(env,
14253 				"%s reference type('%s %s') size cannot be determined: %ld\n",
14254 				reg_arg_name(env, argno), btf_type_str(ref_t),
14255 				ref_tname, PTR_ERR(resolve_ret));
14256 			return -EINVAL;
14257 		}
14258 		proto->arg_size[arg] = type_size;
14259 		arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE;
14260 	}
14261 
14262 	if (is_kfunc_arg_uninit(meta->btf, &args[arg]))
14263 		arg_type |= MEM_UNINIT;
14264 
14265 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]))
14266 		arg_type |= PTR_MAYBE_NULL;
14267 
14268 	/*
14269 	 * Only the first argument of a KF_RELEASE kfunc releases anything, and
14270 	 * bpf_fetch_kfunc_arg_meta() only ever records BPF_REG_1 for it.
14271 	 */
14272 	if (is_kfunc_release(meta) && arg == 0)
14273 		arg_type |= OBJ_RELEASE;
14274 
14275 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
14276 		if (is_kfunc_arg_map(meta->btf, &args[arg]))
14277 			proto->arg_btf_id[arg] = reg2btf_ids[CONST_PTR_TO_MAP];
14278 		else
14279 			proto->arg_btf_id[arg] = ref_id_ptr;
14280 
14281 		arg_type |= PTR_TRUSTED;
14282 
14283 		/*
14284 		 * A KF_RCU kfunc accepts an RCU-protected pointer where it would
14285 		 * otherwise demand a referenced or trusted one. Other argument kinds
14286 		 * have their own provenance requirements and must not inherit MEM_RCU.
14287 		 */
14288 		if (is_kfunc_rcu(meta))
14289 			arg_type |= MEM_RCU;
14290 	}
14291 
14292 	return arg_type;
14293 }
14294 
14295 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
14296 			       const struct btf_func_model *fm, struct bpf_func_proto *proto)
14297 {
14298 	const struct bpf_jit_arg_abi *abi;
14299 	const struct btf *btf = meta->btf;
14300 	const struct btf_param *args;
14301 	const struct btf_type *t;
14302 	u32 i, nargs, slots_used;
14303 	int arg_type;
14304 
14305 	args = (const struct btf_param *)(meta->func_proto + 1);
14306 	nargs = btf_type_vlen(meta->func_proto);
14307 	if (nargs > MAX_BPF_FUNC_ARGS) {
14308 		verbose(env, "Function %s has %d > %d args\n", meta->func_name,
14309 			nargs, MAX_BPF_FUNC_ARGS);
14310 		return -EINVAL;
14311 	}
14312 
14313 	for (i = 0, slots_used = 0; i < nargs; i++) {
14314 		u32 nslots = btf_func_model_arg_slots(fm, i);
14315 
14316 		if (nslots > 1) {
14317 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
14318 			if (!btf_func_arg_align(btf, t)) {
14319 				verbose(env,
14320 					"Function %s arg#%d type %s nests structs more than "
14321 					"%d levels deep\n",
14322 					meta->func_name, i, btf_type_str(t),
14323 					BTF_MEMBER_MAX_DEPTH);
14324 				return -EINVAL;
14325 			}
14326 		}
14327 		slots_used += nslots;
14328 	}
14329 
14330 	if (slots_used > MAX_BPF_FUNC_ARGS) {
14331 		verbose(env, "Function %s needs %d > %d argument slots\n", meta->func_name,
14332 			slots_used, MAX_BPF_FUNC_ARGS);
14333 		return -EINVAL;
14334 	}
14335 
14336 	abi = bpf_jit_arg_abi();
14337 
14338 	for (i = 0, slots_used = 0; i < nargs; i++) {
14339 		u32 nslots = btf_func_model_arg_slots(fm, i);
14340 
14341 		if (!abi && nslots > 1) {
14342 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
14343 			verbose(env,
14344 				"Function %s arg#%d type %s cannot be passed at "
14345 				"argument slot %d on this architecture\n",
14346 				meta->func_name, i, btf_type_str(t), slots_used);
14347 			return -EINVAL;
14348 		}
14349 		slots_used += nslots;
14350 
14351 		arg_type = get_kfunc_arg_type(env, meta, args, i, nargs,
14352 					      slots_used - nslots, proto);
14353 		if (arg_type < 0)
14354 			return arg_type;
14355 
14356 		proto->arg_type[i] = arg_type;
14357 	}
14358 
14359 	if (slots_used > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
14360 		verbose(env, "JIT does not support kfunc %s() with %d argument slots\n",
14361 			meta->func_name, slots_used);
14362 		return -ENOTSUPP;
14363 	}
14364 
14365 	return check_arg_prog_aux(env, proto) ? 0 : -EINVAL;
14366 }
14367 
14368 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
14369 				     argno_t argno, enum bpf_arg_type arg_type,
14370 				     const struct btf *arg_btf, u32 arg_btf_id,
14371 				     struct bpf_call_arg_meta *meta, int insn_idx)
14372 {
14373 	bool taking_projection, struct_same, strict_type_match = false;
14374 	const struct btf_type *arg_t, *reg_t;
14375 	const char *arg_tname, *reg_tname;
14376 	const struct btf *reg_btf;
14377 	u32 reg_btf_id;
14378 
14379 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
14380 		reg_btf = reg->btf;
14381 		reg_btf_id = reg->btf_id;
14382 	} else {
14383 		reg_btf = btf_vmlinux;
14384 		reg_btf_id = *reg2btf_ids[base_type(reg->type)];
14385 	}
14386 
14387 	/*
14388 	 * Enforce strict type matching for arguments that release a reference,
14389 	 * or are no-cast aliases. We do _not_ enforce strict matching by default,
14390 	 * as we want to enable BPF programs to pass types that are bitwise
14391 	 * equivalent without forcing them to explicitly cast with something
14392 	 * like bpf_cast_to_kern_ctx().
14393 	 *
14394 	 * For example, say we had a type like the following:
14395 	 *
14396 	 * struct bpf_cpumask {
14397 	 *	cpumask_t cpumask;
14398 	 *	refcount_t usage;
14399 	 * };
14400 	 *
14401 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
14402 	 * to a struct cpumask, so it would be safe to pass a struct
14403 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
14404 	 *
14405 	 * The philosophy here is similar to how we allow scalars of different
14406 	 * types to be passed to kfuncs as long as the size is the same. The
14407 	 * only difference here is that we're simply allowing
14408 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
14409 	 * resolve types.
14410 	 */
14411 	if ((arg_type_is_release(arg_type) && !is_helper_call(meta, BPF_FUNC_sk_release)) ||
14412 	    (is_kfunc(meta) && btf_type_ids_nocast_alias(&env->log, reg_btf, reg_btf_id,
14413 						    arg_btf, arg_btf_id)))
14414 		strict_type_match = true;
14415 
14416 	arg_t = btf_type_skip_modifiers(arg_btf, arg_btf_id, &arg_btf_id);
14417 	arg_tname = btf_name_by_offset(arg_btf, arg_t->name_off);
14418 	reg_t = btf_type_skip_modifiers(reg_btf, reg_btf_id, &reg_btf_id);
14419 	reg_tname = btf_name_by_offset(reg_btf, reg_t->name_off);
14420 
14421 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_btf_id,
14422 					  reg->var_off.value, arg_btf, arg_btf_id,
14423 					  strict_type_match, !type_is_alloc(reg->type));
14424 
14425 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
14426 	 * actually use it -- it must cast to the underlying type. So we allow
14427 	 * caller to pass in the underlying type. Only kernel BTF has that type:
14428 	 * a type of the same name in the BTF of the program is program memory.
14429 	 * And only a pointer to the start of the object points to that type.
14430 	 */
14431 	taking_projection = is_kfunc(meta) && btf_is_kernel(reg_btf) &&
14432 			    !reg->var_off.value &&
14433 			    btf_is_projection_of(arg_tname, reg_tname);
14434 	if (!taking_projection && !struct_same) {
14435 		verbose(env, "%s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
14436 			meta->func_name, reg_arg_name(env, argno),
14437 			btf_type_str(arg_t), arg_tname,
14438 			reg_arg_name(env, argno), btf_type_str(reg_t), reg_tname);
14439 		return -EINVAL;
14440 	}
14441 	return 0;
14442 }
14443 
14444 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
14445 			     struct bpf_call_arg_meta *meta)
14446 {
14447 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
14448 	bool irq_save;
14449 
14450 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_save]) ||
14451 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
14452 		irq_save = true;
14453 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14454 			kfunc_class = IRQ_LOCK_KFUNC;
14455 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_restore]) ||
14456 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) {
14457 		irq_save = false;
14458 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14459 			kfunc_class = IRQ_LOCK_KFUNC;
14460 	} else {
14461 		verifier_bug(env, "unknown irq flags kfunc");
14462 		return -EFAULT;
14463 	}
14464 
14465 	if (irq_save) {
14466 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
14467 			verbose(env, "expected uninitialized irq flag as %s\n",
14468 				reg_arg_name(env, argno));
14469 			bpf_diag_res(env, env->insn_idx, "IRQ flag is already initialized",
14470 				     "Saving IRQ state requires an uninitialized stack slot for "
14471 				     "the IRQ flag, but this slot already contains tracked IRQ "
14472 				     "flag state.",
14473 				     "Use a fresh stack slot for this save operation, or restore "
14474 				     "the existing IRQ flag before reusing the slot.");
14475 			return -EINVAL;
14476 		}
14477 
14478 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
14479 				       BPF_WRITE, -1, false, false);
14480 		if (err)
14481 			return err;
14482 
14483 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
14484 		if (err)
14485 			return err;
14486 	} else {
14487 		err = is_irq_flag_reg_valid_init(env, reg);
14488 		if (err) {
14489 			verbose(env, "expected an initialized irq flag as %s\n",
14490 				reg_arg_name(env, argno));
14491 			bpf_diag_res(env, env->insn_idx, "uninitialized IRQ flag restore",
14492 				     "Restoring IRQ state requires a stack slot that was "
14493 				     "initialized by a matching IRQ save operation on this path.",
14494 				     "Pass the same stack slot that was previously initialized by "
14495 				     "the matching IRQ save kfunc.");
14496 			return err;
14497 		}
14498 
14499 		spi = irq_flag_get_spi(env, reg);
14500 		if (spi < 0)
14501 			return spi;
14502 
14503 		mark_stack_slots_scratched(env, spi, 1);
14504 
14505 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
14506 		if (err)
14507 			return err;
14508 
14509 		if (!in_rcu_cs(env))
14510 			invalidate_rcu_protected_refs(env);
14511 	}
14512 	return 0;
14513 }
14514 
14515 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14516 {
14517 	struct btf_record *rec = reg_btf_record(reg);
14518 
14519 	if (!env->cur_state->active_locks) {
14520 		verifier_bug(env, "%s w/o active lock", __func__);
14521 		return -EFAULT;
14522 	}
14523 
14524 	if (type_flag(reg->type) & NON_OWN_REF) {
14525 		verifier_bug(env, "NON_OWN_REF already set");
14526 		return -EFAULT;
14527 	}
14528 
14529 	reg->type |= NON_OWN_REF;
14530 	if (rec->refcount_off >= 0)
14531 		reg->type |= MEM_RCU;
14532 
14533 	return 0;
14534 }
14535 
14536 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
14537 {
14538 	struct bpf_func_state *unused;
14539 	struct bpf_reg_state *reg;
14540 	int err;
14541 
14542 	err = release_reference_nomark(env, id);
14543 	WARN_ON_ONCE(err);
14544 
14545 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
14546 		if (reg->id == id) {
14547 			reg->id = 0;
14548 			ref_set_non_owning(env, reg);
14549 		}
14550 	}));
14551 
14552 	return;
14553 }
14554 
14555 /* Implementation details:
14556  *
14557  * Each register points to some region of memory, which we define as an
14558  * allocation. Each allocation may embed a bpf_spin_lock which protects any
14559  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
14560  * allocation. The lock and the data it protects are colocated in the same
14561  * memory region.
14562  *
14563  * Hence, everytime a register holds a pointer value pointing to such
14564  * allocation, the verifier preserves a unique reg->id for it.
14565  *
14566  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
14567  * bpf_spin_lock is called.
14568  *
14569  * To enable this, lock state in the verifier captures two values:
14570  *	active_lock.ptr = Register's type specific pointer
14571  *	active_lock.id  = A unique ID for each register pointer value
14572  *
14573  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
14574  * supported register types.
14575  *
14576  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
14577  * allocated objects is the reg->btf pointer.
14578  *
14579  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
14580  * can establish the provenance of the map value statically for each distinct
14581  * lookup into such maps. They always contain a single map value hence unique
14582  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
14583  *
14584  * So, in case of global variables, they use array maps with max_entries = 1,
14585  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
14586  * into the same map value as max_entries is 1, as described above).
14587  *
14588  * In case of inner map lookups, the inner map pointer has same map_ptr as the
14589  * outer map pointer (in verifier context), but each lookup into an inner map
14590  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
14591  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
14592  * will get different reg->id assigned to each lookup, hence different
14593  * active_lock.id.
14594  *
14595  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
14596  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
14597  * returned from bpf_obj_new. Each allocation receives a new reg->id.
14598  */
14599 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14600 {
14601 	struct bpf_reference_state *s;
14602 	void *ptr;
14603 	u32 id;
14604 
14605 	switch ((int)reg->type) {
14606 	case PTR_TO_MAP_VALUE:
14607 		ptr = reg->map_ptr;
14608 		break;
14609 	case PTR_TO_BTF_ID | MEM_ALLOC:
14610 		ptr = reg->btf;
14611 		break;
14612 	default:
14613 		verifier_bug(env, "unknown reg type for lock check");
14614 		return -EFAULT;
14615 	}
14616 	id = reg->id;
14617 
14618 	if (!env->cur_state->active_locks)
14619 		return -EINVAL;
14620 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
14621 	if (!s) {
14622 		verbose(env, "held lock and object are not in the same allocation\n");
14623 		return -EINVAL;
14624 	}
14625 	return 0;
14626 }
14627 
14628 static bool is_bpf_list_api_kfunc(u32 btf_id)
14629 {
14630 	return is_bpf_list_push_kfunc(btf_id) ||
14631 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
14632 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
14633 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
14634 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
14635 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
14636 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14637 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
14638 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
14639 }
14640 
14641 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
14642 {
14643 	return is_bpf_rbtree_add_kfunc(btf_id) ||
14644 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14645 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
14646 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
14647 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14648 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
14649 }
14650 
14651 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta)
14652 {
14653 	int flags = PROCESS_RES_LOCK;
14654 
14655 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock]) ||
14656 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14657 		flags |= PROCESS_SPIN_LOCK;
14658 	else if (!is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock]) &&
14659 		 !is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14660 		return 0;
14661 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) ||
14662 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14663 		flags |= PROCESS_LOCK_IRQ;
14664 	return flags;
14665 }
14666 
14667 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset)
14668 {
14669 	struct bpf_kfunc_meta kfunc;
14670 	int err;
14671 
14672 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
14673 	if (err || !kfunc.flags)
14674 		return false;
14675 
14676 	return *kfunc.flags & KF_SPINLOCK_SAFE;
14677 }
14678 
14679 /*
14680  * True if insn calls a helper/kfunc that requires one of its arguments to
14681  * be a stack pointer with a constant offset.
14682  */
14683 bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
14684 {
14685 	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
14686 	const struct bpf_func_proto *fn;
14687 	struct bpf_kfunc_desc *desc;
14688 	u32 *flags, btf_id;
14689 	int i;
14690 
14691 	if (bpf_helper_call(insn)) {
14692 		if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
14693 			return false;
14694 	} else if (bpf_pseudo_kfunc_call(insn)) {
14695 		desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14696 		if (!desc)
14697 			return false;
14698 		fn = &desc->proto;
14699 	} else {
14700 		return false;
14701 	}
14702 
14703 	/* Both initialized and uninitialized stack dynptrs need a fixed offset. */
14704 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
14705 		if (arg_type_is_dynptr(fn->arg_type[i]))
14706 			return true;
14707 
14708 	/* vmlinux kfuncs only */
14709 	if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
14710 		return false;
14711 	btf_id = insn->imm;
14712 
14713 	flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
14714 	if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
14715 		return true;
14716 
14717 	if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14718 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
14719 	    btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
14720 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
14721 	    btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
14722 	    btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
14723 		return true;
14724 
14725 	return false;
14726 }
14727 
14728 static bool is_sync_callback_calling_kfunc(u32 btf_id)
14729 {
14730 	return is_bpf_rbtree_add_kfunc(btf_id);
14731 }
14732 
14733 static bool is_async_callback_calling_kfunc(u32 btf_id)
14734 {
14735 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
14736 	       is_task_work_add_kfunc(btf_id) ||
14737 	       is_call_rcu_kfunc(btf_id);
14738 }
14739 
14740 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
14741 {
14742 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
14743 	       insn->imm == special_kfunc_list[KF_bpf_throw];
14744 }
14745 
14746 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
14747 {
14748 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
14749 }
14750 
14751 static bool is_callback_calling_kfunc(u32 btf_id)
14752 {
14753 	return is_sync_callback_calling_kfunc(btf_id) ||
14754 	       is_async_callback_calling_kfunc(btf_id);
14755 }
14756 
14757 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
14758 {
14759 	return is_bpf_rbtree_api_kfunc(btf_id);
14760 }
14761 
14762 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
14763 					  enum btf_field_type head_field_type,
14764 					  u32 kfunc_btf_id)
14765 {
14766 	bool ret;
14767 
14768 	switch (head_field_type) {
14769 	case BPF_LIST_HEAD:
14770 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
14771 		break;
14772 	case BPF_RB_ROOT:
14773 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
14774 		break;
14775 	default:
14776 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
14777 			btf_field_type_name(head_field_type));
14778 		return false;
14779 	}
14780 
14781 	if (!ret)
14782 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
14783 			btf_field_type_name(head_field_type));
14784 	return ret;
14785 }
14786 
14787 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
14788 					  enum btf_field_type node_field_type,
14789 					  u32 kfunc_btf_id)
14790 {
14791 	bool ret;
14792 
14793 	switch (node_field_type) {
14794 	case BPF_LIST_NODE:
14795 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
14796 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
14797 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14798 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
14799 		break;
14800 	case BPF_RB_NODE:
14801 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
14802 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14803 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14804 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
14805 		break;
14806 	default:
14807 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
14808 			btf_field_type_name(node_field_type));
14809 		return false;
14810 	}
14811 
14812 	if (!ret)
14813 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
14814 			btf_field_type_name(node_field_type));
14815 	return ret;
14816 }
14817 
14818 static int
14819 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
14820 				   struct bpf_reg_state *reg, argno_t argno,
14821 				   struct bpf_call_arg_meta *meta,
14822 				   enum btf_field_type head_field_type,
14823 				   struct btf_field **head_field)
14824 {
14825 	const char *head_type_name;
14826 	struct btf_field *field;
14827 	struct btf_record *rec;
14828 	u32 head_off;
14829 
14830 	if (meta->btf != btf_vmlinux) {
14831 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14832 		return -EFAULT;
14833 	}
14834 
14835 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
14836 		return -EFAULT;
14837 
14838 	head_type_name = btf_field_type_name(head_field_type);
14839 	if (!tnum_is_const(reg->var_off)) {
14840 		verbose(env,
14841 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14842 			reg_arg_name(env, argno), head_type_name);
14843 		return -EINVAL;
14844 	}
14845 
14846 	rec = reg_btf_record(reg);
14847 	head_off = reg->var_off.value;
14848 	field = btf_record_find(rec, head_off, head_field_type);
14849 	if (!field) {
14850 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
14851 		return -EINVAL;
14852 	}
14853 
14854 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
14855 	if (check_reg_allocation_locked(env, reg)) {
14856 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
14857 			rec->spin_lock_off, head_type_name);
14858 		return -EINVAL;
14859 	}
14860 
14861 	if (*head_field) {
14862 		verifier_bug(env, "repeating %s arg", head_type_name);
14863 		return -EFAULT;
14864 	}
14865 	*head_field = field;
14866 	return 0;
14867 }
14868 
14869 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
14870 					   struct bpf_reg_state *reg, argno_t argno,
14871 					   struct bpf_call_arg_meta *meta)
14872 {
14873 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
14874 							  &meta->arg_list_head.field);
14875 }
14876 
14877 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
14878 					     struct bpf_reg_state *reg, argno_t argno,
14879 					     struct bpf_call_arg_meta *meta)
14880 {
14881 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
14882 							  &meta->arg_rbtree_root.field);
14883 }
14884 
14885 static int
14886 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
14887 				   struct bpf_reg_state *reg, argno_t argno,
14888 				   struct bpf_call_arg_meta *meta,
14889 				   enum btf_field_type head_field_type,
14890 				   enum btf_field_type node_field_type,
14891 				   struct btf_field **node_field)
14892 {
14893 	const char *node_type_name;
14894 	const struct btf_type *et, *t;
14895 	struct btf_field *field;
14896 	u32 node_off;
14897 
14898 	if (meta->btf != btf_vmlinux) {
14899 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14900 		return -EFAULT;
14901 	}
14902 
14903 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
14904 		return -EFAULT;
14905 
14906 	node_type_name = btf_field_type_name(node_field_type);
14907 	if (!tnum_is_const(reg->var_off)) {
14908 		verbose(env,
14909 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14910 			reg_arg_name(env, argno), node_type_name);
14911 		return -EINVAL;
14912 	}
14913 
14914 	node_off = reg->var_off.value;
14915 	field = reg_find_field_offset(reg, node_off, node_field_type);
14916 	if (!field) {
14917 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
14918 		return -EINVAL;
14919 	}
14920 
14921 	field = *node_field;
14922 
14923 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
14924 	t = btf_type_by_id(reg->btf, reg->btf_id);
14925 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
14926 				  field->graph_root.value_btf_id, true,
14927 				  !type_is_alloc(reg->type))) {
14928 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
14929 			"in struct %s, but arg is at offset=%d in struct %s\n",
14930 			btf_field_type_name(head_field_type),
14931 			btf_field_type_name(node_field_type),
14932 			field->graph_root.node_offset,
14933 			btf_name_by_offset(field->graph_root.btf, et->name_off),
14934 			node_off, btf_name_by_offset(reg->btf, t->name_off));
14935 		return -EINVAL;
14936 	}
14937 	meta->arg_btf = reg->btf;
14938 	meta->arg_btf_id = reg->btf_id;
14939 
14940 	if (node_off != field->graph_root.node_offset) {
14941 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
14942 			node_off, btf_field_type_name(node_field_type),
14943 			field->graph_root.node_offset,
14944 			btf_name_by_offset(field->graph_root.btf, et->name_off));
14945 		return -EINVAL;
14946 	}
14947 
14948 	return 0;
14949 }
14950 
14951 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
14952 					   struct bpf_reg_state *reg, argno_t argno,
14953 					   struct bpf_call_arg_meta *meta)
14954 {
14955 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14956 						  BPF_LIST_HEAD, BPF_LIST_NODE,
14957 						  &meta->arg_list_head.field);
14958 }
14959 
14960 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
14961 					     struct bpf_reg_state *reg, argno_t argno,
14962 					     struct bpf_call_arg_meta *meta)
14963 {
14964 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14965 						  BPF_RB_ROOT, BPF_RB_NODE,
14966 						  &meta->arg_rbtree_root.field);
14967 }
14968 
14969 /*
14970  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
14971  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
14972  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
14973  * them can only be attached to some specific hook points.
14974  */
14975 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
14976 {
14977 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14978 
14979 	switch (prog_type) {
14980 	case BPF_PROG_TYPE_LSM:
14981 		return true;
14982 	case BPF_PROG_TYPE_TRACING:
14983 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
14984 			return true;
14985 		fallthrough;
14986 	default:
14987 		return in_sleepable(env);
14988 	}
14989 }
14990 
14991 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
14992 			     s32 func_id,
14993 			     s16 offset,
14994 			     struct bpf_call_arg_meta *meta)
14995 {
14996 	struct bpf_kfunc_meta kfunc;
14997 	int err;
14998 
14999 	memset(meta, 0, sizeof(*meta));
15000 
15001 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
15002 	if (err)
15003 		return err;
15004 
15005 	meta->btf = kfunc.btf;
15006 	meta->func_id = kfunc.id;
15007 	meta->func_proto = kfunc.proto;
15008 	meta->func_name = kfunc.name;
15009 
15010 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
15011 		return -EACCES;
15012 
15013 	meta->kfunc_flags = *kfunc.flags;
15014 
15015 	/* Only support release referenced argument passed by register */
15016 	if (is_kfunc_release(meta))
15017 		meta->release_regno = BPF_REG_1;
15018 
15019 	return 0;
15020 }
15021 
15022 /*
15023  * Describe a helper's stack access through argument @arg (0-based, R1-R5).
15024  * must_write means the verifier destroys prior state throughout size bytes.
15025  * In other words, must_write follows the verifier's model of the
15026  * function's behaviour, which is safe to use for is_state_visited() pruning.
15027  */
15028 struct arg_access_info
15029 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
15030 			      int arg, int insn_idx)
15031 {
15032 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
15033 	struct arg_access_info info = {
15034 		.size = U32_MAX,
15035 		.may_read = true,
15036 		.may_write = true,
15037 	};
15038 	const struct bpf_func_proto *fn;
15039 	enum bpf_access_type access_type;
15040 	enum bpf_arg_type at;
15041 	bool exact_size = true;
15042 	u64 size = U32_MAX;
15043 
15044 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
15045 		return info;
15046 
15047 	at = fn->arg_type[arg];
15048 	access_type = func_arg_access_type(at);
15049 
15050 	switch (base_type(at)) {
15051 	case ARG_PTR_TO_MAP_KEY:
15052 	case ARG_PTR_TO_MAP_VALUE: {
15053 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
15054 		u64 val;
15055 		int i, map_reg;
15056 
15057 		for (i = 0; i < arg; i++) {
15058 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
15059 				break;
15060 		}
15061 		if (i >= arg)
15062 			goto scan_all_maps;
15063 
15064 		map_reg = BPF_REG_1 + i;
15065 
15066 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
15067 			goto scan_all_maps;
15068 
15069 		i = aux->const_reg_vals[map_reg];
15070 		if (i < env->used_map_cnt) {
15071 			/* Bloom-filter peek reads the value buffer. */
15072 			if (!is_key && insn->imm == BPF_FUNC_map_peek_elem &&
15073 			    env->used_maps[i]->map_type == BPF_MAP_TYPE_BLOOM_FILTER)
15074 				access_type = BPF_READ;
15075 			size = is_key ? env->used_maps[i]->key_size
15076 				      : env->used_maps[i]->value_size;
15077 			goto out;
15078 		}
15079 scan_all_maps:
15080 		/*
15081 		 * Map pointer is not known at this call site (e.g. different
15082 		 * maps on merged paths).  Conservatively return the largest
15083 		 * key_size or value_size across all maps used by the program.
15084 		 * This is only an upper bound, so it cannot establish a definite
15085 		 * write. Map-dependent argument types can also turn an output
15086 		 * into an input, so conservatively retain a read dependency.
15087 		 */
15088 		exact_size = false;
15089 		access_type |= BPF_READ;
15090 		val = 0;
15091 		for (i = 0; i < env->used_map_cnt; i++) {
15092 			struct bpf_map *map = env->used_maps[i];
15093 			u32 sz = is_key ? map->key_size : map->value_size;
15094 
15095 			if (sz > val)
15096 				val = sz;
15097 			if (map->inner_map_meta) {
15098 				sz = is_key ? map->inner_map_meta->key_size
15099 					    : map->inner_map_meta->value_size;
15100 				if (sz > val)
15101 					val = sz;
15102 			}
15103 		}
15104 		if (!val)
15105 			return info;
15106 		size = val;
15107 		goto out;
15108 	}
15109 	case ARG_PTR_TO_MEM:
15110 		if (at & MEM_FIXED_SIZE) {
15111 			size = fn->arg_size[arg];
15112 			goto out;
15113 		}
15114 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
15115 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
15116 			int size_reg = BPF_REG_1 + arg + 1;
15117 
15118 			if (aux->const_reg_mask & BIT(size_reg)) {
15119 				size = aux->const_reg_vals[size_reg];
15120 				goto out;
15121 			}
15122 		}
15123 		/* Preserve access directions even when the extent is unknown. */
15124 		goto out;
15125 	case ARG_PTR_TO_DYNPTR:
15126 		size = BPF_DYNPTR_SIZE;
15127 		break;
15128 	case ARG_PTR_TO_STACK:
15129 		/*
15130 		 * Only used by bpf_calls_callback() helpers. The helper itself
15131 		 * doesn't access stack. The callback subprog does and it's
15132 		 * analyzed separately.
15133 		 */
15134 		return (struct arg_access_info) {};
15135 	default:
15136 		return info;
15137 	}
15138 out:
15139 	info.size = min_t(u64, size, U32_MAX);
15140 	info.may_read = !!(access_type & BPF_READ);
15141 	info.may_write = !!(access_type & BPF_WRITE);
15142 	info.must_write = info.may_write && exact_size && info.size != U32_MAX;
15143 	/* Generic unprivileged outputs retain prior initialization state. */
15144 	if (!env->allow_uninit_stack && arg_type_is_raw_mem(at)) {
15145 		info.may_read = true;
15146 		info.must_write = false;
15147 	}
15148 	return info;
15149 }
15150 
15151 /*
15152  * Describe a kfunc's stack access through argument slot @arg (0-based).
15153  * As for helpers, must_write describes destruction of prior verifier state,
15154  * rather than a guarantee that the callee writes every byte at runtime.
15155  */
15156 struct arg_access_info
15157 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
15158 			     int arg, int insn_idx)
15159 {
15160 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
15161 	struct arg_access_info info = {
15162 		.size = U32_MAX,
15163 		.may_read = true,
15164 		.may_write = true,
15165 	};
15166 	struct bpf_call_arg_meta meta;
15167 	const struct btf_param *args;
15168 	const struct btf_type *t, *ref_t;
15169 	const struct btf *btf;
15170 	u32 i, slot, nargs, type_size;
15171 	u64 size;
15172 
15173 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
15174 		return info;
15175 
15176 	btf = meta.btf;
15177 	args = btf_params(meta.func_proto);
15178 	nargs = btf_type_vlen(meta.func_proto);
15179 
15180 	/*
15181 	 * @arg is an argument slot and a 16-byte parameter takes two of them,
15182 	 * so walk the parameters to find the one that starts at this slot. A
15183 	 * slot holding the upper eightbyte of such a parameter belongs to no
15184 	 * pointer, and neither does a slot past the last parameter.
15185 	 */
15186 	for (i = 0, slot = 0; i < nargs && slot < arg; i++)
15187 		slot += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
15188 	if (i >= nargs || slot != arg)
15189 		return (struct arg_access_info) {};
15190 
15191 	t = btf_type_skip_modifiers(btf, args[i].type, NULL);
15192 	if (!btf_type_is_ptr(t))
15193 		return (struct arg_access_info) {};
15194 
15195 	/* dynptr: fixed 16-byte on-stack representation */
15196 	if (is_kfunc_arg_dynptr(btf, &args[i])) {
15197 		size = BPF_DYNPTR_SIZE;
15198 		goto out;
15199 	}
15200 
15201 	/* ptr + __sz/__szk pair: the size follows the pointer */
15202 	if (i + 1 < nargs &&
15203 	    (btf_param_match_suffix(btf, &args[i + 1], "__sz") ||
15204 	     btf_param_match_suffix(btf, &args[i + 1], "__szk"))) {
15205 		int size_reg = BPF_REG_1 + arg + 1;
15206 
15207 		if (size_reg <= MAX_BPF_FUNC_REG_ARGS &&
15208 		    (aux->const_reg_mask & BIT(size_reg))) {
15209 			size = aux->const_reg_vals[size_reg];
15210 			goto out;
15211 		}
15212 		/* Unknown size: the read may extend anywhere up to the frame top. */
15213 		return info;
15214 	}
15215 
15216 	/* fixed-size pointed-to type: resolve via BTF */
15217 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
15218 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
15219 		size = type_size;
15220 		goto out;
15221 	}
15222 
15223 	return info;
15224 out:
15225 	info.size = min_t(u64, size, U32_MAX);
15226 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
15227 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
15228 		info.may_read = false;
15229 	if (is_kfunc_arg_uninit(btf, &args[i]) &&
15230 	    (is_kfunc_arg_dynptr(btf, &args[i]) || env->allow_uninit_stack))
15231 		info.may_read = false;
15232 	info.must_write = !info.may_read && info.size != U32_MAX;
15233 	return info;
15234 }
15235 
15236 /*
15237  * Called before dead code elimination, some subprograms may be genuinely unreachable.
15238  * Suppress diagnostics so callers can use a conservative result on error.
15239  * The main pass would report errors for reachable subprograms.
15240  */
15241 static bool try_btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
15242 {
15243 	struct bpf_prog *prog = env->prog;
15244 	u32 log_level = env->log.level;
15245 	int err;
15246 
15247 	if (!prog->aux->func_info || !prog->aux->func_info[subprog].type_id)
15248 		return false;
15249 
15250 	env->log.level = 0;
15251 	err = btf_prepare_func_args(env, subprog);
15252 	env->log.level = log_level;
15253 	return !err;
15254 }
15255 
15256 /* Prepare argument metadata for liveness; the main program is handled separately. */
15257 static void prepare_subprog_args(struct bpf_verifier_env *env)
15258 {
15259 	int i;
15260 
15261 	for (i = 1; i < env->subprog_cnt; i++) {
15262 		if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i))
15263 			/* Keep all argument registers live if the prototype is unavailable. */
15264 			env->subprog_info[i].arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
15265 	}
15266 }
15267 
15268 /*
15269  * Derive stack effects for a global subprog's argument slot @arg (0-based)
15270  * from its declared type, matching the main pass's argument checks.
15271  */
15272 struct arg_access_info
15273 bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
15274 				      int arg, int insn_idx)
15275 {
15276 	struct arg_access_info info = {
15277 		.size = U32_MAX,
15278 		.may_read = true,
15279 		.may_write = true,
15280 	};
15281 	struct bpf_subprog_info *sub;
15282 	int callee;
15283 
15284 	callee = bpf_find_subprog(env, insn_idx + insn->imm + 1);
15285 	if (callee < 0)
15286 		return info;
15287 	sub = subprog_info(env, callee);
15288 	if (!try_btf_prepare_func_args(env, callee))
15289 		return info;
15290 
15291 	switch (base_type(sub->args[arg].arg_type)) {
15292 	case ARG_UNUSED:	/* Not an argument slot. */
15293 	case ARG_SCALAR:	/* A scalar, the callee can't dereference it. */
15294 		return (struct arg_access_info) {};
15295 	case ARG_PTR_TO_BTF_ID:
15296 		/*
15297 		 * Trusted arguments cannot be stack pointers.
15298 		 * Untrusted arguments use ARG_IGNORE:
15299 		 * probe reads need no caller stack state, writes are prohibited.
15300 		 */
15301 		return (struct arg_access_info) {};
15302 	case ARG_PTR_TO_MEM:
15303 		/* mem_size is zero for untrusted pointers of unknown size. */
15304 		if (sub->args[arg].mem_size) {
15305 			info.size = sub->args[arg].mem_size;
15306 			info.must_write = true;
15307 		}
15308 		return info;
15309 	case ARG_PTR_TO_DYNPTR:
15310 		/* The callee may adjust the view, but cannot reinitialize the dynptr. */
15311 		info.size = BPF_DYNPTR_SIZE;
15312 		return info;
15313 	default:
15314 		return info;
15315 	}
15316 }
15317 
15318 /* check special kfuncs and return:
15319  *  1  - not fall-through to 'else' branch, continue verification
15320  *  0  - fall-through to 'else' branch
15321  * < 0 - not fall-through to 'else' branch, return error
15322  */
15323 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
15324 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
15325 			       const struct btf_type *ptr_type, struct btf *desc_btf)
15326 {
15327 	const struct btf_type *ret_t;
15328 	int err = 0;
15329 
15330 	if (meta->btf != btf_vmlinux)
15331 		return 0;
15332 
15333 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15334 		struct btf_struct_meta *struct_meta;
15335 		struct btf *ret_btf;
15336 		u32 ret_btf_id;
15337 
15338 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
15339 			return -ENOMEM;
15340 
15341 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
15342 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
15343 			return -EINVAL;
15344 		}
15345 
15346 		ret_btf = env->prog->aux->btf;
15347 		ret_btf_id = meta->arg_constant.value;
15348 
15349 		/* This may be NULL due to user not supplying a BTF */
15350 		if (!ret_btf) {
15351 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
15352 			return -EINVAL;
15353 		}
15354 
15355 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
15356 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
15357 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
15358 			return -EINVAL;
15359 		}
15360 
15361 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15362 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
15363 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
15364 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
15365 				return -EINVAL;
15366 			}
15367 
15368 			if (!bpf_global_percpu_ma_set) {
15369 				mutex_lock(&bpf_percpu_ma_lock);
15370 				if (!bpf_global_percpu_ma_set) {
15371 					/* Charge memory allocated with bpf_global_percpu_ma to
15372 					 * root memcg. The obj_cgroup for root memcg is NULL.
15373 					 */
15374 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
15375 					if (!err)
15376 						bpf_global_percpu_ma_set = true;
15377 				}
15378 				mutex_unlock(&bpf_percpu_ma_lock);
15379 				if (err)
15380 					return err;
15381 			}
15382 
15383 			mutex_lock(&bpf_percpu_ma_lock);
15384 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
15385 			mutex_unlock(&bpf_percpu_ma_lock);
15386 			if (err)
15387 				return err;
15388 		}
15389 
15390 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
15391 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15392 			if (!btf_type_is_scalar_struct(env, ret_btf, ret_t)) {
15393 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
15394 				return -EINVAL;
15395 			}
15396 
15397 			if (struct_meta) {
15398 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
15399 				return -EINVAL;
15400 			}
15401 		}
15402 
15403 		mark_reg_known_zero(env, regs, BPF_REG_0);
15404 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
15405 		regs[BPF_REG_0].btf = ret_btf;
15406 		regs[BPF_REG_0].btf_id = ret_btf_id;
15407 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
15408 			regs[BPF_REG_0].type |= MEM_PERCPU;
15409 
15410 		insn_aux->obj_new_size = ret_t->size;
15411 		insn_aux->kptr_struct_meta = struct_meta;
15412 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
15413 		mark_reg_known_zero(env, regs, BPF_REG_0);
15414 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
15415 		regs[BPF_REG_0].btf = meta->arg_btf;
15416 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
15417 
15418 		insn_aux->kptr_struct_meta =
15419 			btf_find_struct_meta(meta->arg_btf,
15420 					     meta->arg_btf_id);
15421 	} else if (is_list_node_type(ptr_type)) {
15422 		struct btf_field *field = meta->arg_list_head.field;
15423 
15424 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15425 	} else if (is_rbtree_node_type(ptr_type)) {
15426 		struct btf_field *field = meta->arg_rbtree_root.field;
15427 
15428 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15429 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx])) {
15430 		mark_reg_known_zero(env, regs, BPF_REG_0);
15431 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
15432 		regs[BPF_REG_0].btf = desc_btf;
15433 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
15434 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_rdonly_cast])) {
15435 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
15436 		if (!ret_t) {
15437 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
15438 				meta->arg_constant.value);
15439 			return -EINVAL;
15440 		} else if (btf_type_is_struct(ret_t)) {
15441 			mark_reg_known_zero(env, regs, BPF_REG_0);
15442 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15443 			regs[BPF_REG_0].btf = desc_btf;
15444 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
15445 		} else if (btf_type_is_void(ret_t)) {
15446 			mark_reg_known_zero(env, regs, BPF_REG_0);
15447 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
15448 			regs[BPF_REG_0].mem_size = 0;
15449 		} else {
15450 			verbose(env,
15451 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
15452 			return -EINVAL;
15453 		}
15454 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
15455 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice_rdwr])) {
15456 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
15457 
15458 		mark_reg_known_zero(env, regs, BPF_REG_0);
15459 
15460 		if (!meta->arg_constant.found) {
15461 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
15462 			return -EFAULT;
15463 		}
15464 
15465 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
15466 
15467 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
15468 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
15469 
15470 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice])) {
15471 			regs[BPF_REG_0].type |= MEM_RDONLY;
15472 		} else {
15473 			/* this will set env->seen_direct_write to true */
15474 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
15475 				verbose(env, "the prog does not allow writes to packet data\n");
15476 				return -EINVAL;
15477 			}
15478 		}
15479 
15480 		if (!meta->dynptr.id) {
15481 			verifier_bug(env, "no dynptr id");
15482 			return -EFAULT;
15483 		}
15484 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
15485 		regs[BPF_REG_0].buf = meta->slice_buf;
15486 		if (meta->slice_buf.size)
15487 			env->seen_stack_slice = true;
15488 	} else {
15489 		return 0;
15490 	}
15491 
15492 	return 1;
15493 }
15494 
15495 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
15496 
15497 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15498 			    int *insn_idx_p)
15499 {
15500 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
15501 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15502 	struct bpf_reg_state *regs = cur_regs(env);
15503 	const char *func_name, *ptr_type_name;
15504 	const struct btf_type *t, *ptr_type;
15505 	struct bpf_call_arg_meta meta;
15506 	struct bpf_insn_aux_data *insn_aux;
15507 	const char *operation;
15508 	int err, insn_idx = *insn_idx_p;
15509 	u32 i, proto_slots, ptr_type_id, ret_nregs = 1;
15510 	struct bpf_kfunc_desc *desc;
15511 	struct btf *desc_btf;
15512 	int id;
15513 
15514 	/* skip for now, but return error when we find this in fixup_kfunc_call */
15515 	if (!insn->imm)
15516 		return 0;
15517 
15518 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
15519 	if (err == -EACCES && meta.func_name) {
15520 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
15521 		operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name);
15522 		bpf_diag_policy(
15523 			env, insn_idx, operation, "this program cannot call the kfunc",
15524 			"Use a kfunc allowed for this program type and attach point, or change the program context.");
15525 	}
15526 	if (err)
15527 		return err;
15528 	desc_btf = meta.btf;
15529 	func_name = meta.func_name;
15530 	insn_aux = &env->insn_aux_data[insn_idx];
15531 
15532 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15533 	if (!desc) {
15534 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
15535 		return -EFAULT;
15536 	}
15537 	meta.fn = &desc->proto;
15538 
15539 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
15540 
15541 	if (!insn->off &&
15542 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
15543 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
15544 		struct bpf_verifier_state *branch;
15545 		struct bpf_reg_state *regs;
15546 
15547 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15548 		if (IS_ERR(branch)) {
15549 			verbose(env, "failed to push state for failed lock acquisition\n");
15550 			return PTR_ERR(branch);
15551 		}
15552 
15553 		regs = branch->frame[branch->curframe]->regs;
15554 
15555 		/* Clear r0-r5 registers in forked state */
15556 		for (i = 0; i < CALLER_SAVED_REGS; i++)
15557 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
15558 
15559 		/* The kfunc returns int, the upper half of r0 is not known */
15560 		mark_reg_unknown(env, regs, BPF_REG_0);
15561 		reg_set_srange32(&regs[BPF_REG_0], -MAX_ERRNO, -1);
15562 		reg_bounds_sync(&regs[BPF_REG_0]);
15563 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
15564 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
15565 		return -EFAULT;
15566 	}
15567 
15568 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
15569 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
15570 		operation = bpf_diag_fmt(env, "destructive kfunc %s", meta.func_name);
15571 		bpf_diag_policy(
15572 			env, insn_idx, operation, "destructive kfuncs require CAP_SYS_BOOT",
15573 			"Load the program with CAP_SYS_BOOT, or avoid destructive kfuncs.");
15574 		return -EACCES;
15575 	}
15576 
15577 	if (is_kfunc_perfmon(&meta) && !env->allow_ptr_leaks) {
15578 		verbose(env, "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
15579 			func_name);
15580 		operation = bpf_diag_fmt(env, "kfunc %s", func_name);
15581 		bpf_diag_policy(env, insn_idx, operation, "the kfunc requires CAP_PERFMON",
15582 				"Load the program with CAP_PERFMON, or avoid the kfunc.");
15583 		return -EPERM;
15584 	}
15585 
15586 	sleepable = bpf_is_kfunc_sleepable(&meta);
15587 	if (sleepable && !in_sleepable_context(env)) {
15588 		const char *suggestion;
15589 
15590 		if (in_sleepable(env)) {
15591 			verbose(env, "kernel func %s is sleepable within %s\n",
15592 				func_name, non_sleepable_context_description(env));
15593 			suggestion = "Move the kfunc call outside the critical section, or use a non-sleepable kfunc.";
15594 		} else {
15595 			verbose(env, "program must be sleepable to call sleepable kfunc %s\n",
15596 				func_name);
15597 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc.";
15598 		}
15599 		operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name);
15600 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
15601 		return -EACCES;
15602 	}
15603 
15604 	/* Track non-sleepable context for kfuncs, same as for helpers. */
15605 	if (!in_sleepable_context(env))
15606 		insn_aux->non_sleepable = true;
15607 
15608 	/* Check the arguments */
15609 	err = check_func_args(env, &meta, insn_idx);
15610 	if (err < 0)
15611 		return err;
15612 
15613 	err = mark_raw_stack(env, &meta, insn_idx);
15614 	if (err)
15615 		return err;
15616 
15617 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
15618 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
15619 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
15620 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
15621 	      && !env->prog->sleepable))) {
15622 		struct btf_struct_meta *struct_meta;
15623 
15624 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15625 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
15626 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
15627 				func_name);
15628 			return -EINVAL;
15629 		}
15630 	}
15631 
15632 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
15633 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15634 					 set_rbtree_add_callback_state);
15635 		if (err) {
15636 			verbose(env, "kfunc %s#%d failed callback verification\n",
15637 				func_name, meta.func_id);
15638 			return err;
15639 		}
15640 	}
15641 
15642 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
15643 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15644 					 set_timer_callback_state);
15645 		if (err) {
15646 			verbose(env, "kfunc %s#%d failed callback verification\n",
15647 				func_name, meta.func_id);
15648 			return err;
15649 		}
15650 	}
15651 
15652 	if (is_task_work_add_kfunc(meta.func_id)) {
15653 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15654 					 set_task_work_schedule_callback_state);
15655 		if (err) {
15656 			verbose(env, "kfunc %s#%d failed callback verification\n",
15657 				func_name, meta.func_id);
15658 			return err;
15659 		}
15660 	}
15661 
15662 	if (is_call_rcu_kfunc(meta.func_id)) {
15663 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15664 					 set_rcu_callback_state);
15665 		if (err) {
15666 			verbose(env, "kfunc %s#%d failed callback verification\n",
15667 				func_name, meta.func_id);
15668 			return err;
15669 		}
15670 	}
15671 
15672 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
15673 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
15674 
15675 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
15676 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
15677 
15678 	if (rcu_lock) {
15679 		env->cur_state->active_rcu_locks++;
15680 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true,
15681 					env->cur_state->active_rcu_locks);
15682 	} else if (rcu_unlock) {
15683 		if (env->cur_state->active_rcu_locks == 0) {
15684 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
15685 			bpf_diag_ctx_underflow(
15686 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15687 				"Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region.");
15688 			return -EINVAL;
15689 		}
15690 		env->cur_state->active_rcu_locks--;
15691 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
15692 					env->cur_state->active_rcu_locks);
15693 		if (!in_rcu_cs(env))
15694 			invalidate_rcu_protected_refs(env);
15695 	} else if (preempt_disable) {
15696 		env->cur_state->active_preempt_locks++;
15697 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true,
15698 					env->cur_state->active_preempt_locks);
15699 	} else if (preempt_enable) {
15700 		if (env->cur_state->active_preempt_locks == 0) {
15701 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
15702 			bpf_diag_ctx_underflow(
15703 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_PREEMPT,
15704 				"Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption.");
15705 			return -EINVAL;
15706 		}
15707 		env->cur_state->active_preempt_locks--;
15708 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
15709 					env->cur_state->active_preempt_locks);
15710 		if (!in_rcu_cs(env))
15711 			invalidate_rcu_protected_refs(env);
15712 	}
15713 
15714 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
15715 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
15716 		return -EACCES;
15717 	}
15718 
15719 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
15720 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
15721 		bpf_diag_ctx_required(
15722 			env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15723 			"Call this kfunc between bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
15724 		return -EACCES;
15725 	}
15726 
15727 	/* In case of release function, we get register number of refcounted
15728 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
15729 	 */
15730 	if (meta.release_regno) {
15731 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
15732 		if (err)
15733 			return err;
15734 	}
15735 
15736 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
15737 		id = regs[BPF_REG_2].id;
15738 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
15739 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15740 		ref_convert_owning_non_owning(env, id);
15741 	}
15742 
15743 	if ((is_kfunc_call(&meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
15744 	     is_kfunc_call(&meta, special_kfunc_list[KF_bpf_dynptr_slice_rdwr])) &&
15745 	    dynptr_slice_may_be_buffer(meta.dynptr.type)) {
15746 		struct bpf_reg_state *buf = &regs[BPF_REG_3];
15747 
15748 		if (buf->type == PTR_TO_STACK) {
15749 			meta.slice_buf.frameno = buf->frameno;
15750 			meta.slice_buf.off = reg_smin(buf);
15751 			meta.slice_buf.size = reg_smax(buf) - reg_smin(buf) +
15752 					      meta.arg_constant.value;
15753 		} else if (base_type(buf->type) == PTR_TO_MEM) {
15754 			/* a slice is the buffer of the next one */
15755 			meta.slice_buf = buf->buf;
15756 		}
15757 	}
15758 
15759 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
15760 		if (!bpf_jit_supports_exceptions()) {
15761 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
15762 				func_name, meta.func_id);
15763 			return -ENOTSUPP;
15764 		}
15765 		env->seen_exception = true;
15766 
15767 		/* In the case of the default callback, the cookie value passed
15768 		 * to bpf_throw becomes the return value of the program.
15769 		 */
15770 		if (!env->exception_callback_subprog) {
15771 			err = check_return_code(env, BPF_REG_1, "R1");
15772 			if (err < 0)
15773 				return err;
15774 		}
15775 	}
15776 
15777 	bpf_diag_record_caller_saved(env, regs);
15778 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
15779 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15780 		u32 regno = caller_saved[i];
15781 
15782 		bpf_mark_reg_not_init(env, &regs[regno]);
15783 	}
15784 	invalidate_outgoing_stack_args(env, cur_func(env));
15785 
15786 	/* Check return type */
15787 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
15788 
15789 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
15790 		if (meta.btf != btf_vmlinux ||
15791 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
15792 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
15793 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
15794 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
15795 			return -EINVAL;
15796 		}
15797 	}
15798 
15799 	if (btf_type_is_scalar(t)) {
15800 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15801 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
15802 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
15803 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
15804 	} else if (btf_type_is_struct(t)) {
15805 		struct btf_member_path path = {};
15806 		const char *member_note = "";
15807 
15808 		/*
15809 		 * The returned struct comes back as raw register bits modeled
15810 		 * as an unknown scalar, so a pointer member would be laundered
15811 		 * into a scalar and escape provenance and reference tracking.
15812 		 * Only scalars and arena pointers are allowed; see
15813 		 * btf_validate_return_type() in btf.c for why an arena pointer
15814 		 * is safe here.
15815 		 */
15816 		if (!btf_struct_member_walk(env, desc_btf, t,
15817 					    BTF_MEMBER_SCALAR | BTF_MEMBER_ARENA_PTR, 0, &path)) {
15818 			verbose(env,
15819 				"kernel function %s returns %s %s that is not composed of scalars or arena pointers\n",
15820 				func_name, btf_type_str(t),
15821 				btf_name_by_offset(desc_btf, t->name_off));
15822 			if (path.too_deep) {
15823 				member_note = bpf_diag_fmt(
15824 					env, " It nests structs more than %d levels deep.",
15825 					BTF_MEMBER_MAX_DEPTH);
15826 			} else if (path.depth) {
15827 				char bad_name[BTF_MEMBER_PATH_LEN];
15828 
15829 				btf_member_path_str(desc_btf, &path, bad_name, sizeof(bad_name));
15830 				if (!path.bad_type) {
15831 					verbose(env, "member '%s' is a zero-length array\n",
15832 						bad_name);
15833 					member_note = bpf_diag_fmt(
15834 						env, " Its member '%s' is a zero-length array.",
15835 						bad_name);
15836 				} else {
15837 					verbose(env, "member '%s' has type %s\n", bad_name,
15838 						btf_type_str(path.bad_type));
15839 					member_note = bpf_diag_fmt(
15840 						env,
15841 						" Its member '%s' is %s, not a scalar or an arena pointer.",
15842 						bad_name, btf_type_str(path.bad_type));
15843 				}
15844 			}
15845 			bpf_diag_program_structure(
15846 				env, insn_idx, "unsupported kernel function return type",
15847 				"Call a kernel function that returns only scalars or arena pointers by value.",
15848 				"%s() returns %s %s by value.%s "
15849 				"Only kfuncs returning scalar values or arena pointers, or "
15850 				"structures composed of scalar values or arena pointers are "
15851 				"supported.",
15852 				func_name, btf_type_str(t),
15853 				btf_name_by_offset(desc_btf, t->name_off), member_note);
15854 			return -EINVAL;
15855 		}
15856 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15857 	} else if (btf_type_is_ptr(t)) {
15858 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
15859 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
15860 		if (err) {
15861 			if (err < 0)
15862 				return err;
15863 		} else if (btf_type_is_void(ptr_type)) {
15864 			/* kfunc returning 'void *' is equivalent to returning scalar */
15865 			if (!env->allow_ptr_leaks) {
15866 				verbose(env,
15867 					"%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
15868 					func_name);
15869 				return -EPERM;
15870 			}
15871 			mark_reg_unknown(env, regs, BPF_REG_0);
15872 		} else if (!__btf_type_is_struct(ptr_type)) {
15873 			if (!meta.ret_mem.found) {
15874 				__u32 sz;
15875 
15876 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
15877 					meta.ret_mem.found = true;
15878 					meta.ret_mem.size = sz;
15879 					meta.r0_rdonly = true;
15880 				}
15881 
15882 				if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
15883 					meta.r0_rdonly = false;
15884 			}
15885 			if (!meta.ret_mem.found) {
15886 				ptr_type_name = btf_name_by_offset(desc_btf,
15887 								   ptr_type->name_off);
15888 				verbose(env,
15889 					"kernel function %s returns pointer type %s %s is not supported\n",
15890 					func_name,
15891 					btf_type_str(ptr_type),
15892 					ptr_type_name);
15893 				return -EINVAL;
15894 			}
15895 
15896 			mark_reg_known_zero(env, regs, BPF_REG_0);
15897 			regs[BPF_REG_0].type = PTR_TO_MEM;
15898 			regs[BPF_REG_0].mem_size = meta.ret_mem.size;
15899 
15900 			if (meta.r0_rdonly)
15901 				regs[BPF_REG_0].type |= MEM_RDONLY;
15902 
15903 			/* Ensures we don't access the memory after a release_reference() */
15904 			if (meta.ref_obj.id) {
15905 				err = validate_ref_obj(env, &meta.ref_obj);
15906 				if (err)
15907 					return err;
15908 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
15909 			}
15910 
15911 			if (is_kfunc_rcu_protected(&meta))
15912 				regs[BPF_REG_0].type |= MEM_RCU;
15913 		} else {
15914 			enum bpf_reg_type type = PTR_TO_BTF_ID;
15915 
15916 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
15917 				type |= PTR_UNTRUSTED;
15918 			else if (is_kfunc_rcu_protected(&meta) ||
15919 				 (bpf_is_iter_next_kfunc(&meta) &&
15920 				  (get_iter_from_state(env->cur_state, &meta)
15921 					   ->type & MEM_RCU))) {
15922 				/*
15923 				 * If the iterator's constructor (the _new
15924 				 * function e.g., bpf_iter_task_new) has been
15925 				 * annotated with BPF kfunc flag
15926 				 * KF_RCU_PROTECTED and was called within a RCU
15927 				 * read-side critical section, also propagate
15928 				 * the MEM_RCU flag to the pointer returned from
15929 				 * the iterator's next function (e.g.,
15930 				 * bpf_iter_task_next).
15931 				 */
15932 				type |= MEM_RCU;
15933 			} else {
15934 				/*
15935 				 * Any PTR_TO_BTF_ID that is returned from a BPF
15936 				 * kfunc should by default be treated as
15937 				 * implicitly trusted.
15938 				 */
15939 				type |= PTR_TRUSTED;
15940 			}
15941 
15942 			mark_reg_known_zero(env, regs, BPF_REG_0);
15943 			regs[BPF_REG_0].btf = desc_btf;
15944 			regs[BPF_REG_0].type = type;
15945 			regs[BPF_REG_0].btf_id = ptr_type_id;
15946 			if (iter_next_borrows_struct(&meta) && !(type & MEM_RCU))
15947 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
15948 		}
15949 
15950 		if (is_kfunc_ret_null(&meta)) {
15951 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
15952 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
15953 			regs[BPF_REG_0].id = ++env->id_gen;
15954 		}
15955 		if (is_kfunc_acquire(&meta)) {
15956 			id = acquire_reference(env, insn_idx, 0);
15957 			if (id < 0)
15958 				return id;
15959 			regs[BPF_REG_0].id = id;
15960 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
15961 			ref_set_non_owning(env, &regs[BPF_REG_0]);
15962 		}
15963 
15964 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
15965 			regs[BPF_REG_0].id = ++env->id_gen;
15966 	} else if (btf_type_is_void(t)) {
15967 		if (meta.btf == btf_vmlinux) {
15968 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
15969 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
15970 				insn_aux->kptr_struct_meta =
15971 					btf_find_struct_meta(meta.arg_btf,
15972 							     meta.arg_btf_id);
15973 			}
15974 		}
15975 	}
15976 
15977 	if (is_kfunc_dynptr_write(&meta) ?
15978 	    dynptr_write_changes_pkt_data(meta.dynptr_write_type) :
15979 	    bpf_is_kfunc_pkt_changing(&meta))
15980 		clear_all_pkt_pointers(env);
15981 
15982 	/*
15983 	 * These kfuncs write to the head of the skb in place if what they write
15984 	 * to is linear. Like a direct write that takes bpf_unclone_prologue().
15985 	 */
15986 	if (is_kfunc_dynptr_write(&meta) &&
15987 	    dynptr_write_changes_pkt_data(meta.dynptr_write_type))
15988 		may_access_direct_pkt_data(env, NULL, BPF_WRITE);
15989 
15990 	proto_slots = kfunc_abi_slots(&desc->func_model);
15991 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
15992 		struct bpf_func_state *caller = cur_func(env);
15993 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
15994 		u16 out_stack_arg_cnt = proto_slots - MAX_BPF_FUNC_REG_ARGS;
15995 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
15996 
15997 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
15998 			caller_info->stack_arg_cnt = stack_arg_cnt;
15999 	}
16000 
16001 	/*
16002 	 * Record R0 before process_iter_next_call() snapshots the alternate
16003 	 * iterator path's diagnostic position.
16004 	 */
16005 	if (ret_nregs == 1)
16006 		bpf_diag_mod_end(env);
16007 
16008 	if (bpf_is_iter_next_kfunc(&meta)) {
16009 		err = process_iter_next_call(env, insn_idx, &meta);
16010 		if (err)
16011 			return err;
16012 	}
16013 
16014 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
16015 		env->prog->call_session_cookie = true;
16016 
16017 	if (bpf_is_throw_kfunc(insn))
16018 		return process_bpf_exit_full(env, NULL, true);
16019 
16020 	return 0;
16021 }
16022 
16023 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
16024 					 const struct bpf_reg_state *reg,
16025 					 enum bpf_reg_type type)
16026 {
16027 	bool known = tnum_is_const(reg->var_off);
16028 	s64 val = reg->var_off.value;
16029 	s64 smin = reg_smin(reg);
16030 
16031 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
16032 		verbose(env, "math between %s pointer and %lld is not allowed\n",
16033 			reg_type_str(env, type), val);
16034 		return false;
16035 	}
16036 
16037 	if (smin == S64_MIN) {
16038 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
16039 			reg_type_str(env, type));
16040 		return false;
16041 	}
16042 
16043 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
16044 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
16045 			smin, reg_type_str(env, type));
16046 		return false;
16047 	}
16048 
16049 	return true;
16050 }
16051 
16052 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
16053 				      const struct bpf_reg_state *reg,
16054 				      enum bpf_reg_type type)
16055 {
16056 	bool known = tnum_is_const(reg->var_off);
16057 	s64 val = reg->var_off.value;
16058 	s64 smin = reg_smin(reg);
16059 
16060 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
16061 		verbose(env, "%s pointer offset %lld is not allowed\n",
16062 			reg_type_str(env, type), val);
16063 		return false;
16064 	}
16065 
16066 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
16067 		verbose(env, "%s pointer offset %lld is not allowed\n",
16068 			reg_type_str(env, type), smin);
16069 		return false;
16070 	}
16071 
16072 	return true;
16073 }
16074 
16075 enum {
16076 	REASON_BOUNDS	= -1,
16077 	REASON_TYPE	= -2,
16078 	REASON_PATHS	= -3,
16079 	REASON_LIMIT	= -4,
16080 	REASON_STACK	= -5,
16081 };
16082 
16083 static int retrieve_ptr_limit(const struct bpf_verifier_env *env,
16084 			      const struct bpf_reg_state *ptr_reg,
16085 			      u32 *alu_limit, bool mask_to_left)
16086 {
16087 	u32 max = 0, ptr_limit = 0;
16088 
16089 	switch (ptr_reg->type) {
16090 	case PTR_TO_STACK:
16091 		/* Offset 0 is out-of-bounds, but acceptable start for the
16092 		 * left direction, see BPF_REG_FP. Also, unknown scalar
16093 		 * offset where we would need to deal with min/max bounds is
16094 		 * currently prohibited for unprivileged.
16095 		 */
16096 		max = env->stack_limit + mask_to_left;
16097 		ptr_limit = -ptr_reg->var_off.value;
16098 		break;
16099 	case PTR_TO_MAP_VALUE:
16100 		max = ptr_reg->map_ptr->value_size;
16101 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
16102 		break;
16103 	default:
16104 		return REASON_TYPE;
16105 	}
16106 
16107 	if (ptr_limit >= max)
16108 		return REASON_LIMIT;
16109 	*alu_limit = ptr_limit;
16110 	return 0;
16111 }
16112 
16113 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
16114 				    const struct bpf_insn *insn)
16115 {
16116 	return env->bypass_spec_v1 ||
16117 		BPF_SRC(insn->code) == BPF_K ||
16118 		cur_aux(env)->nospec;
16119 }
16120 
16121 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
16122 				       u32 alu_state, u32 alu_limit)
16123 {
16124 	/* If we arrived here from different branches with different
16125 	 * state or limits to sanitize, then this won't work.
16126 	 */
16127 	if (aux->alu_state &&
16128 	    (aux->alu_state != alu_state ||
16129 	     aux->alu_limit != alu_limit))
16130 		return REASON_PATHS;
16131 
16132 	/* Corresponding fixup done in do_misc_fixups(). */
16133 	aux->alu_state = alu_state;
16134 	aux->alu_limit = alu_limit;
16135 	return 0;
16136 }
16137 
16138 static int sanitize_val_alu(struct bpf_verifier_env *env,
16139 			    struct bpf_insn *insn)
16140 {
16141 	struct bpf_insn_aux_data *aux = cur_aux(env);
16142 
16143 	if (can_skip_alu_sanitation(env, insn))
16144 		return 0;
16145 
16146 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
16147 }
16148 
16149 static bool sanitize_needed(u8 opcode)
16150 {
16151 	return opcode == BPF_ADD || opcode == BPF_SUB;
16152 }
16153 
16154 struct bpf_sanitize_info {
16155 	struct bpf_insn_aux_data aux;
16156 	bool mask_to_left;
16157 };
16158 
16159 static int sanitize_speculative_path(struct bpf_verifier_env *env,
16160 				     const struct bpf_insn *insn,
16161 				     u32 next_idx, u32 curr_idx)
16162 {
16163 	struct bpf_verifier_state *branch;
16164 	struct bpf_reg_state *regs;
16165 
16166 	branch = push_stack(env, next_idx, curr_idx, true);
16167 	if (!IS_ERR(branch) && insn) {
16168 		regs = branch->frame[branch->curframe]->regs;
16169 		if (BPF_SRC(insn->code) == BPF_K) {
16170 			mark_reg_unknown(env, regs, insn->dst_reg);
16171 		} else if (BPF_SRC(insn->code) == BPF_X) {
16172 			mark_reg_unknown(env, regs, insn->dst_reg);
16173 			mark_reg_unknown(env, regs, insn->src_reg);
16174 		}
16175 	}
16176 	return PTR_ERR_OR_ZERO(branch);
16177 }
16178 
16179 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
16180 			    struct bpf_insn *insn,
16181 			    const struct bpf_reg_state *ptr_reg,
16182 			    const struct bpf_reg_state *off_reg,
16183 			    struct bpf_reg_state *dst_reg,
16184 			    struct bpf_sanitize_info *info,
16185 			    const bool commit_window)
16186 {
16187 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
16188 	struct bpf_verifier_state *vstate = env->cur_state;
16189 	bool off_is_imm = tnum_is_const(off_reg->var_off);
16190 	bool off_is_neg = reg_smin(off_reg) < 0;
16191 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
16192 	u8 opcode = BPF_OP(insn->code);
16193 	u32 alu_state, alu_limit;
16194 	struct bpf_reg_state tmp;
16195 	int err;
16196 
16197 	if (can_skip_alu_sanitation(env, insn))
16198 		return 0;
16199 
16200 	/* We already marked aux for masking from non-speculative
16201 	 * paths, thus we got here in the first place. We only care
16202 	 * to explore bad access from here.
16203 	 */
16204 	if (vstate->speculative)
16205 		goto do_sim;
16206 
16207 	if (!commit_window) {
16208 		if (!tnum_is_const(off_reg->var_off) &&
16209 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
16210 			return REASON_BOUNDS;
16211 
16212 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
16213 				     (opcode == BPF_SUB && !off_is_neg);
16214 	}
16215 
16216 	err = retrieve_ptr_limit(env, ptr_reg, &alu_limit, info->mask_to_left);
16217 	if (err < 0)
16218 		return err;
16219 
16220 	if (commit_window) {
16221 		/* In commit phase we narrow the masking window based on
16222 		 * the observed pointer move after the simulated operation.
16223 		 */
16224 		alu_state = info->aux.alu_state;
16225 		alu_limit = abs(info->aux.alu_limit - alu_limit);
16226 	} else {
16227 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
16228 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
16229 		alu_state |= ptr_is_dst_reg ?
16230 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
16231 
16232 		/* Limit pruning on unknown scalars to enable deep search for
16233 		 * potential masking differences from other program paths.
16234 		 */
16235 		if (!off_is_imm)
16236 			env->explore_alu_limits = true;
16237 	}
16238 
16239 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
16240 	if (err < 0)
16241 		return err;
16242 do_sim:
16243 	/* If we're in commit phase, we're done here given we already
16244 	 * pushed the truncated dst_reg into the speculative verification
16245 	 * stack.
16246 	 *
16247 	 * Also, when register is a known constant, we rewrite register-based
16248 	 * operation to immediate-based, and thus do not need masking (and as
16249 	 * a consequence, do not need to simulate the zero-truncation either).
16250 	 */
16251 	if (commit_window || off_is_imm)
16252 		return 0;
16253 
16254 	/* Simulate and find potential out-of-bounds access under
16255 	 * speculative execution from truncation as a result of
16256 	 * masking when off was not within expected range. If off
16257 	 * sits in dst, then we temporarily need to move ptr there
16258 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
16259 	 * for cases where we use K-based arithmetic in one direction
16260 	 * and truncated reg-based in the other in order to explore
16261 	 * bad access.
16262 	 */
16263 	if (!ptr_is_dst_reg) {
16264 		tmp = *dst_reg;
16265 		*dst_reg = *ptr_reg;
16266 	}
16267 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
16268 	if (err < 0)
16269 		return REASON_STACK;
16270 	if (!ptr_is_dst_reg)
16271 		*dst_reg = tmp;
16272 	return 0;
16273 }
16274 
16275 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
16276 {
16277 	struct bpf_verifier_state *vstate = env->cur_state;
16278 
16279 	/* If we simulate paths under speculation, we don't update the
16280 	 * insn as 'seen' such that when we verify unreachable paths in
16281 	 * the non-speculative domain, sanitize_dead_code() can still
16282 	 * rewrite/sanitize them.
16283 	 */
16284 	if (!vstate->speculative)
16285 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
16286 }
16287 
16288 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason)
16289 {
16290 	static const char *err = "pointer arithmetic with it prohibited for !root";
16291 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
16292 	u32 dst = insn->dst_reg, src = insn->src_reg;
16293 	struct bpf_reg_state *regs = cur_regs(env);
16294 
16295 	switch (reason) {
16296 	case REASON_BOUNDS:
16297 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
16298 			regs[src].type == SCALAR_VALUE ? src : dst, err);
16299 		break;
16300 	case REASON_TYPE:
16301 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
16302 			regs[src].type == SCALAR_VALUE ? dst : src, err);
16303 		break;
16304 	case REASON_PATHS:
16305 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
16306 			dst, op, err);
16307 		break;
16308 	case REASON_LIMIT:
16309 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
16310 			dst, op, err);
16311 		break;
16312 	case REASON_STACK:
16313 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
16314 			dst, err);
16315 		return -ENOMEM;
16316 	default:
16317 		verifier_bug(env, "unknown reason (%d)", reason);
16318 		break;
16319 	}
16320 
16321 	return -EACCES;
16322 }
16323 
16324 /* check that stack access falls within stack limits and that 'reg' doesn't
16325  * have a variable offset.
16326  *
16327  * Variable offset is prohibited for unprivileged mode for simplicity since it
16328  * requires corresponding support in Spectre masking for stack ALU.  See also
16329  * retrieve_ptr_limit().
16330  */
16331 static int check_stack_access_for_ptr_arithmetic(
16332 				struct bpf_verifier_env *env,
16333 				int regno,
16334 				const struct bpf_reg_state *reg,
16335 				int off)
16336 {
16337 	if (!tnum_is_const(reg->var_off)) {
16338 		char tn_buf[48];
16339 
16340 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
16341 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
16342 			regno, tn_buf, off);
16343 		return -EACCES;
16344 	}
16345 
16346 	if (off >= 0 || off < -(int)env->stack_limit) {
16347 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
16348 			"prohibited for !root; off=%d\n", regno, off);
16349 		return -EACCES;
16350 	}
16351 
16352 	return 0;
16353 }
16354 
16355 static int sanitize_check_bounds(struct bpf_verifier_env *env,
16356 				 const struct bpf_insn *insn,
16357 				 struct bpf_reg_state *dst_reg)
16358 {
16359 	u32 dst = insn->dst_reg;
16360 
16361 	/* For unprivileged we require that resulting offset must be in bounds
16362 	 * in order to be able to sanitize access later on.
16363 	 */
16364 	if (env->bypass_spec_v1)
16365 		return 0;
16366 
16367 	switch (dst_reg->type) {
16368 	case PTR_TO_STACK:
16369 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
16370 							  dst_reg->var_off.value))
16371 			return -EACCES;
16372 		break;
16373 	case PTR_TO_MAP_VALUE:
16374 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
16375 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
16376 				"prohibited for !root\n", dst);
16377 			return -EACCES;
16378 		}
16379 		break;
16380 	default:
16381 		return -EOPNOTSUPP;
16382 	}
16383 
16384 	return 0;
16385 }
16386 
16387 static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
16388 {
16389 	if (tnum_is_const(src_reg->var_off))
16390 		scalar_step_scale(dst_reg, src_reg->var_off.value);
16391 	else
16392 		reg_step_reset(dst_reg);
16393 }
16394 
16395 static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
16396 {
16397 	u64 amount = src_reg->var_off.value;
16398 
16399 	if (tnum_is_const(src_reg->var_off) && amount < 64)
16400 		scalar_step_scale(dst_reg, 1ULL << amount);
16401 	else
16402 		reg_step_reset(dst_reg);
16403 }
16404 
16405 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
16406  * Caller should also handle BPF_MOV case separately.
16407  * If we return -EACCES, caller may want to try again treating pointer as a
16408  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
16409  */
16410 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
16411 				   u32 ptr_regno, const struct bpf_reg_state *ptr_reg,
16412 				   const struct bpf_reg_state *off_reg)
16413 {
16414 	struct bpf_verifier_state *vstate = env->cur_state;
16415 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16416 	struct bpf_reg_state *regs = state->regs, *dst_reg;
16417 	bool known = tnum_is_const(off_reg->var_off);
16418 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
16419 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
16420 	struct bpf_sanitize_info info = {};
16421 	u8 opcode = BPF_OP(insn->code);
16422 	u32 dst = insn->dst_reg;
16423 	const char *reason;
16424 	int ret, bounds_ret;
16425 	bool to_scalar;
16426 
16427 	dst_reg = &regs[dst];
16428 	/*
16429 	 * Only += and -= keep a pointer. Any other op makes a number of it,
16430 	 * which is fine when the program may see values of pointers anyway.
16431 	 */
16432 	to_scalar = opcode != BPF_ADD && opcode != BPF_SUB && env->allow_ptr_leaks;
16433 
16434 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
16435 	    smin_val > smax_val || umin_val > umax_val) {
16436 		/* Taint dst register if offset had invalid bounds derived from
16437 		 * e.g. dead branches.
16438 		 */
16439 		__mark_reg_unknown(env, dst_reg);
16440 		return 0;
16441 	}
16442 
16443 	if (BPF_CLASS(insn->code) != BPF_ALU64 && !to_scalar) {
16444 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
16445 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
16446 			__mark_reg_unknown(env, dst_reg);
16447 			return 0;
16448 		}
16449 
16450 		verbose(env,
16451 			"R%d 32-bit pointer arithmetic prohibited\n",
16452 			dst);
16453 		reason = bpf_diag_fmt(
16454 			env, "R%d holds %s. 32-bit ALU operations on pointers discard pointer tracking, so the verifier cannot keep the result as a safe pointer.",
16455 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
16456 		bpf_diag_register_type(
16457 			env, env->insn_idx, ptr_regno, "32-bit pointer arithmetic", reason,
16458 			"Use a 64-bit ALU instruction with an allowed, bounded scalar offset.");
16459 		return -EACCES;
16460 	}
16461 
16462 	if (ptr_reg->type & PTR_MAYBE_NULL) {
16463 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
16464 			dst, reg_type_str(env, ptr_reg->type));
16465 		reason = bpf_diag_fmt(
16466 			env, "R%d may be NULL (%s). Pointer arithmetic is allowed only after the program proves the pointer is non-NULL on this path.",
16467 			ptr_regno, reg_type_str(env, ptr_reg->type));
16468 		bpf_diag_register_type(
16469 			env, env->insn_idx, ptr_regno, "pointer arithmetic before NULL check", reason,
16470 			"Make sure that a NULL check precedes any arithmetic performed on the pointer.");
16471 		return -EACCES;
16472 	}
16473 
16474 	switch (base_type(ptr_reg->type)) {
16475 	case PTR_TO_CTX:
16476 	case PTR_TO_MAP_VALUE:
16477 	case PTR_TO_MAP_KEY:
16478 	case PTR_TO_STACK:
16479 	case PTR_TO_PACKET_META:
16480 	case PTR_TO_PACKET:
16481 	case PTR_TO_TP_BUFFER:
16482 	case PTR_TO_BTF_ID:
16483 	case PTR_TO_MEM:
16484 	case PTR_TO_BUF:
16485 	case PTR_TO_FUNC:
16486 	case CONST_PTR_TO_DYNPTR:
16487 		break;
16488 	case PTR_TO_FLOW_KEYS:
16489 		if (known)
16490 			break;
16491 		fallthrough;
16492 	case CONST_PTR_TO_MAP:
16493 		/* smin_val represents the known value */
16494 		if (known && smin_val == 0 && opcode == BPF_ADD)
16495 			break;
16496 		fallthrough;
16497 	default:
16498 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
16499 			dst, reg_type_str(env, ptr_reg->type));
16500 		reason = bpf_diag_fmt(
16501 			env, "R%d holds %s. This pointer kind does not allow offset arithmetic.",
16502 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
16503 		bpf_diag_register_type(
16504 			env, env->insn_idx, ptr_regno, "pointer arithmetic is not allowed", reason,
16505 			"Do not change this pointer's offset; use it only in operations accepted for its kind.");
16506 		return -EACCES;
16507 	}
16508 
16509 	if (to_scalar) {
16510 		__mark_reg_unknown(env, dst_reg);
16511 		return 0;
16512 	}
16513 
16514 	/* For 'scalar += pointer', dst_reg inherits the complete pointer
16515 	 * register state. Individual fields may be adjusted later by pointer
16516 	 * arithmetic. Callers guarantee that below does not overwrite off_reg.
16517 	 */
16518 	if (dst_reg != ptr_reg)
16519 		*dst_reg = *ptr_reg;
16520 
16521 	/*
16522 	 * Accesses to untrusted PTR_TO_MEM are done through probe
16523 	 * instructions, hence no need to track offsets.
16524 	 */
16525 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
16526 		return 0;
16527 
16528 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) {
16529 		reason = bpf_diag_fmt(
16530 			env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].",
16531 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF);
16532 		bpf_diag_register_type(
16533 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16534 			"Clamp or bounds-check the scalar offset before applying it to the pointer.");
16535 		return -EINVAL;
16536 	}
16537 	if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) {
16538 		reason = bpf_diag_fmt(
16539 			env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.",
16540 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16541 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16542 		bpf_diag_register_type(
16543 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16544 			"Keep the base pointer within the verifier's allowed offset range before applying more arithmetic.");
16545 		return -EINVAL;
16546 	}
16547 
16548 	if (sanitize_needed(opcode)) {
16549 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
16550 				       &info, false);
16551 		if (ret < 0)
16552 			return sanitize_err(env, insn, ret);
16553 	}
16554 
16555 	/*
16556 	 * Pointer types do not carry 32-bit bounds at the moment. Blank r32
16557 	 * only after sanitize_ptr_alu() may have snapshotted dst_reg into a
16558 	 * speculative path: otherwise reg_bounds_sanity_check() might hit some
16559 	 * constraints violations.
16560 	 */
16561 	__mark_reg32_unbounded(dst_reg);
16562 
16563 	switch (opcode) {
16564 	case BPF_ADD:
16565 		/*
16566 		 * dst_reg gets the pointer type and since some positive
16567 		 * integer value was added to the pointer, give it a new 'id'
16568 		 * if it's a PTR_TO_PACKET.
16569 		 * this creates a new 'base' pointer, off_reg (variable) gets
16570 		 * added into the variable offset, and we copy the fixed offset
16571 		 * from ptr_reg.
16572 		 */
16573 		scalar_step_add(dst_reg, ptr_reg, off_reg);
16574 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
16575 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
16576 		dst_reg->raw = ptr_reg->raw;
16577 		if (reg_is_pkt_pointer(ptr_reg)) {
16578 			if (!known)
16579 				dst_reg->id = ++env->id_gen;
16580 			/*
16581 			 * Clear range for unknown addends since we can't know
16582 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
16583 			 * BEYOND_PKT_END from prior comparison as any pointer
16584 			 * arithmetic invalidates them.
16585 			 */
16586 			if (!known || dst_reg->range < 0)
16587 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16588 		}
16589 		break;
16590 	case BPF_SUB:
16591 		if (dst_reg != ptr_reg) {
16592 			/* scalar -= pointer.  Creates an unknown scalar */
16593 			verbose(env, "R%d tried to subtract pointer from scalar\n",
16594 				dst);
16595 			reason = bpf_diag_fmt(
16596 				env, "This operation subtracts pointer register R%d from scalar register R%d. "
16597 				"The verifier only tracks pointer-minus-scalar arithmetic for allowed pointer types.",
16598 				ptr_regno, dst);
16599 			bpf_diag_register_type(
16600 				env, env->insn_idx, ptr_regno, "pointer subtracted from scalar", reason,
16601 				"Keep the pointer as the base; only add or subtract bounded scalars when permitted.");
16602 			return -EACCES;
16603 		}
16604 		/* We don't allow subtraction from FP, because (according to
16605 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
16606 		 * be able to deal with it.
16607 		 */
16608 		if (ptr_reg->type == PTR_TO_STACK) {
16609 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
16610 				dst);
16611 			reason = bpf_diag_fmt(
16612 				env, "R%d is a stack pointer. The verifier does not allow BPF_SUB to move stack pointers.",
16613 				ptr_regno);
16614 			bpf_diag_register_type(
16615 				env, env->insn_idx, ptr_regno, "subtraction from stack pointer", reason,
16616 				"Use addition from R10 to form stack addresses within the tracked stack frame.");
16617 			return -EACCES;
16618 		}
16619 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
16620 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
16621 		dst_reg->raw = ptr_reg->raw;
16622 		if (reg_is_pkt_pointer(ptr_reg)) {
16623 			if (!known)
16624 				dst_reg->id = ++env->id_gen;
16625 			/*
16626 			 * Clear range if the subtrahend may be negative since
16627 			 * pkt pointer could move past its bounds. A positive
16628 			 * subtrahend moves it backwards keeping positive range
16629 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
16630 			 * prior comparison as arithmetic invalidates them.
16631 			 */
16632 			if ((!known && smin_val < 0) || dst_reg->range < 0)
16633 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16634 		}
16635 		reg_step_reset(dst_reg);
16636 		break;
16637 	case BPF_AND:
16638 	case BPF_OR:
16639 	case BPF_XOR:
16640 		/* bitwise ops on pointers are troublesome, prohibit. */
16641 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
16642 			dst, bpf_alu_string[opcode >> 4]);
16643 		reason = bpf_diag_fmt(
16644 			env, "R%d holds %s. Bitwise operator %s would destroy the pointer value the verifier is tracking.",
16645 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16646 			bpf_alu_string[opcode >> 4]);
16647 		bpf_diag_register_type(
16648 			env, env->insn_idx, ptr_regno, "bitwise operation on pointer", reason,
16649 			"Do bitwise operations on scalar values, not on pointer-valued registers.");
16650 		return -EACCES;
16651 	default:
16652 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
16653 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
16654 			dst, bpf_alu_string[opcode >> 4]);
16655 		reason = bpf_diag_fmt(
16656 			env, "R%d holds %s. Operator %s is not one of the limited pointer arithmetic operations the verifier can track.",
16657 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16658 			bpf_alu_string[opcode >> 4]);
16659 		bpf_diag_register_type(
16660 			env, env->insn_idx, ptr_regno, "invalid pointer arithmetic operator", reason,
16661 			"Use only verifier-supported addition or subtraction with a bounded scalar offset, or perform this operation on a scalar value.");
16662 		return -EACCES;
16663 	}
16664 
16665 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) {
16666 		reason = bpf_diag_fmt(
16667 			env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.",
16668 			dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16669 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16670 		bpf_diag_register_type(
16671 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16672 			"Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range.");
16673 		return -EINVAL;
16674 	}
16675 	/*
16676 	 * A packet pointer that keeps its id or range is checked against a
16677 	 * range set from the checked pointer's umax, so var_off must not tighten
16678 	 * its umax. r32 must still match var_off for reg_bounds_sanity_check().
16679 	 */
16680 	if (reg_is_pkt_pointer(dst_reg) && (known || dst_reg->range > 0))
16681 		__update_reg32_bounds(dst_reg);
16682 	else
16683 		reg_bounds_sync(dst_reg);
16684 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
16685 	if (bounds_ret == -EACCES)
16686 		return bounds_ret;
16687 	if (sanitize_needed(opcode)) {
16688 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
16689 				       &info, true);
16690 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
16691 				    && !env->cur_state->speculative
16692 				    && bounds_ret
16693 				    && !ret,
16694 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
16695 			return -EFAULT;
16696 		}
16697 		if (ret < 0)
16698 			return sanitize_err(env, insn, ret);
16699 	}
16700 
16701 	return 0;
16702 }
16703 
16704 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
16705 				 struct bpf_reg_state *src_reg)
16706 {
16707 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
16708 }
16709 
16710 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
16711 			       struct bpf_reg_state *src_reg)
16712 {
16713 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
16714 }
16715 
16716 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
16717 				 struct bpf_reg_state *src_reg)
16718 {
16719 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
16720 }
16721 
16722 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
16723 			       struct bpf_reg_state *src_reg)
16724 {
16725 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
16726 }
16727 
16728 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
16729 				 struct bpf_reg_state *src_reg)
16730 {
16731 	s32 smin = reg_s32_min(dst_reg);
16732 	s32 smax = reg_s32_max(dst_reg);
16733 	u32 umin = reg_u32_min(dst_reg);
16734 	u32 umax = reg_u32_max(dst_reg);
16735 	s32 tmp_prod[4];
16736 
16737 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
16738 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
16739 		/* Overflow possible, we know nothing */
16740 		umin = 0;
16741 		umax = U32_MAX;
16742 	}
16743 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
16744 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
16745 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
16746 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
16747 		/* Overflow possible, we know nothing */
16748 		smin = S32_MIN;
16749 		smax = S32_MAX;
16750 	} else {
16751 		smin = min_array(tmp_prod, 4);
16752 		smax = max_array(tmp_prod, 4);
16753 	}
16754 
16755 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
16756 					cnum32_from_srange(smin, smax));
16757 }
16758 
16759 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
16760 			       struct bpf_reg_state *src_reg)
16761 {
16762 	s64 smin = reg_smin(dst_reg);
16763 	s64 smax = reg_smax(dst_reg);
16764 	u64 umin = reg_umin(dst_reg);
16765 	u64 umax = reg_umax(dst_reg);
16766 	s64 tmp_prod[4];
16767 
16768 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
16769 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
16770 		/* Overflow possible, we know nothing */
16771 		umin = 0;
16772 		umax = U64_MAX;
16773 	}
16774 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
16775 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
16776 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
16777 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
16778 		/* Overflow possible, we know nothing */
16779 		smin = S64_MIN;
16780 		smax = S64_MAX;
16781 	} else {
16782 		smin = min_array(tmp_prod, 4);
16783 		smax = max_array(tmp_prod, 4);
16784 	}
16785 
16786 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
16787 					cnum64_from_srange(smin, smax));
16788 }
16789 
16790 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
16791 				  struct bpf_reg_state *src_reg)
16792 {
16793 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16794 
16795 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
16796 			 reg_u32_max(dst_reg) / src_val);
16797 
16798 	/* Reset other ranges/tnum to unbounded/unknown. */
16799 	reset_reg64_and_tnum(dst_reg);
16800 }
16801 
16802 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
16803 				struct bpf_reg_state *src_reg)
16804 {
16805 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16806 
16807 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
16808 			 div64_u64(reg_umax(dst_reg), src_val));
16809 
16810 	/* Reset other ranges/tnum to unbounded/unknown. */
16811 	reset_reg32_and_tnum(dst_reg);
16812 }
16813 
16814 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
16815 				  struct bpf_reg_state *src_reg)
16816 {
16817 	s32 smin = reg_s32_min(dst_reg);
16818 	s32 smax = reg_s32_max(dst_reg);
16819 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16820 	s32 res1, res2;
16821 
16822 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
16823 	if (smin == S32_MIN && src_val == -1) {
16824 		/*
16825 		 * If the dividend range contains more than just S32_MIN,
16826 		 * we cannot precisely track the result, so it becomes unbounded.
16827 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
16828 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
16829 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
16830 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
16831 		 */
16832 		if (smax != S32_MIN) {
16833 			smin = S32_MIN;
16834 			smax = S32_MAX;
16835 		}
16836 		goto reset;
16837 	}
16838 
16839 	res1 = smin / src_val;
16840 	res2 = smax / src_val;
16841 	smin = min(res1, res2);
16842 	smax = max(res1, res2);
16843 
16844 reset:
16845 	reg_set_srange32(dst_reg, smin, smax);
16846 	/* Reset other ranges/tnum to unbounded/unknown. */
16847 	reset_reg64_and_tnum(dst_reg);
16848 }
16849 
16850 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
16851 				struct bpf_reg_state *src_reg)
16852 {
16853 	s64 smin = reg_smin(dst_reg);
16854 	s64 smax = reg_smax(dst_reg);
16855 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16856 	s64 res1, res2;
16857 
16858 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
16859 	if (smin == S64_MIN && src_val == -1) {
16860 		/*
16861 		 * If the dividend range contains more than just S64_MIN,
16862 		 * we cannot precisely track the result, so it becomes unbounded.
16863 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
16864 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
16865 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
16866 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
16867 		 */
16868 		if (smax != S64_MIN) {
16869 			smin = S64_MIN;
16870 			smax = S64_MAX;
16871 		}
16872 		goto reset;
16873 	}
16874 
16875 	res1 = div64_s64(smin, src_val);
16876 	res2 = div64_s64(smax, src_val);
16877 	smin = min(res1, res2);
16878 	smax = max(res1, res2);
16879 
16880 reset:
16881 	reg_set_srange64(dst_reg, smin, smax);
16882 	/* Reset other ranges/tnum to unbounded/unknown. */
16883 	reset_reg32_and_tnum(dst_reg);
16884 }
16885 
16886 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
16887 				  struct bpf_reg_state *src_reg)
16888 {
16889 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16890 	u32 res_max = src_val - 1;
16891 
16892 	/*
16893 	 * If dst_umax <= res_max, the result remains unchanged.
16894 	 * e.g., [2, 5] % 10 = [2, 5].
16895 	 */
16896 	if (reg_u32_max(dst_reg) <= res_max)
16897 		return;
16898 
16899 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
16900 
16901 	/* Reset other ranges/tnum to unbounded/unknown. */
16902 	reset_reg64_and_tnum(dst_reg);
16903 }
16904 
16905 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
16906 				struct bpf_reg_state *src_reg)
16907 {
16908 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16909 	u64 res_max = src_val - 1;
16910 
16911 	/*
16912 	 * If dst_umax <= res_max, the result remains unchanged.
16913 	 * e.g., [2, 5] % 10 = [2, 5].
16914 	 */
16915 	if (reg_umax(dst_reg) <= res_max)
16916 		return;
16917 
16918 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
16919 
16920 	/* Reset other ranges/tnum to unbounded/unknown. */
16921 	reset_reg32_and_tnum(dst_reg);
16922 }
16923 
16924 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
16925 				  struct bpf_reg_state *src_reg)
16926 {
16927 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16928 
16929 	/*
16930 	 * Safe absolute value calculation:
16931 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
16932 	 * Here use unsigned integer to avoid overflow.
16933 	 */
16934 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
16935 
16936 	/*
16937 	 * Calculate the maximum possible absolute value of the result.
16938 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
16939 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
16940 	 */
16941 	s32 res_max_abs = src_abs - 1;
16942 
16943 	/*
16944 	 * If the dividend is already within the result range,
16945 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16946 	 */
16947 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
16948 		return;
16949 
16950 	/* General case: result has the same sign as the dividend. */
16951 	if (reg_s32_min(dst_reg) >= 0) {
16952 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
16953 	} else if (reg_s32_max(dst_reg) <= 0) {
16954 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
16955 	} else {
16956 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
16957 	}
16958 
16959 	/* Reset other ranges/tnum to unbounded/unknown. */
16960 	reset_reg64_and_tnum(dst_reg);
16961 }
16962 
16963 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
16964 				struct bpf_reg_state *src_reg)
16965 {
16966 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16967 
16968 	/*
16969 	 * Safe absolute value calculation:
16970 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
16971 	 * Here use unsigned integer to avoid overflow.
16972 	 */
16973 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
16974 
16975 	/*
16976 	 * Calculate the maximum possible absolute value of the result.
16977 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
16978 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
16979 	 */
16980 	s64 res_max_abs = src_abs - 1;
16981 
16982 	/*
16983 	 * If the dividend is already within the result range,
16984 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16985 	 */
16986 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
16987 		return;
16988 
16989 	/* General case: result has the same sign as the dividend. */
16990 	if (reg_smin(dst_reg) >= 0) {
16991 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
16992 	} else if (reg_smax(dst_reg) <= 0) {
16993 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
16994 	} else {
16995 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
16996 	}
16997 
16998 	/* Reset other ranges/tnum to unbounded/unknown. */
16999 	reset_reg32_and_tnum(dst_reg);
17000 }
17001 
17002 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
17003 				 struct bpf_reg_state *src_reg)
17004 {
17005 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
17006 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
17007 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
17008 	u32 umax_val = reg_u32_max(src_reg);
17009 
17010 	if (src_known && dst_known) {
17011 		__mark_reg32_known(dst_reg, var32_off.value);
17012 		return;
17013 	}
17014 
17015 	/* We get our minimum from the var_off, since that's inherently
17016 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
17017 	 */
17018 	reg_set_urange32(dst_reg,
17019 			 var32_off.value,
17020 			 min(reg_u32_max(dst_reg), umax_val));
17021 }
17022 
17023 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
17024 			       struct bpf_reg_state *src_reg)
17025 {
17026 	bool src_known = tnum_is_const(src_reg->var_off);
17027 	bool dst_known = tnum_is_const(dst_reg->var_off);
17028 	u64 umax_val = reg_umax(src_reg);
17029 
17030 	if (src_known && dst_known) {
17031 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
17032 		return;
17033 	}
17034 
17035 	/* We get our minimum from the var_off, since that's inherently
17036 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
17037 	 */
17038 	reg_set_urange64(dst_reg,
17039 			 dst_reg->var_off.value,
17040 			 min(reg_umax(dst_reg), umax_val));
17041 
17042 	/* We may learn something more from the var_off */
17043 	__update_reg_bounds(dst_reg);
17044 }
17045 
17046 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
17047 				struct bpf_reg_state *src_reg)
17048 {
17049 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
17050 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
17051 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
17052 	u32 umin_val = reg_u32_min(src_reg);
17053 
17054 	if (src_known && dst_known) {
17055 		__mark_reg32_known(dst_reg, var32_off.value);
17056 		return;
17057 	}
17058 
17059 	/* We get our maximum from the var_off, and our minimum is the
17060 	 * maximum of the operands' minima
17061 	 */
17062 	reg_set_urange32(dst_reg,
17063 			 max(reg_u32_min(dst_reg), umin_val),
17064 			 var32_off.value | var32_off.mask);
17065 }
17066 
17067 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
17068 			      struct bpf_reg_state *src_reg)
17069 {
17070 	bool src_known = tnum_is_const(src_reg->var_off);
17071 	bool dst_known = tnum_is_const(dst_reg->var_off);
17072 	u64 umin_val = reg_umin(src_reg);
17073 
17074 	if (src_known && dst_known) {
17075 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
17076 		return;
17077 	}
17078 
17079 	/* We get our maximum from the var_off, and our minimum is the
17080 	 * maximum of the operands' minima
17081 	 */
17082 	reg_set_urange64(dst_reg,
17083 			 max(reg_umin(dst_reg), umin_val),
17084 			 dst_reg->var_off.value | dst_reg->var_off.mask);
17085 
17086 	/* We may learn something more from the var_off */
17087 	__update_reg_bounds(dst_reg);
17088 }
17089 
17090 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
17091 				 struct bpf_reg_state *src_reg)
17092 {
17093 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
17094 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
17095 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
17096 
17097 	if (src_known && dst_known) {
17098 		__mark_reg32_known(dst_reg, var32_off.value);
17099 		return;
17100 	}
17101 
17102 	/* We get both minimum and maximum from the var32_off. */
17103 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
17104 }
17105 
17106 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
17107 			       struct bpf_reg_state *src_reg)
17108 {
17109 	bool src_known = tnum_is_const(src_reg->var_off);
17110 	bool dst_known = tnum_is_const(dst_reg->var_off);
17111 
17112 	if (src_known && dst_known) {
17113 		/* dst_reg->var_off.value has been updated earlier */
17114 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
17115 		return;
17116 	}
17117 
17118 	/* We get both minimum and maximum from the var_off. */
17119 	reg_set_urange64(dst_reg,
17120 			 dst_reg->var_off.value,
17121 			 dst_reg->var_off.value | dst_reg->var_off.mask);
17122 }
17123 
17124 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
17125 				   u64 umin_val, u64 umax_val)
17126 {
17127 	/* If we might shift our top bit out, then we know nothing */
17128 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
17129 		reg_set_urange32(dst_reg, 0, U32_MAX);
17130 	else
17131 		/* We lose all sign bit information (except what we can pick
17132 		 * up from var_off)
17133 		 */
17134 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
17135 				 reg_u32_max(dst_reg) << umax_val);
17136 }
17137 
17138 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
17139 				 struct bpf_reg_state *src_reg)
17140 {
17141 	u32 umax_val = reg_u32_max(src_reg);
17142 	u32 umin_val = reg_u32_min(src_reg);
17143 	/* u32 alu operation will zext upper bits */
17144 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
17145 
17146 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
17147 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
17148 	/* Not required but being careful mark reg64 bounds as unknown so
17149 	 * that we are forced to pick them up from tnum and zext later and
17150 	 * if some path skips this step we are still safe.
17151 	 */
17152 	__mark_reg64_unbounded(dst_reg);
17153 	__update_reg32_bounds(dst_reg);
17154 }
17155 
17156 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
17157 				   u64 umin_val, u64 umax_val)
17158 {
17159 	struct cnum64 u, s;
17160 
17161 	/* Special case <<32 because it is a common compiler pattern to sign
17162 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
17163 	 * because s32 bounds don't flip sign when shifting to the left by
17164 	 * 32bits.
17165 	 */
17166 	if (umin_val == 32 && umax_val == 32)
17167 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
17168 				       (s64)reg_s32_max(dst_reg) << 32);
17169 	else
17170 		s = CNUM64_UNBOUNDED;
17171 
17172 	/* If we might shift our top bit out, then we know nothing */
17173 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
17174 		u = CNUM64_UNBOUNDED;
17175 	else
17176 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
17177 				       reg_umax(dst_reg) << umax_val);
17178 
17179 	dst_reg->r64 = cnum64_intersect(u, s);
17180 }
17181 
17182 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
17183 			       struct bpf_reg_state *src_reg)
17184 {
17185 	u64 umax_val = reg_umax(src_reg);
17186 	u64 umin_val = reg_umin(src_reg);
17187 
17188 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
17189 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
17190 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
17191 
17192 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
17193 	/* We may learn something more from the var_off */
17194 	__update_reg_bounds(dst_reg);
17195 }
17196 
17197 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
17198 				 struct bpf_reg_state *src_reg)
17199 {
17200 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
17201 	u32 umax_val = reg_u32_max(src_reg);
17202 	u32 umin_val = reg_u32_min(src_reg);
17203 
17204 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
17205 	 * be negative, then either:
17206 	 * 1) src_reg might be zero, so the sign bit of the result is
17207 	 *    unknown, so we lose our signed bounds
17208 	 * 2) it's known negative, thus the unsigned bounds capture the
17209 	 *    signed bounds
17210 	 * 3) the signed bounds cross zero, so they tell us nothing
17211 	 *    about the result
17212 	 * If the value in dst_reg is known nonnegative, then again the
17213 	 * unsigned bounds capture the signed bounds.
17214 	 * Thus, in all cases it suffices to blow away our signed bounds
17215 	 * and rely on inferring new ones from the unsigned bounds and
17216 	 * var_off of the result.
17217 	 */
17218 
17219 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
17220 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
17221 			 reg_u32_max(dst_reg) >> umin_val);
17222 
17223 	__mark_reg64_unbounded(dst_reg);
17224 	__update_reg32_bounds(dst_reg);
17225 }
17226 
17227 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
17228 			       struct bpf_reg_state *src_reg)
17229 {
17230 	u64 umax_val = reg_umax(src_reg);
17231 	u64 umin_val = reg_umin(src_reg);
17232 
17233 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
17234 	 * be negative, then either:
17235 	 * 1) src_reg might be zero, so the sign bit of the result is
17236 	 *    unknown, so we lose our signed bounds
17237 	 * 2) it's known negative, thus the unsigned bounds capture the
17238 	 *    signed bounds
17239 	 * 3) the signed bounds cross zero, so they tell us nothing
17240 	 *    about the result
17241 	 * If the value in dst_reg is known nonnegative, then again the
17242 	 * unsigned bounds capture the signed bounds.
17243 	 * Thus, in all cases it suffices to blow away our signed bounds
17244 	 * and rely on inferring new ones from the unsigned bounds and
17245 	 * var_off of the result.
17246 	 */
17247 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
17248 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
17249 			 reg_umax(dst_reg) >> umin_val);
17250 
17251 	/* Its not easy to operate on alu32 bounds here because it depends
17252 	 * on bits being shifted in. Take easy way out and mark unbounded
17253 	 * so we can recalculate later from tnum.
17254 	 */
17255 	__mark_reg32_unbounded(dst_reg);
17256 	__update_reg_bounds(dst_reg);
17257 }
17258 
17259 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
17260 				  struct bpf_reg_state *src_reg)
17261 {
17262 	u64 umin_val = reg_u32_min(src_reg);
17263 
17264 	/* Upon reaching here, src_known is true and
17265 	 * umax_val is equal to umin_val.
17266 	 * Blow away the dst_reg umin_value/umax_value and rely on
17267 	 * dst_reg var_off to refine the result.
17268 	 */
17269 	reg_set_srange32(dst_reg,
17270 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
17271 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
17272 
17273 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
17274 
17275 	__mark_reg64_unbounded(dst_reg);
17276 	__update_reg32_bounds(dst_reg);
17277 }
17278 
17279 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
17280 				struct bpf_reg_state *src_reg)
17281 {
17282 	u64 umin_val = reg_umin(src_reg);
17283 
17284 	/* Upon reaching here, src_known is true and umax_val is equal
17285 	 * to umin_val.
17286 	 */
17287 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
17288 			 reg_smax(dst_reg) >> umin_val);
17289 
17290 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
17291 
17292 	/* Its not easy to operate on alu32 bounds here because it depends
17293 	 * on bits being shifted in from upper 32-bits. Take easy way out
17294 	 * and mark unbounded so we can recalculate later from tnum.
17295 	 */
17296 	__mark_reg32_unbounded(dst_reg);
17297 	__update_reg_bounds(dst_reg);
17298 }
17299 
17300 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
17301 {
17302 	/*
17303 	 * Byte swap operation - update var_off using tnum_bswap.
17304 	 * Three cases:
17305 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
17306 	 *    unconditional swap
17307 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
17308 	 *    swap on big-endian, truncation or no-op on little-endian
17309 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
17310 	 *    swap on little-endian, truncation or no-op on big-endian
17311 	 */
17312 
17313 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
17314 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
17315 	bool is_big_endian;
17316 #ifdef CONFIG_CPU_BIG_ENDIAN
17317 	is_big_endian = true;
17318 #else
17319 	is_big_endian = false;
17320 #endif
17321 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
17322 	bool need_bswap = alu64 || (to_le == is_big_endian);
17323 
17324 	/*
17325 	 * If the register is mutated, manually reset its scalar ID to break
17326 	 * any existing ties and avoid incorrect bounds propagation.
17327 	 */
17328 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
17329 		clear_scalar_id(dst_reg);
17330 
17331 	if (need_bswap) {
17332 		if (insn->imm == 16)
17333 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
17334 		else if (insn->imm == 32)
17335 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
17336 		else if (insn->imm == 64)
17337 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
17338 		/*
17339 		 * Byteswap scrambles the range, so we must reset bounds.
17340 		 * Bounds will be re-derived from the new tnum later.
17341 		 */
17342 		__mark_reg_unbounded(dst_reg);
17343 		reg_step_reset(dst_reg);
17344 	}
17345 	/* For bswap16/32, truncate dst register to match the swapped size */
17346 	if (insn->imm == 16 || insn->imm == 32)
17347 		coerce_reg_to_size(dst_reg, insn->imm / 8);
17348 }
17349 
17350 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
17351 					     const struct bpf_reg_state *src_reg)
17352 {
17353 	bool src_is_const = false;
17354 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
17355 
17356 	if (insn_bitness == 32) {
17357 		if (tnum_subreg_is_const(src_reg->var_off)
17358 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
17359 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
17360 			src_is_const = true;
17361 	} else {
17362 		if (tnum_is_const(src_reg->var_off)
17363 		    && reg_smin(src_reg) == reg_smax(src_reg)
17364 		    && reg_umin(src_reg) == reg_umax(src_reg))
17365 			src_is_const = true;
17366 	}
17367 
17368 	switch (BPF_OP(insn->code)) {
17369 	case BPF_ADD:
17370 	case BPF_SUB:
17371 	case BPF_NEG:
17372 	case BPF_AND:
17373 	case BPF_XOR:
17374 	case BPF_OR:
17375 	case BPF_MUL:
17376 	case BPF_END:
17377 		return true;
17378 
17379 	/*
17380 	 * Division and modulo operators range is only safe to compute when the
17381 	 * divisor is a constant.
17382 	 */
17383 	case BPF_DIV:
17384 	case BPF_MOD:
17385 		return src_is_const;
17386 
17387 	/* Shift operators range is only computable if shift dimension operand
17388 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
17389 	 * includes shifts by a negative number.
17390 	 */
17391 	case BPF_LSH:
17392 	case BPF_RSH:
17393 	case BPF_ARSH:
17394 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
17395 	default:
17396 		return false;
17397 	}
17398 }
17399 
17400 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
17401 				      struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg);
17402 
17403 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
17404 			      struct bpf_reg_state *dst_reg, const struct bpf_reg_state *src_reg)
17405 {
17406 	struct bpf_verifier_state *branch;
17407 	struct bpf_reg_state *reg;
17408 	bool alu32;
17409 
17410 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
17411 		alu32 = false;
17412 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
17413 		alu32 = true;
17414 	else
17415 		return 0;
17416 
17417 	branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
17418 	if (IS_ERR(branch))
17419 		return PTR_ERR(branch);
17420 
17421 	reg = &branch->frame[branch->curframe]->regs[insn->dst_reg];
17422 	if (alu32) {
17423 		__mark_reg32_known(reg, 0);
17424 		__mark_reg32_known(dst_reg, -1ull);
17425 	} else {
17426 		__mark_reg_known(reg, 0);
17427 		__mark_reg_known(dst_reg, -1ull);
17428 	}
17429 	/*
17430 	 * The insn is done with in the branch too, and what gets to the next insn is a state
17431 	 * like any other. At this insn the branch is a part of the state that is looked at:
17432 	 * it must not be compared with it.
17433 	 */
17434 	clear_scalar_id(reg);
17435 	return adjust_scalar_min_max_vals(env, insn, reg, *src_reg);
17436 }
17437 
17438 /* WARNING: This function does calculations on 64-bit values, but the actual
17439  * execution may occur on 32-bit values. Therefore, things like bitshifts
17440  * need extra checks in the 32-bit case.
17441  */
17442 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
17443 				      struct bpf_insn *insn,
17444 				      struct bpf_reg_state *dst_reg,
17445 				      struct bpf_reg_state src_reg)
17446 {
17447 	u8 opcode = BPF_OP(insn->code);
17448 	s16 off = insn->off;
17449 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
17450 	int ret;
17451 
17452 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
17453 		__mark_reg_unknown(env, dst_reg);
17454 		return 0;
17455 	}
17456 
17457 	if (sanitize_needed(opcode)) {
17458 		ret = sanitize_val_alu(env, insn);
17459 		if (ret < 0)
17460 			return sanitize_err(env, insn, ret);
17461 	}
17462 
17463 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
17464 	 * There are two classes of instructions: The first class we track both
17465 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
17466 	 * greatest amount of precision when alu operations are mixed with jmp32
17467 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
17468 	 * and BPF_OR. This is possible because these ops have fairly easy to
17469 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
17470 	 * See alu32 verifier tests for examples. The second class of
17471 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
17472 	 * with regards to tracking sign/unsigned bounds because the bits may
17473 	 * cross subreg boundaries in the alu64 case. When this happens we mark
17474 	 * the reg unbounded in the subreg bound space and use the resulting
17475 	 * tnum to calculate an approximation of the sign/unsigned bounds.
17476 	 */
17477 	switch (opcode) {
17478 	case BPF_ADD:
17479 		scalar_step_add(dst_reg, dst_reg, &src_reg);
17480 		scalar32_min_max_add(dst_reg, &src_reg);
17481 		scalar_min_max_add(dst_reg, &src_reg);
17482 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
17483 		break;
17484 	case BPF_SUB:
17485 		scalar32_min_max_sub(dst_reg, &src_reg);
17486 		scalar_min_max_sub(dst_reg, &src_reg);
17487 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
17488 		reg_step_reset(dst_reg);
17489 		break;
17490 	case BPF_NEG:
17491 		env->fake_reg[0] = *dst_reg;
17492 		__mark_reg_known(dst_reg, 0);
17493 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
17494 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
17495 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
17496 		reg_step_reset(dst_reg);
17497 		break;
17498 	case BPF_MUL:
17499 		scalar_step_mul(dst_reg, &src_reg);
17500 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
17501 		scalar32_min_max_mul(dst_reg, &src_reg);
17502 		scalar_min_max_mul(dst_reg, &src_reg);
17503 		break;
17504 	case BPF_DIV:
17505 		/* BPF div specification: x / 0 = 0 */
17506 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
17507 			___mark_reg_known(dst_reg, 0);
17508 			break;
17509 		}
17510 		if (alu32)
17511 			if (off == 1)
17512 				scalar32_min_max_sdiv(dst_reg, &src_reg);
17513 			else
17514 				scalar32_min_max_udiv(dst_reg, &src_reg);
17515 		else
17516 			if (off == 1)
17517 				scalar_min_max_sdiv(dst_reg, &src_reg);
17518 			else
17519 				scalar_min_max_udiv(dst_reg, &src_reg);
17520 		reg_step_reset(dst_reg);
17521 		break;
17522 	case BPF_MOD:
17523 		/* BPF mod specification: x % 0 = x */
17524 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
17525 			break;
17526 		if (alu32)
17527 			if (off == 1)
17528 				scalar32_min_max_smod(dst_reg, &src_reg);
17529 			else
17530 				scalar32_min_max_umod(dst_reg, &src_reg);
17531 		else
17532 			if (off == 1)
17533 				scalar_min_max_smod(dst_reg, &src_reg);
17534 			else
17535 				scalar_min_max_umod(dst_reg, &src_reg);
17536 		reg_step_reset(dst_reg);
17537 		break;
17538 	case BPF_AND:
17539 		if (tnum_is_const(src_reg.var_off)) {
17540 			ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg);
17541 			if (ret)
17542 				return ret;
17543 		}
17544 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
17545 		scalar32_min_max_and(dst_reg, &src_reg);
17546 		scalar_min_max_and(dst_reg, &src_reg);
17547 		reg_step_reset(dst_reg);
17548 		break;
17549 	case BPF_OR:
17550 		if (tnum_is_const(src_reg.var_off)) {
17551 			ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg);
17552 			if (ret)
17553 				return ret;
17554 		}
17555 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
17556 		scalar32_min_max_or(dst_reg, &src_reg);
17557 		scalar_min_max_or(dst_reg, &src_reg);
17558 		reg_step_reset(dst_reg);
17559 		break;
17560 	case BPF_XOR:
17561 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
17562 		scalar32_min_max_xor(dst_reg, &src_reg);
17563 		scalar_min_max_xor(dst_reg, &src_reg);
17564 		reg_step_reset(dst_reg);
17565 		break;
17566 	case BPF_LSH:
17567 		scalar_step_lsh(dst_reg, &src_reg);
17568 		if (alu32)
17569 			scalar32_min_max_lsh(dst_reg, &src_reg);
17570 		else
17571 			scalar_min_max_lsh(dst_reg, &src_reg);
17572 		break;
17573 	case BPF_RSH:
17574 		if (alu32)
17575 			scalar32_min_max_rsh(dst_reg, &src_reg);
17576 		else
17577 			scalar_min_max_rsh(dst_reg, &src_reg);
17578 		reg_step_reset(dst_reg);
17579 		break;
17580 	case BPF_ARSH:
17581 		if (alu32)
17582 			scalar32_min_max_arsh(dst_reg, &src_reg);
17583 		else
17584 			scalar_min_max_arsh(dst_reg, &src_reg);
17585 		reg_step_reset(dst_reg);
17586 		break;
17587 	case BPF_END:
17588 		scalar_byte_swap(dst_reg, insn);
17589 		reg_step_reset(dst_reg);
17590 		break;
17591 	default:
17592 		break;
17593 	}
17594 
17595 	/*
17596 	 * ALU32 ops are zero extended into 64bit register.
17597 	 *
17598 	 * BPF_END is already handled inside the helper (truncation),
17599 	 * so skip zext here to avoid unexpected zero extension.
17600 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
17601 	 * This is a 64bit byte swap operation with alu32==true,
17602 	 * but we should not zero extend the result.
17603 	 */
17604 	if (alu32 && opcode != BPF_END)
17605 		zext_32_to_64(dst_reg);
17606 	reg_bounds_sync(dst_reg);
17607 	return 0;
17608 }
17609 
17610 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
17611  * and var_off.
17612  */
17613 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
17614 				   struct bpf_insn *insn)
17615 {
17616 	struct bpf_verifier_state *vstate = env->cur_state;
17617 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
17618 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
17619 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
17620 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
17621 	struct bpf_insn_aux_data *aux = cur_aux(env);
17622 	u8 opcode = BPF_OP(insn->code);
17623 	int err;
17624 
17625 	dst_reg = &regs[insn->dst_reg];
17626 	if (BPF_SRC(insn->code) == BPF_X)
17627 		src_reg = &regs[insn->src_reg];
17628 	else
17629 		src_reg = NULL;
17630 
17631 	/* Case where at least one operand is an arena. */
17632 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
17633 
17634 		if (dst_reg->type != PTR_TO_ARENA)
17635 			*dst_reg = *src_reg;
17636 
17637 		if (BPF_CLASS(insn->code) == BPF_ALU64) {
17638 			/*
17639 			 * Only arena pointers set needs_zext, but doing so
17640 			 * modifies the instruction at fixup time to an ALU32
17641 			 * and makes it unsuitable for 64-bit scalar args. We
17642 			 * prevent zext from being set if the instruction has
17643 			 * been previously called with non-arena registers.
17644 			 */
17645 			if (aux->prevent_zext) {
17646 				verbose(env, "same insn cannot be used with and without arena pointer\n");
17647 				return -EINVAL;
17648 			}
17649 
17650 			/*
17651 			 * 32-bit operations zero upper bits automatically.
17652 			 * 64-bit operations need to be converted to 32.
17653 			 */
17654 			aux->needs_zext = true;
17655 			aux->zext_dst = true;
17656 		}
17657 
17658 		/* Any arithmetic operations are allowed on arena pointers */
17659 		return 0;
17660 	}
17661 
17662 	/* Prevent the instruction from being used with arena pointers (see above). */
17663 	if (env->prog->aux->arena && BPF_CLASS(insn->code) == BPF_ALU64) {
17664 		if (aux->needs_zext) {
17665 			verbose(env, "same insn cannot be used with and without arena pointer\n");
17666 			return -EINVAL;
17667 		}
17668 
17669 		aux->prevent_zext = true;
17670 	}
17671 
17672 	if (dst_reg->type != SCALAR_VALUE)
17673 		ptr_reg = dst_reg;
17674 
17675 	if (BPF_SRC(insn->code) == BPF_X) {
17676 		if (src_reg->type != SCALAR_VALUE) {
17677 			if (dst_reg->type != SCALAR_VALUE) {
17678 				/* Combining two pointers by any ALU op yields
17679 				 * an arbitrary scalar. Disallow all math except
17680 				 * pointer subtraction
17681 				 */
17682 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
17683 					mark_reg_unknown(env, regs, insn->dst_reg);
17684 					return 0;
17685 				}
17686 				verbose(env, "R%d pointer %s pointer prohibited\n",
17687 					insn->dst_reg,
17688 					bpf_alu_string[opcode >> 4]);
17689 				return -EACCES;
17690 			} else {
17691 				/* scalar += pointer
17692 				 * This is legal, but we have to reverse our
17693 				 * src/dest handling in computing the range
17694 				 */
17695 				err = mark_chain_precision(env, insn->dst_reg);
17696 				if (err)
17697 					return err;
17698 				off_reg = *dst_reg;
17699 				return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg,
17700 							       &off_reg);
17701 			}
17702 		} else if (ptr_reg) {
17703 			/* pointer += scalar */
17704 			err = mark_chain_precision(env, insn->src_reg);
17705 			if (err)
17706 				return err;
17707 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg);
17708 		} else if (dst_reg->precise) {
17709 			/* if dst_reg is precise, src_reg should be precise as well */
17710 			err = mark_chain_precision(env, insn->src_reg);
17711 			if (err)
17712 				return err;
17713 		}
17714 	} else {
17715 		/* Pretend the src is a reg with a known value, since we only
17716 		 * need to be able to read from this state.
17717 		 */
17718 		off_reg.type = SCALAR_VALUE;
17719 		__mark_reg_known(&off_reg, insn->imm);
17720 		src_reg = &off_reg;
17721 		if (ptr_reg) /* pointer += K */
17722 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, ptr_reg, src_reg);
17723 	}
17724 
17725 	/* Got here implies adding two SCALAR_VALUEs */
17726 	if (WARN_ON_ONCE(ptr_reg)) {
17727 		print_verifier_state(env, vstate, vstate->curframe, true);
17728 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
17729 		return -EFAULT;
17730 	}
17731 	if (WARN_ON(!src_reg)) {
17732 		print_verifier_state(env, vstate, vstate->curframe, true);
17733 		verbose(env, "verifier internal error: no src_reg\n");
17734 		return -EFAULT;
17735 	}
17736 	/*
17737 	 * For alu32 linked register tracking, we need to check dst_reg's
17738 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
17739 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
17740 	 */
17741 	u64 dst_umax = reg_umax(dst_reg);
17742 
17743 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
17744 	if (err)
17745 		return err;
17746 	/*
17747 	 * Compilers can generate the code
17748 	 * r1 = r2
17749 	 * r1 += 0x1
17750 	 * if r2 < 1000 goto ...
17751 	 * use r1 in memory access
17752 	 * So remember constant delta between r2 and r1 and update r1 after
17753 	 * 'if' condition.
17754 	 */
17755 	if (env->bpf_capable &&
17756 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
17757 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
17758 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
17759 		u64 val = reg_const_value(src_reg, alu32);
17760 		s32 off;
17761 
17762 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
17763 			goto clear_id;
17764 
17765 		if (alu32 && (dst_umax > U32_MAX))
17766 			goto clear_id;
17767 
17768 		off = (s32)val;
17769 
17770 		if (BPF_OP(insn->code) == BPF_SUB) {
17771 			/* Negating S32_MIN would overflow */
17772 			if (off == S32_MIN)
17773 				goto clear_id;
17774 			off = -off;
17775 		}
17776 
17777 		if (dst_reg->id & BPF_ADD_CONST) {
17778 			/*
17779 			 * If the register already went through rX += val
17780 			 * we cannot accumulate another val into rx->off.
17781 			 */
17782 clear_id:
17783 			clear_scalar_id(dst_reg);
17784 		} else {
17785 			if (alu32)
17786 				dst_reg->id |= BPF_ADD_CONST32;
17787 			else
17788 				dst_reg->id |= BPF_ADD_CONST64;
17789 			dst_reg->delta = off;
17790 		}
17791 	} else {
17792 		/*
17793 		 * Make sure ID is cleared otherwise dst_reg min/max could be
17794 		 * incorrectly propagated into other registers by sync_linked_regs()
17795 		 */
17796 		clear_scalar_id(dst_reg);
17797 	}
17798 	return 0;
17799 }
17800 
17801 /*
17802  * Many checks done by this function are quite conservative.
17803  * This is because main verification pass does not maintain
17804  * enough information to track object identities for some
17805  * of the interesting types, e.g. PTR_TO_MEM.
17806  */
17807 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
17808 			    const struct bpf_reg_state *reg_b)
17809 {
17810 	if (reg_a == reg_b)
17811 		return true;
17812 	/* Require matching flags and base types. */
17813 	if (reg_a->type != reg_b->type)
17814 		return false;
17815 	/* NULL can't be compared to some base+offset pointer. */
17816 	if (type_may_be_null(reg_a->type))
17817 		return false;
17818 
17819 	switch (base_type(reg_a->type)) {
17820 	case PTR_TO_STACK:
17821 		return reg_a->frameno == reg_b->frameno;
17822 	case PTR_TO_MAP_VALUE:
17823 		if (reg_a->map_ptr != reg_b->map_ptr || reg_a->map_uid != reg_b->map_uid)
17824 			return false;
17825 		if (reg_a->id && reg_a->id == reg_b->id)
17826 			return true;
17827 		/*
17828 		 * A plain single-element array has one stable value address,
17829 		 * but not when BPF_F_INNER_MAP is set, see arraymap.c:array_map_meta_equal().
17830 		 */
17831 		if (reg_a->map_ptr->map_type == BPF_MAP_TYPE_ARRAY &&
17832 		    reg_a->map_ptr->max_entries == 1 &&
17833 		    !(reg_a->map_ptr->map_flags & BPF_F_INNER_MAP))
17834 			return true;
17835 		/*
17836 		 * The rules above can be simplified / relaxed if:
17837 		 * - fresh IDs would always be assigned for map-value lookups;
17838 		 * - direct map value loads would always have and ID of zero.
17839 		 */
17840 		return false;
17841 	case PTR_TO_MEM:
17842 	case PTR_TO_BUF:
17843 		return reg_a->id && reg_a->id == reg_b->id;
17844 
17845 	default:
17846 		return false;
17847 	}
17848 }
17849 
17850 /*
17851  * 'range - smax' bytes from a packet pointer are in the packet. reg_bounds_sync() can make smax
17852  * smaller than @smax: with a step of 8, or with 3 zero bits in var_off, 58 becomes 56. Make the
17853  * range smaller by the same number, so that the number of bytes does not grow. umax is not
17854  * sufficient: it is U64_MAX when the offset can be negative.
17855  */
17856 void bpf_trim_pkt_range(struct bpf_reg_state *reg, s64 smax)
17857 {
17858 	if (type_is_pkt_pointer(reg->type) && reg->range > 0)
17859 		reg->range = max_t(s64, reg->range - (smax - reg_smax(reg)), 0);
17860 }
17861 
17862 int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
17863 		      struct cnum64 r64, struct cnum32 r32, u16 base, u16 step)
17864 {
17865 	reg->r64 = r64;
17866 	reg->r32 = r32;
17867 	reg->step = step;
17868 	reg->base = base;
17869 	reg->var_off = tnum_unknown;
17870 	reg_bounds_sync(reg); /* this should infer the tnum alignment */
17871 	bpf_trim_pkt_range(reg, cnum64_smax(r64));
17872 	return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
17873 }
17874 
17875 /*
17876  * Checks if pointer and packet metadata matches between two registers.
17877  * For use with bpf_reg_union().
17878  */
17879 bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b)
17880 {
17881 	if (a->type != b->type)
17882 		return false;
17883 	if (a->type == SCALAR_VALUE)
17884 		return true;
17885 	return !memcmp(a, b, offsetof(struct bpf_reg_state, var_off)) &&
17886 	       a->id == b->id && a->parent_id == b->parent_id && a->map_uid == b->map_uid;
17887 }
17888 
17889 /*
17890  * Extends acc's scalar range to include src's scalar range.
17891  * Caller must ensure that other kinds of metadata is compatible.
17892  * Caller must clear acc's scalar ID.
17893  */
17894 int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
17895 		  const struct bpf_reg_state *src)
17896 {
17897 	u16 base, step;
17898 
17899 	if (!bpf_reg_union_compatible(acc, src)) {
17900 		verifier_bug(env, "union of incompatible registers");
17901 		return -EFAULT;
17902 	}
17903 	acc->r64 = cnum64_union(acc->r64, src->r64);
17904 	acc->r32 = cnum32_union(acc->r32, src->r32);
17905 	acc->var_off = tnum_union(acc->var_off, src->var_off);
17906 
17907 	/* Retain a common congruence if the bases agree modulo the gcd. */
17908 	step = gcd(acc->step, src->step);
17909 	base = acc->base % step;
17910 	if (base != src->base % step) {
17911 		reg_step_reset(acc);
17912 	} else {
17913 		acc->base = base;
17914 		acc->step = step;
17915 	}
17916 	reg_bounds_sync(acc);
17917 	return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
17918 }
17919 
17920 /* check validity of 32-bit and 64-bit arithmetic operations */
17921 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17922 {
17923 	struct bpf_reg_state *regs = cur_regs(env);
17924 	u8 opcode = BPF_OP(insn->code);
17925 	int err;
17926 
17927 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
17928 
17929 	if (opcode == BPF_END || opcode == BPF_NEG) {
17930 		/* check src operand */
17931 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17932 		if (err)
17933 			return err;
17934 
17935 		if (is_pointer_value(env, insn->dst_reg)) {
17936 			verbose(env, "R%d pointer arithmetic prohibited\n",
17937 				insn->dst_reg);
17938 			return -EACCES;
17939 		}
17940 
17941 		/* check dest operand */
17942 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
17943 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17944 			err = err ?: adjust_scalar_min_max_vals(env, insn,
17945 							 &regs[insn->dst_reg],
17946 							 regs[insn->dst_reg]);
17947 		} else {
17948 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
17949 		}
17950 		if (err)
17951 			return err;
17952 
17953 	} else if (opcode == BPF_MOV) {
17954 
17955 		if (BPF_SRC(insn->code) == BPF_X) {
17956 			if (insn->off == BPF_ADDR_SPACE_CAST) {
17957 				if (!env->prog->aux->arena) {
17958 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
17959 					return -EINVAL;
17960 				}
17961 			}
17962 
17963 			/* check src operand */
17964 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17965 			if (err)
17966 				return err;
17967 		}
17968 
17969 		/* check dest operand, mark as required later */
17970 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17971 		if (err)
17972 			return err;
17973 
17974 		if (BPF_SRC(insn->code) == BPF_X) {
17975 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
17976 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
17977 
17978 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
17979 				if (insn->imm) {
17980 					/* off == BPF_ADDR_SPACE_CAST */
17981 					mark_reg_unknown(env, regs, insn->dst_reg);
17982 					if (insn->imm == 1) /* cast from as(1) to as(0) */
17983 						dst_reg->type = PTR_TO_ARENA;
17984 				} else if (insn->off == 0) {
17985 					/* case: R1 = R2
17986 					 * copy register state to dest reg
17987 					 */
17988 					assign_scalar_id_before_mov(env, src_reg);
17989 					*dst_reg = *src_reg;
17990 				} else {
17991 					/* case: R1 = (s8, s16 s32)R2 */
17992 					if (is_pointer_value(env, insn->src_reg)) {
17993 						verbose(env,
17994 							"R%d sign-extension part of pointer\n",
17995 							insn->src_reg);
17996 						return -EACCES;
17997 					} else if (src_reg->type == SCALAR_VALUE) {
17998 						bool no_sext;
17999 
18000 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
18001 						if (no_sext)
18002 							assign_scalar_id_before_mov(env, src_reg);
18003 						*dst_reg = *src_reg;
18004 						if (!no_sext)
18005 							clear_scalar_id(dst_reg);
18006 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
18007 					} else {
18008 						mark_reg_unknown(env, regs, insn->dst_reg);
18009 					}
18010 				}
18011 			} else {
18012 				/* R1 = (u32) R2 */
18013 				if (is_pointer_value(env, insn->src_reg)) {
18014 					verbose(env,
18015 						"R%d partial copy of pointer\n",
18016 						insn->src_reg);
18017 					return -EACCES;
18018 				} else if (src_reg->type == SCALAR_VALUE) {
18019 					if (insn->off == 0) {
18020 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
18021 
18022 						if (is_src_reg_u32)
18023 							assign_scalar_id_before_mov(env, src_reg);
18024 						*dst_reg = *src_reg;
18025 						/* Make sure ID is cleared if src_reg is not in u32
18026 						 * range otherwise dst_reg min/max could be incorrectly
18027 						 * propagated into src_reg by sync_linked_regs()
18028 						 */
18029 						if (!is_src_reg_u32)
18030 							clear_scalar_id(dst_reg);
18031 					} else {
18032 						/* case: W1 = (s8, s16)W2 */
18033 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
18034 
18035 						if (no_sext)
18036 							assign_scalar_id_before_mov(env, src_reg);
18037 						*dst_reg = *src_reg;
18038 						if (!no_sext)
18039 							clear_scalar_id(dst_reg);
18040 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
18041 					}
18042 				} else {
18043 					mark_reg_unknown(env, regs,
18044 							 insn->dst_reg);
18045 				}
18046 				zext_32_to_64(dst_reg);
18047 				reg_bounds_sync(dst_reg);
18048 			}
18049 		} else {
18050 			/* case: R = imm
18051 			 * remember the value we stored into this reg
18052 			 */
18053 			/* clear any state __mark_reg_known doesn't set */
18054 			mark_reg_unknown(env, regs, insn->dst_reg);
18055 			regs[insn->dst_reg].type = SCALAR_VALUE;
18056 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
18057 				__mark_reg_known(regs + insn->dst_reg,
18058 						 insn->imm);
18059 			} else {
18060 				__mark_reg_known(regs + insn->dst_reg,
18061 						 (u32)insn->imm);
18062 			}
18063 		}
18064 
18065 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
18066 
18067 		if (BPF_SRC(insn->code) == BPF_X) {
18068 			/* check src1 operand */
18069 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
18070 			if (err)
18071 				return err;
18072 		}
18073 
18074 		/* check src2 operand */
18075 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18076 		if (err)
18077 			return err;
18078 
18079 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
18080 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
18081 			verbose(env, "div by zero\n");
18082 			return -EINVAL;
18083 		}
18084 
18085 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
18086 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
18087 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
18088 
18089 			if (insn->imm < 0 || insn->imm >= size) {
18090 				verbose(env, "invalid shift %d\n", insn->imm);
18091 				return -EINVAL;
18092 			}
18093 		}
18094 
18095 		/* check dest operand */
18096 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
18097 		err = err ?: adjust_reg_min_max_vals(env, insn);
18098 		if (err)
18099 			return err;
18100 	}
18101 
18102 	err = reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
18103 	if (err)
18104 		return err;
18105 
18106 	bpf_diag_mod_end(env);
18107 	return 0;
18108 }
18109 
18110 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
18111 				   struct bpf_reg_state *dst_reg,
18112 				   enum bpf_reg_type type,
18113 				   bool range_right_open)
18114 {
18115 	struct bpf_func_state *state;
18116 	struct bpf_reg_state *reg;
18117 	int new_range;
18118 
18119 	if (reg_umax(dst_reg) == 0 && range_right_open)
18120 		/* This doesn't give us any range */
18121 		return;
18122 
18123 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
18124 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
18125 		 * than pkt_end, but that's because it's also less than pkt.
18126 		 */
18127 		return;
18128 
18129 	new_range = reg_umax(dst_reg);
18130 	if (range_right_open)
18131 		new_range++;
18132 
18133 	/* Examples for register markings:
18134 	 *
18135 	 * pkt_data in dst register:
18136 	 *
18137 	 *   r2 = r3;
18138 	 *   r2 += 8;
18139 	 *   if (r2 > pkt_end) goto <handle exception>
18140 	 *   <access okay>
18141 	 *
18142 	 *   r2 = r3;
18143 	 *   r2 += 8;
18144 	 *   if (r2 < pkt_end) goto <access okay>
18145 	 *   <handle exception>
18146 	 *
18147 	 *   Where:
18148 	 *     r2 == dst_reg, pkt_end == src_reg
18149 	 *     r2=pkt(id=n,off=8,r=0)
18150 	 *     r3=pkt(id=n,off=0,r=0)
18151 	 *
18152 	 * pkt_data in src register:
18153 	 *
18154 	 *   r2 = r3;
18155 	 *   r2 += 8;
18156 	 *   if (pkt_end >= r2) goto <access okay>
18157 	 *   <handle exception>
18158 	 *
18159 	 *   r2 = r3;
18160 	 *   r2 += 8;
18161 	 *   if (pkt_end <= r2) goto <handle exception>
18162 	 *   <access okay>
18163 	 *
18164 	 *   Where:
18165 	 *     pkt_end == dst_reg, r2 == src_reg
18166 	 *     r2=pkt(id=n,off=8,r=0)
18167 	 *     r3=pkt(id=n,off=0,r=0)
18168 	 *
18169 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
18170 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
18171 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
18172 	 * the check.
18173 	 */
18174 
18175 	/* If our ids match, then we must have the same max_value.  And we
18176 	 * don't care about the other reg's fixed offset, since if it's too big
18177 	 * the range won't allow anything.
18178 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
18179 	 */
18180 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
18181 		if (reg->type == type && reg->id == dst_reg->id)
18182 			/* keep the maximum range already checked */
18183 			reg->range = max(reg->range, new_range);
18184 	}));
18185 }
18186 
18187 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
18188 				u8 opcode, bool is_jmp32);
18189 /*
18190  * Learn more information about live branches by simulating refinement on both branches.
18191  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
18192  * that branch is dead.
18193  */
18194 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
18195 {
18196 	/* Fallthrough (FALSE) branch */
18197 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
18198 	reg_bounds_sync(&env->false_reg1);
18199 	reg_bounds_sync(&env->false_reg2);
18200 	/*
18201 	 * If there is a range bounds violation in *any* of the abstract values in either
18202 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
18203 	 * TRUE branch will be taken.
18204 	 */
18205 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
18206 		return 1;
18207 
18208 	/* Jump (TRUE) branch */
18209 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
18210 	reg_bounds_sync(&env->true_reg1);
18211 	reg_bounds_sync(&env->true_reg2);
18212 	/*
18213 	 * If there is a range bounds violation in *any* of the abstract values in either
18214 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
18215 	 * Only FALSE branch will be taken.
18216 	 */
18217 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
18218 		return 0;
18219 
18220 	/* Both branches are possible, we can't determine which one will be taken. */
18221 	return -1;
18222 }
18223 
18224 /*
18225  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
18226  */
18227 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
18228 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
18229 {
18230 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
18231 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
18232 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
18233 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
18234 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
18235 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
18236 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
18237 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
18238 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
18239 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
18240 
18241 	if (reg1 == reg2) {
18242 		switch (opcode) {
18243 		case BPF_JGE:
18244 		case BPF_JLE:
18245 		case BPF_JSGE:
18246 		case BPF_JSLE:
18247 		case BPF_JEQ:
18248 			return 1;
18249 		case BPF_JGT:
18250 		case BPF_JLT:
18251 		case BPF_JSGT:
18252 		case BPF_JSLT:
18253 		case BPF_JNE:
18254 			return 0;
18255 		case BPF_JSET:
18256 			if (tnum_is_const(t1))
18257 				return t1.value != 0;
18258 			else
18259 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
18260 		default:
18261 			return -1;
18262 		}
18263 	}
18264 
18265 	switch (opcode) {
18266 	case BPF_JEQ:
18267 		/* constants, umin/umax and smin/smax checks would be
18268 		 * redundant in this case because they all should match
18269 		 */
18270 		if (tnum_is_const(t1) && tnum_is_const(t2))
18271 			return t1.value == t2.value;
18272 		if (!tnum_overlap(t1, t2))
18273 			return 0;
18274 		/* non-overlapping ranges */
18275 		if (umin1 > umax2 || umax1 < umin2)
18276 			return 0;
18277 		if (smin1 > smax2 || smax1 < smin2)
18278 			return 0;
18279 		if (!is_jmp32) {
18280 			/* if 64-bit ranges are inconclusive, see if we can
18281 			 * utilize 32-bit subrange knowledge to eliminate
18282 			 * branches that can't be taken a priori
18283 			 */
18284 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
18285 			    reg_u32_max(reg1) < reg_u32_min(reg2))
18286 				return 0;
18287 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
18288 			    reg_s32_max(reg1) < reg_s32_min(reg2))
18289 				return 0;
18290 		}
18291 		break;
18292 	case BPF_JNE:
18293 		/* constants, umin/umax and smin/smax checks would be
18294 		 * redundant in this case because they all should match
18295 		 */
18296 		if (tnum_is_const(t1) && tnum_is_const(t2))
18297 			return t1.value != t2.value;
18298 		if (!tnum_overlap(t1, t2))
18299 			return 1;
18300 		/* non-overlapping ranges */
18301 		if (umin1 > umax2 || umax1 < umin2)
18302 			return 1;
18303 		if (smin1 > smax2 || smax1 < smin2)
18304 			return 1;
18305 		if (!is_jmp32) {
18306 			/* if 64-bit ranges are inconclusive, see if we can
18307 			 * utilize 32-bit subrange knowledge to eliminate
18308 			 * branches that can't be taken a priori
18309 			 */
18310 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
18311 			    reg_u32_max(reg1) < reg_u32_min(reg2))
18312 				return 1;
18313 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
18314 			    reg_s32_max(reg1) < reg_s32_min(reg2))
18315 				return 1;
18316 		}
18317 		break;
18318 	case BPF_JSET:
18319 		if (!is_reg_const(reg2, is_jmp32)) {
18320 			swap(reg1, reg2);
18321 			swap(t1, t2);
18322 		}
18323 		if (!is_reg_const(reg2, is_jmp32))
18324 			return -1;
18325 		if ((~t1.mask & t1.value) & t2.value)
18326 			return 1;
18327 		if (!((t1.mask | t1.value) & t2.value))
18328 			return 0;
18329 		break;
18330 	case BPF_JGT:
18331 		if (umin1 > umax2)
18332 			return 1;
18333 		else if (umax1 <= umin2)
18334 			return 0;
18335 		break;
18336 	case BPF_JSGT:
18337 		if (smin1 > smax2)
18338 			return 1;
18339 		else if (smax1 <= smin2)
18340 			return 0;
18341 		break;
18342 	case BPF_JLT:
18343 		if (umax1 < umin2)
18344 			return 1;
18345 		else if (umin1 >= umax2)
18346 			return 0;
18347 		break;
18348 	case BPF_JSLT:
18349 		if (smax1 < smin2)
18350 			return 1;
18351 		else if (smin1 >= smax2)
18352 			return 0;
18353 		break;
18354 	case BPF_JGE:
18355 		if (umin1 >= umax2)
18356 			return 1;
18357 		else if (umax1 < umin2)
18358 			return 0;
18359 		break;
18360 	case BPF_JSGE:
18361 		if (smin1 >= smax2)
18362 			return 1;
18363 		else if (smax1 < smin2)
18364 			return 0;
18365 		break;
18366 	case BPF_JLE:
18367 		if (umax1 <= umin2)
18368 			return 1;
18369 		else if (umin1 > umax2)
18370 			return 0;
18371 		break;
18372 	case BPF_JSLE:
18373 		if (smax1 <= smin2)
18374 			return 1;
18375 		else if (smin1 > smax2)
18376 			return 0;
18377 		break;
18378 	}
18379 
18380 	return simulate_both_branches_taken(env, opcode, is_jmp32);
18381 }
18382 
18383 int bpf_flip_opcode(u32 opcode)
18384 {
18385 	/* How can we transform "a <op> b" into "b <op> a"? */
18386 	static const u8 opcode_flip[16] = {
18387 		/* these stay the same */
18388 		[BPF_JEQ  >> 4] = BPF_JEQ,
18389 		[BPF_JNE  >> 4] = BPF_JNE,
18390 		[BPF_JSET >> 4] = BPF_JSET,
18391 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
18392 		[BPF_JGE  >> 4] = BPF_JLE,
18393 		[BPF_JGT  >> 4] = BPF_JLT,
18394 		[BPF_JLE  >> 4] = BPF_JGE,
18395 		[BPF_JLT  >> 4] = BPF_JGT,
18396 		[BPF_JSGE >> 4] = BPF_JSLE,
18397 		[BPF_JSGT >> 4] = BPF_JSLT,
18398 		[BPF_JSLE >> 4] = BPF_JSGE,
18399 		[BPF_JSLT >> 4] = BPF_JSGT
18400 	};
18401 	return opcode_flip[opcode >> 4];
18402 }
18403 
18404 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
18405 				   struct bpf_reg_state *src_reg,
18406 				   u8 opcode)
18407 {
18408 	struct bpf_reg_state *pkt;
18409 
18410 	if (src_reg->type == PTR_TO_PACKET_END) {
18411 		pkt = dst_reg;
18412 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
18413 		pkt = src_reg;
18414 		opcode = bpf_flip_opcode(opcode);
18415 	} else {
18416 		return -1;
18417 	}
18418 
18419 	if (pkt->range >= 0)
18420 		return -1;
18421 
18422 	switch (opcode) {
18423 	case BPF_JLE:
18424 		/* pkt <= pkt_end */
18425 		fallthrough;
18426 	case BPF_JGT:
18427 		/* pkt > pkt_end */
18428 		if (pkt->range == BEYOND_PKT_END)
18429 			/* pkt has at last one extra byte beyond pkt_end */
18430 			return opcode == BPF_JGT;
18431 		break;
18432 	case BPF_JLT:
18433 		/* pkt < pkt_end */
18434 		fallthrough;
18435 	case BPF_JGE:
18436 		/* pkt >= pkt_end */
18437 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
18438 			return opcode == BPF_JGE;
18439 		break;
18440 	}
18441 	return -1;
18442 }
18443 
18444 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
18445  * and return:
18446  *  1 - branch will be taken and "goto target" will be executed
18447  *  0 - branch will not be taken and fall-through to next insn
18448  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
18449  *      range [0,10]
18450  */
18451 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
18452 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
18453 {
18454 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
18455 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
18456 
18457 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
18458 		u64 val;
18459 
18460 		/*
18461 		 * The low 32 bits of a valid pointer may well be zero, hence
18462 		 * nothing below applies to a 32-bit comparison.
18463 		 */
18464 		if (is_jmp32)
18465 			return -1;
18466 
18467 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
18468 		if (!is_reg_const(reg2, is_jmp32)) {
18469 			opcode = bpf_flip_opcode(opcode);
18470 			swap(reg1, reg2);
18471 		}
18472 		/* and ensure that reg2 is a constant */
18473 		if (!is_reg_const(reg2, is_jmp32))
18474 			return -1;
18475 
18476 		if (!reg_not_null(env, reg1))
18477 			return -1;
18478 
18479 		/* If pointer is valid tests against zero will fail so we can
18480 		 * use this to direct branch taken.
18481 		 */
18482 		val = reg_const_value(reg2, is_jmp32);
18483 		if (val != 0)
18484 			return -1;
18485 
18486 		switch (opcode) {
18487 		case BPF_JEQ:
18488 			return 0;
18489 		case BPF_JNE:
18490 			return 1;
18491 		default:
18492 			return -1;
18493 		}
18494 	}
18495 
18496 	/* now deal with two scalars, but not necessarily constants */
18497 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
18498 }
18499 
18500 /* Opcode that corresponds to a *false* branch condition.
18501  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
18502  */
18503 u8 bpf_rev_opcode(u8 opcode)
18504 {
18505 	switch (opcode) {
18506 	case BPF_JEQ:		return BPF_JNE;
18507 	case BPF_JNE:		return BPF_JEQ;
18508 	/* JSET doesn't have it's reverse opcode in BPF, so add
18509 	 * BPF_X flag to denote the reverse of that operation
18510 	 */
18511 	case BPF_JSET:		return BPF_JSET | BPF_X;
18512 	case BPF_JSET | BPF_X:	return BPF_JSET;
18513 	case BPF_JGE:		return BPF_JLT;
18514 	case BPF_JGT:		return BPF_JLE;
18515 	case BPF_JLE:		return BPF_JGT;
18516 	case BPF_JLT:		return BPF_JGE;
18517 	case BPF_JSGE:		return BPF_JSLT;
18518 	case BPF_JSGT:		return BPF_JSLE;
18519 	case BPF_JSLE:		return BPF_JSGT;
18520 	case BPF_JSLT:		return BPF_JSGE;
18521 	default:		return 0;
18522 	}
18523 }
18524 
18525 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
18526 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
18527 				u8 opcode, bool is_jmp32)
18528 {
18529 	struct tnum t;
18530 	u64 val;
18531 
18532 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
18533 	switch (opcode) {
18534 	case BPF_JGE:
18535 	case BPF_JGT:
18536 	case BPF_JSGE:
18537 	case BPF_JSGT:
18538 		opcode = bpf_flip_opcode(opcode);
18539 		swap(reg1, reg2);
18540 		break;
18541 	default:
18542 		break;
18543 	}
18544 
18545 	switch (opcode) {
18546 	case BPF_JEQ:
18547 		if (is_jmp32) {
18548 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
18549 			reg2->r32 = reg1->r32;
18550 
18551 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
18552 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18553 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
18554 		} else {
18555 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
18556 			reg2->r64 = reg1->r64;
18557 
18558 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
18559 			reg2->var_off = reg1->var_off;
18560 		}
18561 		break;
18562 	case BPF_JNE:
18563 		if (!is_reg_const(reg2, is_jmp32))
18564 			swap(reg1, reg2);
18565 		if (!is_reg_const(reg2, is_jmp32))
18566 			break;
18567 
18568 		/* try to recompute the bound of reg1 if reg2 is a const and
18569 		 * is exactly the edge of reg1.
18570 		 */
18571 		val = reg_const_value(reg2, is_jmp32);
18572 		if (is_jmp32) {
18573 			/* Complement of the range [val, val] as cnum32. */
18574 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
18575 		} else {
18576 			/* Complement of the range [val, val] as cnum64. */
18577 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
18578 		}
18579 		break;
18580 	case BPF_JSET:
18581 		if (!is_reg_const(reg2, is_jmp32))
18582 			swap(reg1, reg2);
18583 		if (!is_reg_const(reg2, is_jmp32))
18584 			break;
18585 		val = reg_const_value(reg2, is_jmp32);
18586 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
18587 		 * requires single bit to learn something useful. E.g., if we
18588 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
18589 		 * are actually set? We can learn something definite only if
18590 		 * it's a single-bit value to begin with.
18591 		 *
18592 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
18593 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
18594 		 * bit 1 is set, which we can readily use in adjustments.
18595 		 */
18596 		if (hweight64(val) != 1)
18597 			break;
18598 		if (is_jmp32) {
18599 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
18600 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18601 		} else {
18602 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
18603 		}
18604 		break;
18605 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see bpf_rev_opcode() */
18606 		if (!is_reg_const(reg2, is_jmp32))
18607 			swap(reg1, reg2);
18608 		if (!is_reg_const(reg2, is_jmp32))
18609 			break;
18610 		val = reg_const_value(reg2, is_jmp32);
18611 		/* Forget the ranges before narrowing tnums, to avoid invariant
18612 		 * violations if we're on a dead branch.
18613 		 */
18614 		__mark_reg_unbounded(reg1);
18615 		reg_step_reset(reg1);
18616 		if (is_jmp32) {
18617 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
18618 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18619 		} else {
18620 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
18621 		}
18622 		break;
18623 	case BPF_JLE:
18624 		if (is_jmp32) {
18625 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
18626 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
18627 		} else {
18628 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
18629 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
18630 		}
18631 		break;
18632 	case BPF_JLT:
18633 		if (is_jmp32) {
18634 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
18635 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
18636 		} else {
18637 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
18638 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
18639 		}
18640 		break;
18641 	case BPF_JSLE:
18642 		if (is_jmp32) {
18643 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
18644 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
18645 		} else {
18646 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
18647 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
18648 		}
18649 		break;
18650 	case BPF_JSLT:
18651 		if (is_jmp32) {
18652 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
18653 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
18654 		} else {
18655 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
18656 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
18657 		}
18658 		break;
18659 	default:
18660 		return;
18661 	}
18662 }
18663 
18664 /* Check for invariant violations on the registers for both branches of a condition */
18665 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
18666 {
18667 	int err;
18668 
18669 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
18670 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
18671 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
18672 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
18673 	return err;
18674 }
18675 
18676 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
18677 				 struct bpf_reg_state *reg, u32 id,
18678 				 bool is_null)
18679 {
18680 	if (type_may_be_null(reg->type) && reg->id == id &&
18681 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
18682 		/* Old offset should have been known-zero, because we don't
18683 		 * allow pointer arithmetic on pointers that might be NULL.
18684 		 * If we see this happening, don't convert the register.
18685 		 *
18686 		 * But in some cases, some helpers that return local kptrs
18687 		 * advance offset for the returned pointer. In those cases,
18688 		 * it is fine to expect to see reg->var_off.
18689 		 */
18690 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
18691 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
18692 			return;
18693 		if (is_null) {
18694 			/* We don't need id from this point
18695 			 * onwards anymore, thus we should better reset it,
18696 			 * so that state pruning has chances to take effect.
18697 			 */
18698 			__mark_reg_known_zero(reg);
18699 			reg->type = SCALAR_VALUE;
18700 
18701 			return;
18702 		}
18703 
18704 		mark_ptr_not_null_reg(reg);
18705 
18706 		/*
18707 		 * reg->id is preserved for object relationship tracking
18708 		 * and spin_lock lock state tracking
18709 		 */
18710 	}
18711 }
18712 
18713 /* The logic is similar to find_good_pkt_pointers(), both could eventually
18714  * be folded together at some point.
18715  */
18716 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
18717 				  bool is_null)
18718 {
18719 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
18720 	struct bpf_reg_state *regs = state->regs, *reg;
18721 	u32 id = regs[regno].id;
18722 
18723 	if (is_null && find_reference_state(vstate, id))
18724 		/* regs[regno] is in the " == NULL" branch.
18725 		 * No one could have freed the reference state before
18726 		 * doing the NULL check.
18727 		 */
18728 		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
18729 
18730 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
18731 		mark_ptr_or_null_reg(state, reg, id, is_null);
18732 	}));
18733 }
18734 
18735 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
18736 				   struct bpf_reg_state *dst_reg,
18737 				   struct bpf_reg_state *src_reg,
18738 				   struct bpf_verifier_state *this_branch,
18739 				   struct bpf_verifier_state *other_branch)
18740 {
18741 	if (BPF_SRC(insn->code) != BPF_X)
18742 		return false;
18743 
18744 	/* Pointers are always 64-bit. */
18745 	if (BPF_CLASS(insn->code) == BPF_JMP32)
18746 		return false;
18747 
18748 	switch (BPF_OP(insn->code)) {
18749 	case BPF_JGT:
18750 		if ((dst_reg->type == PTR_TO_PACKET &&
18751 		     src_reg->type == PTR_TO_PACKET_END) ||
18752 		    (dst_reg->type == PTR_TO_PACKET_META &&
18753 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18754 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
18755 			find_good_pkt_pointers(this_branch, dst_reg,
18756 					       dst_reg->type, false);
18757 			mark_pkt_end(other_branch, insn->dst_reg, true);
18758 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18759 			    src_reg->type == PTR_TO_PACKET) ||
18760 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18761 			    src_reg->type == PTR_TO_PACKET_META)) {
18762 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
18763 			find_good_pkt_pointers(other_branch, src_reg,
18764 					       src_reg->type, true);
18765 			mark_pkt_end(this_branch, insn->src_reg, false);
18766 		} else {
18767 			return false;
18768 		}
18769 		break;
18770 	case BPF_JLT:
18771 		if ((dst_reg->type == PTR_TO_PACKET &&
18772 		     src_reg->type == PTR_TO_PACKET_END) ||
18773 		    (dst_reg->type == PTR_TO_PACKET_META &&
18774 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18775 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
18776 			find_good_pkt_pointers(other_branch, dst_reg,
18777 					       dst_reg->type, true);
18778 			mark_pkt_end(this_branch, insn->dst_reg, false);
18779 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18780 			    src_reg->type == PTR_TO_PACKET) ||
18781 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18782 			    src_reg->type == PTR_TO_PACKET_META)) {
18783 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
18784 			find_good_pkt_pointers(this_branch, src_reg,
18785 					       src_reg->type, false);
18786 			mark_pkt_end(other_branch, insn->src_reg, true);
18787 		} else {
18788 			return false;
18789 		}
18790 		break;
18791 	case BPF_JGE:
18792 		if ((dst_reg->type == PTR_TO_PACKET &&
18793 		     src_reg->type == PTR_TO_PACKET_END) ||
18794 		    (dst_reg->type == PTR_TO_PACKET_META &&
18795 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18796 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
18797 			find_good_pkt_pointers(this_branch, dst_reg,
18798 					       dst_reg->type, true);
18799 			mark_pkt_end(other_branch, insn->dst_reg, false);
18800 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18801 			    src_reg->type == PTR_TO_PACKET) ||
18802 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18803 			    src_reg->type == PTR_TO_PACKET_META)) {
18804 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
18805 			find_good_pkt_pointers(other_branch, src_reg,
18806 					       src_reg->type, false);
18807 			mark_pkt_end(this_branch, insn->src_reg, true);
18808 		} else {
18809 			return false;
18810 		}
18811 		break;
18812 	case BPF_JLE:
18813 		if ((dst_reg->type == PTR_TO_PACKET &&
18814 		     src_reg->type == PTR_TO_PACKET_END) ||
18815 		    (dst_reg->type == PTR_TO_PACKET_META &&
18816 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18817 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
18818 			find_good_pkt_pointers(other_branch, dst_reg,
18819 					       dst_reg->type, false);
18820 			mark_pkt_end(this_branch, insn->dst_reg, true);
18821 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18822 			    src_reg->type == PTR_TO_PACKET) ||
18823 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18824 			    src_reg->type == PTR_TO_PACKET_META)) {
18825 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
18826 			find_good_pkt_pointers(this_branch, src_reg,
18827 					       src_reg->type, true);
18828 			mark_pkt_end(other_branch, insn->src_reg, false);
18829 		} else {
18830 			return false;
18831 		}
18832 		break;
18833 	default:
18834 		return false;
18835 	}
18836 
18837 	return true;
18838 }
18839 
18840 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
18841 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
18842 {
18843 	struct linked_reg *e;
18844 
18845 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
18846 		return;
18847 
18848 	e = linked_regs_push(reg_set);
18849 	if (e) {
18850 		e->frameno = frameno;
18851 		e->is_reg = is_reg;
18852 		e->regno = spi_or_reg;
18853 	} else {
18854 		clear_scalar_id(reg);
18855 	}
18856 }
18857 
18858 /* For all R being scalar registers or spilled scalar registers
18859  * in verifier state, save R in linked_regs if R->id == id.
18860  * If there are too many Rs sharing same id, reset id for leftover Rs.
18861  */
18862 static void collect_linked_regs(struct bpf_verifier_env *env,
18863 				struct bpf_verifier_state *vstate,
18864 				u32 id,
18865 				struct linked_regs *linked_regs)
18866 {
18867 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18868 	struct bpf_func_state *func;
18869 	struct bpf_reg_state *reg;
18870 	u16 live_regs;
18871 	int i, j;
18872 
18873 	id = id & ~BPF_ADD_CONST;
18874 	for (i = vstate->curframe; i >= 0; i--) {
18875 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
18876 		func = vstate->frame[i];
18877 		for (j = 0; j < BPF_REG_FP; j++) {
18878 			if (!(live_regs & BIT(j)))
18879 				continue;
18880 			reg = &func->regs[j];
18881 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
18882 		}
18883 		for (j = 0; j < bpf_stack_nr_slots(func); j++) {
18884 			struct bpf_stack_state *ss = bpf_stack_slot(func, j);
18885 
18886 			if (!bpf_is_spilled_reg(ss))
18887 				continue;
18888 			reg = &ss->spilled_ptr;
18889 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
18890 		}
18891 	}
18892 }
18893 
18894 /* For all R in linked_regs, copy known_reg range into R
18895  * if R->id == known_reg->id.
18896  */
18897 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
18898 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
18899 {
18900 	struct bpf_reg_state fake_reg;
18901 	struct bpf_reg_state *reg;
18902 	struct linked_reg *e;
18903 	int i;
18904 
18905 	for (i = 0; i < linked_regs->cnt; ++i) {
18906 		e = &linked_regs->entries[i];
18907 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
18908 				: &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
18909 		if (reg->type != SCALAR_VALUE || reg == known_reg)
18910 			continue;
18911 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
18912 			continue;
18913 		/*
18914 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
18915 		 * hold across different ALU widths.
18916 		 */
18917 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
18918 			continue;
18919 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
18920 		    reg->delta == known_reg->delta) {
18921 			*reg = *known_reg;
18922 		} else {
18923 			s32 saved_off = reg->delta;
18924 			u32 saved_id = reg->id;
18925 
18926 			fake_reg.type = SCALAR_VALUE;
18927 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
18928 
18929 			/* reg = known_reg; reg += delta */
18930 			*reg = *known_reg;
18931 			/*
18932 			 * Must preserve off and id, otherwise another sync_linked_regs()
18933 			 * will be incorrect.
18934 			 */
18935 			reg->delta = saved_off;
18936 			reg->id = saved_id;
18937 
18938 			scalar_step_add(reg, reg, &fake_reg);
18939 			scalar32_min_max_add(reg, &fake_reg);
18940 			scalar_min_max_add(reg, &fake_reg);
18941 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
18942 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
18943 				zext_32_to_64(reg);
18944 			reg_bounds_sync(reg);
18945 		}
18946 		if (e->is_reg)
18947 			mark_reg_scratched(env, e->regno);
18948 		else
18949 			mark_stack_slot_scratched(env, e->spi);
18950 	}
18951 }
18952 
18953 static int check_cond_jmp_op(struct bpf_verifier_env *env,
18954 			     struct bpf_insn *insn, int *insn_idx)
18955 {
18956 	struct bpf_verifier_state *this_branch = env->cur_state;
18957 	struct bpf_verifier_state *other_branch;
18958 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
18959 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
18960 	struct bpf_reg_state *eq_branch_regs;
18961 	struct linked_regs linked_regs = {};
18962 	u8 opcode = BPF_OP(insn->code);
18963 	int insn_flags = 0;
18964 	bool is_jmp32;
18965 	int pred = -1;
18966 	int err;
18967 
18968 	/* Only conditional jumps are expected to reach here. */
18969 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
18970 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
18971 		return -EINVAL;
18972 	}
18973 
18974 	if (bpf_is_unwind_goto(insn)) {
18975 		if (!env->cur_state->unwound)
18976 			return 0;
18977 		env->cur_state->unwound = false;
18978 		/*
18979 		 * unwind_exit changed its return address, so the return is
18980 		 * mispredicted and what follows unwind_goto runs speculatively.
18981 		 */
18982 		if (!env->bypass_spec_v1) {
18983 			err = sanitize_speculative_path(env, NULL, *insn_idx + 1, *insn_idx);
18984 			if (err)
18985 				return err;
18986 		}
18987 		*insn_idx += insn->off;
18988 		return 0;
18989 	}
18990 
18991 	if (opcode == BPF_JCOND) {
18992 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
18993 		int idx = *insn_idx;
18994 
18995 		prev_st = find_prev_entry(env, cur_st->parent, idx);
18996 
18997 		/* branch out 'fallthrough' insn as a new state to explore */
18998 		queued_st = push_stack(env, idx + 1, idx, false);
18999 		if (IS_ERR(queued_st))
19000 			return PTR_ERR(queued_st);
19001 
19002 		queued_st->may_goto_depth++;
19003 		if (prev_st)
19004 			widen_imprecise_scalars(env, prev_st, queued_st);
19005 		*insn_idx += insn->off;
19006 		return 0;
19007 	}
19008 
19009 	/* check src2 operand */
19010 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19011 	if (err)
19012 		return err;
19013 
19014 	dst_reg = &regs[insn->dst_reg];
19015 	if (BPF_SRC(insn->code) == BPF_X) {
19016 		/* check src1 operand */
19017 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
19018 		if (err)
19019 			return err;
19020 
19021 		src_reg = &regs[insn->src_reg];
19022 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
19023 		    is_pointer_value(env, insn->src_reg)) {
19024 			verbose(env, "R%d pointer comparison prohibited\n",
19025 				insn->src_reg);
19026 			return -EACCES;
19027 		}
19028 
19029 		if (src_reg->type == PTR_TO_STACK)
19030 			insn_flags |= INSN_F_SRC_REG_STACK;
19031 		if (dst_reg->type == PTR_TO_STACK)
19032 			insn_flags |= INSN_F_DST_REG_STACK;
19033 	} else {
19034 		src_reg = &env->fake_reg[0];
19035 		memset(src_reg, 0, sizeof(*src_reg));
19036 		src_reg->type = SCALAR_VALUE;
19037 		__mark_reg_known(src_reg, insn->imm);
19038 
19039 		if (dst_reg->type == PTR_TO_STACK)
19040 			insn_flags |= INSN_F_DST_REG_STACK;
19041 	}
19042 
19043 	if (insn_flags) {
19044 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, NULL, 0);
19045 		if (err)
19046 			return err;
19047 	}
19048 
19049 	/*
19050 	 * Collect the linked registers before env->{true,false}_reg{1,2} setup,
19051 	 * otherwise ids dropped by collect_linked_regs() would be resurrected
19052 	 * when env->{true,false}_reg{1,2} are copied back.
19053 	 */
19054 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
19055 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
19056 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
19057 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
19058 
19059 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
19060 	env->false_reg1 = *dst_reg;
19061 	env->false_reg2 = *src_reg;
19062 	env->true_reg1 = *dst_reg;
19063 	env->true_reg2 = *src_reg;
19064 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
19065 	if (pred >= 0) {
19066 		/* If we get here with a dst_reg pointer type it is because
19067 		 * above is_branch_taken() special cased the 0 comparison.
19068 		 */
19069 		if (!__is_pointer_value(false, dst_reg))
19070 			err = mark_chain_precision(env, insn->dst_reg);
19071 		if (BPF_SRC(insn->code) == BPF_X && !err &&
19072 		    !__is_pointer_value(false, src_reg))
19073 			err = mark_chain_precision(env, insn->src_reg);
19074 		if (err)
19075 			return err;
19076 	}
19077 
19078 	if (pred == 1) {
19079 		/* Only follow the goto, ignore fall-through. If needed, push
19080 		 * the fall-through branch for simulation under speculative
19081 		 * execution.
19082 		 */
19083 		if (!env->bypass_spec_v1) {
19084 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
19085 			if (err < 0)
19086 				return err;
19087 		}
19088 		if (env->log.level & BPF_LOG_LEVEL)
19089 			print_insn_state(env, this_branch, this_branch->curframe);
19090 		*insn_idx += insn->off;
19091 		return 0;
19092 	} else if (pred == 0) {
19093 		/* Only follow the fall-through branch, since that's where the
19094 		 * program will go. If needed, push the goto branch for
19095 		 * simulation under speculative execution.
19096 		 */
19097 		if (!env->bypass_spec_v1) {
19098 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
19099 							*insn_idx);
19100 			if (err < 0)
19101 				return err;
19102 		}
19103 		if (env->log.level & BPF_LOG_LEVEL)
19104 			print_insn_state(env, this_branch, this_branch->curframe);
19105 		return 0;
19106 	}
19107 
19108 	/* Push scalar registers sharing same ID to jump history,
19109 	 * do this before creating 'other_branch', so that both
19110 	 * 'this_branch' and 'other_branch' share this history
19111 	 * if parent state is created.
19112 	 */
19113 	if (linked_regs.cnt > 1) {
19114 		u16 packed[LINKED_REGS_MAX];
19115 
19116 		linked_regs_pack(&linked_regs, packed);
19117 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, packed, linked_regs.cnt);
19118 		if (err)
19119 			return err;
19120 	}
19121 
19122 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
19123 	if (IS_ERR(other_branch))
19124 		return PTR_ERR(other_branch);
19125 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
19126 
19127 	err = regs_bounds_sanity_check_branches(env);
19128 	if (err)
19129 		return err;
19130 
19131 	*dst_reg = env->false_reg1;
19132 	*src_reg = env->false_reg2;
19133 	other_branch_regs[insn->dst_reg] = env->true_reg1;
19134 	if (BPF_SRC(insn->code) == BPF_X)
19135 		other_branch_regs[insn->src_reg] = env->true_reg2;
19136 
19137 	if (BPF_SRC(insn->code) == BPF_X &&
19138 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
19139 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
19140 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
19141 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
19142 				 &linked_regs);
19143 	}
19144 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
19145 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
19146 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
19147 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
19148 				 &linked_regs);
19149 	}
19150 
19151 	/* if one pointer register is compared to another pointer
19152 	 * register check if PTR_MAYBE_NULL could be lifted.
19153 	 * E.g. register A - maybe null
19154 	 *      register B - not null
19155 	 * for JNE A, B, ... - A is not null in the false branch;
19156 	 * for JEQ A, B, ... - A is not null in the true branch.
19157 	 *
19158 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
19159 	 * not need to be null checked by the BPF program, i.e.,
19160 	 * could be null even without PTR_MAYBE_NULL marking, so
19161 	 * only propagate nullness when neither reg is that type.
19162 	 */
19163 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
19164 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
19165 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
19166 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
19167 		eq_branch_regs = NULL;
19168 		switch (opcode) {
19169 		case BPF_JEQ:
19170 			eq_branch_regs = other_branch_regs;
19171 			break;
19172 		case BPF_JNE:
19173 			eq_branch_regs = regs;
19174 			break;
19175 		default:
19176 			/* do nothing */
19177 			break;
19178 		}
19179 		if (eq_branch_regs) {
19180 			/* src == dst && dst != NULL => src != NULL */
19181 			if (reg_not_null(env, dst_reg) && type_may_be_null(src_reg->type))
19182 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
19183 			/* src == dst && src != NULL => dst != NULL */
19184 			if (reg_not_null(env, src_reg) && type_may_be_null(dst_reg->type))
19185 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
19186 		}
19187 	}
19188 
19189 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
19190 	 * Also does the same detection for a register whose the value is
19191 	 * known to be 0.
19192 	 * NOTE: these optimizations below are related with pointer comparison
19193 	 *       which will never be JMP32.
19194 	 */
19195 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
19196 	    type_may_be_null(dst_reg->type) &&
19197 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
19198 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
19199 		/*
19200 		 * For BPF_X the zero is a property of this execution path,
19201 		 * hence src_reg has to be precise.
19202 		 */
19203 		if (BPF_SRC(insn->code) == BPF_X) {
19204 			err = mark_chain_precision(env, insn->src_reg);
19205 			if (err)
19206 				return err;
19207 		}
19208 		/* Mark all identical registers in each branch as either
19209 		 * safe or unknown depending R == 0 or R != 0 conditional.
19210 		 */
19211 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
19212 				      opcode == BPF_JNE);
19213 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
19214 				      opcode == BPF_JEQ);
19215 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
19216 					   this_branch, other_branch) &&
19217 		   is_pointer_value(env, insn->dst_reg)) {
19218 		verbose(env, "R%d pointer comparison prohibited\n",
19219 			insn->dst_reg);
19220 		return -EACCES;
19221 	}
19222 	if (env->log.level & BPF_LOG_LEVEL)
19223 		print_insn_state(env, this_branch, this_branch->curframe);
19224 	return 0;
19225 }
19226 
19227 /* verify BPF_LD_IMM64 instruction */
19228 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
19229 {
19230 	struct bpf_insn_aux_data *aux = cur_aux(env);
19231 	struct bpf_reg_state *regs = cur_regs(env);
19232 	struct bpf_reg_state *dst_reg;
19233 	struct bpf_map *map;
19234 	int err;
19235 
19236 	if (BPF_SIZE(insn->code) != BPF_DW) {
19237 		verbose(env, "invalid BPF_LD_IMM insn\n");
19238 		return -EINVAL;
19239 	}
19240 
19241 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
19242 	if (err)
19243 		return err;
19244 
19245 	dst_reg = &regs[insn->dst_reg];
19246 	bpf_diag_mod_begin(env, dst_reg, NULL, BPF_DIAG_MOD_WRITE);
19247 	if (insn->src_reg == 0) {
19248 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
19249 
19250 		dst_reg->type = SCALAR_VALUE;
19251 		__mark_reg_known(&regs[insn->dst_reg], imm);
19252 		bpf_diag_mod_end(env);
19253 		return 0;
19254 	}
19255 
19256 	/* All special src_reg cases are listed below. From this point onwards
19257 	 * we either succeed and assign a corresponding dst_reg->type after
19258 	 * zeroing the offset, or fail and reject the program.
19259 	 */
19260 	mark_reg_known_zero(env, regs, insn->dst_reg);
19261 
19262 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
19263 		dst_reg->type = aux->btf_var.reg_type;
19264 		switch (base_type(dst_reg->type)) {
19265 		case PTR_TO_MEM:
19266 			dst_reg->mem_size = aux->btf_var.mem_size;
19267 			break;
19268 		case PTR_TO_BTF_ID:
19269 			dst_reg->btf = aux->btf_var.btf;
19270 			dst_reg->btf_id = aux->btf_var.btf_id;
19271 			break;
19272 		default:
19273 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
19274 			return -EFAULT;
19275 		}
19276 		bpf_diag_mod_end(env);
19277 		return 0;
19278 	}
19279 
19280 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
19281 		struct bpf_prog_aux *aux = env->prog->aux;
19282 		u32 subprogno = bpf_find_subprog(env,
19283 						 env->insn_idx + insn->imm + 1);
19284 
19285 		if (!aux->func_info) {
19286 			verbose(env, "missing btf func_info\n");
19287 			return -EINVAL;
19288 		}
19289 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
19290 			verbose(env, "callback function not static\n");
19291 			return -EINVAL;
19292 		}
19293 		/*
19294 		 * When env->subprog_cnt == 1 this instruction won't be rewritten
19295 		 * to hold a real function address. Assume that no usable program
19296 		 * combines e.g. main and timer callback and just reject here.
19297 		 */
19298 		if (subprogno == 0) {
19299 			verbose(env, "callback function cannot be the main program\n");
19300 			return -EINVAL;
19301 		}
19302 
19303 		dst_reg->type = PTR_TO_FUNC;
19304 		dst_reg->subprogno = subprogno;
19305 		bpf_diag_mod_end(env);
19306 		return 0;
19307 	}
19308 
19309 	map = env->used_maps[aux->map_index];
19310 
19311 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
19312 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
19313 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
19314 			__mark_reg_unknown(env, dst_reg);
19315 			dst_reg->map_ptr = map;
19316 			bpf_diag_mod_end(env);
19317 			return 0;
19318 		}
19319 		__mark_reg_known(dst_reg, aux->map_off);
19320 		dst_reg->type = PTR_TO_MAP_VALUE;
19321 		dst_reg->map_ptr = map;
19322 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
19323 			     map->max_entries != 1);
19324 		/* We want reg->id to be same (0) as map_value is not distinct */
19325 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
19326 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
19327 		dst_reg->type = CONST_PTR_TO_MAP;
19328 		dst_reg->map_ptr = map;
19329 	} else {
19330 		verifier_bug(env, "unexpected src reg value for ldimm64");
19331 		return -EFAULT;
19332 	}
19333 
19334 	bpf_diag_mod_end(env);
19335 	return 0;
19336 }
19337 
19338 static bool may_access_skb(enum bpf_prog_type type)
19339 {
19340 	switch (type) {
19341 	case BPF_PROG_TYPE_SOCKET_FILTER:
19342 	case BPF_PROG_TYPE_SCHED_CLS:
19343 	case BPF_PROG_TYPE_SCHED_ACT:
19344 		return true;
19345 	default:
19346 		return false;
19347 	}
19348 }
19349 
19350 /* verify safety of LD_ABS|LD_IND instructions:
19351  * - they can only appear in the programs where ctx == skb
19352  * - since they are wrappers of function calls, they scratch R1-R5 registers,
19353  *   preserve R6-R9, and store return value into R0
19354  *
19355  * Implicit input:
19356  *   ctx == skb == R6 == CTX
19357  *
19358  * Explicit input:
19359  *   SRC == any register
19360  *   IMM == 32-bit immediate
19361  *
19362  * Output:
19363  *   R0 - 8/16/32-bit skb data converted to cpu endianness
19364  */
19365 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
19366 {
19367 	struct bpf_verifier_state *state = env->cur_state;
19368 	struct bpf_reg_state *regs = cur_regs(env);
19369 	static const int ctx_reg = BPF_REG_6;
19370 	u8 mode = BPF_MODE(insn->code);
19371 	int i, err;
19372 
19373 	if (!may_access_skb(resolve_prog_type(env->prog))) {
19374 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
19375 		return -EINVAL;
19376 	}
19377 
19378 	for (i = state->curframe; i; i--) {
19379 		if (state->frame[i]->in_callback_fn) {
19380 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
19381 			return -EINVAL;
19382 		}
19383 	}
19384 
19385 	if (!env->ops->gen_ld_abs) {
19386 		verifier_bug(env, "gen_ld_abs is null");
19387 		return -EFAULT;
19388 	}
19389 
19390 	/* check whether implicit source operand (register R6) is readable */
19391 	err = check_reg_arg(env, ctx_reg, SRC_OP);
19392 	if (err)
19393 		return err;
19394 
19395 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
19396 	 * gen_ld_abs() may terminate the program at runtime, leading to
19397 	 * reference leak.
19398 	 */
19399 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
19400 	if (err)
19401 		return err;
19402 
19403 	if (regs[ctx_reg].type != PTR_TO_CTX) {
19404 		verbose(env,
19405 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
19406 		return -EINVAL;
19407 	}
19408 
19409 	if (mode == BPF_IND) {
19410 		/* check explicit source operand */
19411 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
19412 		if (err)
19413 			return err;
19414 	}
19415 
19416 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
19417 	if (err < 0)
19418 		return err;
19419 
19420 	/* reset caller saved regs to unreadable */
19421 	bpf_diag_record_caller_saved(env, regs);
19422 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
19423 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
19424 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
19425 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
19426 	}
19427 
19428 	/* mark destination R0 register as readable, since it contains
19429 	 * the value fetched from the packet.
19430 	 * Already marked as written above.
19431 	 */
19432 	mark_reg_unknown(env, regs, BPF_REG_0);
19433 	bpf_diag_mod_end(env);
19434 	/*
19435 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
19436 	 * which must be explored by the verifier when in a subprog.
19437 	 */
19438 	if (env->cur_state->curframe) {
19439 		struct bpf_verifier_state *branch;
19440 
19441 		mark_reg_scratched(env, BPF_REG_0);
19442 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
19443 		if (IS_ERR(branch))
19444 			return PTR_ERR(branch);
19445 		mark_reg_known_zero(env, regs, BPF_REG_0);
19446 		err = prepare_func_exit(env, &env->insn_idx);
19447 		if (err)
19448 			return err;
19449 		env->insn_idx--;
19450 	}
19451 	return 0;
19452 }
19453 
19454 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
19455 {
19456 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
19457 
19458 	/* Default return value range. */
19459 	*range = retval_range(0, 1);
19460 
19461 	switch (prog_type) {
19462 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
19463 		switch (env->prog->expected_attach_type) {
19464 		case BPF_CGROUP_UDP4_RECVMSG:
19465 		case BPF_CGROUP_UDP6_RECVMSG:
19466 		case BPF_CGROUP_UNIX_RECVMSG:
19467 		case BPF_CGROUP_INET4_GETPEERNAME:
19468 		case BPF_CGROUP_INET6_GETPEERNAME:
19469 		case BPF_CGROUP_UNIX_GETPEERNAME:
19470 		case BPF_CGROUP_INET4_GETSOCKNAME:
19471 		case BPF_CGROUP_INET6_GETSOCKNAME:
19472 		case BPF_CGROUP_UNIX_GETSOCKNAME:
19473 			*range = retval_range(1, 1);
19474 			break;
19475 		case BPF_CGROUP_INET4_BIND:
19476 		case BPF_CGROUP_INET6_BIND:
19477 			*range = retval_range(0, 3);
19478 			break;
19479 		default:
19480 			break;
19481 		}
19482 		break;
19483 	case BPF_PROG_TYPE_CGROUP_SKB:
19484 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
19485 			*range = retval_range(0, 3);
19486 		break;
19487 	case BPF_PROG_TYPE_CGROUP_SOCK:
19488 	case BPF_PROG_TYPE_SOCK_OPS:
19489 	case BPF_PROG_TYPE_CGROUP_DEVICE:
19490 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
19491 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
19492 		break;
19493 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19494 		if (!env->prog->aux->attach_btf_id)
19495 			return false;
19496 		*range = retval_range(0, 0);
19497 		break;
19498 	case BPF_PROG_TYPE_TRACING:
19499 		switch (env->prog->expected_attach_type) {
19500 		case BPF_TRACE_FENTRY:
19501 		case BPF_TRACE_FEXIT:
19502 		case BPF_TRACE_FSESSION:
19503 		case BPF_TRACE_FENTRY_MULTI:
19504 		case BPF_TRACE_FEXIT_MULTI:
19505 		case BPF_TRACE_FSESSION_MULTI:
19506 			*range = retval_range(0, 0);
19507 			break;
19508 		case BPF_TRACE_RAW_TP:
19509 		case BPF_MODIFY_RETURN:
19510 			return false;
19511 		case BPF_TRACE_ITER:
19512 		default:
19513 			break;
19514 		}
19515 		break;
19516 	case BPF_PROG_TYPE_KPROBE:
19517 		switch (env->prog->expected_attach_type) {
19518 		case BPF_TRACE_KPROBE_SESSION:
19519 		case BPF_TRACE_UPROBE_SESSION:
19520 			break;
19521 		default:
19522 			return false;
19523 		}
19524 		break;
19525 	case BPF_PROG_TYPE_SK_LOOKUP:
19526 		*range = retval_range(SK_DROP, SK_PASS);
19527 		break;
19528 
19529 	case BPF_PROG_TYPE_LSM:
19530 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
19531 			/* no range found, any return value is allowed */
19532 			if (!get_func_retval_range(env->prog, range))
19533 				return false;
19534 			/* no restricted range, any return value is allowed */
19535 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
19536 				return false;
19537 			range->return_32bit = true;
19538 		} else if (!env->prog->aux->attach_func_proto->type) {
19539 			/* Make sure programs that attach to void
19540 			 * hooks don't try to modify return value.
19541 			 */
19542 			*range = retval_range(1, 1);
19543 		}
19544 		break;
19545 
19546 	case BPF_PROG_TYPE_NETFILTER:
19547 		*range = retval_range(NF_DROP, NF_ACCEPT);
19548 		break;
19549 	case BPF_PROG_TYPE_STRUCT_OPS:
19550 		*range = retval_range(0, 0);
19551 		break;
19552 	case BPF_PROG_TYPE_EXT:
19553 		/* freplace program can return anything as its return value
19554 		 * depends on the to-be-replaced kernel func or bpf program.
19555 		 */
19556 	default:
19557 		return false;
19558 	}
19559 
19560 	/* Continue calculating. */
19561 
19562 	return true;
19563 }
19564 
19565 static bool program_returns_void(struct bpf_verifier_env *env)
19566 {
19567 	const struct bpf_prog *prog = env->prog;
19568 	enum bpf_prog_type prog_type = prog->type;
19569 
19570 	switch (prog_type) {
19571 	case BPF_PROG_TYPE_LSM:
19572 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
19573 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
19574 		    !prog->aux->attach_func_proto->type)
19575 			return true;
19576 		break;
19577 	case BPF_PROG_TYPE_STRUCT_OPS:
19578 		if (!prog->aux->attach_func_proto->type)
19579 			return true;
19580 		break;
19581 	case BPF_PROG_TYPE_EXT:
19582 		/*
19583 		 * If the actual program is an extension, let it
19584 		 * return void - attaching will succeed only if the
19585 		 * program being replaced also returns void, and since
19586 		 * it has passed verification its actual type doesn't matter.
19587 		 */
19588 		if (subprog_returns_void(env, 0))
19589 			return true;
19590 		break;
19591 	default:
19592 		break;
19593 	}
19594 	return false;
19595 }
19596 
19597 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
19598 {
19599 	const char *exit_ctx = "At program exit";
19600 	struct tnum enforce_attach_type_range = tnum_unknown;
19601 	const struct bpf_prog *prog = env->prog;
19602 	struct bpf_reg_state *reg = reg_state(env, regno);
19603 	struct bpf_retval_range range = retval_range(0, 1);
19604 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
19605 	struct bpf_func_state *frame = env->cur_state->frame[0];
19606 	const struct btf_type *reg_type, *ret_type = NULL;
19607 	int err;
19608 
19609 	/* LSM and struct_ops func-ptr's return type could be "void" */
19610 	if (!frame->in_async_callback_fn && program_returns_void(env))
19611 		return 0;
19612 
19613 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
19614 		/* Allow a struct_ops program to return a referenced kptr if it
19615 		 * matches the operator's return type and is in its unmodified
19616 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
19617 		 */
19618 		reg_type = base_type(reg->type) == PTR_TO_BTF_ID ?
19619 			   btf_type_by_id(reg->btf, reg->btf_id) : NULL;
19620 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
19621 						prog->aux->attach_func_proto->type,
19622 						NULL);
19623 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
19624 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
19625 	}
19626 
19627 	/* eBPF calling convention is such that R0 is used
19628 	 * to return the value from eBPF program.
19629 	 * Make sure that it's readable at this time
19630 	 * of bpf_exit, which means that program wrote
19631 	 * something into it earlier
19632 	 */
19633 	err = check_reg_arg(env, regno, SRC_OP);
19634 	if (err)
19635 		return err;
19636 
19637 	if (is_pointer_value(env, regno)) {
19638 		verbose(env, "R%d leaks addr as return value\n", regno);
19639 		return -EACCES;
19640 	}
19641 
19642 	if (frame->in_async_callback_fn) {
19643 		exit_ctx = "At async callback return";
19644 		range = frame->callback_ret_range;
19645 		goto enforce_retval;
19646 	}
19647 
19648 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
19649 		return 0;
19650 
19651 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
19652 		enforce_attach_type_range = tnum_range(2, 3);
19653 
19654 	if (!return_retval_range(env, &range))
19655 		return 0;
19656 
19657 enforce_retval:
19658 	if (reg->type != SCALAR_VALUE) {
19659 		verbose(env, "%s the register R%d is not a known value (%s)\n",
19660 			exit_ctx, regno, reg_type_str(env, reg->type));
19661 		return -EINVAL;
19662 	}
19663 
19664 	err = mark_chain_precision(env, regno);
19665 	if (err)
19666 		return err;
19667 
19668 	if (!retval_range_within(range, reg)) {
19669 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
19670 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
19671 		    prog_type == BPF_PROG_TYPE_LSM &&
19672 		    !prog->aux->attach_func_proto->type)
19673 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
19674 		return -EINVAL;
19675 	}
19676 
19677 	if (!tnum_is_unknown(enforce_attach_type_range) &&
19678 	    tnum_in(enforce_attach_type_range, reg->var_off))
19679 		env->prog->enforce_expected_attach_type = 1;
19680 	return 0;
19681 }
19682 
19683 static int check_global_ret_scalar_reg(struct bpf_verifier_env *env, u32 regno)
19684 {
19685 	struct bpf_reg_state *reg;
19686 	int err;
19687 
19688 	err = check_reg_arg(env, regno, SRC_OP);
19689 	if (err)
19690 		return err;
19691 
19692 	/* Pointers to arena are safe to pass between subprograms. */
19693 	if (is_arena_reg(env, regno))
19694 		return 0;
19695 
19696 	if (is_pointer_value(env, regno)) {
19697 		verbose(env, "R%d leaks addr as return value\n", regno);
19698 		return -EACCES;
19699 	}
19700 
19701 	reg = reg_state(env, regno);
19702 	if (reg->type != SCALAR_VALUE) {
19703 		verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
19704 			regno, reg_type_str(env, reg->type));
19705 		return -EINVAL;
19706 	}
19707 
19708 	return 0;
19709 }
19710 
19711 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
19712 {
19713 	struct bpf_func_state *cur_frame = cur_func(env);
19714 	u32 subprog = cur_frame->subprogno;
19715 	u32 i, nregs;
19716 	int err;
19717 
19718 	if (subprog_returns_void(env, subprog))
19719 		return 0;
19720 
19721 	nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
19722 	for (i = 0; i < nregs; i++) {
19723 		err = check_global_ret_scalar_reg(env, ret_regs[i]);
19724 		if (err)
19725 			return err;
19726 	}
19727 
19728 	return 0;
19729 }
19730 
19731 /* Bitmask with 1s for all caller saved registers */
19732 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
19733 
19734 /* True if do_misc_fixups() replaces calls to helper number 'imm',
19735  * replacement patch is presumed to follow bpf_fastcall contract
19736  * (see mark_fastcall_pattern_for_call() below).
19737  */
19738 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
19739 {
19740 	switch (imm) {
19741 #ifdef CONFIG_X86_64
19742 	case BPF_FUNC_get_smp_processor_id:
19743 #ifdef CONFIG_SMP
19744 	case BPF_FUNC_get_current_task_btf:
19745 	case BPF_FUNC_get_current_task:
19746 #endif
19747 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
19748 #endif
19749 	default:
19750 		return false;
19751 	}
19752 }
19753 
19754 /* If @call is a kfunc or helper call, fills @cs and returns true,
19755  * otherwise returns false.
19756  */
19757 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
19758 			  struct bpf_call_summary *cs)
19759 {
19760 	struct bpf_call_arg_meta meta;
19761 	const struct bpf_func_proto *fn;
19762 	int i;
19763 
19764 	if (bpf_helper_call(call)) {
19765 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
19766 			/* error would be reported later */
19767 			return false;
19768 		cs->fastcall = fn->allow_fastcall &&
19769 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
19770 				bpf_jit_inlines_helper_call(call->imm));
19771 		cs->is_void = fn->ret_type == RET_VOID;
19772 		cs->arg_slot_cnt = 0;
19773 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
19774 			if (fn->arg_type[i] == ARG_UNUSED)
19775 				break;
19776 			cs->arg_slot_cnt++;
19777 		}
19778 		return true;
19779 	}
19780 
19781 	if (bpf_pseudo_kfunc_call(call)) {
19782 		int err;
19783 
19784 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
19785 		if (err < 0)
19786 			/* error would be reported later */
19787 			return false;
19788 		cs->arg_slot_cnt = btf_proto_slots(meta.btf, meta.func_proto);
19789 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
19790 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
19791 		return true;
19792 	}
19793 
19794 	return false;
19795 }
19796 
19797 /* LLVM define a bpf_fastcall function attribute.
19798  * This attribute means that function scratches only some of
19799  * the caller saved registers defined by ABI.
19800  * For BPF the set of such registers could be defined as follows:
19801  * - R0 is scratched only if function is non-void;
19802  * - R1-R5 are scratched only if corresponding parameter type is defined
19803  *   in the function prototype.
19804  *
19805  * The contract between kernel and clang allows to simultaneously use
19806  * such functions and maintain backwards compatibility with old
19807  * kernels that don't understand bpf_fastcall calls:
19808  *
19809  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
19810  *   registers are not scratched by the call;
19811  *
19812  * - as a post-processing step, clang visits each bpf_fastcall call and adds
19813  *   spill/fill for every live r0-r5;
19814  *
19815  * - stack offsets used for the spill/fill are allocated as lowest
19816  *   stack offsets in whole function and are not used for any other
19817  *   purposes;
19818  *
19819  * - when kernel loads a program, it looks for such patterns
19820  *   (bpf_fastcall function surrounded by spills/fills) and checks if
19821  *   spill/fill stack offsets are used exclusively in fastcall patterns;
19822  *
19823  * - if so, and if verifier or current JIT inlines the call to the
19824  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
19825  *   spill/fill pairs;
19826  *
19827  * - when old kernel loads a program, presence of spill/fill pairs
19828  *   keeps BPF program valid, albeit slightly less efficient.
19829  *
19830  * For example:
19831  *
19832  *   r1 = 1;
19833  *   r2 = 2;
19834  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19835  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
19836  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19837  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
19838  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
19839  *   r0 = r1;                            exit;
19840  *   r0 += r2;
19841  *   exit;
19842  *
19843  * The purpose of mark_fastcall_pattern_for_call is to:
19844  * - look for such patterns;
19845  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
19846  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
19847  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
19848  *   at which bpf_fastcall spill/fill stack slots start;
19849  * - update env->subprog_info[*]->keep_fastcall_stack.
19850  *
19851  * The .fastcall_pattern and .fastcall_stack_off are used by
19852  * check_fastcall_stack_contract() to check if every stack access to
19853  * fastcall spill/fill stack slot originates from spill/fill
19854  * instructions, members of fastcall patterns.
19855  *
19856  * If such condition holds true for a subprogram, fastcall patterns could
19857  * be rewritten by remove_fastcall_spills_fills().
19858  * Otherwise bpf_fastcall patterns are not changed in the subprogram
19859  * (code, presumably, generated by an older clang version).
19860  *
19861  * For example, it is *not* safe to remove spill/fill below:
19862  *
19863  *   r1 = 1;
19864  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19865  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19866  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
19867  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
19868  *   r0 += r1;                           exit;
19869  *   exit;
19870  *
19871  * Both uses of the marks assume that a pattern is entered at its first
19872  * spill and thus executes as a unit, hence a pattern is not grown past
19873  * an instruction targeted by a jump.
19874  */
19875 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
19876 					   struct bpf_subprog_info *subprog,
19877 					   int insn_idx, s16 lowest_off)
19878 {
19879 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
19880 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
19881 	u32 clobbered_regs_mask;
19882 	struct bpf_call_summary cs;
19883 	u32 expected_regs_mask;
19884 	s16 off;
19885 	int i;
19886 
19887 	if (!bpf_get_call_summary(env, call, &cs))
19888 		return;
19889 
19890 	/* A bitmask specifying which caller saved registers are clobbered
19891 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
19892 	 * bpf_fastcall contract:
19893 	 * - includes R0 if function is non-void;
19894 	 * - includes R1-R5 if corresponding parameter has is described
19895 	 *   in the function prototype.
19896 	 */
19897 	clobbered_regs_mask = GENMASK(cs.arg_slot_cnt, cs.is_void ? 1 : 0);
19898 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
19899 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
19900 
19901 	/* match pairs of form:
19902 	 *
19903 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
19904 	 * ...
19905 	 * call %[to_be_inlined]
19906 	 * ...
19907 	 * rX = *(u64 *)(r10 - Y)
19908 	 */
19909 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
19910 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
19911 			break;
19912 		/* stx/ldx/call must not be a jump targets, a jump to the first stx is fine */
19913 		if (bpf_is_jump_target(env, insn_idx - i + 1) ||
19914 		    bpf_is_jump_target(env, insn_idx + i))
19915 			break;
19916 		stx = &insns[insn_idx - i];
19917 		ldx = &insns[insn_idx + i];
19918 		/* must be a stack spill/fill pair */
19919 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19920 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
19921 		    stx->dst_reg != BPF_REG_10 ||
19922 		    ldx->src_reg != BPF_REG_10)
19923 			break;
19924 		/* must be a spill/fill for the same reg */
19925 		if (stx->src_reg != ldx->dst_reg)
19926 			break;
19927 		/* must be one of the previously unseen registers */
19928 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
19929 			break;
19930 		/* must be a spill/fill for the same expected offset,
19931 		 * no need to check offset alignment, BPF_DW stack access
19932 		 * is always 8-byte aligned.
19933 		 */
19934 		if (stx->off != off || ldx->off != off)
19935 			break;
19936 		expected_regs_mask &= ~BIT(stx->src_reg);
19937 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
19938 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
19939 	}
19940 	if (i == 1)
19941 		return;
19942 
19943 	/* Conditionally set 'fastcall_spills_num' to allow forward
19944 	 * compatibility when more helper functions are marked as
19945 	 * bpf_fastcall at compile time than current kernel supports, e.g:
19946 	 *
19947 	 *   1: *(u64 *)(r10 - 8) = r1
19948 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
19949 	 *   3: r1 = *(u64 *)(r10 - 8)
19950 	 *   4: *(u64 *)(r10 - 8) = r1
19951 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
19952 	 *   6: r1 = *(u64 *)(r10 - 8)
19953 	 *
19954 	 * There is no need to block bpf_fastcall rewrite for such program.
19955 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
19956 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
19957 	 * does not remove spill/fill pair {4,6}.
19958 	 */
19959 	if (cs.fastcall)
19960 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
19961 	else
19962 		subprog->keep_fastcall_stack = 1;
19963 	/*
19964 	 * The upper end of the longest pattern: no slot of a pattern is above it. Code that never
19965 	 * runs may have a pattern that ends above the frame pointer.
19966 	 */
19967 	subprog->fastcall_stack_off = max(subprog->fastcall_stack_off, min_t(s16, off, 0));
19968 }
19969 
19970 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
19971 {
19972 	struct bpf_subprog_info *subprog = env->subprog_info;
19973 	struct bpf_insn *insn;
19974 	s16 lowest_off;
19975 	int s, i;
19976 
19977 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
19978 		subprog->fastcall_stack_off = S16_MIN;
19979 		/* find lowest stack spill offset used in this subprog */
19980 		lowest_off = 0;
19981 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19982 			insn = env->prog->insnsi + i;
19983 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19984 			    insn->dst_reg != BPF_REG_10)
19985 				continue;
19986 			lowest_off = min(lowest_off, insn->off);
19987 		}
19988 		/* use this offset to find fastcall patterns */
19989 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19990 			insn = env->prog->insnsi + i;
19991 			if (insn->code != (BPF_JMP | BPF_CALL))
19992 				continue;
19993 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
19994 		}
19995 	}
19996 	return 0;
19997 }
19998 
19999 static void adjust_btf_func(struct bpf_verifier_env *env)
20000 {
20001 	struct bpf_prog_aux *aux = env->prog->aux;
20002 	int i;
20003 
20004 	if (!aux->func_info)
20005 		return;
20006 
20007 	/* func_info is not available for hidden subprogs */
20008 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
20009 		aux->func_info[i].insn_off = env->subprog_info[i].start;
20010 }
20011 
20012 /* Find id in idset and increment its count, or add new entry */
20013 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
20014 {
20015 	u32 i;
20016 
20017 	for (i = 0; i < idset->num_ids; i++) {
20018 		if (idset->entries[i].id == id) {
20019 			idset->entries[i].cnt++;
20020 			return;
20021 		}
20022 	}
20023 	/* New id */
20024 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
20025 		idset->entries[idset->num_ids].id = id;
20026 		idset->entries[idset->num_ids].cnt = 1;
20027 		idset->num_ids++;
20028 	}
20029 }
20030 
20031 /* Find id in idset and return its count, or 0 if not found */
20032 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
20033 {
20034 	u32 i;
20035 
20036 	for (i = 0; i < idset->num_ids; i++) {
20037 		if (idset->entries[i].id == id)
20038 			return idset->entries[i].cnt;
20039 	}
20040 	return 0;
20041 }
20042 
20043 /*
20044  * Clear singular scalar ids in a state.
20045  * A register with a non-zero id is called singular if no other register shares
20046  * the same base id. Such registers can be treated as independent (id=0).
20047  */
20048 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
20049 			    struct bpf_verifier_state *st)
20050 {
20051 	struct bpf_idset *idset = &env->idset_scratch;
20052 	struct bpf_func_state *func;
20053 	struct bpf_reg_state *reg;
20054 
20055 	idset->num_ids = 0;
20056 
20057 	bpf_for_each_reg_in_vstate(st, func, reg, ({
20058 		if (reg->type != SCALAR_VALUE)
20059 			continue;
20060 		if (!reg->id)
20061 			continue;
20062 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
20063 	}));
20064 
20065 	bpf_for_each_reg_in_vstate(st, func, reg, ({
20066 		if (reg->type != SCALAR_VALUE)
20067 			continue;
20068 		if (!reg->id)
20069 			continue;
20070 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
20071 			clear_scalar_id(reg);
20072 	}));
20073 }
20074 
20075 /* Return true if it's OK to have the same insn return a different type. */
20076 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20077 {
20078 	switch (base_type(type)) {
20079 	case PTR_TO_CTX:
20080 	case PTR_TO_SOCKET:
20081 	case PTR_TO_SOCK_COMMON:
20082 	case PTR_TO_TCP_SOCK:
20083 	case PTR_TO_XDP_SOCK:
20084 	case PTR_TO_BTF_ID:
20085 	case PTR_TO_ARENA:
20086 		return false;
20087 	case PTR_TO_MEM:
20088 		return !bpf_may_fault_on_deref(type);
20089 	default:
20090 		return true;
20091 	}
20092 }
20093 
20094 /* If an instruction was previously used with particular pointer types, then we
20095  * need to be careful to avoid cases such as the below, where it may be ok
20096  * for one branch accessing the pointer, but not ok for the other branch:
20097  *
20098  * R1 = sock_ptr
20099  * goto X;
20100  * ...
20101  * R1 = some_other_valid_ptr;
20102  * goto X;
20103  * ...
20104  * R2 = *(u32 *)(R1 + 0);
20105  */
20106 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20107 {
20108 	return src != prev && (!reg_type_mismatch_ok(src) ||
20109 			       !reg_type_mismatch_ok(prev));
20110 }
20111 
20112 static bool is_ptr_to_mem(enum bpf_reg_type type)
20113 {
20114 	return base_type(type) == PTR_TO_MEM;
20115 }
20116 
20117 static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a,
20118 					 enum bpf_reg_type type_b)
20119 {
20120 	bool to_mem = is_ptr_to_mem(type_a) || is_ptr_to_mem(type_b);
20121 	enum bpf_reg_type type_merged = to_mem ? PTR_TO_MEM : PTR_TO_BTF_ID;
20122 
20123 	if (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b))
20124 		type_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED :
20125 					PTR_UNTRUSTED;
20126 	else
20127 		type_merged |= ((type_a | type_b) & MEM_RDONLY);
20128 	return type_merged;
20129 }
20130 
20131 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20132 			     bool allow_trust_mismatch)
20133 {
20134 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20135 
20136 	if (*prev_type == NOT_INIT) {
20137 		/* Saw a valid insn
20138 		 * dst_reg = *(u32 *)(src_reg + off)
20139 		 * save type to validate intersecting paths
20140 		 */
20141 		*prev_type = type;
20142 	} else if (reg_type_mismatch(type, *prev_type)) {
20143 		/* Abuser program is trying to use the same insn
20144 		 * dst_reg = *(u32*) (src_reg + off)
20145 		 * with different pointer types:
20146 		 * src_reg == ctx in one branch and
20147 		 * src_reg == stack|map in some other branch.
20148 		 * Reject it.
20149 		 */
20150 		if (allow_trust_mismatch &&
20151 		    bpf_is_ptr_to_mem_or_btf_id(type) &&
20152 		    bpf_is_ptr_to_mem_or_btf_id(*prev_type)) {
20153 			/*
20154 			 * Have to support a use case when one path through
20155 			 * the program yields a TRUSTED pointer while another
20156 			 * is UNTRUSTED. Merge them into a type which keeps
20157 			 * the BPF_PROBE_MEM/BPF_PROBE_MEMSX rewrite when
20158 			 * either side needs it.
20159 			 */
20160 			*prev_type = merge_ptr_types(type, *prev_type);
20161 		} else {
20162 			verbose(env, "same insn cannot be used with different pointers\n");
20163 			return -EINVAL;
20164 		}
20165 	}
20166 
20167 	return 0;
20168 }
20169 
20170 enum {
20171 	PROCESS_BPF_EXIT = 1,
20172 	INSN_IDX_UPDATED = 2,
20173 };
20174 
20175 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20176 				 bool *do_print_state,
20177 				 bool exception_exit)
20178 {
20179 	struct bpf_func_state *cur_frame = cur_func(env);
20180 
20181 	/* We must do check_reference_leak here before
20182 	 * prepare_func_exit to handle the case when
20183 	 * state->curframe > 0, it may be a callback function,
20184 	 * for which reference_state must match caller reference
20185 	 * state when it exits.
20186 	 */
20187 	int err = check_resource_leak(env, exception_exit,
20188 				      exception_exit || !env->cur_state->curframe,
20189 				      exception_exit ? "bpf_throw" :
20190 				      "BPF_EXIT instruction in main prog");
20191 	if (err)
20192 		return err;
20193 
20194 	/* The side effect of the prepare_func_exit which is
20195 	 * being skipped is that it frees bpf_func_state.
20196 	 * Typically, process_bpf_exit will only be hit with
20197 	 * outermost exit. copy_verifier_state in pop_stack will
20198 	 * handle freeing of any extra bpf_func_state left over
20199 	 * from not processing all nested function exits. We
20200 	 * also skip return code checks as they are not needed
20201 	 * for exceptional exits.
20202 	 */
20203 	if (exception_exit)
20204 		return PROCESS_BPF_EXIT;
20205 
20206 	if (env->cur_state->curframe) {
20207 		/* exit from nested function */
20208 		err = prepare_func_exit(env, &env->insn_idx);
20209 		if (err)
20210 			return err;
20211 		*do_print_state = true;
20212 		return INSN_IDX_UPDATED;
20213 	}
20214 
20215 	/*
20216 	 * Return from a regular global subprogram differs from return
20217 	 * from the main program or async/exception callback.
20218 	 * Main program exit implies return code restrictions
20219 	 * that depend on program type.
20220 	 * Exit from exception callback is equivalent to main program exit.
20221 	 * Exit from async callback implies return code restrictions
20222 	 * that depend on async scheduling mechanism.
20223 	 */
20224 	if (cur_frame->subprogno &&
20225 	    !cur_frame->in_async_callback_fn &&
20226 	    !cur_frame->in_exception_callback_fn)
20227 		err = check_global_subprog_return_code(env);
20228 	else
20229 		err = check_return_code(env, BPF_REG_0, "R0");
20230 	if (err)
20231 		return err;
20232 	return PROCESS_BPF_EXIT;
20233 }
20234 
20235 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20236 				       int regno,
20237 				       struct bpf_map *map,
20238 				       u32 *pmin_index, u32 *pmax_index)
20239 {
20240 	struct bpf_reg_state *reg = reg_state(env, regno);
20241 	u64 min_index = reg_umin(reg);
20242 	u64 max_index = reg_umax(reg);
20243 	const u32 size = 8;
20244 
20245 	if (min_index > (u64) U32_MAX * size) {
20246 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
20247 		return -ERANGE;
20248 	}
20249 	if (max_index > (u64) U32_MAX * size) {
20250 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
20251 		return -ERANGE;
20252 	}
20253 
20254 	min_index /= size;
20255 	max_index /= size;
20256 
20257 	if (max_index >= map->max_entries) {
20258 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20259 			     regno, min_index, max_index, map->max_entries);
20260 		return -EINVAL;
20261 	}
20262 
20263 	*pmin_index = min_index;
20264 	*pmax_index = max_index;
20265 	return 0;
20266 }
20267 
20268 static int reject_gotox_out_of_subprog(struct bpf_verifier_env *env, u32 target,
20269 				       u32 subprog_start, u32 subprog_end)
20270 {
20271 	verbose(env, "indirect jump from insn %d to %u leaves the subprog [%u,%u)\n",
20272 		env->insn_idx, target, subprog_start, subprog_end);
20273 	bpf_diag_program_structure(
20274 		env, env->insn_idx, "indirect jump leaves subprogram",
20275 		"Keep every reachable jump-table target inside the subprogram of the indirect jump.",
20276 		"Instruction %d can jump indirectly to instruction %u, which is outside its own subprogram [%u,%u).",
20277 		env->insn_idx, target, subprog_start, subprog_end);
20278 	return -EINVAL;
20279 }
20280 
20281 /* gotox *dst_reg */
20282 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20283 {
20284 	struct bpf_verifier_state *other_branch;
20285 	struct bpf_subprog_info *subprog;
20286 	u32 subprog_start, subprog_end;
20287 	struct bpf_reg_state *dst_reg;
20288 	struct bpf_map *map;
20289 	u32 min_index, max_index;
20290 	int err = 0;
20291 	int n;
20292 	int i;
20293 
20294 	dst_reg = reg_state(env, insn->dst_reg);
20295 	if (dst_reg->type != PTR_TO_INSN) {
20296 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20297 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20298 		return -EINVAL;
20299 	}
20300 
20301 	map = dst_reg->map_ptr;
20302 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20303 		return -EFAULT;
20304 
20305 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20306 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20307 		return -EFAULT;
20308 
20309 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20310 	if (err)
20311 		return err;
20312 
20313 	/* Ensure that the buffer is large enough */
20314 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20315 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
20316 						        max_index - min_index + 1);
20317 		if (!env->gotox_tmp_buf)
20318 			return -ENOMEM;
20319 	}
20320 
20321 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20322 	if (n < 0)
20323 		return n;
20324 	if (n == 0) {
20325 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20326 			     insn->dst_reg, map->id);
20327 		return -EINVAL;
20328 	}
20329 
20330 	subprog = bpf_find_containing_subprog(env, env->insn_idx);
20331 	if (verifier_bug_if(!subprog, env, "no subprog contains insn %d", env->insn_idx))
20332 		return -EFAULT;
20333 	subprog_start = subprog->start;
20334 	subprog_end = (subprog + 1)->start;
20335 
20336 	/*
20337 	 * Maps are confined to a subprog, see compute_subprog_jts(), and the
20338 	 * targets are sorted and free of duplicates, see sort_insn_array_uniq(),
20339 	 * so either all of them belong to this subprog or none of them does.
20340 	 */
20341 	if (env->gotox_tmp_buf->items[0] < subprog_start)
20342 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[0],
20343 						   subprog_start, subprog_end);
20344 	if (env->gotox_tmp_buf->items[n - 1] >= subprog_end)
20345 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[n - 1],
20346 						   subprog_start, subprog_end);
20347 
20348 	for (i = 0; i < n - 1; i++) {
20349 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
20350 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20351 					  env->insn_idx, env->cur_state->speculative);
20352 		if (IS_ERR(other_branch))
20353 			return PTR_ERR(other_branch);
20354 	}
20355 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20356 	mark_indirect_target(env, env->insn_idx);
20357 	return INSN_IDX_UPDATED;
20358 }
20359 
20360 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20361 {
20362 	int err;
20363 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20364 	u8 class = BPF_CLASS(insn->code);
20365 
20366 	switch (class) {
20367 	case BPF_ALU:
20368 	case BPF_ALU64:
20369 		return check_alu_op(env, insn);
20370 
20371 	case BPF_LDX:
20372 		return check_load_mem(env, insn, false,
20373 				      BPF_MODE(insn->code) == BPF_MEMSX,
20374 				      true, "ldx");
20375 
20376 	case BPF_STX:
20377 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
20378 			return check_atomic(env, insn);
20379 		return check_store_reg(env, insn, false);
20380 
20381 	case BPF_ST: {
20382 		/* Handle stack arg write (store immediate) */
20383 		if (is_stack_arg_st(insn)) {
20384 			struct bpf_verifier_state *vstate = env->cur_state;
20385 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
20386 
20387 			return check_stack_arg_write(env, state, insn->off, NULL);
20388 		}
20389 
20390 		enum bpf_reg_type dst_reg_type;
20391 
20392 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20393 		if (err)
20394 			return err;
20395 
20396 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
20397 
20398 		err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg,
20399 				       argno_from_reg(insn->dst_reg),
20400 				       insn->off, BPF_SIZE(insn->code),
20401 				       BPF_WRITE, -1, false, false);
20402 		if (err)
20403 			return err;
20404 
20405 		return save_aux_ptr_type(env, dst_reg_type, false);
20406 	}
20407 	case BPF_JMP:
20408 	case BPF_JMP32: {
20409 		u8 opcode = BPF_OP(insn->code);
20410 
20411 		env->jmps_processed++;
20412 		if (opcode == BPF_CALL) {
20413 			if (env->cur_state->active_locks) {
20414 				/* similar to static subprog calls callx is allowed under a lock */
20415 				if (!bpf_is_callx(insn) &&
20416 				    ((insn->src_reg == BPF_REG_0 &&
20417 				      insn->imm != BPF_FUNC_spin_unlock &&
20418 				      insn->imm != BPF_FUNC_kptr_xchg) ||
20419 				     (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20420 				      !kfunc_spin_allowed(env, insn->imm, insn->off)))) {
20421 					verbose(env,
20422 						"function calls are not allowed while holding a lock\n");
20423 					bpf_diag_ctx_active(
20424 						env, env->insn_idx,
20425 						"function call", BPF_DIAG_CONTEXT_LOCK,
20426 						"Release the BPF spin lock before making this call, or move the call outside the locked region.");
20427 					return -EINVAL;
20428 				}
20429 			}
20430 			mark_reg_scratched(env, BPF_REG_0);
20431 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
20432 				cur_func(env)->no_stack_arg_load = true;
20433 			if (bpf_is_callx(insn))
20434 				return check_func_callx(env, insn, &env->insn_idx);
20435 			if (insn->src_reg == BPF_PSEUDO_CALL)
20436 				return check_func_call(env, insn, &env->insn_idx);
20437 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
20438 				return check_kfunc_call(env, insn, &env->insn_idx);
20439 			return check_helper_call(env, insn, &env->insn_idx);
20440 		} else if (opcode == BPF_JA) {
20441 			if (BPF_SRC(insn->code) == BPF_X)
20442 				return check_indirect_jump(env, insn);
20443 
20444 			if (class == BPF_JMP)
20445 				env->insn_idx += insn->off + 1;
20446 			else
20447 				env->insn_idx += insn->imm + 1;
20448 			return INSN_IDX_UPDATED;
20449 		} else if (opcode == BPF_EXIT) {
20450 			return process_bpf_exit_full(env, do_print_state, false);
20451 		}
20452 		return check_cond_jmp_op(env, insn, &env->insn_idx);
20453 	}
20454 	case BPF_LD: {
20455 		u8 mode = BPF_MODE(insn->code);
20456 
20457 		if (mode == BPF_ABS || mode == BPF_IND)
20458 			return check_ld_abs(env, insn);
20459 
20460 		if (mode == BPF_IMM) {
20461 			err = check_ld_imm(env, insn);
20462 			if (err)
20463 				return err;
20464 
20465 			env->insn_idx++;
20466 			sanitize_mark_insn_seen(env);
20467 		}
20468 		return 0;
20469 	}
20470 	}
20471 	/* all class values are handled above. silence compiler warning */
20472 	return -EFAULT;
20473 }
20474 
20475 /*
20476  * Push the loop entered at insn_idx onto the stack. Usually this adds a single
20477  * entry on top of its enclosing loop. However, an edge may enter an inner loop
20478  * directly, bypassing the header(s) of its enclosing loop(s), e.g.:
20479  *
20480  *   1: for (...):       // enclosing loop, header at 1
20481  *   2:   for (...):     // inner loop, header at 2
20482  *        ...
20483  *   3: if ...:
20484  *        goto 2b;       // enters loop 2 without going through header 1
20485  *
20486  * Such a bypass makes the enclosing loop irreducible, so its header is missing
20487  * from the stack and both headers (1) and (2) need to be pushed onto stack.
20488  * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
20489  * the bypassed ancestors are irreducible and pushed as non-terminating.
20490  *
20491  * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
20492  * of the bpf_loop_at_index(env->insn_idx) and whatever was at the top of the loop stack.
20493  */
20494 static int loop_stack_push(struct bpf_verifier_env *env, bool *pushed)
20495 {
20496 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20497 	struct bpf_func_state *frame = cur_func(env);
20498 	struct loop_stack_entry *loop_stack = frame->loop_stack;
20499 	u32 missing_headers[LOOP_STACK_SIZE];
20500 	u32 cnt = frame->loop_stack_cnt;
20501 	u32 num_missing = 0;
20502 	int h;
20503 
20504 	*pushed = false;
20505 
20506 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
20507 		if (cnt && loop_stack[cnt - 1].loop_id == h)
20508 			break;
20509 		if (num_missing == LOOP_STACK_SIZE)
20510 			goto e2big;
20511 		missing_headers[num_missing] = h;
20512 	}
20513 
20514 	if (num_missing == 0)
20515 		return 0;
20516 	if (cnt + num_missing > LOOP_STACK_SIZE)
20517 		goto e2big;
20518 	frame->loop_stack = realloc_array(frame->loop_stack, cnt, cnt + num_missing,
20519 					 sizeof(*frame->loop_stack));
20520 	if (!frame->loop_stack)
20521 		return -ENOMEM;
20522 	loop_stack = frame->loop_stack;
20523 
20524 	for (; num_missing; num_missing--, cnt++) {
20525 		h = missing_headers[num_missing - 1];
20526 		loop_stack[cnt] = (struct loop_stack_entry){ .loop_id = h };
20527 		if (env->log.level & BPF_LOG_LEVEL2)
20528 			verbose(env, "entering loop %d\n", h);
20529 		*pushed = true;
20530 	}
20531 	frame->loop_stack_cnt = cnt;
20532 	return 0;
20533 
20534 e2big:
20535 	verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
20536 	return -E2BIG;
20537 }
20538 
20539 /*
20540  * An exit from a loop can cross several nested loops, e.g.:
20541  *
20542  *   1: for (...):
20543  *   2:   for (...):
20544  *   3:     for (...):
20545  *            if ...:    // before goto the loop stack is [1, 2, 3 <top>]
20546  *              goto 1b; // after goto it should become [1]
20547  */
20548 static int loop_stack_pop(struct bpf_verifier_env *env)
20549 {
20550 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20551 	struct bpf_func_state *frame = cur_func(env);
20552 	int new_cnt = 0;
20553 	int h, i;
20554 
20555 	/*
20556 	 * Walk the loop nest of insn_idx outwards (innermost first) and stop at
20557 	 * the first loop that is present on the stack - that loop is the common
20558 	 * ancestor and becomes the new top. If no enclosing loop is on the
20559 	 * stack, drop all loops.
20560 	 */
20561 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
20562 		for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
20563 			if (frame->loop_stack[i].loop_id == h) {
20564 				new_cnt = i + 1;
20565 				goto pop;
20566 			}
20567 		}
20568 	}
20569 
20570 pop:
20571 	if (env->log.level & BPF_LOG_LEVEL2)
20572 		for (i = frame->loop_stack_cnt - 1; i >= new_cnt; i--)
20573 			verbose(env, "exiting loop %d\n", frame->loop_stack[i].loop_id);
20574 	frame->loop_stack_cnt = new_cnt;
20575 	return 0;
20576 }
20577 
20578 static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
20579 {
20580 	struct bpf_func_state *frame = cur_func(env);
20581 	struct loop_stack_entry *entry;
20582 
20583 	if (frame->loop_stack_cnt == 0) {
20584 		verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
20585 		return -EFAULT;
20586 	}
20587 
20588 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20589 	if (!entry->terminates)
20590 		return 0;
20591 
20592 	return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state,
20593 				   entry->max_header_count);
20594 }
20595 
20596 static int handle_loop_entry_exit(struct bpf_verifier_env *env)
20597 {
20598 	struct bpf_verifier_state *cur = env->cur_state;
20599 	struct bpf_func_state *frame = cur_func(env);
20600 	struct loop_stack_entry *entry;
20601 	struct bpf_loop_iters iters;
20602 	bool pushed, terminates;
20603 	int err;
20604 
20605 	err = loop_stack_pop(env);
20606 	if (err)
20607 		return err;
20608 
20609 	err = loop_stack_push(env, &pushed);
20610 	if (err)
20611 		return err;
20612 
20613 	if (frame->loop_stack_cnt == 0)
20614 		return 0;
20615 
20616 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20617 	if (env->insn_idx != entry->loop_id)
20618 		return 0;
20619 
20620 	/* If nothing was pushed and env->insn_idx is a loop header, we've taken a backedge. */
20621 	if (!pushed)
20622 		return maybe_clamp_scev_regs(env);
20623 
20624 	err = bpf_compute_loop_iters(env, env->cur_state, &iters);
20625 	if (err < 0)
20626 		return err;
20627 
20628 	terminates = err == 1;
20629 	if (!terminates)
20630 		return 0;
20631 
20632 	/* Create a loop_entry checkpoint before widening */
20633 	err = bpf_split_cur_state(env);
20634 	if (err)
20635 		return err;
20636 
20637 	entry->min_header_count = iters.min_header_count;
20638 	entry->max_header_count = iters.max_header_count;
20639 	entry->entry_state = cur->parent;
20640 	entry->terminates = true;
20641 	err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
20642 	if (err < 0)
20643 		return err;
20644 	return 0;
20645 }
20646 
20647 static int do_check(struct bpf_verifier_env *env)
20648 {
20649 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20650 	struct bpf_verifier_state *state = env->cur_state;
20651 	struct bpf_insn *insns = env->prog->insnsi;
20652 	int insn_cnt = env->prog->len;
20653 	bool do_print_state = false;
20654 	int prev_insn_idx = -1;
20655 
20656 	for (;;) {
20657 		struct bpf_insn *insn;
20658 		struct bpf_insn_aux_data *insn_aux;
20659 		int err, ctx_field_size;
20660 		bool nospec_result;
20661 
20662 		if (signal_pending(current))
20663 			return -EAGAIN;
20664 
20665 		cond_resched_tasks_rcu_qs();
20666 
20667 		/* reset current history entry on each new instruction */
20668 		env->cur_hist_ent = NULL;
20669 
20670 		env->prev_insn_idx = prev_insn_idx;
20671 		if (env->insn_idx >= insn_cnt) {
20672 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20673 				env->insn_idx, insn_cnt);
20674 			return -EFAULT;
20675 		}
20676 
20677 		insn = &insns[env->insn_idx];
20678 		insn_aux = &env->insn_aux_data[env->insn_idx];
20679 
20680 		account_processed_insn(env);
20681 
20682 		if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20683 			verbose(env,
20684 				"BPF program is too large. Processed %d insn\n",
20685 				env->insn_processed);
20686 			return -E2BIG;
20687 		}
20688 
20689 		state->last_insn_idx = env->prev_insn_idx;
20690 		state->insn_idx = env->insn_idx;
20691 		/*
20692 		 * Record the incoming edge so active and queued paths use the same
20693 		 * branch-recording path. A zero-offset conditional has identical
20694 		 * successors, so its outcome cannot be reconstructed from the edge.
20695 		 */
20696 		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
20697 			struct bpf_insn *prev_insn = &insns[prev_insn_idx];
20698 			int fallthrough_idx = prev_insn_idx + 1;
20699 			int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1;
20700 			u8 class = BPF_CLASS(prev_insn->code);
20701 			u8 opcode = BPF_OP(prev_insn->code);
20702 
20703 			if ((class == BPF_JMP || class == BPF_JMP32) &&
20704 			    opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT &&
20705 			    opcode <= BPF_JCOND && branch_idx != fallthrough_idx) {
20706 				if (env->insn_idx == branch_idx)
20707 					bpf_diag_record_branch(env, prev_insn_idx, true);
20708 				else if (env->insn_idx == fallthrough_idx)
20709 					bpf_diag_record_branch(env, prev_insn_idx, false);
20710 			}
20711 		}
20712 
20713 		/*
20714 		 * Possibly widen the registers before creating a checkpoint
20715 		 * in bpf_is_state_visited(). The next loop iteration will
20716 		 * have a chance to hit this checkpoint and converge.
20717 		 */
20718 		err = handle_loop_entry_exit(env);
20719 		if (err)
20720 			return err;
20721 
20722 		if (bpf_is_prune_point(env, env->insn_idx)) {
20723 			err = bpf_is_state_visited(env, env->insn_idx);
20724 			if (err < 0)
20725 				return err;
20726 			if (err == 1) {
20727 				/* found equivalent state, can prune the search */
20728 				if (env->log.level & BPF_LOG_LEVEL) {
20729 					if (do_print_state)
20730 						verbose(env, "\nfrom %d to %d%s: safe\n",
20731 							env->prev_insn_idx, env->insn_idx,
20732 							env->cur_state->speculative ?
20733 							" (speculative execution)" : "");
20734 					else
20735 						verbose(env, "%d: safe\n", env->insn_idx);
20736 				}
20737 				goto process_bpf_exit;
20738 			}
20739 		}
20740 
20741 		if (bpf_is_jmp_point(env, env->insn_idx)) {
20742 			err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
20743 			if (err)
20744 				return err;
20745 		}
20746 
20747 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20748 			verbose(env, "\nfrom %d to %d%s:",
20749 				env->prev_insn_idx, env->insn_idx,
20750 				env->cur_state->speculative ?
20751 				" (speculative execution)" : "");
20752 			print_verifier_state(env, state, state->curframe, true);
20753 			do_print_state = false;
20754 		}
20755 
20756 		if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
20757 		    cur_func(env)->loop_stack_cnt == 0) {
20758 			verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
20759 				     env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
20760 			return -EFAULT;
20761 		}
20762 
20763 		if (env->log.level & BPF_LOG_LEVEL) {
20764 			if (verifier_state_scratched(env))
20765 				print_insn_state(env, state, state->curframe);
20766 
20767 			verbose_linfo(env, env->insn_idx, "; ");
20768 			env->prev_log_pos = env->log.end_pos;
20769 			verbose(env, "%d: ", env->insn_idx);
20770 			bpf_verbose_insn(env, insn);
20771 			verbose(env, "\n");
20772 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20773 			env->prev_log_pos = env->log.end_pos;
20774 		}
20775 
20776 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20777 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20778 							   env->prev_insn_idx);
20779 			if (err)
20780 				return err;
20781 		}
20782 
20783 		sanitize_mark_insn_seen(env);
20784 		prev_insn_idx = env->insn_idx;
20785 
20786 		/* Sanity check: precomputed constants must match verifier state */
20787 		if (!state->speculative && insn_aux->const_reg_mask) {
20788 			struct bpf_reg_state *regs = cur_regs(env);
20789 			u16 mask = insn_aux->const_reg_mask;
20790 
20791 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
20792 				u32 cval = insn_aux->const_reg_vals[r];
20793 
20794 				if (!(mask & BIT(r)))
20795 					continue;
20796 				if (regs[r].type != SCALAR_VALUE)
20797 					continue;
20798 				if (!tnum_is_const(regs[r].var_off))
20799 					continue;
20800 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
20801 						    env, "const R%d: %u != %llu",
20802 						    r, cval, regs[r].var_off.value))
20803 					return -EFAULT;
20804 			}
20805 		}
20806 
20807 		/* Reduce verification complexity by stopping speculative path
20808 		 * verification when a nospec is encountered.
20809 		 */
20810 		if (state->speculative && insn_aux->nospec)
20811 			goto process_bpf_exit;
20812 
20813 		nospec_result = insn_aux->nospec_result;
20814 		ctx_field_size = insn_aux->ctx_field_size;
20815 		err = do_check_insn(env, &do_print_state);
20816 		if (error_recoverable_with_nospec(err) && state->speculative) {
20817 			/* Prevent this speculative path from ever reaching the
20818 			 * insn that would have been unsafe to execute.
20819 			 */
20820 			insn_aux->nospec = true;
20821 			/* If it was an ADD/SUB insn, potentially remove any
20822 			 * markings for alu sanitization.
20823 			 */
20824 			insn_aux->alu_state = 0;
20825 			insn_aux->nospec_result = nospec_result;
20826 			insn_aux->ctx_field_size = ctx_field_size;
20827 			goto process_bpf_exit;
20828 		} else if (err < 0) {
20829 			return err;
20830 		} else if (err == PROCESS_BPF_EXIT) {
20831 			goto process_bpf_exit;
20832 		} else if (err == INSN_IDX_UPDATED) {
20833 		} else if (err == 0) {
20834 			env->insn_idx++;
20835 		}
20836 
20837 		if (state->speculative && insn_aux->nospec_result) {
20838 			/* If we are on a path that performed a jump-op, this
20839 			 * may skip a nospec patched-in after the jump. This can
20840 			 * currently never happen because nospec_result is only
20841 			 * used for the write-ops
20842 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
20843 			 * calls. These must never skip the following insn
20844 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
20845 			 * is false). Still, add a warning to document this in
20846 			 * case nospec_result is used elsewhere in the future.
20847 			 *
20848 			 * All non-branch instructions have a single
20849 			 * fall-through edge. For these, nospec_result should
20850 			 * already work.
20851 			 */
20852 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
20853 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
20854 					    BPF_OP(insn->code) != BPF_CALL, env,
20855 					    "speculation barrier after jump instruction may not have the desired effect"))
20856 				return -EFAULT;
20857 process_bpf_exit:
20858 			account_current_path(env);
20859 			mark_verifier_state_scratched(env);
20860 			err = bpf_update_branch_counts(env, env->cur_state);
20861 			if (err)
20862 				return err;
20863 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20864 					pop_log);
20865 			if (err < 0) {
20866 				if (err != -ENOENT)
20867 					return err;
20868 				break;
20869 			} else {
20870 				do_print_state = true;
20871 				continue;
20872 			}
20873 		}
20874 	}
20875 
20876 	return 0;
20877 }
20878 
20879 static int find_btf_percpu_datasec(struct btf *btf)
20880 {
20881 	const struct btf_type *t;
20882 	const char *tname;
20883 	int i, n;
20884 
20885 	/*
20886 	 * Both vmlinux and module each have their own ".data..percpu"
20887 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20888 	 * types to look at only module's own BTF types.
20889 	 */
20890 	n = btf_nr_types(btf);
20891 	for (i = btf_named_start_id(btf, true); i < n; i++) {
20892 		t = btf_type_by_id(btf, i);
20893 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20894 			continue;
20895 
20896 		tname = btf_name_by_offset(btf, t->name_off);
20897 		if (!strcmp(tname, ".data..percpu"))
20898 			return i;
20899 	}
20900 
20901 	return -ENOENT;
20902 }
20903 
20904 /*
20905  * Add btf to the env->used_btfs array. If needed, refcount the
20906  * corresponding kernel module. To simplify caller's logic
20907  * in case of error or if btf was added before the function
20908  * decreases the btf refcount.
20909  */
20910 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20911 {
20912 	struct btf_mod_pair *btf_mod;
20913 	int ret = 0;
20914 	int i;
20915 
20916 	/* check whether we recorded this BTF (and maybe module) already */
20917 	for (i = 0; i < env->used_btf_cnt; i++)
20918 		if (env->used_btfs[i].btf == btf)
20919 			goto ret_put;
20920 
20921 	if (env->signature) {
20922 		verbose(env, "signed program cannot bind any BTF\n");
20923 		ret = -EACCES;
20924 		goto ret_put;
20925 	}
20926 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20927 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20928 			MAX_USED_BTFS);
20929 		ret = -E2BIG;
20930 		goto ret_put;
20931 	}
20932 
20933 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20934 	btf_mod->btf = btf;
20935 	btf_mod->module = NULL;
20936 
20937 	/* if we reference variables from kernel module, bump its refcount */
20938 	if (btf_is_module(btf)) {
20939 		btf_mod->module = btf_try_get_module(btf);
20940 		if (!btf_mod->module) {
20941 			ret = -ENXIO;
20942 			goto ret_put;
20943 		}
20944 	}
20945 
20946 	env->used_btf_cnt++;
20947 	return 0;
20948 
20949 ret_put:
20950 	/* Either error or this BTF was already added */
20951 	btf_put(btf);
20952 	return ret;
20953 }
20954 
20955 /* replace pseudo btf_id with kernel symbol address */
20956 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20957 				 struct bpf_insn *insn,
20958 				 struct bpf_insn_aux_data *aux,
20959 				 struct btf *btf)
20960 {
20961 	const struct btf_var_secinfo *vsi;
20962 	const struct btf_type *datasec;
20963 	const struct btf_type *t;
20964 	const char *sym_name;
20965 	bool percpu = false;
20966 	u32 type, id = insn->imm;
20967 	s32 datasec_id;
20968 	u64 addr;
20969 	int i;
20970 
20971 	t = btf_type_by_id(btf, id);
20972 	if (!t) {
20973 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20974 		return -ENOENT;
20975 	}
20976 
20977 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20978 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20979 		return -EINVAL;
20980 	}
20981 
20982 	sym_name = btf_name_by_offset(btf, t->name_off);
20983 	addr = kallsyms_lookup_name(sym_name);
20984 	if (!addr) {
20985 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20986 			sym_name);
20987 		return -ENOENT;
20988 	}
20989 	insn[0].imm = (u32)addr;
20990 	insn[1].imm = addr >> 32;
20991 
20992 	if (btf_type_is_func(t)) {
20993 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20994 		aux->btf_var.mem_size = 0;
20995 		return 0;
20996 	}
20997 
20998 	datasec_id = find_btf_percpu_datasec(btf);
20999 	if (datasec_id > 0) {
21000 		datasec = btf_type_by_id(btf, datasec_id);
21001 		for_each_vsi(i, datasec, vsi) {
21002 			if (vsi->type == id) {
21003 				percpu = true;
21004 				break;
21005 			}
21006 		}
21007 	}
21008 
21009 	if (!percpu && !env->allow_ptr_leaks) {
21010 		verbose(env, "access to '%s' is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
21011 			sym_name);
21012 		return -EPERM;
21013 	}
21014 
21015 	type = t->type;
21016 	t = btf_type_skip_modifiers(btf, type, NULL);
21017 	if (percpu) {
21018 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
21019 		aux->btf_var.btf = btf;
21020 		aux->btf_var.btf_id = type;
21021 	} else if (!btf_type_is_struct(t)) {
21022 		const struct btf_type *ret;
21023 		const char *tname;
21024 		u32 tsize;
21025 
21026 		/* resolve the type size of ksym. */
21027 		ret = btf_resolve_size(btf, t, &tsize);
21028 		if (IS_ERR(ret)) {
21029 			tname = btf_name_by_offset(btf, t->name_off);
21030 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
21031 				tname, PTR_ERR(ret));
21032 			return -EINVAL;
21033 		}
21034 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
21035 		aux->btf_var.mem_size = tsize;
21036 	} else {
21037 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
21038 		aux->btf_var.btf = btf;
21039 		aux->btf_var.btf_id = type;
21040 	}
21041 
21042 	return 0;
21043 }
21044 
21045 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
21046 			       struct bpf_insn *insn,
21047 			       struct bpf_insn_aux_data *aux)
21048 {
21049 	struct btf *btf;
21050 	int btf_fd;
21051 	int err;
21052 
21053 	btf_fd = insn[1].imm;
21054 	if (btf_fd) {
21055 		btf = btf_get_by_fd(btf_fd);
21056 		if (IS_ERR(btf)) {
21057 			verbose(env, "invalid module BTF object FD specified.\n");
21058 			return -EINVAL;
21059 		}
21060 		if (!btf_is_kernel(btf)) {
21061 			verbose(env, "BTF fd for ksym is not a kernel BTF\n");
21062 			btf_put(btf);
21063 			return -EINVAL;
21064 		}
21065 	} else {
21066 		if (!btf_vmlinux) {
21067 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
21068 			return -EINVAL;
21069 		}
21070 		btf_get(btf_vmlinux);
21071 		btf = btf_vmlinux;
21072 	}
21073 
21074 	err = __check_pseudo_btf_id(env, insn, aux, btf);
21075 	if (err) {
21076 		btf_put(btf);
21077 		return err;
21078 	}
21079 
21080 	return __add_used_btf(env, btf);
21081 }
21082 
21083 static bool is_tracing_prog_type(enum bpf_prog_type type)
21084 {
21085 	switch (type) {
21086 	case BPF_PROG_TYPE_KPROBE:
21087 	case BPF_PROG_TYPE_TRACEPOINT:
21088 	case BPF_PROG_TYPE_PERF_EVENT:
21089 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
21090 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
21091 		return true;
21092 	default:
21093 		return false;
21094 	}
21095 }
21096 
21097 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
21098 {
21099 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
21100 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
21101 }
21102 
21103 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
21104 					struct bpf_map *map,
21105 					struct bpf_prog *prog)
21106 
21107 {
21108 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
21109 
21110 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
21111 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
21112 		if (is_tracing_prog_type(prog_type)) {
21113 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
21114 			return -EINVAL;
21115 		}
21116 	}
21117 
21118 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
21119 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
21120 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
21121 			return -EINVAL;
21122 		}
21123 	}
21124 
21125 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
21126 		if (is_tracing_prog_type(prog_type)) {
21127 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
21128 			return -EINVAL;
21129 		}
21130 	}
21131 
21132 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
21133 	    !bpf_offload_prog_map_match(prog, map)) {
21134 		verbose(env, "offload device mismatch between prog and map\n");
21135 		return -EINVAL;
21136 	}
21137 
21138 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
21139 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
21140 		return -EINVAL;
21141 	}
21142 
21143 	if (prog->sleepable && !map_needs_no_rcu(map)) {
21144 		verbose(env,
21145 			"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
21146 		return -EINVAL;
21147 	}
21148 
21149 	if (bpf_map_is_cgroup_storage(map) &&
21150 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
21151 		verbose(env, "only one cgroup storage of each type is allowed\n");
21152 		return -EBUSY;
21153 	}
21154 
21155 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
21156 		if (env->prog->aux->arena) {
21157 			verbose(env, "Only one arena per program\n");
21158 			return -EBUSY;
21159 		}
21160 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
21161 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
21162 			return -EPERM;
21163 		}
21164 		if (!env->prog->jit_requested) {
21165 			verbose(env, "JIT is required to use arena\n");
21166 			return -EOPNOTSUPP;
21167 		}
21168 		if (!bpf_jit_supports_arena()) {
21169 			verbose(env, "JIT doesn't support arena\n");
21170 			return -EOPNOTSUPP;
21171 		}
21172 		env->prog->aux->arena = (void *)map;
21173 		env->prog->jit_required = true;
21174 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
21175 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
21176 			return -EINVAL;
21177 		}
21178 	}
21179 
21180 	return 0;
21181 }
21182 
21183 /*
21184  * Keep track of whether the map is used by one program only. Such program may
21185  * store the addresses of its functions into the map when it's frozen, see
21186  * resolve_func_ptrs(), since nothing else relies on what the map has. After
21187  * that the map is not available to other programs.
21188  */
21189 static int bpf_map_claim(struct bpf_verifier_env *env, struct bpf_map *map)
21190 {
21191 	unsigned long me = (unsigned long)env->prog->aux, old;
21192 
21193 	for (;;) {
21194 		old = READ_ONCE(map->user);
21195 		if (old == me || old == BPF_MAP_USER_MANY)
21196 			return 0;
21197 		if (old & BPF_MAP_USER_PATCHED) {
21198 			verbose(env, "map '%s' has addresses of functions of another program\n",
21199 				map->name);
21200 			return -EBUSY;
21201 		}
21202 		if (cmpxchg(&map->user, old, old ? BPF_MAP_USER_MANY : me) == old)
21203 			return 0;
21204 	}
21205 }
21206 
21207 /*
21208  * An exclusive map is bound to the digest of its program. The digest covers
21209  * the insns as they are verified, after the CO-RE relocations the kernel
21210  * applies, so it exists only once check_and_resolve_insns() has computed it,
21211  * and the maps are checked against it there, whether an insn referred to
21212  * them or a continuous fd_array bound them before.
21213  */
21214 static int check_excl_maps(struct bpf_verifier_env *env)
21215 {
21216 	int i;
21217 
21218 	for (i = 0; i < env->used_map_cnt; i++) {
21219 		struct bpf_map *map = env->used_maps[i];
21220 
21221 		if (map->excl_prog_sha &&
21222 		    memcmp(map->excl_prog_sha, env->prog->digest, SHA256_DIGEST_SIZE)) {
21223 			verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
21224 			return -EACCES;
21225 		}
21226 	}
21227 	return 0;
21228 }
21229 
21230 /*
21231  * The program may use every map it referred to, see check_excl_maps(). Only now
21232  * does it leave a trace on them: it claims each as its user, see
21233  * bpf_map_claim(), and takes over its insn arrays. A program rejected before
21234  * this point, one that is not the owner of an exclusive map in particular,
21235  * leaves the maps as it found them. Nothing consults a claim before
21236  * resolve_func_ptrs() and the fixup passes, which run later.
21237  */
21238 static int claim_used_maps(struct bpf_verifier_env *env)
21239 {
21240 	int i, err;
21241 
21242 	for (i = 0; i < env->used_map_cnt; i++) {
21243 		struct bpf_map *map = env->used_maps[i];
21244 
21245 		err = bpf_map_claim(env, map);
21246 		if (err)
21247 			return err;
21248 
21249 		if (map->map_type != BPF_MAP_TYPE_INSN_ARRAY)
21250 			continue;
21251 		err = bpf_insn_array_init(map, env->prog);
21252 		if (err) {
21253 			verbose(env, "Failed to properly initialize insn array\n");
21254 			return err;
21255 		}
21256 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21257 		env->prog->jit_required = true;
21258 	}
21259 	return 0;
21260 }
21261 
21262 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
21263 {
21264 	int i, err;
21265 
21266 	/* check whether we recorded this map already */
21267 	for (i = 0; i < env->used_map_cnt; i++)
21268 		if (env->used_maps[i] == map)
21269 			return i;
21270 
21271 	if (env->signature &&
21272 	    env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) {
21273 		verbose(env, "signed program cannot bind map '%s' not covered by the signature\n",
21274 			map->name);
21275 		return -EACCES;
21276 	}
21277 	if (env->used_map_cnt >= MAX_USED_MAPS) {
21278 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
21279 			MAX_USED_MAPS);
21280 		return -E2BIG;
21281 	}
21282 
21283 	err = check_map_prog_compatibility(env, map, env->prog);
21284 	if (err)
21285 		return err;
21286 
21287 	if (bpf_prog_runs_sleepable(env->prog))
21288 		atomic64_inc(&map->sleepable_refcnt);
21289 
21290 	/* hold the map. If the program is rejected by verifier,
21291 	 * the map will be released by release_maps() or it
21292 	 * will be used by the valid program until it's unloaded
21293 	 * and all maps are released in bpf_free_used_maps()
21294 	 */
21295 	bpf_map_inc(map);
21296 
21297 	env->used_maps[env->used_map_cnt++] = map;
21298 
21299 	return env->used_map_cnt - 1;
21300 }
21301 
21302 /* Add map behind fd to used maps list, if it's not already there, and return
21303  * its index.
21304  * Returns <0 on error, or >= 0 index, on success.
21305  */
21306 static int add_used_map(struct bpf_verifier_env *env, int fd)
21307 {
21308 	struct bpf_map *map;
21309 	CLASS(fd, f)(fd);
21310 
21311 	map = __bpf_map_get(f);
21312 	if (IS_ERR(map)) {
21313 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21314 		return PTR_ERR(map);
21315 	}
21316 
21317 	return __add_used_map(env, map);
21318 }
21319 
21320 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx)
21321 {
21322 	struct bpf_map *map;
21323 
21324 	if (idx >= env->fd_array_cnt) {
21325 		verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n",
21326 			idx, env->fd_array_cnt);
21327 		return -EINVAL;
21328 	}
21329 	map = fd_slot_map(env->fd_array[idx]);
21330 	if (!map) {
21331 		verbose(env, "fd_idx %u is not a map\n", idx);
21332 		return -EINVAL;
21333 	}
21334 	return __add_used_map(env, map);
21335 }
21336 
21337 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx)
21338 {
21339 	int fd;
21340 
21341 	if (copy_from_bpfptr_offset(&fd, env->fd_array_raw,
21342 				    (size_t)idx * sizeof(fd), sizeof(fd)))
21343 		return -EFAULT;
21344 	return add_used_map(env, fd);
21345 }
21346 
21347 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx)
21348 {
21349 	if (env->fd_array)
21350 		return fd_array_get_map_idx_continuous(env, idx);
21351 	if (env->signature) {
21352 		verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n");
21353 		return -EACCES;
21354 	}
21355 	if (!bpfptr_is_null(env->fd_array_raw))
21356 		return fd_array_get_map_idx_sparse(env, idx);
21357 
21358 	verbose(env, "fd_idx without fd_array is invalid\n");
21359 	return -EPROTO;
21360 }
21361 
21362 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21363 {
21364 	u8 class = BPF_CLASS(insn->code);
21365 	u8 opcode = BPF_OP(insn->code);
21366 
21367 	switch (opcode) {
21368 	case BPF_NEG:
21369 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
21370 		    insn->off != 0 || insn->imm != 0) {
21371 			verbose(env, "BPF_NEG uses reserved fields\n");
21372 			return -EINVAL;
21373 		}
21374 		return 0;
21375 	case BPF_END:
21376 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
21377 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
21378 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
21379 			verbose(env, "BPF_END uses reserved fields\n");
21380 			return -EINVAL;
21381 		}
21382 		return 0;
21383 	case BPF_MOV:
21384 		if (BPF_SRC(insn->code) == BPF_X) {
21385 			if (class == BPF_ALU) {
21386 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
21387 				    insn->imm) {
21388 					verbose(env, "BPF_MOV uses reserved fields\n");
21389 					return -EINVAL;
21390 				}
21391 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
21392 				if (insn->imm != 1 && insn->imm != 1u << 16) {
21393 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
21394 					return -EINVAL;
21395 				}
21396 			} else if ((insn->off != 0 && insn->off != 8 &&
21397 				    insn->off != 16 && insn->off != 32) || insn->imm) {
21398 				verbose(env, "BPF_MOV uses reserved fields\n");
21399 				return -EINVAL;
21400 			}
21401 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
21402 			verbose(env, "BPF_MOV uses reserved fields\n");
21403 			return -EINVAL;
21404 		}
21405 		return 0;
21406 	case BPF_ADD:
21407 	case BPF_SUB:
21408 	case BPF_AND:
21409 	case BPF_OR:
21410 	case BPF_XOR:
21411 	case BPF_LSH:
21412 	case BPF_RSH:
21413 	case BPF_ARSH:
21414 	case BPF_MUL:
21415 	case BPF_DIV:
21416 	case BPF_MOD:
21417 		if (BPF_SRC(insn->code) == BPF_X) {
21418 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
21419 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
21420 				verbose(env, "BPF_ALU uses reserved fields\n");
21421 				return -EINVAL;
21422 			}
21423 		} else if (insn->src_reg != BPF_REG_0 ||
21424 			   (insn->off != 0 && insn->off != 1) ||
21425 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
21426 			verbose(env, "BPF_ALU uses reserved fields\n");
21427 			return -EINVAL;
21428 		}
21429 		return 0;
21430 	default:
21431 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
21432 		return -EINVAL;
21433 	}
21434 }
21435 
21436 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21437 {
21438 	u8 class = BPF_CLASS(insn->code);
21439 	u8 opcode = BPF_OP(insn->code);
21440 
21441 	switch (opcode) {
21442 	case BPF_CALL:
21443 		if (bpf_is_callx(insn)) {
21444 			/* callx dst_reg */
21445 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
21446 				verbose(env, "BPF_CALL|BPF_X uses reserved fields\n");
21447 				return -EINVAL;
21448 			}
21449 			return 0;
21450 		}
21451 		if (BPF_SRC(insn->code) != BPF_K ||
21452 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
21453 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
21454 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
21455 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
21456 			verbose(env, "BPF_CALL uses reserved fields\n");
21457 			return -EINVAL;
21458 		}
21459 		return 0;
21460 	case BPF_JA:
21461 		if (BPF_SRC(insn->code) == BPF_X) {
21462 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
21463 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
21464 				return -EINVAL;
21465 			}
21466 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
21467 			   (class == BPF_JMP && insn->imm != 0) ||
21468 			   (class == BPF_JMP32 && insn->off != 0)) {
21469 			verbose(env, "BPF_JA uses reserved fields\n");
21470 			return -EINVAL;
21471 		}
21472 		return 0;
21473 	case BPF_EXIT:
21474 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
21475 		    insn->src_reg > BPF_UNWIND_EXIT || insn->dst_reg != BPF_REG_0 ||
21476 		    class == BPF_JMP32) {
21477 			verbose(env, "BPF_EXIT uses reserved fields\n");
21478 			return -EINVAL;
21479 		}
21480 		return 0;
21481 	case BPF_JCOND:
21482 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg > BPF_UNWIND_GOTO ||
21483 		    insn->dst_reg || insn->imm) {
21484 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
21485 			return -EINVAL;
21486 		}
21487 		return 0;
21488 	default:
21489 		if (BPF_SRC(insn->code) == BPF_X) {
21490 			if (insn->imm != 0) {
21491 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
21492 				return -EINVAL;
21493 			}
21494 		} else if (insn->src_reg != BPF_REG_0) {
21495 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
21496 			return -EINVAL;
21497 		}
21498 		return 0;
21499 	}
21500 }
21501 
21502 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21503 {
21504 	switch (BPF_CLASS(insn->code)) {
21505 	case BPF_ALU:
21506 	case BPF_ALU64:
21507 		return check_alu_fields(env, insn);
21508 	case BPF_LDX:
21509 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21510 		    insn->imm != 0) {
21511 			verbose(env, "BPF_LDX uses reserved fields\n");
21512 			return -EINVAL;
21513 		}
21514 		return 0;
21515 	case BPF_STX:
21516 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
21517 			return 0;
21518 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
21519 			verbose(env, "BPF_STX uses reserved fields\n");
21520 			return -EINVAL;
21521 		}
21522 		return 0;
21523 	case BPF_ST:
21524 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
21525 			verbose(env, "BPF_ST uses reserved fields\n");
21526 			return -EINVAL;
21527 		}
21528 		return 0;
21529 	case BPF_JMP:
21530 	case BPF_JMP32:
21531 		return check_jmp_fields(env, insn);
21532 	case BPF_LD: {
21533 		u8 mode = BPF_MODE(insn->code);
21534 
21535 		if (mode == BPF_ABS || mode == BPF_IND) {
21536 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
21537 			    BPF_SIZE(insn->code) == BPF_DW ||
21538 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
21539 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
21540 				return -EINVAL;
21541 			}
21542 		} else if (mode != BPF_IMM) {
21543 			verbose(env, "invalid BPF_LD mode\n");
21544 			return -EINVAL;
21545 		}
21546 		return 0;
21547 	}
21548 	default:
21549 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
21550 		return -EINVAL;
21551 	}
21552 }
21553 
21554 /*
21555  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
21556  *
21557  * 1. if it accesses map FD, replace it with actual map pointer.
21558  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21559  *
21560  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21561  */
21562 static int check_and_resolve_insns(struct bpf_verifier_env *env)
21563 {
21564 	struct bpf_insn *insn = env->prog->insnsi;
21565 	int insn_cnt = env->prog->len;
21566 	int i, err;
21567 
21568 	err = bpf_prog_calc_tag(env->prog);
21569 	if (err)
21570 		return err;
21571 
21572 	for (i = 0; i < insn_cnt; i++, insn++) {
21573 		if (insn->dst_reg >= MAX_BPF_REG &&
21574 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
21575 			verbose(env, "R%d is invalid\n", insn->dst_reg);
21576 			return -EINVAL;
21577 		}
21578 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
21579 			verbose(env, "R%d is invalid\n", insn->src_reg);
21580 			return -EINVAL;
21581 		}
21582 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21583 			struct bpf_insn_aux_data *aux;
21584 			struct bpf_map *map;
21585 			int map_idx;
21586 			u64 addr;
21587 
21588 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21589 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21590 			    insn[1].off != 0) {
21591 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21592 				return -EINVAL;
21593 			}
21594 
21595 			if (insn[0].off != 0) {
21596 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
21597 				return -EINVAL;
21598 			}
21599 
21600 			if (insn[0].src_reg == 0)
21601 				/* valid generic load 64-bit imm */
21602 				goto next_insn;
21603 
21604 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21605 				aux = &env->insn_aux_data[i];
21606 				err = check_pseudo_btf_id(env, insn, aux);
21607 				if (err)
21608 					return err;
21609 				goto next_insn;
21610 			}
21611 
21612 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21613 				aux = &env->insn_aux_data[i];
21614 				aux->ptr_type = PTR_TO_FUNC;
21615 				goto next_insn;
21616 			}
21617 
21618 			/* In final convert_pseudo_ld_imm64() step, this is
21619 			 * converted into regular 64-bit imm load insn.
21620 			 */
21621 			switch (insn[0].src_reg) {
21622 			case BPF_PSEUDO_MAP_VALUE:
21623 			case BPF_PSEUDO_MAP_IDX_VALUE:
21624 				break;
21625 			case BPF_PSEUDO_MAP_FD:
21626 			case BPF_PSEUDO_MAP_IDX:
21627 				if (insn[1].imm == 0)
21628 					break;
21629 				fallthrough;
21630 			default:
21631 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21632 				return -EINVAL;
21633 			}
21634 
21635 			switch (insn[0].src_reg) {
21636 			case BPF_PSEUDO_MAP_IDX_VALUE:
21637 			case BPF_PSEUDO_MAP_IDX:
21638 				map_idx = fd_array_get_map_idx(env, insn[0].imm);
21639 				break;
21640 			default:
21641 				if (env->signature) {
21642 					verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n");
21643 					return -EINVAL;
21644 				}
21645 				map_idx = add_used_map(env, insn[0].imm);
21646 				break;
21647 			}
21648 
21649 			if (map_idx < 0)
21650 				return map_idx;
21651 			map = env->used_maps[map_idx];
21652 
21653 			aux = &env->insn_aux_data[i];
21654 			aux->map_index = map_idx;
21655 
21656 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21657 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21658 				addr = (unsigned long)map;
21659 			} else {
21660 				u32 off = insn[1].imm;
21661 
21662 				if (!map->ops->map_direct_value_addr) {
21663 					verbose(env, "no direct value access support for this map type\n");
21664 					return -EINVAL;
21665 				}
21666 
21667 				err = map->ops->map_direct_value_addr(map, &addr, off);
21668 				if (err) {
21669 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21670 						map->value_size, off);
21671 					return err;
21672 				}
21673 
21674 				aux->map_off = off;
21675 				addr += off;
21676 			}
21677 
21678 			insn[0].imm = (u32)addr;
21679 			insn[1].imm = addr >> 32;
21680 
21681 next_insn:
21682 			insn++;
21683 			i++;
21684 			continue;
21685 		}
21686 
21687 		/* Basic sanity check before we invest more work here. */
21688 		if (!bpf_opcode_in_insntable(insn->code)) {
21689 			verbose(env, "unknown opcode %02x\n", insn->code);
21690 			return -EINVAL;
21691 		}
21692 
21693 		err = check_insn_fields(env, insn);
21694 		if (err)
21695 			return err;
21696 	}
21697 
21698 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21699 	 * 'struct bpf_map *' into a register instead of user map_fd.
21700 	 * These pointers will be used later by verifier to validate map access.
21701 	 */
21702 	err = check_excl_maps(env);
21703 	if (err)
21704 		return err;
21705 	return claim_used_maps(env);
21706 }
21707 
21708 /* that many pointers to functions are recognized in the maps of a program at most */
21709 #define BPF_MAX_FUNC_PTRS (1 << 20)
21710 
21711 static int add_func_ptr(struct bpf_verifier_env *env, struct bpf_map *map, u32 map_off,
21712 			u32 xlated_off)
21713 {
21714 	struct bpf_func_ptr *ptrs;
21715 
21716 	if (env->func_ptr_cnt == BPF_MAX_FUNC_PTRS) {
21717 		verbose(env, "too many pointers to functions in maps, the limit is %d\n",
21718 			BPF_MAX_FUNC_PTRS);
21719 		return -E2BIG;
21720 	}
21721 
21722 	/* grow by doubling, the array is sorted and searched later */
21723 	if (!(env->func_ptr_cnt & (env->func_ptr_cnt - 1))) {
21724 		ptrs = kvrealloc(env->func_ptrs,
21725 				 array_size(max(2 * env->func_ptr_cnt, 16U), sizeof(*ptrs)),
21726 				 GFP_KERNEL_ACCOUNT);
21727 		if (!ptrs)
21728 			return -ENOMEM;
21729 		env->func_ptrs = ptrs;
21730 	}
21731 	env->func_ptrs[env->func_ptr_cnt++] = (struct bpf_func_ptr){
21732 		.map = map,
21733 		.map_off = map_off,
21734 		.orig_off = xlated_off,
21735 		.xlated_off = xlated_off,
21736 	};
21737 	return 0;
21738 }
21739 
21740 /*
21741  * Compilers put pointers to functions into read-only data: tables of functions,
21742  * structures of operations, vtables, where they are mixed with other data.
21743  * The loader stores such data in a frozen read-only array map and resolves
21744  * a pointer to a static function to the offset in bytes of its first
21745  * instruction in the program: the address of the function in the program.
21746  *
21747  * Find 64-bit values that look like that in the maps of a program that uses
21748  * callx. It's a guess. When the value is not a pointer, the program either
21749  * fails to load, because it does with a pointer what can be done with
21750  * a number only, or it sees the address of a function instead of the number.
21751  * It's known before the control flow graph of the program is built and the main
21752  * verification pass begins which functions may be called via callx.
21753  *
21754  * When the program is jitted the offsets are replaced with the addresses of
21755  * the functions in the map itself, see jit_subprogs(). Hence the program has to
21756  * be the only user of the map, see bpf_map_claim(): nothing else may rely on
21757  * what the map had.
21758  *
21759  * The program reads the addresses of its functions from there like any other
21760  * data, so it has to be allowed to leak pointers.
21761  */
21762 static int resolve_func_ptrs(struct bpf_verifier_env *env)
21763 {
21764 	int insn_cnt = env->prog->len;
21765 	int i, err, subprog;
21766 	struct bpf_map *map;
21767 	u64 addr, val;
21768 	u32 off;
21769 
21770 	if (!env->has_callx || !env->allow_ptr_leaks)
21771 		return 0;
21772 
21773 	for (i = 0; i < env->used_map_cnt; i++) {
21774 		map = env->used_maps[i];
21775 		/* coincidences in maps that are shared with other programs don't matter */
21776 		if (READ_ONCE(map->user) != (unsigned long)env->prog->aux)
21777 			continue;
21778 		if (map->map_type != BPF_MAP_TYPE_ARRAY || map->max_entries != 1 ||
21779 		    !bpf_map_is_rdonly(map) || !map->ops->map_direct_value_addr ||
21780 		    !IS_ERR_OR_NULL(map->record))
21781 			continue;
21782 		if (map->ops->map_direct_value_addr(map, &addr, 0))
21783 			continue;
21784 
21785 		for (off = 0; off + sizeof(u64) <= map->value_size; off += sizeof(u64)) {
21786 			if (!(off % SZ_64K))
21787 				cond_resched();
21788 			val = *(u64 *)(unsigned long)(addr + off);
21789 			if (!val || val % sizeof(struct bpf_insn) ||
21790 			    val / sizeof(struct bpf_insn) >= insn_cnt)
21791 				continue;
21792 			subprog = bpf_find_subprog(env, val / sizeof(struct bpf_insn));
21793 			if (subprog <= 0 || bpf_subprog_is_global(env, subprog))
21794 				continue;
21795 			err = add_func_ptr(env, map, off, val / sizeof(struct bpf_insn));
21796 			if (err)
21797 				return err;
21798 		}
21799 	}
21800 	if (env->func_ptr_cnt)
21801 		sort(env->func_ptrs, env->func_ptr_cnt, sizeof(*env->func_ptrs),
21802 		     cmp_func_ptrs, NULL);
21803 	return 0;
21804 }
21805 
21806 /* drop refcnt of maps used by the rejected program */
21807 static void release_maps(struct bpf_verifier_env *env)
21808 {
21809 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21810 			     env->used_map_cnt);
21811 }
21812 
21813 /* drop refcnt of maps used by the rejected program */
21814 static void release_btfs(struct bpf_verifier_env *env)
21815 {
21816 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21817 }
21818 
21819 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21820 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21821 {
21822 	struct bpf_insn *insn = env->prog->insnsi;
21823 	int insn_cnt = env->prog->len;
21824 	int i;
21825 
21826 	for (i = 0; i < insn_cnt; i++, insn++) {
21827 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21828 			continue;
21829 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21830 			continue;
21831 		insn->src_reg = 0;
21832 	}
21833 }
21834 
21835 static void release_insn_arrays(struct bpf_verifier_env *env)
21836 {
21837 	int i;
21838 
21839 	for (i = 0; i < env->insn_array_map_cnt; i++)
21840 		bpf_insn_array_release(env->insn_array_maps[i]);
21841 }
21842 
21843 /* The verifier does more data flow analysis than llvm and will not
21844  * explore branches that are dead at run time. Malicious programs can
21845  * have dead code too. Therefore replace all dead at-run-time code
21846  * with 'ja -1'.
21847  *
21848  * Just nops are not optimal, e.g. if they would sit at the end of the
21849  * program and through another bug we would manage to jump there, then
21850  * we'd execute beyond program memory otherwise. Returning exception
21851  * code also wouldn't work since we can have subprogs where the dead
21852  * code could be located.
21853  */
21854 static void sanitize_dead_code(struct bpf_verifier_env *env)
21855 {
21856 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21857 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21858 	struct bpf_insn *insn = env->prog->insnsi;
21859 	const int insn_cnt = env->prog->len;
21860 	int i;
21861 
21862 	for (i = 0; i < insn_cnt; i++) {
21863 		if (aux_data[i].seen)
21864 			continue;
21865 		memcpy(insn + i, &trap, sizeof(trap));
21866 		aux_data[i].zext_dst = false;
21867 	}
21868 }
21869 
21870 static void free_states(struct bpf_verifier_env *env)
21871 {
21872 	struct bpf_verifier_state_list *sl;
21873 	struct list_head *head, *pos, *tmp;
21874 	struct bpf_scc_info *info;
21875 	int i, j;
21876 
21877 	bpf_free_verifier_state(env->cur_state, true);
21878 	env->cur_state = NULL;
21879 	while (!pop_stack(env, NULL, NULL, false));
21880 
21881 	list_for_each_safe(pos, tmp, &env->free_list) {
21882 		sl = container_of(pos, struct bpf_verifier_state_list, node);
21883 		bpf_free_verifier_state(&sl->state, false);
21884 		kfree(sl);
21885 	}
21886 	INIT_LIST_HEAD(&env->free_list);
21887 
21888 	for (i = 0; i < env->scc_cnt; ++i) {
21889 		info = env->scc_info[i];
21890 		if (!info)
21891 			continue;
21892 		for (j = 0; j < info->num_visits; j++)
21893 			bpf_free_backedges(&info->visits[j]);
21894 		kvfree(info);
21895 		env->scc_info[i] = NULL;
21896 	}
21897 
21898 	if (!env->explored_states)
21899 		return;
21900 
21901 	for (i = 0; i < state_htab_size(env); i++) {
21902 		head = &env->explored_states[i];
21903 
21904 		list_for_each_safe(pos, tmp, head) {
21905 			sl = container_of(pos, struct bpf_verifier_state_list, node);
21906 			bpf_free_verifier_state(&sl->state, false);
21907 			kfree(sl);
21908 		}
21909 		INIT_LIST_HEAD(&env->explored_states[i]);
21910 	}
21911 }
21912 
21913 static int do_check_common(struct bpf_verifier_env *env, int subprog,
21914 			   enum bpf_func_context context)
21915 {
21916 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21917 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
21918 	struct bpf_prog_aux *aux = env->prog->aux;
21919 	struct bpf_verifier_state *state;
21920 	struct bpf_reg_state *regs;
21921 	u32 old_insns_total = sub->insns_total;
21922 	u32 insn_processed = env->insn_processed;
21923 	int ret, i;
21924 
21925 	env->prev_linfo = NULL;
21926 	env->pass_cnt++;
21927 
21928 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
21929 	if (!state)
21930 		return -ENOMEM;
21931 	state->curframe = 0;
21932 	state->speculative = false;
21933 	state->branches = 1;
21934 	state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE;
21935 	env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK;
21936 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
21937 	if (!state->frame[0]) {
21938 		kfree(state);
21939 		return -ENOMEM;
21940 	}
21941 	env->cur_state = state;
21942 	init_func_state(env, state->frame[0],
21943 			BPF_MAIN_FUNC /* callsite */,
21944 			0 /* frameno */,
21945 			subprog);
21946 	state->first_insn_idx = env->subprog_info[subprog].start;
21947 	state->last_insn_idx = -1;
21948 
21949 	regs = state->frame[state->curframe]->regs;
21950 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21951 		const char *sub_name = bpf_subprog_name(env, subprog);
21952 		struct bpf_subprog_arg_info *arg;
21953 		struct bpf_reg_state *reg;
21954 
21955 		if (env->log.level & BPF_LOG_LEVEL)
21956 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21957 		ret = btf_prepare_func_args(env, subprog);
21958 		if (ret)
21959 			goto out;
21960 
21961 		if (subprog_is_exc_cb(env, subprog)) {
21962 			state->frame[0]->in_exception_callback_fn = true;
21963 
21964 			/*
21965 			 * Global functions are scalar or void, make sure
21966 			 * we return a scalar.
21967 			 */
21968 			if (subprog_returns_void(env, subprog)) {
21969 				verbose(env, "exception cb cannot return void\n");
21970 				ret = -EINVAL;
21971 				goto out;
21972 			}
21973 
21974 			/* Also ensure the callback only has a single scalar argument. */
21975 			if (sub->arg_slot_cnt != 1 || sub->args[0].arg_type != ARG_SCALAR) {
21976 				verbose(env, "exception cb only supports single integer argument\n");
21977 				ret = -EINVAL;
21978 				goto out;
21979 			}
21980 		}
21981 		for (i = BPF_REG_1;
21982 		     i <= min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
21983 			arg = &sub->args[i - BPF_REG_1];
21984 			reg = &regs[i];
21985 
21986 			if (arg->arg_type == ARG_PTR_TO_CTX) {
21987 				reg->type = PTR_TO_CTX;
21988 				mark_reg_known_zero(env, regs, i);
21989 			} else if (arg->arg_type == ARG_SCALAR) {
21990 				reg->type = SCALAR_VALUE;
21991 				mark_reg_unknown(env, regs, i);
21992 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
21993 				/*
21994 				 * The callers may hand in a dynptr of any type.
21995 				 * Take it for that of an skb, so that a write
21996 				 * through it and its slices are treated with care.
21997 				 */
21998 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen, 0);
21999 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
22000 				reg->type = PTR_TO_MEM;
22001 				reg->type |= arg->arg_type &
22002 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
22003 				mark_reg_known_zero(env, regs, i);
22004 				reg->mem_size = arg->mem_size;
22005 				if (arg->arg_type & PTR_MAYBE_NULL)
22006 					reg->id = ++env->id_gen;
22007 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
22008 				reg->type = PTR_TO_BTF_ID;
22009 				if (arg->arg_type & PTR_MAYBE_NULL)
22010 					reg->type |= PTR_MAYBE_NULL;
22011 				if (arg->arg_type & PTR_UNTRUSTED)
22012 					reg->type |= PTR_UNTRUSTED;
22013 				if (arg->arg_type & PTR_TRUSTED)
22014 					reg->type |= PTR_TRUSTED;
22015 				mark_reg_known_zero(env, regs, i);
22016 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
22017 				reg->btf_id = arg->btf_id;
22018 				reg->id = ++env->id_gen;
22019 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
22020 				/* caller can pass either PTR_TO_ARENA or SCALAR */
22021 				mark_reg_unknown(env, regs, i);
22022 			} else {
22023 				verifier_bug(env, "unhandled arg#%d type %d",
22024 					     i - BPF_REG_1 + 1, arg->arg_type);
22025 				ret = -EFAULT;
22026 				goto out;
22027 			}
22028 		}
22029 		if (env->prog->type == BPF_PROG_TYPE_EXT &&
22030 		    sub->arg_slot_cnt > MAX_BPF_FUNC_REG_ARGS) {
22031 			verbose(env, "freplace programs with >%d args not supported yet\n",
22032 				MAX_BPF_FUNC_REG_ARGS);
22033 			ret = -EINVAL;
22034 			goto out;
22035 		}
22036 	} else {
22037 		/* if main BPF program has associated BTF info, validate that
22038 		 * it's matching expected signature, and otherwise mark BTF
22039 		 * info for main program as unreliable
22040 		 */
22041 		if (env->prog->aux->func_info_aux) {
22042 			ret = btf_prepare_func_args(env, 0);
22043 			if (ret || sub->arg_slot_cnt != 1 ||
22044 			    sub->args[0].arg_type != ARG_PTR_TO_CTX) {
22045 				env->prog->aux->func_info_aux[0].unreliable = true;
22046 				sub->arg_slot_cnt = 1;
22047 				sub->stack_arg_cnt = 0;
22048 			}
22049 		}
22050 
22051 		/* 1st arg to a function */
22052 		regs[BPF_REG_1].type = PTR_TO_CTX;
22053 		mark_reg_known_zero(env, regs, BPF_REG_1);
22054 	}
22055 
22056 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
22057 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
22058 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
22059 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
22060 			if (ret < 0)
22061 				goto out;
22062 
22063 			aux->ctx_arg_info[i].ref_id = ret;
22064 		}
22065 	}
22066 
22067 	ret = do_check(env);
22068 out:
22069 	account_current_path(env);
22070 	if (!ret) {
22071 		if (pop_log)
22072 			bpf_vlog_reset(&env->log, 0);
22073 		bpf_diag_event_log_restore(env, 0);
22074 	}
22075 	free_states(env);
22076 
22077 	/*
22078 	 * The override is needed to account for async subprograms, which
22079 	 * are verified with their own set of stack frames and thus are
22080 	 * not accounted as callees by account_current_path().
22081 	 * Accumulate their total counts as total counts of the main or
22082 	 * global subprog hosting the async call.
22083 	 * Start from the saved total of earlier contexts: adding to the current
22084 	 * total would count this pass's synchronous paths twice.
22085 	 */
22086 	sub->insns_total = old_insns_total + (env->insn_processed - insn_processed);
22087 	return ret;
22088 }
22089 
22090 /* Lazily verify all global functions based on their BTF, if they are called
22091  * from main BPF program or any of subprograms transitively.
22092  * BPF global subprogs called from dead code are not validated.
22093  * All callable global functions must pass verification.
22094  * Otherwise the whole program is rejected.
22095  * Consider:
22096  * int bar(int);
22097  * int foo(int f)
22098  * {
22099  *    return bar(f);
22100  * }
22101  * int bar(int b)
22102  * {
22103  *    ...
22104  * }
22105  * foo() will be verified first for R1=any_scalar_value. During verification it
22106  * will be assumed that bar() already verified successfully and call to bar()
22107  * from foo() will be checked for type match only. Later bar() will be verified
22108  * independently to check that it's safe for R1=any_scalar_value.
22109  */
22110 static int do_check_subprogs(struct bpf_verifier_env *env)
22111 {
22112 	struct bpf_prog_aux *aux = env->prog->aux;
22113 	struct bpf_func_info_aux *sub_aux;
22114 	int context, i, ret, new_cnt;
22115 
22116 	if (!aux->func_info)
22117 		return 0;
22118 
22119 	/*
22120 	 * Callbacks cannot throw, so the exception callback always runs in the
22121 	 * main program's context. It is presumed to be always called.
22122 	 */
22123 	if (env->exception_callback_subprog) {
22124 		sub_aux = subprog_aux(env, env->exception_callback_subprog);
22125 		sub_aux->called[env->prog->sleepable] = true;
22126 	}
22127 
22128 again:
22129 	new_cnt = 0;
22130 	for (i = 1; i < env->subprog_cnt; i++) {
22131 		if (!bpf_subprog_is_global(env, i))
22132 			continue;
22133 
22134 		sub_aux = subprog_aux(env, i);
22135 		for (context = 0; context < ARRAY_SIZE(sub_aux->called); context++) {
22136 			if (!sub_aux->called[context] || sub_aux->verified[context])
22137 				continue;
22138 
22139 			env->insn_idx = env->subprog_info[i].start;
22140 			WARN_ON_ONCE(env->insn_idx == 0);
22141 			ret = do_check_common(env, i, context);
22142 			if (ret)
22143 				return ret;
22144 			if (env->log.level & BPF_LOG_LEVEL)
22145 				verbose(env, "Func#%d ('%s') is safe for any args "
22146 					"that match its prototype\n",
22147 					i, bpf_subprog_name(env, i));
22148 
22149 			sub_aux->verified[context] = true;
22150 			new_cnt++;
22151 		}
22152 	}
22153 
22154 	/*
22155 	 * We can't loop forever as each pass verifies at least one new context,
22156 	 * and there are only three contexts per global subprog.
22157 	 */
22158 	if (new_cnt)
22159 		goto again;
22160 
22161 	return 0;
22162 }
22163 
22164 static int do_check_main(struct bpf_verifier_env *env)
22165 {
22166 	int ret;
22167 
22168 	env->insn_idx = 0;
22169 	ret = do_check_common(env, 0, env->prog->sleepable);
22170 	if (!ret)
22171 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22172 	return ret;
22173 }
22174 
22175 static void print_verification_stats(struct bpf_verifier_env *env)
22176 {
22177 	/* Skip over hidden subprogs which are not verified. */
22178 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22179 
22180 	if (env->log.level & BPF_LOG_STATS) {
22181 		verbose(env, "verification time %lld usec\n",
22182 			div_u64(env->verification_time, 1000));
22183 		verbose(env, "stack depth max %d\n", env->max_stack_depth);
22184 		for (i = 0; i < subprog_cnt; i++) {
22185 			const char *name = env->subprog_info[i].name;
22186 			const char *kind;
22187 
22188 			if (!name || !name[0])
22189 				name = "<unknown>";
22190 			kind = i == 0 ? "main" :
22191 			       bpf_subprog_is_global(env, i) ? "global" : "static";
22192 			verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n",
22193 				i, name, kind, env->subprog_info[i].insns_self,
22194 				env->subprog_info[i].insns_total,
22195 				env->subprog_info[i].stack_depth);
22196 		}
22197 	}
22198 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
22199 		"total_states %d peak_states %d mark_read %d\n",
22200 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
22201 		env->max_states_per_insn, env->total_states,
22202 		env->peak_states, env->longest_mark_read_walk);
22203 }
22204 
22205 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
22206 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
22207 {
22208 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
22209 	prog->aux->ctx_arg_info_size = cnt;
22210 
22211 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
22212 }
22213 
22214 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
22215 {
22216 	const struct btf_type *t, *func_proto;
22217 	const struct bpf_struct_ops_desc *st_ops_desc;
22218 	const struct bpf_struct_ops_arg_info *arg_info;
22219 	const struct bpf_struct_ops *st_ops;
22220 	const struct btf_member *member;
22221 	struct bpf_prog *prog = env->prog;
22222 	bool has_refcounted_arg = false;
22223 	u32 btf_id, member_idx, member_off;
22224 	struct btf *btf;
22225 	const char *mname;
22226 	int i, err;
22227 
22228 	if (!prog->gpl_compatible) {
22229 		verbose(env, "struct ops programs must have a GPL compatible license\n");
22230 		return -EINVAL;
22231 	}
22232 
22233 	if (!prog->aux->attach_btf_id)
22234 		return -ENOTSUPP;
22235 
22236 	btf = prog->aux->attach_btf;
22237 	if (btf_is_module(btf)) {
22238 		/* Make sure st_ops is valid through the lifetime of env */
22239 		env->attach_btf_mod = btf_try_get_module(btf);
22240 		if (!env->attach_btf_mod) {
22241 			verbose(env, "struct_ops module %s is not found\n",
22242 				btf_get_name(btf));
22243 			return -ENOTSUPP;
22244 		}
22245 	}
22246 
22247 	btf_id = prog->aux->attach_btf_id;
22248 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22249 	if (!st_ops_desc) {
22250 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22251 			btf_id);
22252 		return -ENOTSUPP;
22253 	}
22254 	st_ops = st_ops_desc->st_ops;
22255 
22256 	t = st_ops_desc->type;
22257 	member_idx = prog->expected_attach_type;
22258 	if (member_idx >= btf_type_vlen(t)) {
22259 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22260 			member_idx, st_ops->name);
22261 		return -EINVAL;
22262 	}
22263 
22264 	member = &btf_type_member(t)[member_idx];
22265 	mname = btf_name_by_offset(btf, member->name_off);
22266 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22267 					       NULL);
22268 	if (!func_proto) {
22269 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22270 			mname, member_idx, st_ops->name);
22271 		return -EINVAL;
22272 	}
22273 
22274 	member_off = __btf_member_bit_offset(t, member) / 8;
22275 	err = bpf_struct_ops_supported(st_ops, member_off);
22276 	if (err) {
22277 		verbose(env, "attach to unsupported member %s of struct %s\n",
22278 			mname, st_ops->name);
22279 		return err;
22280 	}
22281 
22282 	if (st_ops->check_member) {
22283 		err = st_ops->check_member(t, member, prog);
22284 
22285 		if (err) {
22286 			verbose(env, "attach to unsupported member %s of struct %s\n",
22287 				mname, st_ops->name);
22288 			return err;
22289 		}
22290 	}
22291 
22292 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
22293 		verbose(env, "Private stack not supported by jit\n");
22294 		return -EACCES;
22295 	}
22296 
22297 	arg_info = &st_ops_desc->arg_info[member_idx];
22298 	for (i = 0; i < arg_info->cnt; i++) {
22299 		const struct bpf_ctx_arg_aux *info = &arg_info->info[i];
22300 
22301 		if (info->refcounted)
22302 			has_refcounted_arg = true;
22303 		if (base_type(info->reg_type) == PTR_TO_ARENA) {
22304 			if (!bpf_jit_supports_arena_args()) {
22305 				verbose(env, "JIT does not support arena arguments\n");
22306 				return -ENOTSUPP;
22307 			}
22308 			if (!prog->aux->arena) {
22309 				verbose(env,
22310 					"arena argument of %s requires a program with an associated arena\n",
22311 					mname);
22312 				return -EINVAL;
22313 			}
22314 		}
22315 	}
22316 
22317 	/* Tail call is not allowed for programs with refcounted arguments since we
22318 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
22319 	 */
22320 	for (i = 0; i < env->subprog_cnt; i++) {
22321 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
22322 			verbose(env, "program with __ref argument cannot tail call\n");
22323 			return -EINVAL;
22324 		}
22325 	}
22326 
22327 	prog->aux->st_ops = st_ops;
22328 	prog->aux->attach_st_ops_member_off = member_off;
22329 
22330 	prog->aux->attach_func_proto = func_proto;
22331 	prog->aux->attach_func_name = mname;
22332 	env->ops = st_ops->verifier_ops;
22333 
22334 	return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt);
22335 }
22336 #define SECURITY_PREFIX "security_"
22337 
22338 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
22339 
22340 /* list of non-sleepable functions that are otherwise on
22341  * ALLOW_ERROR_INJECTION list
22342  */
22343 BTF_SET_START(btf_non_sleepable_error_inject)
22344 /* Three functions below can be called from sleepable and non-sleepable context.
22345  * Assume non-sleepable from bpf safety point of view.
22346  */
22347 BTF_ID(func, __filemap_add_folio)
22348 #ifdef CONFIG_FAIL_PAGE_ALLOC
22349 BTF_ID(func, should_fail_alloc_page)
22350 #endif
22351 #ifdef CONFIG_FAILSLAB
22352 BTF_ID(func, should_failslab)
22353 #endif
22354 BTF_SET_END(btf_non_sleepable_error_inject)
22355 
22356 static int check_non_sleepable_error_inject(u32 btf_id)
22357 {
22358 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
22359 }
22360 
22361 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
22362 {
22363 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
22364 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22365 	 */
22366 	if (!check_non_sleepable_error_inject(btf_id) &&
22367 	    within_error_injection_list(addr))
22368 		return 0;
22369 
22370 	return -EINVAL;
22371 }
22372 
22373 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22374 {
22375 	if (within_error_injection_list(addr) ||
22376 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22377 		return 0;
22378 
22379 	return -EINVAL;
22380 }
22381 
22382 #else
22383 
22384 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
22385  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
22386  * but that just compares two concrete function names.
22387  */
22388 static bool has_arch_syscall_prefix(const char *func_name)
22389 {
22390 #if defined(__x86_64__)
22391 	return !strncmp(func_name, "__x64_", 6);
22392 #elif defined(__i386__)
22393 	return !strncmp(func_name, "__ia32_", 7);
22394 #elif defined(__s390x__)
22395 	return !strncmp(func_name, "__s390x_", 8);
22396 #elif defined(__aarch64__)
22397 	return !strncmp(func_name, "__arm64_", 8);
22398 #elif defined(__riscv)
22399 	return !strncmp(func_name, "__riscv_", 8);
22400 #elif defined(__powerpc__) || defined(__powerpc64__)
22401 	return !strncmp(func_name, "sys_", 4);
22402 #elif defined(__loongarch__)
22403 	return !strncmp(func_name, "sys_", 4);
22404 #else
22405 	return false;
22406 #endif
22407 }
22408 
22409 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
22410 
22411 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
22412 {
22413 	if (has_arch_syscall_prefix(func_name))
22414 		return 0;
22415 
22416 	return -EINVAL;
22417 }
22418 
22419 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22420 {
22421 	if (has_arch_syscall_prefix(func_name) ||
22422 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22423 		return 0;
22424 
22425 	return -EINVAL;
22426 }
22427 
22428 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
22429 
22430 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
22431 {
22432 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
22433 }
22434 
22435 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
22436 				  const struct btf *btf)
22437 {
22438 	const struct btf_type *t;
22439 	const char *tname;
22440 
22441 	if (!btf_is_kernel(btf))
22442 		return -EINVAL;
22443 
22444 	switch (prog->type) {
22445 	case BPF_PROG_TYPE_TRACING:
22446 		t = btf_type_by_id(btf, btf_id);
22447 		if (!t)
22448 			return -EINVAL;
22449 		tname = btf_name_by_offset(btf, t->name_off);
22450 		if (!tname)
22451 			return -EINVAL;
22452 
22453 		/*
22454 		 * *.multi sleepable programs will pass initial sleepable check,
22455 		 * the actual attached btf ids are checked later during the link
22456 		 * attachment.
22457 		 */
22458 		if (is_tracing_multi_id(prog, btf_id))
22459 			return 0;
22460 		if (!check_attach_sleepable(btf_id, addr, tname))
22461 			return 0;
22462 		/*
22463 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
22464 		 * in the fmodret id set with the KF_SLEEPABLE flag.
22465 		 */
22466 		else {
22467 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
22468 
22469 			if (flags && (*flags & KF_SLEEPABLE))
22470 				return 0;
22471 		}
22472 		break;
22473 	case BPF_PROG_TYPE_LSM:
22474 		/*
22475 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
22476 		 * Only some of them are sleepable.
22477 		 */
22478 		if (bpf_lsm_is_sleepable_hook(btf_id))
22479 			return 0;
22480 		break;
22481 	default:
22482 		break;
22483 	}
22484 	return -EINVAL;
22485 }
22486 
22487 /*
22488  * Resolve the prototype describing a trace target's real ABI. A
22489  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
22490  * prototype, so use the _impl prototype; other targets use their own.
22491  */
22492 static const struct btf_type *
22493 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
22494 {
22495 	const struct btf_type *func;
22496 	struct module *mod = NULL;
22497 	const char *name;
22498 	int implicit;
22499 
22500 	func = btf_type_by_id(btf, func_id);
22501 	if (!func || !btf_type_is_func(func))
22502 		return NULL;
22503 	name = btf_name_by_offset(btf, func->name_off);
22504 
22505 	/*
22506 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
22507 	 * stable only once it is live; hold a module ref across the read to
22508 	 * exclude a concurrent module load.
22509 	 */
22510 	if (btf_is_module(btf)) {
22511 		mod = btf_try_get_module(btf);
22512 		if (!mod)
22513 			return NULL;
22514 	}
22515 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
22516 	module_put(mod);
22517 
22518 	if (implicit == -EINVAL) {
22519 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
22520 		return NULL;
22521 	}
22522 	if (implicit > 0)
22523 		return find_kfunc_impl_proto(log, btf, name);
22524 
22525 	return btf_type_by_id(btf, func->type);
22526 }
22527 
22528 static bool attach_uses_trampoline_retval(enum bpf_attach_type type)
22529 {
22530 	switch (type) {
22531 	case BPF_MODIFY_RETURN:
22532 	case BPF_TRACE_FEXIT:
22533 	case BPF_TRACE_FEXIT_MULTI:
22534 	case BPF_TRACE_FSESSION:
22535 	case BPF_TRACE_FSESSION_MULTI:
22536 		return true;
22537 	default:
22538 		return false;
22539 	}
22540 }
22541 
22542 /*
22543  * BPF code passes argument slot N where the kernel convention passes its Nth
22544  * u64 argument, so describe a BPF function to its trampoline as one u64 per
22545  * slot, and every arch places its arguments right.
22546  */
22547 static int flatten_bpf_func_model(struct bpf_verifier_log *log, const char *tname,
22548 				  struct btf_func_model *m)
22549 {
22550 	u32 i, nslots = 0;
22551 
22552 	for (i = 0; i < m->nr_args; i++)
22553 		nslots += btf_func_model_arg_slots(m, i);
22554 	if (nslots > MAX_BPF_FUNC_ARGS) {
22555 		bpf_log(log, "The function %s has %u argument slots. Too many.\n",
22556 			tname, nslots);
22557 		return -EINVAL;
22558 	}
22559 
22560 	for (i = 0; i < nslots; i++) {
22561 		m->arg_size[i] = sizeof(u64);
22562 		m->arg_flags[i] = 0;
22563 	}
22564 	m->nr_args = nslots;
22565 	return 0;
22566 }
22567 
22568 /*
22569  * The verifier lets a static function use stack arguments counted from its
22570  * BTF, even if that BTF turns out unreliable. A trampoline on the function is
22571  * then given only MAX_BPF_FUNC_REG_ARGS u64 arguments and would lose the
22572  * stack arguments, so such a function cannot be attached to.
22573  */
22574 static int check_unreliable_func_args(struct bpf_verifier_log *log, struct btf *btf,
22575 				      const struct btf_type *func_proto, const char *tname)
22576 {
22577 	struct btf_func_model m;
22578 	u32 i, nslots = 0;
22579 
22580 	if (btf_distill_func_proto(NULL, btf, func_proto, tname, &m)) {
22581 		/* at least a slot for each argument */
22582 		nslots = btf_type_vlen(func_proto);
22583 	} else {
22584 		for (i = 0; i < m.nr_args; i++)
22585 			nslots += btf_func_model_arg_slots(&m, i);
22586 	}
22587 	if (nslots <= MAX_BPF_FUNC_REG_ARGS)
22588 		return 0;
22589 
22590 	bpf_log(log, "Cannot attach to static function %s: unreliable BTF and stack arguments\n",
22591 		tname);
22592 	return -EINVAL;
22593 }
22594 
22595 /* Functions may share a type id. The first of them is attached to. */
22596 static int find_tgt_subprog(const struct bpf_prog *tgt_prog, u32 btf_id)
22597 {
22598 	const struct bpf_prog_aux *aux = tgt_prog->aux;
22599 	int i;
22600 
22601 	for (i = 0; i < aux->func_info_cnt; i++)
22602 		if (aux->func_info[i].type_id == btf_id)
22603 			return i;
22604 
22605 	return -1;
22606 }
22607 
22608 /*
22609  * The prologue of an extension gives a cloned skb a new head, unless the
22610  * prologue of the target program has done that. The callers of the function
22611  * that it replaces must not hold on to the old head.
22612  */
22613 int bpf_check_ext_prologue(struct bpf_verifier_log *log,
22614 			   const struct bpf_prog *tgt_prog, u32 btf_id)
22615 {
22616 	const struct bpf_prog_aux *aux = tgt_prog->aux;
22617 	int subprog = find_tgt_subprog(tgt_prog, btf_id);
22618 
22619 	if (aux->has_prologue)
22620 		return 0;
22621 
22622 	if (subprog >= 0 && !aux->func_info_aux[subprog].called_with_pkt_ptrs)
22623 		return 0;
22624 
22625 	bpf_log(log,
22626 		"Extension writing packet data cannot replace a function whose callers keep packet pointers\n");
22627 	return -EINVAL;
22628 }
22629 
22630 /*
22631  * An extension is verified as a program that runs under the RCU read lock. Does
22632  * the function that it is to replace?
22633  */
22634 static bool func_has_rcu_read_lock(const struct bpf_prog *prog, int subprog)
22635 {
22636 	const struct bpf_func_info_aux *sub_aux = &prog->aux->func_info_aux[subprog];
22637 
22638 	if (!subprog)
22639 		return !prog->sleepable;
22640 
22641 	return !sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] &&
22642 	       !sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK];
22643 }
22644 
22645 /*
22646  * The callers of a global function are checked against the arguments that its
22647  * BTF describes, and an extension is verified with those of its own BTF. It
22648  * must not expect more than the callers of the function provide.
22649  *
22650  * While an extension is loaded, bpf_check_attach_target() runs before its
22651  * arguments are known. check_attach_btf_id() does the check when they are.
22652  */
22653 static int check_ext_args(struct bpf_verifier_log *log, const struct bpf_prog *prog,
22654 			  const struct bpf_prog *tgt_prog, int subprog)
22655 {
22656 	const struct bpf_subprog_arg_info *tgt = tgt_prog->aux->func_info_aux[subprog].args;
22657 	const struct bpf_subprog_arg_info *ext = prog->aux->func_info_aux[0].args;
22658 	int i;
22659 
22660 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS && ext[i].arg_type != ARG_UNUSED; i++) {
22661 		/* An extension may accept NULL where the callers never pass it. */
22662 		if ((ext[i].arg_type == tgt[i].arg_type ||
22663 		     ext[i].arg_type == (tgt[i].arg_type | PTR_MAYBE_NULL)) &&
22664 		    (base_type(ext[i].arg_type) == ARG_PTR_TO_MEM ?
22665 		     ext[i].mem_size <= tgt[i].mem_size : ext[i].btf_id == tgt[i].btf_id))
22666 			continue;
22667 
22668 		bpf_log(log, "Extension program's argument in R%d is incompatible with original\n",
22669 			i + 1);
22670 		return -EINVAL;
22671 	}
22672 
22673 	return 0;
22674 }
22675 
22676 int bpf_check_attach_target(struct bpf_verifier_log *log,
22677 			    const struct bpf_prog *prog,
22678 			    const struct bpf_prog *tgt_prog,
22679 			    u32 btf_id,
22680 			    struct bpf_attach_target_info *tgt_info)
22681 {
22682 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22683 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22684 	char trace_symbol[KSYM_SYMBOL_LEN];
22685 	const char prefix[] = "btf_trace_";
22686 	struct bpf_raw_event_map *btp;
22687 	int ret = 0, subprog = -1;
22688 	const struct btf_type *t;
22689 	bool conservative = true;
22690 	const char *tname, *fname;
22691 	struct btf *btf;
22692 	long addr = 0;
22693 	struct module *mod = NULL;
22694 
22695 	if (!btf_id) {
22696 		bpf_log(log, "Tracing programs must provide btf_id\n");
22697 		return -EINVAL;
22698 	}
22699 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22700 	if (!btf) {
22701 		bpf_log(log,
22702 			"Tracing program can only be attached to another program annotated with BTF\n");
22703 		return -EINVAL;
22704 	}
22705 	t = btf_type_by_id(btf, btf_id);
22706 	if (!t) {
22707 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22708 		return -EINVAL;
22709 	}
22710 	tname = btf_name_by_offset(btf, t->name_off);
22711 	if (!tname) {
22712 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22713 		return -EINVAL;
22714 	}
22715 	if (tgt_prog) {
22716 		struct bpf_prog_aux *aux = tgt_prog->aux;
22717 		enum bpf_cgroup_storage_type stype;
22718 		bool tgt_changes_pkt_data;
22719 		bool tgt_might_sleep;
22720 		bool tgt_can_unwind;
22721 
22722 		if (bpf_prog_is_dev_bound(prog->aux) &&
22723 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22724 			bpf_log(log, "Target program bound device mismatch");
22725 			return -EINVAL;
22726 		}
22727 
22728 		subprog = find_tgt_subprog(tgt_prog, btf_id);
22729 		if (subprog == -1) {
22730 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22731 			return -EINVAL;
22732 		}
22733 		/*
22734 		 * A struct_ops indirect trampoline converts arena arguments
22735 		 * before invoking its program. A tracing or extension program
22736 		 * attached to the main program would see the converted offset as a
22737 		 * regular BTF pointer.
22738 		 */
22739 		if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) {
22740 			bpf_log(log, "Cannot attach to a target with arena context arguments\n");
22741 			return -EOPNOTSUPP;
22742 		}
22743 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22744 			bpf_log(log,
22745 				"%s programs cannot attach to exception callback\n",
22746 				prog_extension ? "Extension" : "Tracing");
22747 			return -EINVAL;
22748 		}
22749 		/* unwind_exit of the main prog is exit, unless it's an extension */
22750 		tgt_can_unwind = (subprog || tgt_prog->type == BPF_PROG_TYPE_EXT) &&
22751 				 (aux->func ? aux->func[subprog]->aux->can_unwind
22752 					    : aux->can_unwind);
22753 		/* unwind_exit would return to the trampoline that called the target */
22754 		if (tgt_can_unwind && !prog_extension &&
22755 		    prog->expected_attach_type != BPF_TRACE_FENTRY) {
22756 			bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);
22757 			return -EINVAL;
22758 		}
22759 		conservative = aux->func_info_aux[subprog].unreliable;
22760 		if (prog_extension) {
22761 			if (aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL ||
22762 			    conservative) {
22763 				bpf_log(log,
22764 					"Cannot replace static functions\n");
22765 				return -EINVAL;
22766 			}
22767 			if (!prog->jit_requested) {
22768 				bpf_log(log,
22769 					"Extension programs should be JITed\n");
22770 				return -EINVAL;
22771 			}
22772 			/* bpf_get_local_storage() returns the storage of the target */
22773 			for_each_cgroup_storage_type(stype) {
22774 				struct bpf_map *storage = prog->aux->cgroup_storage[stype];
22775 
22776 				if (storage && storage != aux->cgroup_storage[stype]) {
22777 					bpf_log(log,
22778 						"Extension program has another cgroup storage than original\n");
22779 					return -EINVAL;
22780 				}
22781 			}
22782 			/*
22783 			 * How much of the buffer of the tracepoint is used
22784 			 * is checked for the program that is attached to it.
22785 			 */
22786 			if (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) {
22787 				bpf_log(log,
22788 					"Cannot extend a writable raw tracepoint program\n");
22789 				return -EINVAL;
22790 			}
22791 			if (!func_has_rcu_read_lock(tgt_prog, subprog)) {
22792 				bpf_log(log,
22793 					"Cannot extend a function that runs without RCU read lock\n");
22794 				return -EINVAL;
22795 			}
22796 			tgt_changes_pkt_data = aux->func
22797 					       ? aux->func[subprog]->aux->changes_pkt_data
22798 					       : aux->changes_pkt_data;
22799 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
22800 				bpf_log(log,
22801 					"Extension program changes packet data, while original does not\n");
22802 				return -EINVAL;
22803 			}
22804 			if (prog->aux->has_prologue &&
22805 			    bpf_check_ext_prologue(log, tgt_prog, btf_id))
22806 				return -EINVAL;
22807 
22808 			tgt_might_sleep = aux->func
22809 					  ? aux->func[subprog]->aux->might_sleep
22810 					  : aux->might_sleep;
22811 			if (prog->aux->might_sleep && !tgt_might_sleep) {
22812 				bpf_log(log,
22813 					"Extension program may sleep, while original does not\n");
22814 				return -EINVAL;
22815 			}
22816 			/* There is no unwind_goto after the calls of the original */
22817 			if (prog->aux->can_unwind && !tgt_can_unwind) {
22818 				bpf_log(log,
22819 					"Extension program can unwind, while original does not\n");
22820 				return -EINVAL;
22821 			}
22822 		}
22823 		if (!tgt_prog->jited) {
22824 			bpf_log(log, "Can attach to only JITed progs\n");
22825 			return -EINVAL;
22826 		}
22827 		if (prog_tracing) {
22828 			if (aux->attach_tracing_prog) {
22829 				/*
22830 				 * Target program is an fentry/fexit which is already attached
22831 				 * to another tracing program. More levels of nesting
22832 				 * attachment are not allowed.
22833 				 */
22834 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22835 				return -EINVAL;
22836 			}
22837 		} else if (tgt_prog->type == prog->type) {
22838 			/*
22839 			 * To avoid potential call chain cycles, prevent attaching of a
22840 			 * program extension to another extension. It's ok to attach
22841 			 * fentry/fexit to extension program.
22842 			 */
22843 			bpf_log(log, "Cannot recursively attach\n");
22844 			return -EINVAL;
22845 		}
22846 		if (prog_extension &&
22847 		    (tgt_prog->type == BPF_PROG_TYPE_TRACING ||
22848 		     tgt_prog->type == BPF_PROG_TYPE_LSM ||
22849 		     tgt_prog->type == BPF_PROG_TYPE_STRUCT_OPS)) {
22850 			/*
22851 			 * These types are checked against the BTF of their hook,
22852 			 * and an extension has the BTF of its target instead.
22853 			 * There is one more reason for fentry/fexit.
22854 			 * The fentry/fexit programs are used for performance
22855 			 * analysis, stats and can be attached to any program
22856 			 * type. When extension program is replacing XDP function
22857 			 * it is necessary to allow performance analysis of all
22858 			 * functions. Both original XDP program and its program
22859 			 * extension. Hence attaching fentry/fexit to
22860 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22861 			 * fentry/fexit was allowed it would be possible to create
22862 			 * long call chain fentry->extension->fentry->extension
22863 			 * beyond reasonable stack size. Hence extending fentry
22864 			 * is not allowed.
22865 			 */
22866 			bpf_log(log, "Cannot extend tracing, LSM and struct_ops programs\n");
22867 			return -EINVAL;
22868 		}
22869 	} else {
22870 		if (prog_extension) {
22871 			bpf_log(log, "Cannot replace kernel functions\n");
22872 			return -EINVAL;
22873 		}
22874 	}
22875 
22876 	switch (prog->expected_attach_type) {
22877 	case BPF_TRACE_RAW_TP:
22878 		if (tgt_prog) {
22879 			bpf_log(log,
22880 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
22881 			return -EINVAL;
22882 		}
22883 		if (!btf_type_is_typedef(t)) {
22884 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22885 				btf_id);
22886 			return -EINVAL;
22887 		}
22888 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22889 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22890 				btf_id, tname);
22891 			return -EINVAL;
22892 		}
22893 		tname += sizeof(prefix) - 1;
22894 
22895 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22896 		 * names. Thus using bpf_raw_event_map to get argument names.
22897 		 */
22898 		btp = bpf_get_raw_tracepoint(tname);
22899 		if (!btp)
22900 			return -EINVAL;
22901 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
22902 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
22903 				tname);
22904 			bpf_put_raw_tracepoint(btp);
22905 			return -EINVAL;
22906 		}
22907 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22908 					trace_symbol);
22909 		bpf_put_raw_tracepoint(btp);
22910 
22911 		if (fname)
22912 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22913 
22914 		if (!fname || ret < 0) {
22915 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22916 				prefix, tname);
22917 			t = btf_type_by_id(btf, t->type);
22918 			if (!btf_type_is_ptr(t))
22919 				/* should never happen in valid vmlinux build */
22920 				return -EINVAL;
22921 		} else {
22922 			t = btf_type_by_id(btf, ret);
22923 			if (!btf_type_is_func(t))
22924 				/* should never happen in valid vmlinux build */
22925 				return -EINVAL;
22926 		}
22927 
22928 		t = btf_type_by_id(btf, t->type);
22929 		if (!btf_type_is_func_proto(t))
22930 			/* should never happen in valid vmlinux build */
22931 			return -EINVAL;
22932 
22933 		break;
22934 	case BPF_TRACE_ITER:
22935 		if (!btf_type_is_func(t)) {
22936 			bpf_log(log, "attach_btf_id %u is not a function\n",
22937 				btf_id);
22938 			return -EINVAL;
22939 		}
22940 		t = btf_type_by_id(btf, t->type);
22941 		if (!btf_type_is_func_proto(t))
22942 			return -EINVAL;
22943 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22944 		if (ret)
22945 			return ret;
22946 		break;
22947 	default:
22948 		if (!prog_extension)
22949 			return -EINVAL;
22950 		fallthrough;
22951 	case BPF_MODIFY_RETURN:
22952 	case BPF_LSM_MAC:
22953 	case BPF_LSM_CGROUP:
22954 	case BPF_TRACE_FENTRY:
22955 	case BPF_TRACE_FEXIT:
22956 	case BPF_TRACE_FSESSION:
22957 	case BPF_TRACE_FSESSION_MULTI:
22958 	case BPF_TRACE_FENTRY_MULTI:
22959 	case BPF_TRACE_FEXIT_MULTI:
22960 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
22961 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
22962 		    !bpf_jit_supports_fsession()) {
22963 			bpf_log(log, "JIT does not support fsession\n");
22964 			return -EOPNOTSUPP;
22965 		}
22966 		if (!btf_type_is_func(t)) {
22967 			bpf_log(log, "attach_btf_id %u is not a function\n",
22968 				btf_id);
22969 			return -EINVAL;
22970 		}
22971 		if (prog_extension &&
22972 		    (btf_check_type_match(log, prog, btf, t) ||
22973 		     check_ext_args(log, prog, tgt_prog, subprog)))
22974 			return -EINVAL;
22975 		t = btf_attach_func_proto(log, btf, btf_id);
22976 		if (!t || !btf_type_is_func_proto(t))
22977 			return -EINVAL;
22978 
22979 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22980 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22981 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22982 			return -EINVAL;
22983 
22984 		if (tgt_prog && conservative) {
22985 			if (subprog > 0) {
22986 				ret = check_unreliable_func_args(log, btf, t, tname);
22987 				if (ret)
22988 					return ret;
22989 			}
22990 			t = NULL;
22991 		}
22992 
22993 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22994 		if (ret < 0)
22995 			return ret;
22996 		if (tgt_prog) {
22997 			ret = flatten_bpf_func_model(log, tname, &tgt_info->fmodel);
22998 			if (ret < 0)
22999 				return ret;
23000 		}
23001 
23002 		if (tgt_info->fmodel.ret_size > 8 &&
23003 		    attach_uses_trampoline_retval(prog->expected_attach_type)) {
23004 			bpf_log(log,
23005 				"Attach to function %s with a >8 byte return value is not supported for this attach type\n",
23006 				tname);
23007 			return -EOPNOTSUPP;
23008 		}
23009 
23010 		/*
23011 		 * *.multi programs don't need an address during program
23012 		 * verification, we just take the module ref if needed.
23013 		 */
23014 		if (is_tracing_multi_id(prog, btf_id)) {
23015 			if (btf_is_module(btf)) {
23016 				mod = btf_try_get_module(btf);
23017 				if (!mod)
23018 					return -ENOENT;
23019 			}
23020 			addr = 0;
23021 		} else if (tgt_prog) {
23022 			if (subprog == 0)
23023 				addr = (long) tgt_prog->bpf_func;
23024 			else
23025 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23026 		} else {
23027 			if (btf_is_module(btf)) {
23028 				mod = btf_try_get_module(btf);
23029 				if (mod)
23030 					addr = find_kallsyms_symbol_value(mod, tname);
23031 				else
23032 					addr = 0;
23033 			} else {
23034 				addr = kallsyms_lookup_name(tname);
23035 			}
23036 			if (!addr) {
23037 				module_put(mod);
23038 				bpf_log(log,
23039 					"The address of function %s cannot be found\n",
23040 					tname);
23041 				return -ENOENT;
23042 			}
23043 		}
23044 
23045 		if (prog->sleepable) {
23046 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
23047 			if (ret) {
23048 				module_put(mod);
23049 				bpf_log(log, "%s is not sleepable\n", tname);
23050 				return ret;
23051 			}
23052 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23053 			if (tgt_prog) {
23054 				module_put(mod);
23055 				bpf_log(log, "can't modify return codes of BPF programs\n");
23056 				return -EINVAL;
23057 			}
23058 			ret = -EINVAL;
23059 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23060 			    !check_attach_modify_return(addr, tname))
23061 				ret = 0;
23062 			if (ret) {
23063 				module_put(mod);
23064 				bpf_log(log, "%s() is not modifiable\n", tname);
23065 				return ret;
23066 			}
23067 		}
23068 
23069 		break;
23070 	}
23071 	tgt_info->tgt_addr = addr;
23072 	tgt_info->tgt_name = tname;
23073 	tgt_info->tgt_type = t;
23074 	tgt_info->tgt_mod = mod;
23075 	return 0;
23076 }
23077 
23078 BTF_SET_START(btf_id_deny)
23079 BTF_ID_UNUSED
23080 #ifdef CONFIG_SMP
23081 BTF_ID(func, ___migrate_enable)
23082 BTF_ID(func, migrate_disable)
23083 BTF_ID(func, migrate_enable)
23084 #endif
23085 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23086 BTF_ID(func, rcu_read_unlock_strict)
23087 #endif
23088 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23089 BTF_ID(func, preempt_count_add)
23090 BTF_ID(func, preempt_count_sub)
23091 #endif
23092 #ifdef CONFIG_PREEMPT_RCU
23093 BTF_ID(func, __rcu_read_lock)
23094 BTF_ID(func, __rcu_read_unlock)
23095 #endif
23096 BTF_SET_END(btf_id_deny)
23097 
23098 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23099  * Currently, we must manually list all __noreturn functions here. Once a more
23100  * robust solution is implemented, this workaround can be removed.
23101  */
23102 BTF_SET_START(noreturn_deny)
23103 #ifdef CONFIG_IA32_EMULATION
23104 BTF_ID(func, __ia32_sys_exit)
23105 BTF_ID(func, __ia32_sys_exit_group)
23106 #endif
23107 #ifdef CONFIG_KUNIT
23108 BTF_ID(func, __kunit_abort)
23109 BTF_ID(func, kunit_try_catch_throw)
23110 #endif
23111 #ifdef CONFIG_MODULES
23112 BTF_ID(func, __module_put_and_kthread_exit)
23113 #endif
23114 #ifdef CONFIG_X86_64
23115 BTF_ID(func, __x64_sys_exit)
23116 BTF_ID(func, __x64_sys_exit_group)
23117 #endif
23118 BTF_ID(func, do_exit)
23119 BTF_ID(func, do_group_exit)
23120 BTF_ID(func, kthread_complete_and_exit)
23121 BTF_ID(func, make_task_dead)
23122 BTF_SET_END(noreturn_deny)
23123 
23124 static bool can_be_sleepable(struct bpf_prog *prog)
23125 {
23126 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23127 		switch (prog->expected_attach_type) {
23128 		case BPF_TRACE_FENTRY:
23129 		case BPF_TRACE_FEXIT:
23130 		case BPF_MODIFY_RETURN:
23131 		case BPF_TRACE_ITER:
23132 		case BPF_TRACE_FSESSION:
23133 		case BPF_TRACE_RAW_TP:
23134 		case BPF_TRACE_FENTRY_MULTI:
23135 		case BPF_TRACE_FEXIT_MULTI:
23136 		case BPF_TRACE_FSESSION_MULTI:
23137 			return true;
23138 		default:
23139 			return false;
23140 		}
23141 	}
23142 	if (prog->type == BPF_PROG_TYPE_LSM)
23143 		return prog->expected_attach_type != BPF_LSM_CGROUP;
23144 
23145 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23146 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
23147 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
23148 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
23149 }
23150 
23151 static int check_attach_btf_id(struct bpf_verifier_env *env)
23152 {
23153 	struct bpf_prog *prog = env->prog;
23154 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23155 	struct bpf_attach_target_info tgt_info = {};
23156 	u32 btf_id = prog->aux->attach_btf_id;
23157 	struct bpf_trampoline *tr;
23158 	int ret;
23159 	u64 key;
23160 
23161 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23162 		if (prog->sleepable)
23163 			/* attach_btf_id checked to be zero already */
23164 			return 0;
23165 		verbose(env, "Syscall programs can only be sleepable\n");
23166 		return -EINVAL;
23167 	}
23168 
23169 	if (prog->sleepable && !can_be_sleepable(prog)) {
23170 		verbose(env, "Program of this type cannot be sleepable\n");
23171 		return -EINVAL;
23172 	}
23173 
23174 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23175 		return check_struct_ops_btf_id(env);
23176 
23177 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23178 	    prog->type != BPF_PROG_TYPE_LSM &&
23179 	    prog->type != BPF_PROG_TYPE_EXT)
23180 		return 0;
23181 
23182 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23183 	if (ret)
23184 		return ret;
23185 
23186 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23187 		/* to make freplace equivalent to their targets, they need to
23188 		 * inherit env->ops and expected_attach_type for the rest of the
23189 		 * verification
23190 		 */
23191 		env->ops = bpf_verifier_ops[tgt_prog->type];
23192 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23193 
23194 		/* only now it is known what the arguments of prog stand for */
23195 		ret = btf_prepare_func_args(env, 0);
23196 		if (ret)
23197 			return ret;
23198 		ret = check_ext_args(&env->log, prog, tgt_prog,
23199 				     find_tgt_subprog(tgt_prog, btf_id));
23200 		if (ret)
23201 			return ret;
23202 	}
23203 
23204 	/* store info about the attachment target that will be used later */
23205 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23206 	prog->aux->attach_func_name = tgt_info.tgt_name;
23207 	prog->aux->mod = tgt_info.tgt_mod;
23208 
23209 	if (tgt_prog) {
23210 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23211 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23212 	}
23213 
23214 	/* An extension has expected_attach_type of its target, it can be any value */
23215 	if (prog->type != BPF_PROG_TYPE_EXT &&
23216 	    prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23217 		prog->aux->attach_btf_trace = true;
23218 		return 0;
23219 	} else if (prog->type != BPF_PROG_TYPE_EXT &&
23220 		   prog->expected_attach_type == BPF_TRACE_ITER) {
23221 		return bpf_iter_prog_supported(prog);
23222 	}
23223 
23224 	if (prog->type == BPF_PROG_TYPE_LSM) {
23225 		ret = bpf_lsm_verify_prog(&env->log, prog);
23226 		if (ret < 0)
23227 			return ret;
23228 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23229 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23230 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23231 			tgt_info.tgt_name);
23232 		return -EINVAL;
23233 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23234 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
23235 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
23236 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23237 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23238 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
23239 			tgt_info.tgt_name);
23240 		return -EINVAL;
23241 	}
23242 
23243 	/*
23244 	 * We don't get trampoline for tracing_multi programs at this point,
23245 	 * it's done when tracing_multi link is created.
23246 	 */
23247 	if (prog->type == BPF_PROG_TYPE_TRACING &&
23248 	    is_tracing_multi(prog->expected_attach_type))
23249 		return 0;
23250 
23251 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23252 	tr = bpf_trampoline_get(key, &tgt_info);
23253 	if (!tr)
23254 		return -ENOMEM;
23255 
23256 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
23257 		bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX);
23258 
23259 	prog->aux->dst_trampoline = tr;
23260 	return 0;
23261 }
23262 
23263 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
23264 				  struct bpf_attach_target_info *tgt_info)
23265 {
23266 	const struct btf_type *t;
23267 	unsigned long addr;
23268 	const char *tname;
23269 	int err;
23270 
23271 	if (!btf_id || !btf)
23272 		return -EINVAL;
23273 
23274 	/* Check noreturn attachment. */
23275 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
23276 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
23277 	     btf_id_set_contains(&noreturn_deny, btf_id))
23278 		return -EINVAL;
23279 	/* Check denied attachment. */
23280 	if (btf_id_set_contains(&btf_id_deny, btf_id))
23281 		return -EINVAL;
23282 
23283 	/* Check and get function target data. */
23284 	t = btf_type_by_id(btf, btf_id);
23285 	if (!t)
23286 		return -EINVAL;
23287 	tname = btf_name_by_offset(btf, t->name_off);
23288 	if (!tname)
23289 		return -EINVAL;
23290 	t = btf_attach_func_proto(NULL, btf, btf_id);
23291 	if (!t || !btf_type_is_func_proto(t))
23292 		return -EINVAL;
23293 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
23294 	if (err < 0)
23295 		return err;
23296 	if (tgt_info->fmodel.ret_size > 8 &&
23297 	    attach_uses_trampoline_retval(prog->expected_attach_type))
23298 		return -EOPNOTSUPP;
23299 	if (btf_is_module(btf)) {
23300 		/* The bpf program already holds reference to module. */
23301 		if (WARN_ON_ONCE(!prog->aux->mod))
23302 			return -EINVAL;
23303 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
23304 	} else {
23305 		addr = kallsyms_lookup_name(tname);
23306 	}
23307 	if (!addr || !ftrace_location(addr))
23308 		return -ENOENT;
23309 
23310 	/* Check sleepable program attachment. */
23311 	if (prog->sleepable) {
23312 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
23313 		if (err)
23314 			return err;
23315 	}
23316 	tgt_info->tgt_addr = addr;
23317 	return 0;
23318 }
23319 
23320 struct btf *bpf_get_btf_vmlinux(void)
23321 {
23322 	/* Pairs with the smp_store_release() on the parse path below. */
23323 	struct btf *btf = smp_load_acquire(&btf_vmlinux);
23324 
23325 	if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
23326 		mutex_lock(&btf_vmlinux_lock);
23327 		btf = btf_vmlinux;
23328 		if (!btf) {
23329 			btf = btf_parse_vmlinux();
23330 			/*
23331 			 * Order the parsed BTF contents and the globals the
23332 			 * parse populated (e.g. bpf_ctx_convert.t) before
23333 			 * the pointer publication. Pairs with the acquire
23334 			 * on the lockless fast path above.
23335 			 */
23336 			smp_store_release(&btf_vmlinux, btf);
23337 		}
23338 		mutex_unlock(&btf_vmlinux_lock);
23339 	}
23340 	return btf;
23341 }
23342 
23343 /*
23344  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
23345  * this case expect that every file descriptor in the array is either a map or
23346  * a BTF. Everything else is considered to be trash.
23347  */
23348 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd)
23349 {
23350 	struct bpf_map *map;
23351 	struct btf *btf;
23352 	CLASS(fd, f)(fd);
23353 	int err;
23354 
23355 	map = __bpf_map_get(f);
23356 	if (!IS_ERR(map)) {
23357 		err = __add_used_map(env, map);
23358 		if (err < 0)
23359 			return err;
23360 		fd_slot_set_map(&env->fd_array[idx], map);
23361 		return 0;
23362 	}
23363 
23364 	btf = __btf_get_by_fd(f);
23365 	if (!IS_ERR(btf)) {
23366 		btf_get(btf);
23367 		err = __add_used_btf(env, btf);
23368 		if (err < 0)
23369 			return err;
23370 		fd_slot_set_btf(&env->fd_array[idx], btf);
23371 		return 0;
23372 	}
23373 
23374 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
23375 	return PTR_ERR(map);
23376 }
23377 
23378 /*
23379  * A continuous fd_array is resolved into an in-memory cache with one slot
23380  * per entry. The bound here is deliberately generous and not derived from
23381  * the per-program object limits: Duplicate entries /are/ permitted, and
23382  * the number of distinct maps and BTFs a program can bind is enforced when
23383  * each entry is resolved by __add_used_map() and __add_used_btf().
23384  */
23385 #define MAX_FD_ARRAY_CNT 4096
23386 
23387 static int process_fd_array_continuous(struct bpf_verifier_env *env,
23388 				       bpfptr_t fd_array, u32 cnt)
23389 {
23390 	int fd, ret;
23391 	u32 i;
23392 
23393 	if (cnt > MAX_FD_ARRAY_CNT) {
23394 		verbose(env, "fd_array has too many entries (%u, max %u)\n",
23395 			cnt, MAX_FD_ARRAY_CNT);
23396 		return -E2BIG;
23397 	}
23398 
23399 	env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT);
23400 	if (!env->fd_array)
23401 		return -ENOMEM;
23402 	env->fd_array_cnt = cnt;
23403 	for (i = 0; i < cnt; i++) {
23404 		if (copy_from_bpfptr_offset(&fd, fd_array,
23405 					    (size_t)i * sizeof(fd), sizeof(fd)))
23406 			return -EFAULT;
23407 		ret = add_fd_from_fd_array(env, i, fd);
23408 		if (ret)
23409 			return ret;
23410 	}
23411 	return 0;
23412 }
23413 
23414 static int process_fd_array(struct bpf_verifier_env *env,
23415 			    union bpf_attr *attr, bpfptr_t uattr)
23416 {
23417 	bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
23418 
23419 	if (bpfptr_is_null(fd_array)) {
23420 		if (attr->fd_array_cnt) {
23421 			verbose(env, "fd_array_cnt %u without fd_array is invalid\n",
23422 				attr->fd_array_cnt);
23423 			return -EINVAL;
23424 		}
23425 		return 0;
23426 	}
23427 	/*
23428 	 * New API: the caller passes fd_array_cnt and a continuous array that
23429 	 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep
23430 	 * the caller's array and resolve entries on the spot at each reference.
23431 	 */
23432 	if (attr->fd_array_cnt)
23433 		return process_fd_array_continuous(env, fd_array,
23434 						   attr->fd_array_cnt);
23435 	env->fd_array_raw = fd_array;
23436 	return 0;
23437 }
23438 
23439 /* replace a generic kfunc with a specialized version if necessary */
23440 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
23441 {
23442 	struct bpf_prog *prog = env->prog;
23443 	bool seen_direct_write;
23444 	void *xdp_kfunc;
23445 	bool is_rdonly;
23446 	u32 func_id = desc->func_id;
23447 	u16 offset = desc->offset;
23448 	unsigned long addr = desc->addr;
23449 
23450 	if (offset) /* return if module BTF is used */
23451 		return 0;
23452 
23453 	if (bpf_dev_bound_kfunc_id(func_id)) {
23454 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
23455 		if (xdp_kfunc)
23456 			addr = (unsigned long)xdp_kfunc;
23457 		/* fallback to default kfunc when not supported by netdev */
23458 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
23459 		seen_direct_write = env->seen_direct_write;
23460 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
23461 
23462 		if (is_rdonly)
23463 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
23464 
23465 		/* restore env->seen_direct_write to its original value, since
23466 		 * may_access_direct_pkt_data mutates it
23467 		 */
23468 		env->seen_direct_write = seen_direct_write;
23469 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
23470 		if (bpf_lsm_has_d_inode_locked(prog))
23471 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
23472 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
23473 		if (bpf_lsm_has_d_inode_locked(prog))
23474 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
23475 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
23476 		if (!env->insn_aux_data[insn_idx].non_sleepable)
23477 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
23478 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
23479 		if (env->insn_aux_data[insn_idx].non_sleepable)
23480 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
23481 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
23482 		if (env->insn_aux_data[insn_idx].non_sleepable)
23483 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
23484 	}
23485 	desc->addr = addr;
23486 	return 0;
23487 }
23488 
23489 static int add_kfunc_desc_target(struct bpf_verifier_env *env,
23490 				 const struct bpf_kfunc_desc *target_desc,
23491 				 u16 base_desc_idx, u16 *desc_idx)
23492 {
23493 	struct bpf_kfunc_desc desc = *target_desc;
23494 	struct bpf_kfunc_desc_tab *new_tab;
23495 	struct bpf_kfunc_desc_tab *tab;
23496 	struct bpf_prog_aux *prog_aux;
23497 	u32 i;
23498 
23499 	prog_aux = env->prog->aux;
23500 	tab = prog_aux->kfunc_tab;
23501 
23502 	if (base_desc_idx >= tab->nr_base_descs) {
23503 		verifier_bug(env, "kfunc desc_idx %d out of bounds (%d descriptors)",
23504 				base_desc_idx, tab->nr_base_descs);
23505 		return -EFAULT;
23506 	}
23507 	if (tab->descs[base_desc_idx].func_id != desc.func_id) {
23508 		verifier_bug(env, "kfunc desc %d has invalid id (expected %d, got %d)",
23509 				base_desc_idx, tab->descs[base_desc_idx].func_id, desc.func_id);
23510 		return -EFAULT;
23511 	}
23512 	if (tab->descs[base_desc_idx].offset != desc.offset) {
23513 		verifier_bug(env, "kfunc desc %d has invalid offset (expected %d, got %d)",
23514 				base_desc_idx, tab->descs[base_desc_idx].offset, desc.offset);
23515 		return -EFAULT;
23516 	}
23517 
23518 	if (tab->descs[base_desc_idx].addr == desc.addr) {
23519 		*desc_idx = base_desc_idx;
23520 		return 0;
23521 	}
23522 
23523 	for (i = tab->nr_base_descs; i < tab->nr_descs; i++) {
23524 		if (tab->descs[i].func_id == desc.func_id &&
23525 		    tab->descs[i].offset == desc.offset &&
23526 		    tab->descs[i].addr == desc.addr) {
23527 			*desc_idx = i;
23528 			return 0;
23529 		}
23530 	}
23531 
23532 	if (tab->nr_descs == MAX_KFUNC_CALL_DESCS) {
23533 		verbose(env, "too many different kernel function call targets\n");
23534 		return -E2BIG;
23535 	}
23536 
23537 	new_tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1),
23538 			   GFP_KERNEL_ACCOUNT);
23539 	if (!new_tab)
23540 		return -ENOMEM;
23541 	tab = new_tab;
23542 	prog_aux->kfunc_tab = tab;
23543 
23544 	*desc_idx = tab->nr_descs;
23545 	tab->descs[tab->nr_descs++] = desc;
23546 	return 0;
23547 }
23548 
23549 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
23550 					    u16 struct_meta_reg,
23551 					    u16 node_offset_reg,
23552 					    struct bpf_insn *insn,
23553 					    struct bpf_insn *insn_buf,
23554 					    int *cnt)
23555 {
23556 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
23557 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
23558 
23559 	insn_buf[0] = addr[0];
23560 	insn_buf[1] = addr[1];
23561 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
23562 	insn_buf[3] = *insn;
23563 	*cnt = 4;
23564 }
23565 
23566 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
23567 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
23568 {
23569 	struct bpf_kfunc_desc desc_copy;
23570 	struct bpf_kfunc_desc *desc;
23571 	unsigned long call_imm;
23572 	u16 base_desc_idx, desc_idx;
23573 	bool near_call;
23574 	int err;
23575 
23576 	if (!insn->imm) {
23577 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
23578 		return -EINVAL;
23579 	}
23580 
23581 	*cnt = 0;
23582 
23583 	/* insn->imm has the btf func_id. Replace it with an offset relative to
23584 	 * __bpf_call_base, unless the JIT needs to call functions that are
23585 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
23586 	 */
23587 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
23588 	if (!desc) {
23589 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
23590 			     insn->imm);
23591 		return -EFAULT;
23592 	}
23593 	base_desc_idx = desc - env->prog->aux->kfunc_tab->descs;
23594 
23595 	near_call = !bpf_jit_supports_far_kfunc_call();
23596 	desc_copy = *desc;
23597 	desc = &desc_copy;
23598 
23599 	err = specialize_kfunc(env, desc, insn_idx);
23600 	if (err)
23601 		return err;
23602 
23603 	if (near_call) {
23604 		call_imm = BPF_CALL_IMM(desc->addr);
23605 		if ((unsigned long)(s32)call_imm != call_imm) {
23606 			verbose(env, "address of kernel func_id %u is out of range\n",
23607 				desc->func_id);
23608 			return -EINVAL;
23609 		}
23610 		insn->imm = call_imm;
23611 	}
23612 
23613 	err = add_kfunc_desc_target(env, desc, base_desc_idx, &desc_idx);
23614 	if (err)
23615 		return err;
23616 	insn->off = desc_idx;
23617 
23618 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
23619 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23620 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23621 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
23622 
23623 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
23624 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23625 				     insn_idx);
23626 			return -EFAULT;
23627 		}
23628 
23629 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
23630 		insn_buf[1] = addr[0];
23631 		insn_buf[2] = addr[1];
23632 		insn_buf[3] = *insn;
23633 		*cnt = 4;
23634 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
23635 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
23636 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
23637 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23638 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23639 
23640 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
23641 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23642 				     insn_idx);
23643 			return -EFAULT;
23644 		}
23645 
23646 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
23647 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23648 				     insn_idx);
23649 			return -EFAULT;
23650 		}
23651 
23652 		insn_buf[0] = addr[0];
23653 		insn_buf[1] = addr[1];
23654 		insn_buf[2] = *insn;
23655 		*cnt = 3;
23656 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
23657 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
23658 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23659 		int struct_meta_reg = BPF_REG_3;
23660 		int node_offset_reg = BPF_REG_4;
23661 
23662 		/* list_add/rbtree_add have an extra arg (prev/less),
23663 		 * so args-to-fixup are in diff regs.
23664 		 */
23665 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
23666 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
23667 			struct_meta_reg = BPF_REG_4;
23668 			node_offset_reg = BPF_REG_5;
23669 		}
23670 
23671 		if (!kptr_struct_meta) {
23672 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23673 				     insn_idx);
23674 			return -EFAULT;
23675 		}
23676 
23677 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
23678 						node_offset_reg, insn, insn_buf, cnt);
23679 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
23680 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
23681 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23682 		*cnt = 1;
23683 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
23684 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
23685 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
23686 
23687 		/*
23688 		 * inline the bpf_session_is_return() for fsession:
23689 		 *   bool bpf_session_is_return(void *ctx)
23690 		 *   {
23691 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
23692 		 *   }
23693 		 */
23694 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23695 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
23696 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
23697 		*cnt = 3;
23698 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
23699 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
23700 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
23701 		/*
23702 		 * inline bpf_session_cookie() for fsession:
23703 		 *   __u64 *bpf_session_cookie(void *ctx)
23704 		 *   {
23705 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
23706 		 *       return &((u64 *)ctx)[-off];
23707 		 *   }
23708 		 */
23709 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23710 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
23711 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
23712 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23713 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
23714 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
23715 		*cnt = 6;
23716 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) {
23717 		/* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */
23718 		int i = 0;
23719 
23720 		/* if (start > end) goto einval; */
23721 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8);
23722 		/* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */
23723 		insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3);
23724 		insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2);
23725 		insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8);
23726 		/* s->cur = start - 1; s->end = end; return 0; */
23727 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1);
23728 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0);
23729 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4);
23730 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23731 		insn_buf[i++] = BPF_JMP_A(5);
23732 		/* einval: s->cur = s->end = 0; return -EINVAL; */
23733 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23734 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23735 		insn_buf[i++] = BPF_JMP_A(2);
23736 		/* e2big: s->cur = s->end = 0; return -E2BIG; */
23737 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23738 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
23739 		*cnt = i;
23740 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) {
23741 		/* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */
23742 		int i = 0;
23743 
23744 		/* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */
23745 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0);
23746 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1);
23747 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4);
23748 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3);
23749 		/* s->cur = r0; return &s->cur; */
23750 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0);
23751 		insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23752 		insn_buf[i++] = BPF_JMP_A(2);
23753 		/* done: s->cur = s->end = 0; return NULL; */
23754 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23755 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23756 		*cnt = i;
23757 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) {
23758 		/* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */
23759 		insn_buf[0] = BPF_JMP_A(0);
23760 		*cnt = 1;
23761 	}
23762 
23763 	if (env->insn_aux_data[insn_idx].arg_prog) {
23764 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
23765 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
23766 		int idx = *cnt;
23767 
23768 		insn_buf[idx++] = ld_addrs[0];
23769 		insn_buf[idx++] = ld_addrs[1];
23770 		insn_buf[idx++] = *insn;
23771 		*cnt = idx;
23772 	}
23773 	return 0;
23774 }
23775 
23776 /*
23777  * Upper bound on the PKCS#7 signature blob passed with a program. Comfortably
23778  * above the largest signature the kernel can verify, and far below anything
23779  * that would make rejecting a load expensive. Deliberately a fixed number so
23780  * that what the syscall accepts does not depend on PAGE_SIZE.
23781  */
23782 #define BPF_PROG_MAX_SIGNATURE_SIZE	(64 * 1024)
23783 
23784 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id)
23785 {
23786 	switch (keyring_id) {
23787 	case 0:
23788 		return BPF_SIG_KEYRING_BUILTIN;
23789 	case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING:
23790 		return BPF_SIG_KEYRING_SECONDARY;
23791 	case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING:
23792 		return BPF_SIG_KEYRING_PLATFORM;
23793 	case KEY_SPEC_BPF_KEYRING:
23794 		return BPF_SIG_KEYRING_BPF;
23795 	default:
23796 		return BPF_SIG_KEYRING_USER;
23797 	}
23798 }
23799 
23800 /*
23801  * Verify the PKCS#7 signature of a loaded program. Called from bpf_check()
23802  * once the program's metadata maps have been resolved into used_maps, so
23803  * the exact maps folded into the signature are the ones the program binds.
23804  *
23805  * The signature covers the instructions followed by the frozen contents of
23806  * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the
23807  * verdict and keyring info are recorded on prog->aux.
23808  */
23809 static int bpf_prog_verify_signature(struct bpf_verifier_env *env,
23810 				     union bpf_attr *attr, bool is_kernel)
23811 {
23812 	bpfptr_t usig = make_bpfptr(attr->signature, is_kernel);
23813 	struct bpf_dynptr_kern sig_ptr, data_ptr;
23814 	struct bpf_prog *prog = env->prog;
23815 	struct bpf_map **maps = env->used_maps;
23816 	struct bpf_key *key = NULL;
23817 	void *sig, *data = NULL;
23818 	u32 map_cnt = env->used_map_cnt;
23819 	u32 i, off, insns_sz;
23820 	u64 data_sz;
23821 	int err = 0;
23822 
23823 	/*
23824 	 * The signature covers the insns as submitted. CO-RE relocations would
23825 	 * have the kernel rewrite them afterwards, with values the loader picks
23826 	 * through the BTF it supplies, see bpf_check_core_relo().
23827 	 */
23828 	if (attr->core_relo_cnt) {
23829 		verbose(env, "signed program cannot carry CO-RE relocations\n");
23830 		return -EACCES;
23831 	}
23832 	if (!attr->signature_size ||
23833 	    attr->signature_size > BPF_PROG_MAX_SIGNATURE_SIZE)
23834 		return -EINVAL;
23835 
23836 	if (system_keyring_id_check(attr->keyring_id) == 0) {
23837 		key = bpf_lookup_system_key(attr->keyring_id);
23838 	} else if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23839 		key = bpf_lookup_keyring();
23840 	} else if (bpf_keyring_enforced()) {
23841 		verbose(env, "caller-supplied keyring refused, use bpf keyring\n");
23842 		return -EPERM;
23843 	} else {
23844 		key = bpf_lookup_user_key(attr->keyring_id, 0);
23845 	}
23846 	if (!key) {
23847 		if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23848 			verbose(env, "the bpf keyring is empty or has not been restricted\n");
23849 			return -ENOKEY;
23850 		}
23851 		verbose(env, "cannot resolve signing keyring with keyring_id %d\n",
23852 			attr->keyring_id);
23853 		return -EINVAL;
23854 	}
23855 
23856 	sig = kvmemdup_bpfptr(usig, attr->signature_size);
23857 	if (IS_ERR(sig)) {
23858 		bpf_key_put(key);
23859 		return PTR_ERR(sig);
23860 	}
23861 
23862 	insns_sz = prog->len * sizeof(struct bpf_insn);
23863 	data_sz = insns_sz;
23864 	for (i = 0; i < map_cnt; i++) {
23865 		struct bpf_map *map = maps[i];
23866 
23867 		if (map->map_type != BPF_MAP_TYPE_ARRAY ||
23868 		    !map->ops->map_direct_value_addr) {
23869 			verbose(env, "signed program metadata map '%s' must be an array\n",
23870 				map->name);
23871 			err = -EINVAL;
23872 			goto out;
23873 		}
23874 		if (!READ_ONCE(map->frozen)) {
23875 			verbose(env, "signed program metadata map '%s' must be frozen\n",
23876 				map->name);
23877 			err = -EPERM;
23878 			goto out;
23879 		}
23880 		if (bpf_map_write_active(map)) {
23881 			verbose(env, "signed program metadata map '%s' has active writers\n",
23882 				map->name);
23883 			err = -EBUSY;
23884 			goto out;
23885 		}
23886 		if (!map->excl_prog_sha) {
23887 			verbose(env, "signed program metadata map '%s' must be exclusive\n",
23888 				map->name);
23889 			err = -EPERM;
23890 			goto out;
23891 		}
23892 		/* The freeze is not final for it, see bpf_map_mmap() */
23893 		if ((map->map_flags & BPF_F_MMAPABLE) && !(map->map_flags & BPF_F_RDONLY_PROG)) {
23894 			verbose(env, "signed program metadata map '%s' must not be mmapable\n",
23895 				map->name);
23896 			err = -EPERM;
23897 			goto out;
23898 		}
23899 		data_sz += map->value_size;
23900 	}
23901 	if (bpf_dynptr_check_size(data_sz)) {
23902 		verbose(env, "signed payload too large: %llu bytes\n", data_sz);
23903 		err = -E2BIG;
23904 		goto out;
23905 	}
23906 	data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
23907 	if (!data) {
23908 		err = -ENOMEM;
23909 		goto out;
23910 	}
23911 	memcpy(data, prog->insnsi, insns_sz);
23912 	off = insns_sz;
23913 	for (i = 0; i < map_cnt; i++) {
23914 		struct bpf_map *map = maps[i];
23915 		u64 addr;
23916 
23917 		err = map->ops->map_direct_value_addr(map, &addr, 0);
23918 		if (err) {
23919 			verbose(env, "failed to read signed metadata map '%s': %d\n",
23920 				map->name, err);
23921 			goto out;
23922 		}
23923 		memcpy(data + off, (void *)(unsigned long)addr,
23924 		       map->value_size);
23925 		off += map->value_size;
23926 	}
23927 
23928 	bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz);
23929 	bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0,
23930 			attr->signature_size);
23931 
23932 	err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr,
23933 					 (struct bpf_dynptr *)&sig_ptr, key);
23934 	if (err) {
23935 		verbose(env, "signature verification failed: %d\n", err);
23936 	} else {
23937 		verbose(env, "signature verification passed\n");
23938 		prog->aux->sig.keyring_serial = bpf_key_serial(key);
23939 		prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id);
23940 		prog->aux->sig.verdict = BPF_SIG_VERIFIED;
23941 	}
23942 out:
23943 	kvfree(data);
23944 	bpf_key_put(key);
23945 	kvfree(sig);
23946 	return err;
23947 }
23948 
23949 /*
23950  * bpf_clone_redirect() transmits from inside the program, so a tc egress or
23951  * lwt_xmit program that redirects to its own device runs again on top of its
23952  * own frame, and again from there, until the datapath's recursion limit drops
23953  * the packet: ten frames deep. Ten MAX_BPF_STACK frames fit the kernel stack
23954  * as they always did; ten MAX_BPF_STACK_JIT frames would not, so a program
23955  * calling it keeps the smaller budget. The redirect helpers that transmit
23956  * after the program has returned leave no frame behind.
23957  */
23958 static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)
23959 {
23960 	const struct bpf_insn *insn = prog->insnsi;
23961 	int i;
23962 
23963 	for (i = 0; i < prog->len; i++, insn++)
23964 		if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_clone_redirect)
23965 			return true;
23966 	return false;
23967 }
23968 
23969 /* Various log level 2 information about the program */
23970 static void log_program(struct bpf_verifier_env *env)
23971 {
23972 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
23973 	struct bpf_insn *insns = env->prog->insnsi;
23974 	u32 insn_cnt = env->prog->len;
23975 	u64 pos, insn_pos;
23976 	u32 i, j;
23977 
23978 	verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
23979 	for (i = 0; i < insn_cnt; ++i) {
23980 		verbose_linfo(env, i, "    ; ");
23981 		if (env->insn_aux_data[i].scc)
23982 			verbose(env, "%3d ", env->insn_aux_data[i].scc);
23983 		else
23984 			verbose(env, "    ");
23985 		if (env->insn_aux_data[i].loop_header >= 0)
23986 			verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
23987 		else
23988 			verbose(env, "    ");
23989 		verbose(env, "%3d ", env->idoms[i]);
23990 		verbose(env, "%3d: ", i);
23991 		for (j = BPF_REG_0; j < BPF_REG_10; ++j)
23992 			if (insn_aux[i].live_regs_before & BIT(j))
23993 				verbose(env, "%d", j);
23994 			else
23995 				verbose(env, ".");
23996 		verbose(env, " ");
23997 		pos = env->log.end_pos;
23998 		bpf_verbose_insn(env, &insns[i]);
23999 		insn_pos = env->log.end_pos;
24000 		if (insn_aux[i].zext_dst)
24001 			verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
24002 		verbose(env, "\n");
24003 		if (bpf_is_ldimm64(&insns[i]))
24004 			i++;
24005 	}
24006 }
24007 
24008 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
24009 	      struct bpf_log_attr *attr_log)
24010 {
24011 	u64 start_time = ktime_get_ns();
24012 	struct bpf_verifier_env *env;
24013 	int i, len, ret = -EINVAL, err;
24014 	bool is_priv;
24015 
24016 	BTF_TYPE_EMIT(enum bpf_features);
24017 
24018 	/* no program is valid */
24019 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24020 		return -EINVAL;
24021 
24022 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24023 	 * allocate/free it every time bpf_check() is called
24024 	 */
24025 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
24026 	if (!env)
24027 		return -ENOMEM;
24028 
24029 	env->bt.env = env;
24030 	env->prog = *prog;
24031 	env->ops = bpf_verifier_ops[env->prog->type];
24032 	env->stack_limit = bpf_prog_stack_limit(env->prog);
24033 	if (bpf_prog_reenters_datapath(env->prog))
24034 		env->stack_limit = MAX_BPF_STACK;
24035 
24036 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24037 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24038 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24039 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24040 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24041 	env->signature = attr->signature;
24042 
24043 	/* user could have requested verbose verifier output
24044 	 * and supplied buffer to store the verification trace
24045 	 */
24046 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
24047 	if (ret)
24048 		goto err_free_env;
24049 	ret = bpf_diag_init(env);
24050 	if (ret)
24051 		goto err_prep;
24052 	if (env->prog->insnsi[env->prog->len - 1].code == (BPF_LD | BPF_IMM | BPF_DW)) {
24053 		verbose(env, "invalid bpf_ld_imm64 insn\n");
24054 		ret = -EINVAL;
24055 		goto err_prep;
24056 	}
24057 
24058 	ret = process_fd_array(env, attr, uattr);
24059 	if (ret)
24060 		goto err_prep;
24061 
24062 	if (env->signature) {
24063 		ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel);
24064 		if (ret)
24065 			goto err_prep;
24066 	}
24067 
24068 	ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token,
24069 				     uattr.is_kernel);
24070 	if (ret)
24071 		goto err_prep;
24072 
24073 	bpf_get_btf_vmlinux();
24074 
24075 	/* Serialize verification of unprivileged programs. */
24076 	if (!is_priv)
24077 		mutex_lock(&bpf_verifier_lock);
24078 
24079 	len = env->insn_aux_data_len = env->prog->len;
24080 	env->insn_aux_data =
24081 		__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),
24082 			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
24083 	ret = -ENOMEM;
24084 	if (!env->insn_aux_data)
24085 		goto skip_full_check;
24086 	for (i = 0; i < len; i++)
24087 		env->insn_aux_data[i].orig_idx = i;
24088 	env->succ = bpf_iarray_realloc(NULL, 2);
24089 	if (!env->succ)
24090 		goto skip_full_check;
24091 
24092 	mark_verifier_state_clean(env);
24093 
24094 	if (IS_ERR(btf_vmlinux)) {
24095 		/* Either gcc or pahole or kernel are broken. */
24096 		verbose(env, "in-kernel BTF is malformed\n");
24097 		ret = PTR_ERR(btf_vmlinux);
24098 		goto skip_full_check;
24099 	}
24100 
24101 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24102 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24103 		env->strict_alignment = true;
24104 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24105 		env->strict_alignment = false;
24106 
24107 	if (is_priv)
24108 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24109 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24110 
24111 	env->explored_states = kvzalloc_objs(struct list_head,
24112 					     state_htab_size(env),
24113 					     GFP_KERNEL_ACCOUNT);
24114 	ret = -ENOMEM;
24115 	if (!env->explored_states)
24116 		goto skip_full_check;
24117 
24118 	for (i = 0; i < state_htab_size(env); i++)
24119 		INIT_LIST_HEAD(&env->explored_states[i]);
24120 	INIT_LIST_HEAD(&env->free_list);
24121 
24122 	/* Prepare BTF and func_info needed to discover all subprograms. */
24123 	ret = bpf_prepare_btf_info(env, attr, uattr);
24124 	if (ret < 0)
24125 		goto skip_full_check;
24126 
24127 	/* Apply CO-RE before validating the program's instruction layout. */
24128 	ret = bpf_check_core_relo(env, attr, uattr);
24129 	if (ret < 0)
24130 		goto skip_full_check;
24131 
24132 	/* Discover all subprograms and collect the properties needed by BTF validation. */
24133 	ret = add_subprogs(env);
24134 	if (ret < 0)
24135 		goto skip_full_check;
24136 
24137 	find_subprog_properties(env);
24138 
24139 	/* Validate BTF before reporting subprogram layout errors. */
24140 	ret = bpf_check_btf_info(env, attr, uattr);
24141 	if (ret < 0)
24142 		goto skip_full_check;
24143 
24144 	ret = check_subprogs(env);
24145 	if (ret < 0)
24146 		goto skip_full_check;
24147 
24148 	/* Validate instructions and resolve the program's referenced resources. */
24149 	ret = check_and_resolve_insns(env);
24150 	if (ret < 0)
24151 		goto skip_full_check;
24152 
24153 	/* Find pointers to functions in the read-only maps of the program. */
24154 	ret = resolve_func_ptrs(env);
24155 	if (ret < 0)
24156 		goto skip_full_check;
24157 
24158 	/* Build kfunc prototypes after resolving program resources. */
24159 	ret = add_kfuncs(env);
24160 	if (ret < 0)
24161 		goto skip_full_check;
24162 
24163 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24164 		ret = bpf_prog_offload_verifier_prep(env->prog);
24165 		if (ret)
24166 			goto skip_full_check;
24167 	}
24168 
24169 	ret = bpf_check_cfg(env);
24170 	if (ret < 0)
24171 		goto skip_full_check;
24172 
24173 	ret = check_unwind_insns(env);
24174 	if (ret < 0)
24175 		goto skip_full_check;
24176 
24177 	ret = bpf_compute_postorder(env);
24178 	if (ret < 0)
24179 		goto skip_full_check;
24180 
24181 	ret = bpf_stack_liveness_init(env);
24182 	if (ret)
24183 		goto skip_full_check;
24184 
24185 	ret = check_attach_btf_id(env);
24186 	if (ret)
24187 		goto skip_full_check;
24188 
24189 	ret = bpf_compute_const_regs(env);
24190 	if (ret < 0)
24191 		goto skip_full_check;
24192 
24193 	ret = bpf_prune_dead_branches(env);
24194 	if (ret < 0)
24195 		goto skip_full_check;
24196 
24197 	ret = sort_subprogs_topo(env);
24198 	if (ret < 0)
24199 		goto skip_full_check;
24200 
24201 	ret = bpf_compute_scc(env);
24202 	if (ret < 0)
24203 		goto skip_full_check;
24204 
24205 	/* must precede the first bpf_ret_reg_pair() user below */
24206 	ret = bpf_compute_subprog_ret_regs(env);
24207 	if (ret < 0)
24208 		goto skip_full_check;
24209 
24210 	prepare_subprog_args(env);
24211 
24212 	ret = bpf_compute_idoms(env);
24213 	if (ret < 0)
24214 		goto skip_full_check;
24215 
24216 	ret = bpf_compute_loops(env);
24217 	if (ret < 0)
24218 		goto skip_full_check;
24219 
24220 	ret = bpf_compute_live_registers(env);
24221 	if (ret < 0)
24222 		goto skip_full_check;
24223 
24224 	if (env->log.level & BPF_LOG_LEVEL2)
24225 		log_program(env);
24226 
24227 	ret = bpf_init_scev(env);
24228 	if (ret < 0)
24229 		goto skip_full_check;
24230 
24231 	ret = bpf_compute_scev(env);
24232 	if (ret < 0)
24233 		goto skip_full_check;
24234 
24235 	bpf_free_subprog_jts(env);
24236 
24237 	ret = mark_fastcall_patterns(env);
24238 	if (ret < 0)
24239 		goto skip_full_check;
24240 
24241 	ret = do_check_main(env);
24242 	ret = ret ?: do_check_subprogs(env);
24243 
24244 	/* reject recursion through the callx edges found by the main pass */
24245 	if (ret == 0 && env->callx_edges)
24246 		ret = sort_subprogs_topo(env);
24247 
24248 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24249 		ret = bpf_prog_offload_finalize(env);
24250 
24251 skip_full_check:
24252 	kvfree(env->explored_states);
24253 
24254 	/* might decrease stack depth, keep it before passes that
24255 	 * allocate additional slots.
24256 	 */
24257 	if (ret == 0)
24258 		ret = bpf_remove_fastcall_spills_fills(env);
24259 
24260 	if (ret == 0)
24261 		ret = check_max_stack_depth(env);
24262 
24263 	/* instruction rewrites happen after this point */
24264 	if (ret == 0)
24265 		ret = bpf_optimize_bpf_loop(env);
24266 
24267 	if (is_priv) {
24268 		if (ret == 0)
24269 			bpf_opt_hard_wire_dead_code_branches(env);
24270 		if (ret == 0)
24271 			ret = bpf_opt_remove_dead_code(env);
24272 		if (ret == 0)
24273 			ret = bpf_opt_remove_nops(env);
24274 	} else {
24275 		if (ret == 0)
24276 			sanitize_dead_code(env);
24277 	}
24278 
24279 	if (ret == 0)
24280 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24281 		ret = bpf_convert_ctx_accesses(env);
24282 
24283 	if (ret == 0)
24284 		ret = bpf_do_misc_fixups(env);
24285 
24286 	/* do 32-bit optimization after insn patching has done so those patched
24287 	 * insns could be handled correctly.
24288 	 */
24289 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24290 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
24291 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24292 								     : false;
24293 	}
24294 
24295 	if (ret == 0)
24296 		ret = bpf_fixup_call_args(env);
24297 
24298 	env->verification_time = ktime_get_ns() - start_time;
24299 	print_verification_stats(env);
24300 	env->prog->aux->verified_insns = env->insn_processed;
24301 
24302 	/* preserve original error even if log finalization is successful */
24303 	err = bpf_log_attr_finalize(attr_log, &env->log);
24304 	if (err)
24305 		ret = err;
24306 
24307 	if (ret)
24308 		goto err_release_maps;
24309 
24310 	if (env->used_map_cnt) {
24311 		/* if program passed verifier, update used_maps in bpf_prog_info */
24312 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
24313 							 env->used_map_cnt,
24314 							 GFP_KERNEL_ACCOUNT);
24315 
24316 		if (!env->prog->aux->used_maps) {
24317 			ret = -ENOMEM;
24318 			goto err_release_maps;
24319 		}
24320 
24321 		memcpy(env->prog->aux->used_maps, env->used_maps,
24322 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24323 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24324 	}
24325 	if (env->used_btf_cnt) {
24326 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24327 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
24328 							 env->used_btf_cnt,
24329 							 GFP_KERNEL_ACCOUNT);
24330 		if (!env->prog->aux->used_btfs) {
24331 			ret = -ENOMEM;
24332 			goto err_release_maps;
24333 		}
24334 
24335 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24336 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24337 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24338 	}
24339 	if (env->used_map_cnt || env->used_btf_cnt) {
24340 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24341 		 * bpf_ld_imm64 instructions
24342 		 */
24343 		convert_pseudo_ld_imm64(env);
24344 	}
24345 
24346 	adjust_btf_func(env);
24347 
24348 	/* extension progs temporarily inherit the attach_type of their targets
24349 	   for verification purposes, so set it back to zero before returning
24350 	 */
24351 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24352 		env->prog->expected_attach_type = 0;
24353 
24354 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
24355 
24356 err_release_maps:
24357 	if (ret)
24358 		release_insn_arrays(env);
24359 	if (!env->prog->aux->used_maps)
24360 		/* if we didn't copy map pointers into bpf_prog_info, release
24361 		 * them now. Otherwise free_used_maps() will release them.
24362 		 */
24363 		release_maps(env);
24364 	if (!env->prog->aux->used_btfs)
24365 		release_btfs(env);
24366 
24367 	*prog = env->prog;
24368 
24369 	module_put(env->attach_btf_mod);
24370 	if (!is_priv)
24371 		mutex_unlock(&bpf_verifier_lock);
24372 	goto err_free_env;
24373 err_prep:
24374 	err = bpf_log_attr_finalize(attr_log, &env->log);
24375 	if (err)
24376 		ret = err;
24377 	release_insn_arrays(env);
24378 	release_maps(env);
24379 	release_btfs(env);
24380 err_free_env:
24381 	bpf_free_subprog_jts(env);
24382 	if (env->insn_aux_data)
24383 		bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
24384 	vfree(env->insn_aux_data);
24385 	kvfree(env->fd_array);
24386 	bpf_free_scev(env);
24387 	bpf_stack_liveness_free(env);
24388 	kvfree(env->cfg.postorder_nums);
24389 	kvfree(env->cfg.insn_postorder);
24390 	kvfree(env->scc_info);
24391 	kvfree(env->succ);
24392 	kvfree(env->gotox_tmp_buf);
24393 	kvfree(env->callx_edges);
24394 	kvfree(env->func_ptrs);
24395 	bpf_diag_free(env);
24396 	kvfree(env->idoms);
24397 	kvfree(env);
24398 	return ret;
24399 }
24400