xref: /linux/kernel/bpf/verifier.c (revision 1cec0b70fdc678d6c0252f3f25e23df0b5a5e49c)
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/bpf_mem_alloc.h>
36 #include <net/xdp.h>
37 #include <linux/trace_events.h>
38 #include <linux/kallsyms.h>
39 
40 #include "diagnostics.h"
41 #include "disasm.h"
42 
43 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
44 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
45 	[_id] = & _name ## _verifier_ops,
46 #define BPF_MAP_TYPE(_id, _ops)
47 #define BPF_LINK_TYPE(_id, _name)
48 #include <linux/bpf_types.h>
49 #undef BPF_PROG_TYPE
50 #undef BPF_MAP_TYPE
51 #undef BPF_LINK_TYPE
52 };
53 
54 enum bpf_features {
55 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
56 	BPF_FEAT_STREAMS	     = 1,
57 	__MAX_BPF_FEAT,
58 };
59 
60 struct bpf_mem_alloc bpf_global_percpu_ma;
61 static bool bpf_global_percpu_ma_set;
62 
63 /* bpf_check() is a static code analyzer that walks eBPF program
64  * instruction by instruction and updates register/stack state.
65  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
66  *
67  * The first pass is depth-first-search to check that the program is a DAG.
68  * It rejects the following programs:
69  * - larger than BPF_MAXINSNS insns
70  * - if loop is present (detected via back-edge)
71  * - unreachable insns exist (shouldn't be a forest. program = one function)
72  * - out of bounds or malformed jumps
73  * The second pass is all possible path descent from the 1st insn.
74  * Since it's analyzing all paths through the program, the length of the
75  * analysis is limited to 64k insn, which may be hit even if total number of
76  * insn is less then 4K, but there are too many branches that change stack/regs.
77  * Number of 'branches to be analyzed' is limited to 1k
78  *
79  * On entry to each instruction, each register has a type, and the instruction
80  * changes the types of the registers depending on instruction semantics.
81  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
82  * copied to R1.
83  *
84  * All registers are 64-bit.
85  * R0 - return register
86  * R1-R5 argument passing registers
87  * R6-R9 callee saved registers
88  * R10 - frame pointer read-only
89  *
90  * At the start of BPF program the register R1 contains a pointer to bpf_context
91  * and has type PTR_TO_CTX.
92  *
93  * Verifier tracks arithmetic operations on pointers in case:
94  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
95  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
96  * 1st insn copies R10 (which has FRAME_PTR) type into R1
97  * and 2nd arithmetic instruction is pattern matched to recognize
98  * that it wants to construct a pointer to some element within stack.
99  * So after 2nd insn, the register R1 has type PTR_TO_STACK
100  * (and -20 constant is saved for further stack bounds checking).
101  * Meaning that this reg is a pointer to stack plus known immediate constant.
102  *
103  * Most of the time the registers have SCALAR_VALUE type, which
104  * means the register has some value, but it's not a valid pointer.
105  * (like pointer plus pointer becomes SCALAR_VALUE type)
106  *
107  * When verifier sees load or store instructions the type of base register
108  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
109  * four pointer types recognized by check_mem_access() function.
110  *
111  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
112  * and the range of [ptr, ptr + map's value_size) is accessible.
113  *
114  * registers used to pass values to function calls are checked against
115  * function argument constraints.
116  *
117  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
118  * It means that the register type passed to this function must be
119  * PTR_TO_STACK and it will be used inside the function as
120  * 'pointer to map element key'
121  *
122  * For example the argument constraints for bpf_map_lookup_elem():
123  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
124  *   .arg1_type = ARG_CONST_MAP_PTR,
125  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
126  *
127  * ret_type says that this function returns 'pointer to map elem value or null'
128  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
129  * 2nd argument should be a pointer to stack, which will be used inside
130  * the helper function as a pointer to map element key.
131  *
132  * On the kernel side the helper function looks like:
133  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
134  * {
135  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
136  *    void *key = (void *) (unsigned long) r2;
137  *    void *value;
138  *
139  *    here kernel can access 'key' and 'map' pointers safely, knowing that
140  *    [key, key + map->key_size) bytes are valid and were initialized on
141  *    the stack of eBPF program.
142  * }
143  *
144  * Corresponding eBPF program may look like:
145  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
146  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
147  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
148  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
149  * here verifier looks at prototype of map_lookup_elem() and sees:
150  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
151  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
152  *
153  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
154  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
155  * and were initialized prior to this call.
156  * If it's ok, then verifier allows this BPF_CALL insn and looks at
157  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
158  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
159  * returns either pointer to map value or NULL.
160  *
161  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
162  * insn, the register holding that pointer in the true branch changes state to
163  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
164  * branch. See check_cond_jmp_op().
165  *
166  * After the call R0 is set to return type of the function and registers R1-R5
167  * are set to NOT_INIT to indicate that they are no longer readable.
168  *
169  * The following reference types represent a potential reference to a kernel
170  * resource which, after first being allocated, must be checked and freed by
171  * the BPF program:
172  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
173  *
174  * When the verifier sees a helper call return a reference type, it allocates a
175  * pointer id for the reference and stores it in the current function state.
176  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
177  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
178  * passes through a NULL-check conditional. For the branch wherein the state is
179  * changed to CONST_IMM, the verifier releases the reference.
180  *
181  * For each helper function that allocates a reference, such as
182  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
183  * bpf_sk_release(). When a reference type passes into the release function,
184  * the verifier also releases the reference. If any unchecked or unreleased
185  * reference remains at the end of the program, the verifier rejects it.
186  */
187 
188 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
189 struct bpf_verifier_stack_elem {
190 	/* verifier state is 'st'
191 	 * before processing instruction 'insn_idx'
192 	 * and after processing instruction 'prev_insn_idx'
193 	 */
194 	struct bpf_verifier_state st;
195 	int insn_idx;
196 	int prev_insn_idx;
197 	struct bpf_verifier_stack_elem *next;
198 	/* length of verifier log at the time this state was pushed on stack */
199 	u32 log_pos;
200 	u64 diag_log_pos;
201 };
202 
203 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
204 #define BPF_COMPLEXITY_LIMIT_STATES	64
205 
206 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
207 
208 #define BPF_PRIV_STACK_MIN_SIZE		64
209 
210 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
211 static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
212 static int release_reference_nomark(struct bpf_verifier_env *env, int id);
213 static int release_reference(struct bpf_verifier_env *env, int id);
214 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
215 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env);
216 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
217 static bool is_tracing_prog_type(enum bpf_prog_type type);
218 static int ref_set_non_owning(struct bpf_verifier_env *env,
219 			      struct bpf_reg_state *reg);
220 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
221 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
222 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
223 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
224 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
225 
226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
227 			      struct bpf_map *map,
228 			      bool unpriv, bool poison)
229 {
230 	unpriv |= bpf_map_ptr_unpriv(aux);
231 	aux->map_ptr_state.unpriv = unpriv;
232 	aux->map_ptr_state.poison = poison;
233 	aux->map_ptr_state.map_ptr = map;
234 }
235 
236 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
237 {
238 	bool poisoned = bpf_map_key_poisoned(aux);
239 
240 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
241 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
242 }
243 
244 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
245 {
246 	ref_obj->id = reg->id;
247 	ref_obj->parent_id = reg->parent_id;
248 	ref_obj->cnt++;
249 }
250 
251 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
252 {
253 	if (ref_obj->cnt > 1) {
254 		verifier_bug(env, "function expects only one referenced object but got %d\n",
255 			     ref_obj->cnt);
256 		return -EFAULT;
257 	}
258 
259 	return 0;
260 }
261 
262 struct bpf_kfunc_meta {
263 	struct btf *btf;
264 	const struct btf_type *proto;
265 	const char *name;
266 	const u32 *flags;
267 	s32 id;
268 };
269 
270 struct btf *btf_vmlinux;
271 
272 typedef struct argno {
273 	int argno;
274 } argno_t;
275 
276 static argno_t argno_from_reg(u32 regno)
277 {
278 	return (argno_t){ .argno = regno };
279 }
280 
281 static argno_t argno_from_arg(u32 arg)
282 {
283 	return (argno_t){ .argno = -arg };
284 }
285 
286 static int reg_from_argno(argno_t a)
287 {
288 	if (a.argno >= 0)
289 		return a.argno;
290 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
291 		return -a.argno;
292 	return -1;
293 }
294 
295 static int arg_from_argno(argno_t a)
296 {
297 	if (a.argno < 0)
298 		return -a.argno;
299 	return -1;
300 }
301 
302 static int arg_idx_from_argno(argno_t a)
303 {
304 	return arg_from_argno(a) - 1;
305 }
306 
307 /* Normalize helper register numbers and kfunc argument numbers to ABI slots. */
308 static u32 arg_slot_from_argno(argno_t a)
309 {
310 	return abs(a.argno) - 1;
311 }
312 
313 static const char *btf_type_name(const struct btf *btf, u32 id)
314 {
315 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
316 }
317 
318 static DEFINE_MUTEX(bpf_verifier_lock);
319 static DEFINE_MUTEX(btf_vmlinux_lock);
320 static DEFINE_MUTEX(bpf_percpu_ma_lock);
321 
322 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
323 {
324 	struct bpf_verifier_env *env = private_data;
325 	va_list args;
326 
327 	if (!bpf_verifier_log_needed(&env->log))
328 		return;
329 
330 	va_start(args, fmt);
331 	bpf_verifier_vlog(&env->log, fmt, args);
332 	va_end(args);
333 }
334 
335 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
336 				   struct bpf_reg_state *reg,
337 				   struct bpf_retval_range range, const char *ctx,
338 				   const char *reg_name)
339 {
340 	bool unknown = true;
341 
342 	verbose(env, "%s the register %s has", ctx, reg_name);
343 	if (reg_smin(reg) > S64_MIN) {
344 		verbose(env, " smin=%lld", reg_smin(reg));
345 		unknown = false;
346 	}
347 	if (reg_smax(reg) < S64_MAX) {
348 		verbose(env, " smax=%lld", reg_smax(reg));
349 		unknown = false;
350 	}
351 	if (unknown)
352 		verbose(env, " unknown scalar value");
353 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
354 }
355 
356 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
357 {
358 	enum bpf_reg_type type;
359 
360 	type = reg->type;
361 	if (type_may_be_null(type))
362 		return false;
363 
364 	/*
365 	 * The types below guarantee a non-NULL base, an unbounded offset can
366 	 * still wrap base + offset to zero.
367 	 */
368 	if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF)
369 		return false;
370 
371 	type = base_type(type);
372 	return type == PTR_TO_SOCKET ||
373 		type == PTR_TO_TCP_SOCK ||
374 		type == PTR_TO_XDP_SOCK ||
375 		type == PTR_TO_BUF ||
376 		type == PTR_TO_MAP_VALUE ||
377 		type == PTR_TO_MAP_KEY ||
378 		type == PTR_TO_SOCK_COMMON ||
379 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
380 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
381 		type == CONST_PTR_TO_MAP;
382 }
383 
384 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
385 {
386 	struct btf_record *rec = NULL;
387 	struct btf_struct_meta *meta;
388 
389 	if (reg->type == PTR_TO_MAP_VALUE) {
390 		rec = reg->map_ptr->record;
391 	} else if (type_is_ptr_alloc_obj(reg->type)) {
392 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
393 		if (meta)
394 			rec = meta->record;
395 	}
396 	return rec;
397 }
398 
399 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
400 {
401 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
402 
403 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
404 }
405 
406 static const struct btf_type *subprog_ret_type(struct bpf_verifier_env *env, int subprog)
407 {
408 	const struct btf_type *func, *func_proto;
409 	const struct btf *btf = env->prog->aux->btf;
410 	u32 btf_id;
411 
412 	if (!btf || !env->prog->aux->func_info)
413 		return NULL;
414 
415 	btf_id = env->prog->aux->func_info[subprog].type_id;
416 
417 	/* Both already validated by prepare_btf_func() at prog load. */
418 	func = btf_type_by_id(btf, btf_id);
419 	func_proto = btf_type_by_id(btf, func->type);
420 
421 	return btf_type_skip_modifiers(btf, func_proto->type, NULL);
422 }
423 
424 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
425 {
426 	const struct btf_type *type = subprog_ret_type(env, subprog);
427 
428 	return type && btf_type_is_void(type);
429 }
430 
431 static u32 ret_regs_cnt(u32 size)
432 {
433 	return size > 8 && size <= 16 ? 2 : 1;
434 }
435 
436 /* Registers holding a function return value, in order. See ret_regs_cnt(). */
437 static const int ret_regs[] = { BPF_REG_0, BPF_REG_2 };
438 
439 static int bpf_compute_subprog_ret_regs(struct bpf_verifier_env *env)
440 {
441 	const struct btf *btf = env->prog->aux->btf;
442 	const struct btf_type *type;
443 	int subprog;
444 	u32 size;
445 
446 	if (!env->prog->jit_requested || bpf_prog_is_offloaded(env->prog->aux))
447 		return 0;
448 
449 	/*
450 	 * Skip the main program: its return value is the program's exit code,
451 	 * read out of R0, so it never uses the register pair. An extension does
452 	 * have a real prototype for subprog 0, but btf_check_func_type_match()
453 	 * refuses to replace a function returning more than 8 bytes.
454 	 */
455 	for (subprog = 1; subprog < env->subprog_cnt; subprog++) {
456 		type = subprog_ret_type(env, subprog);
457 		if (!type || btf_type_is_void(type))
458 			continue;
459 		if (verifier_bug_if(IS_ERR(btf_resolve_size(btf, type, &size)), env,
460 				    "cannot size return type of subprog %d", subprog))
461 			return -EFAULT;
462 		if (ret_regs_cnt(size) > 1) {
463 			subprog_info(env, subprog)->ret_reg_pair = true;
464 			env->prog->jit_required = 1;
465 		}
466 	}
467 
468 	return 0;
469 }
470 
471 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)
472 {
473 	struct bpf_func_info *info;
474 
475 	if (!env->prog->aux->func_info)
476 		return "";
477 
478 	info = &env->prog->aux->func_info[subprog];
479 	return btf_type_name(env->prog->aux->btf, info->type_id);
480 }
481 
482 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
483 {
484 	struct bpf_subprog_info *info = subprog_info(env, subprog);
485 
486 	info->is_cb = true;
487 	info->is_async_cb = true;
488 	info->is_exception_cb = true;
489 }
490 
491 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
492 {
493 	return subprog_info(env, subprog)->is_exception_cb;
494 }
495 
496 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
497 {
498 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
499 }
500 
501 static bool type_is_rdonly_mem(u32 type)
502 {
503 	return type & MEM_RDONLY;
504 }
505 
506 static bool is_acquire_function(enum bpf_func_id func_id,
507 				const struct bpf_map *map)
508 {
509 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
510 
511 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
512 	    func_id == BPF_FUNC_sk_lookup_udp ||
513 	    func_id == BPF_FUNC_skc_lookup_tcp ||
514 	    func_id == BPF_FUNC_ringbuf_reserve ||
515 	    func_id == BPF_FUNC_kptr_xchg)
516 		return true;
517 
518 	if (func_id == BPF_FUNC_map_lookup_elem &&
519 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
520 	     map_type == BPF_MAP_TYPE_SOCKHASH))
521 		return true;
522 
523 	return false;
524 }
525 
526 static bool is_ptr_cast_function(enum bpf_func_id func_id)
527 {
528 	return func_id == BPF_FUNC_tcp_sock ||
529 		func_id == BPF_FUNC_sk_fullsock ||
530 		func_id == BPF_FUNC_skc_to_tcp_sock ||
531 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
532 		func_id == BPF_FUNC_skc_to_udp6_sock ||
533 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
534 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
536 }
537 
538 static bool is_sync_callback_calling_kfunc(u32 btf_id);
539 static bool is_async_callback_calling_kfunc(u32 btf_id);
540 static bool is_call_rcu_kfunc(u32 btf_id);
541 static bool is_callback_calling_kfunc(u32 btf_id);
542 
543 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
544 static bool is_task_work_add_kfunc(u32 func_id);
545 
546 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
547 {
548 	return func_id == BPF_FUNC_for_each_map_elem ||
549 	       func_id == BPF_FUNC_find_vma ||
550 	       func_id == BPF_FUNC_loop ||
551 	       func_id == BPF_FUNC_user_ringbuf_drain;
552 }
553 
554 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
555 {
556 	return func_id == BPF_FUNC_timer_set_callback;
557 }
558 
559 static bool is_callback_calling_function(enum bpf_func_id func_id)
560 {
561 	return is_sync_callback_calling_function(func_id) ||
562 	       is_async_callback_calling_function(func_id);
563 }
564 
565 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
566 {
567 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
568 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
569 }
570 
571 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
572 {
573 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
574 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
575 }
576 
577 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
578 {
579 	/* bpf_timer callbacks are never sleepable. */
580 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
581 		return false;
582 
583 	/* bpf_call_rcu and bpf_call_rcu_tasks_trace callbacks are never sleepable. */
584 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && is_call_rcu_kfunc(insn->imm))
585 		return false;
586 
587 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
588 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
589 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
590 		return true;
591 
592 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
593 	return false;
594 }
595 
596 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
597 {
598 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
599 }
600 
601 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
602 {
603 	int allocated_slots = bpf_stack_nr_slots(state);
604 
605 	/*
606 	 * We need to check that slots between [spi - nr_slots + 1, spi] are
607 	 * within [0, allocated_stack).
608 	 *
609 	 * Please note that the spi grows downwards. For example, a dynptr
610 	 * takes the size of two stack slots; the first slot will be at
611 	 * spi and the second slot will be at spi - 1.
612 	 */
613 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
614 }
615 
616 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
617 			          const char *obj_kind, int nr_slots)
618 {
619 	int off, spi;
620 
621 	if (!tnum_is_const(reg->var_off)) {
622 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
623 		return -EINVAL;
624 	}
625 
626 	off = reg->var_off.value;
627 	if (off >= 0 || off % BPF_REG_SIZE) {
628 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
629 		return -EINVAL;
630 	}
631 
632 	spi = bpf_get_spi(off);
633 	if (spi + 1 < nr_slots) {
634 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
635 		return -EINVAL;
636 	}
637 
638 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
639 		return -ERANGE;
640 	return spi;
641 }
642 
643 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
644 {
645 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
646 }
647 
648 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
649 {
650 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
651 }
652 
653 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
654 {
655 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
656 }
657 
658 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
659 {
660 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
661 	case DYNPTR_TYPE_LOCAL:
662 		return BPF_DYNPTR_TYPE_LOCAL;
663 	case DYNPTR_TYPE_RINGBUF:
664 		return BPF_DYNPTR_TYPE_RINGBUF;
665 	case DYNPTR_TYPE_SKB:
666 		return BPF_DYNPTR_TYPE_SKB;
667 	case DYNPTR_TYPE_XDP:
668 		return BPF_DYNPTR_TYPE_XDP;
669 	case DYNPTR_TYPE_SKB_META:
670 		return BPF_DYNPTR_TYPE_SKB_META;
671 	case DYNPTR_TYPE_FILE:
672 		return BPF_DYNPTR_TYPE_FILE;
673 	default:
674 		return BPF_DYNPTR_TYPE_INVALID;
675 	}
676 }
677 
678 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
679 {
680 	switch (type) {
681 	case BPF_DYNPTR_TYPE_LOCAL:
682 		return DYNPTR_TYPE_LOCAL;
683 	case BPF_DYNPTR_TYPE_RINGBUF:
684 		return DYNPTR_TYPE_RINGBUF;
685 	case BPF_DYNPTR_TYPE_SKB:
686 		return DYNPTR_TYPE_SKB;
687 	case BPF_DYNPTR_TYPE_XDP:
688 		return DYNPTR_TYPE_XDP;
689 	case BPF_DYNPTR_TYPE_SKB_META:
690 		return DYNPTR_TYPE_SKB_META;
691 	case BPF_DYNPTR_TYPE_FILE:
692 		return DYNPTR_TYPE_FILE;
693 	default:
694 		return 0;
695 	}
696 }
697 
698 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
699 {
700 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
701 }
702 
703 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
704 			      enum bpf_dynptr_type type,
705 			      bool first_slot, int id, int parent_id);
706 
707 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
708 				   struct bpf_reg_state *sreg1,
709 				   struct bpf_reg_state *sreg2,
710 				   enum bpf_dynptr_type type, int parent_id)
711 {
712 	int id = ++env->id_gen;
713 
714 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
715 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
716 }
717 
718 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
719 			       struct bpf_reg_state *reg,
720 			       enum bpf_dynptr_type type)
721 {
722 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
723 }
724 
725 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
726 				        struct bpf_func_state *state, int spi);
727 
728 static int destroy_dynptrs_in_stack_slots(struct bpf_verifier_env *env,
729 					  struct bpf_func_state *state,
730 					  int first_spi, int last_spi)
731 {
732 	int spi, err;
733 
734 	for (spi = first_spi; spi <= last_spi; spi++) {
735 		err = destroy_if_dynptr_stack_slot(env, state, spi);
736 		if (err)
737 			return err;
738 	}
739 
740 	return 0;
741 }
742 
743 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
744 				   enum bpf_arg_type arg_type, int insn_idx,
745 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
746 {
747 	struct bpf_func_state *state = bpf_func(env, reg);
748 	int spi, i, err, parent_id = 0;
749 	enum bpf_dynptr_type type;
750 
751 	spi = dynptr_get_spi(env, reg);
752 	if (spi < 0)
753 		return spi;
754 
755 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
756 	 * hence we need to destroy dynptrs in both slots,
757 	 * to ensure that for the following example:
758 	 *	[d1][d1][d2][d2]
759 	 * spi    3   2   1   0
760 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
761 	 * case they do belong to same dynptr, second call won't see slot_type
762 	 * as STACK_DYNPTR and will simply skip destruction.
763 	 */
764 	err = destroy_dynptrs_in_stack_slots(env, state, spi - 1, spi);
765 	if (err)
766 		return err;
767 
768 	for (i = 0; i < BPF_REG_SIZE; i++) {
769 		bpf_stack_slot(state, spi)->slot_type[i] = STACK_DYNPTR;
770 		bpf_stack_slot(state, spi - 1)->slot_type[i] = STACK_DYNPTR;
771 	}
772 
773 	type = arg_to_dynptr_type(arg_type);
774 	if (type == BPF_DYNPTR_TYPE_INVALID)
775 		return -EINVAL;
776 
777 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
778 		err = validate_ref_obj(env, ref_obj);
779 		if (err)
780 			return err;
781 
782 		/* Track parent's id if the parent is a referenced object */
783 		parent_id = ref_obj->id;
784 
785 		if (dynptr_type_referenced(type)) {
786 			int id;
787 
788 			/*
789 			 * Create an intermediate reference that tracks the referenced
790 			 * object for the referenced dynptr. Freeing a referenced dynptr
791 			 * through helpers/kfuncs will invalidate all clones.
792 			 */
793 			id = acquire_reference(env, insn_idx, parent_id);
794 			if (id < 0)
795 				return id;
796 
797 			parent_id = id;
798 		}
799 	} else { /* bpf_dynptr_clone() */
800 		parent_id = dynptr->parent_id;
801 	}
802 
803 	mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr,
804 			       &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id);
805 
806 	return 0;
807 }
808 
809 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
810 {
811 	int i;
812 
813 	for (i = 0; i < BPF_REG_SIZE; i++) {
814 		stack[0].slot_type[i] = STACK_INVALID;
815 		stack[1].slot_type[i] = STACK_INVALID;
816 	}
817 
818 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
819 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
820 }
821 
822 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
823 {
824 	struct bpf_func_state *state = bpf_func(env, reg);
825 	int spi;
826 
827 	spi = dynptr_get_spi(env, reg);
828 	if (spi < 0)
829 		return spi;
830 
831 	/*
832 	 * For referenced dynptr, release the parent ref which cascades to
833 	 * all clones and derived slices. For non-referenced dynptr, only
834 	 * the dynptr and slices derived from it will be invalidated.
835 	 */
836 	reg = &bpf_stack_slot(state, spi)->spilled_ptr;
837 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
838 				      ? reg->parent_id
839 				      : reg->id);
840 }
841 
842 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
843 			       struct bpf_reg_state *reg);
844 
845 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
846 {
847 	if (!env->allow_ptr_leaks)
848 		bpf_mark_reg_not_init(env, reg);
849 	else
850 		__mark_reg_unknown(env, reg);
851 }
852 
853 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
854 {
855 	struct bpf_stack_state *stack;
856 	struct bpf_func_state *state;
857 	struct bpf_reg_state *reg;
858 	int ref_cnt = 0;
859 
860 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
861 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
862 			continue;
863 		if (!stack->spilled_ptr.dynptr.first_slot)
864 			continue;
865 		if (stack->spilled_ptr.parent_id == v_parent_id)
866 			ref_cnt++;
867 	}));
868 
869 	return ref_cnt;
870 }
871 
872 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
873 				        struct bpf_func_state *state, int spi)
874 {
875 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
876 	int err = 0;
877 
878 	/* We always ensure that STACK_DYNPTR is never set partially,
879 	 * hence just checking for slot_type[0] is enough. This is
880 	 * different for STACK_SPILL, where it may be only set for
881 	 * 1 byte, so code has to use is_spilled_reg.
882 	 */
883 	if (slot->slot_type[0] != STACK_DYNPTR)
884 		return 0;
885 
886 	/* Reposition spi to first slot */
887 	if (!slot->spilled_ptr.dynptr.first_slot) {
888 		spi = spi + 1;
889 		slot = bpf_stack_slot(state, spi);
890 	}
891 
892 	/*
893 	 * A referenced dynptr can be overwritten only if there is at
894 	 * least one other dynptr sharing the same virtual ref parent,
895 	 * ensuring the reference can still be properly released.
896 	 */
897 	if (dynptr_type_referenced(slot->spilled_ptr.dynptr.type) &&
898 	    dynptr_ref_cnt(env, slot->spilled_ptr.parent_id) <= 1) {
899 		verbose(env, "cannot overwrite referenced dynptr\n");
900 		bpf_diag_res(
901 			env, env->insn_idx, "referenced dynptr overwrite",
902 			"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.",
903 			"Release or clone the dynptr so another live dynptr still tracks the referenced resource before overwriting this stack slot.");
904 		return -EINVAL;
905 	}
906 
907 	/* Invalidate the dynptr and any derived slices */
908 	err = release_reference(env, slot->spilled_ptr.id);
909 	if (!err) {
910 		mark_stack_slot_scratched(env, spi);
911 		mark_stack_slot_scratched(env, spi - 1);
912 	}
913 
914 	return err;
915 }
916 
917 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
918 {
919 	int spi;
920 
921 	if (reg->type == CONST_PTR_TO_DYNPTR)
922 		return false;
923 
924 	spi = dynptr_get_spi(env, reg);
925 
926 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
927 	 * error because this just means the stack state hasn't been updated yet.
928 	 * We will do check_mem_access to check and update stack bounds later.
929 	 */
930 	if (spi < 0 && spi != -ERANGE)
931 		return false;
932 
933 	/* We don't need to check if the stack slots are marked by previous
934 	 * dynptr initializations because we allow overwriting existing unreferenced
935 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
936 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
937 	 * touching are completely destructed before we reinitialize them for a new
938 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
939 	 * instead of delaying it until the end where the user will get "Unreleased
940 	 * reference" error.
941 	 */
942 	return true;
943 }
944 
945 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
946 {
947 	struct bpf_func_state *state = bpf_func(env, reg);
948 	struct bpf_stack_state *slot;
949 	int i, spi;
950 
951 	/* This already represents first slot of initialized bpf_dynptr.
952 	 *
953 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
954 	 * check_func_arg_reg_off's logic, so we don't need to check its
955 	 * offset and alignment.
956 	 */
957 	if (reg->type == CONST_PTR_TO_DYNPTR)
958 		return true;
959 
960 	spi = dynptr_get_spi(env, reg);
961 	if (spi < 0)
962 		return false;
963 	slot = bpf_stack_slot(state, spi);
964 	if (!slot->spilled_ptr.dynptr.first_slot)
965 		return false;
966 
967 	for (i = 0; i < BPF_REG_SIZE; i++) {
968 		if (slot->slot_type[i] != STACK_DYNPTR ||
969 		    bpf_stack_slot(state, spi - 1)->slot_type[i] != STACK_DYNPTR)
970 			return false;
971 	}
972 
973 	return true;
974 }
975 
976 static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
977 {
978 	struct bpf_func_state *state;
979 	int spi;
980 
981 	if (reg->type == CONST_PTR_TO_DYNPTR)
982 		return reg->dynptr.type;
983 
984 	spi = dynptr_get_spi(env, reg);
985 	if (spi < 0)
986 		return BPF_DYNPTR_TYPE_INVALID;
987 	state = bpf_func(env, reg);
988 	return bpf_stack_slot(state, spi)->spilled_ptr.dynptr.type;
989 }
990 
991 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
992 				    enum bpf_arg_type arg_type)
993 {
994 	/*
995 	 * ARG_PTR_TO_DYNPTR without a type flag takes any type of dynptr.
996 	 * Test the flags rather than the whole arg_type, which may carry
997 	 * unrelated ones such as PTR_MAYBE_NULL.
998 	 */
999 	if (!(arg_type & DYNPTR_TYPE_FLAG_MASK))
1000 		return true;
1001 
1002 	return dynptr_reg_type(env, reg) == arg_to_dynptr_type(arg_type);
1003 }
1004 
1005 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1006 
1007 static bool in_rcu_cs(struct bpf_verifier_env *env);
1008 
1009 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta);
1010 
1011 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1012 				 struct bpf_call_arg_meta *meta,
1013 				 struct bpf_reg_state *reg, int insn_idx,
1014 				 struct btf *btf, u32 btf_id, int nr_slots)
1015 {
1016 	struct bpf_func_state *state = bpf_func(env, reg);
1017 	int spi, i, j, id;
1018 
1019 	spi = iter_get_spi(env, reg, nr_slots);
1020 	if (spi < 0)
1021 		return spi;
1022 
1023 	id = acquire_reference(env, insn_idx, 0);
1024 	if (id < 0)
1025 		return id;
1026 
1027 	for (i = 0; i < nr_slots; i++) {
1028 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1029 		struct bpf_reg_state *st = &slot->spilled_ptr;
1030 
1031 		__mark_reg_known_zero(st);
1032 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1033 		if (is_kfunc_rcu_protected(meta)) {
1034 			if (in_rcu_cs(env))
1035 				st->type |= MEM_RCU;
1036 			else
1037 				st->type |= PTR_UNTRUSTED;
1038 		}
1039 		st->id = i == 0 ? id : 0;
1040 		st->iter.btf = btf;
1041 		st->iter.btf_id = btf_id;
1042 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1043 		st->iter.depth = 0;
1044 
1045 		for (j = 0; j < BPF_REG_SIZE; j++)
1046 			slot->slot_type[j] = STACK_ITER;
1047 
1048 		mark_stack_slot_scratched(env, spi - i);
1049 	}
1050 
1051 	return 0;
1052 }
1053 
1054 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1055 				   struct bpf_reg_state *reg, int nr_slots)
1056 {
1057 	struct bpf_func_state *state = bpf_func(env, reg);
1058 	int spi, i, j;
1059 
1060 	spi = iter_get_spi(env, reg, nr_slots);
1061 	if (spi < 0)
1062 		return spi;
1063 
1064 	for (i = 0; i < nr_slots; i++) {
1065 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1066 		struct bpf_reg_state *st = &slot->spilled_ptr;
1067 
1068 		if (i == 0)
1069 			WARN_ON_ONCE(release_reference(env, st->id));
1070 
1071 		bpf_mark_reg_not_init(env, st);
1072 
1073 		for (j = 0; j < BPF_REG_SIZE; j++)
1074 			slot->slot_type[j] = STACK_INVALID;
1075 
1076 		mark_stack_slot_scratched(env, spi - i);
1077 	}
1078 
1079 	return 0;
1080 }
1081 
1082 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1083 				     struct bpf_reg_state *reg, int nr_slots)
1084 {
1085 	struct bpf_func_state *state = bpf_func(env, reg);
1086 	int spi, i, j;
1087 
1088 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1089 	 * will do check_mem_access to check and update stack bounds later, so
1090 	 * return true for that case.
1091 	 */
1092 	spi = iter_get_spi(env, reg, nr_slots);
1093 	if (spi == -ERANGE)
1094 		return true;
1095 	if (spi < 0)
1096 		return false;
1097 
1098 	for (i = 0; i < nr_slots; i++) {
1099 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1100 
1101 		for (j = 0; j < BPF_REG_SIZE; j++)
1102 			if (slot->slot_type[j] == STACK_ITER)
1103 				return false;
1104 	}
1105 
1106 	return true;
1107 }
1108 
1109 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1110 				   struct btf *btf, u32 btf_id, int nr_slots)
1111 {
1112 	struct bpf_func_state *state = bpf_func(env, reg);
1113 	int spi, i, j;
1114 
1115 	spi = iter_get_spi(env, reg, nr_slots);
1116 	if (spi < 0)
1117 		return -EINVAL;
1118 
1119 	for (i = 0; i < nr_slots; i++) {
1120 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1121 		struct bpf_reg_state *st = &slot->spilled_ptr;
1122 
1123 		if (st->type & PTR_UNTRUSTED)
1124 			return -EPROTO;
1125 		/* only main (first) slot has id set */
1126 		if (i == 0 && !st->id)
1127 			return -EINVAL;
1128 		if (i != 0 && st->id)
1129 			return -EINVAL;
1130 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1131 			return -EINVAL;
1132 
1133 		for (j = 0; j < BPF_REG_SIZE; j++)
1134 			if (slot->slot_type[j] != STACK_ITER)
1135 				return -EINVAL;
1136 	}
1137 
1138 	return 0;
1139 }
1140 
1141 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1142 static int release_irq_state(struct bpf_verifier_env *env, int id);
1143 
1144 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1145 				     struct bpf_call_arg_meta *meta,
1146 				     struct bpf_reg_state *reg, int insn_idx,
1147 				     int kfunc_class)
1148 {
1149 	struct bpf_func_state *state = bpf_func(env, reg);
1150 	struct bpf_stack_state *slot;
1151 	struct bpf_reg_state *st;
1152 	int spi, i, id;
1153 
1154 	spi = irq_flag_get_spi(env, reg);
1155 	if (spi < 0)
1156 		return spi;
1157 
1158 	id = acquire_irq_state(env, insn_idx);
1159 	if (id < 0)
1160 		return id;
1161 
1162 	slot = bpf_stack_slot(state, spi);
1163 	st = &slot->spilled_ptr;
1164 
1165 	__mark_reg_known_zero(st);
1166 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1167 	st->id = id;
1168 	st->irq.kfunc_class = kfunc_class;
1169 
1170 	for (i = 0; i < BPF_REG_SIZE; i++)
1171 		slot->slot_type[i] = STACK_IRQ_FLAG;
1172 
1173 	mark_stack_slot_scratched(env, spi);
1174 	return 0;
1175 }
1176 
1177 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1178 				      int kfunc_class)
1179 {
1180 	struct bpf_func_state *state = bpf_func(env, reg);
1181 	struct bpf_stack_state *slot;
1182 	struct bpf_reg_state *st;
1183 	int spi, i, err;
1184 
1185 	spi = irq_flag_get_spi(env, reg);
1186 	if (spi < 0)
1187 		return spi;
1188 
1189 	slot = bpf_stack_slot(state, spi);
1190 	st = &slot->spilled_ptr;
1191 
1192 	if (st->irq.kfunc_class != kfunc_class) {
1193 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1194 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1195 		const char *reason;
1196 
1197 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1198 			flag_kfunc, used_kfunc);
1199 		reason = bpf_diag_fmt(env,
1200 				      "This IRQ flag was saved by %s IRQ kfuncs, but the restore call "
1201 			"belongs to the %s IRQ kfunc family. Save and restore operations "
1202 			"must use the same family.",
1203 			flag_kfunc, used_kfunc);
1204 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore mismatch", reason,
1205 			     "Restore the flag with the matching IRQ restore kfunc for the save "
1206 			     "operation that created it.",
1207 			     bpf_diag_irq_depth(env->cur_state));
1208 		return -EINVAL;
1209 	}
1210 
1211 	err = release_irq_state(env, st->id);
1212 	WARN_ON_ONCE(err && err != -EACCES);
1213 	if (err) {
1214 		int insn_idx = 0;
1215 
1216 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1217 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1218 				insn_idx = env->cur_state->refs[i].insn_idx;
1219 				break;
1220 			}
1221 		}
1222 
1223 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1224 			env->cur_state->active_irq_id, insn_idx);
1225 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore out of order",
1226 			     "IRQ-disabled regions must be restored in last-in, first-out order, "
1227 			     "but this restore does not match the currently active IRQ flag.",
1228 			     "Restore nested IRQ flags in the reverse order they were saved.",
1229 			     bpf_diag_irq_depth(env->cur_state));
1230 		return err;
1231 	}
1232 
1233 	bpf_mark_reg_not_init(env, st);
1234 
1235 	for (i = 0; i < BPF_REG_SIZE; i++)
1236 		slot->slot_type[i] = STACK_INVALID;
1237 
1238 	mark_stack_slot_scratched(env, spi);
1239 	return 0;
1240 }
1241 
1242 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1243 {
1244 	struct bpf_func_state *state = bpf_func(env, reg);
1245 	struct bpf_stack_state *slot;
1246 	int spi, i;
1247 
1248 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249 	 * will do check_mem_access to check and update stack bounds later, so
1250 	 * return true for that case.
1251 	 */
1252 	spi = irq_flag_get_spi(env, reg);
1253 	if (spi == -ERANGE)
1254 		return true;
1255 	if (spi < 0)
1256 		return false;
1257 
1258 	slot = bpf_stack_slot(state, spi);
1259 
1260 	for (i = 0; i < BPF_REG_SIZE; i++)
1261 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1262 			return false;
1263 	return true;
1264 }
1265 
1266 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1267 {
1268 	struct bpf_func_state *state = bpf_func(env, reg);
1269 	struct bpf_stack_state *slot;
1270 	struct bpf_reg_state *st;
1271 	int spi, i;
1272 
1273 	spi = irq_flag_get_spi(env, reg);
1274 	if (spi < 0)
1275 		return -EINVAL;
1276 
1277 	slot = bpf_stack_slot(state, spi);
1278 	st = &slot->spilled_ptr;
1279 
1280 	if (!st->id)
1281 		return -EINVAL;
1282 
1283 	for (i = 0; i < BPF_REG_SIZE; i++)
1284 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1285 			return -EINVAL;
1286 	return 0;
1287 }
1288 
1289 /* Check if given stack slot is "special":
1290  *   - spilled register state (STACK_SPILL);
1291  *   - dynptr state (STACK_DYNPTR);
1292  *   - iter state (STACK_ITER).
1293  *   - irq flag state (STACK_IRQ_FLAG)
1294  */
1295 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1296 {
1297 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1298 
1299 	switch (type) {
1300 	case STACK_SPILL:
1301 	case STACK_DYNPTR:
1302 	case STACK_ITER:
1303 	case STACK_IRQ_FLAG:
1304 		return true;
1305 	case STACK_INVALID:
1306 	case STACK_POISON:
1307 	case STACK_MISC:
1308 	case STACK_ZERO:
1309 		return false;
1310 	default:
1311 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1312 		return true;
1313 	}
1314 }
1315 
1316 /* The reg state of a pointer or a bounded scalar was saved when
1317  * it was spilled to the stack.
1318  */
1319 
1320 /*
1321  * Mark stack slot as STACK_MISC, unless it is already:
1322  * - STACK_INVALID, in which case they are equivalent.
1323  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1324  * - STACK_POISON, which truly forbids access to the slot.
1325  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1326  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1327  * unnecessary as both are considered equivalent when loading data and pruning,
1328  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1329  * slots.
1330  */
1331 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1332 {
1333 	if (*stype == STACK_ZERO)
1334 		return;
1335 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1336 		return;
1337 	*stype = STACK_MISC;
1338 }
1339 
1340 static void scrub_spilled_slot(u8 *stype)
1341 {
1342 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1343 		*stype = STACK_MISC;
1344 }
1345 
1346 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1347  * small to hold src. This is different from krealloc since we don't want to preserve
1348  * the contents of dst.
1349  *
1350  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1351  * not be allocated.
1352  */
1353 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1354 {
1355 	size_t alloc_bytes;
1356 	void *orig = dst;
1357 	size_t bytes;
1358 
1359 	if (ZERO_OR_NULL_PTR(src))
1360 		goto out;
1361 
1362 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1363 		return NULL;
1364 
1365 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1366 	dst = krealloc(orig, alloc_bytes, flags);
1367 	if (!dst) {
1368 		kfree(orig);
1369 		return NULL;
1370 	}
1371 
1372 	memcpy(dst, src, bytes);
1373 out:
1374 	return dst ? dst : ZERO_SIZE_PTR;
1375 }
1376 
1377 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1378  * small to hold new_n items. new items are zeroed out if the array grows.
1379  *
1380  * Contrary to krealloc_array, does not free arr if new_n is zero.
1381  */
1382 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1383 {
1384 	size_t alloc_size;
1385 	void *new_arr;
1386 
1387 	if (!new_n || old_n == new_n)
1388 		goto out;
1389 
1390 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1391 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1392 	if (!new_arr) {
1393 		kfree(arr);
1394 		return NULL;
1395 	}
1396 	arr = new_arr;
1397 
1398 	if (new_n > old_n)
1399 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1400 
1401 out:
1402 	return arr ? arr : ZERO_SIZE_PTR;
1403 }
1404 
1405 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1406 {
1407 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1408 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1409 	if (!dst->refs)
1410 		return -ENOMEM;
1411 
1412 	dst->acquired_refs = src->acquired_refs;
1413 	dst->active_locks = src->active_locks;
1414 	dst->active_preempt_locks = src->active_preempt_locks;
1415 	dst->active_rcu_locks = src->active_rcu_locks;
1416 	dst->active_irq_id = src->active_irq_id;
1417 	dst->active_lock_id = src->active_lock_id;
1418 	dst->active_lock_ptr = src->active_lock_ptr;
1419 	return 0;
1420 }
1421 
1422 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1423 {
1424 	size_t n = bpf_stack_nr_slots(src);
1425 
1426 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1427 				GFP_KERNEL_ACCOUNT);
1428 	if (!dst->stack)
1429 		return -ENOMEM;
1430 
1431 	dst->allocated_stack = src->allocated_stack;
1432 
1433 	/* copy stack args state */
1434 	n = src->out_stack_arg_cnt;
1435 	if (n) {
1436 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1437 						 sizeof(struct bpf_reg_state),
1438 						 GFP_KERNEL_ACCOUNT);
1439 		if (!dst->stack_arg_regs)
1440 			return -ENOMEM;
1441 	}
1442 
1443 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1444 	return 0;
1445 }
1446 
1447 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1448 {
1449 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1450 				    sizeof(struct bpf_reference_state));
1451 	if (!state->refs)
1452 		return -ENOMEM;
1453 
1454 	state->acquired_refs = n;
1455 	return 0;
1456 }
1457 
1458 /* Possibly update state->allocated_stack to be at least size bytes. Also
1459  * possibly update the function's high-water mark in its bpf_subprog_info.
1460  */
1461 int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1462 {
1463 	size_t old_n = bpf_stack_nr_slots(state), n;
1464 
1465 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1466 	size = round_up(size, BPF_REG_SIZE);
1467 	n = size / BPF_REG_SIZE;
1468 
1469 	if (old_n >= n)
1470 		return 0;
1471 
1472 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1473 	if (!state->stack)
1474 		return -ENOMEM;
1475 
1476 	state->allocated_stack = size;
1477 
1478 	/* update known max for given subprogram */
1479 	if (env->subprog_info[state->subprogno].stack_depth < size)
1480 		env->subprog_info[state->subprogno].stack_depth = size;
1481 
1482 	return 0;
1483 }
1484 
1485 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1486 				struct bpf_func_state *state, int cnt)
1487 {
1488 	size_t old_n = state->out_stack_arg_cnt;
1489 
1490 	if (old_n >= cnt)
1491 		return 0;
1492 
1493 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1494 					      sizeof(struct bpf_reg_state));
1495 	if (!state->stack_arg_regs)
1496 		return -ENOMEM;
1497 
1498 	state->out_stack_arg_cnt = cnt;
1499 	return 0;
1500 }
1501 
1502 /* Acquire a pointer id from the env and update the state->refs to include
1503  * this new pointer reference.
1504  * On success, returns a valid pointer id to associate with the register
1505  * On failure, returns a negative errno.
1506  */
1507 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1508 {
1509 	struct bpf_verifier_state *state = env->cur_state;
1510 	int new_ofs = state->acquired_refs;
1511 	int err;
1512 
1513 	err = resize_reference_state(state, state->acquired_refs + 1);
1514 	if (err)
1515 		return NULL;
1516 	state->refs[new_ofs].insn_idx = insn_idx;
1517 
1518 	return &state->refs[new_ofs];
1519 }
1520 
1521 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1522 {
1523 	struct bpf_reference_state *s;
1524 
1525 	s = acquire_reference_state(env, insn_idx);
1526 	if (!s)
1527 		return -ENOMEM;
1528 	s->type = REF_TYPE_PTR;
1529 	s->id = ++env->id_gen;
1530 	s->parent_id = parent_id;
1531 	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
1532 	return s->id;
1533 }
1534 
1535 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1536 			      int id, void *ptr)
1537 {
1538 	struct bpf_verifier_state *state = env->cur_state;
1539 	struct bpf_reference_state *s;
1540 
1541 	s = acquire_reference_state(env, insn_idx);
1542 	if (!s)
1543 		return -ENOMEM;
1544 	s->type = type;
1545 	s->id = id;
1546 	s->ptr = ptr;
1547 
1548 	state->active_locks++;
1549 	state->active_lock_id = id;
1550 	state->active_lock_ptr = ptr;
1551 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_LOCK, true,
1552 				state->active_locks);
1553 	return 0;
1554 }
1555 
1556 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1557 {
1558 	struct bpf_verifier_state *state = env->cur_state;
1559 	struct bpf_reference_state *s;
1560 
1561 	s = acquire_reference_state(env, insn_idx);
1562 	if (!s)
1563 		return -ENOMEM;
1564 	s->type = REF_TYPE_IRQ;
1565 	s->id = ++env->id_gen;
1566 
1567 	state->active_irq_id = s->id;
1568 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true,
1569 				bpf_diag_irq_depth(state));
1570 	return s->id;
1571 }
1572 
1573 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1574 {
1575 	int last_idx;
1576 	size_t rem;
1577 
1578 	/* IRQ state requires the relative ordering of elements remaining the
1579 	 * same, since it relies on the refs array to behave as a stack, so that
1580 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1581 	 * the array instead of swapping the final element into the deleted idx.
1582 	 */
1583 	last_idx = state->acquired_refs - 1;
1584 	rem = state->acquired_refs - idx - 1;
1585 	if (last_idx && idx != last_idx)
1586 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1587 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1588 	state->acquired_refs--;
1589 	return;
1590 }
1591 
1592 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1593 {
1594 	int i;
1595 
1596 	for (i = 0; i < state->acquired_refs; i++) {
1597 		if (state->refs[i].type != REF_TYPE_PTR)
1598 			continue;
1599 		if (state->refs[i].id == id)
1600 			return true;
1601 	}
1602 
1603 	return false;
1604 }
1605 
1606 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1607 {
1608 	return find_reference_state(env->cur_state, reg->id);
1609 }
1610 
1611 static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr)
1612 {
1613 	struct bpf_verifier_state *state = env->cur_state;
1614 	void *prev_ptr = NULL;
1615 	u32 prev_id = 0;
1616 	int i;
1617 
1618 	for (i = 0; i < state->acquired_refs; i++) {
1619 		if (state->refs[i].type == type && state->refs[i].id == id &&
1620 		    state->refs[i].ptr == ptr) {
1621 			release_reference_state(state, i);
1622 			state->active_locks--;
1623 			/* Reassign active lock (id, ptr). */
1624 			state->active_lock_id = prev_id;
1625 			state->active_lock_ptr = prev_ptr;
1626 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_LOCK,
1627 						false, state->active_locks);
1628 			return 0;
1629 		}
1630 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1631 			prev_id = state->refs[i].id;
1632 			prev_ptr = state->refs[i].ptr;
1633 		}
1634 	}
1635 	return -EINVAL;
1636 }
1637 
1638 static int release_irq_state(struct bpf_verifier_env *env, int id)
1639 {
1640 	struct bpf_verifier_state *state = env->cur_state;
1641 	u32 prev_id = 0;
1642 	int i;
1643 
1644 	if (id != state->active_irq_id)
1645 		return -EACCES;
1646 
1647 	for (i = 0; i < state->acquired_refs; i++) {
1648 		if (state->refs[i].type != REF_TYPE_IRQ)
1649 			continue;
1650 		if (state->refs[i].id == id) {
1651 			release_reference_state(state, i);
1652 			state->active_irq_id = prev_id;
1653 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ,
1654 						false, bpf_diag_irq_depth(state));
1655 			return 0;
1656 		} else {
1657 			prev_id = state->refs[i].id;
1658 		}
1659 	}
1660 	return -EINVAL;
1661 }
1662 
1663 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1664 						   int id, void *ptr)
1665 {
1666 	int i;
1667 
1668 	for (i = 0; i < state->acquired_refs; i++) {
1669 		struct bpf_reference_state *s = &state->refs[i];
1670 
1671 		if (!(s->type & type))
1672 			continue;
1673 
1674 		if (s->id == id && s->ptr == ptr)
1675 			return s;
1676 	}
1677 	return NULL;
1678 }
1679 
1680 static void free_func_state(struct bpf_func_state *state)
1681 {
1682 	if (!state)
1683 		return;
1684 	kfree(state->loop_stack);
1685 	kfree(state->stack_arg_regs);
1686 	kfree(state->stack);
1687 	kfree(state);
1688 }
1689 
1690 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1691 {
1692 	kfree(state->jmp_history);
1693 	state->jmp_history = NULL;
1694 	state->jmp_history_cnt = 0;
1695 }
1696 
1697 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1698 			    bool free_self)
1699 {
1700 	int i;
1701 
1702 	for (i = 0; i <= state->curframe; i++) {
1703 		free_func_state(state->frame[i]);
1704 		state->frame[i] = NULL;
1705 	}
1706 	kfree(state->refs);
1707 	bpf_clear_jmp_history(state);
1708 	if (free_self)
1709 		kfree(state);
1710 }
1711 
1712 /* copy verifier state from src to dst growing dst stack space
1713  * when necessary to accommodate larger src stack
1714  */
1715 static int copy_func_state(struct bpf_func_state *dst,
1716 			   const struct bpf_func_state *src)
1717 {
1718 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1719 	/* Instruction accounting is path-local, not part of verifier state. */
1720 	dst->insns_subtotal = 0;
1721 	dst->loop_stack = copy_array(dst->loop_stack, src->loop_stack, src->loop_stack_cnt,
1722 				     sizeof(*src->loop_stack), GFP_KERNEL_ACCOUNT);
1723 	if (!dst->loop_stack)
1724 		return -ENOMEM;
1725 	return copy_stack_state(dst, src);
1726 }
1727 
1728 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1729 			   const struct bpf_verifier_state *src)
1730 {
1731 	struct bpf_func_state *dst;
1732 	int i, err;
1733 
1734 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1735 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1736 					  GFP_KERNEL_ACCOUNT);
1737 	if (!dst_state->jmp_history)
1738 		return -ENOMEM;
1739 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1740 
1741 	/* if dst has more stack frames then src frame, free them, this is also
1742 	 * necessary in case of exceptional exits using bpf_throw.
1743 	 */
1744 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1745 		free_func_state(dst_state->frame[i]);
1746 		dst_state->frame[i] = NULL;
1747 	}
1748 	err = copy_reference_state(dst_state, src);
1749 	if (err)
1750 		return err;
1751 	dst_state->speculative = src->speculative;
1752 	dst_state->in_sleepable = src->in_sleepable;
1753 	dst_state->curframe = src->curframe;
1754 	dst_state->branches = src->branches;
1755 	dst_state->parent = src->parent;
1756 	dst_state->first_insn_idx = src->first_insn_idx;
1757 	dst_state->last_insn_idx = src->last_insn_idx;
1758 	dst_state->dfs_depth = src->dfs_depth;
1759 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1760 	dst_state->may_goto_depth = src->may_goto_depth;
1761 	dst_state->equal_state = src->equal_state;
1762 	for (i = 0; i <= src->curframe; i++) {
1763 		dst = dst_state->frame[i];
1764 		if (!dst) {
1765 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1766 			if (!dst)
1767 				return -ENOMEM;
1768 			dst_state->frame[i] = dst;
1769 		}
1770 		err = copy_func_state(dst, src->frame[i]);
1771 		if (err)
1772 			return err;
1773 	}
1774 	return 0;
1775 }
1776 
1777 static u32 state_htab_size(struct bpf_verifier_env *env)
1778 {
1779 	return env->prog->len;
1780 }
1781 
1782 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1783 {
1784 	struct bpf_verifier_state *cur = env->cur_state;
1785 	struct bpf_func_state *state = cur->frame[cur->curframe];
1786 
1787 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1788 }
1789 
1790 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1791 {
1792 	int fr;
1793 
1794 	if (a->curframe != b->curframe)
1795 		return false;
1796 
1797 	for (fr = a->curframe; fr >= 0; fr--)
1798 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1799 			return false;
1800 
1801 	return true;
1802 }
1803 
1804 void bpf_free_backedges(struct bpf_scc_visit *visit)
1805 {
1806 	struct bpf_scc_backedge *backedge, *next;
1807 
1808 	for (backedge = visit->backedges; backedge; backedge = next) {
1809 		bpf_free_verifier_state(&backedge->state, false);
1810 		next = backedge->next;
1811 		kfree(backedge);
1812 	}
1813 	visit->backedges = NULL;
1814 }
1815 
1816 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1817 		     int *insn_idx, bool pop_log)
1818 {
1819 	struct bpf_verifier_state *cur = env->cur_state;
1820 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1821 	int err;
1822 
1823 	if (env->head == NULL)
1824 		return -ENOENT;
1825 
1826 	if (cur) {
1827 		err = bpf_copy_verifier_state(cur, &head->st);
1828 		if (err)
1829 			return err;
1830 		bpf_diag_event_log_restore(env, head->diag_log_pos);
1831 	}
1832 	if (pop_log)
1833 		bpf_vlog_reset(&env->log, head->log_pos);
1834 	if (insn_idx)
1835 		*insn_idx = head->insn_idx;
1836 	if (prev_insn_idx)
1837 		*prev_insn_idx = head->prev_insn_idx;
1838 	elem = head->next;
1839 	bpf_free_verifier_state(&head->st, false);
1840 	kfree(head);
1841 	env->head = elem;
1842 	env->stack_size--;
1843 	return 0;
1844 }
1845 
1846 static bool error_recoverable_with_nospec(int err)
1847 {
1848 	/* Should only return true for non-fatal errors that are allowed to
1849 	 * occur during speculative verification. For these we can insert a
1850 	 * nospec and the program might still be accepted. Do not include
1851 	 * something like ENOMEM because it is likely to re-occur for the next
1852 	 * architectural path once it has been recovered-from in all speculative
1853 	 * paths.
1854 	 */
1855 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1856 }
1857 
1858 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1859 					     int insn_idx, int prev_insn_idx,
1860 					     bool speculative)
1861 {
1862 	struct bpf_verifier_state *cur = env->cur_state;
1863 	struct bpf_verifier_stack_elem *elem;
1864 	int err;
1865 
1866 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1867 	if (!elem)
1868 		return ERR_PTR(-ENOMEM);
1869 
1870 	elem->insn_idx = insn_idx;
1871 	elem->prev_insn_idx = prev_insn_idx;
1872 	elem->next = env->head;
1873 	elem->log_pos = env->log.end_pos;
1874 	elem->diag_log_pos = bpf_diag_event_log_save(env);
1875 	env->head = elem;
1876 	env->stack_size++;
1877 	err = bpf_copy_verifier_state(&elem->st, cur);
1878 	if (err)
1879 		return ERR_PTR(-ENOMEM);
1880 	elem->st.speculative |= speculative;
1881 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1882 		verbose(env, "The sequence of %d jumps is too complex.\n",
1883 			env->stack_size);
1884 		return ERR_PTR(-E2BIG);
1885 	}
1886 	if (elem->st.parent) {
1887 		++elem->st.parent->branches;
1888 		/* WARN_ON(branches > 2) technically makes sense here,
1889 		 * but
1890 		 * 1. speculative states will bump 'branches' for non-branch
1891 		 * instructions
1892 		 * 2. is_state_visited() heuristics may decide not to create
1893 		 * a new state for a sequence of branches and all such current
1894 		 * and cloned states will be pointing to a single parent state
1895 		 * which might have large 'branches' count.
1896 		 */
1897 	}
1898 	return &elem->st;
1899 }
1900 
1901 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1902 {
1903 	char *buf = env->tmp_arg_name;
1904 	int len = sizeof(env->tmp_arg_name);
1905 	int arg, regno = reg_from_argno(argno);
1906 
1907 	if (regno >= 0) {
1908 		snprintf(buf, len, "R%d", regno);
1909 	} else {
1910 		arg = arg_from_argno(argno);
1911 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1912 	}
1913 
1914 	return buf;
1915 }
1916 
1917 static const int caller_saved[CALLER_SAVED_REGS] = {
1918 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1919 };
1920 
1921 static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
1922 					 struct bpf_reg_state *regs)
1923 {
1924 	int i;
1925 
1926 	for (i = 1; i < CALLER_SAVED_REGS; i++) {
1927 		bpf_diag_record_scrub(env, &regs[caller_saved[i]],
1928 				      BPF_DIAG_MOD_CALLER_SAVED);
1929 	}
1930 }
1931 
1932 static void reg_step_reset(struct bpf_reg_state *reg)
1933 {
1934 	reg->base = 0;
1935 	reg->step = 1;
1936 }
1937 
1938 static void scalar_step_add(struct bpf_reg_state *dst_reg,
1939 			    const struct bpf_reg_state *a,
1940 			    const struct bpf_reg_state *b)
1941 {
1942 	const struct bpf_reg_state *reg;
1943 	s64 amount, tmp;
1944 
1945 	if (tnum_is_const(b->var_off)) {
1946 		reg = a;
1947 		amount = (s64)b->var_off.value;
1948 	} else if (tnum_is_const(a->var_off)) {
1949 		reg = b;
1950 		amount = (s64)a->var_off.value;
1951 	} else {
1952 		reg_step_reset(dst_reg);
1953 		return;
1954 	}
1955 
1956 	/*
1957 	 * Let x be a possible signed value of the register,
1958 	 * d = amount, s = reg->step, and b = reg->base.
1959 	 * Then x mod s = b, with s > 0 and 0 <= b < s.
1960 	 * If the addition causes signed underflow, the resulting value
1961 	 * is x + d + 2**64.
1962 	 *
1963 	 * Taking the result modulo s and substituting x mod s = b gives:
1964 	 *   (x + d + 2**64) mod s = (b + d + (2**64 mod s)) mod s      (1)
1965 	 * Keeping reg->step = s and updating reg->base to (b + d) mod s
1966 	 * requires (1) to equal (b + d) mod s, which holds if and only
1967 	 * if 2**64 mod s = 0.
1968 	 * Signed overflow subtracts 2**64 and has the same requirement.
1969 	 *
1970 	 * Conservatively reset the stride if either wrap is possible.
1971 	 */
1972 	if (check_add_overflow(reg_smin(reg), amount, &tmp) ||
1973 	    check_add_overflow(reg_smax(reg), amount, &tmp)) {
1974 		reg_step_reset(dst_reg);
1975 		return;
1976 	}
1977 
1978 	dst_reg->base = (reg->base + imod(amount, reg->step)) % reg->step;
1979 	dst_reg->step = reg->step;
1980 }
1981 
1982 static void scalar_step_scale(struct bpf_reg_state *dst_reg, u64 amount)
1983 {
1984 	u16 step;
1985 	s64 tmp;
1986 
1987 	/*
1988 	 * Using the same notation as scalar_step_add(), with d > 0,
1989 	 * the scaled value satisfies (x * d) mod (s * d) = b * d.
1990 	 * If the multiplication wraps, its signed result can be represented
1991 	 * as x * d - n * 2**64 for some nonzero integer n.
1992 	 *
1993 	 * Taking the result modulo s * d gives:
1994 	 *   (x * d - n * 2**64) mod (s * d) =
1995 	 *   (b * d - (n * 2**64 mod (s * d))) mod (s * d)              (1)
1996 	 * Updating dst_reg->base to b * d and dst_reg->step to s * d
1997 	 * requires (1) to equal b * d, which holds if and only if
1998 	 * n * 2**64 mod (s * d) = 0.
1999 	 *
2000 	 * Conservatively reset the stride if a wrap is possible.
2001 	 */
2002 	if (amount == 0 || check_mul_overflow(dst_reg->step, amount, &step) ||
2003 	    check_mul_overflow(reg_smin(dst_reg), (s64)amount, &tmp) ||
2004 	    check_mul_overflow(reg_smax(dst_reg), (s64)amount, &tmp)) {
2005 		reg_step_reset(dst_reg);
2006 		return;
2007 	}
2008 	/*
2009 	 * The above established that `step = dst_reg->step * amount`
2010 	 * does not overflow, therefore the base < step invariant holds
2011 	 * after assignments below.
2012 	 */
2013 	dst_reg->base = dst_reg->base * amount;
2014 	dst_reg->step = step;
2015 }
2016 
2017 /*
2018  * Let x be a possible signed value of the register,
2019  * s = reg->step, and b = reg->base.
2020  * Then x mod s = b, with s > 0 and 0 <= b < s.
2021  * Truncating to N bits and then zero- or sign-extending x
2022  * is equivalent to computing x + k * 2**N for some integer k.
2023  * For example, sign-extending the low 8 bits of x = 255 can
2024  * be expressed as 255 - 2**8 = -1.
2025  *
2026  * Taking the result modulo s and substituting x mod s = b gives:
2027  *   (x + k * 2**N) mod s = (b + (k * 2**N mod s)) mod s
2028  * Keeping reg->base = b and reg->step = s requires this to equal b,
2029  * which holds if and only if k * 2**N mod s = 0.
2030  * Continuing the example with s = 3 and b = 0, we have 255 mod 3 = 0,
2031  * but (-1) mod 3 = 2, so the original base and step no longer hold.
2032  *
2033  * Conservatively reset the stride unless all possible values fit in
2034  * the range where the conversion leaves them unchanged.
2035  * Call before updating the register's bounds. Requires 0 < bits < 64.
2036  */
2037 static void reg_step_check_unsigned(struct bpf_reg_state *reg, u32 bits)
2038 {
2039 	if (reg_umax(reg) >= (1ULL << bits))
2040 		reg_step_reset(reg);
2041 }
2042 
2043 /* This helper doesn't clear reg->id */
2044 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2045 {
2046 	reg->var_off = tnum_const(imm);
2047 	reg->r64 = cnum64_from_urange(imm, imm);
2048 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2049 	reg_step_reset(reg);
2050 }
2051 
2052 /* Mark the unknown part of a register (variable offset or scalar value) as
2053  * known to have the value @imm.
2054  */
2055 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2056 {
2057 	/* Clear off and union(map_ptr, range) */
2058 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2059 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2060 	reg->id = 0;
2061 	reg->parent_id = 0;
2062 	reg->map_uid = 0;
2063 	___mark_reg_known(reg, imm);
2064 }
2065 
2066 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
2067 {
2068 	__mark_reg_known(reg, imm);
2069 	reg->type = SCALAR_VALUE;
2070 }
2071 
2072 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2073 {
2074 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2075 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2076 }
2077 
2078 /* Mark the 'variable offset' part of a register as zero.  This should be
2079  * used only on registers holding a pointer type.
2080  */
2081 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2082 {
2083 	__mark_reg_known(reg, 0);
2084 }
2085 
2086 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2087 {
2088 	__mark_reg_known(reg, 0);
2089 	reg->type = SCALAR_VALUE;
2090 	/* all scalars are assumed imprecise initially (unless unprivileged,
2091 	 * in which case everything is forced to be precise)
2092 	 */
2093 	reg->precise = !env->bpf_capable;
2094 }
2095 
2096 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2097 				struct bpf_reg_state *regs, u32 regno)
2098 {
2099 	__mark_reg_known_zero(regs + regno);
2100 }
2101 
2102 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2103 			      bool first_slot, int id, int parent_id)
2104 {
2105 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2106 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2107 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2108 	 */
2109 	__mark_reg_known_zero(reg);
2110 	reg->type = CONST_PTR_TO_DYNPTR;
2111 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2112 	reg->id = id;
2113 	reg->parent_id = parent_id;
2114 	reg->dynptr.type = type;
2115 	reg->dynptr.first_slot = first_slot;
2116 }
2117 
2118 /*
2119  * Refine the return type of the bpf_map_lookup_elem() for special map types:
2120  * map-in-map, xskmap, sockmap and sockhash.
2121  */
2122 static void refine_map_lookup_value(struct bpf_reg_state *reg)
2123 {
2124 	enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL;
2125 	const struct bpf_map *map = reg->map_ptr;
2126 
2127 	if (map->inner_map_meta) {
2128 		reg->type = CONST_PTR_TO_MAP | maybe_null;
2129 		reg->map_ptr = map->inner_map_meta;
2130 		/*
2131 		 * transfer reg's id which is unique for every map_lookup_elem
2132 		 * as UID of the inner map.
2133 		 */
2134 		reg->map_uid = reg->id;
2135 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2136 		reg->type = PTR_TO_XDP_SOCK | maybe_null;
2137 		reg->map_uid = 0;
2138 	} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2139 		   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2140 		reg->type = PTR_TO_SOCKET | maybe_null;
2141 		reg->map_uid = 0;
2142 	}
2143 }
2144 
2145 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2146 {
2147 	reg->type &= ~PTR_MAYBE_NULL;
2148 }
2149 
2150 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2151 				struct btf_field_graph_root *ds_head)
2152 {
2153 	__mark_reg_known(&regs[regno], ds_head->node_offset);
2154 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2155 	regs[regno].btf = ds_head->btf;
2156 	regs[regno].btf_id = ds_head->value_btf_id;
2157 }
2158 
2159 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2160 {
2161 	return type_is_pkt_pointer(reg->type);
2162 }
2163 
2164 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2165 {
2166 	return reg_is_pkt_pointer(reg) ||
2167 	       reg->type == PTR_TO_PACKET_END;
2168 }
2169 
2170 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2171 {
2172 	return base_type(reg->type) == PTR_TO_MEM &&
2173 	       (reg->type &
2174 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2175 }
2176 
2177 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2178 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2179 				    enum bpf_reg_type which)
2180 {
2181 	/* The register can already have a range from prior markings.
2182 	 * This is fine as long as it hasn't been advanced from its
2183 	 * origin.
2184 	 */
2185 	return reg->type == which &&
2186 	       reg->id == 0 &&
2187 	       tnum_equals_const(reg->var_off, 0);
2188 }
2189 
2190 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2191 {
2192 	reg->r32 = CNUM32_UNBOUNDED;
2193 }
2194 
2195 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2196 {
2197 	reg->r64 = CNUM64_UNBOUNDED;
2198 }
2199 
2200 /* Reset the min/max bounds of a register */
2201 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2202 {
2203 	__mark_reg64_unbounded(reg);
2204 	__mark_reg32_unbounded(reg);
2205 }
2206 
2207 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
2208 {
2209 	__mark_reg64_unbounded(reg);
2210 	reg->var_off = tnum_unknown;
2211 }
2212 
2213 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
2214 {
2215 	__mark_reg32_unbounded(reg);
2216 	reg->var_off = tnum_unknown;
2217 }
2218 
2219 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
2220 {
2221 	tnum = tnum_subreg(tnum);
2222 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
2223 		/* min signed is max(sign bit) | min(other bits) */
2224 		/* max signed is min(sign bit) | max(other bits) */
2225 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
2226 					  tnum.value | (tnum.mask & S32_MAX));
2227 	else
2228 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
2229 }
2230 
2231 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
2232 {
2233 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
2234 		/* min signed is max(sign bit) | min(other bits) */
2235 		/* max signed is min(sign bit) | max(other bits) */
2236 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
2237 					  tnum.value | (tnum.mask & S64_MAX));
2238 	else
2239 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
2240 }
2241 
2242 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2243 {
2244 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
2245 }
2246 
2247 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2248 {
2249 	u64 tnum_next, tmax;
2250 	bool umin_in_tnum;
2251 
2252 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2253 
2254 	/* Check if u64 and tnum overlap in a single value */
2255 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2256 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2257 	tmax = reg->var_off.value | reg->var_off.mask;
2258 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2259 		/* The u64 range and the tnum only overlap in umin.
2260 		 * u64:  ---[xxxxxx]-----
2261 		 * tnum: --xx----------x-
2262 		 */
2263 		___mark_reg_known(reg, reg_umin(reg));
2264 	} else if (!umin_in_tnum && tnum_next == tmax) {
2265 		/* The u64 range and the tnum only overlap in the maximum value
2266 		 * represented by the tnum, called tmax.
2267 		 * u64:  ---[xxxxxx]-----
2268 		 * tnum: xx-----x--------
2269 		 */
2270 		___mark_reg_known(reg, tmax);
2271 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2272 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2273 		/* The u64 range and the tnum only overlap in between umin
2274 		 * (excluded) and umax.
2275 		 * u64:  ---[xxxxxx]-----
2276 		 * tnum: xx----x-------x-
2277 		 */
2278 		___mark_reg_known(reg, tnum_next);
2279 	}
2280 }
2281 
2282 static void __update_reg_bounds(struct bpf_reg_state *reg)
2283 {
2284 	__update_reg32_bounds(reg);
2285 	__update_reg64_bounds(reg);
2286 }
2287 
2288 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2289 {
2290 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2291 }
2292 
2293 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2294 {
2295 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2296 }
2297 
2298 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2299 {
2300 	deduce_bounds_32_from_64(reg);
2301 	deduce_bounds_64_from_32(reg);
2302 }
2303 
2304 /* Attempts to improve var_off based on unsigned min/max information */
2305 static void __reg_bound_offset(struct bpf_reg_state *reg)
2306 {
2307 	struct tnum var64_off = tnum_intersect(reg->var_off,
2308 					       tnum_range(reg_umin(reg),
2309 							  reg_umax(reg)));
2310 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2311 					       tnum_range(reg_u32_min(reg),
2312 							  reg_u32_max(reg)));
2313 	u32 trailing_zero_bits;
2314 	u16 base = reg->base;
2315 	u16 step = reg->step;
2316 
2317 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2318 
2319 	if (base == 0)
2320 		trailing_zero_bits = count_trailing_zeros(step);
2321 	else
2322 		trailing_zero_bits = min(count_trailing_zeros(base),
2323 					 count_trailing_zeros(step));
2324 	reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
2325 }
2326 
2327 static void __update_bounds_from_step(struct bpf_reg_state *reg)
2328 {
2329 	reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
2330 	deduce_bounds_32_from_64(reg);
2331 }
2332 
2333 static bool range_bounds_violation(struct bpf_reg_state *reg);
2334 
2335 static void reg_bounds_sync(struct bpf_reg_state *reg)
2336 {
2337 	/* If the input reg_state is invalid, we can exit early */
2338 	if (range_bounds_violation(reg))
2339 		return;
2340 	/* We might have learned new bounds from the var_off. */
2341 	__update_reg_bounds(reg);
2342 	/* We might have learned something about the sign bit. */
2343 	__reg_deduce_bounds(reg);
2344 	__reg_deduce_bounds(reg);
2345 	/* We might have learned some bits from the bounds. */
2346 	__reg_bound_offset(reg);
2347 	/* Intersecting with the old var_off might have improved our bounds
2348 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2349 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2350 	 */
2351 	__update_reg_bounds(reg);
2352 	/*
2353 	 * Both tnum and base+step define a sequence of points,
2354 	 * potentially w/o intersection, or intersecting after N
2355 	 * tnum_step()'s, where N can be large. On the other hand,
2356 	 * step+base *must* be in sync with r64 in order for
2357 	 * array traversal logic starting at reg_umin() to be sound.
2358 	 * Hence, place this as a final step in the reg_bounds_sync().
2359 	 */
2360 	__update_bounds_from_step(reg);
2361 }
2362 
2363 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2364 {
2365 	if (!tnum_is_const(reg->var_off))
2366 		return false;
2367 
2368 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2369 }
2370 
2371 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2372 {
2373 	if (!tnum_subreg_is_const(reg->var_off))
2374 		return false;
2375 
2376 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2377 }
2378 
2379 static bool range_bounds_violation(struct bpf_reg_state *reg)
2380 {
2381 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2382 }
2383 
2384 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2385 				   struct bpf_reg_state *reg, const char *ctx)
2386 {
2387 	const char *msg;
2388 
2389 	if (range_bounds_violation(reg)) {
2390 		msg = "range bounds violation";
2391 		goto out;
2392 	}
2393 
2394 	if (const_tnum_range_mismatch(reg)) {
2395 		msg = "const tnum out of sync with range bounds";
2396 		goto out;
2397 	}
2398 
2399 	if (const_tnum_range_mismatch_32(reg)) {
2400 		msg = "const subreg tnum out of sync with range bounds";
2401 		goto out;
2402 	}
2403 
2404 	if (reg->step == 0 || reg->base >= reg->step) {
2405 		msg = "invalid base/step";
2406 		goto out;
2407 	}
2408 
2409 	return 0;
2410 out:
2411 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2412 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u",
2413 		     ctx, msg,
2414 		     reg->r64.base, reg->r64.size,
2415 		     reg->r32.base, reg->r32.size,
2416 		     reg->var_off.value, reg->var_off.mask,
2417 		     reg->base, reg->step);
2418 	if (env->test_reg_invariants)
2419 		return -EFAULT;
2420 	__mark_reg_unbounded(reg);
2421 	reg_step_reset(reg);
2422 	return 0;
2423 }
2424 
2425 /* Mark a register as having a completely unknown (scalar) value. */
2426 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2427 {
2428 	memset(reg, 0, sizeof(*reg));
2429 	reg->type = SCALAR_VALUE;
2430 	reg->var_off = tnum_unknown;
2431 	__mark_reg_unbounded(reg);
2432 	reg_step_reset(reg);
2433 }
2434 
2435 /* Mark a register as having a completely unknown (scalar) value,
2436  * initialize .precise as true when not bpf capable.
2437  */
2438 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2439 			       struct bpf_reg_state *reg)
2440 {
2441 	bpf_mark_reg_unknown_imprecise(reg);
2442 	reg->precise = !env->bpf_capable;
2443 }
2444 
2445 static void mark_reg_unknown(struct bpf_verifier_env *env,
2446 			     struct bpf_reg_state *regs, u32 regno)
2447 {
2448 	__mark_reg_unknown(env, regs + regno);
2449 }
2450 
2451 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2452 				struct bpf_reg_state *regs,
2453 				u32 regno,
2454 				s32 s32_min,
2455 				s32 s32_max)
2456 {
2457 	struct bpf_reg_state *reg = regs + regno;
2458 
2459 	reg_set_srange32(reg,
2460 			 max_t(s32, reg_s32_min(reg), s32_min),
2461 			 min_t(s32, reg_s32_max(reg), s32_max));
2462 	reg_set_srange64(reg,
2463 			 max_t(s64, reg_smin(reg), s32_min),
2464 			 min_t(s64, reg_smax(reg), s32_max));
2465 
2466 	reg_bounds_sync(reg);
2467 
2468 	return reg_bounds_sanity_check(env, reg, "s32_range");
2469 }
2470 
2471 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2472 			   struct bpf_reg_state *reg)
2473 {
2474 	__mark_reg_unknown(env, reg);
2475 	reg->type = NOT_INIT;
2476 }
2477 
2478 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2479 			   struct bpf_reg_state *regs, u32 regno,
2480 			   enum bpf_reg_type reg_type,
2481 			   struct btf *btf, u32 btf_id,
2482 			   enum bpf_type_flag flag)
2483 {
2484 	switch (reg_type) {
2485 	case SCALAR_VALUE:
2486 		mark_reg_unknown(env, regs, regno);
2487 		return 0;
2488 	case PTR_TO_BTF_ID:
2489 		mark_reg_known_zero(env, regs, regno);
2490 		regs[regno].type = PTR_TO_BTF_ID | flag;
2491 		regs[regno].btf = btf;
2492 		regs[regno].btf_id = btf_id;
2493 		if (type_may_be_null(flag))
2494 			regs[regno].id = ++env->id_gen;
2495 		return 0;
2496 	case PTR_TO_MEM:
2497 		mark_reg_known_zero(env, regs, regno);
2498 		regs[regno].type = PTR_TO_MEM | flag;
2499 		regs[regno].mem_size = 0;
2500 		return 0;
2501 	default:
2502 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2503 		return -EFAULT;
2504 	}
2505 }
2506 
2507 static void init_reg_state(struct bpf_verifier_env *env,
2508 			   struct bpf_func_state *state)
2509 {
2510 	struct bpf_reg_state *regs = state->regs;
2511 	int i;
2512 
2513 	for (i = 0; i < MAX_BPF_REG; i++) {
2514 		bpf_mark_reg_not_init(env, &regs[i]);
2515 	}
2516 
2517 	/* frame pointer */
2518 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2519 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2520 	regs[BPF_REG_FP].frameno = state->frameno;
2521 }
2522 
2523 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2524 {
2525 	/*
2526 	 * return_32bit is set to false by default and set explicitly
2527 	 * by the caller when necessary.
2528 	 */
2529 	return (struct bpf_retval_range){ minval, maxval, false };
2530 }
2531 
2532 static void init_func_state(struct bpf_verifier_env *env,
2533 			    struct bpf_func_state *state,
2534 			    int callsite, int frameno, int subprogno)
2535 {
2536 	state->callsite = callsite;
2537 	state->frameno = frameno;
2538 	bpf_diag_init_frame(env, state);
2539 	state->subprogno = subprogno;
2540 	state->callback_ret_range = retval_range(0, 0);
2541 	init_reg_state(env, state);
2542 	mark_verifier_state_scratched(env);
2543 }
2544 
2545 /* Similar to push_stack(), but for async callbacks */
2546 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2547 						int insn_idx, int prev_insn_idx,
2548 						int subprog, bool is_sleepable)
2549 {
2550 	struct bpf_verifier_stack_elem *elem;
2551 	struct bpf_func_state *frame;
2552 
2553 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2554 	if (!elem)
2555 		return ERR_PTR(-ENOMEM);
2556 
2557 	elem->insn_idx = insn_idx;
2558 	elem->prev_insn_idx = prev_insn_idx;
2559 	elem->next = env->head;
2560 	elem->log_pos = env->log.end_pos;
2561 	elem->diag_log_pos = bpf_diag_event_log_save(env);
2562 	env->head = elem;
2563 	env->stack_size++;
2564 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2565 		verbose(env,
2566 			"The sequence of %d jumps is too complex for async cb.\n",
2567 			env->stack_size);
2568 		return ERR_PTR(-E2BIG);
2569 	}
2570 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2571 	 * The caller state doesn't matter.
2572 	 * This is async callback. It starts in a fresh stack.
2573 	 * Initialize it similar to do_check_common().
2574 	 */
2575 	elem->st.branches = 1;
2576 	elem->st.in_sleepable = is_sleepable;
2577 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2578 	if (!frame)
2579 		return ERR_PTR(-ENOMEM);
2580 	init_func_state(env, frame,
2581 			BPF_MAIN_FUNC /* callsite */,
2582 			0 /* frameno within this callchain */,
2583 			subprog /* subprog number within this prog */);
2584 	elem->st.frame[0] = frame;
2585 	return &elem->st;
2586 }
2587 
2588 static int cmp_subprogs(const void *a, const void *b)
2589 {
2590 	return ((struct bpf_subprog_info *)a)->start -
2591 	       ((struct bpf_subprog_info *)b)->start;
2592 }
2593 
2594 /* Find subprogram that contains instruction at 'off' */
2595 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2596 {
2597 	struct bpf_subprog_info *vals = env->subprog_info;
2598 	int l, r, m;
2599 
2600 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2601 		return NULL;
2602 
2603 	l = 0;
2604 	r = env->subprog_cnt - 1;
2605 	while (l < r) {
2606 		m = l + (r - l + 1) / 2;
2607 		if (vals[m].start <= off)
2608 			l = m;
2609 		else
2610 			r = m - 1;
2611 	}
2612 	return &vals[l];
2613 }
2614 
2615 /* Find subprogram that starts exactly at 'off' */
2616 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2617 {
2618 	struct bpf_subprog_info *p;
2619 
2620 	p = bpf_find_containing_subprog(env, off);
2621 	if (!p || p->start != off)
2622 		return -ENOENT;
2623 	return p - env->subprog_info;
2624 }
2625 
2626 static int add_subprog(struct bpf_verifier_env *env, int off)
2627 {
2628 	int insn_cnt = env->prog->len;
2629 	int ret;
2630 
2631 	if (off >= insn_cnt || off < 0) {
2632 		verbose(env, "call to invalid destination\n");
2633 		return -EINVAL;
2634 	}
2635 	ret = bpf_find_subprog(env, off);
2636 	if (ret >= 0)
2637 		return ret;
2638 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2639 		verbose(env, "too many subprograms\n");
2640 		return -E2BIG;
2641 	}
2642 	/* determine subprog starts. The end is one before the next starts */
2643 	env->subprog_info[env->subprog_cnt].exit_idx = U32_MAX;
2644 	env->subprog_info[env->subprog_cnt++].start = off;
2645 	sort(env->subprog_info, env->subprog_cnt,
2646 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2647 	return env->subprog_cnt - 1;
2648 }
2649 
2650 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2651 {
2652 	struct bpf_prog_aux *aux = env->prog->aux;
2653 	struct btf *btf = aux->btf;
2654 	const struct btf_type *t;
2655 	u32 main_btf_id, id;
2656 	const char *name;
2657 	int ret, i;
2658 
2659 	/* Non-zero func_info_cnt implies valid btf */
2660 	if (!aux->func_info_cnt)
2661 		return 0;
2662 	main_btf_id = aux->func_info[0].type_id;
2663 
2664 	t = btf_type_by_id(btf, main_btf_id);
2665 	if (!t) {
2666 		verbose(env, "invalid btf id for main subprog in func_info\n");
2667 		return -EINVAL;
2668 	}
2669 
2670 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2671 	if (IS_ERR(name)) {
2672 		ret = PTR_ERR(name);
2673 		/* If there is no tag present, there is no exception callback */
2674 		if (ret == -ENOENT)
2675 			ret = 0;
2676 		else if (ret == -EEXIST)
2677 			verbose(env, "multiple exception callback tags for main subprog\n");
2678 		return ret;
2679 	}
2680 
2681 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2682 	if (ret < 0) {
2683 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2684 		return ret;
2685 	}
2686 	id = ret;
2687 	t = btf_type_by_id(btf, id);
2688 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2689 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2690 		return -EINVAL;
2691 	}
2692 	ret = 0;
2693 	for (i = 0; i < aux->func_info_cnt; i++) {
2694 		if (aux->func_info[i].type_id != id)
2695 			continue;
2696 		ret = aux->func_info[i].insn_off;
2697 		/* Further func_info and subprog checks will also happen
2698 		 * later, so assume this is the right insn_off for now.
2699 		 */
2700 		if (!ret) {
2701 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2702 			ret = -EINVAL;
2703 		}
2704 	}
2705 	if (!ret) {
2706 		verbose(env, "exception callback type id not found in func_info\n");
2707 		ret = -EINVAL;
2708 	}
2709 	return ret;
2710 }
2711 
2712 #define MAX_KFUNC_BTFS	256
2713 
2714 struct bpf_kfunc_btf {
2715 	struct btf *btf;
2716 	struct module *module;
2717 	u16 offset;
2718 };
2719 
2720 struct bpf_kfunc_btf_tab {
2721 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2722 	u32 nr_descs;
2723 };
2724 
2725 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2726 {
2727 	const struct bpf_kfunc_desc *d0 = a;
2728 	const struct bpf_kfunc_desc *d1 = b;
2729 
2730 	/* func_id is not greater than BTF_MAX_TYPE */
2731 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2732 }
2733 
2734 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2735 {
2736 	const struct bpf_kfunc_btf *d0 = a;
2737 	const struct bpf_kfunc_btf *d1 = b;
2738 
2739 	return d0->offset - d1->offset;
2740 }
2741 
2742 static struct bpf_kfunc_desc *
2743 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2744 {
2745 	struct bpf_kfunc_desc desc = {
2746 		.func_id = func_id,
2747 		.offset = offset,
2748 	};
2749 	struct bpf_kfunc_desc_tab *tab;
2750 
2751 	tab = prog->aux->kfunc_tab;
2752 	return bsearch(&desc, tab->descs, tab->nr_base_descs,
2753 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2754 }
2755 
2756 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2757 		       u16 desc_idx, u8 **func_addr)
2758 {
2759 	struct bpf_kfunc_desc_tab *tab;
2760 	const struct bpf_kfunc_desc *desc;
2761 
2762 	tab = prog->aux->kfunc_tab;
2763 	if (desc_idx >= tab->nr_descs)
2764 		return -EFAULT;
2765 	desc = &tab->descs[desc_idx];
2766 	if (desc->func_id != func_id)
2767 		return -EFAULT;
2768 
2769 	*func_addr = (u8 *)desc->addr;
2770 	return 0;
2771 }
2772 
2773 #define BPF_FD_SLOT_BTF	1UL
2774 
2775 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map)
2776 {
2777 	slot->val = (unsigned long)map;
2778 }
2779 
2780 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf)
2781 {
2782 	slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF;
2783 }
2784 
2785 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot)
2786 {
2787 	if (slot.val & BPF_FD_SLOT_BTF)
2788 		return NULL;
2789 	return (struct bpf_map *)slot.val;
2790 }
2791 
2792 static struct btf *fd_slot_btf(struct bpf_fd_array slot)
2793 {
2794 	if (!(slot.val & BPF_FD_SLOT_BTF))
2795 		return NULL;
2796 	return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF);
2797 }
2798 
2799 static struct btf *
2800 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx)
2801 {
2802 	struct btf *btf;
2803 
2804 	if (idx >= env->fd_array_cnt) {
2805 		verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n",
2806 			idx, env->fd_array_cnt);
2807 		return ERR_PTR(-EINVAL);
2808 	}
2809 	btf = fd_slot_btf(env->fd_array[idx]);
2810 	if (!btf) {
2811 		verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx);
2812 		return ERR_PTR(-EINVAL);
2813 	}
2814 	btf_get(btf);
2815 	return btf;
2816 }
2817 
2818 static struct btf *
2819 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx)
2820 {
2821 	struct btf *btf;
2822 	int btf_fd;
2823 
2824 	if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw,
2825 				    (size_t)idx * sizeof(btf_fd), sizeof(btf_fd)))
2826 		return ERR_PTR(-EFAULT);
2827 	btf = btf_get_by_fd(btf_fd);
2828 	if (IS_ERR(btf)) {
2829 		verbose(env, "invalid module BTF fd specified\n");
2830 		return btf;
2831 	}
2832 	return btf;
2833 }
2834 
2835 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx)
2836 {
2837 	if (env->signature) {
2838 		verbose(env, "signed program cannot bind any BTF\n");
2839 		return ERR_PTR(-EACCES);
2840 	}
2841 	if (env->fd_array)
2842 		return fd_array_get_btf_continuous(env, idx);
2843 	if (!bpfptr_is_null(env->fd_array_raw))
2844 		return fd_array_get_btf_sparse(env, idx);
2845 
2846 	verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2847 	return ERR_PTR(-EPROTO);
2848 }
2849 
2850 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2851 					 s16 offset)
2852 {
2853 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2854 	struct bpf_kfunc_btf_tab *tab;
2855 	struct bpf_kfunc_btf *b;
2856 	struct module *mod;
2857 	struct btf *btf;
2858 
2859 	tab = env->prog->aux->kfunc_btf_tab;
2860 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2861 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2862 	if (!b) {
2863 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2864 			verbose(env, "too many different module BTFs\n");
2865 			return ERR_PTR(-E2BIG);
2866 		}
2867 
2868 		btf = fd_array_get_btf(env, offset);
2869 		if (IS_ERR(btf))
2870 			return btf;
2871 		if (!btf_is_module(btf)) {
2872 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2873 			btf_put(btf);
2874 			return ERR_PTR(-EINVAL);
2875 		}
2876 
2877 		mod = btf_try_get_module(btf);
2878 		if (!mod) {
2879 			btf_put(btf);
2880 			return ERR_PTR(-ENXIO);
2881 		}
2882 
2883 		b = &tab->descs[tab->nr_descs++];
2884 		b->btf = btf;
2885 		b->module = mod;
2886 		b->offset = offset;
2887 
2888 		/* sort() reorders entries by value, so b may no longer point
2889 		 * to the right entry after this
2890 		 */
2891 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2892 		     kfunc_btf_cmp_by_off, NULL);
2893 	} else {
2894 		btf = b->btf;
2895 	}
2896 
2897 	return btf;
2898 }
2899 
2900 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2901 {
2902 	if (!tab)
2903 		return;
2904 
2905 	while (tab->nr_descs--) {
2906 		module_put(tab->descs[tab->nr_descs].module);
2907 		btf_put(tab->descs[tab->nr_descs].btf);
2908 	}
2909 	kfree(tab);
2910 }
2911 
2912 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2913 {
2914 	if (offset) {
2915 		if (offset < 0) {
2916 			/* In the future, this can be allowed to increase limit
2917 			 * of fd index into fd_array, interpreted as u16.
2918 			 */
2919 			verbose(env, "negative offset disallowed for kernel module function call\n");
2920 			return ERR_PTR(-EINVAL);
2921 		}
2922 
2923 		return __find_kfunc_desc_btf(env, offset);
2924 	}
2925 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2926 }
2927 
2928 static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset)
2929 {
2930 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2931 	struct bpf_kfunc_btf_tab *tab;
2932 	struct bpf_kfunc_btf *b;
2933 
2934 	if (!offset)
2935 		return btf_vmlinux ?: ERR_PTR(-ENOENT);
2936 	if (offset < 0)
2937 		return ERR_PTR(-EINVAL);
2938 
2939 	tab = env->prog->aux->kfunc_btf_tab;
2940 	if (!tab)
2941 		return ERR_PTR(-ENOENT);
2942 
2943 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2944 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2945 	return b ? b->btf : ERR_PTR(-ENOENT);
2946 }
2947 
2948 #define KF_IMPL_SUFFIX "_impl"
2949 
2950 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2951 						    struct btf *btf,
2952 						    const char *func_name)
2953 {
2954 	const struct btf_type *func;
2955 	char buf[KSYM_NAME_LEN];
2956 	s32 impl_id;
2957 	int len;
2958 
2959 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2960 	if (len < 0 || len >= sizeof(buf)) {
2961 		bpf_log(log, "function name %s%s is too long\n",
2962 			func_name, KF_IMPL_SUFFIX);
2963 		return NULL;
2964 	}
2965 
2966 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
2967 	if (impl_id <= 0) {
2968 		bpf_log(log, "cannot find function %s in BTF\n", buf);
2969 		return NULL;
2970 	}
2971 
2972 	func = btf_type_by_id(btf, impl_id);
2973 
2974 	return btf_type_by_id(btf, func->type);
2975 }
2976 
2977 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
2978 			    s32 func_id,
2979 			    s16 offset,
2980 			    struct bpf_kfunc_meta *kfunc)
2981 {
2982 	const struct btf_type *func, *func_proto;
2983 	const char *func_name;
2984 	u32 *kfunc_flags;
2985 	struct btf *btf;
2986 
2987 	if (func_id <= 0) {
2988 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
2989 		return -EINVAL;
2990 	}
2991 
2992 	btf = find_kfunc_desc_btf(env, offset);
2993 	if (IS_ERR(btf)) {
2994 		verbose(env, "failed to find BTF for kernel function\n");
2995 		return PTR_ERR(btf);
2996 	}
2997 
2998 	/*
2999 	 * Note that kfunc_flags may be NULL at this point, which
3000 	 * means that we couldn't find func_id in any relevant
3001 	 * kfunc_id_set. This most likely indicates an invalid kfunc
3002 	 * call.  However we don't fail with an error here,
3003 	 * and let the caller decide what to do with NULL kfunc->flags.
3004 	 */
3005 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
3006 
3007 	func = btf_type_by_id(btf, func_id);
3008 	if (!func || !btf_type_is_func(func)) {
3009 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
3010 		return -EINVAL;
3011 	}
3012 
3013 	func_name = btf_name_by_offset(btf, func->name_off);
3014 
3015 	/*
3016 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
3017 	 * can be found through the counterpart _impl kfunc.
3018 	 */
3019 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
3020 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
3021 	else
3022 		func_proto = btf_type_by_id(btf, func->type);
3023 
3024 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3025 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
3026 			func_id);
3027 		return -EINVAL;
3028 	}
3029 
3030 	memset(kfunc, 0, sizeof(*kfunc));
3031 	kfunc->btf = btf;
3032 	kfunc->id = func_id;
3033 	kfunc->name = func_name;
3034 	kfunc->proto = func_proto;
3035 	kfunc->flags = kfunc_flags;
3036 
3037 	return 0;
3038 }
3039 
3040 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3041 			       const struct btf_func_model *fm, struct bpf_func_proto *proto);
3042 
3043 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
3044 {
3045 	struct bpf_call_arg_meta meta;
3046 	struct bpf_kfunc_btf_tab *btf_tab;
3047 	struct btf_func_model func_model;
3048 	struct bpf_kfunc_desc_tab *tab;
3049 	struct bpf_prog_aux *prog_aux;
3050 	struct bpf_kfunc_meta kfunc;
3051 	struct bpf_kfunc_desc *desc;
3052 	unsigned long addr;
3053 	int err;
3054 
3055 	prog_aux = env->prog->aux;
3056 	tab = prog_aux->kfunc_tab;
3057 	btf_tab = prog_aux->kfunc_btf_tab;
3058 	if (!tab) {
3059 		if (!btf_vmlinux) {
3060 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3061 			return -ENOTSUPP;
3062 		}
3063 
3064 		if (!env->prog->jit_requested) {
3065 			verbose(env, "JIT is required for calling kernel function\n");
3066 			return -ENOTSUPP;
3067 		}
3068 
3069 		if (!bpf_jit_supports_kfunc_call()) {
3070 			verbose(env, "JIT does not support calling kernel function\n");
3071 			return -ENOTSUPP;
3072 		}
3073 
3074 		if (!env->prog->gpl_compatible) {
3075 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3076 			return -EINVAL;
3077 		}
3078 
3079 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
3080 		if (!tab)
3081 			return -ENOMEM;
3082 		prog_aux->kfunc_tab = tab;
3083 	}
3084 
3085 	env->prog->jit_required = 1;
3086 
3087 	/* func_id == 0 is always invalid, but instead of returning an error, be
3088 	 * conservative and wait until the code elimination pass before returning
3089 	 * error, so that invalid calls that get pruned out can be in BPF programs
3090 	 * loaded from userspace.  It is also required that offset be untouched
3091 	 * for such calls.
3092 	 */
3093 	if (!func_id && !offset)
3094 		return 0;
3095 
3096 	if (!btf_tab && offset) {
3097 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
3098 		if (!btf_tab)
3099 			return -ENOMEM;
3100 		prog_aux->kfunc_btf_tab = btf_tab;
3101 	}
3102 
3103 	if (find_kfunc_desc(env->prog, func_id, offset))
3104 		return 0;
3105 
3106 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
3107 		verbose(env, "too many different kernel function calls\n");
3108 		return -E2BIG;
3109 	}
3110 	if (tab->nr_descs != tab->nr_base_descs) {
3111 		verifier_bug(env, "unexpected specialized func desc found (%d descs, %d base descs)",
3112 			     tab->nr_descs, tab->nr_base_descs);
3113 		return -EFAULT;
3114 	}
3115 
3116 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
3117 	if (err)
3118 		return err;
3119 
3120 	addr = kallsyms_lookup_name(kfunc.name);
3121 	if (!addr) {
3122 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
3123 		return -EINVAL;
3124 	}
3125 
3126 	if (bpf_dev_bound_kfunc_id(func_id)) {
3127 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3128 		if (err)
3129 			return err;
3130 	}
3131 
3132 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
3133 	if (err)
3134 		return err;
3135 	if (func_model.ret_size > 8) {
3136 		if (kfunc.flags && (*kfunc.flags & KF_FASTCALL)) {
3137 			verbose(env, "kfunc %s with >8-byte return is not supported with KF_FASTCALL\n",
3138 				kfunc.name);
3139 			return -EOPNOTSUPP;
3140 		}
3141 		if (!bpf_jit_supports_kfunc_ret_reg_pair()) {
3142 			verbose(env, "kfunc %s with >8-byte return is not supported by JIT\n",
3143 				kfunc.name);
3144 			return -EOPNOTSUPP;
3145 		}
3146 	}
3147 
3148 	memset(&meta, 0, sizeof(meta));
3149 	meta.btf = kfunc.btf;
3150 	meta.func_id = kfunc.id;
3151 	meta.func_proto = kfunc.proto;
3152 	meta.func_name = kfunc.name;
3153 	meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;
3154 
3155 	tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT);
3156 	if (!tab)
3157 		return -ENOMEM;
3158 	prog_aux->kfunc_tab = tab;
3159 
3160 	desc = &tab->descs[tab->nr_descs];
3161 	memset(desc, 0, sizeof(*desc));
3162 
3163 	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
3164 	if (err)
3165 		return err;
3166 
3167 	desc->func_id = func_id;
3168 	desc->offset = offset;
3169 	desc->addr = addr;
3170 	desc->func_model = func_model;
3171 	tab->nr_descs++;
3172 	tab->nr_base_descs++;
3173 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
3174 	     kfunc_desc_cmp_by_id_off, NULL);
3175 	return 0;
3176 }
3177 
3178 static int add_subprogs(struct bpf_verifier_env *env)
3179 {
3180 	struct bpf_subprog_info *subprog = env->subprog_info;
3181 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3182 	struct bpf_insn *insn = env->prog->insnsi;
3183 	const char *operation, *suggestion;
3184 
3185 	/* Add entry function. */
3186 	ret = add_subprog(env, 0);
3187 	if (ret)
3188 		return ret;
3189 
3190 	for (i = 0; i < insn_cnt; i++, insn++) {
3191 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
3192 			continue;
3193 
3194 		if (!env->bpf_capable) {
3195 			if (bpf_pseudo_func(insn)) {
3196 				operation = "BPF function reference";
3197 				suggestion = "Load this program with the required capability, or avoid BPF function references in unprivileged programs.";
3198 			} else {
3199 				operation = "BPF-to-BPF function call";
3200 				suggestion = "Load this program with the required capability, or avoid BPF-to-BPF function calls in unprivileged programs.";
3201 			}
3202 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3203 			bpf_diag_policy(
3204 				env, i, operation,
3205 				"loading or calling other BPF functions requires CAP_BPF or CAP_SYS_ADMIN",
3206 				suggestion);
3207 			return -EPERM;
3208 		}
3209 
3210 		ret = add_subprog(env, i + insn->imm + 1);
3211 		if (ret < 0)
3212 			return ret;
3213 	}
3214 
3215 	/*
3216 	 * func_info describes all functions of the program. Those that are
3217 	 * referenced only from data, e.g. from a table of functions to be
3218 	 * called via callx, are not seen by the loop above. They are possible
3219 	 * callees that have to be known upfront as well.
3220 	 */
3221 	if (env->bpf_capable) {
3222 		struct bpf_prog_aux *aux = env->prog->aux;
3223 
3224 		for (i = 1; i < aux->func_info_cnt; i++) {
3225 			ret = add_subprog(env, aux->func_info[i].insn_off);
3226 			if (ret < 0)
3227 				return ret;
3228 		}
3229 	}
3230 
3231 	ret = bpf_find_exception_callback_insn_off(env);
3232 	if (ret < 0)
3233 		return ret;
3234 	ex_cb_insn = ret;
3235 
3236 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3237 	 * marked using BTF decl tag to serve as the exception callback.
3238 	 */
3239 	if (ex_cb_insn) {
3240 		ret = add_subprog(env, ex_cb_insn);
3241 		if (ret < 0)
3242 			return ret;
3243 		for (i = 1; i < env->subprog_cnt; i++) {
3244 			if (env->subprog_info[i].start != ex_cb_insn)
3245 				continue;
3246 			env->exception_callback_subprog = i;
3247 			bpf_mark_subprog_exc_cb(env, i);
3248 			break;
3249 		}
3250 	}
3251 
3252 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3253 	 * logic. 'subprog_cnt' should not be increased.
3254 	 */
3255 	subprog[env->subprog_cnt].start = insn_cnt;
3256 
3257 	if (env->log.level & BPF_LOG_LEVEL2)
3258 		for (i = 0; i < env->subprog_cnt; i++)
3259 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3260 
3261 	return 0;
3262 }
3263 
3264 static int add_kfuncs(struct bpf_verifier_env *env)
3265 {
3266 	struct bpf_insn *insn = env->prog->insnsi;
3267 	int i, ret, insn_cnt = env->prog->len;
3268 
3269 	for (i = 0; i < insn_cnt; i++, insn++) {
3270 		if (!bpf_pseudo_kfunc_call(insn))
3271 			continue;
3272 
3273 		if (!env->bpf_capable) {
3274 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3275 			bpf_diag_policy(
3276 				env, i, "kernel function call",
3277 				"calling kernel functions requires CAP_BPF or CAP_SYS_ADMIN",
3278 				"Load this program with the required capability, or avoid kernel function calls in unprivileged programs.");
3279 			return -EPERM;
3280 		}
3281 
3282 		ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
3283 		if (ret < 0)
3284 			return ret;
3285 	}
3286 
3287 	return 0;
3288 }
3289 
3290 static void find_subprog_properties(struct bpf_verifier_env *env)
3291 {
3292 	struct bpf_subprog_info *subprog = env->subprog_info;
3293 	struct bpf_insn *insn = env->prog->insnsi;
3294 	int cur_subprog;
3295 
3296 	for (cur_subprog = 0; cur_subprog < env->subprog_cnt; cur_subprog++) {
3297 		int i;
3298 
3299 		for (i = subprog[cur_subprog].start;
3300 		     i < subprog[cur_subprog + 1].start; i++) {
3301 			u8 code = insn[i].code;
3302 
3303 			if (code == (BPF_JMP | BPF_CALL) &&
3304 			    insn[i].src_reg == 0 &&
3305 			    insn[i].imm == BPF_FUNC_tail_call) {
3306 				subprog[cur_subprog].has_tail_call = true;
3307 				subprog[cur_subprog].tail_call_reachable = true;
3308 			}
3309 			if (BPF_CLASS(code) == BPF_LD &&
3310 			    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3311 				subprog[cur_subprog].has_ld_abs = true;
3312 			if (bpf_is_callx(&insn[i]))
3313 				env->has_callx = true;
3314 		}
3315 	}
3316 }
3317 
3318 static int check_subprogs(struct bpf_verifier_env *env)
3319 {
3320 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3321 	struct bpf_subprog_info *subprog = env->subprog_info;
3322 	struct bpf_insn *insn = env->prog->insnsi;
3323 	int insn_cnt = env->prog->len;
3324 
3325 	/* now check that all jumps are within the same subprog */
3326 	subprog_start = subprog[cur_subprog].start;
3327 	subprog_end = subprog[cur_subprog + 1].start;
3328 	for (i = 0; i < insn_cnt; i++) {
3329 		u8 code = insn[i].code;
3330 
3331 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3332 			goto next;
3333 		if (BPF_OP(code) == BPF_CALL)
3334 			goto next;
3335 		if (BPF_OP(code) == BPF_EXIT) {
3336 			subprog[cur_subprog].exit_idx = i;
3337 			goto next;
3338 		}
3339 		if (insn_is_gotox(&insn[i]))
3340 			goto next;
3341 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3342 		if (off < subprog_start || off >= subprog_end) {
3343 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3344 			bpf_diag_program_structure(
3345 				env, i, "jump out of range",
3346 				"Keep branch targets within the same subprogram, or use an explicit subprogram call.",
3347 				"Instruction %d jumps to instruction %d, but subprogram %d only contains instructions %d through %d. "
3348 				"A branch target must stay inside the same subprogram.",
3349 				i, off, cur_subprog, subprog_start, subprog_end - 1);
3350 			return -EINVAL;
3351 		}
3352 next:
3353 		if (i == subprog_end - 1) {
3354 			/*
3355 			 * To avoid fall-through from one subprog into another,
3356 			 * the last insn of the subprog should be either exit
3357 			 * or unconditional jump back or bpf_throw call.
3358 			 */
3359 			if (code != (BPF_JMP | BPF_EXIT) &&
3360 			    code != (BPF_JMP32 | BPF_JA) &&
3361 			    code != (BPF_JMP | BPF_JA) &&
3362 			    !insn_is_gotox(&insn[i])) {
3363 				verbose(env, "last insn is not an exit or jmp\n");
3364 				bpf_diag_program_structure(
3365 					env, i, "subprogram can fall through",
3366 					"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
3367 					"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
3368 					cur_subprog, i);
3369 				return -EINVAL;
3370 			}
3371 			subprog_start = subprog_end;
3372 			cur_subprog++;
3373 			if (cur_subprog < env->subprog_cnt)
3374 				subprog_end = subprog[cur_subprog + 1].start;
3375 		}
3376 	}
3377 	return 0;
3378 }
3379 
3380 /*
3381  * The callee of callx is known to the main verification pass only, which
3382  * records the 'caller' -> 'callee' edge of the call graph for the checks
3383  * that follow it: absence of recursion and the maximum stack depth.
3384  */
3385 static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee)
3386 {
3387 	u32 cnt = env->subprog_cnt;
3388 
3389 	if (!env->callx_edges) {
3390 		env->callx_edges = kvcalloc(BITS_TO_LONGS(cnt * cnt), sizeof(long),
3391 					    GFP_KERNEL_ACCOUNT);
3392 		if (!env->callx_edges)
3393 			return -ENOMEM;
3394 	}
3395 	__set_bit(caller * cnt + callee, env->callx_edges);
3396 	return 0;
3397 }
3398 
3399 /*
3400  * Return the first subprog with the number >= 'from' that 'caller' calls
3401  * via callx, or -1 when there is none.
3402  */
3403 static int next_callx_callee(struct bpf_verifier_env *env, int caller, int from)
3404 {
3405 	u32 cnt = env->subprog_cnt;
3406 	unsigned long bit, end = (caller + 1) * cnt;
3407 
3408 	if (!env->callx_edges || from >= cnt)
3409 		return -1;
3410 	bit = find_next_bit(env->callx_edges, end, caller * cnt + from);
3411 	return bit < end ? bit - caller * cnt : -1;
3412 }
3413 
3414 /*
3415  * Sort subprogs in topological order so that leaf subprogs come first and
3416  * their callers come later. This is a DFS post-order traversal of the call
3417  * graph. Scan only reachable instructions (those in the computed postorder) of
3418  * the current subprog to discover callees (direct subprogs and sync
3419  * callbacks).
3420  *
3421  * The callees of callx are not known before the main verification pass.
3422  * When callx is used the sort is repeated after it with the recorded callx
3423  * edges added to the call graph to reject recursion through indirect calls.
3424  */
3425 static int sort_subprogs_topo(struct bpf_verifier_env *env)
3426 {
3427 	struct bpf_subprog_info *si = env->subprog_info;
3428 	int *insn_postorder = env->cfg.insn_postorder;
3429 	struct bpf_insn *insn = env->prog->insnsi;
3430 	int cnt = env->subprog_cnt;
3431 	int *dfs_stack = NULL;
3432 	int top = 0, order = 0;
3433 	int i, ret = 0;
3434 	u8 *color = NULL;
3435 
3436 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
3437 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
3438 	if (!color || !dfs_stack) {
3439 		ret = -ENOMEM;
3440 		goto out;
3441 	}
3442 
3443 	/*
3444 	 * DFS post-order traversal.
3445 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
3446 	 */
3447 	for (i = 0; i < cnt; i++) {
3448 		if (color[i])
3449 			continue;
3450 		color[i] = 1;
3451 		dfs_stack[top++] = i;
3452 
3453 		while (top > 0) {
3454 			int cur = dfs_stack[top - 1];
3455 			int po_start = si[cur].postorder_start;
3456 			int po_end = si[cur + 1].postorder_start;
3457 			bool pushed = false;
3458 			int j;
3459 
3460 			for (j = po_start; j < po_end; j++) {
3461 				int idx = insn_postorder[j];
3462 				int callee;
3463 
3464 				if (bpf_is_callx(&insn[idx])) {
3465 					/* find a callee that is not explored yet */
3466 					callee = -1;
3467 					do {
3468 						callee = next_callx_callee(env, cur, callee + 1);
3469 					} while (callee >= 0 && color[callee] == 2);
3470 					if (callee < 0)
3471 						continue;
3472 				} else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) {
3473 					callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
3474 					if (callee < 0) {
3475 						ret = -EFAULT;
3476 						goto out;
3477 					}
3478 				} else {
3479 					continue;
3480 				}
3481 				if (color[callee] == 2)
3482 					continue;
3483 				if (color[callee] == 1) {
3484 					if (bpf_pseudo_func(&insn[idx]))
3485 						continue;
3486 					verbose(env, "recursive call from %s() to %s()\n",
3487 						bpf_subprog_name(env, cur),
3488 						bpf_subprog_name(env, callee));
3489 					bpf_diag_program_structure(
3490 						env, idx, "recursive subprogram call",
3491 						"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
3492 						"This bpf2bpf call would make the subprogram call graph recursive. "
3493 						"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
3494 					ret = -EINVAL;
3495 					goto out;
3496 				}
3497 				color[callee] = 1;
3498 				dfs_stack[top++] = callee;
3499 				pushed = true;
3500 				break;
3501 			}
3502 
3503 			if (!pushed) {
3504 				color[cur] = 2;
3505 				env->subprog_topo_order[order++] = cur;
3506 				top--;
3507 			}
3508 		}
3509 	}
3510 
3511 	if (env->log.level & BPF_LOG_LEVEL2)
3512 		for (i = 0; i < cnt; i++)
3513 			verbose(env, "topo_order[%d] = %s\n",
3514 				i, bpf_subprog_name(env, env->subprog_topo_order[i]));
3515 out:
3516 	kvfree(dfs_stack);
3517 	kvfree(color);
3518 	return ret;
3519 }
3520 
3521 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
3522 				       int spi, int nr_slots)
3523 {
3524 	int i;
3525 
3526 	for (i = 0; i < nr_slots; i++)
3527 		mark_stack_slot_scratched(env, spi - i);
3528 }
3529 
3530 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3531 			   enum bpf_reg_arg_type t)
3532 {
3533 	struct bpf_reg_state *reg;
3534 
3535 	mark_reg_scratched(env, regno);
3536 
3537 	reg = &regs[regno];
3538 	if (t == SRC_OP) {
3539 		/* check whether register used as source operand can be read */
3540 		if (reg->type == NOT_INIT) {
3541 			verbose(env, "R%d !read_ok\n", regno);
3542 			bpf_diag_unreadable_reg(env, env->insn_idx, regno);
3543 			return -EACCES;
3544 		}
3545 		/* We don't need to worry about FP liveness because it's read-only */
3546 		if (regno == BPF_REG_FP)
3547 			return 0;
3548 
3549 		return 0;
3550 	} else {
3551 		/* check whether register used as dest operand can be written to */
3552 		if (regno == BPF_REG_FP) {
3553 			verbose(env, "frame pointer is read only\n");
3554 			return -EACCES;
3555 		}
3556 		if (t == DST_OP)
3557 			mark_reg_unknown(env, regs, regno);
3558 	}
3559 	return 0;
3560 }
3561 
3562 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3563 			 enum bpf_reg_arg_type t)
3564 {
3565 	struct bpf_verifier_state *vstate = env->cur_state;
3566 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3567 
3568 	return __check_reg_arg(env, state->regs, regno, t);
3569 }
3570 
3571 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3572 {
3573 	env->insn_aux_data[idx].indirect_target = true;
3574 }
3575 
3576 static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)
3577 {
3578 	env->insn_aux_data[idx].non_stack_access = true;
3579 }
3580 
3581 /* Layout of one packed linked register in the jump history, see linked_regs_pack() */
3582 #define LR_FRAMENO_BITS	4
3583 #define LR_INDEX_BITS	11
3584 #define LR_FRAMENO_MASK	((1u << LR_FRAMENO_BITS) - 1)
3585 #define LR_IS_REG	BIT(LR_FRAMENO_BITS)
3586 #define LR_INDEX_OFF	(LR_FRAMENO_BITS + 1)
3587 #define LR_INDEX_MASK	((1u << LR_INDEX_BITS) - 1)
3588 #define LINKED_REGS_MAX	BPF_LINKED_REGS_MAX
3589 
3590 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3591 static_assert(MAX_BPF_REG <= (1 << LR_INDEX_BITS));
3592 static_assert(MAX_BPF_STACK_SLOTS <= (1 << LR_INDEX_BITS));
3593 static_assert(LR_INDEX_OFF + LR_INDEX_BITS <= 16);
3594 
3595 struct linked_reg {
3596 	u8 frameno;
3597 	union {
3598 		u16 spi;
3599 		u16 regno;
3600 	};
3601 	bool is_reg;
3602 };
3603 
3604 struct linked_regs {
3605 	int cnt;
3606 	struct linked_reg entries[LINKED_REGS_MAX];
3607 };
3608 
3609 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3610 {
3611 	if (s->cnt < LINKED_REGS_MAX)
3612 		return &s->entries[s->cnt++];
3613 
3614 	return NULL;
3615 }
3616 
3617 /*
3618  * Pack linked registers for a jump history entry, one u16 each:
3619  * - 4 bits frameno
3620  * - 1 bit  is_reg
3621  * - 11 bits register or stack slot index
3622  */
3623 static void linked_regs_pack(const struct linked_regs *s, u16 *packed)
3624 {
3625 	int i;
3626 
3627 	for (i = 0; i < s->cnt; ++i) {
3628 		const struct linked_reg *e = &s->entries[i];
3629 
3630 		packed[i] = e->frameno | (e->is_reg ? LR_IS_REG : 0) | (e->spi << LR_INDEX_OFF);
3631 	}
3632 }
3633 
3634 static void linked_regs_unpack(const struct bpf_jmp_history_entry *hist, struct linked_regs *s)
3635 {
3636 	int i;
3637 
3638 	s->cnt = hist->linked_regs_cnt;
3639 	for (i = 0; i < s->cnt; ++i) {
3640 		struct linked_reg *e = &s->entries[i];
3641 		u16 packed = hist->linked_regs[i];
3642 
3643 		e->frameno = packed & LR_FRAMENO_MASK;
3644 		e->is_reg  = packed & LR_IS_REG;
3645 		e->spi     = (packed >> LR_INDEX_OFF) & LR_INDEX_MASK;
3646 	}
3647 }
3648 
3649 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3650 {
3651 	const struct btf_type *func;
3652 	struct btf *desc_btf;
3653 
3654 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3655 		return NULL;
3656 
3657 	desc_btf = find_kfunc_desc_btf_cached(data, insn->off);
3658 	if (IS_ERR(desc_btf))
3659 		return "<error>";
3660 
3661 	func = btf_type_by_id(desc_btf, insn->imm);
3662 	if (!func || !btf_type_is_func(func))
3663 		return "<error>";
3664 	return btf_name_by_offset(desc_btf, func->name_off);
3665 }
3666 
3667 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3668 {
3669 	const struct bpf_insn_cbs cbs = {
3670 		.cb_call	= bpf_disasm_kfunc_name,
3671 		.cb_print	= verbose,
3672 		.private_data	= env,
3673 	};
3674 
3675 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3676 }
3677 
3678 /* If any register R in hist->linked_regs is marked as precise in bt,
3679  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3680  */
3681 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3682 {
3683 	struct linked_regs linked_regs;
3684 	bool some_precise = false;
3685 	int i;
3686 
3687 	if (!hist || !hist->linked_regs_cnt)
3688 		return;
3689 
3690 	linked_regs_unpack(hist, &linked_regs);
3691 	for (i = 0; i < linked_regs.cnt; ++i) {
3692 		struct linked_reg *e = &linked_regs.entries[i];
3693 
3694 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3695 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3696 			some_precise = true;
3697 			break;
3698 		}
3699 	}
3700 
3701 	if (!some_precise)
3702 		return;
3703 
3704 	for (i = 0; i < linked_regs.cnt; ++i) {
3705 		struct linked_reg *e = &linked_regs.entries[i];
3706 
3707 		if (e->is_reg)
3708 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3709 		else
3710 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3711 	}
3712 }
3713 
3714 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3715 {
3716 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3717 }
3718 
3719 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3720  * desired reg and stack masks across all relevant frames
3721  */
3722 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3723 				      struct bpf_verifier_state *starting_state)
3724 {
3725 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3726 }
3727 
3728 /* check if register is a constant scalar value */
3729 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3730 {
3731 	return reg->type == SCALAR_VALUE &&
3732 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3733 }
3734 
3735 /* assuming is_reg_const() is true, return constant value of a register */
3736 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3737 {
3738 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3739 }
3740 
3741 static bool is_pointer_regtype(enum bpf_reg_type type)
3742 {
3743 	return type != SCALAR_VALUE && type != NOT_INIT;
3744 }
3745 
3746 static bool __is_pointer_value(bool allow_ptr_leaks,
3747 			       const struct bpf_reg_state *reg)
3748 {
3749 	if (allow_ptr_leaks)
3750 		return false;
3751 
3752 	return is_pointer_regtype(reg->type);
3753 }
3754 
3755 static void clear_scalar_id(struct bpf_reg_state *reg)
3756 {
3757 	reg->id = 0;
3758 	reg->delta = 0;
3759 }
3760 
3761 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3762 					struct bpf_reg_state *src_reg)
3763 {
3764 	if (src_reg->type != SCALAR_VALUE)
3765 		return;
3766 	/*
3767 	 * The verifier is processing rX = rY insn and
3768 	 * rY->id has special linked register already.
3769 	 * Cleared it, since multiple rX += const are not supported.
3770 	 */
3771 	if (src_reg->id & BPF_ADD_CONST)
3772 		clear_scalar_id(src_reg);
3773 	/*
3774 	 * Ensure that src_reg has a valid ID that will be copied to
3775 	 * dst_reg and then will be used by sync_linked_regs() to
3776 	 * propagate min/max range.
3777 	 */
3778 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3779 		src_reg->id = ++env->id_gen;
3780 }
3781 
3782 static void save_register_state(struct bpf_verifier_env *env,
3783 				struct bpf_func_state *state,
3784 				int spi, struct bpf_reg_state *reg,
3785 				int size)
3786 {
3787 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3788 	int i;
3789 
3790 	bpf_diag_mod_begin(env, &slot->spilled_ptr, reg, BPF_DIAG_MOD_SPILL);
3791 	slot->spilled_ptr = *reg;
3792 
3793 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3794 		slot->slot_type[i - 1] = STACK_SPILL;
3795 
3796 	/* size < 8 bytes spill */
3797 	for (; i; i--)
3798 		mark_stack_slot_misc(env, &slot->slot_type[i - 1]);
3799 
3800 	bpf_diag_mod_end(env);
3801 }
3802 
3803 static bool is_bpf_st_mem(struct bpf_insn *insn)
3804 {
3805 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3806 }
3807 
3808 static int get_reg_width(struct bpf_reg_state *reg)
3809 {
3810 	return fls64(reg_umax(reg));
3811 }
3812 
3813 /* See comment for mark_fastcall_pattern_for_call() */
3814 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3815 					  struct bpf_func_state *state, int insn_idx, int off)
3816 {
3817 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3818 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3819 	int i;
3820 
3821 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3822 		return;
3823 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3824 	 * from something that is not a part of the fastcall pattern,
3825 	 * disable fastcall rewrites for current subprogram by setting
3826 	 * fastcall_stack_off to a value smaller than any possible offset.
3827 	 */
3828 	subprog->fastcall_stack_off = S16_MIN;
3829 	/* reset fastcall aux flags within subprogram,
3830 	 * happens at most once per subprogram
3831 	 */
3832 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3833 		aux[i].fastcall_spills_num = 0;
3834 		aux[i].fastcall_pattern = 0;
3835 	}
3836 }
3837 
3838 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3839 {
3840 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3841 	int i;
3842 
3843 	/* regular write of data into stack destroys any spilled ptr */
3844 	slot->spilled_ptr.type = NOT_INIT;
3845 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3846 	if (is_stack_slot_special(slot))
3847 		for (i = 0; i < BPF_REG_SIZE; i++)
3848 			scrub_spilled_slot(&slot->slot_type[i]);
3849 }
3850 
3851 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3852  * stack boundary and alignment are checked in check_mem_access()
3853  */
3854 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3855 				       /* stack frame we're writing to */
3856 				       struct bpf_func_state *state,
3857 				       int off, int size, int value_regno,
3858 				       int insn_idx)
3859 {
3860 	struct bpf_func_state *cur; /* state of the current function */
3861 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3862 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3863 	struct bpf_reg_state *reg = NULL;
3864 	int insn_flags = INSN_F_STACK_ACCESS;
3865 	int hist_spi = spi, hist_frame = state->frameno;
3866 	struct bpf_stack_state *ss = bpf_stack_slot(state, spi);
3867 
3868 	/*
3869 	 * caller checked that off % size == 0 and -env->stack_limit <= off < 0,
3870 	 * so it's aligned access and [off, off + size) are within stack limits
3871 	 */
3872 	if (!env->allow_ptr_leaks &&
3873 	    bpf_is_spilled_reg(ss) &&
3874 	    !bpf_is_spilled_scalar_reg(ss) &&
3875 	    size != BPF_REG_SIZE) {
3876 		const char *reason;
3877 
3878 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3879 		reason = bpf_diag_fmt(env,
3880 				      "This store writes %d bytes at stack offset %d into a stack slot that currently holds a spilled pointer. "
3881 			"Partial writes to spilled pointers are rejected because they can corrupt pointer metadata and leak kernel pointers.",
3882 			size, off);
3883 		bpf_diag_memory(
3884 			env, insn_idx, "stack spill corruption", reason,
3885 			"Write the full 8-byte spilled pointer slot, or use a separate stack slot for scalar data before overwriting only part of it.");
3886 		return -EACCES;
3887 	}
3888 
3889 	cur = env->cur_state->frame[env->cur_state->curframe];
3890 	if (value_regno >= 0)
3891 		reg = &cur->regs[value_regno];
3892 	if (!env->bypass_spec_v4) {
3893 		bool sanitize = reg && is_pointer_regtype(reg->type);
3894 
3895 		for (i = 0; i < size; i++) {
3896 			u8 type = ss->slot_type[(slot - i) %
3897 							      BPF_REG_SIZE];
3898 
3899 			if (type != STACK_MISC && type != STACK_ZERO) {
3900 				sanitize = true;
3901 				break;
3902 			}
3903 		}
3904 
3905 		if (sanitize)
3906 			env->insn_aux_data[insn_idx].nospec_result = true;
3907 	}
3908 
3909 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3910 	if (err)
3911 		return err;
3912 
3913 	mark_stack_slot_scratched(env, spi);
3914 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3915 		bool reg_value_fits;
3916 
3917 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3918 		/* Make sure that reg had an ID to build a relation on spill. */
3919 		if (reg_value_fits)
3920 			assign_scalar_id_before_mov(env, reg);
3921 		save_register_state(env, state, spi, reg, size);
3922 		/* Break the relation on a narrowing spill. */
3923 		if (!reg_value_fits)
3924 			clear_scalar_id(&ss->spilled_ptr);
3925 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3926 		   env->bpf_capable) {
3927 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3928 
3929 		memset(tmp_reg, 0, sizeof(*tmp_reg));
3930 		__mark_reg_known(tmp_reg, insn->imm);
3931 		tmp_reg->type = SCALAR_VALUE;
3932 		save_register_state(env, state, spi, tmp_reg, size);
3933 	} else if (reg && is_pointer_regtype(reg->type)) {
3934 		/* register containing pointer is being spilled into stack */
3935 		if (size != BPF_REG_SIZE) {
3936 			verbose_linfo(env, insn_idx, "; ");
3937 			verbose(env, "invalid size of register spill\n");
3938 			return -EACCES;
3939 		}
3940 		if (state != cur && reg->type == PTR_TO_STACK) {
3941 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3942 			return -EINVAL;
3943 		}
3944 		save_register_state(env, state, spi, reg, size);
3945 	} else {
3946 		u8 type = STACK_MISC;
3947 
3948 		if (bpf_is_spilled_reg(ss))
3949 			bpf_diag_record_scrub(env, &ss->spilled_ptr,
3950 					      BPF_DIAG_MOD_WRITE);
3951 		scrub_special_slot(state, spi);
3952 
3953 		/* when we zero initialize stack slots mark them as such */
3954 		if ((reg && bpf_register_is_null(reg)) ||
3955 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3956 			/* STACK_ZERO case happened because register spill
3957 			 * wasn't properly aligned at the stack slot boundary,
3958 			 * so it's not a register spill anymore; force
3959 			 * originating register to be precise to make
3960 			 * STACK_ZERO correct for subsequent states
3961 			 */
3962 			err = mark_chain_precision(env, value_regno);
3963 			if (err)
3964 				return err;
3965 			type = STACK_ZERO;
3966 		}
3967 
3968 		/* Mark slots affected by this stack write. */
3969 		for (i = 0; i < size; i++)
3970 			ss->slot_type[(slot - i) % BPF_REG_SIZE] = type;
3971 		insn_flags = 0; /* not a register spill */
3972 	}
3973 
3974 	if (insn_flags)
3975 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3976 					    hist_spi, hist_frame, NULL, 0);
3977 	return 0;
3978 }
3979 
3980 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
3981  * known to contain a variable offset.
3982  * This function checks whether the write is permitted and conservatively
3983  * tracks the effects of the write, considering that each stack slot in the
3984  * dynamic range is potentially written to.
3985  *
3986  * 'value_regno' can be -1, meaning that an unknown value is being written to
3987  * the stack.
3988  *
3989  * Spilled pointers in range are not marked as written because we don't know
3990  * what's going to be actually written. This means that read propagation for
3991  * future reads cannot be terminated by this write.
3992  *
3993  * For privileged programs, uninitialized stack slots are considered
3994  * initialized by this write (even though we don't know exactly what offsets
3995  * are going to be written to). The idea is that we don't want the verifier to
3996  * reject future reads that access slots written to through variable offsets.
3997  */
3998 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3999 				     /* func where register points to */
4000 				     struct bpf_func_state *state,
4001 				     struct bpf_reg_state *ptr_reg, int off, int size,
4002 				     int value_regno, int insn_idx)
4003 {
4004 	struct bpf_func_state *cur; /* state of the current function */
4005 	int min_off, max_off;
4006 	int i, err;
4007 	struct bpf_reg_state *value_reg = NULL;
4008 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4009 	bool writing_zero = false;
4010 	/* set if the fact that we're writing a zero is used to let any
4011 	 * stack slots remain STACK_ZERO
4012 	 */
4013 	bool zero_used = false;
4014 
4015 	cur = env->cur_state->frame[env->cur_state->curframe];
4016 	min_off = reg_smin(ptr_reg) + off;
4017 	max_off = reg_smax(ptr_reg) + off + size;
4018 	if (value_regno >= 0)
4019 		value_reg = &cur->regs[value_regno];
4020 	if ((value_reg && bpf_register_is_null(value_reg)) ||
4021 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4022 		writing_zero = true;
4023 
4024 	err = destroy_dynptrs_in_stack_slots(env, state, bpf_get_spi(max_off - 1),
4025 					     bpf_get_spi(min_off));
4026 	if (err)
4027 		return err;
4028 
4029 	/* Variable offset writes destroy any spilled pointers in range. */
4030 	for (i = min_off; i < max_off; i++) {
4031 		struct bpf_stack_state *ss;
4032 		u8 new_type, *stype;
4033 		int slot, spi;
4034 
4035 		slot = -i - 1;
4036 		spi = slot / BPF_REG_SIZE;
4037 		ss = bpf_stack_slot(state, spi);
4038 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
4039 		mark_stack_slot_scratched(env, spi);
4040 
4041 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4042 			/* Reject the write if range we may write to has not
4043 			 * been initialized beforehand. If we didn't reject
4044 			 * here, the ptr status would be erased below (even
4045 			 * though not all slots are actually overwritten),
4046 			 * possibly opening the door to leaks.
4047 			 *
4048 			 * We do however catch STACK_INVALID case below, and
4049 			 * only allow reading possibly uninitialized memory
4050 			 * later for CAP_PERFMON, as the write may not happen to
4051 			 * that slot.
4052 			 */
4053 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4054 				insn_idx, i);
4055 			return -EINVAL;
4056 		}
4057 
4058 		/* If writing_zero and the spi slot contains a spill of value 0,
4059 		 * maintain the spill type.
4060 		 */
4061 		if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) {
4062 			struct bpf_reg_state *spill_reg = &ss->spilled_ptr;
4063 
4064 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4065 				zero_used = true;
4066 				continue;
4067 			}
4068 		}
4069 
4070 		/*
4071 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
4072 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
4073 		 * and valid program is rejected by check_stack_read_fixed_off()
4074 		 * with obscure "invalid size of register fill" message.
4075 		 */
4076 		scrub_special_slot(state, spi);
4077 
4078 		/* Update the slot type. */
4079 		new_type = STACK_MISC;
4080 		if (writing_zero && *stype == STACK_ZERO) {
4081 			new_type = STACK_ZERO;
4082 			zero_used = true;
4083 		}
4084 		/* If the slot is STACK_INVALID, we check whether it's OK to
4085 		 * pretend that it will be initialized by this write. The slot
4086 		 * might not actually be written to, and so if we mark it as
4087 		 * initialized future reads might leak uninitialized memory.
4088 		 * For privileged programs, we will accept such reads to slots
4089 		 * that may or may not be written because, if we're reject
4090 		 * them, the error would be too confusing.
4091 		 * Conservatively, treat STACK_POISON in a similar way.
4092 		 */
4093 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
4094 		    !env->allow_uninit_stack) {
4095 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4096 					insn_idx, i);
4097 			return -EINVAL;
4098 		}
4099 		*stype = new_type;
4100 	}
4101 	if (zero_used) {
4102 		/* backtracking doesn't work for STACK_ZERO yet. */
4103 		err = mark_chain_precision(env, value_regno);
4104 		if (err)
4105 			return err;
4106 	}
4107 	bpf_diag_record_scrub_stack(env, state, min_off, max_off,
4108 				    BPF_DIAG_MOD_VAR_WRITE);
4109 	return 0;
4110 }
4111 
4112 /* When register 'dst_regno' is assigned some values from stack[min_off,
4113  * max_off), we set the register's type according to the types of the
4114  * respective stack slots. If all the stack values are known to be zeros, then
4115  * so is the destination reg. Otherwise, the register is considered to be
4116  * SCALAR. This function does not deal with register filling; the caller must
4117  * ensure that all spilled registers in the stack range have been marked as
4118  * read.
4119  *
4120  * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered
4121  * zero bytes. In that case, mark the contributing stack slots precise so
4122  * pruning cannot reuse a zero-spill state for a later non-zero spill state.
4123  *
4124  * Returns an error if precision backtracking fails.
4125  */
4126 static int mark_reg_stack_read(struct bpf_verifier_env *env,
4127 			       /* func where src register points to */
4128 			       struct bpf_func_state *ptr_state,
4129 			       int min_off, int max_off, int dst_regno)
4130 {
4131 	struct bpf_verifier_state *vstate = env->cur_state;
4132 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4133 	int i, slot, spi;
4134 	u8 *stype;
4135 	int zeros = 0, zero_spills = 0;
4136 
4137 	for (i = min_off; i < max_off; i++) {
4138 		slot = -i - 1;
4139 		spi = slot / BPF_REG_SIZE;
4140 		mark_stack_slot_scratched(env, spi);
4141 		stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4142 		if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) {
4143 			zeros++;
4144 			continue;
4145 		}
4146 		if (stype[slot % BPF_REG_SIZE] == STACK_SPILL &&
4147 		    bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) {
4148 			zero_spills++;
4149 			zeros++;
4150 			continue;
4151 		}
4152 		break;
4153 	}
4154 	if (zeros == max_off - min_off) {
4155 		/* Any access_size read into register is zero extended,
4156 		 * so the whole register == const_zero.
4157 		 */
4158 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4159 		if (zero_spills) {
4160 			for (i = min_off; i < max_off; i++) {
4161 				slot = -i - 1;
4162 				spi = slot / BPF_REG_SIZE;
4163 				stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4164 				if (stype[slot % BPF_REG_SIZE] == STACK_SPILL)
4165 					bpf_bt_set_frame_slot(&env->bt, ptr_state->frameno, spi);
4166 			}
4167 			return mark_chain_precision_batch(env, env->cur_state);
4168 		}
4169 	} else {
4170 		/* have read misc data from the stack */
4171 		mark_reg_unknown(env, state->regs, dst_regno);
4172 	}
4173 
4174 	return 0;
4175 }
4176 
4177 static void bpf_diag_stack_read_invalid(struct bpf_verifier_env *env, int off, int i, int size,
4178 					enum bpf_stack_slot_type type)
4179 {
4180 	const char *problem, *reason, *suggestion, *kind;
4181 
4182 	if (type == STACK_INVALID) {
4183 		reason = bpf_diag_fmt(
4184 			env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range is uninitialized on this path. "
4185 			"Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.",
4186 			size, off, i);
4187 		bpf_diag_memory(
4188 			env, env->insn_idx, "uninitialized stack read", reason,
4189 			"Initialize every byte in the stack range before reading it, adjust the offset and size so the read covers only initialized bytes, "
4190 			"or load with CAP_PERFMON if uninitialized stack reads are intended.");
4191 		return;
4192 	}
4193 
4194 	switch (type) {
4195 	case STACK_DYNPTR:
4196 		kind = "dynptr";
4197 		suggestion = "Use dynptr helpers or kfuncs to access the object represented by the dynptr instead of reading the dynptr state directly.";
4198 		break;
4199 	case STACK_ITER:
4200 		kind = "iterator";
4201 		suggestion = "Use iterator kfuncs to advance or destroy the iterator instead of reading its state directly.";
4202 		break;
4203 	case STACK_IRQ_FLAG:
4204 		kind = "IRQ flag";
4205 		suggestion = "Pass the saved IRQ flag to the matching restore kfunc instead of reading its state directly.";
4206 		break;
4207 	default:
4208 		return;
4209 	}
4210 
4211 	problem = bpf_diag_fmt(env, "direct read of %s stack state", kind);
4212 	reason = bpf_diag_fmt(
4213 		env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range belongs to verifier-managed %s state. "
4214 		"This state has an opaque representation that BPF programs cannot read directly.",
4215 		size, off, i, kind);
4216 	bpf_diag_memory(env, env->insn_idx, problem, reason, suggestion);
4217 }
4218 
4219 /* Read the stack at 'off' and put the results into the register indicated by
4220  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4221  * spilled reg.
4222  *
4223  * 'dst_regno' can be -1, meaning that the read value is not going to a
4224  * register.
4225  *
4226  * The access is assumed to be within the current stack bounds.
4227  */
4228 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4229 				      /* func where src register points to */
4230 				      struct bpf_func_state *reg_state,
4231 				      int off, int size, int dst_regno)
4232 {
4233 	struct bpf_verifier_state *vstate = env->cur_state;
4234 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4235 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4236 	struct bpf_reg_state *reg;
4237 	u8 *stype, type;
4238 	int err;
4239 	int insn_flags = INSN_F_STACK_ACCESS;
4240 	int hist_spi = spi, hist_frame = reg_state->frameno;
4241 	struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi);
4242 
4243 	stype = ss->slot_type;
4244 	reg = &ss->spilled_ptr;
4245 
4246 	mark_stack_slot_scratched(env, spi);
4247 
4248 	/*
4249 	 * Refine the in-progress load record's origin to the source stack slot.
4250 	 */
4251 	if (dst_regno >= 0)
4252 		bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE);
4253 
4254 	if (bpf_is_spilled_reg(ss)) {
4255 		u8 spill_size = bpf_spill_size(ss);
4256 
4257 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4258 			if (reg->type != SCALAR_VALUE) {
4259 				verbose_linfo(env, env->insn_idx, "; ");
4260 				verbose(env, "invalid size of register fill\n");
4261 				return -EACCES;
4262 			}
4263 
4264 			if (size <= spill_size &&
4265 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4266 				if (dst_regno < 0)
4267 					return 0;
4268 
4269 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
4270 				    get_reg_width(reg) <= 32)
4271 					/* Ensure stack slot has an ID to build a relation
4272 					 * with the destination register on fill.
4273 					 */
4274 					assign_scalar_id_before_mov(env, reg);
4275 				state->regs[dst_regno] = *reg;
4276 
4277 				/* Break the relation on a narrowing fill.
4278 				 * coerce_reg_to_size will adjust the boundaries.
4279 				 */
4280 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4281 					clear_scalar_id(&state->regs[dst_regno]);
4282 			} else {
4283 				int spill_cnt = 0, zero_cnt = 0;
4284 
4285 				for (i = 0; i < size; i++) {
4286 					type = stype[(slot - i) % BPF_REG_SIZE];
4287 					if (type == STACK_SPILL) {
4288 						spill_cnt++;
4289 						continue;
4290 					}
4291 					if (type == STACK_MISC)
4292 						continue;
4293 					if (type == STACK_ZERO) {
4294 						zero_cnt++;
4295 						continue;
4296 					}
4297 					if (type == STACK_INVALID && env->allow_uninit_stack)
4298 						continue;
4299 					if (type == STACK_POISON) {
4300 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4301 							off, i, size);
4302 					} else {
4303 						verbose(env, "invalid read from stack off %d+%d size %d\n",
4304 							off, i, size);
4305 						bpf_diag_stack_read_invalid(env, off, i, size, type);
4306 					}
4307 					return -EACCES;
4308 				}
4309 
4310 				if (dst_regno < 0)
4311 					return 0;
4312 
4313 				if (spill_cnt == size &&
4314 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4315 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4316 					/* this IS register fill, so keep insn_flags */
4317 				} else if (zero_cnt == size) {
4318 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4319 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4320 					insn_flags = 0; /* not restoring original register state */
4321 				} else {
4322 					err = mark_reg_stack_read(env, reg_state, off, off + size,
4323 								  dst_regno);
4324 					if (err)
4325 						return err;
4326 					insn_flags = 0; /* not restoring original register state */
4327 				}
4328 			}
4329 		} else if (dst_regno >= 0) {
4330 			/* restore register state from stack */
4331 			if (env->bpf_capable)
4332 				/* Ensure stack slot has an ID to build a relation
4333 				 * with the destination register on fill.
4334 				 */
4335 				assign_scalar_id_before_mov(env, reg);
4336 			state->regs[dst_regno] = *reg;
4337 			/* mark reg as written since spilled pointer state likely
4338 			 * has its liveness marks cleared by is_state_visited()
4339 			 * which resets stack/reg liveness for state transitions
4340 			 */
4341 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4342 			/* If dst_regno==-1, the caller is asking us whether
4343 			 * it is acceptable to use this value as a SCALAR_VALUE
4344 			 * (e.g. for XADD).
4345 			 * We must not allow unprivileged callers to do that
4346 			 * with spilled pointers.
4347 			 */
4348 			verbose(env, "leaking pointer from stack off %d\n",
4349 				off);
4350 			return -EACCES;
4351 		}
4352 	} else {
4353 		for (i = 0; i < size; i++) {
4354 			type = stype[(slot - i) % BPF_REG_SIZE];
4355 			if (type == STACK_MISC)
4356 				continue;
4357 			if (type == STACK_ZERO)
4358 				continue;
4359 			if (type == STACK_INVALID && env->allow_uninit_stack)
4360 				continue;
4361 			if (type == STACK_POISON) {
4362 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4363 					off, i, size);
4364 			} else {
4365 				verbose(env, "invalid read from stack off %d+%d size %d\n",
4366 					off, i, size);
4367 				bpf_diag_stack_read_invalid(env, off, i, size, type);
4368 			}
4369 			return -EACCES;
4370 		}
4371 		if (dst_regno >= 0) {
4372 			err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4373 			if (err)
4374 				return err;
4375 		}
4376 		insn_flags = 0; /* we are not restoring spilled register */
4377 	}
4378 	if (insn_flags)
4379 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4380 					    hist_spi, hist_frame, NULL, 0);
4381 	return 0;
4382 }
4383 
4384 enum bpf_access_src {
4385 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4386 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4387 };
4388 
4389 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4390 					 argno_t argno, int off, int access_size,
4391 					 bool zero_size_allowed,
4392 					 enum bpf_access_type type,
4393 					 struct bpf_call_arg_meta *meta);
4394 
4395 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4396 {
4397 	return cur_regs(env) + regno;
4398 }
4399 
4400 /* Read the stack at 'reg + off' and put the result into the register
4401  * 'dst_regno'.
4402  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
4403  * but not its variable offset.
4404  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4405  *
4406  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4407  * filling registers (i.e. reads of spilled register cannot be detected when
4408  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4409  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
4410  * offset; for a fixed offset check_stack_read_fixed_off should be used
4411  * instead.
4412  */
4413 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4414 				    argno_t ptr_argno, int off, int size, int dst_regno)
4415 {
4416 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
4417 	int err;
4418 	int min_off, max_off;
4419 
4420 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4421 	 */
4422 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
4423 					    false, BPF_READ, NULL);
4424 	if (err)
4425 		return err;
4426 
4427 	min_off = reg_smin(reg) + off;
4428 	max_off = reg_smax(reg) + off;
4429 	err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size,
4430 				  dst_regno);
4431 	if (err)
4432 		return err;
4433 	return 0;
4434 }
4435 
4436 /* check_stack_read dispatches to check_stack_read_fixed_off or
4437  * check_stack_read_var_off.
4438  *
4439  * The caller must ensure that the offset falls within the allocated stack
4440  * bounds.
4441  *
4442  * 'dst_regno' is a register which will receive the value from the stack. It
4443  * can be -1, meaning that the read value is not going to a register.
4444  */
4445 static int check_stack_read(struct bpf_verifier_env *env,
4446 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
4447 			    int dst_regno)
4448 {
4449 	struct bpf_func_state *state = bpf_func(env, reg);
4450 	int err;
4451 	/* Some accesses are only permitted with a static offset. */
4452 	bool var_off = !tnum_is_const(reg->var_off);
4453 
4454 	/* The offset is required to be static when reads don't go to a
4455 	 * register, in order to not leak pointers (see
4456 	 * check_stack_read_fixed_off).
4457 	 */
4458 	if (dst_regno < 0 && var_off) {
4459 		const char *reason;
4460 		char tn_buf[48];
4461 
4462 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4463 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4464 			tn_buf, off, size);
4465 		reason = bpf_diag_fmt(
4466 			env, "The instruction would access the stack through variable offset %s plus fixed offset %d and size %d. "
4467 			"This stack access requires a constant stack offset and a precise initialized range.",
4468 			tn_buf, off, size);
4469 		bpf_diag_memory(
4470 			env, env->insn_idx, "variable-offset stack access", reason,
4471 			"Use a fixed stack offset for the instruction, selecting the target stack slot on separate control-flow paths if necessary.");
4472 		return -EACCES;
4473 	}
4474 	/* Variable offset is prohibited for unprivileged mode for simplicity
4475 	 * since it requires corresponding support in Spectre masking for stack
4476 	 * ALU. See also retrieve_ptr_limit(). The check in
4477 	 * check_stack_access_for_ptr_arithmetic() called by
4478 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4479 	 * with variable offsets, therefore no check is required here. Further,
4480 	 * just checking it here would be insufficient as speculative stack
4481 	 * writes could still lead to unsafe speculative behaviour.
4482 	 */
4483 	if (!var_off) {
4484 		off += reg->var_off.value;
4485 		err = check_stack_read_fixed_off(env, state, off, size,
4486 						 dst_regno);
4487 	} else {
4488 		/* Variable offset stack reads need more conservative handling
4489 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4490 		 * branch.
4491 		 */
4492 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
4493 					       dst_regno);
4494 	}
4495 	return err;
4496 }
4497 
4498 /* check_stack_write dispatches to check_stack_write_fixed_off or
4499  * check_stack_write_var_off.
4500  *
4501  * 'reg' is the register used as a pointer into the stack.
4502  * 'value_regno' is the register whose value we're writing to the stack. It can
4503  * be -1, meaning that we're not writing from a register.
4504  *
4505  * The caller must ensure that the offset falls within the maximum stack size.
4506  */
4507 static int check_stack_write(struct bpf_verifier_env *env,
4508 			     struct bpf_reg_state *reg, int off, int size,
4509 			     int value_regno, int insn_idx)
4510 {
4511 	struct bpf_func_state *state = bpf_func(env, reg);
4512 	int err;
4513 
4514 	if (tnum_is_const(reg->var_off)) {
4515 		off += reg->var_off.value;
4516 		err = check_stack_write_fixed_off(env, state, off, size,
4517 						  value_regno, insn_idx);
4518 	} else {
4519 		/* Variable offset stack reads need more conservative handling
4520 		 * than fixed offset ones.
4521 		 */
4522 		err = check_stack_write_var_off(env, state,
4523 						reg, off, size,
4524 						value_regno, insn_idx);
4525 	}
4526 	return err;
4527 }
4528 
4529 /*
4530  * Write a value to the outgoing stack arg area.
4531  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4532  */
4533 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4534 				 int off, struct bpf_reg_state *value_reg)
4535 {
4536 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4537 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4538 	int spi = -off / BPF_REG_SIZE - 1;
4539 	struct bpf_reg_state *arg;
4540 	int err;
4541 
4542 	if (spi >= max_stack_arg_regs) {
4543 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4544 			off, max_stack_arg_regs);
4545 		return -EINVAL;
4546 	}
4547 
4548 	err = grow_stack_arg_slots(env, state, spi + 1);
4549 	if (err)
4550 		return err;
4551 
4552 	/* Track the max outgoing stack arg slot count. */
4553 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4554 		subprog->max_out_stack_arg_cnt = spi + 1;
4555 
4556 	arg = &state->stack_arg_regs[spi];
4557 	bpf_diag_mod_begin(env, arg, value_reg, BPF_DIAG_MOD_WRITE);
4558 
4559 	if (value_reg) {
4560 		state->stack_arg_regs[spi] = *value_reg;
4561 	} else {
4562 		/* BPF_ST: store immediate, treat as scalar */
4563 		arg->type = SCALAR_VALUE;
4564 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4565 	}
4566 	bpf_diag_mod_end(env);
4567 	state->no_stack_arg_load = true;
4568 	return bpf_push_jmp_history(env, env->cur_state,
4569 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4570 }
4571 
4572 /*
4573  * Read a value from the incoming stack arg area.
4574  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4575  */
4576 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4577 				int off, int dst_regno)
4578 {
4579 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4580 	struct bpf_verifier_state *vstate = env->cur_state;
4581 	int spi = off / BPF_REG_SIZE - 1;
4582 	struct bpf_func_state *caller, *cur;
4583 	struct bpf_reg_state *arg;
4584 
4585 	if (state->no_stack_arg_load) {
4586 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4587 		return -EINVAL;
4588 	}
4589 
4590 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4591 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4592 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4593 		return -EACCES;
4594 	}
4595 
4596 	caller = vstate->frame[vstate->curframe - 1];
4597 	arg = &caller->stack_arg_regs[spi];
4598 	cur = vstate->frame[vstate->curframe];
4599 	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
4600 	cur->regs[dst_regno] = *arg;
4601 	bpf_diag_mod_end(env);
4602 	return bpf_push_jmp_history(env, env->cur_state,
4603 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4604 }
4605 
4606 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4607 {
4608 	struct bpf_func_state *caller = cur_func(env);
4609 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4610 
4611 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4612 	return mark_chain_precision_batch(env, env->cur_state);
4613 }
4614 
4615 static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)
4616 {
4617 	int regno = reg_from_argno(argno);
4618 
4619 	if (regno >= 0)
4620 		return mark_chain_precision(env, regno);
4621 	return mark_stack_arg_precision(env, arg_idx_from_argno(argno));
4622 }
4623 
4624 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4625 				     int nargs, const char *callee_name, const struct btf *btf,
4626 				     const struct btf_param *args)
4627 {
4628 	int i, spi;
4629 
4630 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4631 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4632 		if (spi >= caller->out_stack_arg_cnt ||
4633 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4634 			const char *arg_name = NULL;
4635 
4636 			if (args && args[i].name_off)
4637 				arg_name = btf_name_by_offset(btf, args[i].name_off);
4638 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4639 				nargs, spi + 1);
4640 			bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi,
4641 						  callee_name, arg_name);
4642 			return -EFAULT;
4643 		}
4644 	}
4645 
4646 	return 0;
4647 }
4648 
4649 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4650 					      struct bpf_reg_state *regs, int arg)
4651 {
4652 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4653 		return &regs[arg + 1];
4654 
4655 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4656 }
4657 
4658 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4659 				 int off, int size, enum bpf_access_type type)
4660 {
4661 	struct bpf_map *map = reg->map_ptr;
4662 	u32 cap = bpf_map_flags_to_cap(map);
4663 
4664 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4665 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4666 			map->value_size, reg_smin(reg) + off, size);
4667 		return -EACCES;
4668 	}
4669 
4670 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4671 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4672 			map->value_size, reg_smin(reg) + off, size);
4673 		return -EACCES;
4674 	}
4675 
4676 	return 0;
4677 }
4678 
4679 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4680 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4681 			      int off, int size, u32 mem_size,
4682 			      bool zero_size_allowed)
4683 {
4684 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4685 
4686 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4687 		return 0;
4688 
4689 	switch (reg->type) {
4690 	case PTR_TO_MAP_KEY:
4691 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4692 			mem_size, off, size);
4693 		break;
4694 	case PTR_TO_MAP_VALUE:
4695 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4696 			mem_size, off, size);
4697 		break;
4698 	case PTR_TO_PACKET:
4699 	case PTR_TO_PACKET_META:
4700 	case PTR_TO_PACKET_END:
4701 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4702 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4703 		break;
4704 	case PTR_TO_CTX:
4705 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4706 			mem_size, off, size);
4707 		break;
4708 	case PTR_TO_MEM:
4709 	default:
4710 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4711 			mem_size, off, size);
4712 	}
4713 
4714 	return -EACCES;
4715 }
4716 
4717 /* check read/write into a memory region with possible variable offset */
4718 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4719 				   int off, int size, u32 mem_size,
4720 				   bool zero_size_allowed)
4721 {
4722 	const char *proof = "";
4723 	const char *start;
4724 	s64 max_start, max_end;
4725 	int err;
4726 
4727 	/* We may have adjusted the register pointing to memory region, so we
4728 	 * need to try adding each of min_value and max_value to off
4729 	 * to make sure our theoretical access will be safe.
4730 	 *
4731 	 * The minimum value is only important with signed
4732 	 * comparisons where we can't assume the floor of a
4733 	 * value is 0.  If we are using signed variables for our
4734 	 * index'es we need to make sure that whatever we use
4735 	 * will have a set floor within our range.
4736 	 */
4737 	if (reg_smin(reg) < 0 &&
4738 	    (reg_smin(reg) == S64_MIN ||
4739 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4740 	      reg_smin(reg) + off < 0)) {
4741 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4742 			reg_arg_name(env, argno));
4743 		err = -EACCES;
4744 		if (bpf_diag_enabled(env)) {
4745 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4746 			proof = bpf_diag_fmt(
4747 				env, "the minimal bound for a memory access is a negative value: %s",
4748 				start);
4749 		}
4750 		goto report_error;
4751 	}
4752 
4753 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4754 				 mem_size, zero_size_allowed);
4755 	if (err) {
4756 		verbose(env, "%s min value is outside of the allowed memory range\n",
4757 			reg_arg_name(env, argno));
4758 		if (bpf_diag_enabled(env)) {
4759 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4760 			proof = bpf_diag_fmt(
4761 				env, "the minimal bound for a memory access is %s and is outside of the object of size %u",
4762 				start, mem_size);
4763 		}
4764 		goto report_error;
4765 	}
4766 
4767 	/* If we haven't set a max value then we need to bail since we can't be
4768 	 * sure we won't do bad things.
4769 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4770 	 */
4771 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4772 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4773 			reg_arg_name(env, argno));
4774 		err = -EACCES;
4775 		if (bpf_diag_enabled(env))
4776 			proof = bpf_diag_fmt(
4777 				env, "the maximal bound for a memory access is %llu and exceeds maximum allowed offset of %u",
4778 				reg_umax(reg), BPF_MAX_VAR_OFF);
4779 		goto report_error;
4780 	}
4781 
4782 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4783 				 mem_size, zero_size_allowed);
4784 	if (err) {
4785 		verbose(env, "%s max value is outside of the allowed memory range\n",
4786 			reg_arg_name(env, argno));
4787 		if (bpf_diag_enabled(env)) {
4788 			max_start = (s64)reg_umax(reg) + off;
4789 			max_end = max_start + size;
4790 			proof = bpf_diag_fmt(
4791 				env, "the maximal bound for a memory access is %lld: start %lld + access_size %d, beyond object_size %u",
4792 				max_end, max_start, size, mem_size);
4793 		}
4794 		goto report_error;
4795 	}
4796 
4797 	return 0;
4798 
4799 report_error:
4800 	bpf_diag_mem_bounds(env, env->insn_idx, reg_from_argno(argno),
4801 			    reg_arg_name(env, argno), reg_type_str(env, reg->type), proof,
4802 			    off, size, mem_size, reg);
4803 	return err;
4804 }
4805 
4806 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4807 			       const struct bpf_reg_state *reg, argno_t argno,
4808 			       bool fixed_off_ok)
4809 {
4810 	/* Access to this pointer-typed register or passing it to a helper
4811 	 * is only allowed in its original, unmodified form.
4812 	 */
4813 
4814 	if (!tnum_is_const(reg->var_off)) {
4815 		char tn_buf[48];
4816 
4817 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4818 		verbose(env, "variable %s access var_off=%s disallowed\n",
4819 			reg_type_str(env, reg->type), tn_buf);
4820 		return -EACCES;
4821 	}
4822 
4823 	if (reg_smin(reg) < 0) {
4824 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4825 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4826 		return -EACCES;
4827 	}
4828 
4829 	if (!fixed_off_ok && reg->var_off.value != 0) {
4830 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4831 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4832 		bpf_diag_invalid_deref(env, env->insn_idx, reg_from_argno(argno),
4833 				       reg_arg_name(env, argno), reg,
4834 					      BPF_DIAG_DEREF_MODIFIED_PTR, reg->var_off.value);
4835 		return -EACCES;
4836 	}
4837 
4838 	return 0;
4839 }
4840 
4841 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4842 		             const struct bpf_reg_state *reg, int regno)
4843 {
4844 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4845 }
4846 
4847 static int map_kptr_match_type(struct bpf_verifier_env *env,
4848 			       struct btf_field *kptr_field,
4849 			       struct bpf_reg_state *reg, u32 regno)
4850 {
4851 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4852 	int perm_flags;
4853 	const char *reg_name = "";
4854 
4855 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4856 		goto bad_type;
4857 
4858 	if (btf_is_kernel(reg->btf)) {
4859 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4860 
4861 		/* Only unreferenced case accepts untrusted pointers */
4862 		if (kptr_field->type == BPF_KPTR_UNREF)
4863 			perm_flags |= PTR_UNTRUSTED;
4864 	} else {
4865 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4866 		if (kptr_field->type == BPF_KPTR_PERCPU)
4867 			perm_flags |= MEM_PERCPU;
4868 	}
4869 
4870 	if (type_flag(reg->type) & ~perm_flags)
4871 		goto bad_type;
4872 
4873 	/*
4874 	 * A BPF_KPTR_PERCPU field is read back as MEM_PERCPU, so the value
4875 	 * stored in it must carry the same flag.
4876 	 */
4877 	if ((kptr_field->type == BPF_KPTR_PERCPU) != !!(reg->type & MEM_PERCPU))
4878 		goto bad_type;
4879 
4880 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4881 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4882 
4883 	/* For ref_ptr case, release function check should ensure we get one
4884 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4885 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4886 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4887 	 * reg->id is not needed here.
4888 	 */
4889 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4890 		return -EACCES;
4891 
4892 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4893 	 * we also need to take into account the reg->var_off.
4894 	 *
4895 	 * We want to support cases like:
4896 	 *
4897 	 * struct foo {
4898 	 *         struct bar br;
4899 	 *         struct baz bz;
4900 	 * };
4901 	 *
4902 	 * struct foo *v;
4903 	 * v = func();	      // PTR_TO_BTF_ID
4904 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
4905 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
4906 	 *                    // first member type of struct after comparison fails
4907 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
4908 	 *                    // to match type
4909 	 *
4910 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
4911 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4912 	 * the struct to match type against first member of struct, i.e. reject
4913 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4914 	 * strict mode to true for type match.
4915 	 */
4916 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
4917 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4918 				  kptr_field->type != BPF_KPTR_UNREF,
4919 				  !type_is_alloc(reg->type)))
4920 		goto bad_type;
4921 	return 0;
4922 bad_type:
4923 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4924 		reg_type_str(env, reg->type), reg_name);
4925 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4926 	if (kptr_field->type == BPF_KPTR_UNREF)
4927 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4928 			targ_name);
4929 	else
4930 		verbose(env, "\n");
4931 	return -EINVAL;
4932 }
4933 
4934 static bool in_sleepable(struct bpf_verifier_env *env)
4935 {
4936 	return env->cur_state->in_sleepable;
4937 }
4938 
4939 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4940  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4941  */
4942 static bool in_rcu_cs(struct bpf_verifier_env *env)
4943 {
4944 	return env->cur_state->active_rcu_locks ||
4945 	       env->cur_state->active_preempt_locks ||
4946 	       env->cur_state->active_locks ||
4947 	       env->cur_state->active_irq_id ||
4948 	       !in_sleepable(env);
4949 }
4950 
4951 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4952 BTF_SET_START(rcu_protected_types)
4953 #ifdef CONFIG_NET
4954 BTF_ID(struct, prog_test_ref_kfunc)
4955 #endif
4956 #ifdef CONFIG_CGROUPS
4957 BTF_ID(struct, cgroup)
4958 #endif
4959 #ifdef CONFIG_BPF_JIT
4960 BTF_ID(struct, bpf_cpumask)
4961 #endif
4962 BTF_ID(struct, task_struct)
4963 #ifdef CONFIG_BPF_CRYPTO
4964 BTF_ID(struct, bpf_crypto_ctx)
4965 #endif
4966 #ifdef CONFIG_INET
4967 BTF_ID(struct, bpf_ksock)
4968 #endif
4969 BTF_SET_END(rcu_protected_types)
4970 
4971 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4972 {
4973 	if (!btf_is_kernel(btf))
4974 		return true;
4975 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4976 }
4977 
4978 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
4979 {
4980 	struct btf_struct_meta *meta;
4981 
4982 	if (btf_is_kernel(kptr_field->kptr.btf))
4983 		return NULL;
4984 
4985 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
4986 				    kptr_field->kptr.btf_id);
4987 
4988 	return meta ? meta->record : NULL;
4989 }
4990 
4991 static bool rcu_safe_kptr(const struct btf_field *field)
4992 {
4993 	const struct btf_field_kptr *kptr = &field->kptr;
4994 
4995 	return field->type == BPF_KPTR_PERCPU ||
4996 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
4997 }
4998 
4999 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5000 {
5001 	struct btf_record *rec;
5002 	u32 ret;
5003 
5004 	ret = PTR_MAYBE_NULL;
5005 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5006 		ret |= MEM_RCU;
5007 		if (kptr_field->type == BPF_KPTR_PERCPU)
5008 			ret |= MEM_PERCPU;
5009 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5010 			ret |= MEM_ALLOC;
5011 
5012 		rec = kptr_pointee_btf_record(kptr_field);
5013 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5014 			ret |= NON_OWN_REF;
5015 	} else {
5016 		ret |= PTR_UNTRUSTED;
5017 	}
5018 
5019 	return ret;
5020 }
5021 
5022 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5023 			    struct btf_field *field)
5024 {
5025 	struct bpf_reg_state *reg;
5026 	const struct btf_type *t;
5027 
5028 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5029 	mark_reg_known_zero(env, cur_regs(env), regno);
5030 	reg = reg_state(env, regno);
5031 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5032 	reg->mem_size = t->size;
5033 	reg->id = ++env->id_gen;
5034 
5035 	return 0;
5036 }
5037 
5038 static int check_map_kptr_access(struct bpf_verifier_env *env,
5039 				 int value_regno, int insn_idx,
5040 				 struct btf_field *kptr_field)
5041 {
5042 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5043 	int class = BPF_CLASS(insn->code);
5044 	struct bpf_reg_state *val_reg;
5045 	int ret;
5046 
5047 	/* Things we already checked for in check_map_access and caller:
5048 	 *  - Reject cases where variable offset may touch kptr
5049 	 *  - size of access (must be BPF_DW)
5050 	 *  - tnum_is_const(reg->var_off)
5051 	 *  - kptr_field->offset == off + reg->var_off.value
5052 	 */
5053 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5054 	if (BPF_MODE(insn->code) != BPF_MEM) {
5055 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5056 		return -EACCES;
5057 	}
5058 
5059 	/* We only allow loading referenced kptr, since it will be marked as
5060 	 * untrusted, similar to unreferenced kptr.
5061 	 */
5062 	if (class != BPF_LDX &&
5063 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5064 		verbose(env, "store to referenced kptr disallowed\n");
5065 		return -EACCES;
5066 	}
5067 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5068 		verbose(env, "store to uptr disallowed\n");
5069 		return -EACCES;
5070 	}
5071 
5072 	if (class == BPF_LDX) {
5073 		if (kptr_field->type == BPF_UPTR)
5074 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5075 
5076 		/* We can simply mark the value_regno receiving the pointer
5077 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5078 		 */
5079 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5080 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5081 				      btf_ld_kptr_type(env, kptr_field));
5082 		if (ret < 0)
5083 			return ret;
5084 	} else if (class == BPF_STX) {
5085 		val_reg = reg_state(env, value_regno);
5086 		if (bpf_register_is_null(val_reg)) {
5087 			/*
5088 			 * This store is valid only because the scalar is known to be
5089 			 * zero. Mark it precise so another scalar cannot be pruned
5090 			 * against this state.
5091 			 */
5092 			return mark_chain_precision(env, value_regno);
5093 		}
5094 		if (map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5095 			return -EACCES;
5096 	} else if (class == BPF_ST) {
5097 		if (insn->imm) {
5098 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5099 				kptr_field->offset);
5100 			return -EACCES;
5101 		}
5102 	} else {
5103 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5104 		return -EACCES;
5105 	}
5106 	return 0;
5107 }
5108 
5109 /*
5110  * Return the size of the memory region accessible from a pointer to map value.
5111  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
5112  */
5113 static u32 map_mem_size(const struct bpf_map *map)
5114 {
5115 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5116 		return map->max_entries * sizeof(long);
5117 
5118 	return map->value_size;
5119 }
5120 
5121 /* check read/write into a map element with possible variable offset */
5122 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
5123 			    int off, int size, bool zero_size_allowed,
5124 			    enum bpf_access_src src)
5125 {
5126 	struct bpf_map *map = reg->map_ptr;
5127 	u32 mem_size = map_mem_size(map);
5128 	struct btf_record *rec;
5129 	int err, i;
5130 
5131 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
5132 	if (err)
5133 		return err;
5134 
5135 	if (IS_ERR_OR_NULL(map->record))
5136 		return 0;
5137 	rec = map->record;
5138 	for (i = 0; i < rec->cnt; i++) {
5139 		struct btf_field *field = &rec->fields[i];
5140 		u32 p = field->offset;
5141 
5142 		/* If any part of a field  can be touched by load/store, reject
5143 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5144 		 * it is sufficient to check x1 < y2 && y1 < x2.
5145 		 */
5146 		if (reg_smin(reg) + off < p + field->size &&
5147 		    p < reg_umax(reg) + off + size) {
5148 			switch (field->type) {
5149 			case BPF_KPTR_UNREF:
5150 			case BPF_KPTR_REF:
5151 			case BPF_KPTR_PERCPU:
5152 			case BPF_UPTR:
5153 				if (src != ACCESS_DIRECT) {
5154 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5155 						btf_field_type_name(field->type));
5156 					return -EACCES;
5157 				}
5158 				if (!tnum_is_const(reg->var_off)) {
5159 					verbose(env, "%s access cannot have variable offset\n",
5160 						btf_field_type_name(field->type));
5161 					return -EACCES;
5162 				}
5163 				if (p != off + reg->var_off.value) {
5164 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5165 						btf_field_type_name(field->type),
5166 						p, off + reg->var_off.value);
5167 					return -EACCES;
5168 				}
5169 				if (size != bpf_size_to_bytes(BPF_DW)) {
5170 					verbose(env, "%s access size must be BPF_DW\n",
5171 						btf_field_type_name(field->type));
5172 					return -EACCES;
5173 				}
5174 				break;
5175 			default:
5176 				verbose(env, "%s cannot be accessed directly by load/store\n",
5177 					btf_field_type_name(field->type));
5178 				return -EACCES;
5179 			}
5180 		}
5181 	}
5182 	return 0;
5183 }
5184 
5185 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5186 			       const struct bpf_call_arg_meta *meta,
5187 			       enum bpf_access_type t)
5188 {
5189 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5190 
5191 	switch (prog_type) {
5192 	/* Program types only with direct read access go here! */
5193 	case BPF_PROG_TYPE_LWT_IN:
5194 	case BPF_PROG_TYPE_LWT_OUT:
5195 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5196 	case BPF_PROG_TYPE_SK_REUSEPORT:
5197 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5198 	case BPF_PROG_TYPE_CGROUP_SKB:
5199 		if (t == BPF_WRITE)
5200 			return false;
5201 		fallthrough;
5202 
5203 	/* Program types with direct read + write access go here! */
5204 	case BPF_PROG_TYPE_SCHED_CLS:
5205 	case BPF_PROG_TYPE_SCHED_ACT:
5206 	case BPF_PROG_TYPE_XDP:
5207 	case BPF_PROG_TYPE_LWT_XMIT:
5208 	case BPF_PROG_TYPE_SK_SKB:
5209 	case BPF_PROG_TYPE_SK_MSG:
5210 		if (meta && !meta->btf && meta->func_id)
5211 			return meta->fn->pkt_access;
5212 
5213 		if (t == BPF_WRITE)
5214 			env->seen_direct_write = true;
5215 		return true;
5216 
5217 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5218 		if (t == BPF_WRITE)
5219 			env->seen_direct_write = true;
5220 
5221 		return true;
5222 
5223 	default:
5224 		return false;
5225 	}
5226 }
5227 
5228 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
5229 			       int size, bool zero_size_allowed)
5230 {
5231 	int err;
5232 
5233 	if (reg->range < 0) {
5234 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
5235 		return -EINVAL;
5236 	}
5237 
5238 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
5239 	if (err)
5240 		return err;
5241 
5242 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5243 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
5244 	 * otherwise find_good_pkt_pointers would have refused to set range info
5245 	 * that __check_mem_access would have rejected this pkt access.
5246 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
5247 	 */
5248 	env->prog->aux->max_pkt_offset =
5249 		max_t(u32, env->prog->aux->max_pkt_offset,
5250 		      off + reg_umax(reg) + size - 1);
5251 
5252 	return 0;
5253 }
5254 
5255 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
5256 {
5257 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
5258 }
5259 
5260 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5261 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5262 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
5263 {
5264 	if (env->ops->is_valid_access &&
5265 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
5266 		/* A non zero info.ctx_field_size indicates that this field is a
5267 		 * candidate for later verifier transformation to load the whole
5268 		 * field and then apply a mask when accessed with a narrower
5269 		 * access than actual ctx access size. A zero info.ctx_field_size
5270 		 * will only allow for whole field access and rejects any other
5271 		 * type of narrower access.
5272 		 */
5273 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
5274 			if (info->ref_id &&
5275 			    !find_reference_state(env->cur_state, info->ref_id)) {
5276 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
5277 					off);
5278 				return -EACCES;
5279 			}
5280 		} else {
5281 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
5282 		}
5283 		/* remember the offset of last byte accessed in ctx */
5284 		if (env->prog->aux->max_ctx_offset < off + size)
5285 			env->prog->aux->max_ctx_offset = off + size;
5286 		return 0;
5287 	}
5288 
5289 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5290 	return -EACCES;
5291 }
5292 
5293 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
5294 			    int off, int access_size, enum bpf_access_type t,
5295 			    struct bpf_insn_access_aux *info)
5296 {
5297 	/*
5298 	 * Program types that don't rewrite ctx accesses can safely
5299 	 * dereference ctx pointers with fixed offsets.
5300 	 */
5301 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
5302 	bool fixed_off_ok = !env->ops->convert_ctx_access;
5303 	int err;
5304 
5305 	if (var_off_ok)
5306 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
5307 	else
5308 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
5309 	if (err)
5310 		return err;
5311 	off += reg_umax(reg);
5312 
5313 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
5314 	if (err)
5315 		verbose_linfo(env, insn_idx, "; ");
5316 	return err;
5317 }
5318 
5319 static int check_flow_keys_access(struct bpf_verifier_env *env,
5320 				  struct bpf_reg_state *reg, argno_t argno,
5321 				  int off, int size)
5322 {
5323 	/* Only a constant offset is allowed here; fold it into off. */
5324 	if (!tnum_is_const(reg->var_off)) {
5325 		char tn_buf[48];
5326 
5327 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5328 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
5329 			reg_arg_name(env, argno), off, tn_buf);
5330 		return -EACCES;
5331 	}
5332 	off += reg->var_off.value;
5333 
5334 	if (size < 0 || off < 0 ||
5335 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5336 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5337 			off, size);
5338 		return -EACCES;
5339 	}
5340 	return 0;
5341 }
5342 
5343 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5344 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
5345 			     enum bpf_access_type t)
5346 {
5347 	struct bpf_insn_access_aux info = {};
5348 	bool valid;
5349 
5350 	if (reg_smin(reg) < 0) {
5351 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5352 			reg_arg_name(env, argno));
5353 		return -EACCES;
5354 	}
5355 
5356 	switch (reg->type) {
5357 	case PTR_TO_SOCK_COMMON:
5358 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5359 		break;
5360 	case PTR_TO_SOCKET:
5361 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5362 		break;
5363 	case PTR_TO_TCP_SOCK:
5364 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5365 		break;
5366 	case PTR_TO_XDP_SOCK:
5367 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5368 		break;
5369 	default:
5370 		valid = false;
5371 	}
5372 
5373 	if (valid) {
5374 		env->insn_aux_data[insn_idx].ctx_field_size =
5375 			info.ctx_field_size;
5376 		return 0;
5377 	}
5378 
5379 	verbose(env, "%s invalid %s access off=%d size=%d\n",
5380 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
5381 
5382 	return -EACCES;
5383 }
5384 
5385 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5386 {
5387 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5388 }
5389 
5390 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5391 {
5392 	const struct bpf_reg_state *reg = reg_state(env, regno);
5393 
5394 	return reg->type == PTR_TO_CTX;
5395 }
5396 
5397 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5398 {
5399 	const struct bpf_reg_state *reg = reg_state(env, regno);
5400 
5401 	return type_is_sk_pointer(reg->type);
5402 }
5403 
5404 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5405 {
5406 	const struct bpf_reg_state *reg = reg_state(env, regno);
5407 
5408 	return type_is_pkt_pointer(reg->type);
5409 }
5410 
5411 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5412 {
5413 	const struct bpf_reg_state *reg = reg_state(env, regno);
5414 
5415 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5416 	return reg->type == PTR_TO_FLOW_KEYS;
5417 }
5418 
5419 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5420 {
5421 	const struct bpf_reg_state *reg = reg_state(env, regno);
5422 
5423 	return reg->type == PTR_TO_ARENA;
5424 }
5425 
5426 /*
5427  * There are no address spaces in Rust, addresses of arena are plain numbers.
5428  * When the program is loaded with BPF_F_ARENA_SCALAR and has an arena a load or
5429  * a store through a number is an access to arena at the low 32 bits of it,
5430  * like the access through PTR_TO_ARENA is. The register stays a number.
5431  */
5432 static bool is_arena_scalar(struct bpf_verifier_env *env, int regno)
5433 {
5434 	const struct bpf_reg_state *reg = reg_state(env, regno);
5435 
5436 	return reg->type == SCALAR_VALUE && env->arena_scalar && env->prog->aux->arena;
5437 }
5438 
5439 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno,
5440 			       struct bpf_insn *insn)
5441 {
5442 	const struct bpf_reg_state *reg = reg_state(env, regno);
5443 
5444 	/*
5445 	 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the
5446 	 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load
5447 	 * with no exception table entry, so a fault (e.g. NULL deref) crashes
5448 	 * the kernel instead of being handled. Reject the source pointer types
5449 	 * that would have needed that protection, the remaining ones stay
5450 	 * allowed.
5451 	 */
5452 	return insn->imm == BPF_LOAD_ACQ && bpf_may_fault_on_deref(reg->type);
5453 }
5454 
5455 /* Return false if @regno contains a pointer whose type isn't supported for
5456  * atomic instruction @insn.
5457  */
5458 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
5459 			       struct bpf_insn *insn)
5460 {
5461 	if (is_ctx_reg(env, regno))
5462 		return false;
5463 	if (is_pkt_reg(env, regno))
5464 		return false;
5465 	if (is_flow_key_reg(env, regno))
5466 		return false;
5467 	if (is_sk_reg(env, regno))
5468 		return false;
5469 	if (is_arena_reg(env, regno) || is_arena_scalar(env, regno))
5470 		return bpf_jit_supports_insn(insn, true);
5471 	if (is_load_acq_unsafe(env, regno, insn))
5472 		return false;
5473 	return true;
5474 }
5475 
5476 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5477 #ifdef CONFIG_NET
5478 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5479 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5480 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5481 #endif
5482 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5483 };
5484 
5485 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
5486 {
5487 	/* A referenced register is always trusted. */
5488 	if (reg_is_referenced(env, reg))
5489 		return true;
5490 
5491 	/* Types listed in the reg2btf_ids are always trusted */
5492 	if (reg2btf_ids[base_type(reg->type)] &&
5493 	    !bpf_type_has_unsafe_modifiers(reg->type))
5494 		return true;
5495 
5496 	/* If a register is not referenced, it is trusted if it has the
5497 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5498 	 * other type modifiers may be safe, but we elect to take an opt-in
5499 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5500 	 * not.
5501 	 *
5502 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5503 	 * for whether a register is trusted.
5504 	 */
5505 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5506 	       !bpf_type_has_unsafe_modifiers(reg->type);
5507 }
5508 
5509 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5510 {
5511 	return reg->type & MEM_RCU;
5512 }
5513 
5514 static void clear_trusted_flags(enum bpf_type_flag *flag)
5515 {
5516 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5517 }
5518 
5519 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5520 				   const struct bpf_reg_state *reg,
5521 				   int off, int size, bool strict)
5522 {
5523 	struct tnum reg_off;
5524 	int ip_align;
5525 
5526 	/* Byte size accesses are always allowed. */
5527 	if (!strict || size == 1)
5528 		return 0;
5529 
5530 	/* For platforms that do not have a Kconfig enabling
5531 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5532 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5533 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5534 	 * to this code only in strict mode where we want to emulate
5535 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5536 	 * unconditional IP align value of '2'.
5537 	 */
5538 	ip_align = 2;
5539 
5540 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
5541 	if (!tnum_is_aligned(reg_off, size)) {
5542 		char tn_buf[48];
5543 
5544 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5545 		verbose(env,
5546 			"misaligned packet access off %d+%s+%d size %d\n",
5547 			ip_align, tn_buf, off, size);
5548 		return -EACCES;
5549 	}
5550 
5551 	return 0;
5552 }
5553 
5554 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5555 				       const struct bpf_reg_state *reg,
5556 				       const char *pointer_desc,
5557 				       int off, int size, bool strict)
5558 {
5559 	struct tnum reg_off;
5560 
5561 	/* Byte size accesses are always allowed. */
5562 	if (!strict || size == 1)
5563 		return 0;
5564 
5565 	reg_off = tnum_add(reg->var_off, tnum_const(off));
5566 	if (!tnum_is_aligned(reg_off, size)) {
5567 		char tn_buf[48];
5568 
5569 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5570 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
5571 			pointer_desc, tn_buf, off, size);
5572 		return -EACCES;
5573 	}
5574 
5575 	return 0;
5576 }
5577 
5578 static int check_ptr_alignment(struct bpf_verifier_env *env,
5579 			       const struct bpf_reg_state *reg, int off,
5580 			       int size, bool strict_alignment_once)
5581 {
5582 	bool strict = env->strict_alignment || strict_alignment_once;
5583 	const char *pointer_desc = "";
5584 
5585 	switch (reg->type) {
5586 	case PTR_TO_PACKET:
5587 	case PTR_TO_PACKET_META:
5588 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5589 		 * right in front, treat it the very same way.
5590 		 */
5591 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5592 	case PTR_TO_FLOW_KEYS:
5593 		pointer_desc = "flow keys ";
5594 		break;
5595 	case PTR_TO_MAP_KEY:
5596 		pointer_desc = "key ";
5597 		break;
5598 	case PTR_TO_MAP_VALUE:
5599 		pointer_desc = "value ";
5600 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5601 			strict = true;
5602 		break;
5603 	case PTR_TO_CTX:
5604 		pointer_desc = "context ";
5605 		break;
5606 	case PTR_TO_STACK:
5607 		pointer_desc = "stack ";
5608 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5609 		 * and check_stack_read_fixed_off() relies on stack accesses being
5610 		 * aligned.
5611 		 */
5612 		strict = true;
5613 		break;
5614 	case PTR_TO_SOCKET:
5615 		pointer_desc = "sock ";
5616 		break;
5617 	case PTR_TO_SOCK_COMMON:
5618 		pointer_desc = "sock_common ";
5619 		break;
5620 	case PTR_TO_TCP_SOCK:
5621 		pointer_desc = "tcp_sock ";
5622 		break;
5623 	case PTR_TO_XDP_SOCK:
5624 		pointer_desc = "xdp_sock ";
5625 		break;
5626 	case PTR_TO_ARENA:
5627 		return 0;
5628 	default:
5629 		break;
5630 	}
5631 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5632 					   strict);
5633 }
5634 
5635 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5636 {
5637 	if (!bpf_jit_supports_private_stack())
5638 		return NO_PRIV_STACK;
5639 
5640 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5641 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5642 	 * explicitly.
5643 	 */
5644 	switch (prog->type) {
5645 	case BPF_PROG_TYPE_KPROBE:
5646 	case BPF_PROG_TYPE_TRACEPOINT:
5647 	case BPF_PROG_TYPE_PERF_EVENT:
5648 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5649 		return PRIV_STACK_ADAPTIVE;
5650 	case BPF_PROG_TYPE_TRACING:
5651 	case BPF_PROG_TYPE_LSM:
5652 	case BPF_PROG_TYPE_STRUCT_OPS:
5653 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5654 			return PRIV_STACK_ADAPTIVE;
5655 		fallthrough;
5656 	default:
5657 		break;
5658 	}
5659 
5660 	return NO_PRIV_STACK;
5661 }
5662 
5663 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5664 {
5665 	if (env->prog->jit_requested)
5666 		return round_up(stack_depth, 16);
5667 
5668 	/* round up to 32-bytes, since this is granularity
5669 	 * of interpreter stack size
5670 	 */
5671 	return round_up(max_t(u32, stack_depth, 1), 32);
5672 }
5673 
5674 /* temporary state used for call frame depth calculation */
5675 struct bpf_subprog_call_depth_info {
5676 	int ret_insn; /* caller instruction where we return to. */
5677 	int caller; /* caller subprogram idx */
5678 	int frame; /* # of consecutive static call stack frames on top of stack */
5679 	int callx_insn; /* callx instruction whose callees are being walked */
5680 	int callx_next; /* next callee of callx_insn to walk */
5681 	bool via_callx; /* the subprogram is entered via callx */
5682 };
5683 
5684 /* starting from main bpf function walk all instructions of the function
5685  * and recursively walk all callees that given function can call.
5686  * Ignore jump and exit insns.
5687  */
5688 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5689 					 struct bpf_subprog_call_depth_info *dinfo,
5690 					 bool priv_stack_supported)
5691 {
5692 	struct bpf_subprog_info *subprog = env->subprog_info;
5693 	struct bpf_insn *insn = env->prog->insnsi;
5694 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5695 	bool tail_call_reachable = false;
5696 	int total;
5697 	int tmp;
5698 
5699 	/* no caller idx */
5700 	dinfo[idx].caller = -1;
5701 	dinfo[idx].via_callx = false;
5702 
5703 	i = subprog[idx].start;
5704 	if (!priv_stack_supported)
5705 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5706 process_func:
5707 	dinfo[idx].callx_insn = -1;
5708 	if (subprog[idx].has_ld_abs) {
5709 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5710 			if (subprog[tmp].is_cb) {
5711 				verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
5712 				return -EINVAL;
5713 			}
5714 		}
5715 	}
5716 
5717 	/* protect against potential stack overflow that might happen when
5718 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5719 	 * depth for such case down to 256 so that the worst case scenario
5720 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5721 	 * 8k).
5722 	 *
5723 	 * To get the idea what might happen, see an example:
5724 	 * func1 -> sub rsp, 128
5725 	 *  subfunc1 -> sub rsp, 256
5726 	 *  tailcall1 -> add rsp, 256
5727 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5728 	 *   subfunc2 -> sub rsp, 64
5729 	 *   subfunc22 -> sub rsp, 128
5730 	 *   tailcall2 -> add rsp, 128
5731 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5732 	 *
5733 	 * tailcall will unwind the current stack frame but it will not get rid
5734 	 * of caller's stack as shown on the example above.
5735 	 */
5736 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5737 		verbose(env,
5738 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5739 			depth);
5740 		return -EACCES;
5741 	}
5742 
5743 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5744 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5745 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5746 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5747 	} else if (priv_stack_supported) {
5748 		/* Request private stack support only if the subprog stack
5749 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5750 		 * avoid jit penalty if the stack usage is small.
5751 		 */
5752 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5753 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5754 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5755 	}
5756 
5757 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5758 		if (subprog_depth > env->max_stack_depth)
5759 			env->max_stack_depth = subprog_depth;
5760 		if (subprog_depth > env->stack_limit) {
5761 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5762 				idx, subprog_depth);
5763 			return -EACCES;
5764 		}
5765 	} else {
5766 		depth += subprog_depth;
5767 		if (depth > env->max_stack_depth)
5768 			env->max_stack_depth = depth;
5769 		if (depth > env->stack_limit) {
5770 			total = 0;
5771 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5772 				total++;
5773 
5774 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5775 				total, depth);
5776 			return -EACCES;
5777 		}
5778 	}
5779 continue_func:
5780 	subprog_end = subprog[idx + 1].start;
5781 	for (; i < subprog_end; i++) {
5782 		int next_insn, sidx;
5783 
5784 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off &&
5785 		    bpf_is_throw_kfunc(insn + i)) {
5786 			bool err = false;
5787 
5788 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5789 				if (subprog[tmp].is_cb) {
5790 					err = true;
5791 					break;
5792 				}
5793 			}
5794 			if (!err)
5795 				continue;
5796 			verbose(env,
5797 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5798 				i, idx);
5799 			return -EINVAL;
5800 		}
5801 
5802 		if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i)) {
5803 			/*
5804 			 * Walk the callees and the callbacks recorded by
5805 			 * the main verification pass one by one, returning to
5806 			 * this insn after each.
5807 			 */
5808 			if (dinfo[idx].callx_insn != i) {
5809 				dinfo[idx].callx_insn = i;
5810 				dinfo[idx].callx_next = 0;
5811 			}
5812 			sidx = next_callx_callee(env, idx, dinfo[idx].callx_next);
5813 			if (sidx < 0)
5814 				continue;
5815 			dinfo[idx].callx_next = sidx + 1;
5816 			dinfo[idx].ret_insn = i;
5817 			next_insn = subprog[sidx].start;
5818 		} else if (bpf_pseudo_call(insn + i) || bpf_pseudo_func(insn + i)) {
5819 			/* find the callee */
5820 			next_insn = i + insn[i].imm + 1;
5821 			sidx = bpf_find_subprog(env, next_insn);
5822 			if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5823 				return -EFAULT;
5824 			if (subprog[sidx].is_async_cb) {
5825 				/* async callbacks don't increase bpf prog stack size unless called directly */
5826 				if (!bpf_pseudo_call(insn + i))
5827 					continue;
5828 				if (subprog[sidx].is_exception_cb) {
5829 					verbose(env, "insn %d cannot call exception cb directly", i);
5830 					return -EINVAL;
5831 				}
5832 			}
5833 			/* remember insn to return to */
5834 			dinfo[idx].ret_insn = i + 1;
5835 		} else {
5836 			continue;
5837 		}
5838 
5839 		/*
5840 		 * sort_subprogs_topo() tolerates cycles in the call graph that
5841 		 * go through the address of a function being taken, since it
5842 		 * doesn't know what it is taken for. Such cycle is a recursion
5843 		 * unless it's an async callback, which are skipped above.
5844 		 * The main verification pass limits the depth of the recursion,
5845 		 * but it doesn't follow calls of global functions.
5846 		 */
5847 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5848 			if (tmp != sidx)
5849 				continue;
5850 			verbose(env, "recursive call from %s() to %s()\n",
5851 				bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx));
5852 			bpf_diag_program_structure(
5853 				env, i, "recursive subprogram call",
5854 				"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
5855 				"This call or callback would make the subprogram call graph recursive. "
5856 				"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
5857 			return -EINVAL;
5858 		}
5859 
5860 		/* store caller info for after we return from callee */
5861 		dinfo[idx].frame = frame;
5862 
5863 		/* push caller idx into callee's dinfo */
5864 		dinfo[sidx].caller = idx;
5865 		dinfo[sidx].via_callx = bpf_is_callx(insn + i);
5866 
5867 		i = next_insn;
5868 
5869 		idx = sidx;
5870 		if (!priv_stack_supported)
5871 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5872 
5873 		/* sync tail_call_reachable with callee state on entry */
5874 		tail_call_reachable = subprog[idx].has_tail_call;
5875 
5876 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5877 		if (frame >= MAX_CALL_FRAMES) {
5878 			verbose(env, "the call stack of %d frames is too deep !\n",
5879 				frame);
5880 			return -E2BIG;
5881 		}
5882 		goto process_func;
5883 	}
5884 	/* if tail call got detected across bpf2bpf calls then mark each of the
5885 	 * currently present subprog frames as tail call reachable subprogs;
5886 	 * this info will be utilized by JIT so that we will be preserving the
5887 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5888 	 */
5889 	if (tail_call_reachable) {
5890 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5891 			if (subprog[tmp].is_cb) {
5892 				verbose(env, "cannot tail call within callback\n");
5893 				return -EINVAL;
5894 			}
5895 			if (subprog[tmp].stack_arg_cnt) {
5896 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5897 				return -EINVAL;
5898 			}
5899 			/*
5900 			 * JITs pass tail call counter in a register that is
5901 			 * not available when the callee is called via callx.
5902 			 */
5903 			if (dinfo[tmp].via_callx) {
5904 				verbose(env, "tail_calls are not allowed in functions called via callx\n");
5905 				return -EINVAL;
5906 			}
5907 			subprog[tmp].tail_call_reachable = true;
5908 		}
5909 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
5910 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
5911 		return -EINVAL;
5912 	}
5913 
5914 	if (subprog[0].tail_call_reachable)
5915 		env->prog->aux->tail_call_reachable = true;
5916 
5917 	/* end of for() loop means the last insn of the 'subprog'
5918 	 * was reached. Doesn't matter whether it was JA or EXIT
5919 	 */
5920 	if (frame == 0 && dinfo[idx].caller < 0)
5921 		return 0;
5922 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
5923 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5924 
5925 	/* pop caller idx from callee */
5926 	idx = dinfo[idx].caller;
5927 
5928 	/* retrieve caller state from its frame */
5929 	frame = dinfo[idx].frame;
5930 	i = dinfo[idx].ret_insn;
5931 
5932 	/* reset tail_call_reachable to the parent's actual state */
5933 	tail_call_reachable = subprog[idx].tail_call_reachable;
5934 
5935 	goto continue_func;
5936 }
5937 
5938 static int check_max_stack_depth(struct bpf_verifier_env *env)
5939 {
5940 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
5941 	struct bpf_subprog_call_depth_info *dinfo;
5942 	struct bpf_subprog_info *si = env->subprog_info;
5943 	bool priv_stack_supported;
5944 	int ret;
5945 
5946 	dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
5947 	if (!dinfo)
5948 		return -ENOMEM;
5949 
5950 	for (int i = 0; i < env->subprog_cnt; i++) {
5951 		if (si[i].has_tail_call) {
5952 			priv_stack_mode = NO_PRIV_STACK;
5953 			break;
5954 		}
5955 	}
5956 
5957 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
5958 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
5959 
5960 	/* All async_cb subprogs use normal kernel stack. If a particular
5961 	 * subprog appears in both main prog and async_cb subtree, that
5962 	 * subprog will use normal kernel stack to avoid potential nesting.
5963 	 * The reverse subprog traversal ensures when main prog subtree is
5964 	 * checked, the subprogs appearing in async_cb subtrees are already
5965 	 * marked as using normal kernel stack, so stack size checking can
5966 	 * be done properly.
5967 	 */
5968 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
5969 		if (!i || si[i].is_async_cb) {
5970 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
5971 			ret = check_max_stack_depth_subprog(env, i, dinfo,
5972 					priv_stack_supported);
5973 			if (ret < 0) {
5974 				kvfree(dinfo);
5975 				return ret;
5976 			}
5977 		}
5978 	}
5979 
5980 	for (int i = 0; i < env->subprog_cnt; i++) {
5981 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5982 			env->prog->aux->jits_use_priv_stack = true;
5983 			break;
5984 		}
5985 	}
5986 
5987 	kvfree(dinfo);
5988 
5989 	return 0;
5990 }
5991 
5992 static int __check_buffer_access(struct bpf_verifier_env *env,
5993 				 const char *buf_info,
5994 				 const struct bpf_reg_state *reg,
5995 				 argno_t argno, int off, int size,
5996 				 u32 *access_end)
5997 {
5998 	s64 start;
5999 
6000 	if (!tnum_is_const(reg->var_off)) {
6001 		char tn_buf[48];
6002 
6003 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6004 		verbose(env,
6005 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
6006 			reg_arg_name(env, argno), off, tn_buf);
6007 		return -EACCES;
6008 	}
6009 
6010 	start = (s64)reg->var_off.value + off;
6011 	if (start < 0) {
6012 		verbose(env,
6013 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
6014 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
6015 		return -EACCES;
6016 	}
6017 
6018 	*access_end = start + size;
6019 	return 0;
6020 }
6021 
6022 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6023 				  const struct bpf_reg_state *reg,
6024 				  argno_t argno, int off, int size)
6025 {
6026 	u32 access_end;
6027 	int err;
6028 
6029 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
6030 	if (err)
6031 		return err;
6032 
6033 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
6034 
6035 	return 0;
6036 }
6037 
6038 static int check_buffer_access(struct bpf_verifier_env *env,
6039 			       const struct bpf_reg_state *reg,
6040 			       argno_t argno, int off, int size,
6041 			       bool zero_size_allowed,
6042 			       u32 *max_access)
6043 {
6044 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6045 	u32 access_end;
6046 	int err;
6047 
6048 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
6049 	if (err)
6050 		return err;
6051 
6052 	*max_access = max(access_end, *max_access);
6053 
6054 	return 0;
6055 }
6056 
6057 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6058 static void zext_32_to_64(struct bpf_reg_state *reg)
6059 {
6060 	reg_step_check_unsigned(reg, 32);
6061 	reg->var_off = tnum_subreg(reg->var_off);
6062 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
6063 }
6064 
6065 /* truncate register to smaller size (in bytes)
6066  * must be called with size < BPF_REG_SIZE
6067  */
6068 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6069 {
6070 	u64 mask = (1ULL << (size * 8)) - 1;
6071 
6072 	reg_step_check_unsigned(reg, size * 8);
6073 
6074 	/* clear high bits in bit representation */
6075 	reg->var_off = tnum_cast(reg->var_off, size);
6076 
6077 	/* fix arithmetic bounds */
6078 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
6079 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
6080 	else
6081 		reg_set_urange64(reg, 0, mask);
6082 
6083 	/* If size is smaller than 32bit register the 32bit register
6084 	 * values are also truncated so we push 64-bit bounds into
6085 	 * 32-bit bounds. Above were truncated < 32-bits already.
6086 	 */
6087 	if (size < 4)
6088 		__mark_reg32_unbounded(reg);
6089 
6090 	reg_bounds_sync(reg);
6091 }
6092 
6093 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6094 {
6095 	if (size == 1) {
6096 		reg_set_srange64(reg, S8_MIN, S8_MAX);
6097 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6098 	} else if (size == 2) {
6099 		reg_set_srange64(reg, S16_MIN, S16_MAX);
6100 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6101 	} else {
6102 		/* size == 4 */
6103 		reg_set_srange64(reg, S32_MIN, S32_MAX);
6104 		reg_set_srange32(reg, S32_MIN, S32_MAX);
6105 	}
6106 	reg->var_off = tnum_unknown;
6107 }
6108 
6109 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6110 {
6111 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6112 	u64 top_smax_value, top_smin_value;
6113 	u64 num_bits = size * 8;
6114 	s64 limit = 1LL << (num_bits - 1);
6115 
6116 	/* If every value fits the signed N-bit range sign extension is a noop. */
6117 	if (reg_smin(reg) >= -limit && reg_smax(reg) < limit)
6118 		return;
6119 
6120 	/* See commen at reg_step_check_unsigned(). */
6121 	reg_step_reset(reg);
6122 
6123 	if (tnum_is_const(reg->var_off)) {
6124 		u64_cval = reg->var_off.value;
6125 		if (size == 1)
6126 			reg->var_off = tnum_const((s8)u64_cval);
6127 		else if (size == 2)
6128 			reg->var_off = tnum_const((s16)u64_cval);
6129 		else
6130 			/* size == 4 */
6131 			reg->var_off = tnum_const((s32)u64_cval);
6132 
6133 		u64_cval = reg->var_off.value;
6134 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
6135 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
6136 		return;
6137 	}
6138 
6139 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
6140 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
6141 
6142 	if (top_smax_value != top_smin_value)
6143 		goto out;
6144 
6145 	/* find the s64_min and s64_min after sign extension */
6146 	if (size == 1) {
6147 		init_s64_max = (s8)reg_smax(reg);
6148 		init_s64_min = (s8)reg_smin(reg);
6149 	} else if (size == 2) {
6150 		init_s64_max = (s16)reg_smax(reg);
6151 		init_s64_min = (s16)reg_smin(reg);
6152 	} else {
6153 		init_s64_max = (s32)reg_smax(reg);
6154 		init_s64_min = (s32)reg_smin(reg);
6155 	}
6156 
6157 	s64_max = max(init_s64_max, init_s64_min);
6158 	s64_min = min(init_s64_max, init_s64_min);
6159 
6160 	/* both of s64_max/s64_min positive or negative */
6161 	if ((s64_max >= 0) == (s64_min >= 0)) {
6162 		reg_set_srange64(reg, s64_min, s64_max);
6163 		reg_set_srange32(reg, s64_min, s64_max);
6164 		reg->var_off = tnum_range(s64_min, s64_max);
6165 		return;
6166 	}
6167 
6168 out:
6169 	set_sext64_default_val(reg, size);
6170 }
6171 
6172 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6173 {
6174 	if (size == 1)
6175 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6176 	else
6177 		/* size == 2 */
6178 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6179 	reg->var_off = tnum_subreg(tnum_unknown);
6180 }
6181 
6182 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6183 {
6184 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6185 	u32 top_smax_value, top_smin_value;
6186 	u32 num_bits = size * 8;
6187 
6188 	/*
6189 	 * If value fits the non-negative half of the signed N-bit range,
6190 	 * sign extension is a noop.
6191 	 */
6192 	if (reg_umax(reg) < (1ULL << (num_bits - 1)))
6193 		return;
6194 
6195 	/* See comment at reg_step_check_unsigned(). */
6196 	reg_step_reset(reg);
6197 
6198 	if (tnum_is_const(reg->var_off)) {
6199 		u32_val = reg->var_off.value;
6200 		if (size == 1)
6201 			reg->var_off = tnum_const((s8)u32_val);
6202 		else
6203 			reg->var_off = tnum_const((s16)u32_val);
6204 
6205 		u32_val = reg->var_off.value;
6206 		reg_set_srange32(reg, u32_val, u32_val);
6207 		return;
6208 	}
6209 
6210 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
6211 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
6212 
6213 	if (top_smax_value != top_smin_value)
6214 		goto out;
6215 
6216 	/* find the s32_min and s32_min after sign extension */
6217 	if (size == 1) {
6218 		init_s32_max = (s8)reg_s32_max(reg);
6219 		init_s32_min = (s8)reg_s32_min(reg);
6220 	} else {
6221 		/* size == 2 */
6222 		init_s32_max = (s16)reg_s32_max(reg);
6223 		init_s32_min = (s16)reg_s32_min(reg);
6224 	}
6225 	s32_max = max(init_s32_max, init_s32_min);
6226 	s32_min = min(init_s32_max, init_s32_min);
6227 
6228 	if ((s32_min >= 0) == (s32_max >= 0)) {
6229 		reg_set_srange32(reg, s32_min, s32_max);
6230 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6231 		return;
6232 	}
6233 
6234 out:
6235 	set_sext32_default_val(reg, size);
6236 }
6237 
6238 bool bpf_map_is_rdonly(const struct bpf_map *map)
6239 {
6240 	/* A map is considered read-only if the following condition are true:
6241 	 *
6242 	 * 1) BPF program side cannot change any of the map content. The
6243 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6244 	 *    and was set at map creation time.
6245 	 * 2) The map value(s) have been initialized from user space by a
6246 	 *    loader and then "frozen", such that no new map update/delete
6247 	 *    operations from syscall side are possible for the rest of
6248 	 *    the map's lifetime from that point onwards.
6249 	 * 3) Any parallel/pending map update/delete operations from syscall
6250 	 *    side have been completed. Only after that point, it's safe to
6251 	 *    assume that map value(s) are immutable.
6252 	 */
6253 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6254 	       READ_ONCE(map->frozen) &&
6255 	       !bpf_map_write_active(map);
6256 }
6257 
6258 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6259 			bool is_ldsx)
6260 {
6261 	void *ptr;
6262 	u64 addr;
6263 	int err;
6264 
6265 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY || map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
6266 		return -EINVAL;
6267 	err = map->ops->map_direct_value_addr(map, &addr, off);
6268 	if (err)
6269 		return err;
6270 	ptr = (void *)(long)addr + off;
6271 
6272 	switch (size) {
6273 	case sizeof(u8):
6274 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6275 		break;
6276 	case sizeof(u16):
6277 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6278 		break;
6279 	case sizeof(u32):
6280 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6281 		break;
6282 	case sizeof(u64):
6283 		*val = *(u64 *)ptr;
6284 		break;
6285 	default:
6286 		return -EINVAL;
6287 	}
6288 	return 0;
6289 }
6290 
6291 static int cmp_func_ptrs(const void *_a, const void *_b)
6292 {
6293 	const struct bpf_func_ptr *a = _a, *b = _b;
6294 
6295 	if (a->map != b->map)
6296 		return a->map < b->map ? -1 : 1;
6297 	if (a->map_off != b->map_off)
6298 		return a->map_off < b->map_off ? -1 : 1;
6299 	return 0;
6300 }
6301 
6302 /* Find the first pointer to a function at or after 'off' in the value of 'map' */
6303 static u32 func_ptr_lower_bound(struct bpf_verifier_env *env, const struct bpf_map *map, u64 off)
6304 {
6305 	u32 l = 0, r = env->func_ptr_cnt, m;
6306 	struct bpf_func_ptr *p;
6307 
6308 	while (l < r) {
6309 		m = l + (r - l) / 2;
6310 		p = &env->func_ptrs[m];
6311 		if (p->map < map || (p->map == map && p->map_off < off))
6312 			l = m + 1;
6313 		else
6314 			r = m;
6315 	}
6316 	return l;
6317 }
6318 
6319 /*
6320  * Return pointers to functions that overlap with 'size' bytes at offset 'off'
6321  * of the value of 'map' and their number in 'cnt'.
6322  */
6323 struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env,
6324 					     const struct bpf_map *map,
6325 					     u64 off, u64 size, u32 *cnt)
6326 {
6327 	u32 first, last;
6328 
6329 	*cnt = 0;
6330 	if (!env->func_ptr_cnt || !size)
6331 		return NULL;
6332 
6333 	/* a pointer that starts up to 7 bytes before 'off' overlaps too */
6334 	first = func_ptr_lower_bound(env, map, off >= sizeof(u64) ? off - sizeof(u64) + 1 : 0);
6335 	last = func_ptr_lower_bound(env, map, off + size);
6336 	if (first >= last)
6337 		return NULL;
6338 
6339 	*cnt = last - first;
6340 	return &env->func_ptrs[first];
6341 }
6342 
6343 /* Return all pointers to functions in the value of 'map' */
6344 struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
6345 				       const struct bpf_map *map, u32 *cnt)
6346 {
6347 	return bpf_map_range_func_ptrs(env, map, 0, (u64)map->value_size, cnt);
6348 }
6349 
6350 /* instructions [off, off + len) replaced the instruction at 'off' */
6351 void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len)
6352 {
6353 	struct bpf_func_ptr *p;
6354 	u32 i;
6355 
6356 	if (len <= 1)
6357 		return;
6358 
6359 	for (i = 0; i < env->func_ptr_cnt; i++) {
6360 		p = &env->func_ptrs[i];
6361 		if (p->xlated_off <= off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6362 			continue;
6363 		p->xlated_off += len - 1;
6364 	}
6365 }
6366 
6367 /*
6368  * Instructions [off, off + len) are about to be removed. It's called before
6369  * the starts of subprogs are adjusted. A subprog is gone when all of its
6370  * instructions are. Otherwise, e.g. when its first instruction is a nop,
6371  * it starts where the removed instructions did.
6372  */
6373 void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
6374 {
6375 	struct bpf_func_ptr *p;
6376 	int subprog;
6377 	u32 i;
6378 
6379 	for (i = 0; i < env->func_ptr_cnt; i++) {
6380 		p = &env->func_ptrs[i];
6381 		if (p->xlated_off < off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6382 			continue;
6383 		if (p->xlated_off >= off + len) {
6384 			p->xlated_off -= len;
6385 			continue;
6386 		}
6387 		subprog = bpf_find_subprog(env, p->xlated_off);
6388 		if (subprog > 0 && env->subprog_info[subprog + 1].start > off + len)
6389 			p->xlated_off = off;
6390 		else
6391 			p->xlated_off = BPF_FUNC_PTR_DELETED;
6392 	}
6393 }
6394 
6395 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6396 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6397 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6398 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6399 
6400 /*
6401  * Allow list few fields as RCU trusted or full trusted.
6402  * This logic doesn't allow mix tagging and will be removed once GCC supports
6403  * btf_type_tag.
6404  */
6405 
6406 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6407 BTF_TYPE_SAFE_RCU(struct task_struct) {
6408 	const cpumask_t *cpus_ptr;
6409 	struct css_set __rcu *cgroups;
6410 	struct task_struct __rcu *real_parent;
6411 	struct task_struct *group_leader;
6412 };
6413 
6414 BTF_TYPE_SAFE_RCU(struct cgroup) {
6415 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6416 	struct kernfs_node *kn;
6417 };
6418 
6419 BTF_TYPE_SAFE_RCU(struct css_set) {
6420 	struct cgroup *dfl_cgrp;
6421 };
6422 
6423 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
6424 	struct cgroup *cgroup;
6425 };
6426 
6427 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6428 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6429 	struct file __rcu *exe_file;
6430 #ifdef CONFIG_MEMCG
6431 	struct task_struct __rcu *owner;
6432 #endif
6433 };
6434 
6435 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6436  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6437  */
6438 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6439 	struct sock *sk;
6440 };
6441 
6442 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6443 	struct sock *sk;
6444 };
6445 
6446 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6447 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6448 	struct seq_file *seq;
6449 };
6450 
6451 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6452 	struct bpf_iter_meta *meta;
6453 	struct task_struct *task;
6454 };
6455 
6456 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6457 	struct file *file;
6458 };
6459 
6460 BTF_TYPE_SAFE_TRUSTED(struct file) {
6461 	struct inode *f_inode;
6462 };
6463 
6464 /*
6465  * The pointer fields in the sched_ext ops argument containers are pinned by the
6466  * callers for the duration of the ops calls and are never NULL.
6467  */
6468 BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) {
6469 #ifdef CONFIG_EXT_GROUP_SCHED
6470 	struct cgroup *cgroup;
6471 #endif
6472 };
6473 
6474 BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) {
6475 	struct task_struct *task;
6476 };
6477 
6478 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) {
6479 	struct sched_ext_ops *ops;
6480 };
6481 
6482 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) {
6483 	struct sched_ext_ops *ops;
6484 };
6485 
6486 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
6487 	struct inode *d_inode;
6488 };
6489 
6490 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm) {
6491 	struct mm_struct *mm;
6492 };
6493 
6494 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6495 	struct sock *sk;
6496 };
6497 
6498 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
6499 	struct mm_struct *vm_mm;
6500 	struct file *vm_file;
6501 };
6502 
6503 static bool type_is_rcu(struct bpf_verifier_env *env,
6504 			struct bpf_reg_state *reg,
6505 			const char *field_name, u32 btf_id)
6506 {
6507 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6508 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6509 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6510 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
6511 
6512 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6513 }
6514 
6515 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6516 				struct bpf_reg_state *reg,
6517 				const char *field_name, u32 btf_id)
6518 {
6519 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6520 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6521 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6522 
6523 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6524 }
6525 
6526 static bool type_is_trusted(struct bpf_verifier_env *env,
6527 			    struct bpf_reg_state *reg,
6528 			    const char *field_name, u32 btf_id)
6529 {
6530 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6531 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6532 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6533 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6534 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args));
6535 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args));
6536 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args));
6537 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args));
6538 
6539 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6540 }
6541 
6542 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6543 				    struct bpf_reg_state *reg,
6544 				    const char *field_name, u32 btf_id)
6545 {
6546 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6547 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
6548 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm));
6549 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
6550 
6551 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6552 					  "__safe_trusted_or_null");
6553 }
6554 
6555 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6556 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6557 				   argno_t argno, int off, int size,
6558 				   enum bpf_access_type atype,
6559 				   int value_regno)
6560 {
6561 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6562 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6563 	const char *field_name = NULL;
6564 	enum bpf_type_flag flag = 0;
6565 	u32 btf_id = 0;
6566 	s64 min_off;
6567 	int ret;
6568 
6569 	if (!env->allow_ptr_leaks) {
6570 		verbose(env,
6571 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6572 			tname);
6573 		return -EPERM;
6574 	}
6575 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6576 		verbose(env,
6577 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6578 			tname);
6579 		return -EINVAL;
6580 	}
6581 
6582 	if (check_add_overflow(reg_smin(reg), off, &min_off)) {
6583 		verbose(env,
6584 			"%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n",
6585 			reg_arg_name(env, argno), tname, reg_smin(reg), off);
6586 		return -EACCES;
6587 	}
6588 
6589 	if (min_off < 0) {
6590 		verbose(env,
6591 			"%s is ptr_%s invalid negative access: off=%lld\n",
6592 			reg_arg_name(env, argno), tname, min_off);
6593 		return -EACCES;
6594 	}
6595 
6596 	if (reg->type & MEM_USER) {
6597 		verbose(env,
6598 			"%s is ptr_%s access user memory\n",
6599 			reg_arg_name(env, argno), tname);
6600 		return -EACCES;
6601 	}
6602 
6603 	if (reg->type & MEM_PERCPU) {
6604 		verbose(env,
6605 			"%s is ptr_%s access percpu memory\n",
6606 			reg_arg_name(env, argno), tname);
6607 		return -EACCES;
6608 	}
6609 
6610 	if (atype != BPF_READ && bpf_may_fault_on_deref(reg->type)) {
6611 		verbose(env, "only read is supported\n");
6612 		return -EACCES;
6613 	}
6614 
6615 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6616 		if (!tnum_is_const(reg->var_off)) {
6617 			char tn_buf[48];
6618 
6619 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6620 			verbose(env,
6621 				"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6622 				reg_arg_name(env, argno), tname, off, tn_buf);
6623 			return -EACCES;
6624 		}
6625 
6626 		off += reg->var_off.value;
6627 
6628 		if (!btf_is_kernel(reg->btf)) {
6629 			verifier_bug(env, "reg->btf must be kernel btf");
6630 			return -EFAULT;
6631 		}
6632 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6633 		if (ret < 0)
6634 			verbose(env,
6635 				"%s cannot write into ptr_%s at off=%d size=%d\n",
6636 				reg_arg_name(env, argno), tname, off, size);
6637 	} else {
6638 		/* Writes are permitted with default btf_struct_access for
6639 		 * program allocated objects (which always have id > 0).
6640 		 */
6641 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6642 			verbose(env, "only read is supported\n");
6643 			return -EACCES;
6644 		}
6645 
6646 		/*
6647 		 * A fault-prone allocated object may still be read through a
6648 		 * BPF_PROBE_MEM load after its lifetime protection ends. Writes
6649 		 * through such pointers were rejected above.
6650 		 */
6651 		if (type_is_alloc(reg->type) && !bpf_may_fault_on_deref(reg->type) &&
6652 		    !type_is_non_owning_ref(reg->type) &&
6653 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
6654 			verifier_bug(env, "allocated object must have a referenced id");
6655 			return -EFAULT;
6656 		}
6657 
6658 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6659 	}
6660 
6661 	if (ret < 0)
6662 		return ret;
6663 
6664 	if (ret != PTR_TO_BTF_ID) {
6665 		/* just mark; */
6666 
6667 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6668 		/* If this is an untrusted pointer, all pointers formed by walking it
6669 		 * also inherit the untrusted flag.
6670 		 */
6671 		flag = PTR_UNTRUSTED;
6672 
6673 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
6674 		/* By default any pointer obtained from walking a trusted pointer is no
6675 		 * longer trusted, unless the field being accessed has explicitly been
6676 		 * marked as inheriting its parent's state of trust (either full or RCU).
6677 		 * For example:
6678 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6679 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6680 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6681 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6682 		 *
6683 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6684 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6685 		 */
6686 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6687 			flag |= PTR_TRUSTED;
6688 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6689 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6690 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6691 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6692 				/* ignore __rcu tag and mark it MEM_RCU */
6693 				flag |= MEM_RCU;
6694 			} else if (flag & MEM_RCU ||
6695 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6696 				/* __rcu tagged pointers can be NULL */
6697 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6698 
6699 				/* We always trust them */
6700 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6701 				    flag & PTR_UNTRUSTED)
6702 					flag &= ~PTR_UNTRUSTED;
6703 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6704 				/* keep as-is */
6705 			} else {
6706 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6707 				clear_trusted_flags(&flag);
6708 			}
6709 		} else {
6710 			/*
6711 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6712 			 * aggressively mark as untrusted otherwise such
6713 			 * pointers will be plain PTR_TO_BTF_ID without flags
6714 			 * and will be allowed to be passed into helpers for
6715 			 * compat reasons.
6716 			 */
6717 			flag = PTR_UNTRUSTED;
6718 		}
6719 	} else {
6720 		/* Old compat. Deprecated */
6721 		clear_trusted_flags(&flag);
6722 	}
6723 
6724 	if (atype == BPF_READ && value_regno >= 0) {
6725 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6726 		if (ret < 0)
6727 			return ret;
6728 	}
6729 
6730 	return 0;
6731 }
6732 
6733 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6734 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6735 				   argno_t argno, int off, int size,
6736 				   enum bpf_access_type atype,
6737 				   int value_regno)
6738 {
6739 	struct bpf_map *map = reg->map_ptr;
6740 	struct bpf_reg_state map_reg;
6741 	enum bpf_type_flag flag = 0;
6742 	const struct btf_type *t;
6743 	const char *tname;
6744 	u32 btf_id;
6745 	int ret;
6746 
6747 	if (!btf_vmlinux) {
6748 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6749 		return -ENOTSUPP;
6750 	}
6751 
6752 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6753 		verbose(env, "map_ptr access not supported for map type %d\n",
6754 			map->map_type);
6755 		return -ENOTSUPP;
6756 	}
6757 
6758 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6759 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6760 
6761 	if (!env->allow_ptr_leaks) {
6762 		verbose(env,
6763 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6764 			tname);
6765 		return -EPERM;
6766 	}
6767 
6768 	if (off < 0) {
6769 		verbose(env, "%s is %s invalid negative access: off=%d\n",
6770 			reg_arg_name(env, argno), tname, off);
6771 		return -EACCES;
6772 	}
6773 
6774 	if (atype != BPF_READ) {
6775 		verbose(env, "only read from %s is supported\n", tname);
6776 		return -EACCES;
6777 	}
6778 
6779 	/* Simulate access to a PTR_TO_BTF_ID */
6780 	memset(&map_reg, 0, sizeof(map_reg));
6781 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
6782 			      btf_vmlinux, *map->ops->map_btf_id, 0);
6783 	if (ret < 0)
6784 		return ret;
6785 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6786 	if (ret < 0)
6787 		return ret;
6788 
6789 	if (value_regno >= 0) {
6790 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6791 		if (ret < 0)
6792 			return ret;
6793 	}
6794 
6795 	return 0;
6796 }
6797 
6798 /*
6799  * Check that the stack access at the given offset is within bounds. The
6800  * maximum valid offset is -1.
6801  *
6802  * The minimum valid offset is -env->stack_limit for writes, and
6803  * -state->allocated_stack for reads.
6804  */
6805 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6806                                           s64 off,
6807                                           struct bpf_func_state *state,
6808                                           enum bpf_access_type t)
6809 {
6810 	int min_valid_off;
6811 
6812 	if (t == BPF_WRITE || env->allow_uninit_stack)
6813 		min_valid_off = -(int)env->stack_limit;
6814 	else
6815 		min_valid_off = -state->allocated_stack;
6816 
6817 	if (off < min_valid_off || off > -1)
6818 		return -EACCES;
6819 	return 0;
6820 }
6821 
6822 /* Check that the stack access at 'regno + off' falls within the maximum stack
6823  * bounds.
6824  *
6825  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6826  */
6827 static int check_stack_access_within_bounds(
6828 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6829 		argno_t argno, int off, int access_size,
6830 		enum bpf_access_type type)
6831 {
6832 	struct bpf_func_state *state = bpf_func(env, reg);
6833 	s64 min_off, max_off;
6834 	int err;
6835 	char *err_extra;
6836 
6837 	if (type == BPF_READ)
6838 		err_extra = " read from";
6839 	else
6840 		err_extra = " write to";
6841 
6842 	if (tnum_is_const(reg->var_off)) {
6843 		min_off = (s64)reg->var_off.value + off;
6844 		max_off = min_off + access_size;
6845 	} else {
6846 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
6847 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
6848 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
6849 				err_extra, reg_arg_name(env, argno));
6850 			return -EACCES;
6851 		}
6852 		min_off = reg_smin(reg) + off;
6853 		max_off = reg_smax(reg) + off + access_size;
6854 	}
6855 
6856 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6857 	if (!err && max_off > 0)
6858 		err = -EINVAL; /* out of stack access into non-negative offsets */
6859 	if (!err && access_size < 0)
6860 		/* access_size should not be negative (or overflow an int); others checks
6861 		 * along the way should have prevented such an access.
6862 		 */
6863 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6864 
6865 	if (err) {
6866 		if (tnum_is_const(reg->var_off)) {
6867 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
6868 				err_extra, reg_arg_name(env, argno), min_off, access_size);
6869 		} else {
6870 			char tn_buf[48];
6871 
6872 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6873 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
6874 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
6875 		}
6876 		return err;
6877 	}
6878 
6879 	/*
6880 	 * Every stack access passes through here, including buffers passed to
6881 	 * helpers and kfuncs and accesses into a caller's frame, so check the
6882 	 * fastcall contract of the frame that owns the slots once for all of
6883 	 * them. Zero-sized accesses touch no stack and keep the rewrite enabled.
6884 	 */
6885 	if (access_size)
6886 		check_fastcall_stack_contract(env, state, env->insn_idx, min_off);
6887 
6888 	/* Note that there is no stack access with offset zero, so the needed stack
6889 	 * size is -min_off, not -min_off+1.
6890 	 */
6891 	return bpf_grow_stack_state(env, state, -min_off /* size */);
6892 }
6893 
6894 static bool get_func_retval_range(struct bpf_prog *prog,
6895 				  struct bpf_retval_range *range)
6896 {
6897 	if (prog->type == BPF_PROG_TYPE_LSM &&
6898 		prog->expected_attach_type == BPF_LSM_MAC &&
6899 		!bpf_lsm_get_retval_range(prog, range)) {
6900 		return true;
6901 	}
6902 	return false;
6903 }
6904 
6905 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
6906 {
6907 	struct bpf_reg_state fake_reg;
6908 
6909 	if (!val)
6910 		return;
6911 
6912 	fake_reg.type = SCALAR_VALUE;
6913 	__mark_reg_known(&fake_reg, val);
6914 
6915 	scalar_step_add(dst_reg, dst_reg, &fake_reg);
6916 	scalar32_min_max_add(dst_reg, &fake_reg);
6917 	scalar_min_max_add(dst_reg, &fake_reg);
6918 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
6919 
6920 	reg_bounds_sync(dst_reg);
6921 }
6922 
6923 /* there is no support for callx in the interpreter */
6924 static int require_callx_jit(struct bpf_verifier_env *env)
6925 {
6926 	if (!env->prog->jit_requested) {
6927 		verbose(env, "JIT is required to use callx\n");
6928 		return -EOPNOTSUPP;
6929 	}
6930 	if (!bpf_jit_supports_callx()) {
6931 		verbose(env, "JIT doesn't support callx\n");
6932 		return -EOPNOTSUPP;
6933 	}
6934 	env->prog->jit_required = true;
6935 	return 0;
6936 }
6937 
6938 static void mark_reg_func_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
6939 			      int regno, int subprog)
6940 {
6941 	mark_reg_known_zero(env, regs, regno);
6942 	regs[regno].type = PTR_TO_FUNC;
6943 	regs[regno].subprogno = subprog;
6944 }
6945 
6946 /* a read from a table of functions branches into that many states at most */
6947 #define BPF_MAX_FUNC_PTR_TARGETS 64
6948 /* and that many pointers at most are next to what is read at variable offset */
6949 #define BPF_MAX_FUNC_PTR_RANGE 4096
6950 
6951 /* Count up to 'limit' offsets in [min_off, max_off] that the read is possible at */
6952 static u32 count_read_offsets(struct tnum offs, u64 min_off, u64 max_off, u32 limit)
6953 {
6954 	u64 o = min_off, next;
6955 	u32 cnt = 0;
6956 
6957 	if (!tnum_in(offs, tnum_const(o))) {
6958 		next = tnum_step(offs, o);
6959 		if (next <= o)
6960 			return 0;
6961 		o = next;
6962 	}
6963 	while (o <= max_off && cnt < limit) {
6964 		cnt++;
6965 		next = tnum_step(offs, o);
6966 		if (next <= o)
6967 			break;
6968 		o = next;
6969 	}
6970 	return cnt;
6971 }
6972 
6973 /*
6974  * A read from a frozen read-only map that has pointers to functions, see
6975  * resolve_func_ptrs(). The bounds and var_off of the offset tell where the read
6976  * is possible at, e.g. var_off is the stride of the elements of an array.
6977  * A read of exactly one pointer yields PTR_TO_FUNC. When the offset is variable
6978  * and only pointers can be read, which is how an element of a table of
6979  * functions is loaded, the verification continues with each of them. Other
6980  * reads that overlap with a pointer are rejected, because their result is not
6981  * known until the program is jitted.
6982  *
6983  * Return -ENOENT if there are no pointers to functions in the bytes that are read.
6984  */
6985 static int check_func_ptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
6986 			       int size, int value_regno)
6987 {
6988 	u64 min_off = reg_umin(reg) + off, max_off = reg_umax(reg) + off;
6989 	struct tnum offs = tnum_add(reg->var_off, tnum_const(off));
6990 	struct bpf_reg_state *regs = cur_regs(env);
6991 	struct bpf_map *map = reg->map_ptr;
6992 	struct bpf_verifier_state *branch;
6993 	int subprog, targets[BPF_MAX_FUNC_PTR_TARGETS];
6994 	struct bpf_func_ptr *ptrs;
6995 	u32 i, cnt, n = 0;
6996 	u64 o, lo, hi;
6997 	int err;
6998 
6999 	ptrs = bpf_map_range_func_ptrs(env, map, min_off, max_off - min_off + size, &cnt);
7000 	if (!ptrs)
7001 		return -ENOENT;
7002 	if (cnt > BPF_MAX_FUNC_PTR_RANGE)
7003 		goto overlap;
7004 
7005 	for (i = 0; i < cnt; i++) {
7006 		/* the offsets at which the read overlaps with the pointer */
7007 		lo = ptrs[i].map_off >= size ? ptrs[i].map_off - size + 1 : 0;
7008 		lo = max(lo, min_off);
7009 		hi = min(ptrs[i].map_off + sizeof(u64) - 1, max_off);
7010 		for (o = lo; o <= hi; o++) {
7011 			if (!tnum_in(offs, tnum_const(o)))
7012 				continue;
7013 			if (o != ptrs[i].map_off || size != sizeof(u64) || value_regno < 0)
7014 				goto overlap;
7015 			if (n == BPF_MAX_FUNC_PTR_TARGETS) {
7016 				verbose(env, "read from map '%s' may yield more than %d pointers to functions\n",
7017 					map->name, BPF_MAX_FUNC_PTR_TARGETS);
7018 				return -E2BIG;
7019 			}
7020 			subprog = bpf_find_subprog(env, ptrs[i].xlated_off);
7021 			if (verifier_bug_if(subprog <= 0, env,
7022 					    "no function at insn %u for map '%s' offset %u",
7023 					    ptrs[i].xlated_off, map->name, ptrs[i].map_off))
7024 				return -EFAULT;
7025 			targets[n++] = subprog;
7026 		}
7027 	}
7028 	/* pointers are next to what is read, e.g. the data of an array of vtables */
7029 	if (!n)
7030 		return -ENOENT;
7031 	/* either every offset that the read is possible at is a pointer or none */
7032 	if (count_read_offsets(offs, min_off, max_off, n + 1) != n)
7033 		goto overlap;
7034 
7035 	/* the map has the offset of the function until the program is jitted */
7036 	err = require_callx_jit(env);
7037 	if (err)
7038 		return err;
7039 
7040 	for (i = 0; i < n - 1; i++) {
7041 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx,
7042 				    env->cur_state->speculative);
7043 		if (IS_ERR(branch))
7044 			return PTR_ERR(branch);
7045 		mark_reg_func_ptr(env, branch->frame[branch->curframe]->regs, value_regno,
7046 				  targets[i]);
7047 	}
7048 	mark_reg_func_ptr(env, regs, value_regno, targets[n - 1]);
7049 	return 0;
7050 
7051 overlap:
7052 	verbose(env, "read of %d bytes at offset [%llu,%llu] of map '%s' overlaps with a pointer to a function\n",
7053 		size, min_off, max_off, map->name);
7054 	return -EACCES;
7055 }
7056 
7057 static int check_map_mem_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
7058 			      int bpf_size, int value_regno, bool is_ldsx)
7059 {
7060 	struct bpf_reg_state *regs = cur_regs(env);
7061 	int size = bpf_size_to_bytes(bpf_size);
7062 	struct bpf_map *map = reg->map_ptr;
7063 	int err;
7064 
7065 	switch (map->map_type) {
7066 	case BPF_MAP_TYPE_INSN_ARRAY:
7067 		if (bpf_size != BPF_DW) {
7068 			verbose(env, "Invalid read of %d bytes from insn_array\n", size);
7069 			return -EACCES;
7070 		}
7071 		regs[value_regno] = *reg;
7072 		add_scalar_to_reg(&regs[value_regno], off);
7073 		regs[value_regno].type = PTR_TO_INSN;
7074 		return 0;
7075 	case BPF_MAP_TYPE_PERCPU_ARRAY:
7076 		goto reg_unknown;
7077 	default:
7078 		break;
7079 	}
7080 
7081 	if (env->func_ptr_cnt) {
7082 		err = check_func_ptr_read(env, reg, off, size, value_regno);
7083 		if (err != -ENOENT)
7084 			return err;
7085 	}
7086 
7087 	/* If map is read-only, track its contents as scalars. */
7088 	if (tnum_is_const(reg->var_off) &&
7089 	    bpf_map_is_rdonly(map) &&
7090 	    map->ops->map_direct_value_addr) {
7091 		int map_off = off + reg->var_off.value;
7092 		u64 val = 0;
7093 
7094 		err = bpf_map_direct_read(map, map_off, size, &val, is_ldsx);
7095 		if (err)
7096 			return err;
7097 
7098 		regs[value_regno].type = SCALAR_VALUE;
7099 		__mark_reg_known(&regs[value_regno], val);
7100 		return 0;
7101 	}
7102 
7103 reg_unknown:
7104 	mark_reg_unknown(env, regs, value_regno);
7105 	return 0;
7106 }
7107 
7108 /* check whether memory at (regno + off) is accessible for t = (read | write)
7109  * if t==write, value_regno is a register which value is stored into memory
7110  * if t==read, value_regno is a register which will receive the value from memory
7111  * if t==write && value_regno==-1, some unknown value is stored into memory
7112  * if t==read && value_regno==-1, don't care what we read from memory
7113  */
7114 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
7115 			    int off, int bpf_size, enum bpf_access_type t,
7116 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7117 {
7118 	struct bpf_reg_state *regs = cur_regs(env);
7119 	enum bpf_reg_type ptr_type = reg->type;
7120 	int size, err = 0;
7121 
7122 	size = bpf_size_to_bytes(bpf_size);
7123 	if (size < 0)
7124 		return size;
7125 
7126 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7127 	if (err)
7128 		return err;
7129 
7130 	if (reg->type == PTR_TO_MAP_KEY) {
7131 		if (t == BPF_WRITE) {
7132 			verbose(env, "write to change key %s not allowed\n",
7133 				reg_arg_name(env, argno));
7134 			return -EACCES;
7135 		}
7136 
7137 		err = check_mem_region_access(env, reg, argno, off, size,
7138 					      reg->map_ptr->key_size, false);
7139 		if (err)
7140 			return err;
7141 		if (value_regno >= 0)
7142 			mark_reg_unknown(env, regs, value_regno);
7143 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7144 		struct btf_field *kptr_field = NULL;
7145 
7146 		if (t == BPF_WRITE && value_regno >= 0 &&
7147 		    is_pointer_value(env, value_regno)) {
7148 			verbose(env, "R%d leaks addr into map\n", value_regno);
7149 			return -EACCES;
7150 		}
7151 		err = check_map_access_type(env, reg, off, size, t);
7152 		if (err)
7153 			return err;
7154 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
7155 		if (err)
7156 			return err;
7157 		if (tnum_is_const(reg->var_off))
7158 			kptr_field = btf_record_find(reg->map_ptr->record,
7159 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7160 		if (kptr_field) {
7161 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
7162 		} else if (t == BPF_READ && value_regno >= 0) {
7163 			err = check_map_mem_read(env, reg, off, bpf_size, value_regno, is_ldsx);
7164 		}
7165 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7166 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7167 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7168 
7169 		if (type_may_be_null(reg->type)) {
7170 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7171 				reg_type_str(env, reg->type));
7172 			bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7173 					       reg_arg_name(env, argno), reg,
7174 						      BPF_DIAG_DEREF_NULLABLE_PTR, 0);
7175 			return -EACCES;
7176 		}
7177 
7178 		if (t == BPF_WRITE && rdonly_mem) {
7179 			verbose(env, "%s cannot write into %s\n",
7180 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7181 			return -EACCES;
7182 		}
7183 
7184 		if (t == BPF_WRITE && value_regno >= 0 &&
7185 		    is_pointer_value(env, value_regno)) {
7186 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7187 			return -EACCES;
7188 		}
7189 
7190 		if (rdonly_untrusted && !env->allow_ptr_leaks) {
7191 			verbose(env, "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7192 				reg_type_str(env, reg->type));
7193 			bpf_diag_policy(env, insn_idx, "read from untrusted read-only memory",
7194 					"the access requires CAP_PERFMON",
7195 					"Load the program with CAP_PERFMON, or avoid dereferencing untrusted pointers.");
7196 			return -EPERM;
7197 		}
7198 
7199 		/*
7200 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7201 		 * instructions, hence no need to check bounds in that case.
7202 		 */
7203 		if (!rdonly_untrusted)
7204 			err = check_mem_region_access(env, reg, argno, off, size,
7205 						      reg->mem_size, false);
7206 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7207 			mark_reg_unknown(env, regs, value_regno);
7208 	} else if (reg->type == PTR_TO_CTX) {
7209 		struct bpf_insn_access_aux info = {
7210 			.reg_type = SCALAR_VALUE,
7211 			.is_ldsx = is_ldsx,
7212 			.log = &env->log,
7213 		};
7214 		struct bpf_retval_range range;
7215 
7216 		if (t == BPF_WRITE && value_regno >= 0 &&
7217 		    is_pointer_value(env, value_regno)) {
7218 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7219 			return -EACCES;
7220 		}
7221 
7222 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
7223 		if (!err && t == BPF_READ && value_regno >= 0) {
7224 			/* ctx access returns either a scalar, or a
7225 			 * PTR_TO_PACKET[_META,_END]. In the latter
7226 			 * case, we know the offset is zero.
7227 			 */
7228 			if (info.reg_type == SCALAR_VALUE) {
7229 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7230 					mark_reg_unknown(env, regs, value_regno);
7231 					err = __mark_reg_s32_range(env, regs, value_regno,
7232 								   range.minval, range.maxval);
7233 					if (err)
7234 						return err;
7235 				} else {
7236 					mark_reg_unknown(env, regs, value_regno);
7237 				}
7238 			} else {
7239 				mark_reg_known_zero(env, regs,
7240 						    value_regno);
7241 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7242 					regs[value_regno].btf = info.btf;
7243 					regs[value_regno].btf_id = info.btf_id;
7244 					regs[value_regno].id = info.ref_id;
7245 				} else if (base_type(info.reg_type) == PTR_TO_MEM) {
7246 					regs[value_regno].mem_size = info.mem_size;
7247 				}
7248 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
7249 					regs[value_regno].id = ++env->id_gen;
7250 			}
7251 			regs[value_regno].type = info.reg_type;
7252 		}
7253 
7254 	} else if (reg->type == PTR_TO_STACK) {
7255 		/* Basic bounds checks. */
7256 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
7257 		if (err)
7258 			return err;
7259 
7260 		if (t == BPF_READ)
7261 			err = check_stack_read(env, reg, argno, off, size,
7262 					       value_regno);
7263 		else
7264 			err = check_stack_write(env, reg, off, size,
7265 						value_regno, insn_idx);
7266 	} else if (reg_is_pkt_pointer(reg)) {
7267 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7268 			verbose(env, "cannot write into packet\n");
7269 			return -EACCES;
7270 		}
7271 		if (t == BPF_WRITE && value_regno >= 0 &&
7272 		    is_pointer_value(env, value_regno)) {
7273 			verbose(env, "R%d leaks addr into packet\n",
7274 				value_regno);
7275 			return -EACCES;
7276 		}
7277 		err = check_packet_access(env, reg, argno, off, size, false);
7278 		if (!err && t == BPF_READ && value_regno >= 0)
7279 			mark_reg_unknown(env, regs, value_regno);
7280 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7281 		if (t == BPF_WRITE && value_regno >= 0 &&
7282 		    is_pointer_value(env, value_regno)) {
7283 			verbose(env, "R%d leaks addr into flow keys\n",
7284 				value_regno);
7285 			return -EACCES;
7286 		}
7287 
7288 		err = check_flow_keys_access(env, reg, argno, off, size);
7289 		if (!err && t == BPF_READ && value_regno >= 0)
7290 			mark_reg_unknown(env, regs, value_regno);
7291 	} else if (type_is_sk_pointer(reg->type)) {
7292 		if (t == BPF_WRITE) {
7293 			verbose(env, "%s cannot write into %s\n",
7294 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7295 			return -EACCES;
7296 		}
7297 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
7298 		if (!err && value_regno >= 0)
7299 			mark_reg_unknown(env, regs, value_regno);
7300 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7301 		err = check_tp_buffer_access(env, reg, argno, off, size);
7302 		if (!err && t == BPF_READ && value_regno >= 0)
7303 			mark_reg_unknown(env, regs, value_regno);
7304 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7305 		   !type_may_be_null(reg->type)) {
7306 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
7307 					      value_regno);
7308 	} else if (reg->type == CONST_PTR_TO_MAP) {
7309 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
7310 					      value_regno);
7311 	} else if (base_type(reg->type) == PTR_TO_BUF &&
7312 		   !type_may_be_null(reg->type)) {
7313 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7314 		u32 *max_access;
7315 
7316 		if (rdonly_mem) {
7317 			if (t == BPF_WRITE) {
7318 				verbose(env, "%s cannot write into %s\n",
7319 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7320 				return -EACCES;
7321 			}
7322 			max_access = &env->prog->aux->max_rdonly_access;
7323 		} else {
7324 			max_access = &env->prog->aux->max_rdwr_access;
7325 		}
7326 
7327 		err = check_buffer_access(env, reg, argno, off, size, false,
7328 					  max_access);
7329 
7330 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7331 			mark_reg_unknown(env, regs, value_regno);
7332 	} else if (reg->type == PTR_TO_ARENA) {
7333 		if (t == BPF_READ && value_regno >= 0)
7334 			mark_reg_unknown(env, regs, value_regno);
7335 	} else {
7336 		enum bpf_diag_invalid_deref_kind kind = BPF_DIAG_DEREF_INVALID_PTR;
7337 
7338 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7339 			reg_type_str(env, reg->type));
7340 		if (reg->type == SCALAR_VALUE)
7341 			kind = BPF_DIAG_DEREF_SCALAR;
7342 		else if (type_may_be_null(reg->type))
7343 			kind = BPF_DIAG_DEREF_NULLABLE_PTR;
7344 		bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7345 				       reg_arg_name(env, argno), reg, kind, 0);
7346 		return -EACCES;
7347 	}
7348 
7349 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7350 	    regs[value_regno].type == SCALAR_VALUE) {
7351 		if (!is_ldsx) {
7352 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7353 			coerce_reg_to_size(&regs[value_regno], size);
7354 		} else {
7355 			/*
7356 			 * Sign-extension can change the register value relative
7357 			 * to a scalar it is linked with by id (e.g. a zero-
7358 			 * extending fill of the same spilled stack slot), thus
7359 			 * drop the shared id in that case.
7360 			 */
7361 			bool no_sext = reg_umax(&regs[value_regno]) <
7362 					(1ULL << (size * BITS_PER_BYTE - 1));
7363 
7364 			coerce_reg_to_size_sx(&regs[value_regno], size);
7365 			if (!no_sext)
7366 				clear_scalar_id(&regs[value_regno]);
7367 		}
7368 	}
7369 
7370 	if (!err && bpf_is_mem_insn(&env->prog->insnsi[insn_idx]) && ptr_type != PTR_TO_STACK)
7371 		mark_non_stack_access(env, insn_idx);
7372 
7373 	return err;
7374 }
7375 
7376 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7377 			     bool allow_trust_mismatch);
7378 
7379 /*
7380  * Returns the register to check the access of the current insn with.
7381  * For a number in a program with an arena that is 'arena'.
7382  */
7383 static struct bpf_reg_state *mem_access_reg(struct bpf_verifier_env *env, int regno,
7384 					    struct bpf_reg_state *arena)
7385 {
7386 	if (!is_arena_scalar(env, regno))
7387 		return cur_regs(env) + regno;
7388 
7389 	memset(arena, 0, sizeof(*arena));
7390 	arena->type = PTR_TO_ARENA;
7391 	env->insn_aux_data[env->insn_idx].arena_scalar = true;
7392 	return arena;
7393 }
7394 
7395 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7396 			  bool strict_alignment_once, bool is_ldsx,
7397 			  bool allow_trust_mismatch, const char *ctx)
7398 {
7399 	struct bpf_verifier_state *vstate = env->cur_state;
7400 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7401 	struct bpf_reg_state *regs = cur_regs(env);
7402 	struct bpf_reg_state arena, *src_reg;
7403 	enum bpf_reg_type src_reg_type;
7404 	int err;
7405 
7406 	/* Handle stack arg read */
7407 	if (is_stack_arg_ldx(insn)) {
7408 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7409 		if (err)
7410 			return err;
7411 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
7412 	}
7413 
7414 	/* check src operand */
7415 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7416 	if (err)
7417 		return err;
7418 
7419 	/* check dst operand */
7420 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7421 	if (err)
7422 		return err;
7423 
7424 	src_reg = mem_access_reg(env, insn->src_reg, &arena);
7425 	src_reg_type = src_reg->type;
7426 
7427 	/*
7428 	 * check_stack_read_fixed_off() may refine the modification's origin to
7429 	 * the source stack slot.
7430 	 */
7431 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
7432 	err = check_mem_access(env, env->insn_idx, src_reg, argno_from_reg(insn->src_reg),
7433 			       insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7434 			       strict_alignment_once, is_ldsx);
7435 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7436 				       allow_trust_mismatch);
7437 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7438 	if (!err)
7439 		bpf_diag_mod_end(env);
7440 
7441 	return err;
7442 }
7443 
7444 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7445 			   bool strict_alignment_once)
7446 {
7447 	struct bpf_verifier_state *vstate = env->cur_state;
7448 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7449 	struct bpf_reg_state *regs = cur_regs(env);
7450 	struct bpf_reg_state arena, *dst_reg;
7451 	enum bpf_reg_type dst_reg_type;
7452 	int err;
7453 
7454 	/* Handle stack arg write */
7455 	if (is_stack_arg_stx(insn)) {
7456 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
7457 		if (err)
7458 			return err;
7459 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
7460 	}
7461 
7462 	/* check src1 operand */
7463 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7464 	if (err)
7465 		return err;
7466 
7467 	/* check src2 operand */
7468 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7469 	if (err)
7470 		return err;
7471 
7472 	dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
7473 	dst_reg_type = dst_reg->type;
7474 
7475 	/* Check if (dst_reg + off) is writeable. */
7476 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
7477 			       insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7478 			       strict_alignment_once, false);
7479 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7480 
7481 	return err;
7482 }
7483 
7484 static int check_atomic_rmw(struct bpf_verifier_env *env,
7485 			    struct bpf_insn *insn)
7486 {
7487 	struct bpf_reg_state arena, *dst_reg;
7488 	int load_reg;
7489 	int err;
7490 
7491 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7492 		verbose(env, "invalid atomic operand size\n");
7493 		return -EINVAL;
7494 	}
7495 
7496 	/* check src1 operand */
7497 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7498 	if (err)
7499 		return err;
7500 
7501 	/* check src2 operand */
7502 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7503 	if (err)
7504 		return err;
7505 
7506 	if (insn->imm == BPF_CMPXCHG) {
7507 		/* Check comparison of R0 with memory location */
7508 		const u32 aux_reg = BPF_REG_0;
7509 
7510 		err = check_reg_arg(env, aux_reg, SRC_OP);
7511 		if (err)
7512 			return err;
7513 
7514 		if (is_pointer_value(env, aux_reg)) {
7515 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7516 			return -EACCES;
7517 		}
7518 	}
7519 
7520 	if (is_pointer_value(env, insn->src_reg)) {
7521 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7522 		return -EACCES;
7523 	}
7524 
7525 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7526 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7527 			insn->dst_reg,
7528 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7529 		return -EACCES;
7530 	}
7531 
7532 	/* load_reg may be dst_reg. Look at dst_reg before it's marked as unknown. */
7533 	dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
7534 
7535 	load_reg = bpf_atomic_load_reg(insn);
7536 	if (load_reg >= 0) {
7537 		/* check and record load of old value */
7538 		err = check_reg_arg(env, load_reg, DST_OP);
7539 		if (err)
7540 			return err;
7541 	}
7542 
7543 	/* Check whether we can read the memory, with second call for fetch
7544 	 * case to simulate the register fill.
7545 	 */
7546 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7547 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7548 	if (!err && load_reg >= 0) {
7549 		bpf_diag_mod_begin(env, cur_regs(env) + load_reg, NULL, BPF_DIAG_MOD_WRITE);
7550 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
7551 				       insn->off, BPF_SIZE(insn->code),
7552 				       BPF_READ, load_reg, true, false);
7553 		if (!err)
7554 			bpf_diag_mod_end(env);
7555 	}
7556 	if (err)
7557 		return err;
7558 
7559 	err = save_aux_ptr_type(env, dst_reg->type, false);
7560 	if (err)
7561 		return err;
7562 	/* Check whether we can write into the same memory. */
7563 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7564 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7565 	if (err)
7566 		return err;
7567 	return 0;
7568 }
7569 
7570 static int check_atomic_load(struct bpf_verifier_env *env,
7571 			     struct bpf_insn *insn)
7572 {
7573 	int err;
7574 
7575 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7576 	if (err)
7577 		return err;
7578 
7579 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7580 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7581 			insn->src_reg,
7582 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7583 		return -EACCES;
7584 	}
7585 
7586 	return check_load_mem(env, insn, true, false, false, "atomic_load");
7587 }
7588 
7589 static int check_atomic_store(struct bpf_verifier_env *env,
7590 			      struct bpf_insn *insn)
7591 {
7592 	int err;
7593 
7594 	err = check_store_reg(env, insn, true);
7595 	if (err)
7596 		return err;
7597 
7598 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7599 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7600 			insn->dst_reg,
7601 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7602 		return -EACCES;
7603 	}
7604 
7605 	return 0;
7606 }
7607 
7608 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7609 {
7610 	switch (insn->imm) {
7611 	case BPF_ADD:
7612 	case BPF_ADD | BPF_FETCH:
7613 	case BPF_AND:
7614 	case BPF_AND | BPF_FETCH:
7615 	case BPF_OR:
7616 	case BPF_OR | BPF_FETCH:
7617 	case BPF_XOR:
7618 	case BPF_XOR | BPF_FETCH:
7619 	case BPF_XCHG:
7620 	case BPF_CMPXCHG:
7621 		return check_atomic_rmw(env, insn);
7622 	case BPF_LOAD_ACQ:
7623 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7624 			verbose(env,
7625 				"64-bit load-acquires are only supported on 64-bit arches\n");
7626 			return -EOPNOTSUPP;
7627 		}
7628 		return check_atomic_load(env, insn);
7629 	case BPF_STORE_REL:
7630 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7631 			verbose(env,
7632 				"64-bit store-releases are only supported on 64-bit arches\n");
7633 			return -EOPNOTSUPP;
7634 		}
7635 		return check_atomic_store(env, insn);
7636 	default:
7637 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7638 			insn->imm);
7639 		return -EINVAL;
7640 	}
7641 }
7642 
7643 /* When register 'regno' is used to read the stack (either directly or through
7644  * a helper function) make sure that it's within stack boundary and, depending
7645  * on the access type and privileges, that all elements of the stack are
7646  * initialized.
7647  *
7648  * All registers that have been spilled on the stack in the slots within the
7649  * read offsets are marked as read.
7650  */
7651 static int check_stack_range_initialized(
7652 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
7653 		int access_size, bool zero_size_allowed,
7654 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7655 {
7656 	struct bpf_func_state *state = bpf_func(env, reg);
7657 	int err, min_off, max_off, i, j, slot, spi;
7658 	/* Some accesses can write anything into the stack, others are
7659 	 * read-only.
7660 	 */
7661 	bool clobber = type == BPF_WRITE;
7662 	/*
7663 	 * Negative access_size signals global subprog arg check where
7664 	 * STACK_POISON slots are acceptable. static stack liveness
7665 	 * might have determined that subprog doesn't read them,
7666 	 * but BTF based global subprog validation isn't accurate enough.
7667 	 */
7668 	bool allow_poison = access_size < 0 || clobber;
7669 	u32 arg_slot = arg_slot_from_argno(argno);
7670 	bool uninit = clobber && meta && arg_slot < MAX_BPF_FUNC_ARGS &&
7671 		      (meta->arg_raw_mem.mask & BIT(arg_slot));
7672 	bool raw_mode = uninit && env->allow_uninit_stack &&
7673 			!(meta->arg_raw_mem.var_size_mask & BIT(arg_slot));
7674 
7675 	access_size = abs(access_size);
7676 
7677 	if (access_size == 0 && !zero_size_allowed) {
7678 		verbose(env, "invalid zero-sized read\n");
7679 		return -EACCES;
7680 	}
7681 
7682 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
7683 	if (err)
7684 		return err;
7685 
7686 	if (tnum_is_const(reg->var_off)) {
7687 		min_off = max_off = reg->var_off.value + off;
7688 	} else {
7689 		/* Variable offset is prohibited for unprivileged mode for
7690 		 * simplicity since it requires corresponding support in
7691 		 * Spectre masking for stack ALU.
7692 		 * See also retrieve_ptr_limit().
7693 		 */
7694 		if (!env->bypass_spec_v1) {
7695 			char tn_buf[48];
7696 
7697 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7698 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
7699 				reg_arg_name(env, argno), tn_buf);
7700 			return -EACCES;
7701 		}
7702 		/*
7703 		 * The call may touch any byte in the possible range, but does not
7704 		 * definitely initialize all of it. Fall back to ordinary stack checks.
7705 		 */
7706 		raw_mode = false;
7707 
7708 		min_off = reg_smin(reg) + off;
7709 		max_off = reg_smax(reg) + off;
7710 	}
7711 
7712 	/* Unprivileged outputs retain each byte's initialization state. */
7713 	if (raw_mode) {
7714 		meta->arg_raw_mem.size[arg_slot] = access_size;
7715 		return 0;
7716 	}
7717 
7718 	for (i = min_off; i < max_off + access_size; i++) {
7719 		struct bpf_stack_state *ss;
7720 		u8 *stype;
7721 
7722 		slot = -i - 1;
7723 		spi = slot / BPF_REG_SIZE;
7724 		if (state->allocated_stack <= slot) {
7725 			verbose(env, "allocated_stack too small\n");
7726 			return -EFAULT;
7727 		}
7728 
7729 		ss = bpf_stack_slot(state, spi);
7730 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
7731 		if (*stype == STACK_MISC)
7732 			goto mark;
7733 		if ((*stype == STACK_ZERO) ||
7734 		    (*stype == STACK_INVALID && (uninit || env->allow_uninit_stack))) {
7735 			if (clobber && (*stype != STACK_INVALID || env->allow_uninit_stack)) {
7736 				/* helper can write anything into the stack */
7737 				*stype = STACK_MISC;
7738 			}
7739 			goto mark;
7740 		}
7741 
7742 		/*
7743 		 * Only the bytes marked STACK_SPILL hold the spilled register.
7744 		 * The rest of a narrowly spilled slot keeps its previous type
7745 		 * and must be initialized on its own.
7746 		 */
7747 		if (*stype == STACK_SPILL &&
7748 		    (ss->spilled_ptr.type == SCALAR_VALUE ||
7749 		     env->allow_ptr_leaks)) {
7750 			if (clobber) {
7751 				__mark_reg_unknown(env, &ss->spilled_ptr);
7752 				for (j = 0; j < BPF_REG_SIZE; j++)
7753 					scrub_spilled_slot(&ss->slot_type[j]);
7754 			}
7755 			goto mark;
7756 		}
7757 
7758 		if (*stype == STACK_POISON) {
7759 			if (allow_poison) {
7760 				if (uninit && env->allow_uninit_stack)
7761 					*stype = STACK_MISC;
7762 				goto mark;
7763 			}
7764 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
7765 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7766 		} else if (tnum_is_const(reg->var_off)) {
7767 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
7768 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7769 		} else {
7770 			char tn_buf[48];
7771 
7772 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7773 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
7774 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
7775 		}
7776 		return -EACCES;
7777 mark:
7778 		;
7779 	}
7780 	return 0;
7781 }
7782 
7783 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7784 				   argno_t argno, int access_size,
7785 				   enum bpf_access_type access_type, bool zero_size_allowed,
7786 				   struct bpf_call_arg_meta *meta, bool *known_memory)
7787 {
7788 	struct bpf_reg_state *regs = cur_regs(env);
7789 	u32 *max_access;
7790 
7791 	if (known_memory)
7792 		*known_memory = true;
7793 
7794 	switch (base_type(reg->type)) {
7795 	case PTR_TO_PACKET:
7796 	case PTR_TO_PACKET_META:
7797 		if (!may_access_direct_pkt_data(env, meta, access_type)) {
7798 			verbose(env, "function access to the packet is not allowed\n");
7799 			return -EACCES;
7800 		}
7801 		return check_packet_access(env, reg, argno, 0, access_size,
7802 					   zero_size_allowed);
7803 	case PTR_TO_MAP_KEY:
7804 		if (access_type == BPF_WRITE) {
7805 			verbose(env, "%s cannot write into %s\n",
7806 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7807 			return -EACCES;
7808 		}
7809 		return check_mem_region_access(env, reg, argno, 0, access_size,
7810 					       reg->map_ptr->key_size, false);
7811 	case PTR_TO_MAP_VALUE:
7812 		if (check_map_access_type(env, reg, 0, access_size, access_type))
7813 			return -EACCES;
7814 		return check_map_access(env, reg, argno, 0, access_size,
7815 					zero_size_allowed, ACCESS_HELPER);
7816 	case PTR_TO_MEM:
7817 		if (type_is_rdonly_mem(reg->type)) {
7818 			if (access_type == BPF_WRITE) {
7819 				verbose(env, "%s cannot write into %s\n",
7820 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7821 				return -EACCES;
7822 			}
7823 		}
7824 		return check_mem_region_access(env, reg, argno, 0,
7825 					       access_size, reg->mem_size,
7826 					       zero_size_allowed);
7827 	case PTR_TO_BUF:
7828 		if (type_is_rdonly_mem(reg->type)) {
7829 			if (access_type == BPF_WRITE) {
7830 				verbose(env, "%s cannot write into %s\n",
7831 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7832 				return -EACCES;
7833 			}
7834 
7835 			max_access = &env->prog->aux->max_rdonly_access;
7836 		} else {
7837 			max_access = &env->prog->aux->max_rdwr_access;
7838 		}
7839 		return check_buffer_access(env, reg, argno, 0,
7840 					   access_size, zero_size_allowed,
7841 					   max_access);
7842 	case PTR_TO_STACK:
7843 		return check_stack_range_initialized(
7844 				env, reg,
7845 				argno, 0, access_size,
7846 				zero_size_allowed, access_type, meta);
7847 	case PTR_TO_BTF_ID:
7848 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
7849 					       access_size, access_type, -1);
7850 	case PTR_TO_CTX:
7851 		/* Only permit reading or writing syscall context using helper calls. */
7852 		if (is_var_ctx_off_allowed(env->prog)) {
7853 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
7854 							  zero_size_allowed);
7855 			if (err)
7856 				return err;
7857 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
7858 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
7859 			return 0;
7860 		}
7861 		fallthrough;
7862 	default: /* scalar_value or invalid ptr */
7863 		/* Allow zero-byte read from NULL, regardless of pointer type */
7864 		if (zero_size_allowed && access_size == 0 &&
7865 		    bpf_register_is_null(reg))
7866 			return 0;
7867 		if (known_memory && base_type(reg->type) != PTR_TO_CTX)
7868 			*known_memory = false;
7869 
7870 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
7871 			reg_type_str(env, reg->type));
7872 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7873 		return -EACCES;
7874 	}
7875 }
7876 
7877 enum bpf_mem_size_failure {
7878 	BPF_MEM_SIZE_FAIL_NONE,
7879 	BPF_MEM_SIZE_FAIL_MEMORY,
7880 	BPF_MEM_SIZE_FAIL_SIZE,
7881 };
7882 
7883 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7884  * size.
7885  *
7886  * @mem_reg contains the pointer, @size_reg contains the access size.
7887  */
7888 static int check_mem_size_reg(struct bpf_verifier_env *env,
7889 			      struct bpf_reg_state *mem_reg,
7890 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
7891 			      argno_t size_argno, u32 access_type,
7892 			      bool zero_size_allowed,
7893 			      struct bpf_call_arg_meta *meta,
7894 			      enum bpf_mem_size_failure *failure)
7895 {
7896 	int err = 0;
7897 
7898 	if (failure)
7899 		*failure = BPF_MEM_SIZE_FAIL_NONE;
7900 
7901 	/* This is used to refine r0 return value bounds for helpers
7902 	 * that enforce this value as an upper bound on return values.
7903 	 * See do_refine_retval_range() for helpers that can refine
7904 	 * the return value. C type of helper is u32 so we pull register
7905 	 * bound from umax_value however, if negative verifier errors
7906 	 * out. Only upper bounds can be learned because retval is an
7907 	 * int type and negative retvals are allowed.
7908 	 */
7909 	meta->msize_max_value = reg_umax(size_reg);
7910 
7911 	/*
7912 	 * Check variable ranges byte by byte instead of using raw mode. Keep the
7913 	 * MEM_UNINIT annotation so invalid bytes are accepted without marking them
7914 	 * initialized when the caller cannot read uninitialized stack memory.
7915 	 */
7916 	if (!tnum_is_const(size_reg->var_off))
7917 		meta->arg_raw_mem.var_size_mask |= BIT(arg_slot_from_argno(mem_argno));
7918 
7919 	if (reg_smin(size_reg) < 0) {
7920 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
7921 			reg_arg_name(env, size_argno));
7922 		err = -EACCES;
7923 		goto size_error;
7924 	}
7925 
7926 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
7927 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
7928 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
7929 		err = -EACCES;
7930 		goto size_error;
7931 	}
7932 
7933 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
7934 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7935 			reg_arg_name(env, size_argno));
7936 		err = -EACCES;
7937 		goto size_error;
7938 	}
7939 
7940 	if (access_type & BPF_READ)
7941 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
7942 					      BPF_READ, zero_size_allowed, meta, NULL);
7943 	if (!err && access_type & BPF_WRITE)
7944 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
7945 					      BPF_WRITE, zero_size_allowed, meta, NULL);
7946 	if (err && failure)
7947 		*failure = BPF_MEM_SIZE_FAIL_MEMORY;
7948 
7949 	if (!err)
7950 		err = mark_arg_precision(env, size_argno);
7951 
7952 	return err;
7953 
7954 size_error:
7955 	if (failure)
7956 		*failure = BPF_MEM_SIZE_FAIL_SIZE;
7957 	return err;
7958 }
7959 
7960 static bool is_subprog(const struct bpf_call_arg_meta *meta)
7961 {
7962 	return meta->btf && !meta->func_id;
7963 }
7964 
7965 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7966 			 argno_t argno, u32 mem_size, enum bpf_access_type access_type,
7967 			 struct bpf_call_arg_meta *meta, bool *known_memory)
7968 {
7969 	int size, err = 0;
7970 
7971 	if (bpf_register_is_null(reg))
7972 		return mark_arg_precision(env, argno);
7973 	if (known_memory)
7974 		*known_memory = true;
7975 
7976 	if (mem_size > S32_MAX) {
7977 		verbose(env, "%s memory size %u is too large\n",
7978 			reg_arg_name(env, argno), mem_size);
7979 		return -EACCES;
7980 	}
7981 
7982 	/*
7983 	 * Only a global subprog may read poisoned stack slots:
7984 	 * its static stack liveness proved the callee body skips them.
7985 	 */
7986 	size = (is_subprog(meta) &&
7987 		base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size;
7988 
7989 	if (access_type & BPF_READ)
7990 		err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta,
7991 					      known_memory);
7992 	if (!err && (access_type & BPF_WRITE))
7993 		err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta,
7994 					      known_memory);
7995 
7996 	return err;
7997 }
7998 
7999 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8000 					argno_t argno, struct ret_mem_desc *ret_mem)
8001 {
8002 	int regno = reg_from_argno(argno);
8003 	int err;
8004 
8005 	if (ret_mem->found) {
8006 		verifier_bug(env, "only one allocation size argument permitted");
8007 		return -EFAULT;
8008 	}
8009 
8010 	if (!tnum_is_const(reg->var_off)) {
8011 		verbose(env, "%s is not a const\n", reg_arg_name(env, argno));
8012 		return -EINVAL;
8013 	}
8014 
8015 	if (reg->var_off.value > U32_MAX) {
8016 		verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno));
8017 		return -EINVAL;
8018 	}
8019 
8020 	if (regno >= 0)
8021 		err = mark_chain_precision(env, regno);
8022 	else
8023 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8024 	if (err)
8025 		return err;
8026 
8027 	ret_mem->size = reg->var_off.value;
8028 	ret_mem->found = true;
8029 
8030 	return 0;
8031 }
8032 
8033 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8034 			     argno_t argno, struct bpf_call_arg_meta *meta)
8035 {
8036 	int regno = reg_from_argno(argno);
8037 	int err;
8038 
8039 	if (meta->arg_constant.found) {
8040 		verifier_bug(env, "only one constant argument permitted");
8041 		return -EFAULT;
8042 	}
8043 
8044 	if (!tnum_is_const(reg->var_off)) {
8045 		verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno));
8046 		return -EINVAL;
8047 	}
8048 
8049 	if (regno >= 0)
8050 		err = mark_chain_precision(env, regno);
8051 	else
8052 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8053 	if (err < 0)
8054 		return err;
8055 
8056 	meta->arg_constant.found = true;
8057 	meta->arg_constant.value = reg->var_off.value;
8058 
8059 	return 0;
8060 }
8061 
8062 enum {
8063 	PROCESS_SPIN_LOCK = (1 << 0),
8064 	PROCESS_RES_LOCK  = (1 << 1),
8065 	PROCESS_LOCK_IRQ  = (1 << 2),
8066 };
8067 
8068 /* Implementation details:
8069  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8070  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8071  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8072  * Two separate bpf_obj_new will also have different reg->id.
8073  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8074  * clears reg->id after value_or_null->value transition, since the verifier only
8075  * cares about the range of access to valid map value pointer and doesn't care
8076  * about actual address of the map element.
8077  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8078  * reg->id > 0 after value_or_null->value transition. By doing so
8079  * two bpf_map_lookups will be considered two different pointers that
8080  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8081  * returned from bpf_obj_new.
8082  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8083  * dead-locks.
8084  * Since only one bpf_spin_lock is allowed the checks are simpler than
8085  * reg_is_refcounted() logic. The verifier needs to remember only
8086  * one spin_lock instead of array of acquired_refs.
8087  * env->cur_state->active_locks remembers which map value element or allocated
8088  * object got locked and clears it after bpf_spin_unlock.
8089  */
8090 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
8091 {
8092 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8093 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8094 	struct bpf_verifier_state *cur = env->cur_state;
8095 	struct bpf_reference_state *lock;
8096 	bool is_const = tnum_is_const(reg->var_off);
8097 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8098 	u64 val = reg->var_off.value;
8099 	struct bpf_map *map = NULL;
8100 	struct btf *btf = NULL;
8101 	struct btf_record *rec;
8102 	u32 spin_lock_off;
8103 	int err;
8104 
8105 	if (!is_const) {
8106 		verbose(env,
8107 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
8108 			reg_arg_name(env, argno), lock_str);
8109 		return -EINVAL;
8110 	}
8111 	if (reg->type == PTR_TO_MAP_VALUE) {
8112 		map = reg->map_ptr;
8113 		if (!map->btf) {
8114 			verbose(env,
8115 				"map '%s' has to have BTF in order to use %s_lock\n",
8116 				map->name, lock_str);
8117 			return -EINVAL;
8118 		}
8119 	} else {
8120 		btf = reg->btf;
8121 	}
8122 
8123 	rec = reg_btf_record(reg);
8124 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8125 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8126 			map ? map->name : "kptr", lock_str);
8127 		return -EINVAL;
8128 	}
8129 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8130 	if (spin_lock_off != val) {
8131 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8132 			val, lock_str, spin_lock_off);
8133 		return -EINVAL;
8134 	}
8135 	if (is_lock) {
8136 		void *ptr;
8137 		int type;
8138 
8139 		if (map)
8140 			ptr = map;
8141 		else
8142 			ptr = btf;
8143 
8144 		if (!is_res_lock && cur->active_locks) {
8145 			lock = find_lock_state(cur, REF_TYPE_LOCK, 0, NULL);
8146 			if (lock) {
8147 				verbose(env,
8148 					"Locking two bpf_spin_locks are not allowed\n");
8149 				bpf_diag_lock(
8150 					env, env->insn_idx, "nested spin lock",
8151 					"This path already holds a bpf_spin_lock. The verifier allows only one regular BPF spin lock at a time.",
8152 					"Unlock the current bpf_spin_lock before taking another one.", lock);
8153 				return -EINVAL;
8154 			}
8155 		} else if (is_res_lock && cur->active_locks) {
8156 			lock = find_lock_state(cur, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
8157 					       reg->id, ptr);
8158 			if (lock) {
8159 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8160 				bpf_diag_lock(
8161 					env, env->insn_idx, "recursive resource spin lock",
8162 					"This path already holds the same resource spin lock. Taking it again would deadlock.",
8163 					"Avoid reacquiring the same resource spin lock before it is unlocked.", lock);
8164 				return -EINVAL;
8165 			}
8166 		}
8167 
8168 		if (is_res_lock && is_irq)
8169 			type = REF_TYPE_RES_LOCK_IRQ;
8170 		else if (is_res_lock)
8171 			type = REF_TYPE_RES_LOCK;
8172 		else
8173 			type = REF_TYPE_LOCK;
8174 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8175 		if (err < 0) {
8176 			verbose(env, "Failed to acquire lock state\n");
8177 			return err;
8178 		}
8179 	} else {
8180 		void *ptr;
8181 		int type;
8182 
8183 		if (map)
8184 			ptr = map;
8185 		else
8186 			ptr = btf;
8187 
8188 		if (!cur->active_locks) {
8189 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8190 			bpf_diag_res(
8191 				env, env->insn_idx, "unlock without lock",
8192 				"This unlock operation has no matching active lock on the current path.",
8193 				"Take the matching lock before this unlock, or remove the unmatched unlock path.");
8194 			return -EINVAL;
8195 		}
8196 
8197 		if (is_res_lock && is_irq)
8198 			type = REF_TYPE_RES_LOCK_IRQ;
8199 		else if (is_res_lock)
8200 			type = REF_TYPE_RES_LOCK;
8201 		else
8202 			type = REF_TYPE_LOCK;
8203 
8204 		lock = find_lock_state(cur, type, reg->id, ptr);
8205 		if (!lock) {
8206 			verbose(env, "%s_unlock of different lock\n", lock_str);
8207 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8208 					       cur->active_lock_ptr);
8209 			bpf_diag_lock(
8210 				env, env->insn_idx, "unlock of a different lock",
8211 				"This unlock does not match any active lock with the same tracked identity on the current path.",
8212 				"Unlock the same lock object that was most recently acquired.", lock);
8213 			return -EINVAL;
8214 		}
8215 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8216 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8217 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8218 					       cur->active_lock_ptr);
8219 			bpf_diag_lock(
8220 				env, env->insn_idx, "unlock out of order",
8221 				"Locks must be released in last-in, first-out order, but this unlock does not match the currently active lock.",
8222 				"Release nested locks in the reverse order they were acquired.", lock);
8223 			return -EINVAL;
8224 		}
8225 		if (release_lock_state(env, type, reg->id, ptr)) {
8226 			verbose(env, "%s_unlock of different lock\n", lock_str);
8227 			bpf_diag_lock(
8228 				env, env->insn_idx, "unlock of a different lock",
8229 				"The verifier could not release a lock state matching this unlock operation.",
8230 				"Pass the same lock object and lock kind that were used for the matching lock operation.",
8231 				lock);
8232 			return -EINVAL;
8233 		}
8234 		/*
8235 		 * Invalidate non-owning refs before RCU demotion clears their
8236 		 * NON_OWN_REF flag.
8237 		 */
8238 		invalidate_non_owning_refs(env);
8239 
8240 		if (!in_rcu_cs(env))
8241 			invalidate_rcu_protected_refs(env);
8242 	}
8243 	return 0;
8244 }
8245 
8246 /* Check if @regno is a pointer to a specific field in a map value */
8247 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8248 				   enum btf_field_type field_type,
8249 				   struct bpf_map_desc *map_desc)
8250 {
8251 	bool is_const = tnum_is_const(reg->var_off);
8252 	struct bpf_map *map = reg->map_ptr;
8253 	u64 val = reg->var_off.value;
8254 	const char *struct_name = btf_field_type_name(field_type);
8255 	int field_off = -1;
8256 
8257 	if (!is_const) {
8258 		verbose(env,
8259 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
8260 			reg_arg_name(env, argno), struct_name);
8261 		return -EINVAL;
8262 	}
8263 	if (!map->btf) {
8264 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8265 			struct_name);
8266 		return -EINVAL;
8267 	}
8268 	if (!btf_record_has_field(map->record, field_type)) {
8269 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8270 		return -EINVAL;
8271 	}
8272 	switch (field_type) {
8273 	case BPF_TIMER:
8274 		field_off = map->record->timer_off;
8275 		break;
8276 	case BPF_TASK_WORK:
8277 		field_off = map->record->task_work_off;
8278 		break;
8279 	case BPF_RCU_HEAD:
8280 		field_off = map->record->rcu_head_off;
8281 		break;
8282 	case BPF_WORKQUEUE:
8283 		field_off = map->record->wq_off;
8284 		break;
8285 	default:
8286 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8287 		return -EINVAL;
8288 	}
8289 	if (field_off != val) {
8290 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8291 			val, struct_name, field_off);
8292 		return -EINVAL;
8293 	}
8294 	if (map_desc->ptr) {
8295 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
8296 		return -EFAULT;
8297 	}
8298 	map_desc->uid = reg->map_uid;
8299 	map_desc->ptr = map;
8300 	return 0;
8301 }
8302 
8303 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8304 			      struct bpf_map_desc *map)
8305 {
8306 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8307 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8308 		return -EOPNOTSUPP;
8309 	}
8310 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
8311 }
8312 
8313 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8314 			     struct bpf_call_arg_meta *meta)
8315 {
8316 	struct bpf_reg_state *reg = reg_state(env, regno);
8317 	struct btf_field *kptr_field;
8318 	struct bpf_map *map_ptr;
8319 	struct btf_record *rec;
8320 	u32 kptr_off;
8321 
8322 	if (type_is_ptr_alloc_obj(reg->type)) {
8323 		rec = reg_btf_record(reg);
8324 	} else { /* PTR_TO_MAP_VALUE */
8325 		map_ptr = reg->map_ptr;
8326 		if (!map_ptr->btf) {
8327 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8328 				map_ptr->name);
8329 			return -EINVAL;
8330 		}
8331 		rec = map_ptr->record;
8332 		meta->map.ptr = map_ptr;
8333 	}
8334 
8335 	if (!tnum_is_const(reg->var_off)) {
8336 		verbose(env,
8337 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8338 			regno);
8339 		return -EINVAL;
8340 	}
8341 
8342 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8343 		verbose(env, "R%d has no valid kptr\n", regno);
8344 		return -EINVAL;
8345 	}
8346 
8347 	kptr_off = reg->var_off.value;
8348 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8349 	if (!kptr_field) {
8350 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8351 		return -EACCES;
8352 	}
8353 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8354 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8355 		return -EACCES;
8356 	}
8357 	meta->kptr_field = kptr_field;
8358 	return 0;
8359 }
8360 
8361 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
8362 			      const char *call_name, const char *reason, const char *suggestion);
8363 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
8364 						 argno_t argno, const char *call_name,
8365 						 const char *suggestion, const char *fmt, ...);
8366 
8367 /*
8368  * Validate dynptr arguments for helper, kfunc and subprog.
8369  *
8370  * @meta carries the dynptr and referenced-object state. The dynptr is populated
8371  * when the argument is tagged with MEM_UNINIT (i.e., the dynptr argument that
8372  * will be constructed) and consumed when the argument is expected to be an
8373  * initialized dynptr. The reference tracks the parent object (e.g., file or skb
8374  * in qdisc program) when constructing a dynptr.
8375  *
8376  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8377  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8378  *
8379  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8380  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8381  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8382  *
8383  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
8384  * dynptr points to. At the first level, the verifier will make sure a
8385  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
8386  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
8387  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
8388  * and checked dynamically during runtime.
8389  */
8390 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8391 			       argno_t argno, int insn_idx, enum bpf_arg_type arg_type,
8392 			       struct bpf_call_arg_meta *meta)
8393 {
8394 	int spi, err = 0;
8395 
8396 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8397 	 *		 constructing a mutable bpf_dynptr object.
8398 	 *
8399 	 *		 Currently, this is only possible with PTR_TO_STACK
8400 	 *		 pointing to a region of at least 16 bytes which doesn't
8401 	 *		 contain an existing bpf_dynptr.
8402 	 *
8403 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
8404 	 *		  destroyed.
8405 	 *
8406 	 *  None       - Points to a initialized dynptr that cannot be
8407 	 *		 reinitialized or destroyed. However, the view of the
8408 	 *		 dynptr and the memory it points to may be mutated.
8409 	 */
8410 	if (arg_type & MEM_UNINIT) {
8411 		int i;
8412 
8413 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8414 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8415 			bpf_diag_res(
8416 				env, insn_idx, "dynptr is already initialized",
8417 				"This function constructs a dynptr and requires an uninitialized dynptr stack slot, but the selected slot already holds dynptr state.",
8418 				"Use a fresh stack dynptr slot, or release/destroy the existing dynptr before reusing the slot.");
8419 			return -EINVAL;
8420 		}
8421 
8422 		/* we write BPF_DW bits (8 bytes) at a time */
8423 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8424 			err = check_mem_access(env, insn_idx, reg, argno,
8425 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8426 			if (err)
8427 				return err;
8428 		}
8429 
8430 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx,
8431 					      &meta->ref_obj, &meta->dynptr);
8432 	} else /* OBJ_RELEASE and None case from above */ {
8433 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8434 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
8435 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
8436 			bpf_diag_res(
8437 				env, insn_idx, "const dynptr release",
8438 				"This release operation was given a const dynptr. Const dynptr values are verifier-provided views and cannot be released by the program.",
8439 				"Release only mutable dynptrs that the program initialized or reserved.");
8440 			return -EINVAL;
8441 		}
8442 
8443 		if (!is_dynptr_reg_valid_init(env, reg)) {
8444 			verbose(env, "Expected an initialized dynptr as %s\n",
8445 				reg_arg_name(env, argno));
8446 			bpf_diag_res(
8447 				env, insn_idx, "uninitialized dynptr use",
8448 				"This operation requires an initialized dynptr, but the stack slot does not currently hold a valid dynptr on this path.",
8449 				"Initialize the dynptr on every path before this call, and avoid overwriting or releasing it before this use.");
8450 			return -EINVAL;
8451 		}
8452 
8453 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
8454 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
8455 			enum bpf_dynptr_type expected_type = arg_to_dynptr_type(arg_type);
8456 			enum bpf_dynptr_type actual_type = dynptr_reg_type(env, reg);
8457 
8458 			verbose(env, "Expected a dynptr of type %s as %s\n",
8459 				dynptr_type_str(expected_type), reg_arg_name(env, argno));
8460 			bpf_diag_call_arg_fmt(
8461 				env, insn_idx, argno, meta->func_name,
8462 				"Use a dynptr constructor that matches this operation, or call an operation that accepts the dynptr's current type.",
8463 				"the dynptr is initialized with backing object type %s, but this operation expects dynptr type %s",
8464 				dynptr_type_str(actual_type), dynptr_type_str(expected_type));
8465 			return -EINVAL;
8466 		}
8467 
8468 		if (reg->type != CONST_PTR_TO_DYNPTR) {
8469 			struct bpf_func_state *state = bpf_func(env, reg);
8470 
8471 			spi = dynptr_get_spi(env, reg);
8472 			if (spi < 0)
8473 				return spi;
8474 
8475 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
8476 
8477 			reg = &bpf_stack_slot(state, spi)->spilled_ptr;
8478 		}
8479 
8480 		meta->dynptr.type = reg->dynptr.type;
8481 		meta->dynptr.id = reg->id;
8482 		meta->dynptr.parent_id = reg->parent_id;
8483 	}
8484 	return err;
8485 }
8486 
8487 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta)
8488 {
8489 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8490 }
8491 
8492 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta)
8493 {
8494 	return meta->kfunc_flags & KF_ITER_NEW;
8495 }
8496 
8497 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta)
8498 {
8499 	return meta->kfunc_flags & KF_ITER_DESTROY;
8500 }
8501 
8502 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx,
8503 			      const struct btf_param *arg)
8504 {
8505 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8506 	 * kfunc is iter state pointer
8507 	 */
8508 	if (is_iter_kfunc(meta))
8509 		return arg_idx == 0;
8510 
8511 	/* iter passed as an argument to a generic kfunc */
8512 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8513 }
8514 
8515 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8516 			    u32 arg, argno_t argno, int insn_idx,
8517 			    struct bpf_call_arg_meta *meta)
8518 {
8519 	struct bpf_func_state *state = bpf_func(env, reg);
8520 	const struct btf_type *t;
8521 	int spi, err, i, nr_slots, btf_id;
8522 
8523 	if (reg->type != PTR_TO_STACK) {
8524 		verbose(env, "%s expected pointer to an iterator on stack\n",
8525 			reg_arg_name(env, argno));
8526 		bpf_diag_call_arg_fmt(
8527 			env, insn_idx, argno, meta->func_name,
8528 			"Pass the address of a stack iterator object for iterator new, next, and destroy calls.",
8529 			"iterator state must live in verifier-tracked stack memory, but %s is %s",
8530 			reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type));
8531 		return -EINVAL;
8532 	}
8533 
8534 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8535 	 * ensures struct convention, so we wouldn't need to do any BTF
8536 	 * validation here. But given iter state can be passed as a parameter
8537 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8538 	 * conservative here.
8539 	 */
8540 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg);
8541 	if (btf_id < 0) {
8542 		verbose(env, "expected valid iter pointer as %s\n",
8543 			reg_arg_name(env, argno));
8544 		bpf_diag_call_arg(
8545 			env, insn_idx, argno, meta->func_name,
8546 			"the function expects a recognized iterator state pointer, but this argument does not match a valid iterator type",
8547 			"Pass the exact iterator state type expected by this function.");
8548 		return -EINVAL;
8549 	}
8550 	t = btf_type_by_id(meta->btf, btf_id);
8551 	nr_slots = t->size / BPF_REG_SIZE;
8552 
8553 	if (is_iter_new_kfunc(meta)) {
8554 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8555 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8556 			verbose(env, "expected uninitialized iter_%s as %s\n",
8557 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8558 			bpf_diag_res(
8559 				env, insn_idx, "iterator is already initialized",
8560 				"Iterator creation requires an uninitialized iterator stack object, but this stack range already contains iterator state.",
8561 				"Use a fresh iterator stack slot, or destroy the existing iterator before reusing the slot.");
8562 			return -EINVAL;
8563 		}
8564 
8565 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8566 			err = check_mem_access(env, insn_idx, reg, argno,
8567 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8568 			if (err)
8569 				return err;
8570 		}
8571 
8572 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8573 		if (err)
8574 			return err;
8575 	} else {
8576 		/* iter_next() or iter_destroy(), as well as any kfunc
8577 		 * accepting iter argument, expect initialized iter state
8578 		 */
8579 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8580 		switch (err) {
8581 		case 0:
8582 			break;
8583 		case -EINVAL:
8584 			verbose(env, "expected an initialized iter_%s as %s\n",
8585 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8586 			bpf_diag_res(
8587 				env, insn_idx, "uninitialized iterator use",
8588 				"This iterator operation requires an initialized iterator state object, but the stack range does not contain a live iterator on this path.",
8589 				"Call the matching iterator new kfunc on every path before calling next or destroy, and do not destroy the iterator before this use.");
8590 			return err;
8591 		case -EPROTO:
8592 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8593 			bpf_diag_ctx_required(
8594 				env, insn_idx, meta->func_name, BPF_DIAG_CONTEXT_RCU,
8595 				"Wrap iterator use in bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
8596 			return err;
8597 		default:
8598 			return err;
8599 		}
8600 
8601 		spi = iter_get_spi(env, reg, nr_slots);
8602 		if (spi < 0)
8603 			return spi;
8604 
8605 		mark_stack_slots_scratched(env, spi, nr_slots);
8606 
8607 		/* remember meta->iter info for process_iter_next_call() */
8608 		meta->iter.spi = spi;
8609 		meta->iter.frameno = reg->frameno;
8610 		update_ref_obj(&meta->ref_obj, &bpf_stack_slot(state, spi)->spilled_ptr);
8611 
8612 		if (is_iter_destroy_kfunc(meta)) {
8613 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8614 			if (err)
8615 				return err;
8616 		}
8617 	}
8618 
8619 	return 0;
8620 }
8621 
8622 /* Look for a previous loop entry at insn_idx: nearest parent state
8623  * stopped at insn_idx with callsites matching those in cur->frame.
8624  */
8625 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8626 						  struct bpf_verifier_state *cur,
8627 						  int insn_idx)
8628 {
8629 	struct bpf_verifier_state_list *sl;
8630 	struct bpf_verifier_state *st;
8631 	struct list_head *pos, *head;
8632 
8633 	/* Explored states are pushed in stack order, most recent states come first */
8634 	head = bpf_explored_state(env, insn_idx);
8635 	list_for_each(pos, head) {
8636 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8637 		/* If st->branches != 0 state is a part of current DFS verification path,
8638 		 * hence cur & st for a loop.
8639 		 */
8640 		st = &sl->state;
8641 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8642 		    st->dfs_depth < cur->dfs_depth)
8643 			return st;
8644 	}
8645 
8646 	return NULL;
8647 }
8648 
8649 /*
8650  * Check if scalar registers are exact for the purpose of not widening.
8651  * More lenient than regs_exact()
8652  */
8653 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
8654 				    const struct bpf_reg_state *rcur)
8655 {
8656 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
8657 }
8658 
8659 static void maybe_widen_reg(struct bpf_verifier_env *env,
8660 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
8661 {
8662 	if (rold->type != SCALAR_VALUE)
8663 		return;
8664 	if (rold->type != rcur->type)
8665 		return;
8666 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
8667 		return;
8668 	__mark_reg_unknown(env, rcur);
8669 }
8670 
8671 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8672 				   struct bpf_verifier_state *old,
8673 				   struct bpf_verifier_state *cur)
8674 {
8675 	struct bpf_func_state *fold, *fcur;
8676 	int i, fr, num_slots;
8677 
8678 	for (fr = old->curframe; fr >= 0; fr--) {
8679 		fold = old->frame[fr];
8680 		fcur = cur->frame[fr];
8681 
8682 		for (i = 0; i < MAX_BPF_REG; i++)
8683 			maybe_widen_reg(env,
8684 					&fold->regs[i],
8685 					&fcur->regs[i]);
8686 
8687 		num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur));
8688 		for (i = 0; i < num_slots; i++) {
8689 			struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i);
8690 			struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i);
8691 
8692 			if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss))
8693 				continue;
8694 
8695 			maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr);
8696 		}
8697 	}
8698 	return 0;
8699 }
8700 
8701 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8702 						 struct bpf_call_arg_meta *meta)
8703 {
8704 	int iter_frameno = meta->iter.frameno;
8705 	int iter_spi = meta->iter.spi;
8706 
8707 	return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr;
8708 }
8709 
8710 /* process_iter_next_call() is called when verifier gets to iterator's next
8711  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8712  * to it as just "iter_next()" in comments below.
8713  *
8714  * BPF verifier relies on a crucial contract for any iter_next()
8715  * implementation: it should *eventually* return NULL, and once that happens
8716  * it should keep returning NULL. That is, once iterator exhausts elements to
8717  * iterate, it should never reset or spuriously return new elements.
8718  *
8719  * With the assumption of such contract, process_iter_next_call() simulates
8720  * a fork in the verifier state to validate loop logic correctness and safety
8721  * without having to simulate infinite amount of iterations.
8722  *
8723  * In current state, we first assume that iter_next() returned NULL and
8724  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8725  * conditions we should not form an infinite loop and should eventually reach
8726  * exit.
8727  *
8728  * Besides that, we also fork current state and enqueue it for later
8729  * verification. In a forked state we keep iterator state as ACTIVE
8730  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8731  * also bump iteration depth to prevent erroneous infinite loop detection
8732  * later on (see iter_active_depths_differ() comment for details). In this
8733  * state we assume that we'll eventually loop back to another iter_next()
8734  * calls (it could be in exactly same location or in some other instruction,
8735  * it doesn't matter, we don't make any unnecessary assumptions about this,
8736  * everything revolves around iterator state in a stack slot, not which
8737  * instruction is calling iter_next()). When that happens, we either will come
8738  * to iter_next() with equivalent state and can conclude that next iteration
8739  * will proceed in exactly the same way as we just verified, so it's safe to
8740  * assume that loop converges. If not, we'll go on another iteration
8741  * simulation with a different input state, until all possible starting states
8742  * are validated or we reach maximum number of instructions limit.
8743  *
8744  * This way, we will either exhaustively discover all possible input states
8745  * that iterator loop can start with and eventually will converge, or we'll
8746  * effectively regress into bounded loop simulation logic and either reach
8747  * maximum number of instructions if loop is not provably convergent, or there
8748  * is some statically known limit on number of iterations (e.g., if there is
8749  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8750  *
8751  * Iteration convergence logic in is_state_visited() relies on exact
8752  * states comparison, which ignores read and precision marks.
8753  * This is necessary because read and precision marks are not finalized
8754  * while in the loop. Exact comparison might preclude convergence for
8755  * simple programs like below:
8756  *
8757  *     i = 0;
8758  *     while(iter_next(&it))
8759  *       i++;
8760  *
8761  * At each iteration step i++ would produce a new distinct state and
8762  * eventually instruction processing limit would be reached.
8763  *
8764  * To avoid such behavior speculatively forget (widen) range for
8765  * imprecise scalar registers, if those registers were not precise at the
8766  * end of the previous iteration and do not match exactly.
8767  *
8768  * This is a conservative heuristic that allows to verify wide range of programs,
8769  * however it precludes verification of programs that conjure an
8770  * imprecise value on the first loop iteration and use it as precise on a second.
8771  * For example, the following safe program would fail to verify:
8772  *
8773  *     struct bpf_num_iter it;
8774  *     int arr[10];
8775  *     int i = 0, a = 0;
8776  *     bpf_iter_num_new(&it, 0, 10);
8777  *     while (bpf_iter_num_next(&it)) {
8778  *       if (a == 0) {
8779  *         a = 1;
8780  *         i = 7; // Because i changed verifier would forget
8781  *                // it's range on second loop entry.
8782  *       } else {
8783  *         arr[i] = 42; // This would fail to verify.
8784  *       }
8785  *     }
8786  *     bpf_iter_num_destroy(&it);
8787  */
8788 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8789 				  struct bpf_call_arg_meta *meta)
8790 {
8791 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8792 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8793 	struct bpf_reg_state *cur_iter, *queued_iter;
8794 
8795 	BTF_TYPE_EMIT(struct bpf_iter);
8796 
8797 	cur_iter = get_iter_from_state(cur_st, meta);
8798 
8799 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8800 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8801 		verifier_bug(env, "unexpected iterator state %d (%s)",
8802 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8803 		return -EFAULT;
8804 	}
8805 
8806 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8807 		/* Because iter_next() call is a checkpoint is_state_visitied()
8808 		 * should guarantee parent state with same call sites and insn_idx.
8809 		 */
8810 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8811 		    !same_callsites(cur_st->parent, cur_st)) {
8812 			verifier_bug(env, "bad parent state for iter next call");
8813 			return -EFAULT;
8814 		}
8815 		/* Note cur_st->parent in the call below, it is necessary to skip
8816 		 * checkpoint created for cur_st by is_state_visited()
8817 		 * right at this instruction.
8818 		 */
8819 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8820 		/* branch out active iter state */
8821 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8822 		if (IS_ERR(queued_st))
8823 			return PTR_ERR(queued_st);
8824 
8825 		queued_iter = get_iter_from_state(queued_st, meta);
8826 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8827 		queued_iter->iter.depth++;
8828 		if (prev_st)
8829 			widen_imprecise_scalars(env, prev_st, queued_st);
8830 
8831 		queued_fr = queued_st->frame[queued_st->curframe];
8832 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8833 	}
8834 
8835 	/* switch to DRAINED state, but keep the depth unchanged */
8836 	/* mark current iter state as drained and assume returned NULL */
8837 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8838 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8839 
8840 	return 0;
8841 }
8842 
8843 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8844 {
8845 	return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO;
8846 }
8847 
8848 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8849 {
8850 	/*
8851 	 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw
8852 	 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be
8853 	 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized().
8854 	 */
8855 	return (base_type(type) == ARG_PTR_TO_MEM ||
8856 		base_type(type) == ARG_PTR_TO_MAP_VALUE) &&
8857 	       type & MEM_UNINIT;
8858 }
8859 
8860 static bool arg_type_is_release(enum bpf_arg_type type)
8861 {
8862 	return type & OBJ_RELEASE;
8863 }
8864 
8865 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8866 {
8867 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8868 }
8869 
8870 /*
8871  * An argument that only ever takes a scalar, so a zero register passed to it
8872  * is a value rather than a NULL pointer.
8873  */
8874 static bool arg_type_is_scalar(enum bpf_arg_type type)
8875 {
8876 	switch (base_type(type)) {
8877 	case ARG_SCALAR:
8878 	case ARG_CONST_SCALAR:
8879 	case ARG_MEM_SIZE:
8880 	case ARG_MEM_SIZE_OR_ZERO:
8881 	case ARG_CONST_MEM_SIZE:
8882 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8883 		return true;
8884 	default:
8885 		return false;
8886 	}
8887 }
8888 
8889 /*
8890  * A helper has no BTF and a nonzero function ID. A kfunc has both, while a
8891  * BPF subprogram has BTF and a zero function ID.
8892  */
8893 static bool is_helper(const struct bpf_call_arg_meta *meta)
8894 {
8895 	return !meta->btf && meta->func_id;
8896 }
8897 
8898 static bool is_helper_call(const struct bpf_call_arg_meta *meta, enum bpf_func_id func_id)
8899 {
8900 	return is_helper(meta) && meta->func_id == func_id;
8901 }
8902 
8903 static bool is_kfunc(const struct bpf_call_arg_meta *meta)
8904 {
8905 	return meta->btf && meta->func_id;
8906 }
8907 
8908 static bool is_kfunc_call(const struct bpf_call_arg_meta *meta, u32 btf_id)
8909 {
8910 	return is_kfunc(meta) && meta->func_id == btf_id;
8911 }
8912 
8913 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8914 				const struct bpf_call_arg_meta *meta,
8915 				enum bpf_arg_type *arg_type)
8916 {
8917 	if (!meta->map.ptr) {
8918 		/* kernel subsystem misconfigured verifier */
8919 		verifier_bug(env, "invalid map_ptr to access map->type");
8920 		return -EFAULT;
8921 	}
8922 
8923 	switch (meta->map.ptr->map_type) {
8924 	case BPF_MAP_TYPE_SOCKMAP:
8925 	case BPF_MAP_TYPE_SOCKHASH:
8926 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8927 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8928 		} else {
8929 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8930 			return -EINVAL;
8931 		}
8932 		break;
8933 	case BPF_MAP_TYPE_BLOOM_FILTER:
8934 		if (is_helper_call(meta, BPF_FUNC_map_peek_elem))
8935 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8936 		break;
8937 	default:
8938 		break;
8939 	}
8940 	return 0;
8941 }
8942 
8943 static int resolve_func_arg_type(struct bpf_verifier_env *env,
8944 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
8945 				 struct bpf_call_arg_meta *meta,
8946 				 enum bpf_arg_type *arg_type, u32 *arg_size);
8947 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8948 				     argno_t argno, enum bpf_arg_type arg_type,
8949 				     const struct btf *arg_btf, u32 arg_btf_id,
8950 				     struct bpf_call_arg_meta *meta, int insn_idx);
8951 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf,
8952 					const struct btf_param *arg);
8953 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
8954 					  const struct btf_param *arg,
8955 					  const char *name);
8956 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta);
8957 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta);
8958 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta);
8959 static bool is_bpf_obj_drop_kfunc(u32 func_id);
8960 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id);
8961 static bool is_bpf_rbtree_add_kfunc(u32 func_id);
8962 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta);
8963 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);
8964 static int process_irq_flag(struct bpf_verifier_env *env,
8965 			    struct bpf_reg_state *reg, argno_t argno,
8966 			    struct bpf_call_arg_meta *meta);
8967 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
8968 					   struct bpf_reg_state *reg,
8969 					   argno_t argno,
8970 					   struct bpf_call_arg_meta *meta);
8971 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
8972 					     struct bpf_reg_state *reg,
8973 					     argno_t argno,
8974 					     struct bpf_call_arg_meta *meta);
8975 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
8976 					   struct bpf_reg_state *reg,
8977 					   argno_t argno,
8978 					   struct bpf_call_arg_meta *meta);
8979 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
8980 					     struct bpf_reg_state *reg,
8981 					     argno_t argno,
8982 					     struct bpf_call_arg_meta *meta);
8983 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env);
8984 
8985 struct bpf_reg_types {
8986 	const enum bpf_reg_type types[10];
8987 	u32 *btf_id;
8988 };
8989 
8990 static const struct bpf_reg_types sock_types = {
8991 	.types = {
8992 		PTR_TO_SOCK_COMMON,
8993 		PTR_TO_SOCKET,
8994 		PTR_TO_TCP_SOCK,
8995 		PTR_TO_XDP_SOCK,
8996 	},
8997 };
8998 
8999 #ifdef CONFIG_NET
9000 static const struct bpf_reg_types btf_id_sock_common_types = {
9001 	.types = {
9002 		PTR_TO_SOCK_COMMON,
9003 		PTR_TO_SOCKET,
9004 		PTR_TO_TCP_SOCK,
9005 		PTR_TO_XDP_SOCK,
9006 		PTR_TO_BTF_ID,
9007 		PTR_TO_BTF_ID | PTR_TRUSTED,
9008 	},
9009 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9010 };
9011 #endif
9012 
9013 static const struct bpf_reg_types mem_types = {
9014 	.types = {
9015 		PTR_TO_STACK,
9016 		PTR_TO_PACKET,
9017 		PTR_TO_PACKET_META,
9018 		PTR_TO_MAP_KEY,
9019 		PTR_TO_MAP_VALUE,
9020 		PTR_TO_MEM,
9021 		PTR_TO_MEM | MEM_RINGBUF,
9022 		PTR_TO_BUF,
9023 		PTR_TO_BTF_ID | PTR_TRUSTED,
9024 		PTR_TO_CTX,
9025 	},
9026 };
9027 
9028 static const struct bpf_reg_types map_value_or_alloc_obj_types = {
9029 	.types = {
9030 		PTR_TO_MAP_VALUE,
9031 		PTR_TO_BTF_ID | MEM_ALLOC,
9032 	}
9033 };
9034 
9035 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9036 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9037 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9038 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9039 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9040 static const struct bpf_reg_types btf_ptr_types = {
9041 	.types = {
9042 		PTR_TO_BTF_ID,
9043 		PTR_TO_BTF_ID | PTR_TRUSTED,
9044 		PTR_TO_BTF_ID | MEM_RCU,
9045 	},
9046 };
9047 static const struct bpf_reg_types percpu_btf_ptr_types = {
9048 	.types = {
9049 		PTR_TO_BTF_ID | MEM_PERCPU,
9050 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9051 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9052 	}
9053 };
9054 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9055 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9056 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9057 static const struct bpf_reg_types map_value_types = { .types = { PTR_TO_MAP_VALUE } };
9058 static const struct bpf_reg_types arena_types = {
9059 	.types = {
9060 		PTR_TO_ARENA,
9061 		SCALAR_VALUE,
9062 	}
9063 };
9064 static const struct bpf_reg_types ctx_out_types = {
9065 	.types = { PTR_TO_MEM | MEM_RDONLY | PTR_TRUSTED },
9066 };
9067 
9068 static const struct bpf_reg_types alloc_obj_drop_types = {
9069 	.types = {
9070 		PTR_TO_BTF_ID | MEM_ALLOC,
9071 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU,
9072 	}
9073 };
9074 
9075 static const struct bpf_reg_types alloc_obj_types = {
9076 	.types = {
9077 		PTR_TO_BTF_ID | MEM_ALLOC,
9078 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU,
9079 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9080 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9081 	}
9082 };
9083 
9084 static const struct bpf_reg_types kptr_xchg_dest_types = {
9085 	.types = {
9086 		PTR_TO_MAP_VALUE,
9087 		PTR_TO_BTF_ID | MEM_ALLOC,
9088 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9089 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9090 	}
9091 };
9092 static const struct bpf_reg_types dynptr_types = {
9093 	.types = {
9094 		PTR_TO_STACK,
9095 		CONST_PTR_TO_DYNPTR,
9096 	}
9097 };
9098 
9099 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9100 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9101 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9102 	[ARG_MEM_SIZE]			= &scalar_types,
9103 	[ARG_MEM_SIZE_OR_ZERO]		= &scalar_types,
9104 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9105 	[ARG_SCALAR]			= &scalar_types,
9106 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9107 	[ARG_PTR_TO_CTX]		= &context_types,
9108 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9109 #ifdef CONFIG_NET
9110 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9111 #endif
9112 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9113 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9114 	[ARG_PTR_TO_SPIN_LOCK]		= &map_value_or_alloc_obj_types,
9115 	[ARG_PTR_TO_MEM]		= &mem_types,
9116 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9117 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9118 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9119 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9120 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9121 	[ARG_PTR_TO_TIMER]		= &map_value_types,
9122 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9123 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9124 	[ARG_CONST_SCALAR]		= &scalar_types,
9125 	[ARG_CONST_MEM_SIZE]		= &scalar_types,
9126 	[ARG_PTR_TO_ALLOC_BTF_ID]	= &alloc_obj_drop_types,
9127 	[ARG_PTR_TO_REFCOUNTED_KPTR]	= &alloc_obj_types,
9128 	[ARG_PTR_TO_ITER]		= &stack_ptr_types,
9129 	[ARG_PTR_TO_LIST_HEAD]		= &map_value_or_alloc_obj_types,
9130 	[ARG_PTR_TO_LIST_NODE]		= &alloc_obj_types,
9131 	[ARG_PTR_TO_RB_ROOT]		= &map_value_or_alloc_obj_types,
9132 	[ARG_PTR_TO_RB_NODE]		= &alloc_obj_types,
9133 	[ARG_PTR_TO_RES_SPIN_LOCK]	= &map_value_or_alloc_obj_types,
9134 	[ARG_PTR_TO_WORKQUEUE]		= &map_value_types,
9135 	[ARG_PTR_TO_TASK_WORK]		= &map_value_types,
9136 	[ARG_PTR_TO_RCU_HEAD]		= &map_value_types,
9137 	[ARG_PTR_TO_IRQ_FLAG]		= &stack_ptr_types,
9138 	[ARG_PTR_TO_ARENA]		= &arena_types,
9139 	[ARG_PTR_TO_CTX_OUT]		= &ctx_out_types,
9140 };
9141 
9142 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
9143 			      const char *call_name, const char *reason,
9144 			      const char *suggestion)
9145 {
9146 	int arg = arg_from_argno(argno);
9147 	int regno = reg_from_argno(argno);
9148 	int stack_slot = -1;
9149 
9150 	if (arg < 0 && regno >= BPF_REG_1 && regno <= BPF_REG_5)
9151 		arg = regno;
9152 	if (arg > MAX_BPF_FUNC_REG_ARGS)
9153 		stack_slot = arg - MAX_BPF_FUNC_REG_ARGS - 1;
9154 
9155 	bpf_diag_call_type(env, insn_idx, arg, regno, stack_slot,
9156 			   call_name && *call_name ? call_name : "call",
9157 			   reg_arg_name(env, argno), reason, suggestion);
9158 }
9159 
9160 static const char *bpf_diag_arg_name(struct bpf_verifier_env *env, argno_t argno)
9161 {
9162 	return bpf_diag_fmt(env, "%s", reg_arg_name(env, argno));
9163 }
9164 
9165 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
9166 						 argno_t argno, const char *call_name,
9167 						 const char *suggestion, const char *fmt, ...)
9168 {
9169 	const char *reason;
9170 	va_list args;
9171 
9172 	va_start(args, fmt);
9173 	reason = bpf_diag_vfmt(env, fmt, args);
9174 	va_end(args);
9175 
9176 	bpf_diag_call_arg(env, insn_idx, argno, call_name, reason, suggestion);
9177 }
9178 
9179 static int check_func_arg_nullability(struct bpf_verifier_env *env,
9180 				      struct bpf_reg_state *reg, u32 arg, argno_t argno,
9181 				      enum bpf_arg_type arg_type,
9182 				      struct bpf_call_arg_meta *meta, int insn_idx)
9183 {
9184 	const char *expected_type = "pointer";
9185 
9186 	if (arg_type_is_scalar(arg_type) || type_may_be_null(arg_type) ||
9187 	    (!bpf_register_is_null(reg) && !type_may_be_null(reg->type)))
9188 		return 0;
9189 
9190 	if (meta->btf) {
9191 		u32 arg_btf_id;
9192 
9193 		arg_btf_id = btf_params(meta->func_proto)[arg].type;
9194 		expected_type = bpf_diag_fmt(env, "value of type %s",
9195 					     bpf_diag_fmt_btf_type(env, meta->btf, arg_btf_id));
9196 	}
9197 
9198 	verbose(env, "Possibly NULL pointer passed to trusted %s\n",
9199 		reg_arg_name(env, argno));
9200 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9201 			      "Add a NULL check and make the call only on the non-NULL path.",
9202 			      "the pointer may be NULL, but this call requires a non-NULL %s",
9203 			      expected_type);
9204 	return -EACCES;
9205 }
9206 
9207 static int check_func_arg_release(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9208 				  u32 arg, argno_t argno, enum bpf_arg_type arg_type,
9209 				  struct bpf_call_arg_meta *meta, int insn_idx)
9210 {
9211 	const char *expected_type = "pointer";
9212 
9213 	if (!arg_type_is_release(arg_type))
9214 		return 0;
9215 
9216 	if (arg_type_is_dynptr(arg_type) || reg_is_referenced(env, reg) ||
9217 	    bpf_register_is_null(reg))
9218 		return 0;
9219 
9220 	verbose(env, "release function %s expects referenced PTR_TO_BTF_ID passed to %s\n",
9221 		meta->func_name, reg_arg_name(env, argno));
9222 
9223 	if (is_kfunc(meta)) {
9224 		const struct btf_param *btf_arg;
9225 		const struct btf_type *t;
9226 		u32 ref_id;
9227 
9228 		btf_arg = &btf_params(meta->func_proto)[arg];
9229 		ref_id = btf_arg->type;
9230 		t = btf_type_skip_modifiers(meta->btf, btf_arg->type, NULL);
9231 		if (btf_type_is_ptr(t))
9232 			btf_type_skip_modifiers(meta->btf, t->type, &ref_id);
9233 		expected_type = bpf_diag_fmt(env, "value of type %s",
9234 					     bpf_diag_fmt_btf_type(env, meta->btf, ref_id));
9235 	}
9236 
9237 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9238 			      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.",
9239 					   expected_type),
9240 			      "release functions require a value that owns a live resource returned by a matching acquire function");
9241 	return -EINVAL;
9242 }
9243 
9244 static const char *bpf_diag_expected_reg_types(struct bpf_verifier_env *env,
9245 					       const enum bpf_reg_type *types, int count)
9246 {
9247 	size_t len = 0, size = 1;
9248 	char *buf;
9249 	int i;
9250 
9251 	for (i = 0; i < count; i++)
9252 		size += strlen(reg_type_str(env, types[i])) + (i ? 2 : 0);
9253 
9254 	buf = bpf_diag_fmt_buf(env, size);
9255 	if (!buf)
9256 		return "";
9257 
9258 	for (i = 0; i < count; i++)
9259 		len += scnprintf(buf + len, size - len, "%s%s", i ? ", " : "",
9260 				 reg_type_str(env, types[i]));
9261 	return buf;
9262 }
9263 
9264 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
9265 			  enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
9266 {
9267 	enum bpf_reg_type expected, type = reg->type;
9268 	const struct bpf_reg_types *compatible;
9269 	const char *actual, *accepted;
9270 	int i, j;
9271 
9272 	compatible = compatible_reg_types[base_type(arg_type)];
9273 	if (!compatible) {
9274 		verifier_bug(env, "unsupported arg type %d", arg_type);
9275 		return -EFAULT;
9276 	}
9277 	if (is_kfunc(meta) && base_type(arg_type) == ARG_PTR_TO_BTF_ID &&
9278 	    (base_type(type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(type)]))
9279 		goto found;
9280 
9281 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9282 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9283 	 *
9284 	 * Same for MAYBE_NULL:
9285 	 *
9286 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9287 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9288 	 *
9289 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9290 	 *
9291 	 * Therefore we fold these flags depending on the arg_type before comparison.
9292 	 */
9293 	if (arg_type & MEM_RDONLY)
9294 		type &= ~MEM_RDONLY;
9295 	if (arg_type & PTR_MAYBE_NULL)
9296 		type &= ~PTR_MAYBE_NULL;
9297 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9298 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9299 	/* Allow allocated memory for BTF-defined ARG_PTR_TO_MEM but not helpers. */
9300 	if (!is_helper(meta) && base_type(arg_type) == ARG_PTR_TO_MEM &&
9301 	    type_is_ptr_alloc_obj(type))
9302 		type = PTR_TO_MEM;
9303 
9304 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9305 	if (is_helper_call(meta, BPF_FUNC_kptr_xchg) && type_is_alloc(type) &&
9306 	    reg_from_argno(argno) == BPF_REG_2) {
9307 		type &= ~MEM_ALLOC;
9308 		type &= ~MEM_PERCPU;
9309 	}
9310 
9311 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9312 		expected = compatible->types[i];
9313 		if (expected == NOT_INIT)
9314 			break;
9315 
9316 		if (type == expected)
9317 			goto found;
9318 	}
9319 
9320 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
9321 	for (j = 0; j + 1 < i; j++)
9322 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9323 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9324 	actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type));
9325 	accepted = bpf_diag_expected_reg_types(env, compatible->types, i);
9326 	bpf_diag_call_arg_fmt(env, env->insn_idx, argno, meta->func_name,
9327 			      bpf_diag_fmt(env, "Pass %s.", bpf_diag_arg_type_plain(arg_type)),
9328 			      "it has type %s, but this argument accepts %s",
9329 			      actual, accepted);
9330 	return -EACCES;
9331 
9332 found:
9333 	return 0;
9334 }
9335 
9336 static struct btf_field *
9337 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9338 {
9339 	struct btf_field *field;
9340 	struct btf_record *rec;
9341 
9342 	rec = reg_btf_record(reg);
9343 	if (!rec)
9344 		return NULL;
9345 
9346 	field = btf_record_find(rec, off, fields);
9347 	if (!field)
9348 		return NULL;
9349 
9350 	return field;
9351 }
9352 
9353 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9354 				  const struct bpf_reg_state *reg, argno_t argno,
9355 				  enum bpf_arg_type arg_type)
9356 {
9357 	u32 type = reg->type;
9358 
9359 	/* When referenced register is passed to release function, its fixed
9360 	 * offset must be 0.
9361 	 *
9362 	 * We will check arg_type_is_release reg has id when storing
9363 	 * meta->release_regno.
9364 	 */
9365 	if (arg_type_is_release(arg_type)) {
9366 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9367 		 * may not directly point to the object being released, but to
9368 		 * dynptr pointing to such object, which might be at some offset
9369 		 * on the stack. In that case, we simply to fallback to the
9370 		 * default handling.
9371 		 */
9372 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9373 			return 0;
9374 
9375 		/* Doing check_ptr_off_reg check for the offset will catch this
9376 		 * because fixed_off_ok is false, but checking here allows us
9377 		 * to give the user a better error message.
9378 		 */
9379 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
9380 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
9381 				reg_arg_name(env, argno));
9382 			return -EINVAL;
9383 		}
9384 	}
9385 
9386 	switch (type) {
9387 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9388 	case PTR_TO_STACK:
9389 	case PTR_TO_PACKET:
9390 	case PTR_TO_PACKET_META:
9391 	case PTR_TO_MAP_KEY:
9392 	case PTR_TO_MAP_VALUE:
9393 	case PTR_TO_MEM:
9394 	case PTR_TO_MEM | MEM_RDONLY:
9395 	case PTR_TO_MEM | MEM_RINGBUF:
9396 	case PTR_TO_BUF:
9397 	case PTR_TO_BUF | MEM_RDONLY:
9398 	case PTR_TO_ARENA:
9399 	case SCALAR_VALUE:
9400 		return 0;
9401 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9402 	 * fixed offset.
9403 	 */
9404 	case PTR_TO_BTF_ID:
9405 	case PTR_TO_BTF_ID | MEM_ALLOC:
9406 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9407 	case PTR_TO_BTF_ID | MEM_RCU:
9408 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9409 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9410 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9411 		 * its fixed offset must be 0. bpf_refcount_acquire() returns the
9412 		 * pointer it was given while incrementing the refcount at the
9413 		 * refcount field offset, so it needs a zero offset too. In the
9414 		 * other cases, fixed offset can be non-zero. var_off always must
9415 		 * be 0 for PTR_TO_BTF_ID, hence we still need to do checks
9416 		 * instead of returning.
9417 		 */
9418 		return __check_ptr_off_reg(env, reg, argno,
9419 					   base_type(arg_type) != ARG_PTR_TO_REFCOUNTED_KPTR);
9420 	case PTR_TO_CTX:
9421 		/*
9422 		 * Allow fixed and variable offsets for syscall context, but
9423 		 * only when the argument is passed as memory, not ctx,
9424 		 * otherwise we may get modified ctx in tail called programs and
9425 		 * global subprogs (that may act as extension prog hooks).
9426 		 */
9427 		if (base_type(arg_type) != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
9428 			return 0;
9429 		fallthrough;
9430 	default:
9431 		return __check_ptr_off_reg(env, reg, argno, false);
9432 	}
9433 }
9434 
9435 static int check_arg_const_str(struct bpf_verifier_env *env,
9436 			       struct bpf_reg_state *reg, argno_t argno)
9437 {
9438 	struct bpf_map *map = reg->map_ptr;
9439 	int err;
9440 	int map_off;
9441 	u64 map_addr;
9442 	char *str_ptr;
9443 	u32 cnt;
9444 
9445 	if (reg->type != PTR_TO_MAP_VALUE)
9446 		return -EINVAL;
9447 
9448 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9449 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
9450 			reg_arg_name(env, argno));
9451 		return -EACCES;
9452 	}
9453 
9454 	if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
9455 		verbose(env, "%s points to percpu_array map which cannot be used as const string\n",
9456 			reg_arg_name(env, argno));
9457 		return -EACCES;
9458 	}
9459 
9460 	if (!bpf_map_is_rdonly(map)) {
9461 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
9462 		return -EACCES;
9463 	}
9464 
9465 	if (!tnum_is_const(reg->var_off)) {
9466 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
9467 		return -EACCES;
9468 	}
9469 
9470 	if (!map->ops->map_direct_value_addr) {
9471 		verbose(env, "no direct value access support for this map type\n");
9472 		return -EACCES;
9473 	}
9474 
9475 	err = check_map_access(env, reg, argno, 0,
9476 			       map->value_size - reg->var_off.value, false,
9477 			       ACCESS_HELPER);
9478 	if (err)
9479 		return err;
9480 
9481 	map_off = reg->var_off.value;
9482 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9483 	if (err) {
9484 		verbose(env, "direct value access on string failed\n");
9485 		return err;
9486 	}
9487 
9488 	str_ptr = (char *)(long)(map_addr);
9489 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9490 		verbose(env, "string is not zero-terminated\n");
9491 		return -EINVAL;
9492 	}
9493 	/* the bytes of a pointer to a function are not known until the program is jitted */
9494 	if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) {
9495 		verbose(env, "string overlaps with a pointer to a function\n");
9496 		return -EACCES;
9497 	}
9498 	return 0;
9499 }
9500 
9501 /* Returns constant key value in `value` if possible, else negative error */
9502 static int get_constant_map_key(struct bpf_verifier_env *env,
9503 				struct bpf_reg_state *key,
9504 				u32 key_size,
9505 				s64 *value)
9506 {
9507 	struct bpf_func_state *state = bpf_func(env, key);
9508 	struct bpf_stack_state *ss;
9509 	struct bpf_reg_state *reg;
9510 	int slot, spi, off;
9511 	int spill_size = 0;
9512 	int zero_size = 0;
9513 	int stack_off;
9514 	int i, err;
9515 	u8 *stype;
9516 
9517 	if (!env->bpf_capable)
9518 		return -EOPNOTSUPP;
9519 	if (key->type != PTR_TO_STACK)
9520 		return -EOPNOTSUPP;
9521 	if (!tnum_is_const(key->var_off))
9522 		return -EOPNOTSUPP;
9523 
9524 	stack_off = key->var_off.value;
9525 	slot = -stack_off - 1;
9526 	spi = slot / BPF_REG_SIZE;
9527 	off = slot % BPF_REG_SIZE;
9528 	ss = bpf_stack_slot(state, spi);
9529 	stype = ss->slot_type;
9530 
9531 	/* First handle precisely tracked STACK_ZERO */
9532 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9533 		zero_size++;
9534 	if (zero_size >= key_size) {
9535 		*value = 0;
9536 		return 0;
9537 	}
9538 
9539 	/* Check that stack contains a scalar spill of expected size */
9540 	if (!bpf_is_spilled_scalar_reg(ss))
9541 		return -EOPNOTSUPP;
9542 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9543 		spill_size++;
9544 	if (spill_size != key_size)
9545 		return -EOPNOTSUPP;
9546 
9547 	reg = &ss->spilled_ptr;
9548 	if (!tnum_is_const(reg->var_off))
9549 		/* Stack value not statically known */
9550 		return -EOPNOTSUPP;
9551 
9552 	/* We are relying on a constant value. So mark as precise
9553 	 * to prevent pruning on it.
9554 	 */
9555 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
9556 	err = mark_chain_precision_batch(env, env->cur_state);
9557 	if (err < 0)
9558 		return err;
9559 
9560 	*value = reg->var_off.value;
9561 	return 0;
9562 }
9563 
9564 static bool can_elide_value_nullness(const struct bpf_map *map);
9565 
9566 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9567 			       argno_t argno, struct bpf_call_arg_meta *meta)
9568 {
9569 	/* Use map_uid (which is unique id of inner map) to reject:
9570 	 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9571 	 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9572 	 * if (inner_map1 && inner_map2) {
9573 	 *     timer = bpf_map_lookup_elem(inner_map1);
9574 	 *     if (timer)
9575 	 *         // mismatch would have been allowed
9576 	 *         bpf_timer_init(timer, inner_map2);
9577 	 * }
9578 	 *
9579 	 * Comparing map_ptr is enough to distinguish normal and outer maps.
9580 	 */
9581 	if (meta->map.ptr &&
9582 	    (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) {
9583 		argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1);
9584 		struct btf_record *rec = meta->map.ptr->record;
9585 		const char *obj_name = "workqueue";
9586 
9587 		if (rec->timer_off >= 0)
9588 			obj_name = "timer";
9589 		else if (rec->task_work_off >= 0)
9590 			obj_name = "bpf_task_work";
9591 		else if (rec->rcu_head_off >= 0)
9592 			obj_name = "bpf_rcu_head";
9593 
9594 		verbose(env, "%s pointer in %s map_uid=%d ",
9595 			obj_name, reg_arg_name(env, obj_argno), meta->map.uid);
9596 		verbose(env, "doesn't match map pointer in %s map_uid=%d\n",
9597 			reg_arg_name(env, argno), reg->map_uid);
9598 		return -EINVAL;
9599 	}
9600 
9601 	meta->map.ptr = reg->map_ptr;
9602 	meta->map.uid = reg->map_uid;
9603 	return 0;
9604 }
9605 
9606 /*
9607  * MEM_WRITE alone denotes an input/output buffer. MEM_UNINIT marks an output
9608  * whose incoming contents are not read.
9609  */
9610 static enum bpf_access_type func_arg_access_type(enum bpf_arg_type arg_type)
9611 {
9612 	if (!(arg_type & MEM_WRITE))
9613 		return BPF_READ;
9614 	if (arg_type & MEM_UNINIT)
9615 		return BPF_WRITE;
9616 	return BPF_READ | BPF_WRITE;
9617 }
9618 
9619 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,
9620 			  struct bpf_call_arg_meta *meta,
9621 			  int insn_idx)
9622 {
9623 	const struct btf_param *btf_arg = is_kfunc(meta) ?
9624 					  &btf_params(meta->func_proto)[arg] : NULL;
9625 	const struct bpf_func_proto *fn = meta->fn;
9626 	struct bpf_func_state *caller = cur_func(env);
9627 	struct bpf_reg_state *regs = cur_regs(env);
9628 	argno_t argno = argno_from_arg(slot + 1);
9629 	struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, slot);
9630 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9631 	int regno = reg_from_argno(argno);
9632 	u32 arg_size = arg_type & MEM_FIXED_SIZE ? fn->arg_size[arg] : 0;
9633 	u32 key_size;
9634 	int err = 0;
9635 
9636 	if (arg_type == ARG_PTR_TO_PROG_AUX) {
9637 		cur_aux(env)->arg_prog = regno;
9638 		return 0;
9639 	}
9640 
9641 	if (arg_type == ARG_IGNORE)
9642 		return 0;
9643 
9644 	if (regno >= 0) {
9645 		err = check_reg_arg(env, regno, SRC_OP);
9646 		if (err)
9647 			return err;
9648 	}
9649 
9650 	/* Preserve the legacy helper behavior for privileged pointer leaks. */
9651 	if (arg_type == ARG_ANYTHING) {
9652 		if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
9653 			verbose(env, "%s leaks addr into helper function\n",
9654 				reg_arg_name(env, argno));
9655 			return -EACCES;
9656 		}
9657 		return 0;
9658 	}
9659 
9660 	err = resolve_func_arg_type(env, reg, arg, argno, meta, &arg_type, &arg_size);
9661 	if (err)
9662 		return err;
9663 
9664 	if (arg_type_is_raw_mem(arg_type))
9665 		meta->arg_raw_mem.mask |= BIT(slot);
9666 
9667 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) {
9668 		err = mark_arg_precision(env, argno);
9669 		if (err)
9670 			return err;
9671 		return 0;
9672 	}
9673 
9674 	err = check_func_arg_nullability(env, reg, arg, argno, arg_type, meta, insn_idx);
9675 	if (err)
9676 		return err;
9677 
9678 	err = check_reg_type(env, reg, argno, arg_type, meta);
9679 	if (err)
9680 		return err;
9681 
9682 	err = check_func_arg_reg_off(env, reg, argno, arg_type);
9683 	if (err)
9684 		return err;
9685 
9686 	err = check_func_arg_release(env, reg, arg, argno, arg_type, meta, insn_idx);
9687 	if (err)
9688 		return err;
9689 
9690 	if (reg_is_referenced(env, reg))
9691 		update_ref_obj(&meta->ref_obj, reg);
9692 
9693 	switch (base_type(arg_type)) {
9694 	case ARG_CONST_SCALAR:
9695 		err = process_const_arg(env, reg, argno, meta);
9696 		if (err < 0) {
9697 			if (err == -EINVAL)
9698 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9699 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
9700 						      "the function requires this scalar argument to be a verifier-known constant, but %s is variable on this path",
9701 						      reg_arg_name(env, argno));
9702 			return err;
9703 		}
9704 		break;
9705 	case ARG_SCALAR:
9706 		break;
9707 	case ARG_CONST_MAP_PTR:
9708 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9709 		err = process_map_ptr_arg(env, reg, argno, meta);
9710 		if (err)
9711 			return err;
9712 		break;
9713 	case ARG_PTR_TO_MAP_KEY:
9714 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9715 		 * check that [key, key + map->key_size) are within
9716 		 * stack limits and initialized
9717 		 */
9718 		if (!meta->map.ptr) {
9719 			/* in function declaration map_ptr must come before
9720 			 * map_key, so that it's verified and known before
9721 			 * we have to check map_key here. Otherwise it means
9722 			 * that kernel subsystem misconfigured verifier
9723 			 */
9724 			verifier_bug(env, "invalid map_ptr to access map->key");
9725 			return -EFAULT;
9726 		}
9727 		key_size = meta->map.ptr->key_size;
9728 		err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, meta,
9729 					      NULL);
9730 		if (err)
9731 			return err;
9732 		if (can_elide_value_nullness(meta->map.ptr)) {
9733 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9734 			if (err < 0) {
9735 				meta->const_map_key = -1;
9736 				if (err == -EOPNOTSUPP)
9737 					err = 0;
9738 				else
9739 					return err;
9740 			}
9741 		}
9742 		break;
9743 	case ARG_PTR_TO_MAP_VALUE:
9744 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
9745 			return 0;
9746 
9747 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9748 		 * check [value, value + map->value_size) validity
9749 		 */
9750 		if (!meta->map.ptr) {
9751 			/* kernel subsystem misconfigured verifier */
9752 			verifier_bug(env, "invalid map_ptr to access map->value");
9753 			return -EFAULT;
9754 		}
9755 
9756 		err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size,
9757 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9758 					      false, meta, NULL);
9759 		break;
9760 	case ARG_PTR_TO_BTF_ID:
9761 	case ARG_PTR_TO_BTF_ID_SOCK_COMMON:
9762 	{
9763 		const u32 *arg_btf_id = fn->arg_btf_id[arg];
9764 		const struct btf *arg_btf = is_kfunc(meta) ? meta->btf : btf_vmlinux;
9765 
9766 		if (!meta->btf) {
9767 			const struct bpf_reg_types *compatible;
9768 
9769 			if (base_type(reg->type) != PTR_TO_BTF_ID)
9770 				break;
9771 
9772 			if (is_helper_call(meta, BPF_FUNC_kptr_xchg))
9773 				return map_kptr_match_type(env, meta->kptr_field, reg, regno) ?
9774 				       -EACCES : 0;
9775 
9776 			if (!arg_btf_id) {
9777 				compatible = compatible_reg_types[base_type(arg_type)];
9778 				if (!compatible->btf_id) {
9779 					verifier_bug(env, "missing arg compatible BTF ID");
9780 					return -EFAULT;
9781 				}
9782 				arg_btf_id = compatible->btf_id;
9783 			}
9784 			if (arg_btf_id == BPF_PTR_POISON) {
9785 				verbose(env, "verifier internal error:");
9786 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
9787 					reg_arg_name(env, argno));
9788 				return -EACCES;
9789 			}
9790 		}
9791 
9792 		if (is_kfunc(meta) && (!is_trusted_reg(env, reg) ||
9793 				       bpf_type_has_unsafe_modifiers(reg->type))) {
9794 			if (!(arg_type & MEM_RCU)) {
9795 				const char *actual_type, *arg_name, *expected_type;
9796 
9797 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
9798 				verbose(env, "%s must be referenced or trusted\n",
9799 					reg_arg_name(env, argno));
9800 				arg_name = reg_arg_name(env, argno);
9801 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
9802 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9803 						      "Pass a pointer acquired from a verifier-tracked source, or call this function only inside the required protection if it accepts RCU pointers.",
9804 						      "the function requires a trusted or resource-owning pointer to %s, but %s is %s",
9805 						      expected_type, arg_name, actual_type);
9806 				return -EINVAL;
9807 			}
9808 			if (!is_rcu_reg(reg)) {
9809 				const char *actual_type, *arg_name, *expected_type;
9810 
9811 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
9812 				verbose(env, "%s must be a rcu pointer\n",
9813 					reg_arg_name(env, argno));
9814 				arg_name = reg_arg_name(env, argno);
9815 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
9816 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9817 						      "Use this function with a pointer that is valid in an RCU read lock region.",
9818 						      "the function requires an RCU-protected pointer to %s, but %s is %s",
9819 						      expected_type, arg_name, actual_type);
9820 				return -EINVAL;
9821 			}
9822 		}
9823 
9824 		err = process_arg_ptr_to_btf_id(env, reg, argno, arg_type, arg_btf,
9825 						*arg_btf_id, meta, insn_idx);
9826 		if (err < 0)
9827 			return err;
9828 		break;
9829 	}
9830 	case ARG_PTR_TO_PERCPU_BTF_ID:
9831 		if (!reg->btf_id) {
9832 			verbose(env, "Helper has invalid btf_id in %s\n", reg_arg_name(env, argno));
9833 			return -EACCES;
9834 		}
9835 		meta->ret_btf = reg->btf;
9836 		meta->ret_btf_id = reg->btf_id;
9837 		break;
9838 	case ARG_PTR_TO_SPIN_LOCK:
9839 		if (in_rbtree_lock_required_cb(env)) {
9840 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9841 			return -EACCES;
9842 		}
9843 		if (is_helper_call(meta, BPF_FUNC_spin_lock)) {
9844 			err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK);
9845 			if (err)
9846 				return err;
9847 		} else if (is_helper_call(meta, BPF_FUNC_spin_unlock)) {
9848 			err = process_spin_lock(env, reg, argno, 0);
9849 			if (err)
9850 				return err;
9851 		} else {
9852 			verifier_bug(env, "spin lock arg on unexpected helper");
9853 			return -EFAULT;
9854 		}
9855 		break;
9856 	case ARG_PTR_TO_TIMER:
9857 		err = process_timer_func(env, reg, argno, &meta->map);
9858 		if (err)
9859 			return err;
9860 		break;
9861 	case ARG_PTR_TO_CTX:
9862 		if (is_bpf_cast_to_kern_ctx_kfunc(meta)) {
9863 			err = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
9864 			if (err < 0)
9865 				return -EINVAL;
9866 			meta->ret_btf_id = err;
9867 		}
9868 		break;
9869 	case ARG_PTR_TO_ARENA:
9870 		break;
9871 	case ARG_PTR_TO_ALLOC_BTF_ID:
9872 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
9873 			if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
9874 				verbose(env, "%s expected for bpf_obj_drop()\n",
9875 					reg_arg_name(env, argno));
9876 				return -EINVAL;
9877 			}
9878 		} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
9879 			if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
9880 				verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
9881 					reg_arg_name(env, argno));
9882 				return -EINVAL;
9883 			}
9884 		}
9885 		if (!reg_is_referenced(env, reg)) {
9886 			verbose(env, "allocated object must be referenced\n");
9887 			bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9888 					      "Pass the owned object pointer before it is released or transferred.",
9889 					      "the allocated object pointer in %s must still carry verifier-tracked ownership, but this pointer no longer owns a live resource",
9890 					      reg_arg_name(env, argno));
9891 			return -EINVAL;
9892 		}
9893 		if (meta->btf == btf_vmlinux) {
9894 			meta->arg_btf = reg->btf;
9895 			meta->arg_btf_id = reg->btf_id;
9896 		}
9897 		break;
9898 	case ARG_PTR_TO_FUNC:
9899 		meta->subprogno = reg->subprogno;
9900 		break;
9901 	case ARG_PTR_TO_MEM:
9902 	{
9903 		enum bpf_access_type access_type;
9904 		bool known_memory;
9905 
9906 		/* The access to this pointer is only checked when we hit the
9907 		 * next is_mem_size argument below.
9908 		 */
9909 		if (!(arg_type & MEM_FIXED_SIZE))
9910 			break;
9911 
9912 		access_type = func_arg_access_type(arg_type);
9913 
9914 		err = check_mem_reg(env, reg, argno, arg_size, access_type, meta, &known_memory);
9915 		if (err < 0) {
9916 			if (known_memory)
9917 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9918 					"Pass memory with at least the required number of accessible bytes and suitable read or write access.",
9919 					"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",
9920 					arg_size,
9921 					bpf_diag_reg_type_plain(env, reg->type));
9922 			else
9923 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9924 					"Pass stack, map, context, or other verifier-known memory of the expected type and size, not an integer cast to a pointer.",
9925 					"the function expects %u bytes of memory, but it is %s and not verifier-known memory",
9926 					arg_size,
9927 					bpf_diag_reg_type_plain(env, reg->type));
9928 			return err;
9929 		}
9930 		/*
9931 		 * PTR_TO_PACKET gets passed as PTR_TO_MEM, preventing us from adjusting
9932 		 * bounds tracking information.
9933 		 */
9934 		if (is_subprog(meta) && meta->subprog_may_change_pkt &&
9935 		    (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))) {
9936 			verbose(env,
9937 				"cannot pass packet pointer %s to %s(): function may change packet data\n",
9938 				reg_arg_name(env, argno), meta->func_name);
9939 			return -EINVAL;
9940 		}
9941 		if (arg_type & MEM_ALIGNED)
9942 			err = check_ptr_alignment(env, reg, 0, arg_size, true);
9943 		break;
9944 	}
9945 	case ARG_CONST_MEM_SIZE:
9946 		err = process_const_arg(env, reg, argno, meta);
9947 		if (err < 0) {
9948 			if (err == -EINVAL)
9949 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9950 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
9951 						      "the function requires this memory size to be a verifier-known constant, but %s is variable on this path",
9952 						      reg_arg_name(env, argno));
9953 			return err;
9954 		}
9955 		fallthrough;
9956 	case ARG_MEM_SIZE:
9957 	case ARG_MEM_SIZE_OR_ZERO:
9958 	{
9959 		struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, prev_slot);
9960 		argno_t buff_argno = argno_from_arg(prev_slot + 1);
9961 		enum bpf_mem_size_failure failure;
9962 		const char *buff_arg, *size_arg;
9963 		bool zero_size_allowed;
9964 		u32 access_type;
9965 
9966 		if (meta->btf && bpf_register_is_null(buff_reg))
9967 			break;
9968 
9969 		access_type = func_arg_access_type(fn->arg_type[arg - 1]);
9970 
9971 		zero_size_allowed = meta->btf || base_type(arg_type) == ARG_MEM_SIZE_OR_ZERO;
9972 
9973 		err = check_mem_size_reg(env, buff_reg, reg, buff_argno, argno,
9974 					 access_type, zero_size_allowed, meta, &failure);
9975 		if (!err)
9976 			break;
9977 
9978 		buff_arg = bpf_diag_arg_name(env, buff_argno);
9979 		size_arg = bpf_diag_arg_name(env, argno);
9980 		verbose(env, "%s and ", reg_arg_name(env, buff_argno));
9981 		verbose(env, "%s memory, len pair leads to invalid memory access\n",
9982 			reg_arg_name(env, argno));
9983 		if (failure == BPF_MEM_SIZE_FAIL_MEMORY) {
9984 			bpf_diag_call_arg_fmt(env, insn_idx, buff_argno, meta->func_name,
9985 					      "Pass a stack, map, context, or other verifier-known memory pointer, and keep the paired length within that object.",
9986 					      "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",
9987 					      size_arg, buff_arg);
9988 		} else if (failure == BPF_MEM_SIZE_FAIL_SIZE) {
9989 			if (reg_smin(reg) < 0)
9990 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9991 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
9992 					"the memory size in %s may be negative because its signed minimum is %lld",
9993 					size_arg, reg_smin(reg));
9994 			else if (!zero_size_allowed && reg_umin(reg) == 0)
9995 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9996 					"Ensure the memory size is non-zero before this call.",
9997 					"the memory size in %s may be zero, but the function requires a non-zero size",
9998 					size_arg);
9999 			else
10000 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10001 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
10002 					"the memory size in %s may reach %llu bytes, but variable memory accesses must stay below %u bytes",
10003 					size_arg, reg_umax(reg), BPF_MAX_VAR_SIZ);
10004 		}
10005 		break;
10006 	}
10007 	case ARG_PTR_TO_DYNPTR: {
10008 		if (is_bpf_dynptr_clone_kfunc(meta) &&
10009 		    (arg_type & MEM_UNINIT)) {
10010 			enum bpf_dynptr_type parent_type = meta->dynptr.type;
10011 
10012 			if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10013 				verifier_bug(env, "no dynptr type for parent of clone");
10014 				return -EFAULT;
10015 			}
10016 
10017 			arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10018 		}
10019 
10020 		err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, meta);
10021 		if (err)
10022 			return err;
10023 		break;
10024 	}
10025 	case ARG_PTR_TO_ITER:
10026 		if (is_bpf_iter_css_task_new_kfunc(meta) &&
10027 		    !check_css_task_iter_allowlist(env)) {
10028 			verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
10029 			return -EINVAL;
10030 		}
10031 		err = process_iter_arg(env, reg, arg, argno, insn_idx, meta);
10032 		if (err < 0)
10033 			return err;
10034 		break;
10035 	case ARG_PTR_TO_LIST_HEAD:
10036 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10037 		    !reg_is_referenced(env, reg)) {
10038 			verbose(env, "allocated object must be referenced\n");
10039 			return -EINVAL;
10040 		}
10041 		err = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
10042 		if (err < 0)
10043 			return err;
10044 		break;
10045 	case ARG_PTR_TO_RB_ROOT:
10046 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10047 		    !reg_is_referenced(env, reg)) {
10048 			verbose(env, "allocated object must be referenced\n");
10049 			return -EINVAL;
10050 		}
10051 		err = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
10052 		if (err < 0)
10053 			return err;
10054 		break;
10055 	case ARG_PTR_TO_LIST_NODE:
10056 		if (!(is_kfunc_arg_nonown_allowed(meta->btf, btf_arg) &&
10057 		      type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg))) {
10058 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10059 				verbose(env, "%s expected pointer to allocated object\n",
10060 					reg_arg_name(env, argno));
10061 				return -EINVAL;
10062 			}
10063 			if (!reg_is_referenced(env, reg)) {
10064 				verbose(env, "allocated object must be referenced\n");
10065 				return -EINVAL;
10066 			}
10067 		}
10068 		err = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
10069 		if (err < 0)
10070 			return err;
10071 		break;
10072 	case ARG_PTR_TO_RB_NODE:
10073 		if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
10074 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10075 				verbose(env, "%s expected pointer to allocated object\n",
10076 					reg_arg_name(env, argno));
10077 				return -EINVAL;
10078 			}
10079 			if (!reg_is_referenced(env, reg)) {
10080 				verbose(env, "allocated object must be referenced\n");
10081 				return -EINVAL;
10082 			}
10083 		} else {
10084 			if (!type_is_non_owning_ref(reg->type) &&
10085 			    !reg_is_referenced(env, reg)) {
10086 				verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n",
10087 					meta->func_name);
10088 				return -EINVAL;
10089 			}
10090 			if (in_rbtree_lock_required_cb(env)) {
10091 				verbose(env, "%s not allowed in rbtree cb\n", meta->func_name);
10092 				return -EINVAL;
10093 			}
10094 		}
10095 		err = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
10096 		if (err < 0)
10097 			return err;
10098 		break;
10099 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
10100 		if (meta->btf && is_kfunc_arg_scalar_with_name(meta->btf, btf_arg,
10101 							       "rdonly_buf_size"))
10102 			meta->r0_rdonly = true;
10103 		err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem);
10104 		if (err < 0) {
10105 			if (meta->btf && err == -EINVAL)
10106 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10107 						      "Pass a verifier-known constant size for this function's buffer argument.",
10108 						      "the function uses this argument as a return-buffer size, but %s is invalid or variable on this path",
10109 						      reg_arg_name(env, argno));
10110 			return err;
10111 		}
10112 		break;
10113 	case ARG_PTR_TO_REFCOUNTED_KPTR:
10114 	{
10115 		struct btf_record *rec;
10116 
10117 		if (!type_is_non_owning_ref(reg->type) && reg_is_referenced(env, reg))
10118 			meta->arg_owning_ref = true;
10119 
10120 		rec = reg_btf_record(reg);
10121 		if (!rec) {
10122 			verifier_bug(env, "Couldn't find btf_record");
10123 			return -EFAULT;
10124 		}
10125 
10126 		if (rec->refcount_off < 0) {
10127 			verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
10128 				reg_arg_name(env, argno));
10129 			return -EINVAL;
10130 		}
10131 
10132 		meta->arg_btf = reg->btf;
10133 		meta->arg_btf_id = reg->btf_id;
10134 		break;
10135 	}
10136 	case ARG_PTR_TO_CONST_STR:
10137 	{
10138 		err = check_arg_const_str(env, reg, argno);
10139 		if (err)
10140 			return err;
10141 		break;
10142 	}
10143 	case ARG_PTR_TO_WORKQUEUE:
10144 		err = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
10145 		if (err < 0)
10146 			return err;
10147 		break;
10148 	case ARG_PTR_TO_TASK_WORK:
10149 		err = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
10150 		if (err < 0)
10151 			return err;
10152 		break;
10153 	case ARG_PTR_TO_RCU_HEAD:
10154 		err = check_map_field_pointer(env, reg, argno, BPF_RCU_HEAD, &meta->map);
10155 		if (err < 0)
10156 			return err;
10157 		break;
10158 	case ARG_PTR_TO_IRQ_FLAG:
10159 		err = process_irq_flag(env, reg, argno, meta);
10160 		if (err < 0)
10161 			return err;
10162 		break;
10163 	case ARG_PTR_TO_CTX_OUT:
10164 		if (reg->mem_size != arg_size) {
10165 			verbose(env, "%s expected %u bytes of ctx-provided memory, got %u\n",
10166 				reg_arg_name(env, argno), arg_size, reg->mem_size);
10167 			return -EINVAL;
10168 		}
10169 		break;
10170 	case ARG_PTR_TO_RES_SPIN_LOCK:
10171 	{
10172 		int flags;
10173 
10174 		if (in_rbtree_lock_required_cb(env)) {
10175 			verbose(env, "can't res_spin_{lock,unlock} in rbtree cb\n");
10176 			return -EACCES;
10177 		}
10178 
10179 		flags = get_bpf_res_spin_lock_kfunc_flags(meta);
10180 		if (!flags)
10181 			return -EFAULT;
10182 		err = process_spin_lock(env, reg, argno, flags);
10183 		if (err < 0)
10184 			return err;
10185 		break;
10186 	}
10187 	case ARG_KPTR_XCHG_DEST:
10188 		err = process_kptr_func(env, regno, meta);
10189 		if (err)
10190 			return err;
10191 		break;
10192 	}
10193 
10194 	return err;
10195 }
10196 
10197 /*
10198  * The slots a parameter takes, from its BTF type. This has to agree with
10199  * btf_func_model_arg_slots(), which answers the same from the size the
10200  * func model recorded, or the verifier would check an argument at a slot
10201  * the JIT does not place it at.
10202  */
10203 static u32 btf_arg_slots(const struct btf_type *t)
10204 {
10205 	if (btf_type_is_int(t) || btf_type_is_struct(t))
10206 		return (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE;
10207 	return 1;
10208 }
10209 
10210 static u32 btf_proto_slots(const struct btf *btf, const struct btf_type *func_proto)
10211 {
10212 	const struct btf_param *args = btf_params(func_proto);
10213 	u32 i, nargs = btf_type_vlen(func_proto), slots_used = 0;
10214 
10215 	for (i = 0; i < nargs; i++)
10216 		slots_used += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
10217 
10218 	return slots_used;
10219 }
10220 
10221 /* The argument slot @slot holds an eightbyte of a by-value argument. */
10222 static int check_arg_extra_slot(struct bpf_verifier_env *env, struct bpf_func_state *caller,
10223 				u32 slot, struct bpf_call_arg_meta *meta)
10224 {
10225 	struct bpf_reg_state *reg = get_func_arg_reg(caller, cur_regs(env), slot);
10226 	argno_t argno = argno_from_arg(slot + 1);
10227 	int regno = reg_from_argno(argno);
10228 	int err;
10229 
10230 	if (regno >= 0) {
10231 		err = check_reg_arg(env, regno, SRC_OP);
10232 		if (err)
10233 			return err;
10234 	}
10235 
10236 	return check_reg_type(env, reg, argno, ARG_SCALAR, meta);
10237 }
10238 
10239 static int check_func_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10240 			   int insn_idx)
10241 {
10242 	u32 slot = 0, prev_slot = 0, proto_slots, nslots;
10243 	struct bpf_func_state *caller = cur_func(env);
10244 	const struct btf_param *args = NULL;
10245 	u32 arg, nargs = MAX_BPF_FUNC_REG_ARGS;
10246 	int err;
10247 
10248 	if (meta->btf) {
10249 		args = btf_params(meta->func_proto);
10250 		nargs = btf_type_vlen(meta->func_proto);
10251 	}
10252 
10253 	/*
10254 	 * A by-value argument of more than one eightbyte takes a slot per
10255 	 * eightbyte, so the slots a call occupies are no longer its parameter
10256 	 * count. Only a proto whose parameters take a slot each can name the
10257 	 * argument a stack slot belongs to.
10258 	 */
10259 	proto_slots = meta->btf ? btf_proto_slots(meta->btf, meta->func_proto) : nargs;
10260 
10261 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
10262 		err = check_outgoing_stack_args(env, caller, proto_slots, meta->func_name,
10263 						meta->btf, proto_slots == nargs ? args : NULL);
10264 		if (err)
10265 			return err;
10266 	}
10267 
10268 	for (arg = 0; arg < nargs; arg++, prev_slot = slot, slot += nslots) {
10269 		const struct btf_type *t;
10270 		u32 k;
10271 
10272 		nslots = 1;
10273 		if (args) {
10274 			t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
10275 			nslots = btf_arg_slots(t);
10276 		}
10277 
10278 		if (meta->fn->arg_type[arg] == ARG_UNUSED)
10279 			break;
10280 		err = check_func_arg(env, arg, slot, prev_slot, meta, insn_idx);
10281 		if (err)
10282 			return err;
10283 
10284 		/*
10285 		 * check_func_arg() took the first slot. A parameter of more
10286 		 * than one eightbyte is always a scalar, so every slot it
10287 		 * takes beyond the first holds one too.
10288 		 */
10289 		for (k = 1; k < nslots; k++) {
10290 			err = check_arg_extra_slot(env, caller, slot + k, meta);
10291 			if (err)
10292 				return err;
10293 		}
10294 	}
10295 
10296 	return 0;
10297 }
10298 
10299 static int mark_raw_stack(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10300 			  int insn_idx)
10301 {
10302 	struct bpf_func_state *caller = cur_func(env);
10303 	u32 slot;
10304 	int i, err;
10305 
10306 	/*
10307 	 * Validate every argument before initializing outputs: an input argument
10308 	 * may alias an output buffer. Use the normal stack-write checks to discard
10309 	 * stale spills and preserve the rules for special stack objects.
10310 	 */
10311 	for (slot = 0; slot < MAX_BPF_FUNC_ARGS; slot++) {
10312 		struct bpf_reg_state *reg;
10313 		argno_t argno = argno_from_arg(slot + 1);
10314 
10315 		if (!meta->arg_raw_mem.size[slot])
10316 			continue;
10317 		reg = get_func_arg_reg(caller, cur_regs(env), slot);
10318 
10319 		for (i = 0; i < meta->arg_raw_mem.size[slot]; i++) {
10320 			err = check_mem_access(env, insn_idx, reg, argno, i, BPF_B,
10321 					       BPF_WRITE, -1, false, false);
10322 			if (err)
10323 				return err;
10324 		}
10325 	}
10326 
10327 	return 0;
10328 }
10329 
10330 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
10331 {
10332 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
10333 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10334 
10335 	if (func_id != BPF_FUNC_map_update_elem &&
10336 	    func_id != BPF_FUNC_map_delete_elem)
10337 		return false;
10338 
10339 	/* It's not possible to get access to a locked struct sock in these
10340 	 * contexts, so updating is safe.
10341 	 */
10342 	switch (type) {
10343 	case BPF_PROG_TYPE_TRACING:
10344 		if (eatype == BPF_TRACE_ITER)
10345 			return true;
10346 		break;
10347 	case BPF_PROG_TYPE_SOCK_OPS:
10348 		/* map_update allowed only via dedicated helpers with event type checks */
10349 		if (func_id == BPF_FUNC_map_delete_elem)
10350 			return true;
10351 		break;
10352 	case BPF_PROG_TYPE_SK_REUSEPORT:
10353 	case BPF_PROG_TYPE_SK_LOOKUP:
10354 		return true;
10355 	default:
10356 		break;
10357 	}
10358 
10359 	verbose(env, "cannot update sockmap in this context\n");
10360 	return false;
10361 }
10362 
10363 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10364 {
10365 	return env->prog->jit_requested &&
10366 	       bpf_jit_supports_subprog_tailcalls();
10367 }
10368 
10369 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10370 					struct bpf_map *map, int func_id)
10371 {
10372 	if (!map)
10373 		return 0;
10374 
10375 	/* We need a two way check, first is from map perspective ... */
10376 	switch (map->map_type) {
10377 	case BPF_MAP_TYPE_PROG_ARRAY:
10378 		if (func_id != BPF_FUNC_tail_call)
10379 			goto error;
10380 		break;
10381 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10382 		if (func_id != BPF_FUNC_perf_event_read &&
10383 		    func_id != BPF_FUNC_perf_event_output &&
10384 		    func_id != BPF_FUNC_skb_output &&
10385 		    func_id != BPF_FUNC_perf_event_read_value &&
10386 		    func_id != BPF_FUNC_xdp_output)
10387 			goto error;
10388 		break;
10389 	case BPF_MAP_TYPE_RINGBUF:
10390 		if (func_id != BPF_FUNC_ringbuf_output &&
10391 		    func_id != BPF_FUNC_ringbuf_reserve &&
10392 		    func_id != BPF_FUNC_ringbuf_query &&
10393 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10394 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10395 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10396 			goto error;
10397 		break;
10398 	case BPF_MAP_TYPE_USER_RINGBUF:
10399 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10400 			goto error;
10401 		break;
10402 	case BPF_MAP_TYPE_STACK_TRACE:
10403 		if (func_id != BPF_FUNC_get_stackid)
10404 			goto error;
10405 		break;
10406 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10407 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10408 		    func_id != BPF_FUNC_current_task_under_cgroup)
10409 			goto error;
10410 		break;
10411 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10412 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10413 		if (func_id != BPF_FUNC_get_local_storage)
10414 			goto error;
10415 		break;
10416 	case BPF_MAP_TYPE_DEVMAP:
10417 	case BPF_MAP_TYPE_DEVMAP_HASH:
10418 		if (func_id != BPF_FUNC_redirect_map &&
10419 		    func_id != BPF_FUNC_map_lookup_elem)
10420 			goto error;
10421 		break;
10422 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10423 	 * appear.
10424 	 */
10425 	case BPF_MAP_TYPE_CPUMAP:
10426 		if (func_id != BPF_FUNC_redirect_map)
10427 			goto error;
10428 		break;
10429 	case BPF_MAP_TYPE_XSKMAP:
10430 		if (func_id != BPF_FUNC_redirect_map &&
10431 		    func_id != BPF_FUNC_map_lookup_elem)
10432 			goto error;
10433 		break;
10434 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10435 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10436 		if (func_id != BPF_FUNC_map_lookup_elem)
10437 			goto error;
10438 		break;
10439 	case BPF_MAP_TYPE_SOCKMAP:
10440 		if (func_id != BPF_FUNC_sk_redirect_map &&
10441 		    func_id != BPF_FUNC_sock_map_update &&
10442 		    func_id != BPF_FUNC_msg_redirect_map &&
10443 		    func_id != BPF_FUNC_sk_select_reuseport &&
10444 		    func_id != BPF_FUNC_map_lookup_elem &&
10445 		    !may_update_sockmap(env, func_id))
10446 			goto error;
10447 		break;
10448 	case BPF_MAP_TYPE_SOCKHASH:
10449 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10450 		    func_id != BPF_FUNC_sock_hash_update &&
10451 		    func_id != BPF_FUNC_msg_redirect_hash &&
10452 		    func_id != BPF_FUNC_sk_select_reuseport &&
10453 		    func_id != BPF_FUNC_map_lookup_elem &&
10454 		    !may_update_sockmap(env, func_id))
10455 			goto error;
10456 		break;
10457 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10458 		if (func_id != BPF_FUNC_sk_select_reuseport)
10459 			goto error;
10460 		break;
10461 	case BPF_MAP_TYPE_QUEUE:
10462 	case BPF_MAP_TYPE_STACK:
10463 		if (func_id != BPF_FUNC_map_peek_elem &&
10464 		    func_id != BPF_FUNC_map_pop_elem &&
10465 		    func_id != BPF_FUNC_map_push_elem)
10466 			goto error;
10467 		break;
10468 	case BPF_MAP_TYPE_SK_STORAGE:
10469 		if (func_id != BPF_FUNC_sk_storage_get &&
10470 		    func_id != BPF_FUNC_sk_storage_delete &&
10471 		    func_id != BPF_FUNC_kptr_xchg)
10472 			goto error;
10473 		break;
10474 	case BPF_MAP_TYPE_INODE_STORAGE:
10475 		if (func_id != BPF_FUNC_inode_storage_get &&
10476 		    func_id != BPF_FUNC_inode_storage_delete &&
10477 		    func_id != BPF_FUNC_kptr_xchg)
10478 			goto error;
10479 		break;
10480 	case BPF_MAP_TYPE_TASK_STORAGE:
10481 		if (func_id != BPF_FUNC_task_storage_get &&
10482 		    func_id != BPF_FUNC_task_storage_delete &&
10483 		    func_id != BPF_FUNC_kptr_xchg)
10484 			goto error;
10485 		break;
10486 	case BPF_MAP_TYPE_CGRP_STORAGE:
10487 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10488 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10489 		    func_id != BPF_FUNC_kptr_xchg)
10490 			goto error;
10491 		break;
10492 	case BPF_MAP_TYPE_BLOOM_FILTER:
10493 		if (func_id != BPF_FUNC_map_peek_elem &&
10494 		    func_id != BPF_FUNC_map_push_elem)
10495 			goto error;
10496 		break;
10497 	case BPF_MAP_TYPE_INSN_ARRAY:
10498 		goto error;
10499 	default:
10500 		break;
10501 	}
10502 
10503 	/* ... and second from the function itself. */
10504 	switch (func_id) {
10505 	case BPF_FUNC_tail_call:
10506 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10507 			goto error;
10508 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
10509 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10510 			return -EINVAL;
10511 		}
10512 		break;
10513 	case BPF_FUNC_perf_event_read:
10514 	case BPF_FUNC_perf_event_output:
10515 	case BPF_FUNC_perf_event_read_value:
10516 	case BPF_FUNC_skb_output:
10517 	case BPF_FUNC_xdp_output:
10518 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10519 			goto error;
10520 		break;
10521 	case BPF_FUNC_ringbuf_output:
10522 	case BPF_FUNC_ringbuf_reserve:
10523 	case BPF_FUNC_ringbuf_query:
10524 	case BPF_FUNC_ringbuf_reserve_dynptr:
10525 	case BPF_FUNC_ringbuf_submit_dynptr:
10526 	case BPF_FUNC_ringbuf_discard_dynptr:
10527 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10528 			goto error;
10529 		break;
10530 	case BPF_FUNC_user_ringbuf_drain:
10531 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10532 			goto error;
10533 		break;
10534 	case BPF_FUNC_get_stackid:
10535 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10536 			goto error;
10537 		break;
10538 	case BPF_FUNC_current_task_under_cgroup:
10539 	case BPF_FUNC_skb_under_cgroup:
10540 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10541 			goto error;
10542 		break;
10543 	case BPF_FUNC_redirect_map:
10544 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10545 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10546 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10547 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10548 			goto error;
10549 		break;
10550 	case BPF_FUNC_sk_redirect_map:
10551 	case BPF_FUNC_msg_redirect_map:
10552 	case BPF_FUNC_sock_map_update:
10553 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10554 			goto error;
10555 		break;
10556 	case BPF_FUNC_sk_redirect_hash:
10557 	case BPF_FUNC_msg_redirect_hash:
10558 	case BPF_FUNC_sock_hash_update:
10559 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10560 			goto error;
10561 		break;
10562 	case BPF_FUNC_get_local_storage:
10563 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10564 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10565 			goto error;
10566 		break;
10567 	case BPF_FUNC_sk_select_reuseport:
10568 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10569 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10570 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10571 			goto error;
10572 		break;
10573 	case BPF_FUNC_map_pop_elem:
10574 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10575 		    map->map_type != BPF_MAP_TYPE_STACK)
10576 			goto error;
10577 		break;
10578 	case BPF_FUNC_map_peek_elem:
10579 	case BPF_FUNC_map_push_elem:
10580 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10581 		    map->map_type != BPF_MAP_TYPE_STACK &&
10582 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10583 			goto error;
10584 		break;
10585 	case BPF_FUNC_map_lookup_percpu_elem:
10586 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10587 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10588 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10589 			goto error;
10590 		break;
10591 	case BPF_FUNC_sk_storage_get:
10592 	case BPF_FUNC_sk_storage_delete:
10593 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10594 			goto error;
10595 		break;
10596 	case BPF_FUNC_inode_storage_get:
10597 	case BPF_FUNC_inode_storage_delete:
10598 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10599 			goto error;
10600 		break;
10601 	case BPF_FUNC_task_storage_get:
10602 	case BPF_FUNC_task_storage_delete:
10603 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10604 			goto error;
10605 		break;
10606 	case BPF_FUNC_cgrp_storage_get:
10607 	case BPF_FUNC_cgrp_storage_delete:
10608 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10609 			goto error;
10610 		break;
10611 	default:
10612 		break;
10613 	}
10614 
10615 	return 0;
10616 error:
10617 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10618 		map->map_type, func_id_name(func_id), func_id);
10619 	return -EINVAL;
10620 }
10621 
10622 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10623 {
10624 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10625 	bool has_size = fn->arg_size[arg] != 0;
10626 	bool is_next_size = false;
10627 
10628 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10629 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10630 
10631 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10632 		return is_next_size;
10633 
10634 	return has_size == is_next_size || is_next_size == is_fixed;
10635 }
10636 
10637 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10638 {
10639 	/* bpf_xxx(..., buf, len) call will access 'len'
10640 	 * bytes from memory 'buf'. Both arg types need
10641 	 * to be paired, so make sure there's no buggy
10642 	 * helper function specification.
10643 	 */
10644 	if (arg_type_is_mem_size(fn->arg1_type) ||
10645 	    check_args_pair_invalid(fn, 0) ||
10646 	    check_args_pair_invalid(fn, 1) ||
10647 	    check_args_pair_invalid(fn, 2) ||
10648 	    check_args_pair_invalid(fn, 3) ||
10649 	    check_args_pair_invalid(fn, 4))
10650 		return false;
10651 
10652 	return true;
10653 }
10654 
10655 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10656 {
10657 	int i;
10658 
10659 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10660 		if (fn->arg_type[i] == ARG_UNUSED)
10661 			break;
10662 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10663 			return !!fn->arg_btf_id[i];
10664 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10665 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10666 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10667 		    /* arg_btf_id and arg_size are in a union. */
10668 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10669 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10670 			return false;
10671 	}
10672 
10673 	return true;
10674 }
10675 
10676 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
10677 {
10678 	int i;
10679 
10680 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10681 		enum bpf_arg_type arg_type = fn->arg_type[i];
10682 
10683 		if (arg_type == ARG_UNUSED)
10684 			break;
10685 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
10686 			continue;
10687 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
10688 			return false;
10689 	}
10690 
10691 	return true;
10692 }
10693 
10694 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
10695 {
10696 	int i;
10697 
10698 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10699 		enum bpf_arg_type arg_type = fn->arg_type[i];
10700 
10701 		if (arg_type == ARG_UNUSED)
10702 			break;
10703 		if (arg_type_is_release(arg_type)) {
10704 			if (meta->release_regno)
10705 				return false;
10706 			meta->release_regno = i + 1;
10707 		}
10708 	}
10709 
10710 	return true;
10711 }
10712 
10713 static bool check_arg_prog_aux(struct bpf_verifier_env *env,
10714 			       const struct bpf_func_proto *proto)
10715 {
10716 	bool seen = false;
10717 	argno_t argno;
10718 	u32 i;
10719 
10720 	for (i = 0; i < ARRAY_SIZE(proto->arg_type); i++) {
10721 		if (proto->arg_type[i] == ARG_UNUSED)
10722 			break;
10723 		if (proto->arg_type[i] != ARG_PTR_TO_PROG_AUX)
10724 			continue;
10725 
10726 		if (seen) {
10727 			verifier_bug(env, "Only 1 prog->aux argument supported");
10728 			return false;
10729 		}
10730 
10731 		argno = argno_from_arg(i + 1);
10732 		if (reg_from_argno(argno) < 0) {
10733 			verbose(env, "%s prog->aux cannot be a stack argument\n",
10734 				reg_arg_name(env, argno));
10735 			return false;
10736 		}
10737 
10738 		seen = true;
10739 	}
10740 
10741 	return true;
10742 }
10743 
10744 static int check_func_proto(struct bpf_verifier_env *env, const struct bpf_func_proto *fn,
10745 			    struct bpf_call_arg_meta *meta)
10746 {
10747 	return check_arg_prog_aux(env, fn) &&
10748 	       check_arg_pair_ok(fn) &&
10749 	       check_mem_arg_rw_flag_ok(fn) &&
10750 	       check_proto_release_reg(fn, meta) &&
10751 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10752 }
10753 
10754 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10755  * are now invalid, so turn them into unknown SCALAR_VALUE.
10756  *
10757  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10758  * since these slices point to packet data.
10759  */
10760 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10761 {
10762 	struct bpf_func_state *state;
10763 	struct bpf_reg_state *reg;
10764 
10765 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10766 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) {
10767 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_PKT_DATA_CHANGE);
10768 			mark_reg_invalid(env, reg);
10769 		}
10770 	}));
10771 }
10772 
10773 enum {
10774 	AT_PKT_END = -1,
10775 	BEYOND_PKT_END = -2,
10776 };
10777 
10778 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10779 {
10780 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10781 	struct bpf_reg_state *reg = &state->regs[regn];
10782 
10783 	if (reg->type != PTR_TO_PACKET)
10784 		/* PTR_TO_PACKET_META is not supported yet */
10785 		return;
10786 
10787 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10788 	 * How far beyond pkt_end it goes is unknown.
10789 	 * if (!range_open) it's the case of pkt >= pkt_end
10790 	 * if (range_open) it's the case of pkt > pkt_end
10791 	 * hence this pointer is at least 1 byte bigger than pkt_end
10792 	 */
10793 	if (range_open)
10794 		reg->range = BEYOND_PKT_END;
10795 	else
10796 		reg->range = AT_PKT_END;
10797 }
10798 
10799 static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
10800 {
10801 	int i;
10802 
10803 	for (i = 0; i < state->acquired_refs; i++) {
10804 		if (state->refs[i].type != REF_TYPE_PTR)
10805 			continue;
10806 		if (state->refs[i].id == id) {
10807 			release_reference_state(state, i);
10808 			return 0;
10809 		}
10810 	}
10811 	return -EINVAL;
10812 }
10813 
10814 static int release_reference_nomark(struct bpf_verifier_env *env, int id)
10815 {
10816 	int err;
10817 
10818 	err = __release_reference_nomark(env->cur_state, id);
10819 	if (!err)
10820 		bpf_diag_record_ref_release(env, env->insn_idx, id);
10821 	return err;
10822 }
10823 
10824 static int idstack_push(struct bpf_idmap *idmap, u32 id)
10825 {
10826 	int i;
10827 
10828 	if (!id)
10829 		return 0;
10830 
10831 	for (i = 0; i < idmap->cnt; i++)
10832 		if (idmap->map[i].old == id)
10833 			return 0;
10834 
10835 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
10836 		return -EFAULT;
10837 
10838 	idmap->map[idmap->cnt++].old = id;
10839 	return 0;
10840 }
10841 
10842 static int idstack_pop(struct bpf_idmap *idmap)
10843 {
10844 	if (!idmap->cnt)
10845 		return 0;
10846 
10847 	return idmap->map[--idmap->cnt].old;
10848 }
10849 
10850 /* Release id and objects derived from it iteratively in a DFS manner */
10851 static int release_reference(struct bpf_verifier_env *env, int id)
10852 {
10853 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
10854 	struct bpf_verifier_state *vstate = env->cur_state;
10855 	struct bpf_idmap *idstack = &env->idmap_scratch;
10856 	struct bpf_stack_state *stack;
10857 	struct bpf_func_state *state;
10858 	struct bpf_reg_state *reg;
10859 	int i, err;
10860 
10861 	idstack->cnt = 0;
10862 	err = idstack_push(idstack, id);
10863 	if (err)
10864 		return err;
10865 
10866 	if (find_reference_state(vstate, id)) {
10867 		err = release_reference_nomark(env, id);
10868 		WARN_ON_ONCE(err);
10869 	}
10870 
10871 	while ((id = idstack_pop(idstack))) {
10872 		/*
10873 		 * Child references are inaccessible after parent is released,
10874 		 * any child references that exist at this point are a leak.
10875 		 */
10876 		for (i = 0; i < vstate->acquired_refs; i++) {
10877 			if (vstate->refs[i].type != REF_TYPE_PTR)
10878 				continue;
10879 			if (vstate->refs[i].parent_id != id)
10880 				continue;
10881 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
10882 				vstate->refs[i].id, vstate->refs[i].insn_idx);
10883 			return -EINVAL;
10884 		}
10885 
10886 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
10887 			if (reg->id != id && reg->parent_id != id)
10888 				continue;
10889 
10890 			/* Free objects derived from the current object */
10891 			if (reg->parent_id == id) {
10892 				err = idstack_push(idstack, reg->id);
10893 				if (err)
10894 					return err;
10895 			}
10896 
10897 			/*
10898 			 * A dynptr occupies two stack slots that invalidate_dynptr()
10899 			 * clears together. Record both scrubs before invalidating it.
10900 			 */
10901 			if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) {
10902 				struct bpf_stack_state *dyn_stack = stack;
10903 
10904 				if (reg->dynptr.first_slot)
10905 					dyn_stack--;
10906 				bpf_diag_record_scrub(env, &dyn_stack[0].spilled_ptr,
10907 						      BPF_DIAG_MOD_REF_RELEASE);
10908 				bpf_diag_record_scrub(env, &dyn_stack[1].spilled_ptr,
10909 						      BPF_DIAG_MOD_REF_RELEASE);
10910 				invalidate_dynptr(env, dyn_stack);
10911 				continue;
10912 			}
10913 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_REF_RELEASE);
10914 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
10915 				mark_reg_invalid(env, reg);
10916 		}));
10917 	}
10918 
10919 	return 0;
10920 }
10921 
10922 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10923 {
10924 	struct bpf_func_state *unused;
10925 	struct bpf_reg_state *reg;
10926 
10927 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10928 		if (type_is_non_owning_ref(reg->type)) {
10929 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_NON_OWN_REF);
10930 			mark_reg_invalid(env, reg);
10931 		}
10932 	}));
10933 }
10934 
10935 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
10936 {
10937 	struct bpf_stack_state *stack;
10938 	struct bpf_func_state *state;
10939 	struct bpf_reg_state *reg;
10940 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
10941 
10942 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
10943 		if (reg->type & MEM_RCU) {
10944 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
10945 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL | NON_OWN_REF);
10946 			reg->type |= PTR_UNTRUSTED;
10947 			bpf_diag_mod_end(env);
10948 		}
10949 	}));
10950 }
10951 
10952 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
10953 {
10954 	struct bpf_func_state *state;
10955 	struct bpf_reg_state *reg;
10956 	int err;
10957 
10958 	err = release_reference_nomark(env, id);
10959 	if (err)
10960 		return err;
10961 
10962 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10963 		if (reg->id != id)
10964 			continue;
10965 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10966 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
10967 			if (!type_may_be_null(reg->type))
10968 				reg->id = 0;
10969 			reg->type &= ~MEM_ALLOC;
10970 			reg->type |= MEM_RCU;
10971 			bpf_diag_mod_end(env);
10972 		}
10973 	}));
10974 
10975 	return err;
10976 }
10977 
10978 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10979 				    struct bpf_reg_state *regs)
10980 {
10981 	int i;
10982 
10983 	bpf_diag_record_caller_saved(env, regs);
10984 
10985 	/* after the call registers r0 - r5 were scratched */
10986 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10987 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
10988 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10989 	}
10990 }
10991 
10992 static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,
10993 					   struct bpf_func_state *state)
10994 {
10995 	int i, nslots = state->out_stack_arg_cnt;
10996 
10997 	for (i = 0; i < nslots; i++) {
10998 		bpf_diag_record_scrub(env, &state->stack_arg_regs[i], BPF_DIAG_MOD_CALLER_SAVED);
10999 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
11000 	}
11001 }
11002 
11003 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
11004 				   struct bpf_func_state *caller,
11005 				   struct bpf_func_state *callee,
11006 				   int insn_idx);
11007 
11008 static int set_callee_state(struct bpf_verifier_env *env,
11009 			    struct bpf_func_state *caller,
11010 			    struct bpf_func_state *callee, int insn_idx);
11011 
11012 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
11013 			    set_callee_state_fn set_callee_state_cb,
11014 			    struct bpf_verifier_state *state)
11015 {
11016 	struct bpf_func_state *caller, *callee;
11017 	int err;
11018 
11019 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
11020 		verbose(env, "the call stack of %d frames is too deep\n",
11021 			state->curframe + 2);
11022 		return -E2BIG;
11023 	}
11024 
11025 	if (state->frame[state->curframe + 1]) {
11026 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
11027 		return -EFAULT;
11028 	}
11029 
11030 	caller = state->frame[state->curframe];
11031 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
11032 	if (!callee)
11033 		return -ENOMEM;
11034 	state->frame[state->curframe + 1] = callee;
11035 
11036 	/* callee cannot access r0, r6 - r9 for reading and has to write
11037 	 * into its own stack before reading from it.
11038 	 * callee can read/write into caller's stack
11039 	 */
11040 	init_func_state(env, callee,
11041 			/* remember the callsite, it will be used by bpf_exit */
11042 			callsite,
11043 			state->curframe + 1 /* frameno within this callchain */,
11044 			subprog /* subprog number within this prog */);
11045 	err = set_callee_state_cb(env, caller, callee, callsite);
11046 	if (err)
11047 		goto err_out;
11048 
11049 	/* only increment it after check_reg_arg() finished */
11050 	state->curframe++;
11051 
11052 	return 0;
11053 
11054 err_out:
11055 	free_func_state(callee);
11056 	state->frame[state->curframe + 1] = NULL;
11057 	return err;
11058 }
11059 
11060 static void gen_subprog_arg_proto(const struct bpf_subprog_info *sub, const struct btf *btf,
11061 				  const struct btf_type *func_proto, struct bpf_func_proto *proto)
11062 {
11063 	const struct btf_param *args = btf_params(func_proto);
11064 	u32 arg, slot = 0;
11065 
11066 	memset(proto, 0, sizeof(*proto));
11067 	for (arg = 0; arg < btf_type_vlen(func_proto); arg++) {
11068 		enum bpf_arg_type arg_type = sub->args[slot].arg_type;
11069 		const struct btf_type *t;
11070 
11071 		if (arg_type & PTR_UNTRUSTED) {
11072 			/*
11073 			 * An __arg_untrusted argument accepts any caller value. The
11074 			 * callee treats it as read-only and uses probe-read instructions
11075 			 * to protect against invalid memory access.
11076 			 */
11077 			arg_type = ARG_IGNORE;
11078 		} else if (base_type(arg_type) == ARG_PTR_TO_ARENA) {
11079 			arg_type |= PTR_MAYBE_NULL;
11080 		} else if (base_type(arg_type) == ARG_PTR_TO_MEM) {
11081 			proto->arg_size[arg] = sub->args[slot].mem_size;
11082 			arg_type |= MEM_FIXED_SIZE | MEM_WRITE;
11083 		} else if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
11084 			proto->arg_btf_id[arg] = &sub->args[slot].btf_id;
11085 		}
11086 		proto->arg_type[arg] = arg_type;
11087 		t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
11088 		slot += btf_arg_slots(t);
11089 	}
11090 }
11091 
11092 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, struct btf *btf)
11093 {
11094 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
11095 	struct bpf_func_state *caller = cur_func(env);
11096 	const struct btf_type *func, *func_proto;
11097 	struct bpf_call_arg_meta meta;
11098 	struct bpf_func_proto *fn;
11099 	int ret, err;
11100 	u32 i;
11101 
11102 	memset(&meta, 0, sizeof(meta));
11103 	meta.btf = btf;
11104 	meta.subprog_may_change_pkt = sub->changes_pkt_data;
11105 	meta.func_name = bpf_subprog_name(env, subprog);
11106 
11107 	ret = btf_prepare_func_args(env, subprog);
11108 	if (ret) {
11109 		if (bpf_in_stack_arg_cnt(sub) > 0) {
11110 			err = check_outgoing_stack_args(env, caller, sub->arg_slot_cnt,
11111 							bpf_subprog_name(env, subprog),
11112 							NULL, NULL);
11113 			if (err)
11114 				return err;
11115 		}
11116 		return ret;
11117 	}
11118 
11119 	func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id);
11120 	func_proto = btf_type_by_id(btf, func->type);
11121 
11122 	fn = &env->bpf_subprog_scratch;
11123 	gen_subprog_arg_proto(sub, btf, func_proto, fn);
11124 	meta.fn = fn;
11125 	meta.func_proto = func_proto;
11126 
11127 	/*
11128 	 * Check if all register arguments declared in BTF are initialized.
11129 	 * If they aren't the BTF is unreliable.
11130 	 */
11131 	if (!bpf_subprog_is_global(env, subprog)) {
11132 		for (i = 0; i < min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++)
11133 			if (caller->regs[BPF_REG_1 + i].type == NOT_INIT)
11134 				return -EINVAL;
11135 	}
11136 	return check_func_args(env, &meta, env->insn_idx);
11137 }
11138 
11139 /*
11140  * Check that call-site argument states match a subprog's BTF signature.
11141  *
11142  * Returns:
11143  * EFAULT - there is a verifier bug. Abort verification.
11144  * Other errors - there is a type mismatch or BTF is not available.
11145  * 0 - BTF matches with what bpf_reg_state expects.
11146  */
11147 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog)
11148 {
11149 	struct bpf_prog *prog = env->prog;
11150 	struct btf *btf = prog->aux->btf;
11151 	u32 btf_id;
11152 	int err;
11153 
11154 	if (!prog->aux->func_info)
11155 		return -EINVAL;
11156 
11157 	btf_id = prog->aux->func_info[subprog].type_id;
11158 	if (!btf_id)
11159 		return -EFAULT;
11160 
11161 	if (prog->aux->func_info_aux[subprog].unreliable)
11162 		return -EINVAL;
11163 
11164 	err = btf_check_func_arg_match(env, subprog, btf);
11165 	/* Compiler optimizations can remove arguments from static functions
11166 	 * or mismatched type can be passed into a global function.
11167 	 * In such cases mark the function as unreliable from BTF point of view.
11168 	 */
11169 	if (err)
11170 		prog->aux->func_info_aux[subprog].unreliable = true;
11171 	return err;
11172 }
11173 
11174 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11175 			      int insn_idx, int subprog,
11176 			      set_callee_state_fn set_callee_state_cb)
11177 {
11178 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
11179 	struct bpf_func_state *caller, *callee;
11180 	int err;
11181 
11182 	caller = state->frame[state->curframe];
11183 	err = btf_check_subprog_call(env, subprog);
11184 	if (err == -EFAULT)
11185 		return err;
11186 
11187 	/* set_callee_state is used for direct subprog calls, but we are
11188 	 * interested in validating only BPF helpers that can call subprogs as
11189 	 * callbacks
11190 	 */
11191 	env->subprog_info[subprog].is_cb = true;
11192 	if (bpf_pseudo_kfunc_call(insn) &&
11193 	    !is_callback_calling_kfunc(insn->imm)) {
11194 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
11195 			     func_id_name(insn->imm), insn->imm);
11196 		return -EFAULT;
11197 	} else if (!bpf_pseudo_kfunc_call(insn) &&
11198 		   !is_callback_calling_function(insn->imm)) { /* helper */
11199 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
11200 			     func_id_name(insn->imm), insn->imm);
11201 		return -EFAULT;
11202 	}
11203 
11204 	if (bpf_is_async_callback_calling_insn(insn)) {
11205 		struct bpf_verifier_state *async_cb;
11206 
11207 		/* there is no real recursion here. timer and workqueue callbacks are async */
11208 		env->subprog_info[subprog].is_async_cb = true;
11209 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
11210 					 insn_idx, subprog,
11211 					 is_async_cb_sleepable(env, insn));
11212 		if (IS_ERR(async_cb))
11213 			return PTR_ERR(async_cb);
11214 		callee = async_cb->frame[0];
11215 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
11216 
11217 		/* Convert bpf_timer_set_callback() args into timer callback args */
11218 		err = set_callee_state_cb(env, caller, callee, insn_idx);
11219 		if (err)
11220 			return err;
11221 
11222 		return 0;
11223 	}
11224 
11225 	/*
11226 	 * The address of the callback might be taken in another function or
11227 	 * read from a map, see check_func_ptr_read(). Like with callx it's
11228 	 * known here what is called.
11229 	 */
11230 	err = record_callx_edge(env, caller->subprogno, subprog);
11231 	if (err)
11232 		return err;
11233 
11234 	/* for callback functions enqueue entry to callback and
11235 	 * proceed with next instruction within current frame.
11236 	 */
11237 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
11238 	if (IS_ERR(callback_state))
11239 		return PTR_ERR(callback_state);
11240 
11241 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
11242 			       callback_state);
11243 	if (err)
11244 		return err;
11245 
11246 	callback_state->callback_unroll_depth++;
11247 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
11248 	caller->callback_depth = 0;
11249 	return 0;
11250 }
11251 
11252 static int process_bpf_exit_full(struct bpf_verifier_env *env,
11253 				 bool *do_print_state, bool exception_exit);
11254 
11255 /*
11256  * Call of a static subprog. The callee is verified in the context of
11257  * the caller, hence set up a new frame and continue from the first
11258  * instruction of the callee.
11259  */
11260 static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
11261 				  int *insn_idx)
11262 {
11263 	struct bpf_verifier_state *state = env->cur_state;
11264 	struct bpf_subprog_info *caller_info;
11265 	u16 callee_incoming, stack_arg_cnt;
11266 	struct bpf_func_state *caller;
11267 	int err;
11268 
11269 	caller = state->frame[state->curframe];
11270 
11271 	/*
11272 	 * Track caller's total stack arg count (incoming + max outgoing).
11273 	 * This is needed so the JIT knows how much stack arg space to allocate.
11274 	 */
11275 	caller_info = &env->subprog_info[caller->subprogno];
11276 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
11277 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
11278 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
11279 		caller_info->stack_arg_cnt = stack_arg_cnt;
11280 
11281 	/*
11282 	 * For regular function entry setup new frame and continue
11283 	 * from that frame.
11284 	 */
11285 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
11286 	if (err)
11287 		return err;
11288 
11289 	bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11290 	clear_caller_saved_regs(env, caller->regs);
11291 
11292 	/* and go analyze first insn of the callee */
11293 	*insn_idx = env->subprog_info[subprog].start - 1;
11294 
11295 	if (env->log.level & BPF_LOG_LEVEL) {
11296 		verbose(env, "caller:\n");
11297 		print_verifier_state(env, state, caller->frameno, true);
11298 		verbose(env, "callee:\n");
11299 		print_verifier_state(env, state, state->curframe, true);
11300 	}
11301 
11302 	return 0;
11303 }
11304 
11305 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11306 			   int *insn_idx)
11307 {
11308 	struct bpf_verifier_state *state = env->cur_state;
11309 	struct bpf_func_state *caller;
11310 	int err, subprog, target_insn;
11311 	u32 i, nregs;
11312 
11313 	target_insn = *insn_idx + insn->imm + 1;
11314 	subprog = bpf_find_subprog(env, target_insn);
11315 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
11316 			    target_insn))
11317 		return -EFAULT;
11318 
11319 	caller = state->frame[state->curframe];
11320 	err = btf_check_subprog_call(env, subprog);
11321 	if (err == -EFAULT)
11322 		return err;
11323 	if (bpf_subprog_is_global(env, subprog)) {
11324 		struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog);
11325 		const char *sub_name = bpf_subprog_name(env, subprog);
11326 		const char *operation;
11327 		bool returns_void;
11328 
11329 		if (env->cur_state->active_locks) {
11330 			verbose(env, "global function calls are not allowed while holding a lock,\n"
11331 				     "use static function instead\n");
11332 			operation = bpf_diag_fmt(env, "global function %s()", sub_name);
11333 			bpf_diag_ctx_active(env, *insn_idx, operation, BPF_DIAG_CONTEXT_LOCK,
11334 					    "Release the lock before calling the global function, or use a static function instead.");
11335 			return -EINVAL;
11336 		}
11337 
11338 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
11339 			const char *suggestion;
11340 
11341 			verbose(env, "sleepable global function %s() called in %s\n",
11342 				sub_name, non_sleepable_context_description(env));
11343 			if (in_sleepable(env))
11344 				suggestion = "Move the call outside the critical section, or use a non-sleepable function.";
11345 			else
11346 				suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable function.";
11347 			operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name);
11348 			bpf_diag_ctx_forbidden(env, *insn_idx, operation, suggestion);
11349 			return -EINVAL;
11350 		}
11351 
11352 		if (err) {
11353 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
11354 				subprog, sub_name);
11355 			return err;
11356 		}
11357 
11358 		if (env->log.level & BPF_LOG_LEVEL)
11359 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
11360 				subprog, sub_name);
11361 		sub_aux->called[in_sleepable_context(env)] = true;
11362 		returns_void = subprog_returns_void(env, subprog);
11363 		if (env->subprog_info[subprog].changes_pkt_data)
11364 			clear_all_pkt_pointers(env);
11365 		if (returns_void)
11366 			bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11367 		else
11368 			bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
11369 		clear_caller_saved_regs(env, caller->regs);
11370 		invalidate_outgoing_stack_args(env, cur_func(env));
11371 
11372 		/*
11373 		 * A non-void global function returns a 64-bit SCALAR_VALUE in
11374 		 * R0, or a >8 byte SCALAR_VALUE in the R0:R2 register pair.
11375 		 */
11376 		if (!returns_void) {
11377 			nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
11378 			mark_reg_unknown(env, caller->regs, ret_regs[0]);
11379 			bpf_diag_mod_end(env);
11380 			for (i = 1; i < nregs; i++) {
11381 				bpf_diag_mod_begin(env, &caller->regs[ret_regs[i]], NULL,
11382 						   BPF_DIAG_MOD_WRITE);
11383 				mark_reg_unknown(env, caller->regs, ret_regs[i]);
11384 				bpf_diag_mod_end(env);
11385 			}
11386 		}
11387 
11388 		if (env->subprog_info[subprog].might_throw) {
11389 			struct bpf_verifier_state *branch;
11390 
11391 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
11392 			if (IS_ERR(branch)) {
11393 				verbose(env, "failed to push state for global subprog exception path\n");
11394 				return PTR_ERR(branch);
11395 			}
11396 			return process_bpf_exit_full(env, NULL, true);
11397 		}
11398 
11399 		/* continue with next insn after call */
11400 		return 0;
11401 	}
11402 
11403 	return check_static_func_call(env, subprog, insn_idx);
11404 }
11405 
11406 /*
11407  * callx dst_reg: call a bpf subprog whose address is in dst_reg.
11408  *
11409  * The address of a subprog is either loaded into a register by ld_imm64 with
11410  * src_reg == BPF_PSEUDO_FUNC, or it is read from a frozen read-only map, see
11411  * resolve_func_ptrs(). Both are possible for static subprogs only. Hence all
11412  * possible callees of callx are discovered by add_subprogs() and are reachable
11413  * in the control flow graph before the main verification pass begins.
11414  * PTR_TO_FUNC register identifies the callee, so from here on callx is verified
11415  * as a direct call of that static subprog.
11416  */
11417 static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn,
11418 			    int *insn_idx)
11419 {
11420 	struct bpf_func_state *caller = cur_func(env);
11421 	struct bpf_reg_state *reg;
11422 	const char *reason;
11423 	int err, subprog;
11424 
11425 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11426 	if (err)
11427 		return err;
11428 
11429 	reg = reg_state(env, insn->dst_reg);
11430 	if (reg->type != PTR_TO_FUNC) {
11431 		verbose(env, "R%d has type %s, expected func\n", insn->dst_reg,
11432 			reg_type_str(env, reg->type));
11433 		reason = bpf_diag_fmt(
11434 			env, "R%d holds %s, but callx can only call through the address of a static BPF function.",
11435 			insn->dst_reg, bpf_diag_reg_type_plain(env, reg->type));
11436 		bpf_diag_register_type(
11437 			env, *insn_idx, insn->dst_reg, "indirect call through a non-function pointer", reason,
11438 			"Load the address of a static BPF function into the register before callx.");
11439 		return -EACCES;
11440 	}
11441 
11442 	/*
11443 	 * Arithmetic on PTR_TO_FUNC is allowed, but only unmodified address
11444 	 * of a subprog can be called.
11445 	 */
11446 	err = check_ptr_off_reg(env, reg, insn->dst_reg);
11447 	if (err)
11448 		return err;
11449 
11450 	/* the callx is valid, but only a JIT can execute it */
11451 	err = require_callx_jit(env);
11452 	if (err)
11453 		return err;
11454 
11455 	/* PTR_TO_FUNC is a pointer to a static subprog */
11456 	subprog = reg->subprogno;
11457 	err = btf_check_subprog_call(env, subprog);
11458 	if (err == -EFAULT)
11459 		return err;
11460 
11461 	err = record_callx_edge(env, caller->subprogno, subprog);
11462 	if (err)
11463 		return err;
11464 
11465 	return check_static_func_call(env, subprog, insn_idx);
11466 }
11467 
11468 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
11469 				   struct bpf_func_state *caller,
11470 				   struct bpf_func_state *callee)
11471 {
11472 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
11473 	 *      void *callback_ctx, u64 flags);
11474 	 * callback_fn(struct bpf_map *map, void *key, void *value,
11475 	 *      void *callback_ctx);
11476 	 */
11477 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11478 
11479 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11480 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11481 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11482 	callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid;
11483 
11484 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11485 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11486 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11487 	callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid;
11488 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11489 
11490 	/* pointer to stack or null */
11491 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
11492 
11493 	/* unused */
11494 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11495 	return 0;
11496 }
11497 
11498 static int set_callee_state(struct bpf_verifier_env *env,
11499 			    struct bpf_func_state *caller,
11500 			    struct bpf_func_state *callee, int insn_idx)
11501 {
11502 	int i;
11503 
11504 	/* copy r1 - r5 args that callee can access.  The copy includes parent
11505 	 * pointers, which connects us up to the liveness chain
11506 	 */
11507 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
11508 		callee->regs[i] = caller->regs[i];
11509 	return 0;
11510 }
11511 
11512 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
11513 				       struct bpf_func_state *caller,
11514 				       struct bpf_func_state *callee,
11515 				       int insn_idx)
11516 {
11517 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
11518 	struct bpf_map *map;
11519 	int err;
11520 
11521 	/* valid map_ptr and poison value does not matter */
11522 	map = insn_aux->map_ptr_state.map_ptr;
11523 	if (!map->ops->map_set_for_each_callback_args ||
11524 	    !map->ops->map_for_each_callback) {
11525 		verbose(env, "callback function not allowed for map\n");
11526 		return -ENOTSUPP;
11527 	}
11528 
11529 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
11530 	if (err)
11531 		return err;
11532 
11533 	callee->in_callback_fn = true;
11534 	callee->callback_ret_range = retval_range(0, 1);
11535 	return 0;
11536 }
11537 
11538 static int set_loop_callback_state(struct bpf_verifier_env *env,
11539 				   struct bpf_func_state *caller,
11540 				   struct bpf_func_state *callee,
11541 				   int insn_idx)
11542 {
11543 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
11544 	 *	    u64 flags);
11545 	 * callback_fn(u64 index, void *callback_ctx);
11546 	 */
11547 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
11548 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11549 
11550 	/* unused */
11551 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11552 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11553 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11554 
11555 	callee->in_callback_fn = true;
11556 	callee->callback_ret_range = retval_range(0, 1);
11557 	return 0;
11558 }
11559 
11560 static int set_timer_callback_state(struct bpf_verifier_env *env,
11561 				    struct bpf_func_state *caller,
11562 				    struct bpf_func_state *callee,
11563 				    int insn_idx)
11564 {
11565 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
11566 	u32 map_uid = caller->regs[BPF_REG_1].map_uid;
11567 
11568 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
11569 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11570 	 */
11571 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11572 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11573 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11574 	callee->regs[BPF_REG_1].map_uid = map_uid;
11575 
11576 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11577 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11578 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11579 	callee->regs[BPF_REG_2].map_uid = map_uid;
11580 
11581 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11582 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11583 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11584 	callee->regs[BPF_REG_3].map_uid = map_uid;
11585 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11586 
11587 	/* unused */
11588 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11589 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11590 	callee->in_async_callback_fn = true;
11591 	callee->callback_ret_range = retval_range(0, 0);
11592 	return 0;
11593 }
11594 
11595 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
11596 				       struct bpf_func_state *caller,
11597 				       struct bpf_func_state *callee,
11598 				       int insn_idx)
11599 {
11600 	/* bpf_find_vma(struct task_struct *task, u64 addr,
11601 	 *               void *callback_fn, void *callback_ctx, u64 flags)
11602 	 * (callback_fn)(struct task_struct *task,
11603 	 *               struct vm_area_struct *vma, void *callback_ctx);
11604 	 */
11605 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11606 
11607 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
11608 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11609 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
11610 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
11611 
11612 	/* pointer to stack or null */
11613 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
11614 
11615 	/* unused */
11616 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11617 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11618 	callee->in_callback_fn = true;
11619 	callee->callback_ret_range = retval_range(0, 1);
11620 	return 0;
11621 }
11622 
11623 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
11624 					   struct bpf_func_state *caller,
11625 					   struct bpf_func_state *callee,
11626 					   int insn_idx)
11627 {
11628 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
11629 	 *			  callback_ctx, u64 flags);
11630 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
11631 	 */
11632 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
11633 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
11634 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11635 
11636 	/* unused */
11637 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11638 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11639 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11640 
11641 	callee->in_callback_fn = true;
11642 	callee->callback_ret_range = retval_range(0, 1);
11643 	return 0;
11644 }
11645 
11646 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
11647 					 struct bpf_func_state *caller,
11648 					 struct bpf_func_state *callee,
11649 					 int insn_idx)
11650 {
11651 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
11652 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
11653 	 *
11654 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
11655 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
11656 	 * by this point, so look at 'root'
11657 	 */
11658 	struct btf_field *field;
11659 
11660 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
11661 				      caller->regs[BPF_REG_1].var_off.value,
11662 				      BPF_RB_ROOT);
11663 	if (!field || !field->graph_root.value_btf_id)
11664 		return -EFAULT;
11665 
11666 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
11667 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
11668 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
11669 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
11670 
11671 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11672 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11673 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11674 	callee->in_callback_fn = true;
11675 	callee->callback_ret_range = retval_range(0, 1);
11676 	return 0;
11677 }
11678 
11679 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11680 						 struct bpf_func_state *caller,
11681 						 struct bpf_func_state *callee,
11682 						 int insn_idx)
11683 {
11684 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11685 	u32 map_uid = caller->regs[BPF_REG_3].map_uid;
11686 
11687 	/*
11688 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11689 	 */
11690 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11691 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11692 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11693 	callee->regs[BPF_REG_1].map_uid = map_uid;
11694 
11695 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11696 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11697 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11698 	callee->regs[BPF_REG_2].map_uid = map_uid;
11699 
11700 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11701 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11702 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11703 	callee->regs[BPF_REG_3].map_uid = map_uid;
11704 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11705 
11706 	/* unused */
11707 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11708 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11709 	callee->in_async_callback_fn = true;
11710 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11711 	return 0;
11712 }
11713 
11714 static int set_rcu_callback_state(struct bpf_verifier_env *env,
11715 				  struct bpf_func_state *caller,
11716 				  struct bpf_func_state *callee,
11717 				  int insn_idx)
11718 {
11719 	struct bpf_map *map_ptr = caller->regs[BPF_REG_2].map_ptr;
11720 	u32 map_uid = caller->regs[BPF_REG_2].map_uid;
11721 
11722 	/*
11723 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11724 	 */
11725 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11726 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11727 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11728 	callee->regs[BPF_REG_1].map_uid = map_uid;
11729 
11730 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11731 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11732 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11733 	callee->regs[BPF_REG_2].map_uid = map_uid;
11734 
11735 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11736 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11737 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11738 	callee->regs[BPF_REG_3].map_uid = map_uid;
11739 
11740 	/* unused */
11741 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11742 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11743 	callee->in_async_callback_fn = true;
11744 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11745 	return 0;
11746 }
11747 
11748 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11749 
11750 static void account_processed_insn(struct bpf_verifier_env *env)
11751 {
11752 	struct bpf_func_state *frame = cur_func(env);
11753 
11754 	env->insn_processed++;
11755 	frame->insns_subtotal++;
11756 	env->subprog_info[frame->subprogno].insns_self++;
11757 }
11758 
11759 static void account_processed_insns(struct bpf_verifier_env *env,
11760 				    struct bpf_func_state *callee,
11761 				    struct bpf_func_state *caller)
11762 {
11763 	u32 insns;
11764 
11765 	if (!callee)
11766 		return;
11767 
11768 	insns = callee->insns_subtotal;
11769 
11770 	env->subprog_info[callee->subprogno].insns_total += insns;
11771 	if (caller)
11772 		caller->insns_subtotal += insns;
11773 	callee->insns_subtotal = 0;
11774 }
11775 
11776 static void account_current_path(struct bpf_verifier_env *env)
11777 {
11778 	struct bpf_verifier_state *state = env->cur_state;
11779 	int frame;
11780 
11781 	for (frame = state->curframe; frame >= 0; frame--)
11782 		account_processed_insns(env, state->frame[frame],
11783 					frame ? state->frame[frame - 1] : NULL);
11784 }
11785 
11786 /*
11787  * Are we currently verifying the callback for an rbtree kfunc that must
11788  * be called with a lock held, or one of that callback's subprogs? If so,
11789  * no need to complain about an unreleased lock.
11790  */
11791 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11792 {
11793 	struct bpf_verifier_state *state = env->cur_state;
11794 	struct bpf_insn *insn = env->prog->insnsi;
11795 	struct bpf_func_state *callee;
11796 	int kfunc_btf_id;
11797 	u32 frame;
11798 
11799 	for (frame = state->curframe; frame; frame--) {
11800 		callee = state->frame[frame];
11801 		if (!callee->in_callback_fn)
11802 			continue;
11803 
11804 		kfunc_btf_id = insn[callee->callsite].imm;
11805 		if (is_rbtree_lock_required_kfunc(kfunc_btf_id))
11806 			return true;
11807 	}
11808 
11809 	return false;
11810 }
11811 
11812 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
11813 {
11814 	if (range.return_32bit)
11815 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
11816 	else
11817 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
11818 }
11819 
11820 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11821 {
11822 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
11823 	struct bpf_func_state *caller, *callee;
11824 	struct bpf_reg_state *r0;
11825 	bool in_callback_fn;
11826 	u32 i, nregs;
11827 	int err;
11828 
11829 	callee = state->frame[state->curframe];
11830 	r0 = &callee->regs[BPF_REG_0];
11831 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
11832 	for (i = 0; i < nregs; i++) {
11833 		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
11834 			continue;
11835 		/* technically it's ok to return caller's stack pointer
11836 		 * (or caller's caller's pointer) back to the caller,
11837 		 * since these pointers are valid. Only current stack
11838 		 * pointer will be invalid as soon as function exits,
11839 		 * but let's be conservative
11840 		 */
11841 		verbose(env, "cannot return stack pointer to the caller\n");
11842 		return -EINVAL;
11843 	}
11844 
11845 	caller = state->frame[state->curframe - 1];
11846 	if (callee->in_callback_fn) {
11847 		if (r0->type != SCALAR_VALUE) {
11848 			verbose(env, "R0 not a scalar value\n");
11849 			return -EACCES;
11850 		}
11851 
11852 		/* we are going to rely on register's precise value */
11853 		err = mark_chain_precision(env, BPF_REG_0);
11854 		if (err)
11855 			return err;
11856 
11857 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11858 		if (!retval_range_within(callee->callback_ret_range, r0)) {
11859 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11860 					       "At callback return", "R0");
11861 			return -EINVAL;
11862 		}
11863 		if (!bpf_calls_callback(env, callee->callsite)) {
11864 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11865 				     *insn_idx, callee->callsite);
11866 			return -EFAULT;
11867 		}
11868 	} else {
11869 		/*
11870 		 * return to the caller whatever the callee had in the
11871 		 * return register(s)
11872 		 */
11873 		for (i = 0; i < nregs; i++) {
11874 			u32 regno = ret_regs[i];
11875 
11876 			bpf_diag_mod_begin(env, &caller->regs[regno], &callee->regs[regno],
11877 					   BPF_DIAG_MOD_WRITE);
11878 			caller->regs[regno] = callee->regs[regno];
11879 			bpf_diag_mod_end(env);
11880 		}
11881 	}
11882 
11883 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
11884 	err = destroy_dynptrs_in_stack_slots(env, callee, 0,
11885 					     callee->allocated_stack / BPF_REG_SIZE - 1);
11886 	if (err)
11887 		return err;
11888 
11889 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11890 	 * there function call logic would reschedule callback visit. If iteration
11891 	 * converges is_state_visited() would prune that visit eventually.
11892 	 */
11893 	in_callback_fn = callee->in_callback_fn;
11894 	if (in_callback_fn)
11895 		*insn_idx = callee->callsite;
11896 	else
11897 		*insn_idx = callee->callsite + 1;
11898 
11899 	if (env->log.level & BPF_LOG_LEVEL) {
11900 		verbose(env, "returning from callee:\n");
11901 		print_verifier_state(env, state, callee->frameno, true);
11902 		verbose(env, "to caller at %d:\n", *insn_idx);
11903 		print_verifier_state(env, state, caller->frameno, true);
11904 	}
11905 	account_processed_insns(env, callee, caller);
11906 	/* clear everything in the callee. In case of exceptional exits using
11907 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11908 	free_func_state(callee);
11909 	state->frame[state->curframe--] = NULL;
11910 	invalidate_outgoing_stack_args(env, caller);
11911 
11912 	/* for callbacks widen imprecise scalars to make programs like below verify:
11913 	 *
11914 	 *   struct ctx { int i; }
11915 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11916 	 *   ...
11917 	 *   struct ctx = { .i = 0; }
11918 	 *   bpf_loop(100, cb, &ctx, 0);
11919 	 *
11920 	 * This is similar to what is done in process_iter_next_call() for open
11921 	 * coded iterators.
11922 	 */
11923 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11924 	if (prev_st) {
11925 		err = widen_imprecise_scalars(env, prev_st, state);
11926 		if (err)
11927 			return err;
11928 	}
11929 	return 0;
11930 }
11931 
11932 static int do_refine_retval_range(struct bpf_verifier_env *env,
11933 				  struct bpf_reg_state *regs, int ret_type,
11934 				  int func_id,
11935 				  struct bpf_call_arg_meta *meta)
11936 {
11937 	struct bpf_retval_range range;
11938 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11939 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11940 
11941 	if (ret_type != RET_INTEGER)
11942 		return 0;
11943 
11944 	switch (func_id) {
11945 	case BPF_FUNC_get_stack:
11946 	case BPF_FUNC_get_task_stack:
11947 	case BPF_FUNC_probe_read_str:
11948 	case BPF_FUNC_probe_read_kernel_str:
11949 	case BPF_FUNC_probe_read_user_str:
11950 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
11951 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
11952 		reg_bounds_sync(ret_reg);
11953 		break;
11954 	case BPF_FUNC_get_smp_processor_id:
11955 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
11956 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
11957 		reg_bounds_sync(ret_reg);
11958 		break;
11959 	case BPF_FUNC_get_retval:
11960 		/*
11961 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
11962 		 * CGROUP_GETSOCKOPT type.
11963 		 */
11964 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
11965 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
11966 			break;
11967 
11968 		if (prog_type == BPF_PROG_TYPE_LSM &&
11969 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11970 			if (!env->prog->aux->attach_func_proto->type)
11971 				break;
11972 			bpf_lsm_get_retval_range(env->prog, &range);
11973 		} else {
11974 			range.minval = -MAX_ERRNO;
11975 			range.maxval = 0;
11976 		}
11977 
11978 		reg_set_srange64(ret_reg, range.minval, range.maxval);
11979 		reg_set_srange32(ret_reg, range.minval, range.maxval);
11980 		reg_bounds_sync(ret_reg);
11981 		break;
11982 	}
11983 
11984 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11985 }
11986 
11987 static int
11988 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11989 		int func_id, int insn_idx)
11990 {
11991 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11992 	struct bpf_map *map = meta->map.ptr;
11993 
11994 	if (func_id != BPF_FUNC_tail_call &&
11995 	    func_id != BPF_FUNC_map_lookup_elem &&
11996 	    func_id != BPF_FUNC_map_update_elem &&
11997 	    func_id != BPF_FUNC_map_delete_elem &&
11998 	    func_id != BPF_FUNC_map_push_elem &&
11999 	    func_id != BPF_FUNC_map_pop_elem &&
12000 	    func_id != BPF_FUNC_map_peek_elem &&
12001 	    func_id != BPF_FUNC_for_each_map_elem &&
12002 	    func_id != BPF_FUNC_redirect_map &&
12003 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
12004 		return 0;
12005 
12006 	if (map == NULL) {
12007 		verifier_bug(env, "expected map for helper call");
12008 		return -EFAULT;
12009 	}
12010 
12011 	/* In case of read-only, some additional restrictions
12012 	 * need to be applied in order to prevent altering the
12013 	 * state of the map from program side.
12014 	 */
12015 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
12016 	    (func_id == BPF_FUNC_map_delete_elem ||
12017 	     func_id == BPF_FUNC_map_update_elem ||
12018 	     func_id == BPF_FUNC_map_push_elem ||
12019 	     func_id == BPF_FUNC_map_pop_elem)) {
12020 		verbose(env, "write into map forbidden\n");
12021 		return -EACCES;
12022 	}
12023 
12024 	if (!aux->map_ptr_state.map_ptr)
12025 		bpf_map_ptr_store(aux, meta->map.ptr,
12026 				  !meta->map.ptr->bypass_spec_v1, false);
12027 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
12028 		bpf_map_ptr_store(aux, meta->map.ptr,
12029 				  !meta->map.ptr->bypass_spec_v1, true);
12030 	return 0;
12031 }
12032 
12033 static int
12034 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12035 		int func_id, int insn_idx)
12036 {
12037 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12038 	struct bpf_reg_state *reg;
12039 	struct bpf_map *map = meta->map.ptr;
12040 	u64 val, max;
12041 	int err;
12042 
12043 	if (func_id != BPF_FUNC_tail_call)
12044 		return 0;
12045 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
12046 		verbose(env, "expected prog array map for tail call");
12047 		return -EINVAL;
12048 	}
12049 
12050 	reg = reg_state(env, BPF_REG_3);
12051 	val = reg->var_off.value;
12052 	max = map->max_entries;
12053 
12054 	if (!(is_reg_const(reg, false) && val < max)) {
12055 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12056 		return 0;
12057 	}
12058 
12059 	err = mark_chain_precision(env, BPF_REG_3);
12060 	if (err)
12061 		return err;
12062 	if (bpf_map_key_unseen(aux))
12063 		bpf_map_key_store(aux, val);
12064 	else if (!bpf_map_key_poisoned(aux) &&
12065 		  bpf_map_key_immediate(aux) != val)
12066 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12067 	return 0;
12068 }
12069 
12070 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
12071 {
12072 	struct bpf_verifier_state *state = env->cur_state;
12073 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12074 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
12075 	bool refs_lingering = false;
12076 	int i;
12077 
12078 	if (!exception_exit && cur_func(env)->frameno)
12079 		return 0;
12080 
12081 	for (i = 0; i < state->acquired_refs; i++) {
12082 		if (state->refs[i].type != REF_TYPE_PTR)
12083 			continue;
12084 		/* Allow struct_ops programs to return a referenced kptr back to
12085 		 * kernel. Type checks are performed later in check_return_code.
12086 		 */
12087 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
12088 		    reg->id == state->refs[i].id)
12089 			continue;
12090 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
12091 			state->refs[i].id, state->refs[i].insn_idx);
12092 		bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx);
12093 		refs_lingering = true;
12094 	}
12095 	return refs_lingering ? -EINVAL : 0;
12096 }
12097 
12098 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
12099 {
12100 	int err;
12101 
12102 	if (check_lock && env->cur_state->active_locks) {
12103 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
12104 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_LOCK,
12105 				    "Release the BPF spin lock before this operation on every path.");
12106 		return -EINVAL;
12107 	}
12108 
12109 	err = check_reference_leak(env, exception_exit);
12110 	if (err) {
12111 		verbose(env, "%s would lead to reference leak\n", prefix);
12112 		return err;
12113 	}
12114 
12115 	if (check_lock && env->cur_state->active_irq_id) {
12116 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
12117 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_IRQ,
12118 				    "Restore the saved IRQ state before this operation on every path.");
12119 		return -EINVAL;
12120 	}
12121 
12122 	if (check_lock && env->cur_state->active_rcu_locks) {
12123 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
12124 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_RCU,
12125 				    "Call bpf_rcu_read_unlock() before this operation on every path.");
12126 		return -EINVAL;
12127 	}
12128 
12129 	if (check_lock && env->cur_state->active_preempt_locks) {
12130 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
12131 		bpf_diag_ctx_active(
12132 			env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_PREEMPT,
12133 			"Call bpf_preempt_enable() before this operation on every path.");
12134 		return -EINVAL;
12135 	}
12136 
12137 	return 0;
12138 }
12139 
12140 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
12141 				   struct bpf_reg_state *regs)
12142 {
12143 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
12144 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
12145 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
12146 	struct bpf_bprintf_data data = {};
12147 	int err, fmt_map_off, num_args;
12148 	u64 fmt_addr;
12149 	char *fmt;
12150 
12151 	/* data must be an array of u64 */
12152 	if (data_len_reg->var_off.value % 8)
12153 		return -EINVAL;
12154 	num_args = data_len_reg->var_off.value / 8;
12155 
12156 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
12157 	 * and map_direct_value_addr is set.
12158 	 */
12159 	fmt_map_off = fmt_reg->var_off.value;
12160 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
12161 						  fmt_map_off);
12162 	if (err) {
12163 		verbose(env, "failed to retrieve map value address\n");
12164 		return -EFAULT;
12165 	}
12166 	fmt = (char *)(long)fmt_addr + fmt_map_off;
12167 
12168 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
12169 	 * can focus on validating the format specifiers.
12170 	 */
12171 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
12172 	if (err < 0)
12173 		verbose(env, "Invalid format string\n");
12174 
12175 	return err;
12176 }
12177 
12178 static int check_get_func_ip(struct bpf_verifier_env *env)
12179 {
12180 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12181 	int func_id = BPF_FUNC_get_func_ip;
12182 
12183 	if (type == BPF_PROG_TYPE_TRACING) {
12184 		if (!bpf_prog_has_trampoline(env->prog)) {
12185 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
12186 				func_id_name(func_id), func_id);
12187 			return -ENOTSUPP;
12188 		}
12189 		return 0;
12190 	} else if (type == BPF_PROG_TYPE_KPROBE) {
12191 		return 0;
12192 	}
12193 
12194 	verbose(env, "func %s#%d not supported for program type %d\n",
12195 		func_id_name(func_id), func_id, type);
12196 	return -ENOTSUPP;
12197 }
12198 
12199 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
12200 {
12201 	return &env->insn_aux_data[env->insn_idx];
12202 }
12203 
12204 /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */
12205 static int loop_flag_is_zero(struct bpf_verifier_env *env)
12206 {
12207 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
12208 	int err;
12209 
12210 	if (!bpf_register_is_null(reg))
12211 		return 0;
12212 
12213 	err = mark_chain_precision(env, BPF_REG_4);
12214 	if (err)
12215 		return err;
12216 	return 1;
12217 }
12218 
12219 static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
12220 {
12221 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
12222 	int flag_is_zero;
12223 
12224 	if (!state->initialized) {
12225 		flag_is_zero = loop_flag_is_zero(env);
12226 		if (flag_is_zero < 0)
12227 			return flag_is_zero;
12228 		state->initialized = 1;
12229 		state->fit_for_inline = flag_is_zero;
12230 		state->callback_subprogno = subprogno;
12231 		return 0;
12232 	}
12233 
12234 	if (!state->fit_for_inline)
12235 		return 0;
12236 
12237 	flag_is_zero = loop_flag_is_zero(env);
12238 	if (flag_is_zero < 0)
12239 		return flag_is_zero;
12240 	state->fit_for_inline = (flag_is_zero &&
12241 				 state->callback_subprogno == subprogno);
12242 	return 0;
12243 }
12244 
12245 /* Returns whether or not the given map can potentially elide
12246  * lookup return value nullness check. This is possible if the key
12247  * is statically known.
12248  */
12249 static bool can_elide_value_nullness(const struct bpf_map *map)
12250 {
12251 	if (map->map_flags & BPF_F_INNER_MAP)
12252 		return false;
12253 
12254 	switch (map->map_type) {
12255 	case BPF_MAP_TYPE_ARRAY:
12256 	case BPF_MAP_TYPE_PERCPU_ARRAY:
12257 		return true;
12258 	default:
12259 		return false;
12260 	}
12261 }
12262 
12263 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
12264 			 const struct bpf_func_proto **ptr)
12265 {
12266 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
12267 		return -ERANGE;
12268 
12269 	if (!env->ops->get_func_proto)
12270 		return -EINVAL;
12271 
12272 	*ptr = env->ops->get_func_proto(func_id, env->prog);
12273 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
12274 }
12275 
12276 /* Check if we're in a sleepable context. */
12277 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
12278 {
12279 	return !in_rcu_cs(env);
12280 }
12281 
12282 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
12283 {
12284 	if (in_sleepable(env)) {
12285 		if (env->cur_state->active_rcu_locks)
12286 			return "rcu_read_lock region";
12287 		if (env->cur_state->active_preempt_locks)
12288 			return "non-preemptible region";
12289 		if (env->cur_state->active_irq_id)
12290 			return "IRQ-disabled region";
12291 		if (env->cur_state->active_locks)
12292 			return "lock region";
12293 	}
12294 	return "non-sleepable prog";
12295 }
12296 
12297 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
12298 		       bool convert_rcu, bool release_dynptr)
12299 {
12300 	int err = -EINVAL;
12301 
12302 	if (bpf_register_is_null(reg))
12303 		return 0;
12304 
12305 	if (release_dynptr)
12306 		err = unmark_stack_slots_dynptr(env, reg);
12307 	else if (convert_rcu)
12308 		err = ref_convert_alloc_rcu_protected(env, reg->id);
12309 	else if (reg_is_referenced(env, reg))
12310 		err = release_reference(env, reg->id);
12311 
12312 	return err;
12313 }
12314 
12315 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12316 			     int *insn_idx_p)
12317 {
12318 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12319 	bool returns_cpu_specific_alloc_ptr = false;
12320 	const struct bpf_func_proto *fn = NULL;
12321 	enum bpf_return_type ret_type;
12322 	enum bpf_type_flag ret_flag;
12323 	struct bpf_reg_state *regs;
12324 	struct bpf_call_arg_meta meta;
12325 	const char *operation;
12326 	int insn_idx = *insn_idx_p;
12327 	bool changes_data;
12328 	int i, err, func_id;
12329 
12330 	/* find function prototype */
12331 	func_id = insn->imm;
12332 	err = bpf_get_helper_proto(env, insn->imm, &fn);
12333 	if (err == -ERANGE) {
12334 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
12335 		return -EINVAL;
12336 	}
12337 
12338 	if (err) {
12339 		verbose(env, "program of this type cannot use helper %s#%d\n",
12340 			func_id_name(func_id), func_id);
12341 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12342 		bpf_diag_policy(
12343 			env, insn_idx, operation, "this program type does not allow the helper",
12344 			"Use a helper allowed for this program type, or move the logic to a compatible program type.");
12345 		return err;
12346 	}
12347 
12348 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
12349 	if (!env->prog->gpl_compatible && fn->gpl_only) {
12350 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
12351 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12352 		bpf_diag_policy(
12353 			env, insn_idx, operation,
12354 			"this helper is restricted to GPL-compatible programs",
12355 			"Use a GPL-compatible license, or replace the helper with one that is available to non-GPL programs.");
12356 		return -EINVAL;
12357 	}
12358 
12359 	if (fn->allowed && !fn->allowed(env->prog)) {
12360 		verbose(env, "helper call is not allowed in probe\n");
12361 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12362 		bpf_diag_policy(
12363 			env, insn_idx, operation,
12364 			"the helper-specific policy callback rejected this program",
12365 			"Use the helper only from an allowed attach point or program configuration.");
12366 		return -EINVAL;
12367 	}
12368 
12369 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
12370 	changes_data = bpf_helper_changes_pkt_data(func_id);
12371 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
12372 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
12373 		return -EFAULT;
12374 	}
12375 
12376 	memset(&meta, 0, sizeof(meta));
12377 
12378 	err = check_func_proto(env, fn, &meta);
12379 	if (err) {
12380 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
12381 		return err;
12382 	}
12383 
12384 	if (fn->might_sleep && !in_sleepable_context(env)) {
12385 		const char *suggestion;
12386 
12387 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
12388 			non_sleepable_context_description(env));
12389 		if (in_sleepable(env))
12390 			suggestion = "Move the helper call outside the critical section, or use a non-sleepable helper.";
12391 		else
12392 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable helper.";
12393 		operation = bpf_diag_fmt(env, "sleepable helper %s#%d",
12394 					 func_id_name(func_id), func_id);
12395 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
12396 		return -EINVAL;
12397 	}
12398 
12399 	/* Track non-sleepable context for helpers. */
12400 	if (!in_sleepable_context(env))
12401 		env->insn_aux_data[insn_idx].non_sleepable = true;
12402 
12403 	meta.func_id = func_id;
12404 	meta.func_name = func_id_name(func_id);
12405 	meta.fn = fn;
12406 	err = check_func_args(env, &meta, insn_idx);
12407 	if (err)
12408 		return err;
12409 
12410 	err = record_func_map(env, &meta, func_id, insn_idx);
12411 	if (err)
12412 		return err;
12413 
12414 	err = record_func_key(env, &meta, func_id, insn_idx);
12415 	if (err)
12416 		return err;
12417 
12418 	regs = cur_regs(env);
12419 
12420 	err = mark_raw_stack(env, &meta, insn_idx);
12421 	if (err)
12422 		return err;
12423 
12424 	if (meta.release_regno) {
12425 		struct bpf_reg_state *reg = &regs[meta.release_regno];
12426 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
12427 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
12428 
12429 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
12430 		if (err)
12431 			return err;
12432 	}
12433 
12434 	switch (func_id) {
12435 	case BPF_FUNC_tail_call:
12436 		err = check_resource_leak(env, false, true, "tail_call");
12437 		if (err)
12438 			return err;
12439 		break;
12440 	case BPF_FUNC_get_local_storage:
12441 		/* check that flags argument in get_local_storage(map, flags) is 0,
12442 		 * this is required because get_local_storage() can't return an error.
12443 		 */
12444 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
12445 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
12446 			return -EINVAL;
12447 		}
12448 		err = mark_chain_precision(env, BPF_REG_2);
12449 		if (err)
12450 			return err;
12451 		break;
12452 	case BPF_FUNC_for_each_map_elem:
12453 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12454 					 set_map_elem_callback_state);
12455 		break;
12456 	case BPF_FUNC_timer_set_callback:
12457 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12458 					 set_timer_callback_state);
12459 		break;
12460 	case BPF_FUNC_find_vma:
12461 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12462 					 set_find_vma_callback_state);
12463 		break;
12464 	case BPF_FUNC_snprintf:
12465 		err = check_bpf_snprintf_call(env, regs);
12466 		break;
12467 	case BPF_FUNC_loop:
12468 		err = update_loop_inline_state(env, meta.subprogno);
12469 		if (err)
12470 			return err;
12471 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
12472 		 * is finished, thus mark it precise.
12473 		 */
12474 		err = mark_chain_precision(env, BPF_REG_1);
12475 		if (err)
12476 			return err;
12477 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
12478 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12479 						 set_loop_callback_state);
12480 		} else {
12481 			cur_func(env)->callback_depth = 0;
12482 			if (env->log.level & BPF_LOG_LEVEL2)
12483 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
12484 					env->cur_state->curframe);
12485 		}
12486 		break;
12487 	case BPF_FUNC_dynptr_from_mem:
12488 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
12489 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
12490 				reg_type_str(env, regs[BPF_REG_1].type));
12491 			return -EACCES;
12492 		}
12493 		break;
12494 	case BPF_FUNC_set_retval:
12495 	{
12496 		struct bpf_retval_range range = {
12497 			.minval = -MAX_ERRNO,
12498 			.maxval = 0,
12499 			.return_32bit = true
12500 		};
12501 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
12502 
12503 		if (r1->type != SCALAR_VALUE) {
12504 			verbose(env, "R1 is not a scalar\n");
12505 			return -EINVAL;
12506 		}
12507 
12508 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
12509 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
12510 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
12511 			break;
12512 
12513 		if (prog_type == BPF_PROG_TYPE_LSM &&
12514 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
12515 			if (!env->prog->aux->attach_func_proto->type) {
12516 				/* Make sure programs that attach to void
12517 				 * hooks don't try to modify return value.
12518 				 */
12519 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12520 				return -EINVAL;
12521 			}
12522 			bpf_lsm_get_retval_range(env->prog, &range);
12523 		}
12524 
12525 		err = mark_chain_precision(env, BPF_REG_1);
12526 		if (err)
12527 			return err;
12528 
12529 		if (!retval_range_within(range, r1)) {
12530 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
12531 			return -EINVAL;
12532 		}
12533 
12534 		break;
12535 	}
12536 	case BPF_FUNC_dynptr_write:
12537 	{
12538 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
12539 
12540 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
12541 			return -EFAULT;
12542 
12543 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
12544 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
12545 			/* this will trigger clear_all_pkt_pointers(), which will
12546 			 * invalidate all dynptr slices associated with the skb
12547 			 */
12548 			changes_data = true;
12549 
12550 		break;
12551 	}
12552 	case BPF_FUNC_per_cpu_ptr:
12553 	case BPF_FUNC_this_cpu_ptr:
12554 	{
12555 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
12556 		const struct btf_type *type;
12557 
12558 		if (reg->type & MEM_RCU) {
12559 			type = btf_type_by_id(reg->btf, reg->btf_id);
12560 			if (!type || !btf_type_is_struct(type)) {
12561 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
12562 				return -EFAULT;
12563 			}
12564 			returns_cpu_specific_alloc_ptr = true;
12565 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
12566 		}
12567 		break;
12568 	}
12569 	case BPF_FUNC_user_ringbuf_drain:
12570 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12571 					 set_user_ringbuf_callback_state);
12572 		break;
12573 	}
12574 
12575 	if (err)
12576 		return err;
12577 
12578 	/* reset caller saved regs */
12579 	bpf_diag_record_caller_saved(env, regs);
12580 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
12581 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12582 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
12583 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12584 	}
12585 	invalidate_outgoing_stack_args(env, cur_func(env));
12586 
12587 	/* update return register (already marked as written above) */
12588 	ret_type = fn->ret_type;
12589 	ret_flag = type_flag(ret_type);
12590 
12591 	switch (base_type(ret_type)) {
12592 	case RET_INTEGER:
12593 		/* sets type to SCALAR_VALUE */
12594 		mark_reg_unknown(env, regs, BPF_REG_0);
12595 		break;
12596 	case RET_VOID:
12597 		regs[BPF_REG_0].type = NOT_INIT;
12598 		break;
12599 	case RET_PTR_TO_MAP_VALUE:
12600 		/* There is no offset yet applied, variable or fixed */
12601 		mark_reg_known_zero(env, regs, BPF_REG_0);
12602 		/* remember map_ptr, so that check_map_access()
12603 		 * can check 'value_size' boundary of memory access
12604 		 * to map element returned from bpf_map_lookup_elem()
12605 		 */
12606 		if (meta.map.ptr == NULL) {
12607 			verifier_bug(env, "unexpected null map_ptr");
12608 			return -EFAULT;
12609 		}
12610 
12611 		if (func_id == BPF_FUNC_map_lookup_elem &&
12612 		    can_elide_value_nullness(meta.map.ptr) &&
12613 		    meta.const_map_key >= 0 &&
12614 		    meta.const_map_key < meta.map.ptr->max_entries)
12615 			ret_flag &= ~PTR_MAYBE_NULL;
12616 
12617 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
12618 		regs[BPF_REG_0].map_uid = meta.map.uid;
12619 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
12620 		if (type_may_be_null(ret_flag) ||
12621 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
12622 			regs[BPF_REG_0].id = ++env->id_gen;
12623 		}
12624 		/* requires regs[BPF_REG_0].id to be set because of the map-in-map case */
12625 		refine_map_lookup_value(&regs[BPF_REG_0]);
12626 		break;
12627 	case RET_PTR_TO_SOCKET:
12628 		mark_reg_known_zero(env, regs, BPF_REG_0);
12629 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
12630 		break;
12631 	case RET_PTR_TO_SOCK_COMMON:
12632 		mark_reg_known_zero(env, regs, BPF_REG_0);
12633 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
12634 		break;
12635 	case RET_PTR_TO_TCP_SOCK:
12636 		mark_reg_known_zero(env, regs, BPF_REG_0);
12637 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
12638 		break;
12639 	case RET_PTR_TO_MEM:
12640 		mark_reg_known_zero(env, regs, BPF_REG_0);
12641 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
12642 		regs[BPF_REG_0].mem_size = meta.ret_mem.size;
12643 		break;
12644 	case RET_PTR_TO_MEM_OR_BTF_ID:
12645 	{
12646 		const struct btf_type *t;
12647 
12648 		mark_reg_known_zero(env, regs, BPF_REG_0);
12649 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
12650 		if (!btf_type_is_struct(t)) {
12651 			u32 tsize;
12652 			const struct btf_type *ret;
12653 			const char *tname;
12654 
12655 			/* resolve the type size of ksym. */
12656 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
12657 			if (IS_ERR(ret)) {
12658 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
12659 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
12660 					tname, PTR_ERR(ret));
12661 				return -EINVAL;
12662 			}
12663 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
12664 			regs[BPF_REG_0].mem_size = tsize;
12665 		} else {
12666 			if (returns_cpu_specific_alloc_ptr) {
12667 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
12668 			} else {
12669 				/* MEM_RDONLY may be carried from ret_flag, but it
12670 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
12671 				 * it will confuse the check of PTR_TO_BTF_ID in
12672 				 * check_mem_access().
12673 				 */
12674 				ret_flag &= ~MEM_RDONLY;
12675 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
12676 			}
12677 
12678 			regs[BPF_REG_0].btf = meta.ret_btf;
12679 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12680 		}
12681 		break;
12682 	}
12683 	case RET_PTR_TO_BTF_ID:
12684 	{
12685 		struct btf *ret_btf;
12686 		int ret_btf_id;
12687 
12688 		mark_reg_known_zero(env, regs, BPF_REG_0);
12689 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
12690 		if (func_id == BPF_FUNC_kptr_xchg) {
12691 			ret_btf = meta.kptr_field->kptr.btf;
12692 			ret_btf_id = meta.kptr_field->kptr.btf_id;
12693 			if (!btf_is_kernel(ret_btf)) {
12694 				regs[BPF_REG_0].type |= MEM_ALLOC;
12695 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
12696 					regs[BPF_REG_0].type |= MEM_PERCPU;
12697 			}
12698 		} else {
12699 			if (fn->ret_btf_id == BPF_PTR_POISON) {
12700 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
12701 					     func_id_name(func_id));
12702 				return -EFAULT;
12703 			}
12704 			ret_btf = btf_vmlinux;
12705 			ret_btf_id = *fn->ret_btf_id;
12706 		}
12707 		if (ret_btf_id == 0) {
12708 			verbose(env, "invalid return type %u of func %s#%d\n",
12709 				base_type(ret_type), func_id_name(func_id),
12710 				func_id);
12711 			return -EINVAL;
12712 		}
12713 		regs[BPF_REG_0].btf = ret_btf;
12714 		regs[BPF_REG_0].btf_id = ret_btf_id;
12715 		break;
12716 	}
12717 	default:
12718 		verbose(env, "unknown return type %u of func %s#%d\n",
12719 			base_type(ret_type), func_id_name(func_id), func_id);
12720 		return -EINVAL;
12721 	}
12722 
12723 	if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id)
12724 		regs[BPF_REG_0].id = ++env->id_gen;
12725 
12726 	if (is_ptr_cast_function(func_id) &&
12727 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
12728 		struct bpf_verifier_state *branch;
12729 		struct bpf_reg_state *r0;
12730 
12731 		err = validate_ref_obj(env, &meta.ref_obj);
12732 		if (err)
12733 			return err;
12734 
12735 		bpf_diag_mod_end(env);
12736 
12737 		/*
12738 		 * In order for a release of any of the original or cast pointers
12739 		 * to invalidate all other pointers, reuse the same reference id for
12740 		 * the cast result.
12741 		 * This reference id can't be used for nullness propagation,
12742 		 * as cast might return NULL for a non-NULL input.
12743 		 * Hence, explore the NULL case as a separate branch.
12744 		 */
12745 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12746 		if (IS_ERR(branch))
12747 			return PTR_ERR(branch);
12748 
12749 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
12750 		__mark_reg_known_zero(r0);
12751 		r0->type = SCALAR_VALUE;
12752 
12753 		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
12754 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
12755 		regs[BPF_REG_0].id = meta.ref_obj.id;
12756 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
12757 		int id = acquire_reference(env, insn_idx, 0);
12758 
12759 		if (id < 0)
12760 			return id;
12761 
12762 		regs[BPF_REG_0].id = id;
12763 	}
12764 
12765 	if (func_id == BPF_FUNC_dynptr_data)
12766 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
12767 
12768 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
12769 	if (err)
12770 		return err;
12771 
12772 	bpf_diag_mod_end(env);
12773 
12774 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
12775 	if (err)
12776 		return err;
12777 
12778 	if ((func_id == BPF_FUNC_get_stack ||
12779 	     func_id == BPF_FUNC_get_task_stack) &&
12780 	    !env->prog->has_callchain_buf) {
12781 		const char *err_str;
12782 
12783 #ifdef CONFIG_PERF_EVENTS
12784 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
12785 		err_str = "cannot get callchain buffer for func %s#%d\n";
12786 #else
12787 		err = -ENOTSUPP;
12788 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
12789 #endif
12790 		if (err) {
12791 			verbose(env, err_str, func_id_name(func_id), func_id);
12792 			return err;
12793 		}
12794 
12795 		env->prog->has_callchain_buf = true;
12796 	}
12797 
12798 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
12799 		env->prog->call_get_stack = true;
12800 
12801 	if (func_id == BPF_FUNC_get_func_ip) {
12802 		if (check_get_func_ip(env))
12803 			return -ENOTSUPP;
12804 		env->prog->call_get_func_ip = true;
12805 	}
12806 
12807 	if (func_id == BPF_FUNC_tail_call) {
12808 		if (env->cur_state->curframe) {
12809 			struct bpf_verifier_state *branch;
12810 
12811 			/*
12812 			 * A taken tail call is modeled as a return from the current
12813 			 * frame. A callback frame cannot be left that way because
12814 			 * prepare_func_exit() would apply its return contract to the
12815 			 * unknown R0 synthesized below. Stack-depth validation rejects
12816 			 * this construct anyway.
12817 			 */
12818 			if (cur_func(env)->in_callback_fn) {
12819 				verbose(env, "cannot tail call within callback\n");
12820 				return -EINVAL;
12821 			}
12822 			mark_reg_scratched(env, BPF_REG_0);
12823 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12824 			if (IS_ERR(branch))
12825 				return PTR_ERR(branch);
12826 			clear_all_pkt_pointers(env);
12827 			mark_reg_unknown(env, regs, BPF_REG_0);
12828 			err = prepare_func_exit(env, &env->insn_idx);
12829 			if (err)
12830 				return err;
12831 			env->insn_idx--;
12832 		} else {
12833 			changes_data = false;
12834 		}
12835 	}
12836 
12837 	if (changes_data)
12838 		clear_all_pkt_pointers(env);
12839 	return 0;
12840 }
12841 
12842 /*
12843  * Mark the register(s) holding a @size byte kfunc return value as unknown
12844  * scalars and return how many registers that took. Both halves of a register
12845  * pair are treated the same way.
12846  *
12847  * R0 is written in the diagnostic modification scope the caller opened before
12848  * the caller-saved scrub, since R0 gets no scrub record of its own and that
12849  * scope is what carries its pre-call value into the history. A scope tracks a
12850  * single register and does not nest, so close it before recording the rest of
12851  * the return value. A value that fits in R0 leaves the caller's scope open for
12852  * the caller to close, so a later write to R0 still lands in it.
12853  */
12854 static u32 mark_kfunc_ret_regs(struct bpf_verifier_env *env,
12855 			       struct bpf_reg_state *regs, u32 size)
12856 {
12857 	u32 i, nregs = ret_regs_cnt(size);
12858 
12859 	mark_reg_unknown(env, regs, ret_regs[0]);
12860 	if (nregs == 1)
12861 		return nregs;
12862 
12863 	bpf_diag_mod_end(env);
12864 	for (i = 1; i < nregs; i++) {
12865 		bpf_diag_mod_begin(env, &regs[ret_regs[i]], NULL, BPF_DIAG_MOD_WRITE);
12866 		mark_reg_unknown(env, regs, ret_regs[i]);
12867 		bpf_diag_mod_end(env);
12868 	}
12869 
12870 	return nregs;
12871 }
12872 
12873 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta)
12874 {
12875 	return meta->kfunc_flags & KF_ACQUIRE;
12876 }
12877 
12878 static bool is_kfunc_release(struct bpf_call_arg_meta *meta)
12879 {
12880 	return meta->kfunc_flags & KF_RELEASE;
12881 }
12882 
12883 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta)
12884 {
12885 	return meta->kfunc_flags & KF_DESTRUCTIVE;
12886 }
12887 
12888 static bool is_kfunc_perfmon(struct bpf_call_arg_meta *meta)
12889 {
12890 	return meta->kfunc_flags & KF_PERFMON;
12891 }
12892 
12893 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta)
12894 {
12895 	return meta->kfunc_flags & KF_RCU;
12896 }
12897 
12898 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta)
12899 {
12900 	return meta->kfunc_flags & KF_RCU_PROTECTED;
12901 }
12902 
12903 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12904 				  const struct btf_param *arg)
12905 {
12906 	const struct btf_type *t;
12907 
12908 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12909 	if (!btf_type_is_scalar(t))
12910 		return false;
12911 
12912 	return btf_param_match_suffix(btf, arg, "__sz");
12913 }
12914 
12915 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12916 					const struct btf_param *arg)
12917 {
12918 	const struct btf_type *t;
12919 
12920 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12921 	if (!btf_type_is_scalar(t))
12922 		return false;
12923 
12924 	return btf_param_match_suffix(btf, arg, "__szk");
12925 }
12926 
12927 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12928 {
12929 	return btf_param_match_suffix(btf, arg, "__k");
12930 }
12931 
12932 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12933 {
12934 	return btf_param_match_suffix(btf, arg, "__ign");
12935 }
12936 
12937 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12938 {
12939 	return btf_param_match_suffix(btf, arg, "__map");
12940 }
12941 
12942 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg)
12943 {
12944 	return btf_param_match_suffix(btf, arg, "__const_map");
12945 }
12946 
12947 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12948 {
12949 	return btf_param_match_suffix(btf, arg, "__alloc");
12950 }
12951 
12952 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12953 {
12954 	return btf_param_match_suffix(btf, arg, "__uninit");
12955 }
12956 
12957 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12958 {
12959 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12960 }
12961 
12962 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12963 {
12964 	return btf_param_match_suffix(btf, arg, "__nullable") ||
12965 	       btf_param_match_suffix(btf, arg, "__arena");
12966 }
12967 
12968 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
12969 {
12970 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
12971 }
12972 
12973 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12974 {
12975 	return btf_param_match_suffix(btf, arg, "__str");
12976 }
12977 
12978 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12979 {
12980 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12981 }
12982 
12983 static bool is_kfunc_arg_ctx_out(const struct btf *btf, const struct btf_param *arg)
12984 {
12985 	return btf_param_match_suffix(btf, arg, "__ctx_out");
12986 }
12987 
12988 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg)
12989 {
12990 	return btf_param_match_suffix(btf, arg, "__arena__nullable") ||
12991 	       btf_param_match_suffix(btf, arg, "__arena");
12992 }
12993 
12994 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12995 					  const struct btf_param *arg,
12996 					  const char *name)
12997 {
12998 	int len, target_len = strlen(name);
12999 	const char *param_name;
13000 
13001 	param_name = btf_name_by_offset(btf, arg->name_off);
13002 	if (str_is_empty(param_name))
13003 		return false;
13004 	len = strlen(param_name);
13005 	if (len != target_len)
13006 		return false;
13007 	if (strcmp(param_name, name))
13008 		return false;
13009 
13010 	return true;
13011 }
13012 
13013 enum {
13014 	KF_ARG_DYNPTR_ID,
13015 	KF_ARG_LIST_HEAD_ID,
13016 	KF_ARG_LIST_NODE_ID,
13017 	KF_ARG_RB_ROOT_ID,
13018 	KF_ARG_RB_NODE_ID,
13019 	KF_ARG_WORKQUEUE_ID,
13020 	KF_ARG_RES_SPIN_LOCK_ID,
13021 	KF_ARG_TASK_WORK_ID,
13022 	KF_ARG_PROG_AUX_ID,
13023 	KF_ARG_TIMER_ID,
13024 	KF_ARG_RCU_HEAD_ID
13025 };
13026 
13027 BTF_ID_LIST(kf_arg_btf_ids)
13028 BTF_ID(struct, bpf_dynptr)
13029 BTF_ID(struct, bpf_list_head)
13030 BTF_ID(struct, bpf_list_node)
13031 BTF_ID(struct, bpf_rb_root)
13032 BTF_ID(struct, bpf_rb_node)
13033 BTF_ID(struct, bpf_wq)
13034 BTF_ID(struct, bpf_res_spin_lock)
13035 BTF_ID(struct, bpf_task_work)
13036 BTF_ID(struct, bpf_prog_aux)
13037 BTF_ID(struct, bpf_timer)
13038 BTF_ID(struct, bpf_rcu_head)
13039 
13040 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
13041 				    const struct btf_param *arg, int type)
13042 {
13043 	const struct btf_type *t;
13044 	u32 res_id;
13045 
13046 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13047 	if (!t)
13048 		return false;
13049 	if (!btf_type_is_ptr(t))
13050 		return false;
13051 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
13052 	if (!t)
13053 		return false;
13054 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
13055 }
13056 
13057 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
13058 {
13059 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
13060 }
13061 
13062 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
13063 {
13064 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
13065 }
13066 
13067 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
13068 {
13069 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
13070 }
13071 
13072 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
13073 {
13074 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
13075 }
13076 
13077 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
13078 {
13079 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
13080 }
13081 
13082 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
13083 {
13084 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
13085 }
13086 
13087 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
13088 {
13089 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
13090 }
13091 
13092 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
13093 {
13094 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
13095 }
13096 
13097 static bool is_kfunc_arg_rcu_head(const struct btf *btf, const struct btf_param *arg)
13098 {
13099 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RCU_HEAD_ID);
13100 }
13101 
13102 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
13103 {
13104 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
13105 }
13106 
13107 static bool is_rbtree_node_type(const struct btf_type *t)
13108 {
13109 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
13110 }
13111 
13112 static bool is_list_node_type(const struct btf_type *t)
13113 {
13114 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
13115 }
13116 
13117 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
13118 				  const struct btf_param *arg)
13119 {
13120 	const struct btf_type *t;
13121 
13122 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
13123 	if (!t)
13124 		return false;
13125 
13126 	return true;
13127 }
13128 
13129 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
13130 {
13131 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
13132 }
13133 
13134 /*
13135  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
13136  *   - the _impl prototype with full arg list (meta->func_proto)
13137  *   - the BPF API prototype w/o implicit args (func->type in BTF)
13138  * To determine whether an argument is implicit, we compare its position
13139  * against the number of arguments in the prototype w/o implicit args.
13140  */
13141 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx)
13142 {
13143 	const struct btf_type *func, *func_proto;
13144 	u32 argn;
13145 
13146 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
13147 		return false;
13148 
13149 	func = btf_type_by_id(meta->btf, meta->func_id);
13150 	func_proto = btf_type_by_id(meta->btf, func->type);
13151 	argn = btf_type_vlen(func_proto);
13152 
13153 	return argn <= arg_idx;
13154 }
13155 
13156 #define BTF_MEMBER_MAX_DEPTH	4
13157 #define BTF_MEMBER_PATH_LEN	64
13158 
13159 struct btf_member_path {
13160 	const struct btf_member *member[BTF_MEMBER_MAX_DEPTH];
13161 	bool in_array[BTF_MEMBER_MAX_DEPTH];
13162 	const struct btf_type *bad_type;
13163 	int depth;
13164 	bool too_deep;
13165 };
13166 
13167 static bool btf_member_kind_allowed(const struct btf *btf, const struct btf_type *t,
13168 				    u32 member_kinds)
13169 {
13170 	if ((member_kinds & BTF_MEMBER_SCALAR) && btf_type_is_scalar(t))
13171 		return true;
13172 	if ((member_kinds & BTF_MEMBER_ARENA_PTR) && btf_type_is_arena_ptr(btf, t))
13173 		return true;
13174 	return false;
13175 }
13176 
13177 /*
13178  * Returns true if every member of struct @t is of a kind listed in
13179  * @member_kinds, 4 levels of nesting allowed. An array member counts as its
13180  * element type.
13181  */
13182 static bool btf_struct_member_walk(struct bpf_verifier_env *env, const struct btf *btf,
13183 				   const struct btf_type *t, u32 member_kinds, int rec,
13184 				   struct btf_member_path *path)
13185 {
13186 	const struct btf_type *member_type;
13187 	const struct btf_member *member;
13188 	bool in_array;
13189 	u32 i;
13190 
13191 	if (!btf_type_is_struct(t))
13192 		return false;
13193 
13194 	for_each_member(i, t, member) {
13195 		const struct btf_array *array;
13196 
13197 		in_array = false;
13198 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
13199 		/*
13200 		 * Every element of an array is laid out in the value being
13201 		 * returned, so an array counts as its element type however many
13202 		 * dimensions deep that is.
13203 		 */
13204 		while (btf_type_is_array(member_type)) {
13205 			array = btf_array(member_type);
13206 			if (!array->nelems) {
13207 				member_type = NULL;
13208 				goto bad_member;
13209 			}
13210 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
13211 			in_array = true;
13212 		}
13213 		if (btf_type_is_struct(member_type)) {
13214 			if (rec >= BTF_MEMBER_MAX_DEPTH - 1) {
13215 				verbose(env, "max struct nesting depth exceeded\n");
13216 				if (path)
13217 					path->too_deep = true;
13218 				return false;
13219 			}
13220 			if (!btf_struct_member_walk(env, btf, member_type, member_kinds,
13221 						    rec + 1, path))
13222 				goto bad_path;
13223 			continue;
13224 		}
13225 		if (!btf_member_kind_allowed(btf, member_type, member_kinds))
13226 			goto bad_member;
13227 	}
13228 	return true;
13229 
13230 bad_member:
13231 	if (path) {
13232 		path->depth = rec + 1;
13233 		path->bad_type = member_type;
13234 	}
13235 bad_path:
13236 	if (path && path->depth) {
13237 		path->member[rec] = member;
13238 		path->in_array[rec] = in_array;
13239 	}
13240 	return false;
13241 }
13242 
13243 bool btf_struct_is_composed_of(struct bpf_verifier_env *env,
13244 			       const struct btf *btf,
13245 			       const struct btf_type *t, u32 member_kinds)
13246 {
13247 	return btf_struct_member_walk(env, btf, t, member_kinds, 0, NULL);
13248 }
13249 
13250 static bool btf_type_is_scalar_struct(struct bpf_verifier_env *env,
13251 				      const struct btf *btf,
13252 				      const struct btf_type *t)
13253 {
13254 	return btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR);
13255 }
13256 
13257 static int resolve_func_arg_type(struct bpf_verifier_env *env,
13258 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
13259 				 struct bpf_call_arg_meta *meta,
13260 				 enum bpf_arg_type *arg_type, u32 *arg_size)
13261 {
13262 	const struct btf_param *args;
13263 	const struct btf_type *ref_t, *resolve_ret;
13264 	const struct btf *btf;
13265 	const char *ref_tname;
13266 	u32 ref_id;
13267 
13268 	if (base_type(*arg_type) == ARG_PTR_TO_MAP_VALUE)
13269 		return resolve_map_arg_type(env, meta, arg_type);
13270 
13271 	if (base_type(*arg_type) != ARG_PTR_TO_BTF_ID)
13272 		return 0;
13273 
13274 	if (!is_kfunc(meta) || arg_type_is_release(*arg_type) ||
13275 	    base_type(reg->type) == PTR_TO_BTF_ID ||
13276 	    reg2btf_ids[base_type(reg->type)])
13277 		return 0;
13278 
13279 	args = btf_params(meta->func_proto);
13280 	ref_id = *meta->fn->arg_btf_id[arg];
13281 	btf = is_kfunc_arg_map(meta->btf, &args[arg]) ? btf_vmlinux : meta->btf;
13282 	ref_t = btf_type_skip_modifiers(btf, ref_id, &ref_id);
13283 	ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13284 
13285 	if (!btf_type_is_scalar_struct(env, btf, ref_t))
13286 		return 0;
13287 
13288 	resolve_ret = btf_resolve_size(btf, ref_t, arg_size);
13289 	if (IS_ERR(resolve_ret)) {
13290 		verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
13291 			reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname,
13292 			PTR_ERR(resolve_ret));
13293 		return -EINVAL;
13294 	}
13295 	*arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE |
13296 		    (*arg_type & (PTR_MAYBE_NULL | MEM_UNINIT));
13297 
13298 	return 0;
13299 }
13300 
13301 static void btf_member_path_str(const struct btf *btf, const struct btf_member_path *path,
13302 				char *buf, size_t buf_sz)
13303 {
13304 	size_t len = 0;
13305 	int i;
13306 
13307 	buf[0] = '\0';
13308 	for (i = 0; i < path->depth; i++) {
13309 		const char *name = btf_name_by_offset(btf, path->member[i]->name_off);
13310 
13311 		/* An anonymous struct or union has no name to spell. */
13312 		if (!name || !name[0])
13313 			continue;
13314 		len += scnprintf(buf + len, buf_sz - len, "%s%s", len ? "." : "", name);
13315 		if (path->in_array[i])
13316 			len += scnprintf(buf + len, buf_sz - len, "[]");
13317 	}
13318 }
13319 
13320 enum special_kfunc_type {
13321 	KF_bpf_obj_new_impl,
13322 	KF_bpf_obj_new,
13323 	KF_bpf_obj_drop_impl,
13324 	KF_bpf_obj_drop,
13325 	KF_bpf_refcount_acquire_impl,
13326 	KF_bpf_refcount_acquire,
13327 	KF_bpf_list_push_front_impl,
13328 	KF_bpf_list_push_front,
13329 	KF_bpf_list_push_back_impl,
13330 	KF_bpf_list_push_back,
13331 	KF_bpf_list_add,
13332 	KF_bpf_list_pop_front,
13333 	KF_bpf_list_pop_back,
13334 	KF_bpf_list_del,
13335 	KF_bpf_list_front,
13336 	KF_bpf_list_back,
13337 	KF_bpf_list_is_first,
13338 	KF_bpf_list_is_last,
13339 	KF_bpf_list_empty,
13340 	KF_bpf_cast_to_kern_ctx,
13341 	KF_bpf_rdonly_cast,
13342 	KF_bpf_rcu_read_lock,
13343 	KF_bpf_rcu_read_unlock,
13344 	KF_bpf_rbtree_remove,
13345 	KF_bpf_rbtree_add_impl,
13346 	KF_bpf_rbtree_add,
13347 	KF_bpf_rbtree_first,
13348 	KF_bpf_rbtree_root,
13349 	KF_bpf_rbtree_left,
13350 	KF_bpf_rbtree_right,
13351 	KF_bpf_dynptr_from_skb,
13352 	KF_bpf_dynptr_from_xdp,
13353 	KF_bpf_dynptr_from_skb_meta,
13354 	KF_bpf_xdp_pull_data,
13355 	KF_bpf_dynptr_slice,
13356 	KF_bpf_dynptr_slice_rdwr,
13357 	KF_bpf_dynptr_clone,
13358 	KF_bpf_percpu_obj_new_impl,
13359 	KF_bpf_percpu_obj_new,
13360 	KF_bpf_percpu_obj_drop_impl,
13361 	KF_bpf_percpu_obj_drop,
13362 	KF_bpf_throw,
13363 	KF_bpf_wq_set_callback,
13364 	KF_bpf_preempt_disable,
13365 	KF_bpf_preempt_enable,
13366 	KF_bpf_iter_css_task_new,
13367 	KF_bpf_session_cookie,
13368 	KF_bpf_get_kmem_cache,
13369 	KF_bpf_local_irq_save,
13370 	KF_bpf_local_irq_restore,
13371 	KF_bpf_iter_num_new,
13372 	KF_bpf_iter_num_next,
13373 	KF_bpf_iter_num_destroy,
13374 	KF_bpf_set_dentry_xattr,
13375 	KF_bpf_remove_dentry_xattr,
13376 	KF_bpf_res_spin_lock,
13377 	KF_bpf_res_spin_unlock,
13378 	KF_bpf_res_spin_lock_irqsave,
13379 	KF_bpf_res_spin_unlock_irqrestore,
13380 	KF_bpf_dynptr_from_file,
13381 	KF_bpf_dynptr_file_discard,
13382 	KF___bpf_trap,
13383 	KF_bpf_task_work_schedule_signal,
13384 	KF_bpf_task_work_schedule_resume,
13385 	KF_bpf_call_rcu,
13386 	KF_bpf_call_rcu_tasks_trace,
13387 	KF_bpf_arena_alloc_pages,
13388 	KF_bpf_arena_free_pages,
13389 	KF_bpf_arena_reserve_pages,
13390 	KF_bpf_session_is_return,
13391 	KF_bpf_stream_vprintk,
13392 	KF_bpf_stream_print_stack,
13393 };
13394 
13395 BTF_ID_LIST(special_kfunc_list)
13396 BTF_ID(func, bpf_obj_new_impl)
13397 BTF_ID(func, bpf_obj_new)
13398 BTF_ID(func, bpf_obj_drop_impl)
13399 BTF_ID(func, bpf_obj_drop)
13400 BTF_ID(func, bpf_refcount_acquire_impl)
13401 BTF_ID(func, bpf_refcount_acquire)
13402 BTF_ID(func, bpf_list_push_front_impl)
13403 BTF_ID(func, bpf_list_push_front)
13404 BTF_ID(func, bpf_list_push_back_impl)
13405 BTF_ID(func, bpf_list_push_back)
13406 BTF_ID(func, bpf_list_add)
13407 BTF_ID(func, bpf_list_pop_front)
13408 BTF_ID(func, bpf_list_pop_back)
13409 BTF_ID(func, bpf_list_del)
13410 BTF_ID(func, bpf_list_front)
13411 BTF_ID(func, bpf_list_back)
13412 BTF_ID(func, bpf_list_is_first)
13413 BTF_ID(func, bpf_list_is_last)
13414 BTF_ID(func, bpf_list_empty)
13415 BTF_ID(func, bpf_cast_to_kern_ctx)
13416 BTF_ID(func, bpf_rdonly_cast)
13417 BTF_ID(func, bpf_rcu_read_lock)
13418 BTF_ID(func, bpf_rcu_read_unlock)
13419 BTF_ID(func, bpf_rbtree_remove)
13420 BTF_ID(func, bpf_rbtree_add_impl)
13421 BTF_ID(func, bpf_rbtree_add)
13422 BTF_ID(func, bpf_rbtree_first)
13423 BTF_ID(func, bpf_rbtree_root)
13424 BTF_ID(func, bpf_rbtree_left)
13425 BTF_ID(func, bpf_rbtree_right)
13426 #ifdef CONFIG_NET
13427 BTF_ID(func, bpf_dynptr_from_skb)
13428 BTF_ID(func, bpf_dynptr_from_xdp)
13429 BTF_ID(func, bpf_dynptr_from_skb_meta)
13430 BTF_ID(func, bpf_xdp_pull_data)
13431 #else
13432 BTF_ID_UNUSED
13433 BTF_ID_UNUSED
13434 BTF_ID_UNUSED
13435 BTF_ID_UNUSED
13436 #endif
13437 BTF_ID(func, bpf_dynptr_slice)
13438 BTF_ID(func, bpf_dynptr_slice_rdwr)
13439 BTF_ID(func, bpf_dynptr_clone)
13440 BTF_ID(func, bpf_percpu_obj_new_impl)
13441 BTF_ID(func, bpf_percpu_obj_new)
13442 BTF_ID(func, bpf_percpu_obj_drop_impl)
13443 BTF_ID(func, bpf_percpu_obj_drop)
13444 BTF_ID(func, bpf_throw)
13445 BTF_ID(func, bpf_wq_set_callback)
13446 BTF_ID(func, bpf_preempt_disable)
13447 BTF_ID(func, bpf_preempt_enable)
13448 #ifdef CONFIG_CGROUPS
13449 BTF_ID(func, bpf_iter_css_task_new)
13450 #else
13451 BTF_ID_UNUSED
13452 #endif
13453 #ifdef CONFIG_BPF_EVENTS
13454 BTF_ID(func, bpf_session_cookie)
13455 #else
13456 BTF_ID_UNUSED
13457 #endif
13458 BTF_ID(func, bpf_get_kmem_cache)
13459 BTF_ID(func, bpf_local_irq_save)
13460 BTF_ID(func, bpf_local_irq_restore)
13461 BTF_ID(func, bpf_iter_num_new)
13462 BTF_ID(func, bpf_iter_num_next)
13463 BTF_ID(func, bpf_iter_num_destroy)
13464 #ifdef CONFIG_BPF_LSM
13465 BTF_ID(func, bpf_set_dentry_xattr)
13466 BTF_ID(func, bpf_remove_dentry_xattr)
13467 #else
13468 BTF_ID_UNUSED
13469 BTF_ID_UNUSED
13470 #endif
13471 BTF_ID(func, bpf_res_spin_lock)
13472 BTF_ID(func, bpf_res_spin_unlock)
13473 BTF_ID(func, bpf_res_spin_lock_irqsave)
13474 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
13475 BTF_ID(func, bpf_dynptr_from_file)
13476 BTF_ID(func, bpf_dynptr_file_discard)
13477 BTF_ID(func, __bpf_trap)
13478 BTF_ID(func, bpf_task_work_schedule_signal)
13479 BTF_ID(func, bpf_task_work_schedule_resume)
13480 BTF_ID(func, bpf_call_rcu)
13481 BTF_ID(func, bpf_call_rcu_tasks_trace)
13482 BTF_ID(func, bpf_arena_alloc_pages)
13483 BTF_ID(func, bpf_arena_free_pages)
13484 BTF_ID(func, bpf_arena_reserve_pages)
13485 #ifdef CONFIG_BPF_EVENTS
13486 BTF_ID(func, bpf_session_is_return)
13487 #else
13488 BTF_ID_UNUSED
13489 #endif
13490 BTF_ID(func, bpf_stream_vprintk)
13491 BTF_ID(func, bpf_stream_print_stack)
13492 
13493 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta)
13494 {
13495 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]);
13496 }
13497 
13498 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta)
13499 {
13500 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_clone]);
13501 }
13502 
13503 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta)
13504 {
13505 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_iter_css_task_new]);
13506 }
13507 
13508 static bool is_bpf_obj_new_kfunc(u32 func_id)
13509 {
13510 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
13511 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
13512 }
13513 
13514 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
13515 {
13516 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
13517 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
13518 }
13519 
13520 static bool is_bpf_obj_drop_kfunc(u32 func_id)
13521 {
13522 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
13523 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
13524 }
13525 
13526 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
13527 {
13528 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
13529 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
13530 }
13531 
13532 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
13533 {
13534 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
13535 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
13536 }
13537 
13538 static bool is_bpf_list_push_kfunc(u32 func_id)
13539 {
13540 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
13541 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13542 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
13543 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13544 	       func_id == special_kfunc_list[KF_bpf_list_add];
13545 }
13546 
13547 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
13548 {
13549 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
13550 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
13551 }
13552 
13553 static bool is_call_rcu_kfunc(u32 func_id)
13554 {
13555 	return func_id == special_kfunc_list[KF_bpf_call_rcu] ||
13556 	       func_id == special_kfunc_list[KF_bpf_call_rcu_tasks_trace];
13557 }
13558 
13559 static bool is_task_work_add_kfunc(u32 func_id)
13560 {
13561 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
13562 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
13563 }
13564 
13565 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta)
13566 {
13567 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
13568 		return false;
13569 
13570 	return meta->kfunc_flags & KF_RET_NULL;
13571 }
13572 
13573 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta)
13574 {
13575 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_lock]);
13576 }
13577 
13578 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta)
13579 {
13580 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_unlock]);
13581 }
13582 
13583 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta)
13584 {
13585 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_disable]);
13586 }
13587 
13588 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta)
13589 {
13590 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_enable]);
13591 }
13592 
13593 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta)
13594 {
13595 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_xdp_pull_data]);
13596 }
13597 
13598 static u32 kfunc_abi_slots(const struct btf_func_model *fm)
13599 {
13600 	const struct bpf_jit_arg_abi *abi = bpf_jit_arg_abi();
13601 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
13602 	u32 i, nslots, slots = 0;
13603 
13604 	for (i = 0; i < fm->nr_args; i++)
13605 		slots += btf_func_model_arg_slots(fm, i);
13606 
13607 	if (!abi)
13608 		return slots;
13609 
13610 	nslots = bpf_jit_place_args(abi, fm, pos_of_slot);
13611 	for (i = 0; i < nslots; i++)
13612 		if (pos_of_slot[i] + 1 > slots)
13613 			slots = pos_of_slot[i] + 1;
13614 
13615 	return slots;
13616 }
13617 
13618 static u32 __btf_func_arg_align(const struct btf *btf, const struct btf_type *t, int rec)
13619 {
13620 	const struct btf_member *member;
13621 	const struct btf_type *mt;
13622 	u32 align, i;
13623 
13624 	while (btf_type_is_array(t))
13625 		t = btf_type_skip_modifiers(btf, btf_array(t)->type, NULL);
13626 
13627 	if (btf_type_is_int(t))
13628 		return t->size > BPF_REG_SIZE ? t->size : BPF_REG_SIZE;
13629 	if (!btf_type_is_struct(t))
13630 		return BPF_REG_SIZE;
13631 	if (rec >= BTF_MEMBER_MAX_DEPTH)
13632 		return 0;
13633 
13634 	for_each_member(i, t, member) {
13635 		mt = btf_type_skip_modifiers(btf, member->type, NULL);
13636 		align = __btf_func_arg_align(btf, mt, rec + 1);
13637 		if (!align)
13638 			return 0;
13639 		if (align > BPF_REG_SIZE)
13640 			return 2 * BPF_REG_SIZE;
13641 	}
13642 	return BPF_REG_SIZE;
13643 }
13644 
13645 u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t)
13646 {
13647 	return __btf_func_arg_align(btf, t, 0);
13648 }
13649 
13650 static int
13651 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
13652 		   const struct btf_param *args, int arg, int nargs, u32 slot,
13653 		   struct bpf_func_proto *proto)
13654 {
13655 	const struct btf_type *t, *ref_t = NULL, *resolve_ret;
13656 	const u32 *ref_id_ptr = NULL;
13657 	argno_t argno = argno_from_arg(slot + 1);
13658 	const char *ref_tname = NULL;
13659 	u32 ref_id, type_size;
13660 	int arg_type;
13661 
13662 	proto->arg_btf_id[arg] = NULL;
13663 
13664 	if (is_kfunc_arg_prog_aux(meta->btf, &args[arg]))
13665 		return ARG_PTR_TO_PROG_AUX;
13666 
13667 	if (is_kfunc_arg_ignore(meta->btf, &args[arg]) || is_kfunc_arg_implicit(meta, arg))
13668 		return ARG_IGNORE;
13669 
13670 	t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
13671 
13672 	/* Scalar arguments are classified from their BTF suffix/name alone. */
13673 	if (btf_type_is_scalar(t)) {
13674 		if (is_kfunc_arg_constant(meta->btf, &args[arg]))
13675 			return ARG_CONST_SCALAR;
13676 		if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg]))
13677 			return ARG_CONST_MEM_SIZE;
13678 		if (is_kfunc_arg_mem_size(meta->btf, &args[arg]))
13679 			return ARG_MEM_SIZE;
13680 		if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") ||
13681 		    is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size"))
13682 			return ARG_CONST_ALLOC_SIZE_OR_ZERO;
13683 		return ARG_SCALAR;
13684 	}
13685 
13686 	if (btf_type_is_struct(t)) {
13687 		if (!t->size || t->size > 2 * BPF_REG_SIZE) {
13688 			verbose(env,
13689 				"%s type %s has size %u, only 1 to %d bytes "
13690 				"can be passed by value\n",
13691 				reg_arg_name(env, argno), btf_type_str(t), t->size,
13692 				2 * BPF_REG_SIZE);
13693 			return -EINVAL;
13694 		}
13695 		if (!btf_type_is_scalar_struct(env, meta->btf, t)) {
13696 			verbose(env, "%s type %s is not composed of scalars\n",
13697 				reg_arg_name(env, argno), btf_type_str(t));
13698 			return -EINVAL;
13699 		}
13700 		return ARG_SCALAR;
13701 	}
13702 
13703 	if (!btf_type_is_ptr(t)) {
13704 		verbose(env, "Unrecognized %s type %s\n",
13705 			reg_arg_name(env, argno), btf_type_str(t));
13706 		return -EINVAL;
13707 	}
13708 	/* Keep a pointer to the BTF field containing the resolved referent ID. */
13709 	ref_id_ptr = &t->type;
13710 	ref_t = btf_type_skip_modifiers(meta->btf, *ref_id_ptr, &ref_id);
13711 	while (*ref_id_ptr != ref_id)
13712 		ref_id_ptr = &btf_type_by_id(meta->btf, *ref_id_ptr)->type;
13713 	ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
13714 
13715 	/* In this function, we verify the kfunc's BTF as per the argument type,
13716 	 * leaving the rest of the verification with respect to the register
13717 	 * type to our caller. When a set of conditions hold in the BTF type of
13718 	 * arguments, we resolve it to a known bpf_arg_type.
13719 	 */
13720 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]) ||
13721 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_is_return]) ||
13722 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_cookie]))
13723 		arg_type = ARG_PTR_TO_CTX;
13724 	else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
13725 		arg_type = ARG_PTR_TO_CTX;
13726 	else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
13727 		arg_type = ARG_PTR_TO_ALLOC_BTF_ID;
13728 	else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
13729 		arg_type = ARG_PTR_TO_REFCOUNTED_KPTR;
13730 	else if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) {
13731 		arg_type = ARG_PTR_TO_DYNPTR;
13732 
13733 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb]))
13734 			arg_type |= DYNPTR_TYPE_SKB;
13735 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_xdp]))
13736 			arg_type |= DYNPTR_TYPE_XDP;
13737 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb_meta]))
13738 			arg_type |= DYNPTR_TYPE_SKB_META;
13739 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_file]) ||
13740 			 is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_file_discard]))
13741 			/* OBJ_RELEASE for the latter comes from KF_RELEASE below */
13742 			arg_type |= DYNPTR_TYPE_FILE;
13743 	} else if (is_kfunc_arg_iter(meta, arg, &args[arg]))
13744 		arg_type = ARG_PTR_TO_ITER;
13745 	else if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
13746 		arg_type = ARG_PTR_TO_LIST_HEAD;
13747 	else if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
13748 		arg_type = ARG_PTR_TO_LIST_NODE;
13749 	else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
13750 		arg_type = ARG_PTR_TO_RB_ROOT;
13751 	else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
13752 		arg_type = ARG_PTR_TO_RB_NODE;
13753 	else if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
13754 		arg_type = ARG_PTR_TO_CONST_STR;
13755 	else if (is_kfunc_arg_const_map(meta->btf, &args[arg]))
13756 		arg_type = ARG_CONST_MAP_PTR;
13757 	else if (is_kfunc_arg_map(meta->btf, &args[arg]))
13758 		arg_type = ARG_PTR_TO_BTF_ID;
13759 	else if (is_kfunc_arg_wq(meta->btf, &args[arg]))
13760 		arg_type = ARG_PTR_TO_WORKQUEUE;
13761 	else if (is_kfunc_arg_timer(meta->btf, &args[arg]))
13762 		arg_type = ARG_PTR_TO_TIMER;
13763 	else if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
13764 		arg_type = ARG_PTR_TO_TASK_WORK;
13765 	else if (is_kfunc_arg_rcu_head(meta->btf, &args[arg]))
13766 		arg_type = ARG_PTR_TO_RCU_HEAD;
13767 	else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
13768 		arg_type = ARG_PTR_TO_IRQ_FLAG;
13769 	else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
13770 		arg_type = ARG_PTR_TO_RES_SPIN_LOCK;
13771 	else if (is_kfunc_arg_ctx_out(meta->btf, &args[arg])) {
13772 		if (!btf_type_is_scalar(ref_t)) {
13773 			verbose(env, "%s __ctx_out argument must point to a scalar\n",
13774 				reg_arg_name(env, argno));
13775 			return -EINVAL;
13776 		}
13777 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
13778 		if (IS_ERR(resolve_ret)) {
13779 			verbose(env,
13780 				"%s reference type('%s %s') size cannot be determined: %ld\n",
13781 				reg_arg_name(env, argno), btf_type_str(ref_t),
13782 				ref_tname, PTR_ERR(resolve_ret));
13783 			return -EINVAL;
13784 		}
13785 		proto->arg_size[arg] = type_size;
13786 		arg_type = ARG_PTR_TO_CTX_OUT | MEM_FIXED_SIZE;
13787 	} else if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
13788 		arg_type = ARG_PTR_TO_FUNC;
13789 	else if (is_kfunc_arg_arena(meta->btf, &args[arg])) {
13790 		if (!bpf_jit_supports_arena_args()) {
13791 			verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n",
13792 				meta->func_name);
13793 			return -ENOTSUPP;
13794 		}
13795 		if (!env->prog->aux->arena) {
13796 			verbose(env,
13797 				"%s arena pointer requires a program with an associated arena\n",
13798 				reg_arg_name(env, argno));
13799 			return -EINVAL;
13800 		}
13801 		if (reg_from_argno(argno) < 0) {
13802 			verbose(env, "%s arena pointer cannot be a stack argument\n",
13803 				reg_arg_name(env, argno));
13804 			return -EINVAL;
13805 		}
13806 		/*
13807 		 * Both suffixes accept a constant zero. The function model determines
13808 		 * whether the JIT rebases it to the arena base or preserves NULL.
13809 		 * The common nullable path below records that verifier property.
13810 		 */
13811 		arg_type = ARG_PTR_TO_ARENA;
13812 	} else if (arg + 1 < nargs &&
13813 		 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) ||
13814 		  is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) {
13815 		if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) &&
13816 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
13817 			verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n",
13818 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
13819 			return -EINVAL;
13820 		}
13821 		arg_type = ARG_PTR_TO_MEM | MEM_WRITE;
13822 	} else if (btf_type_is_struct(ref_t))
13823 		/* A pointer to a struct without a size argument is classified as ARG_PTR_TO_BTF_ID */
13824 		arg_type = ARG_PTR_TO_BTF_ID;
13825 	else {
13826 		/*
13827 		 * Otherwise this is a fixed-size memory buffer supported by
13828 		 * check_helper_mem_access(): a pointer to a scalar or a struct of
13829 		 * scalars. The access size is derived from the pointed-to BTF type.
13830 		 */
13831 		if (!btf_type_is_scalar(ref_t) &&
13832 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
13833 			verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n",
13834 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
13835 			return -EINVAL;
13836 		}
13837 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
13838 		if (IS_ERR(resolve_ret)) {
13839 			verbose(env,
13840 				"%s reference type('%s %s') size cannot be determined: %ld\n",
13841 				reg_arg_name(env, argno), btf_type_str(ref_t),
13842 				ref_tname, PTR_ERR(resolve_ret));
13843 			return -EINVAL;
13844 		}
13845 		proto->arg_size[arg] = type_size;
13846 		arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE;
13847 	}
13848 
13849 	if (is_kfunc_arg_uninit(meta->btf, &args[arg]))
13850 		arg_type |= MEM_UNINIT;
13851 
13852 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]))
13853 		arg_type |= PTR_MAYBE_NULL;
13854 
13855 	/*
13856 	 * Only the first argument of a KF_RELEASE kfunc releases anything, and
13857 	 * bpf_fetch_kfunc_arg_meta() only ever records BPF_REG_1 for it.
13858 	 */
13859 	if (is_kfunc_release(meta) && arg == 0)
13860 		arg_type |= OBJ_RELEASE;
13861 
13862 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
13863 		if (is_kfunc_arg_map(meta->btf, &args[arg]))
13864 			proto->arg_btf_id[arg] = reg2btf_ids[CONST_PTR_TO_MAP];
13865 		else
13866 			proto->arg_btf_id[arg] = ref_id_ptr;
13867 
13868 		/*
13869 		 * A KF_RCU kfunc accepts an RCU-protected pointer where it would
13870 		 * otherwise demand a referenced or trusted one. Other argument kinds
13871 		 * have their own provenance requirements and must not inherit MEM_RCU.
13872 		 */
13873 		if (is_kfunc_rcu(meta))
13874 			arg_type |= MEM_RCU;
13875 	}
13876 
13877 	return arg_type;
13878 }
13879 
13880 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
13881 			       const struct btf_func_model *fm, struct bpf_func_proto *proto)
13882 {
13883 	const struct bpf_jit_arg_abi *abi;
13884 	const struct btf *btf = meta->btf;
13885 	const struct btf_param *args;
13886 	const struct btf_type *t;
13887 	u32 i, nargs, slots_used;
13888 	int arg_type;
13889 
13890 	args = (const struct btf_param *)(meta->func_proto + 1);
13891 	nargs = btf_type_vlen(meta->func_proto);
13892 	if (nargs > MAX_BPF_FUNC_ARGS) {
13893 		verbose(env, "Function %s has %d > %d args\n", meta->func_name,
13894 			nargs, MAX_BPF_FUNC_ARGS);
13895 		return -EINVAL;
13896 	}
13897 
13898 	for (i = 0, slots_used = 0; i < nargs; i++) {
13899 		u32 nslots = btf_func_model_arg_slots(fm, i);
13900 
13901 		if (nslots > 1) {
13902 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13903 			if (!btf_func_arg_align(btf, t)) {
13904 				verbose(env,
13905 					"Function %s arg#%d type %s nests structs more than "
13906 					"%d levels deep\n",
13907 					meta->func_name, i, btf_type_str(t),
13908 					BTF_MEMBER_MAX_DEPTH);
13909 				return -EINVAL;
13910 			}
13911 		}
13912 		slots_used += nslots;
13913 	}
13914 
13915 	if (slots_used > MAX_BPF_FUNC_ARGS) {
13916 		verbose(env, "Function %s needs %d > %d argument slots\n", meta->func_name,
13917 			slots_used, MAX_BPF_FUNC_ARGS);
13918 		return -EINVAL;
13919 	}
13920 
13921 	abi = bpf_jit_arg_abi();
13922 
13923 	for (i = 0, slots_used = 0; i < nargs; i++) {
13924 		u32 nslots = btf_func_model_arg_slots(fm, i);
13925 
13926 		if (!abi && nslots > 1) {
13927 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13928 			verbose(env,
13929 				"Function %s arg#%d type %s cannot be passed at "
13930 				"argument slot %d on this architecture\n",
13931 				meta->func_name, i, btf_type_str(t), slots_used);
13932 			return -EINVAL;
13933 		}
13934 		slots_used += nslots;
13935 
13936 		arg_type = get_kfunc_arg_type(env, meta, args, i, nargs,
13937 					      slots_used - nslots, proto);
13938 		if (arg_type < 0)
13939 			return arg_type;
13940 
13941 		proto->arg_type[i] = arg_type;
13942 	}
13943 
13944 	if (slots_used > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
13945 		verbose(env, "JIT does not support kfunc %s() with %d argument slots\n",
13946 			meta->func_name, slots_used);
13947 		return -ENOTSUPP;
13948 	}
13949 
13950 	return check_arg_prog_aux(env, proto) ? 0 : -EINVAL;
13951 }
13952 
13953 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
13954 				     argno_t argno, enum bpf_arg_type arg_type,
13955 				     const struct btf *arg_btf, u32 arg_btf_id,
13956 				     struct bpf_call_arg_meta *meta, int insn_idx)
13957 {
13958 	bool taking_projection, struct_same, strict_type_match = false;
13959 	const struct btf_type *arg_t, *reg_t;
13960 	const char *arg_tname, *reg_tname;
13961 	const struct btf *reg_btf;
13962 	u32 reg_btf_id;
13963 
13964 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
13965 		reg_btf = reg->btf;
13966 		reg_btf_id = reg->btf_id;
13967 	} else {
13968 		reg_btf = btf_vmlinux;
13969 		reg_btf_id = *reg2btf_ids[base_type(reg->type)];
13970 	}
13971 
13972 	/*
13973 	 * Enforce strict type matching for arguments that release a reference,
13974 	 * or are no-cast aliases. We do _not_ enforce strict matching by default,
13975 	 * as we want to enable BPF programs to pass types that are bitwise
13976 	 * equivalent without forcing them to explicitly cast with something
13977 	 * like bpf_cast_to_kern_ctx().
13978 	 *
13979 	 * For example, say we had a type like the following:
13980 	 *
13981 	 * struct bpf_cpumask {
13982 	 *	cpumask_t cpumask;
13983 	 *	refcount_t usage;
13984 	 * };
13985 	 *
13986 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
13987 	 * to a struct cpumask, so it would be safe to pass a struct
13988 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
13989 	 *
13990 	 * The philosophy here is similar to how we allow scalars of different
13991 	 * types to be passed to kfuncs as long as the size is the same. The
13992 	 * only difference here is that we're simply allowing
13993 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
13994 	 * resolve types.
13995 	 */
13996 	if ((arg_type_is_release(arg_type) && !is_helper_call(meta, BPF_FUNC_sk_release)) ||
13997 	    (is_kfunc(meta) && btf_type_ids_nocast_alias(&env->log, reg_btf, reg_btf_id,
13998 						    arg_btf, arg_btf_id)))
13999 		strict_type_match = true;
14000 
14001 	arg_t = btf_type_skip_modifiers(arg_btf, arg_btf_id, &arg_btf_id);
14002 	arg_tname = btf_name_by_offset(arg_btf, arg_t->name_off);
14003 	reg_t = btf_type_skip_modifiers(reg_btf, reg_btf_id, &reg_btf_id);
14004 	reg_tname = btf_name_by_offset(reg_btf, reg_t->name_off);
14005 
14006 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_btf_id,
14007 					  reg->var_off.value, arg_btf, arg_btf_id,
14008 					  strict_type_match, !type_is_alloc(reg->type));
14009 
14010 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
14011 	 * actually use it -- it must cast to the underlying type. So we allow
14012 	 * caller to pass in the underlying type.
14013 	 */
14014 	taking_projection = is_kfunc(meta) && btf_is_projection_of(arg_tname, reg_tname);
14015 	if (!taking_projection && !struct_same) {
14016 		verbose(env, "%s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
14017 			meta->func_name, reg_arg_name(env, argno),
14018 			btf_type_str(arg_t), arg_tname,
14019 			reg_arg_name(env, argno), btf_type_str(reg_t), reg_tname);
14020 		return -EINVAL;
14021 	}
14022 	return 0;
14023 }
14024 
14025 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
14026 			     struct bpf_call_arg_meta *meta)
14027 {
14028 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
14029 	bool irq_save;
14030 
14031 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_save]) ||
14032 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
14033 		irq_save = true;
14034 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14035 			kfunc_class = IRQ_LOCK_KFUNC;
14036 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_restore]) ||
14037 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) {
14038 		irq_save = false;
14039 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14040 			kfunc_class = IRQ_LOCK_KFUNC;
14041 	} else {
14042 		verifier_bug(env, "unknown irq flags kfunc");
14043 		return -EFAULT;
14044 	}
14045 
14046 	if (irq_save) {
14047 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
14048 			verbose(env, "expected uninitialized irq flag as %s\n",
14049 				reg_arg_name(env, argno));
14050 			bpf_diag_res(env, env->insn_idx, "IRQ flag is already initialized",
14051 				     "Saving IRQ state requires an uninitialized stack slot for "
14052 				     "the IRQ flag, but this slot already contains tracked IRQ "
14053 				     "flag state.",
14054 				     "Use a fresh stack slot for this save operation, or restore "
14055 				     "the existing IRQ flag before reusing the slot.");
14056 			return -EINVAL;
14057 		}
14058 
14059 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
14060 				       BPF_WRITE, -1, false, false);
14061 		if (err)
14062 			return err;
14063 
14064 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
14065 		if (err)
14066 			return err;
14067 	} else {
14068 		err = is_irq_flag_reg_valid_init(env, reg);
14069 		if (err) {
14070 			verbose(env, "expected an initialized irq flag as %s\n",
14071 				reg_arg_name(env, argno));
14072 			bpf_diag_res(env, env->insn_idx, "uninitialized IRQ flag restore",
14073 				     "Restoring IRQ state requires a stack slot that was "
14074 				     "initialized by a matching IRQ save operation on this path.",
14075 				     "Pass the same stack slot that was previously initialized by "
14076 				     "the matching IRQ save kfunc.");
14077 			return err;
14078 		}
14079 
14080 		spi = irq_flag_get_spi(env, reg);
14081 		if (spi < 0)
14082 			return spi;
14083 
14084 		mark_stack_slots_scratched(env, spi, 1);
14085 
14086 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
14087 		if (err)
14088 			return err;
14089 
14090 		if (!in_rcu_cs(env))
14091 			invalidate_rcu_protected_refs(env);
14092 	}
14093 	return 0;
14094 }
14095 
14096 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14097 {
14098 	struct btf_record *rec = reg_btf_record(reg);
14099 
14100 	if (!env->cur_state->active_locks) {
14101 		verifier_bug(env, "%s w/o active lock", __func__);
14102 		return -EFAULT;
14103 	}
14104 
14105 	if (type_flag(reg->type) & NON_OWN_REF) {
14106 		verifier_bug(env, "NON_OWN_REF already set");
14107 		return -EFAULT;
14108 	}
14109 
14110 	reg->type |= NON_OWN_REF;
14111 	if (rec->refcount_off >= 0)
14112 		reg->type |= MEM_RCU;
14113 
14114 	return 0;
14115 }
14116 
14117 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
14118 {
14119 	struct bpf_func_state *unused;
14120 	struct bpf_reg_state *reg;
14121 	int err;
14122 
14123 	err = release_reference_nomark(env, id);
14124 	WARN_ON_ONCE(err);
14125 
14126 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
14127 		if (reg->id == id) {
14128 			reg->id = 0;
14129 			ref_set_non_owning(env, reg);
14130 		}
14131 	}));
14132 
14133 	return;
14134 }
14135 
14136 /* Implementation details:
14137  *
14138  * Each register points to some region of memory, which we define as an
14139  * allocation. Each allocation may embed a bpf_spin_lock which protects any
14140  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
14141  * allocation. The lock and the data it protects are colocated in the same
14142  * memory region.
14143  *
14144  * Hence, everytime a register holds a pointer value pointing to such
14145  * allocation, the verifier preserves a unique reg->id for it.
14146  *
14147  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
14148  * bpf_spin_lock is called.
14149  *
14150  * To enable this, lock state in the verifier captures two values:
14151  *	active_lock.ptr = Register's type specific pointer
14152  *	active_lock.id  = A unique ID for each register pointer value
14153  *
14154  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
14155  * supported register types.
14156  *
14157  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
14158  * allocated objects is the reg->btf pointer.
14159  *
14160  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
14161  * can establish the provenance of the map value statically for each distinct
14162  * lookup into such maps. They always contain a single map value hence unique
14163  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
14164  *
14165  * So, in case of global variables, they use array maps with max_entries = 1,
14166  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
14167  * into the same map value as max_entries is 1, as described above).
14168  *
14169  * In case of inner map lookups, the inner map pointer has same map_ptr as the
14170  * outer map pointer (in verifier context), but each lookup into an inner map
14171  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
14172  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
14173  * will get different reg->id assigned to each lookup, hence different
14174  * active_lock.id.
14175  *
14176  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
14177  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
14178  * returned from bpf_obj_new. Each allocation receives a new reg->id.
14179  */
14180 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14181 {
14182 	struct bpf_reference_state *s;
14183 	void *ptr;
14184 	u32 id;
14185 
14186 	switch ((int)reg->type) {
14187 	case PTR_TO_MAP_VALUE:
14188 		ptr = reg->map_ptr;
14189 		break;
14190 	case PTR_TO_BTF_ID | MEM_ALLOC:
14191 		ptr = reg->btf;
14192 		break;
14193 	default:
14194 		verifier_bug(env, "unknown reg type for lock check");
14195 		return -EFAULT;
14196 	}
14197 	id = reg->id;
14198 
14199 	if (!env->cur_state->active_locks)
14200 		return -EINVAL;
14201 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
14202 	if (!s) {
14203 		verbose(env, "held lock and object are not in the same allocation\n");
14204 		return -EINVAL;
14205 	}
14206 	return 0;
14207 }
14208 
14209 static bool is_bpf_list_api_kfunc(u32 btf_id)
14210 {
14211 	return is_bpf_list_push_kfunc(btf_id) ||
14212 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
14213 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
14214 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
14215 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
14216 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
14217 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14218 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
14219 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
14220 }
14221 
14222 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
14223 {
14224 	return is_bpf_rbtree_add_kfunc(btf_id) ||
14225 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14226 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
14227 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
14228 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14229 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
14230 }
14231 
14232 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta)
14233 {
14234 	int flags = PROCESS_RES_LOCK;
14235 
14236 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock]) ||
14237 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14238 		flags |= PROCESS_SPIN_LOCK;
14239 	else if (!is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock]) &&
14240 		 !is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14241 		return 0;
14242 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) ||
14243 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14244 		flags |= PROCESS_LOCK_IRQ;
14245 	return flags;
14246 }
14247 
14248 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset)
14249 {
14250 	struct bpf_kfunc_meta kfunc;
14251 	int err;
14252 
14253 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
14254 	if (err || !kfunc.flags)
14255 		return false;
14256 
14257 	return *kfunc.flags & KF_SPINLOCK_SAFE;
14258 }
14259 
14260 /*
14261  * True if insn calls a helper/kfunc that requires one of its arguments to
14262  * be a stack pointer with a constant offset.
14263  */
14264 bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
14265 {
14266 	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
14267 	const struct bpf_func_proto *fn;
14268 	struct bpf_kfunc_desc *desc;
14269 	u32 *flags, btf_id;
14270 	int i;
14271 
14272 	if (bpf_helper_call(insn)) {
14273 		if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
14274 			return false;
14275 	} else if (bpf_pseudo_kfunc_call(insn)) {
14276 		desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14277 		if (!desc)
14278 			return false;
14279 		fn = &desc->proto;
14280 	} else {
14281 		return false;
14282 	}
14283 
14284 	/* Both initialized and uninitialized stack dynptrs need a fixed offset. */
14285 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
14286 		if (arg_type_is_dynptr(fn->arg_type[i]))
14287 			return true;
14288 
14289 	/* vmlinux kfuncs only */
14290 	if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
14291 		return false;
14292 	btf_id = insn->imm;
14293 
14294 	flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
14295 	if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
14296 		return true;
14297 
14298 	if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14299 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
14300 	    btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
14301 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
14302 	    btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
14303 	    btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
14304 		return true;
14305 
14306 	return false;
14307 }
14308 
14309 static bool is_sync_callback_calling_kfunc(u32 btf_id)
14310 {
14311 	return is_bpf_rbtree_add_kfunc(btf_id);
14312 }
14313 
14314 static bool is_async_callback_calling_kfunc(u32 btf_id)
14315 {
14316 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
14317 	       is_task_work_add_kfunc(btf_id) ||
14318 	       is_call_rcu_kfunc(btf_id);
14319 }
14320 
14321 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
14322 {
14323 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
14324 	       insn->imm == special_kfunc_list[KF_bpf_throw];
14325 }
14326 
14327 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
14328 {
14329 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
14330 }
14331 
14332 static bool is_callback_calling_kfunc(u32 btf_id)
14333 {
14334 	return is_sync_callback_calling_kfunc(btf_id) ||
14335 	       is_async_callback_calling_kfunc(btf_id);
14336 }
14337 
14338 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
14339 {
14340 	return is_bpf_rbtree_api_kfunc(btf_id);
14341 }
14342 
14343 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
14344 					  enum btf_field_type head_field_type,
14345 					  u32 kfunc_btf_id)
14346 {
14347 	bool ret;
14348 
14349 	switch (head_field_type) {
14350 	case BPF_LIST_HEAD:
14351 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
14352 		break;
14353 	case BPF_RB_ROOT:
14354 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
14355 		break;
14356 	default:
14357 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
14358 			btf_field_type_name(head_field_type));
14359 		return false;
14360 	}
14361 
14362 	if (!ret)
14363 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
14364 			btf_field_type_name(head_field_type));
14365 	return ret;
14366 }
14367 
14368 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
14369 					  enum btf_field_type node_field_type,
14370 					  u32 kfunc_btf_id)
14371 {
14372 	bool ret;
14373 
14374 	switch (node_field_type) {
14375 	case BPF_LIST_NODE:
14376 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
14377 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
14378 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14379 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
14380 		break;
14381 	case BPF_RB_NODE:
14382 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
14383 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14384 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14385 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
14386 		break;
14387 	default:
14388 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
14389 			btf_field_type_name(node_field_type));
14390 		return false;
14391 	}
14392 
14393 	if (!ret)
14394 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
14395 			btf_field_type_name(node_field_type));
14396 	return ret;
14397 }
14398 
14399 static int
14400 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
14401 				   struct bpf_reg_state *reg, argno_t argno,
14402 				   struct bpf_call_arg_meta *meta,
14403 				   enum btf_field_type head_field_type,
14404 				   struct btf_field **head_field)
14405 {
14406 	const char *head_type_name;
14407 	struct btf_field *field;
14408 	struct btf_record *rec;
14409 	u32 head_off;
14410 
14411 	if (meta->btf != btf_vmlinux) {
14412 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14413 		return -EFAULT;
14414 	}
14415 
14416 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
14417 		return -EFAULT;
14418 
14419 	head_type_name = btf_field_type_name(head_field_type);
14420 	if (!tnum_is_const(reg->var_off)) {
14421 		verbose(env,
14422 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14423 			reg_arg_name(env, argno), head_type_name);
14424 		return -EINVAL;
14425 	}
14426 
14427 	rec = reg_btf_record(reg);
14428 	head_off = reg->var_off.value;
14429 	field = btf_record_find(rec, head_off, head_field_type);
14430 	if (!field) {
14431 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
14432 		return -EINVAL;
14433 	}
14434 
14435 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
14436 	if (check_reg_allocation_locked(env, reg)) {
14437 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
14438 			rec->spin_lock_off, head_type_name);
14439 		return -EINVAL;
14440 	}
14441 
14442 	if (*head_field) {
14443 		verifier_bug(env, "repeating %s arg", head_type_name);
14444 		return -EFAULT;
14445 	}
14446 	*head_field = field;
14447 	return 0;
14448 }
14449 
14450 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
14451 					   struct bpf_reg_state *reg, argno_t argno,
14452 					   struct bpf_call_arg_meta *meta)
14453 {
14454 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
14455 							  &meta->arg_list_head.field);
14456 }
14457 
14458 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
14459 					     struct bpf_reg_state *reg, argno_t argno,
14460 					     struct bpf_call_arg_meta *meta)
14461 {
14462 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
14463 							  &meta->arg_rbtree_root.field);
14464 }
14465 
14466 static int
14467 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
14468 				   struct bpf_reg_state *reg, argno_t argno,
14469 				   struct bpf_call_arg_meta *meta,
14470 				   enum btf_field_type head_field_type,
14471 				   enum btf_field_type node_field_type,
14472 				   struct btf_field **node_field)
14473 {
14474 	const char *node_type_name;
14475 	const struct btf_type *et, *t;
14476 	struct btf_field *field;
14477 	u32 node_off;
14478 
14479 	if (meta->btf != btf_vmlinux) {
14480 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14481 		return -EFAULT;
14482 	}
14483 
14484 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
14485 		return -EFAULT;
14486 
14487 	node_type_name = btf_field_type_name(node_field_type);
14488 	if (!tnum_is_const(reg->var_off)) {
14489 		verbose(env,
14490 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14491 			reg_arg_name(env, argno), node_type_name);
14492 		return -EINVAL;
14493 	}
14494 
14495 	node_off = reg->var_off.value;
14496 	field = reg_find_field_offset(reg, node_off, node_field_type);
14497 	if (!field) {
14498 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
14499 		return -EINVAL;
14500 	}
14501 
14502 	field = *node_field;
14503 
14504 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
14505 	t = btf_type_by_id(reg->btf, reg->btf_id);
14506 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
14507 				  field->graph_root.value_btf_id, true,
14508 				  !type_is_alloc(reg->type))) {
14509 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
14510 			"in struct %s, but arg is at offset=%d in struct %s\n",
14511 			btf_field_type_name(head_field_type),
14512 			btf_field_type_name(node_field_type),
14513 			field->graph_root.node_offset,
14514 			btf_name_by_offset(field->graph_root.btf, et->name_off),
14515 			node_off, btf_name_by_offset(reg->btf, t->name_off));
14516 		return -EINVAL;
14517 	}
14518 	meta->arg_btf = reg->btf;
14519 	meta->arg_btf_id = reg->btf_id;
14520 
14521 	if (node_off != field->graph_root.node_offset) {
14522 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
14523 			node_off, btf_field_type_name(node_field_type),
14524 			field->graph_root.node_offset,
14525 			btf_name_by_offset(field->graph_root.btf, et->name_off));
14526 		return -EINVAL;
14527 	}
14528 
14529 	return 0;
14530 }
14531 
14532 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
14533 					   struct bpf_reg_state *reg, argno_t argno,
14534 					   struct bpf_call_arg_meta *meta)
14535 {
14536 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14537 						  BPF_LIST_HEAD, BPF_LIST_NODE,
14538 						  &meta->arg_list_head.field);
14539 }
14540 
14541 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
14542 					     struct bpf_reg_state *reg, argno_t argno,
14543 					     struct bpf_call_arg_meta *meta)
14544 {
14545 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14546 						  BPF_RB_ROOT, BPF_RB_NODE,
14547 						  &meta->arg_rbtree_root.field);
14548 }
14549 
14550 /*
14551  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
14552  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
14553  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
14554  * them can only be attached to some specific hook points.
14555  */
14556 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
14557 {
14558 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14559 
14560 	switch (prog_type) {
14561 	case BPF_PROG_TYPE_LSM:
14562 		return true;
14563 	case BPF_PROG_TYPE_TRACING:
14564 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
14565 			return true;
14566 		fallthrough;
14567 	default:
14568 		return in_sleepable(env);
14569 	}
14570 }
14571 
14572 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
14573 			     s32 func_id,
14574 			     s16 offset,
14575 			     struct bpf_call_arg_meta *meta)
14576 {
14577 	struct bpf_kfunc_meta kfunc;
14578 	int err;
14579 
14580 	memset(meta, 0, sizeof(*meta));
14581 
14582 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
14583 	if (err)
14584 		return err;
14585 
14586 	meta->btf = kfunc.btf;
14587 	meta->func_id = kfunc.id;
14588 	meta->func_proto = kfunc.proto;
14589 	meta->func_name = kfunc.name;
14590 
14591 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
14592 		return -EACCES;
14593 
14594 	meta->kfunc_flags = *kfunc.flags;
14595 
14596 	/* Only support release referenced argument passed by register */
14597 	if (is_kfunc_release(meta))
14598 		meta->release_regno = BPF_REG_1;
14599 
14600 	return 0;
14601 }
14602 
14603 /*
14604  * Describe a helper's stack access through argument @arg (0-based, R1-R5).
14605  * must_write means the verifier destroys prior state throughout size bytes.
14606  * In other words, must_write follows the verifier's model of the
14607  * function's behaviour, which is safe to use for is_state_visited() pruning.
14608  */
14609 struct arg_access_info
14610 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
14611 			      int arg, int insn_idx)
14612 {
14613 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
14614 	struct arg_access_info info = {
14615 		.size = U32_MAX,
14616 		.may_read = true,
14617 		.may_write = true,
14618 	};
14619 	const struct bpf_func_proto *fn;
14620 	enum bpf_access_type access_type;
14621 	enum bpf_arg_type at;
14622 	bool exact_size = true;
14623 	u64 size = U32_MAX;
14624 
14625 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
14626 		return info;
14627 
14628 	at = fn->arg_type[arg];
14629 	access_type = func_arg_access_type(at);
14630 
14631 	switch (base_type(at)) {
14632 	case ARG_PTR_TO_MAP_KEY:
14633 	case ARG_PTR_TO_MAP_VALUE: {
14634 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
14635 		u64 val;
14636 		int i, map_reg;
14637 
14638 		for (i = 0; i < arg; i++) {
14639 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
14640 				break;
14641 		}
14642 		if (i >= arg)
14643 			goto scan_all_maps;
14644 
14645 		map_reg = BPF_REG_1 + i;
14646 
14647 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
14648 			goto scan_all_maps;
14649 
14650 		i = aux->const_reg_vals[map_reg];
14651 		if (i < env->used_map_cnt) {
14652 			/* Bloom-filter peek reads the value buffer. */
14653 			if (!is_key && insn->imm == BPF_FUNC_map_peek_elem &&
14654 			    env->used_maps[i]->map_type == BPF_MAP_TYPE_BLOOM_FILTER)
14655 				access_type = BPF_READ;
14656 			size = is_key ? env->used_maps[i]->key_size
14657 				      : env->used_maps[i]->value_size;
14658 			goto out;
14659 		}
14660 scan_all_maps:
14661 		/*
14662 		 * Map pointer is not known at this call site (e.g. different
14663 		 * maps on merged paths).  Conservatively return the largest
14664 		 * key_size or value_size across all maps used by the program.
14665 		 * This is only an upper bound, so it cannot establish a definite
14666 		 * write. Map-dependent argument types can also turn an output
14667 		 * into an input, so conservatively retain a read dependency.
14668 		 */
14669 		exact_size = false;
14670 		access_type |= BPF_READ;
14671 		val = 0;
14672 		for (i = 0; i < env->used_map_cnt; i++) {
14673 			struct bpf_map *map = env->used_maps[i];
14674 			u32 sz = is_key ? map->key_size : map->value_size;
14675 
14676 			if (sz > val)
14677 				val = sz;
14678 			if (map->inner_map_meta) {
14679 				sz = is_key ? map->inner_map_meta->key_size
14680 					    : map->inner_map_meta->value_size;
14681 				if (sz > val)
14682 					val = sz;
14683 			}
14684 		}
14685 		if (!val)
14686 			return info;
14687 		size = val;
14688 		goto out;
14689 	}
14690 	case ARG_PTR_TO_MEM:
14691 		if (at & MEM_FIXED_SIZE) {
14692 			size = fn->arg_size[arg];
14693 			goto out;
14694 		}
14695 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
14696 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
14697 			int size_reg = BPF_REG_1 + arg + 1;
14698 
14699 			if (aux->const_reg_mask & BIT(size_reg)) {
14700 				size = aux->const_reg_vals[size_reg];
14701 				goto out;
14702 			}
14703 		}
14704 		/* Preserve access directions even when the extent is unknown. */
14705 		goto out;
14706 	case ARG_PTR_TO_DYNPTR:
14707 		size = BPF_DYNPTR_SIZE;
14708 		break;
14709 	case ARG_PTR_TO_STACK:
14710 		/*
14711 		 * Only used by bpf_calls_callback() helpers. The helper itself
14712 		 * doesn't access stack. The callback subprog does and it's
14713 		 * analyzed separately.
14714 		 */
14715 		return (struct arg_access_info) {};
14716 	default:
14717 		return info;
14718 	}
14719 out:
14720 	info.size = min_t(u64, size, U32_MAX);
14721 	info.may_read = !!(access_type & BPF_READ);
14722 	info.may_write = !!(access_type & BPF_WRITE);
14723 	info.must_write = info.may_write && exact_size && info.size != U32_MAX;
14724 	/* Generic unprivileged outputs retain prior initialization state. */
14725 	if (!env->allow_uninit_stack && arg_type_is_raw_mem(at)) {
14726 		info.may_read = true;
14727 		info.must_write = false;
14728 	}
14729 	return info;
14730 }
14731 
14732 /*
14733  * Describe a kfunc's stack access through argument slot @arg (0-based).
14734  * As for helpers, must_write describes destruction of prior verifier state,
14735  * rather than a guarantee that the callee writes every byte at runtime.
14736  */
14737 struct arg_access_info
14738 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
14739 			     int arg, int insn_idx)
14740 {
14741 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
14742 	struct arg_access_info info = {
14743 		.size = U32_MAX,
14744 		.may_read = true,
14745 		.may_write = true,
14746 	};
14747 	struct bpf_call_arg_meta meta;
14748 	const struct btf_param *args;
14749 	const struct btf_type *t, *ref_t;
14750 	const struct btf *btf;
14751 	u32 i, slot, nargs, type_size;
14752 	u64 size;
14753 
14754 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
14755 		return info;
14756 
14757 	btf = meta.btf;
14758 	args = btf_params(meta.func_proto);
14759 	nargs = btf_type_vlen(meta.func_proto);
14760 
14761 	/*
14762 	 * @arg is an argument slot and a 16-byte parameter takes two of them,
14763 	 * so walk the parameters to find the one that starts at this slot. A
14764 	 * slot holding the upper eightbyte of such a parameter belongs to no
14765 	 * pointer, and neither does a slot past the last parameter.
14766 	 */
14767 	for (i = 0, slot = 0; i < nargs && slot < arg; i++)
14768 		slot += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
14769 	if (i >= nargs || slot != arg)
14770 		return (struct arg_access_info) {};
14771 
14772 	t = btf_type_skip_modifiers(btf, args[i].type, NULL);
14773 	if (!btf_type_is_ptr(t))
14774 		return (struct arg_access_info) {};
14775 
14776 	/* dynptr: fixed 16-byte on-stack representation */
14777 	if (is_kfunc_arg_dynptr(btf, &args[i])) {
14778 		size = BPF_DYNPTR_SIZE;
14779 		goto out;
14780 	}
14781 
14782 	/* ptr + __sz/__szk pair: the size follows the pointer */
14783 	if (i + 1 < nargs &&
14784 	    (btf_param_match_suffix(btf, &args[i + 1], "__sz") ||
14785 	     btf_param_match_suffix(btf, &args[i + 1], "__szk"))) {
14786 		int size_reg = BPF_REG_1 + arg + 1;
14787 
14788 		if (size_reg <= MAX_BPF_FUNC_REG_ARGS &&
14789 		    (aux->const_reg_mask & BIT(size_reg))) {
14790 			size = aux->const_reg_vals[size_reg];
14791 			goto out;
14792 		}
14793 		/* Unknown size: the read may extend anywhere up to the frame top. */
14794 		return info;
14795 	}
14796 
14797 	/* fixed-size pointed-to type: resolve via BTF */
14798 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
14799 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
14800 		size = type_size;
14801 		goto out;
14802 	}
14803 
14804 	return info;
14805 out:
14806 	info.size = min_t(u64, size, U32_MAX);
14807 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
14808 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
14809 		info.may_read = false;
14810 	if (is_kfunc_arg_uninit(btf, &args[i]) &&
14811 	    (is_kfunc_arg_dynptr(btf, &args[i]) || env->allow_uninit_stack))
14812 		info.may_read = false;
14813 	info.must_write = !info.may_read && info.size != U32_MAX;
14814 	return info;
14815 }
14816 
14817 /*
14818  * Called before dead code elimination, some subprograms may be genuinely unreachable.
14819  * Suppress diagnostics so callers can use a conservative result on error.
14820  * The main pass would report errors for reachable subprograms.
14821  */
14822 static bool try_btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
14823 {
14824 	struct bpf_prog *prog = env->prog;
14825 	u32 log_level = env->log.level;
14826 	int err;
14827 
14828 	if (!prog->aux->func_info || !prog->aux->func_info[subprog].type_id)
14829 		return false;
14830 
14831 	env->log.level = 0;
14832 	err = btf_prepare_func_args(env, subprog);
14833 	env->log.level = log_level;
14834 	return !err;
14835 }
14836 
14837 /* Prepare argument metadata for liveness; the main program is handled separately. */
14838 static void prepare_subprog_args(struct bpf_verifier_env *env)
14839 {
14840 	int i;
14841 
14842 	for (i = 1; i < env->subprog_cnt; i++) {
14843 		if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i))
14844 			/* Keep all argument registers live if the prototype is unavailable. */
14845 			env->subprog_info[i].arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
14846 	}
14847 }
14848 
14849 /*
14850  * Derive stack effects for a global subprog's argument slot @arg (0-based)
14851  * from its declared type, matching the main pass's argument checks.
14852  */
14853 struct arg_access_info
14854 bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
14855 				      int arg, int insn_idx)
14856 {
14857 	struct arg_access_info info = {
14858 		.size = U32_MAX,
14859 		.may_read = true,
14860 		.may_write = true,
14861 	};
14862 	struct bpf_subprog_info *sub;
14863 	int callee;
14864 
14865 	callee = bpf_find_subprog(env, insn_idx + insn->imm + 1);
14866 	if (callee < 0)
14867 		return info;
14868 	sub = subprog_info(env, callee);
14869 	if (!try_btf_prepare_func_args(env, callee))
14870 		return info;
14871 
14872 	switch (base_type(sub->args[arg].arg_type)) {
14873 	case ARG_UNUSED:	/* Not an argument slot. */
14874 	case ARG_ANYTHING:	/* A scalar, the callee can't dereference it. */
14875 		return (struct arg_access_info) {};
14876 	case ARG_PTR_TO_BTF_ID:
14877 		/*
14878 		 * Trusted arguments cannot be stack pointers.
14879 		 * Untrusted arguments use ARG_IGNORE:
14880 		 * probe reads need no caller stack state, writes are prohibited.
14881 		 */
14882 		return (struct arg_access_info) {};
14883 	case ARG_PTR_TO_MEM:
14884 		/* mem_size is zero for untrusted pointers of unknown size. */
14885 		if (sub->args[arg].mem_size) {
14886 			info.size = sub->args[arg].mem_size;
14887 			info.must_write = true;
14888 		}
14889 		return info;
14890 	default:
14891 		return info;
14892 	}
14893 }
14894 
14895 /* check special kfuncs and return:
14896  *  1  - not fall-through to 'else' branch, continue verification
14897  *  0  - fall-through to 'else' branch
14898  * < 0 - not fall-through to 'else' branch, return error
14899  */
14900 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
14901 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
14902 			       const struct btf_type *ptr_type, struct btf *desc_btf)
14903 {
14904 	const struct btf_type *ret_t;
14905 	int err = 0;
14906 
14907 	if (meta->btf != btf_vmlinux)
14908 		return 0;
14909 
14910 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
14911 		struct btf_struct_meta *struct_meta;
14912 		struct btf *ret_btf;
14913 		u32 ret_btf_id;
14914 
14915 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
14916 			return -ENOMEM;
14917 
14918 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
14919 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
14920 			return -EINVAL;
14921 		}
14922 
14923 		ret_btf = env->prog->aux->btf;
14924 		ret_btf_id = meta->arg_constant.value;
14925 
14926 		/* This may be NULL due to user not supplying a BTF */
14927 		if (!ret_btf) {
14928 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
14929 			return -EINVAL;
14930 		}
14931 
14932 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
14933 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
14934 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
14935 			return -EINVAL;
14936 		}
14937 
14938 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
14939 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
14940 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
14941 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
14942 				return -EINVAL;
14943 			}
14944 
14945 			if (!bpf_global_percpu_ma_set) {
14946 				mutex_lock(&bpf_percpu_ma_lock);
14947 				if (!bpf_global_percpu_ma_set) {
14948 					/* Charge memory allocated with bpf_global_percpu_ma to
14949 					 * root memcg. The obj_cgroup for root memcg is NULL.
14950 					 */
14951 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
14952 					if (!err)
14953 						bpf_global_percpu_ma_set = true;
14954 				}
14955 				mutex_unlock(&bpf_percpu_ma_lock);
14956 				if (err)
14957 					return err;
14958 			}
14959 
14960 			mutex_lock(&bpf_percpu_ma_lock);
14961 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
14962 			mutex_unlock(&bpf_percpu_ma_lock);
14963 			if (err)
14964 				return err;
14965 		}
14966 
14967 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
14968 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
14969 			if (!btf_type_is_scalar_struct(env, ret_btf, ret_t)) {
14970 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
14971 				return -EINVAL;
14972 			}
14973 
14974 			if (struct_meta) {
14975 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
14976 				return -EINVAL;
14977 			}
14978 		}
14979 
14980 		mark_reg_known_zero(env, regs, BPF_REG_0);
14981 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
14982 		regs[BPF_REG_0].btf = ret_btf;
14983 		regs[BPF_REG_0].btf_id = ret_btf_id;
14984 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
14985 			regs[BPF_REG_0].type |= MEM_PERCPU;
14986 
14987 		insn_aux->obj_new_size = ret_t->size;
14988 		insn_aux->kptr_struct_meta = struct_meta;
14989 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
14990 		mark_reg_known_zero(env, regs, BPF_REG_0);
14991 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
14992 		regs[BPF_REG_0].btf = meta->arg_btf;
14993 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
14994 
14995 		insn_aux->kptr_struct_meta =
14996 			btf_find_struct_meta(meta->arg_btf,
14997 					     meta->arg_btf_id);
14998 	} else if (is_list_node_type(ptr_type)) {
14999 		struct btf_field *field = meta->arg_list_head.field;
15000 
15001 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15002 	} else if (is_rbtree_node_type(ptr_type)) {
15003 		struct btf_field *field = meta->arg_rbtree_root.field;
15004 
15005 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15006 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx])) {
15007 		mark_reg_known_zero(env, regs, BPF_REG_0);
15008 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
15009 		regs[BPF_REG_0].btf = desc_btf;
15010 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
15011 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_rdonly_cast])) {
15012 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
15013 		if (!ret_t) {
15014 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
15015 				meta->arg_constant.value);
15016 			return -EINVAL;
15017 		} else if (btf_type_is_struct(ret_t)) {
15018 			mark_reg_known_zero(env, regs, BPF_REG_0);
15019 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15020 			regs[BPF_REG_0].btf = desc_btf;
15021 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
15022 		} else if (btf_type_is_void(ret_t)) {
15023 			mark_reg_known_zero(env, regs, BPF_REG_0);
15024 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
15025 			regs[BPF_REG_0].mem_size = 0;
15026 		} else {
15027 			verbose(env,
15028 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
15029 			return -EINVAL;
15030 		}
15031 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
15032 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice_rdwr])) {
15033 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
15034 
15035 		mark_reg_known_zero(env, regs, BPF_REG_0);
15036 
15037 		if (!meta->arg_constant.found) {
15038 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
15039 			return -EFAULT;
15040 		}
15041 
15042 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
15043 
15044 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
15045 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
15046 
15047 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice])) {
15048 			regs[BPF_REG_0].type |= MEM_RDONLY;
15049 		} else {
15050 			/* this will set env->seen_direct_write to true */
15051 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
15052 				verbose(env, "the prog does not allow writes to packet data\n");
15053 				return -EINVAL;
15054 			}
15055 		}
15056 
15057 		if (!meta->dynptr.id) {
15058 			verifier_bug(env, "no dynptr id");
15059 			return -EFAULT;
15060 		}
15061 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
15062 	} else {
15063 		return 0;
15064 	}
15065 
15066 	return 1;
15067 }
15068 
15069 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
15070 
15071 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15072 			    int *insn_idx_p)
15073 {
15074 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
15075 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15076 	struct bpf_reg_state *regs = cur_regs(env);
15077 	const char *func_name, *ptr_type_name;
15078 	const struct btf_type *t, *ptr_type;
15079 	struct bpf_call_arg_meta meta;
15080 	struct bpf_insn_aux_data *insn_aux;
15081 	const char *operation;
15082 	int err, insn_idx = *insn_idx_p;
15083 	u32 i, proto_slots, ptr_type_id, ret_nregs = 1;
15084 	struct bpf_kfunc_desc *desc;
15085 	struct btf *desc_btf;
15086 	int id;
15087 
15088 	/* skip for now, but return error when we find this in fixup_kfunc_call */
15089 	if (!insn->imm)
15090 		return 0;
15091 
15092 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
15093 	if (err == -EACCES && meta.func_name) {
15094 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
15095 		operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name);
15096 		bpf_diag_policy(
15097 			env, insn_idx, operation, "this program cannot call the kfunc",
15098 			"Use a kfunc allowed for this program type and attach point, or change the program context.");
15099 	}
15100 	if (err)
15101 		return err;
15102 	desc_btf = meta.btf;
15103 	func_name = meta.func_name;
15104 	insn_aux = &env->insn_aux_data[insn_idx];
15105 
15106 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15107 	if (!desc) {
15108 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
15109 		return -EFAULT;
15110 	}
15111 	meta.fn = &desc->proto;
15112 
15113 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
15114 
15115 	if (!insn->off &&
15116 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
15117 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
15118 		struct bpf_verifier_state *branch;
15119 		struct bpf_reg_state *regs;
15120 
15121 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15122 		if (IS_ERR(branch)) {
15123 			verbose(env, "failed to push state for failed lock acquisition\n");
15124 			return PTR_ERR(branch);
15125 		}
15126 
15127 		regs = branch->frame[branch->curframe]->regs;
15128 
15129 		/* Clear r0-r5 registers in forked state */
15130 		for (i = 0; i < CALLER_SAVED_REGS; i++)
15131 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
15132 
15133 		mark_reg_unknown(env, regs, BPF_REG_0);
15134 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
15135 		if (err) {
15136 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
15137 			return err;
15138 		}
15139 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
15140 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
15141 		return -EFAULT;
15142 	}
15143 
15144 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
15145 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
15146 		operation = bpf_diag_fmt(env, "destructive kfunc %s", meta.func_name);
15147 		bpf_diag_policy(
15148 			env, insn_idx, operation, "destructive kfuncs require CAP_SYS_BOOT",
15149 			"Load the program with CAP_SYS_BOOT, or avoid destructive kfuncs.");
15150 		return -EACCES;
15151 	}
15152 
15153 	if (is_kfunc_perfmon(&meta) && !env->allow_ptr_leaks) {
15154 		verbose(env, "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
15155 			func_name);
15156 		operation = bpf_diag_fmt(env, "kfunc %s", func_name);
15157 		bpf_diag_policy(env, insn_idx, operation, "the kfunc requires CAP_PERFMON",
15158 				"Load the program with CAP_PERFMON, or avoid the kfunc.");
15159 		return -EPERM;
15160 	}
15161 
15162 	sleepable = bpf_is_kfunc_sleepable(&meta);
15163 	if (sleepable && !in_sleepable_context(env)) {
15164 		const char *suggestion;
15165 
15166 		if (in_sleepable(env)) {
15167 			verbose(env, "kernel func %s is sleepable within %s\n",
15168 				func_name, non_sleepable_context_description(env));
15169 			suggestion = "Move the kfunc call outside the critical section, or use a non-sleepable kfunc.";
15170 		} else {
15171 			verbose(env, "program must be sleepable to call sleepable kfunc %s\n",
15172 				func_name);
15173 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc.";
15174 		}
15175 		operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name);
15176 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
15177 		return -EACCES;
15178 	}
15179 
15180 	/* Track non-sleepable context for kfuncs, same as for helpers. */
15181 	if (!in_sleepable_context(env))
15182 		insn_aux->non_sleepable = true;
15183 
15184 	/* Check the arguments */
15185 	err = check_func_args(env, &meta, insn_idx);
15186 	if (err < 0)
15187 		return err;
15188 
15189 	err = mark_raw_stack(env, &meta, insn_idx);
15190 	if (err)
15191 		return err;
15192 
15193 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
15194 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
15195 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
15196 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
15197 	      && !env->prog->sleepable))) {
15198 		struct btf_struct_meta *struct_meta;
15199 
15200 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15201 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
15202 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
15203 				func_name);
15204 			return -EINVAL;
15205 		}
15206 	}
15207 
15208 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
15209 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15210 					 set_rbtree_add_callback_state);
15211 		if (err) {
15212 			verbose(env, "kfunc %s#%d failed callback verification\n",
15213 				func_name, meta.func_id);
15214 			return err;
15215 		}
15216 	}
15217 
15218 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
15219 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15220 					 set_timer_callback_state);
15221 		if (err) {
15222 			verbose(env, "kfunc %s#%d failed callback verification\n",
15223 				func_name, meta.func_id);
15224 			return err;
15225 		}
15226 	}
15227 
15228 	if (is_task_work_add_kfunc(meta.func_id)) {
15229 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15230 					 set_task_work_schedule_callback_state);
15231 		if (err) {
15232 			verbose(env, "kfunc %s#%d failed callback verification\n",
15233 				func_name, meta.func_id);
15234 			return err;
15235 		}
15236 	}
15237 
15238 	if (is_call_rcu_kfunc(meta.func_id)) {
15239 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15240 					 set_rcu_callback_state);
15241 		if (err) {
15242 			verbose(env, "kfunc %s#%d failed callback verification\n",
15243 				func_name, meta.func_id);
15244 			return err;
15245 		}
15246 	}
15247 
15248 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
15249 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
15250 
15251 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
15252 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
15253 
15254 	if (rcu_lock) {
15255 		env->cur_state->active_rcu_locks++;
15256 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true,
15257 					env->cur_state->active_rcu_locks);
15258 	} else if (rcu_unlock) {
15259 		if (env->cur_state->active_rcu_locks == 0) {
15260 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
15261 			bpf_diag_ctx_underflow(
15262 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15263 				"Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region.");
15264 			return -EINVAL;
15265 		}
15266 		env->cur_state->active_rcu_locks--;
15267 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
15268 					env->cur_state->active_rcu_locks);
15269 		if (!in_rcu_cs(env))
15270 			invalidate_rcu_protected_refs(env);
15271 	} else if (preempt_disable) {
15272 		env->cur_state->active_preempt_locks++;
15273 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true,
15274 					env->cur_state->active_preempt_locks);
15275 	} else if (preempt_enable) {
15276 		if (env->cur_state->active_preempt_locks == 0) {
15277 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
15278 			bpf_diag_ctx_underflow(
15279 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_PREEMPT,
15280 				"Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption.");
15281 			return -EINVAL;
15282 		}
15283 		env->cur_state->active_preempt_locks--;
15284 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
15285 					env->cur_state->active_preempt_locks);
15286 		if (!in_rcu_cs(env))
15287 			invalidate_rcu_protected_refs(env);
15288 	}
15289 
15290 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
15291 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
15292 		return -EACCES;
15293 	}
15294 
15295 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
15296 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
15297 		bpf_diag_ctx_required(
15298 			env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15299 			"Call this kfunc between bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
15300 		return -EACCES;
15301 	}
15302 
15303 	/* In case of release function, we get register number of refcounted
15304 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
15305 	 */
15306 	if (meta.release_regno) {
15307 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
15308 		if (err)
15309 			return err;
15310 	}
15311 
15312 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
15313 		id = regs[BPF_REG_2].id;
15314 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
15315 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15316 		ref_convert_owning_non_owning(env, id);
15317 	}
15318 
15319 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
15320 		if (!bpf_jit_supports_exceptions()) {
15321 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
15322 				func_name, meta.func_id);
15323 			return -ENOTSUPP;
15324 		}
15325 		env->seen_exception = true;
15326 
15327 		/* In the case of the default callback, the cookie value passed
15328 		 * to bpf_throw becomes the return value of the program.
15329 		 */
15330 		if (!env->exception_callback_subprog) {
15331 			err = check_return_code(env, BPF_REG_1, "R1");
15332 			if (err < 0)
15333 				return err;
15334 		}
15335 	}
15336 
15337 	bpf_diag_record_caller_saved(env, regs);
15338 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
15339 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15340 		u32 regno = caller_saved[i];
15341 
15342 		bpf_mark_reg_not_init(env, &regs[regno]);
15343 	}
15344 	invalidate_outgoing_stack_args(env, cur_func(env));
15345 
15346 	/* Check return type */
15347 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
15348 
15349 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
15350 		if (meta.btf != btf_vmlinux ||
15351 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
15352 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
15353 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
15354 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
15355 			return -EINVAL;
15356 		}
15357 	}
15358 
15359 	if (btf_type_is_scalar(t)) {
15360 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15361 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
15362 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
15363 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
15364 	} else if (btf_type_is_struct(t)) {
15365 		struct btf_member_path path = {};
15366 		const char *member_note = "";
15367 
15368 		/*
15369 		 * The returned struct comes back as raw register bits modeled
15370 		 * as an unknown scalar, so a pointer member would be laundered
15371 		 * into a scalar and escape provenance and reference tracking.
15372 		 * Only scalars and arena pointers are allowed; see
15373 		 * btf_validate_return_type() in btf.c for why an arena pointer
15374 		 * is safe here.
15375 		 */
15376 		if (!btf_struct_member_walk(env, desc_btf, t,
15377 					    BTF_MEMBER_SCALAR | BTF_MEMBER_ARENA_PTR, 0, &path)) {
15378 			verbose(env,
15379 				"kernel function %s returns %s %s that is not composed of scalars or arena pointers\n",
15380 				func_name, btf_type_str(t),
15381 				btf_name_by_offset(desc_btf, t->name_off));
15382 			if (path.too_deep) {
15383 				member_note = bpf_diag_fmt(
15384 					env, " It nests structs more than %d levels deep.",
15385 					BTF_MEMBER_MAX_DEPTH);
15386 			} else if (path.depth) {
15387 				char bad_name[BTF_MEMBER_PATH_LEN];
15388 
15389 				btf_member_path_str(desc_btf, &path, bad_name, sizeof(bad_name));
15390 				if (!path.bad_type) {
15391 					verbose(env, "member '%s' is a zero-length array\n",
15392 						bad_name);
15393 					member_note = bpf_diag_fmt(
15394 						env, " Its member '%s' is a zero-length array.",
15395 						bad_name);
15396 				} else {
15397 					verbose(env, "member '%s' has type %s\n", bad_name,
15398 						btf_type_str(path.bad_type));
15399 					member_note = bpf_diag_fmt(
15400 						env,
15401 						" Its member '%s' is %s, not a scalar or an arena pointer.",
15402 						bad_name, btf_type_str(path.bad_type));
15403 				}
15404 			}
15405 			bpf_diag_program_structure(
15406 				env, insn_idx, "unsupported kernel function return type",
15407 				"Call a kernel function that returns only scalars or arena pointers by value.",
15408 				"%s() returns %s %s by value.%s "
15409 				"Only kfuncs returning scalar values or arena pointers, or "
15410 				"structures composed of scalar values or arena pointers are "
15411 				"supported.",
15412 				func_name, btf_type_str(t),
15413 				btf_name_by_offset(desc_btf, t->name_off), member_note);
15414 			return -EINVAL;
15415 		}
15416 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15417 	} else if (btf_type_is_ptr(t)) {
15418 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
15419 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
15420 		if (err) {
15421 			if (err < 0)
15422 				return err;
15423 		} else if (btf_type_is_void(ptr_type)) {
15424 			/* kfunc returning 'void *' is equivalent to returning scalar */
15425 			mark_reg_unknown(env, regs, BPF_REG_0);
15426 		} else if (!__btf_type_is_struct(ptr_type)) {
15427 			if (!meta.ret_mem.found) {
15428 				__u32 sz;
15429 
15430 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
15431 					meta.ret_mem.found = true;
15432 					meta.ret_mem.size = sz;
15433 					meta.r0_rdonly = true;
15434 				}
15435 
15436 				if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
15437 					meta.r0_rdonly = false;
15438 			}
15439 			if (!meta.ret_mem.found) {
15440 				ptr_type_name = btf_name_by_offset(desc_btf,
15441 								   ptr_type->name_off);
15442 				verbose(env,
15443 					"kernel function %s returns pointer type %s %s is not supported\n",
15444 					func_name,
15445 					btf_type_str(ptr_type),
15446 					ptr_type_name);
15447 				return -EINVAL;
15448 			}
15449 
15450 			mark_reg_known_zero(env, regs, BPF_REG_0);
15451 			regs[BPF_REG_0].type = PTR_TO_MEM;
15452 			regs[BPF_REG_0].mem_size = meta.ret_mem.size;
15453 
15454 			if (meta.r0_rdonly)
15455 				regs[BPF_REG_0].type |= MEM_RDONLY;
15456 
15457 			/* Ensures we don't access the memory after a release_reference() */
15458 			if (meta.ref_obj.id) {
15459 				err = validate_ref_obj(env, &meta.ref_obj);
15460 				if (err)
15461 					return err;
15462 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
15463 			}
15464 
15465 			if (is_kfunc_rcu_protected(&meta))
15466 				regs[BPF_REG_0].type |= MEM_RCU;
15467 		} else {
15468 			enum bpf_reg_type type = PTR_TO_BTF_ID;
15469 
15470 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
15471 				type |= PTR_UNTRUSTED;
15472 			else if (is_kfunc_rcu_protected(&meta) ||
15473 				 (bpf_is_iter_next_kfunc(&meta) &&
15474 				  (get_iter_from_state(env->cur_state, &meta)
15475 					   ->type & MEM_RCU))) {
15476 				/*
15477 				 * If the iterator's constructor (the _new
15478 				 * function e.g., bpf_iter_task_new) has been
15479 				 * annotated with BPF kfunc flag
15480 				 * KF_RCU_PROTECTED and was called within a RCU
15481 				 * read-side critical section, also propagate
15482 				 * the MEM_RCU flag to the pointer returned from
15483 				 * the iterator's next function (e.g.,
15484 				 * bpf_iter_task_next).
15485 				 */
15486 				type |= MEM_RCU;
15487 			} else {
15488 				/*
15489 				 * Any PTR_TO_BTF_ID that is returned from a BPF
15490 				 * kfunc should by default be treated as
15491 				 * implicitly trusted.
15492 				 */
15493 				type |= PTR_TRUSTED;
15494 			}
15495 
15496 			mark_reg_known_zero(env, regs, BPF_REG_0);
15497 			regs[BPF_REG_0].btf = desc_btf;
15498 			regs[BPF_REG_0].type = type;
15499 			regs[BPF_REG_0].btf_id = ptr_type_id;
15500 		}
15501 
15502 		if (is_kfunc_ret_null(&meta)) {
15503 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
15504 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
15505 			regs[BPF_REG_0].id = ++env->id_gen;
15506 		}
15507 		if (is_kfunc_acquire(&meta)) {
15508 			id = acquire_reference(env, insn_idx, 0);
15509 			if (id < 0)
15510 				return id;
15511 			regs[BPF_REG_0].id = id;
15512 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
15513 			ref_set_non_owning(env, &regs[BPF_REG_0]);
15514 		}
15515 
15516 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
15517 			regs[BPF_REG_0].id = ++env->id_gen;
15518 	} else if (btf_type_is_void(t)) {
15519 		if (meta.btf == btf_vmlinux) {
15520 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
15521 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
15522 				insn_aux->kptr_struct_meta =
15523 					btf_find_struct_meta(meta.arg_btf,
15524 							     meta.arg_btf_id);
15525 			}
15526 		}
15527 	}
15528 
15529 	if (bpf_is_kfunc_pkt_changing(&meta))
15530 		clear_all_pkt_pointers(env);
15531 
15532 	proto_slots = kfunc_abi_slots(&desc->func_model);
15533 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
15534 		struct bpf_func_state *caller = cur_func(env);
15535 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
15536 		u16 out_stack_arg_cnt = proto_slots - MAX_BPF_FUNC_REG_ARGS;
15537 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
15538 
15539 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
15540 			caller_info->stack_arg_cnt = stack_arg_cnt;
15541 	}
15542 
15543 	/*
15544 	 * Record R0 before process_iter_next_call() snapshots the alternate
15545 	 * iterator path's diagnostic position.
15546 	 */
15547 	if (ret_nregs == 1)
15548 		bpf_diag_mod_end(env);
15549 
15550 	if (bpf_is_iter_next_kfunc(&meta)) {
15551 		err = process_iter_next_call(env, insn_idx, &meta);
15552 		if (err)
15553 			return err;
15554 	}
15555 
15556 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
15557 		env->prog->call_session_cookie = true;
15558 
15559 	if (bpf_is_throw_kfunc(insn))
15560 		return process_bpf_exit_full(env, NULL, true);
15561 
15562 	return 0;
15563 }
15564 
15565 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
15566 					 const struct bpf_reg_state *reg,
15567 					 enum bpf_reg_type type)
15568 {
15569 	bool known = tnum_is_const(reg->var_off);
15570 	s64 val = reg->var_off.value;
15571 	s64 smin = reg_smin(reg);
15572 
15573 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
15574 		verbose(env, "math between %s pointer and %lld is not allowed\n",
15575 			reg_type_str(env, type), val);
15576 		return false;
15577 	}
15578 
15579 	if (smin == S64_MIN) {
15580 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
15581 			reg_type_str(env, type));
15582 		return false;
15583 	}
15584 
15585 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
15586 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
15587 			smin, reg_type_str(env, type));
15588 		return false;
15589 	}
15590 
15591 	return true;
15592 }
15593 
15594 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
15595 				      const struct bpf_reg_state *reg,
15596 				      enum bpf_reg_type type)
15597 {
15598 	bool known = tnum_is_const(reg->var_off);
15599 	s64 val = reg->var_off.value;
15600 	s64 smin = reg_smin(reg);
15601 
15602 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
15603 		verbose(env, "%s pointer offset %lld is not allowed\n",
15604 			reg_type_str(env, type), val);
15605 		return false;
15606 	}
15607 
15608 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
15609 		verbose(env, "%s pointer offset %lld is not allowed\n",
15610 			reg_type_str(env, type), smin);
15611 		return false;
15612 	}
15613 
15614 	return true;
15615 }
15616 
15617 enum {
15618 	REASON_BOUNDS	= -1,
15619 	REASON_TYPE	= -2,
15620 	REASON_PATHS	= -3,
15621 	REASON_LIMIT	= -4,
15622 	REASON_STACK	= -5,
15623 };
15624 
15625 static int retrieve_ptr_limit(const struct bpf_verifier_env *env,
15626 			      const struct bpf_reg_state *ptr_reg,
15627 			      u32 *alu_limit, bool mask_to_left)
15628 {
15629 	u32 max = 0, ptr_limit = 0;
15630 
15631 	switch (ptr_reg->type) {
15632 	case PTR_TO_STACK:
15633 		/* Offset 0 is out-of-bounds, but acceptable start for the
15634 		 * left direction, see BPF_REG_FP. Also, unknown scalar
15635 		 * offset where we would need to deal with min/max bounds is
15636 		 * currently prohibited for unprivileged.
15637 		 */
15638 		max = env->stack_limit + mask_to_left;
15639 		ptr_limit = -ptr_reg->var_off.value;
15640 		break;
15641 	case PTR_TO_MAP_VALUE:
15642 		max = ptr_reg->map_ptr->value_size;
15643 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
15644 		break;
15645 	default:
15646 		return REASON_TYPE;
15647 	}
15648 
15649 	if (ptr_limit >= max)
15650 		return REASON_LIMIT;
15651 	*alu_limit = ptr_limit;
15652 	return 0;
15653 }
15654 
15655 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
15656 				    const struct bpf_insn *insn)
15657 {
15658 	return env->bypass_spec_v1 ||
15659 		BPF_SRC(insn->code) == BPF_K ||
15660 		cur_aux(env)->nospec;
15661 }
15662 
15663 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
15664 				       u32 alu_state, u32 alu_limit)
15665 {
15666 	/* If we arrived here from different branches with different
15667 	 * state or limits to sanitize, then this won't work.
15668 	 */
15669 	if (aux->alu_state &&
15670 	    (aux->alu_state != alu_state ||
15671 	     aux->alu_limit != alu_limit))
15672 		return REASON_PATHS;
15673 
15674 	/* Corresponding fixup done in do_misc_fixups(). */
15675 	aux->alu_state = alu_state;
15676 	aux->alu_limit = alu_limit;
15677 	return 0;
15678 }
15679 
15680 static int sanitize_val_alu(struct bpf_verifier_env *env,
15681 			    struct bpf_insn *insn)
15682 {
15683 	struct bpf_insn_aux_data *aux = cur_aux(env);
15684 
15685 	if (can_skip_alu_sanitation(env, insn))
15686 		return 0;
15687 
15688 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
15689 }
15690 
15691 static bool sanitize_needed(u8 opcode)
15692 {
15693 	return opcode == BPF_ADD || opcode == BPF_SUB;
15694 }
15695 
15696 struct bpf_sanitize_info {
15697 	struct bpf_insn_aux_data aux;
15698 	bool mask_to_left;
15699 };
15700 
15701 static int sanitize_speculative_path(struct bpf_verifier_env *env,
15702 				     const struct bpf_insn *insn,
15703 				     u32 next_idx, u32 curr_idx)
15704 {
15705 	struct bpf_verifier_state *branch;
15706 	struct bpf_reg_state *regs;
15707 
15708 	branch = push_stack(env, next_idx, curr_idx, true);
15709 	if (!IS_ERR(branch) && insn) {
15710 		regs = branch->frame[branch->curframe]->regs;
15711 		if (BPF_SRC(insn->code) == BPF_K) {
15712 			mark_reg_unknown(env, regs, insn->dst_reg);
15713 		} else if (BPF_SRC(insn->code) == BPF_X) {
15714 			mark_reg_unknown(env, regs, insn->dst_reg);
15715 			mark_reg_unknown(env, regs, insn->src_reg);
15716 		}
15717 	}
15718 	return PTR_ERR_OR_ZERO(branch);
15719 }
15720 
15721 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
15722 			    struct bpf_insn *insn,
15723 			    const struct bpf_reg_state *ptr_reg,
15724 			    const struct bpf_reg_state *off_reg,
15725 			    struct bpf_reg_state *dst_reg,
15726 			    struct bpf_sanitize_info *info,
15727 			    const bool commit_window)
15728 {
15729 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
15730 	struct bpf_verifier_state *vstate = env->cur_state;
15731 	bool off_is_imm = tnum_is_const(off_reg->var_off);
15732 	bool off_is_neg = reg_smin(off_reg) < 0;
15733 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
15734 	u8 opcode = BPF_OP(insn->code);
15735 	u32 alu_state, alu_limit;
15736 	struct bpf_reg_state tmp;
15737 	int err;
15738 
15739 	if (can_skip_alu_sanitation(env, insn))
15740 		return 0;
15741 
15742 	/* We already marked aux for masking from non-speculative
15743 	 * paths, thus we got here in the first place. We only care
15744 	 * to explore bad access from here.
15745 	 */
15746 	if (vstate->speculative)
15747 		goto do_sim;
15748 
15749 	if (!commit_window) {
15750 		if (!tnum_is_const(off_reg->var_off) &&
15751 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
15752 			return REASON_BOUNDS;
15753 
15754 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
15755 				     (opcode == BPF_SUB && !off_is_neg);
15756 	}
15757 
15758 	err = retrieve_ptr_limit(env, ptr_reg, &alu_limit, info->mask_to_left);
15759 	if (err < 0)
15760 		return err;
15761 
15762 	if (commit_window) {
15763 		/* In commit phase we narrow the masking window based on
15764 		 * the observed pointer move after the simulated operation.
15765 		 */
15766 		alu_state = info->aux.alu_state;
15767 		alu_limit = abs(info->aux.alu_limit - alu_limit);
15768 	} else {
15769 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
15770 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
15771 		alu_state |= ptr_is_dst_reg ?
15772 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
15773 
15774 		/* Limit pruning on unknown scalars to enable deep search for
15775 		 * potential masking differences from other program paths.
15776 		 */
15777 		if (!off_is_imm)
15778 			env->explore_alu_limits = true;
15779 	}
15780 
15781 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
15782 	if (err < 0)
15783 		return err;
15784 do_sim:
15785 	/* If we're in commit phase, we're done here given we already
15786 	 * pushed the truncated dst_reg into the speculative verification
15787 	 * stack.
15788 	 *
15789 	 * Also, when register is a known constant, we rewrite register-based
15790 	 * operation to immediate-based, and thus do not need masking (and as
15791 	 * a consequence, do not need to simulate the zero-truncation either).
15792 	 */
15793 	if (commit_window || off_is_imm)
15794 		return 0;
15795 
15796 	/* Simulate and find potential out-of-bounds access under
15797 	 * speculative execution from truncation as a result of
15798 	 * masking when off was not within expected range. If off
15799 	 * sits in dst, then we temporarily need to move ptr there
15800 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
15801 	 * for cases where we use K-based arithmetic in one direction
15802 	 * and truncated reg-based in the other in order to explore
15803 	 * bad access.
15804 	 */
15805 	if (!ptr_is_dst_reg) {
15806 		tmp = *dst_reg;
15807 		*dst_reg = *ptr_reg;
15808 	}
15809 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
15810 	if (err < 0)
15811 		return REASON_STACK;
15812 	if (!ptr_is_dst_reg)
15813 		*dst_reg = tmp;
15814 	return 0;
15815 }
15816 
15817 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
15818 {
15819 	struct bpf_verifier_state *vstate = env->cur_state;
15820 
15821 	/* If we simulate paths under speculation, we don't update the
15822 	 * insn as 'seen' such that when we verify unreachable paths in
15823 	 * the non-speculative domain, sanitize_dead_code() can still
15824 	 * rewrite/sanitize them.
15825 	 */
15826 	if (!vstate->speculative)
15827 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
15828 }
15829 
15830 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason)
15831 {
15832 	static const char *err = "pointer arithmetic with it prohibited for !root";
15833 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
15834 	u32 dst = insn->dst_reg, src = insn->src_reg;
15835 	struct bpf_reg_state *regs = cur_regs(env);
15836 
15837 	switch (reason) {
15838 	case REASON_BOUNDS:
15839 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
15840 			regs[src].type == SCALAR_VALUE ? src : dst, err);
15841 		break;
15842 	case REASON_TYPE:
15843 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
15844 			regs[src].type == SCALAR_VALUE ? dst : src, err);
15845 		break;
15846 	case REASON_PATHS:
15847 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
15848 			dst, op, err);
15849 		break;
15850 	case REASON_LIMIT:
15851 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
15852 			dst, op, err);
15853 		break;
15854 	case REASON_STACK:
15855 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
15856 			dst, err);
15857 		return -ENOMEM;
15858 	default:
15859 		verifier_bug(env, "unknown reason (%d)", reason);
15860 		break;
15861 	}
15862 
15863 	return -EACCES;
15864 }
15865 
15866 /* check that stack access falls within stack limits and that 'reg' doesn't
15867  * have a variable offset.
15868  *
15869  * Variable offset is prohibited for unprivileged mode for simplicity since it
15870  * requires corresponding support in Spectre masking for stack ALU.  See also
15871  * retrieve_ptr_limit().
15872  */
15873 static int check_stack_access_for_ptr_arithmetic(
15874 				struct bpf_verifier_env *env,
15875 				int regno,
15876 				const struct bpf_reg_state *reg,
15877 				int off)
15878 {
15879 	if (!tnum_is_const(reg->var_off)) {
15880 		char tn_buf[48];
15881 
15882 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
15883 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
15884 			regno, tn_buf, off);
15885 		return -EACCES;
15886 	}
15887 
15888 	if (off >= 0 || off < -(int)env->stack_limit) {
15889 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
15890 			"prohibited for !root; off=%d\n", regno, off);
15891 		return -EACCES;
15892 	}
15893 
15894 	return 0;
15895 }
15896 
15897 static int sanitize_check_bounds(struct bpf_verifier_env *env,
15898 				 const struct bpf_insn *insn,
15899 				 struct bpf_reg_state *dst_reg)
15900 {
15901 	u32 dst = insn->dst_reg;
15902 
15903 	/* For unprivileged we require that resulting offset must be in bounds
15904 	 * in order to be able to sanitize access later on.
15905 	 */
15906 	if (env->bypass_spec_v1)
15907 		return 0;
15908 
15909 	switch (dst_reg->type) {
15910 	case PTR_TO_STACK:
15911 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
15912 							  dst_reg->var_off.value))
15913 			return -EACCES;
15914 		break;
15915 	case PTR_TO_MAP_VALUE:
15916 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
15917 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
15918 				"prohibited for !root\n", dst);
15919 			return -EACCES;
15920 		}
15921 		break;
15922 	default:
15923 		return -EOPNOTSUPP;
15924 	}
15925 
15926 	return 0;
15927 }
15928 
15929 static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
15930 {
15931 	if (tnum_is_const(src_reg->var_off))
15932 		scalar_step_scale(dst_reg, src_reg->var_off.value);
15933 	else
15934 		reg_step_reset(dst_reg);
15935 }
15936 
15937 static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
15938 {
15939 	u64 amount = src_reg->var_off.value;
15940 
15941 	if (tnum_is_const(src_reg->var_off) && amount < 64)
15942 		scalar_step_scale(dst_reg, 1ULL << amount);
15943 	else
15944 		reg_step_reset(dst_reg);
15945 }
15946 
15947 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
15948  * Caller should also handle BPF_MOV case separately.
15949  * If we return -EACCES, caller may want to try again treating pointer as a
15950  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
15951  */
15952 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
15953 				   u32 ptr_regno, const struct bpf_reg_state *ptr_reg,
15954 				   const struct bpf_reg_state *off_reg)
15955 {
15956 	struct bpf_verifier_state *vstate = env->cur_state;
15957 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15958 	struct bpf_reg_state *regs = state->regs, *dst_reg;
15959 	bool known = tnum_is_const(off_reg->var_off);
15960 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
15961 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
15962 	struct bpf_sanitize_info info = {};
15963 	u8 opcode = BPF_OP(insn->code);
15964 	u32 dst = insn->dst_reg;
15965 	const char *reason;
15966 	int ret, bounds_ret;
15967 	bool to_scalar;
15968 
15969 	dst_reg = &regs[dst];
15970 	/*
15971 	 * Only += and -= keep a pointer. Any other op makes a number of it,
15972 	 * which is fine when the program may see values of pointers anyway.
15973 	 */
15974 	to_scalar = opcode != BPF_ADD && opcode != BPF_SUB && env->allow_ptr_leaks;
15975 
15976 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
15977 	    smin_val > smax_val || umin_val > umax_val) {
15978 		/* Taint dst register if offset had invalid bounds derived from
15979 		 * e.g. dead branches.
15980 		 */
15981 		__mark_reg_unknown(env, dst_reg);
15982 		return 0;
15983 	}
15984 
15985 	if (BPF_CLASS(insn->code) != BPF_ALU64 && !to_scalar) {
15986 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
15987 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15988 			__mark_reg_unknown(env, dst_reg);
15989 			return 0;
15990 		}
15991 
15992 		verbose(env,
15993 			"R%d 32-bit pointer arithmetic prohibited\n",
15994 			dst);
15995 		reason = bpf_diag_fmt(
15996 			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.",
15997 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
15998 		bpf_diag_register_type(
15999 			env, env->insn_idx, ptr_regno, "32-bit pointer arithmetic", reason,
16000 			"Use a 64-bit ALU instruction with an allowed, bounded scalar offset.");
16001 		return -EACCES;
16002 	}
16003 
16004 	if (ptr_reg->type & PTR_MAYBE_NULL) {
16005 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
16006 			dst, reg_type_str(env, ptr_reg->type));
16007 		reason = bpf_diag_fmt(
16008 			env, "R%d may be NULL (%s). Pointer arithmetic is allowed only after the program proves the pointer is non-NULL on this path.",
16009 			ptr_regno, reg_type_str(env, ptr_reg->type));
16010 		bpf_diag_register_type(
16011 			env, env->insn_idx, ptr_regno, "pointer arithmetic before NULL check", reason,
16012 			"Make sure that a NULL check precedes any arithmetic performed on the pointer.");
16013 		return -EACCES;
16014 	}
16015 
16016 	switch (base_type(ptr_reg->type)) {
16017 	case PTR_TO_CTX:
16018 	case PTR_TO_MAP_VALUE:
16019 	case PTR_TO_MAP_KEY:
16020 	case PTR_TO_STACK:
16021 	case PTR_TO_PACKET_META:
16022 	case PTR_TO_PACKET:
16023 	case PTR_TO_TP_BUFFER:
16024 	case PTR_TO_BTF_ID:
16025 	case PTR_TO_MEM:
16026 	case PTR_TO_BUF:
16027 	case PTR_TO_FUNC:
16028 	case CONST_PTR_TO_DYNPTR:
16029 		break;
16030 	case PTR_TO_FLOW_KEYS:
16031 		if (known)
16032 			break;
16033 		fallthrough;
16034 	case CONST_PTR_TO_MAP:
16035 		/* smin_val represents the known value */
16036 		if (known && smin_val == 0 && opcode == BPF_ADD)
16037 			break;
16038 		fallthrough;
16039 	default:
16040 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
16041 			dst, reg_type_str(env, ptr_reg->type));
16042 		reason = bpf_diag_fmt(
16043 			env, "R%d holds %s. This pointer kind does not allow offset arithmetic.",
16044 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
16045 		bpf_diag_register_type(
16046 			env, env->insn_idx, ptr_regno, "pointer arithmetic is not allowed", reason,
16047 			"Do not change this pointer's offset; use it only in operations accepted for its kind.");
16048 		return -EACCES;
16049 	}
16050 
16051 	if (to_scalar) {
16052 		__mark_reg_unknown(env, dst_reg);
16053 		return 0;
16054 	}
16055 
16056 	/* For 'scalar += pointer', dst_reg inherits the complete pointer
16057 	 * register state. Individual fields may be adjusted later by pointer
16058 	 * arithmetic. Callers guarantee that below does not overwrite off_reg.
16059 	 */
16060 	if (dst_reg != ptr_reg)
16061 		*dst_reg = *ptr_reg;
16062 
16063 	/*
16064 	 * Accesses to untrusted PTR_TO_MEM are done through probe
16065 	 * instructions, hence no need to track offsets.
16066 	 */
16067 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
16068 		return 0;
16069 
16070 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) {
16071 		reason = bpf_diag_fmt(
16072 			env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].",
16073 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF);
16074 		bpf_diag_register_type(
16075 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16076 			"Clamp or bounds-check the scalar offset before applying it to the pointer.");
16077 		return -EINVAL;
16078 	}
16079 	if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) {
16080 		reason = bpf_diag_fmt(
16081 			env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.",
16082 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16083 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16084 		bpf_diag_register_type(
16085 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16086 			"Keep the base pointer within the verifier's allowed offset range before applying more arithmetic.");
16087 		return -EINVAL;
16088 	}
16089 
16090 	if (sanitize_needed(opcode)) {
16091 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
16092 				       &info, false);
16093 		if (ret < 0)
16094 			return sanitize_err(env, insn, ret);
16095 	}
16096 
16097 	/*
16098 	 * Pointer types do not carry 32-bit bounds at the moment. Blank r32
16099 	 * only after sanitize_ptr_alu() may have snapshotted dst_reg into a
16100 	 * speculative path: otherwise reg_bounds_sanity_check() might hit some
16101 	 * constraints violations.
16102 	 */
16103 	__mark_reg32_unbounded(dst_reg);
16104 
16105 	switch (opcode) {
16106 	case BPF_ADD:
16107 		/*
16108 		 * dst_reg gets the pointer type and since some positive
16109 		 * integer value was added to the pointer, give it a new 'id'
16110 		 * if it's a PTR_TO_PACKET.
16111 		 * this creates a new 'base' pointer, off_reg (variable) gets
16112 		 * added into the variable offset, and we copy the fixed offset
16113 		 * from ptr_reg.
16114 		 */
16115 		scalar_step_add(dst_reg, ptr_reg, off_reg);
16116 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
16117 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
16118 		dst_reg->raw = ptr_reg->raw;
16119 		if (reg_is_pkt_pointer(ptr_reg)) {
16120 			if (!known)
16121 				dst_reg->id = ++env->id_gen;
16122 			/*
16123 			 * Clear range for unknown addends since we can't know
16124 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
16125 			 * BEYOND_PKT_END from prior comparison as any pointer
16126 			 * arithmetic invalidates them.
16127 			 */
16128 			if (!known || dst_reg->range < 0)
16129 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16130 		}
16131 		break;
16132 	case BPF_SUB:
16133 		if (dst_reg != ptr_reg) {
16134 			/* scalar -= pointer.  Creates an unknown scalar */
16135 			verbose(env, "R%d tried to subtract pointer from scalar\n",
16136 				dst);
16137 			reason = bpf_diag_fmt(
16138 				env, "This operation subtracts pointer register R%d from scalar register R%d. "
16139 				"The verifier only tracks pointer-minus-scalar arithmetic for allowed pointer types.",
16140 				ptr_regno, dst);
16141 			bpf_diag_register_type(
16142 				env, env->insn_idx, ptr_regno, "pointer subtracted from scalar", reason,
16143 				"Keep the pointer as the base; only add or subtract bounded scalars when permitted.");
16144 			return -EACCES;
16145 		}
16146 		/* We don't allow subtraction from FP, because (according to
16147 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
16148 		 * be able to deal with it.
16149 		 */
16150 		if (ptr_reg->type == PTR_TO_STACK) {
16151 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
16152 				dst);
16153 			reason = bpf_diag_fmt(
16154 				env, "R%d is a stack pointer. The verifier does not allow BPF_SUB to move stack pointers.",
16155 				ptr_regno);
16156 			bpf_diag_register_type(
16157 				env, env->insn_idx, ptr_regno, "subtraction from stack pointer", reason,
16158 				"Use addition from R10 to form stack addresses within the tracked stack frame.");
16159 			return -EACCES;
16160 		}
16161 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
16162 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
16163 		dst_reg->raw = ptr_reg->raw;
16164 		if (reg_is_pkt_pointer(ptr_reg)) {
16165 			if (!known)
16166 				dst_reg->id = ++env->id_gen;
16167 			/*
16168 			 * Clear range if the subtrahend may be negative since
16169 			 * pkt pointer could move past its bounds. A positive
16170 			 * subtrahend moves it backwards keeping positive range
16171 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
16172 			 * prior comparison as arithmetic invalidates them.
16173 			 */
16174 			if ((!known && smin_val < 0) || dst_reg->range < 0)
16175 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16176 		}
16177 		reg_step_reset(dst_reg);
16178 		break;
16179 	case BPF_AND:
16180 	case BPF_OR:
16181 	case BPF_XOR:
16182 		/* bitwise ops on pointers are troublesome, prohibit. */
16183 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
16184 			dst, bpf_alu_string[opcode >> 4]);
16185 		reason = bpf_diag_fmt(
16186 			env, "R%d holds %s. Bitwise operator %s would destroy the pointer value the verifier is tracking.",
16187 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16188 			bpf_alu_string[opcode >> 4]);
16189 		bpf_diag_register_type(
16190 			env, env->insn_idx, ptr_regno, "bitwise operation on pointer", reason,
16191 			"Do bitwise operations on scalar values, not on pointer-valued registers.");
16192 		return -EACCES;
16193 	default:
16194 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
16195 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
16196 			dst, bpf_alu_string[opcode >> 4]);
16197 		reason = bpf_diag_fmt(
16198 			env, "R%d holds %s. Operator %s is not one of the limited pointer arithmetic operations the verifier can track.",
16199 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16200 			bpf_alu_string[opcode >> 4]);
16201 		bpf_diag_register_type(
16202 			env, env->insn_idx, ptr_regno, "invalid pointer arithmetic operator", reason,
16203 			"Use only verifier-supported addition or subtraction with a bounded scalar offset, or perform this operation on a scalar value.");
16204 		return -EACCES;
16205 	}
16206 
16207 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) {
16208 		reason = bpf_diag_fmt(
16209 			env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.",
16210 			dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16211 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16212 		bpf_diag_register_type(
16213 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16214 			"Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range.");
16215 		return -EINVAL;
16216 	}
16217 	/*
16218 	 * A packet pointer that keeps its id or range is checked against a
16219 	 * range set from the checked pointer's umax, so var_off must not tighten
16220 	 * its umax. r32 must still match var_off for reg_bounds_sanity_check().
16221 	 */
16222 	if (reg_is_pkt_pointer(dst_reg) && (known || dst_reg->range > 0))
16223 		__update_reg32_bounds(dst_reg);
16224 	else
16225 		reg_bounds_sync(dst_reg);
16226 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
16227 	if (bounds_ret == -EACCES)
16228 		return bounds_ret;
16229 	if (sanitize_needed(opcode)) {
16230 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
16231 				       &info, true);
16232 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
16233 				    && !env->cur_state->speculative
16234 				    && bounds_ret
16235 				    && !ret,
16236 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
16237 			return -EFAULT;
16238 		}
16239 		if (ret < 0)
16240 			return sanitize_err(env, insn, ret);
16241 	}
16242 
16243 	return 0;
16244 }
16245 
16246 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
16247 				 struct bpf_reg_state *src_reg)
16248 {
16249 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
16250 }
16251 
16252 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
16253 			       struct bpf_reg_state *src_reg)
16254 {
16255 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
16256 }
16257 
16258 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
16259 				 struct bpf_reg_state *src_reg)
16260 {
16261 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
16262 }
16263 
16264 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
16265 			       struct bpf_reg_state *src_reg)
16266 {
16267 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
16268 }
16269 
16270 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
16271 				 struct bpf_reg_state *src_reg)
16272 {
16273 	s32 smin = reg_s32_min(dst_reg);
16274 	s32 smax = reg_s32_max(dst_reg);
16275 	u32 umin = reg_u32_min(dst_reg);
16276 	u32 umax = reg_u32_max(dst_reg);
16277 	s32 tmp_prod[4];
16278 
16279 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
16280 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
16281 		/* Overflow possible, we know nothing */
16282 		umin = 0;
16283 		umax = U32_MAX;
16284 	}
16285 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
16286 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
16287 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
16288 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
16289 		/* Overflow possible, we know nothing */
16290 		smin = S32_MIN;
16291 		smax = S32_MAX;
16292 	} else {
16293 		smin = min_array(tmp_prod, 4);
16294 		smax = max_array(tmp_prod, 4);
16295 	}
16296 
16297 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
16298 					cnum32_from_srange(smin, smax));
16299 }
16300 
16301 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
16302 			       struct bpf_reg_state *src_reg)
16303 {
16304 	s64 smin = reg_smin(dst_reg);
16305 	s64 smax = reg_smax(dst_reg);
16306 	u64 umin = reg_umin(dst_reg);
16307 	u64 umax = reg_umax(dst_reg);
16308 	s64 tmp_prod[4];
16309 
16310 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
16311 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
16312 		/* Overflow possible, we know nothing */
16313 		umin = 0;
16314 		umax = U64_MAX;
16315 	}
16316 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
16317 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
16318 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
16319 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
16320 		/* Overflow possible, we know nothing */
16321 		smin = S64_MIN;
16322 		smax = S64_MAX;
16323 	} else {
16324 		smin = min_array(tmp_prod, 4);
16325 		smax = max_array(tmp_prod, 4);
16326 	}
16327 
16328 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
16329 					cnum64_from_srange(smin, smax));
16330 }
16331 
16332 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
16333 				  struct bpf_reg_state *src_reg)
16334 {
16335 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16336 
16337 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
16338 			 reg_u32_max(dst_reg) / src_val);
16339 
16340 	/* Reset other ranges/tnum to unbounded/unknown. */
16341 	reset_reg64_and_tnum(dst_reg);
16342 }
16343 
16344 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
16345 				struct bpf_reg_state *src_reg)
16346 {
16347 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16348 
16349 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
16350 			 div64_u64(reg_umax(dst_reg), src_val));
16351 
16352 	/* Reset other ranges/tnum to unbounded/unknown. */
16353 	reset_reg32_and_tnum(dst_reg);
16354 }
16355 
16356 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
16357 				  struct bpf_reg_state *src_reg)
16358 {
16359 	s32 smin = reg_s32_min(dst_reg);
16360 	s32 smax = reg_s32_max(dst_reg);
16361 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16362 	s32 res1, res2;
16363 
16364 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
16365 	if (smin == S32_MIN && src_val == -1) {
16366 		/*
16367 		 * If the dividend range contains more than just S32_MIN,
16368 		 * we cannot precisely track the result, so it becomes unbounded.
16369 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
16370 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
16371 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
16372 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
16373 		 */
16374 		if (smax != S32_MIN) {
16375 			smin = S32_MIN;
16376 			smax = S32_MAX;
16377 		}
16378 		goto reset;
16379 	}
16380 
16381 	res1 = smin / src_val;
16382 	res2 = smax / src_val;
16383 	smin = min(res1, res2);
16384 	smax = max(res1, res2);
16385 
16386 reset:
16387 	reg_set_srange32(dst_reg, smin, smax);
16388 	/* Reset other ranges/tnum to unbounded/unknown. */
16389 	reset_reg64_and_tnum(dst_reg);
16390 }
16391 
16392 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
16393 				struct bpf_reg_state *src_reg)
16394 {
16395 	s64 smin = reg_smin(dst_reg);
16396 	s64 smax = reg_smax(dst_reg);
16397 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16398 	s64 res1, res2;
16399 
16400 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
16401 	if (smin == S64_MIN && src_val == -1) {
16402 		/*
16403 		 * If the dividend range contains more than just S64_MIN,
16404 		 * we cannot precisely track the result, so it becomes unbounded.
16405 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
16406 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
16407 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
16408 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
16409 		 */
16410 		if (smax != S64_MIN) {
16411 			smin = S64_MIN;
16412 			smax = S64_MAX;
16413 		}
16414 		goto reset;
16415 	}
16416 
16417 	res1 = div64_s64(smin, src_val);
16418 	res2 = div64_s64(smax, src_val);
16419 	smin = min(res1, res2);
16420 	smax = max(res1, res2);
16421 
16422 reset:
16423 	reg_set_srange64(dst_reg, smin, smax);
16424 	/* Reset other ranges/tnum to unbounded/unknown. */
16425 	reset_reg32_and_tnum(dst_reg);
16426 }
16427 
16428 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
16429 				  struct bpf_reg_state *src_reg)
16430 {
16431 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16432 	u32 res_max = src_val - 1;
16433 
16434 	/*
16435 	 * If dst_umax <= res_max, the result remains unchanged.
16436 	 * e.g., [2, 5] % 10 = [2, 5].
16437 	 */
16438 	if (reg_u32_max(dst_reg) <= res_max)
16439 		return;
16440 
16441 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
16442 
16443 	/* Reset other ranges/tnum to unbounded/unknown. */
16444 	reset_reg64_and_tnum(dst_reg);
16445 }
16446 
16447 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
16448 				struct bpf_reg_state *src_reg)
16449 {
16450 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16451 	u64 res_max = src_val - 1;
16452 
16453 	/*
16454 	 * If dst_umax <= res_max, the result remains unchanged.
16455 	 * e.g., [2, 5] % 10 = [2, 5].
16456 	 */
16457 	if (reg_umax(dst_reg) <= res_max)
16458 		return;
16459 
16460 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
16461 
16462 	/* Reset other ranges/tnum to unbounded/unknown. */
16463 	reset_reg32_and_tnum(dst_reg);
16464 }
16465 
16466 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
16467 				  struct bpf_reg_state *src_reg)
16468 {
16469 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16470 
16471 	/*
16472 	 * Safe absolute value calculation:
16473 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
16474 	 * Here use unsigned integer to avoid overflow.
16475 	 */
16476 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
16477 
16478 	/*
16479 	 * Calculate the maximum possible absolute value of the result.
16480 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
16481 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
16482 	 */
16483 	s32 res_max_abs = src_abs - 1;
16484 
16485 	/*
16486 	 * If the dividend is already within the result range,
16487 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16488 	 */
16489 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
16490 		return;
16491 
16492 	/* General case: result has the same sign as the dividend. */
16493 	if (reg_s32_min(dst_reg) >= 0) {
16494 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
16495 	} else if (reg_s32_max(dst_reg) <= 0) {
16496 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
16497 	} else {
16498 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
16499 	}
16500 
16501 	/* Reset other ranges/tnum to unbounded/unknown. */
16502 	reset_reg64_and_tnum(dst_reg);
16503 }
16504 
16505 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
16506 				struct bpf_reg_state *src_reg)
16507 {
16508 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16509 
16510 	/*
16511 	 * Safe absolute value calculation:
16512 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
16513 	 * Here use unsigned integer to avoid overflow.
16514 	 */
16515 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
16516 
16517 	/*
16518 	 * Calculate the maximum possible absolute value of the result.
16519 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
16520 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
16521 	 */
16522 	s64 res_max_abs = src_abs - 1;
16523 
16524 	/*
16525 	 * If the dividend is already within the result range,
16526 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16527 	 */
16528 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
16529 		return;
16530 
16531 	/* General case: result has the same sign as the dividend. */
16532 	if (reg_smin(dst_reg) >= 0) {
16533 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
16534 	} else if (reg_smax(dst_reg) <= 0) {
16535 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
16536 	} else {
16537 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
16538 	}
16539 
16540 	/* Reset other ranges/tnum to unbounded/unknown. */
16541 	reset_reg32_and_tnum(dst_reg);
16542 }
16543 
16544 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
16545 				 struct bpf_reg_state *src_reg)
16546 {
16547 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16548 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16549 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16550 	u32 umax_val = reg_u32_max(src_reg);
16551 
16552 	if (src_known && dst_known) {
16553 		__mark_reg32_known(dst_reg, var32_off.value);
16554 		return;
16555 	}
16556 
16557 	/* We get our minimum from the var_off, since that's inherently
16558 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
16559 	 */
16560 	reg_set_urange32(dst_reg,
16561 			 var32_off.value,
16562 			 min(reg_u32_max(dst_reg), umax_val));
16563 }
16564 
16565 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
16566 			       struct bpf_reg_state *src_reg)
16567 {
16568 	bool src_known = tnum_is_const(src_reg->var_off);
16569 	bool dst_known = tnum_is_const(dst_reg->var_off);
16570 	u64 umax_val = reg_umax(src_reg);
16571 
16572 	if (src_known && dst_known) {
16573 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16574 		return;
16575 	}
16576 
16577 	/* We get our minimum from the var_off, since that's inherently
16578 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
16579 	 */
16580 	reg_set_urange64(dst_reg,
16581 			 dst_reg->var_off.value,
16582 			 min(reg_umax(dst_reg), umax_val));
16583 
16584 	/* We may learn something more from the var_off */
16585 	__update_reg_bounds(dst_reg);
16586 }
16587 
16588 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
16589 				struct bpf_reg_state *src_reg)
16590 {
16591 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16592 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16593 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16594 	u32 umin_val = reg_u32_min(src_reg);
16595 
16596 	if (src_known && dst_known) {
16597 		__mark_reg32_known(dst_reg, var32_off.value);
16598 		return;
16599 	}
16600 
16601 	/* We get our maximum from the var_off, and our minimum is the
16602 	 * maximum of the operands' minima
16603 	 */
16604 	reg_set_urange32(dst_reg,
16605 			 max(reg_u32_min(dst_reg), umin_val),
16606 			 var32_off.value | var32_off.mask);
16607 }
16608 
16609 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
16610 			      struct bpf_reg_state *src_reg)
16611 {
16612 	bool src_known = tnum_is_const(src_reg->var_off);
16613 	bool dst_known = tnum_is_const(dst_reg->var_off);
16614 	u64 umin_val = reg_umin(src_reg);
16615 
16616 	if (src_known && dst_known) {
16617 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16618 		return;
16619 	}
16620 
16621 	/* We get our maximum from the var_off, and our minimum is the
16622 	 * maximum of the operands' minima
16623 	 */
16624 	reg_set_urange64(dst_reg,
16625 			 max(reg_umin(dst_reg), umin_val),
16626 			 dst_reg->var_off.value | dst_reg->var_off.mask);
16627 
16628 	/* We may learn something more from the var_off */
16629 	__update_reg_bounds(dst_reg);
16630 }
16631 
16632 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
16633 				 struct bpf_reg_state *src_reg)
16634 {
16635 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16636 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16637 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16638 
16639 	if (src_known && dst_known) {
16640 		__mark_reg32_known(dst_reg, var32_off.value);
16641 		return;
16642 	}
16643 
16644 	/* We get both minimum and maximum from the var32_off. */
16645 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
16646 }
16647 
16648 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
16649 			       struct bpf_reg_state *src_reg)
16650 {
16651 	bool src_known = tnum_is_const(src_reg->var_off);
16652 	bool dst_known = tnum_is_const(dst_reg->var_off);
16653 
16654 	if (src_known && dst_known) {
16655 		/* dst_reg->var_off.value has been updated earlier */
16656 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16657 		return;
16658 	}
16659 
16660 	/* We get both minimum and maximum from the var_off. */
16661 	reg_set_urange64(dst_reg,
16662 			 dst_reg->var_off.value,
16663 			 dst_reg->var_off.value | dst_reg->var_off.mask);
16664 }
16665 
16666 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
16667 				   u64 umin_val, u64 umax_val)
16668 {
16669 	/* If we might shift our top bit out, then we know nothing */
16670 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
16671 		reg_set_urange32(dst_reg, 0, U32_MAX);
16672 	else
16673 		/* We lose all sign bit information (except what we can pick
16674 		 * up from var_off)
16675 		 */
16676 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
16677 				 reg_u32_max(dst_reg) << umax_val);
16678 }
16679 
16680 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
16681 				 struct bpf_reg_state *src_reg)
16682 {
16683 	u32 umax_val = reg_u32_max(src_reg);
16684 	u32 umin_val = reg_u32_min(src_reg);
16685 	/* u32 alu operation will zext upper bits */
16686 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
16687 
16688 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
16689 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
16690 	/* Not required but being careful mark reg64 bounds as unknown so
16691 	 * that we are forced to pick them up from tnum and zext later and
16692 	 * if some path skips this step we are still safe.
16693 	 */
16694 	__mark_reg64_unbounded(dst_reg);
16695 	__update_reg32_bounds(dst_reg);
16696 }
16697 
16698 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
16699 				   u64 umin_val, u64 umax_val)
16700 {
16701 	struct cnum64 u, s;
16702 
16703 	/* Special case <<32 because it is a common compiler pattern to sign
16704 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
16705 	 * because s32 bounds don't flip sign when shifting to the left by
16706 	 * 32bits.
16707 	 */
16708 	if (umin_val == 32 && umax_val == 32)
16709 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
16710 				       (s64)reg_s32_max(dst_reg) << 32);
16711 	else
16712 		s = CNUM64_UNBOUNDED;
16713 
16714 	/* If we might shift our top bit out, then we know nothing */
16715 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
16716 		u = CNUM64_UNBOUNDED;
16717 	else
16718 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
16719 				       reg_umax(dst_reg) << umax_val);
16720 
16721 	dst_reg->r64 = cnum64_intersect(u, s);
16722 }
16723 
16724 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
16725 			       struct bpf_reg_state *src_reg)
16726 {
16727 	u64 umax_val = reg_umax(src_reg);
16728 	u64 umin_val = reg_umin(src_reg);
16729 
16730 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
16731 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
16732 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
16733 
16734 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
16735 	/* We may learn something more from the var_off */
16736 	__update_reg_bounds(dst_reg);
16737 }
16738 
16739 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
16740 				 struct bpf_reg_state *src_reg)
16741 {
16742 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
16743 	u32 umax_val = reg_u32_max(src_reg);
16744 	u32 umin_val = reg_u32_min(src_reg);
16745 
16746 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
16747 	 * be negative, then either:
16748 	 * 1) src_reg might be zero, so the sign bit of the result is
16749 	 *    unknown, so we lose our signed bounds
16750 	 * 2) it's known negative, thus the unsigned bounds capture the
16751 	 *    signed bounds
16752 	 * 3) the signed bounds cross zero, so they tell us nothing
16753 	 *    about the result
16754 	 * If the value in dst_reg is known nonnegative, then again the
16755 	 * unsigned bounds capture the signed bounds.
16756 	 * Thus, in all cases it suffices to blow away our signed bounds
16757 	 * and rely on inferring new ones from the unsigned bounds and
16758 	 * var_off of the result.
16759 	 */
16760 
16761 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
16762 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
16763 			 reg_u32_max(dst_reg) >> umin_val);
16764 
16765 	__mark_reg64_unbounded(dst_reg);
16766 	__update_reg32_bounds(dst_reg);
16767 }
16768 
16769 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
16770 			       struct bpf_reg_state *src_reg)
16771 {
16772 	u64 umax_val = reg_umax(src_reg);
16773 	u64 umin_val = reg_umin(src_reg);
16774 
16775 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
16776 	 * be negative, then either:
16777 	 * 1) src_reg might be zero, so the sign bit of the result is
16778 	 *    unknown, so we lose our signed bounds
16779 	 * 2) it's known negative, thus the unsigned bounds capture the
16780 	 *    signed bounds
16781 	 * 3) the signed bounds cross zero, so they tell us nothing
16782 	 *    about the result
16783 	 * If the value in dst_reg is known nonnegative, then again the
16784 	 * unsigned bounds capture the signed bounds.
16785 	 * Thus, in all cases it suffices to blow away our signed bounds
16786 	 * and rely on inferring new ones from the unsigned bounds and
16787 	 * var_off of the result.
16788 	 */
16789 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
16790 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
16791 			 reg_umax(dst_reg) >> umin_val);
16792 
16793 	/* Its not easy to operate on alu32 bounds here because it depends
16794 	 * on bits being shifted in. Take easy way out and mark unbounded
16795 	 * so we can recalculate later from tnum.
16796 	 */
16797 	__mark_reg32_unbounded(dst_reg);
16798 	__update_reg_bounds(dst_reg);
16799 }
16800 
16801 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
16802 				  struct bpf_reg_state *src_reg)
16803 {
16804 	u64 umin_val = reg_u32_min(src_reg);
16805 
16806 	/* Upon reaching here, src_known is true and
16807 	 * umax_val is equal to umin_val.
16808 	 * Blow away the dst_reg umin_value/umax_value and rely on
16809 	 * dst_reg var_off to refine the result.
16810 	 */
16811 	reg_set_srange32(dst_reg,
16812 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
16813 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
16814 
16815 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
16816 
16817 	__mark_reg64_unbounded(dst_reg);
16818 	__update_reg32_bounds(dst_reg);
16819 }
16820 
16821 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
16822 				struct bpf_reg_state *src_reg)
16823 {
16824 	u64 umin_val = reg_umin(src_reg);
16825 
16826 	/* Upon reaching here, src_known is true and umax_val is equal
16827 	 * to umin_val.
16828 	 */
16829 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
16830 			 reg_smax(dst_reg) >> umin_val);
16831 
16832 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
16833 
16834 	/* Its not easy to operate on alu32 bounds here because it depends
16835 	 * on bits being shifted in from upper 32-bits. Take easy way out
16836 	 * and mark unbounded so we can recalculate later from tnum.
16837 	 */
16838 	__mark_reg32_unbounded(dst_reg);
16839 	__update_reg_bounds(dst_reg);
16840 }
16841 
16842 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
16843 {
16844 	/*
16845 	 * Byte swap operation - update var_off using tnum_bswap.
16846 	 * Three cases:
16847 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
16848 	 *    unconditional swap
16849 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
16850 	 *    swap on big-endian, truncation or no-op on little-endian
16851 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
16852 	 *    swap on little-endian, truncation or no-op on big-endian
16853 	 */
16854 
16855 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
16856 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
16857 	bool is_big_endian;
16858 #ifdef CONFIG_CPU_BIG_ENDIAN
16859 	is_big_endian = true;
16860 #else
16861 	is_big_endian = false;
16862 #endif
16863 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
16864 	bool need_bswap = alu64 || (to_le == is_big_endian);
16865 
16866 	/*
16867 	 * If the register is mutated, manually reset its scalar ID to break
16868 	 * any existing ties and avoid incorrect bounds propagation.
16869 	 */
16870 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
16871 		clear_scalar_id(dst_reg);
16872 
16873 	if (need_bswap) {
16874 		if (insn->imm == 16)
16875 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
16876 		else if (insn->imm == 32)
16877 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
16878 		else if (insn->imm == 64)
16879 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
16880 		/*
16881 		 * Byteswap scrambles the range, so we must reset bounds.
16882 		 * Bounds will be re-derived from the new tnum later.
16883 		 */
16884 		__mark_reg_unbounded(dst_reg);
16885 		reg_step_reset(dst_reg);
16886 	}
16887 	/* For bswap16/32, truncate dst register to match the swapped size */
16888 	if (insn->imm == 16 || insn->imm == 32)
16889 		coerce_reg_to_size(dst_reg, insn->imm / 8);
16890 }
16891 
16892 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
16893 					     const struct bpf_reg_state *src_reg)
16894 {
16895 	bool src_is_const = false;
16896 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
16897 
16898 	if (insn_bitness == 32) {
16899 		if (tnum_subreg_is_const(src_reg->var_off)
16900 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
16901 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
16902 			src_is_const = true;
16903 	} else {
16904 		if (tnum_is_const(src_reg->var_off)
16905 		    && reg_smin(src_reg) == reg_smax(src_reg)
16906 		    && reg_umin(src_reg) == reg_umax(src_reg))
16907 			src_is_const = true;
16908 	}
16909 
16910 	switch (BPF_OP(insn->code)) {
16911 	case BPF_ADD:
16912 	case BPF_SUB:
16913 	case BPF_NEG:
16914 	case BPF_AND:
16915 	case BPF_XOR:
16916 	case BPF_OR:
16917 	case BPF_MUL:
16918 	case BPF_END:
16919 		return true;
16920 
16921 	/*
16922 	 * Division and modulo operators range is only safe to compute when the
16923 	 * divisor is a constant.
16924 	 */
16925 	case BPF_DIV:
16926 	case BPF_MOD:
16927 		return src_is_const;
16928 
16929 	/* Shift operators range is only computable if shift dimension operand
16930 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
16931 	 * includes shifts by a negative number.
16932 	 */
16933 	case BPF_LSH:
16934 	case BPF_RSH:
16935 	case BPF_ARSH:
16936 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
16937 	default:
16938 		return false;
16939 	}
16940 }
16941 
16942 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
16943 			      struct bpf_reg_state *dst_reg)
16944 {
16945 	struct bpf_verifier_state *branch;
16946 	struct bpf_reg_state *regs;
16947 	bool alu32;
16948 
16949 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
16950 		alu32 = false;
16951 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
16952 		alu32 = true;
16953 	else
16954 		return 0;
16955 
16956 	branch = push_stack(env, env->insn_idx, env->insn_idx, false);
16957 	if (IS_ERR(branch))
16958 		return PTR_ERR(branch);
16959 
16960 	regs = branch->frame[branch->curframe]->regs;
16961 	if (alu32) {
16962 		__mark_reg32_known(&regs[insn->dst_reg], 0);
16963 		__mark_reg32_known(dst_reg, -1ull);
16964 	} else {
16965 		__mark_reg_known(&regs[insn->dst_reg], 0);
16966 		__mark_reg_known(dst_reg, -1ull);
16967 	}
16968 	return 0;
16969 }
16970 
16971 /* WARNING: This function does calculations on 64-bit values, but the actual
16972  * execution may occur on 32-bit values. Therefore, things like bitshifts
16973  * need extra checks in the 32-bit case.
16974  */
16975 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
16976 				      struct bpf_insn *insn,
16977 				      struct bpf_reg_state *dst_reg,
16978 				      struct bpf_reg_state src_reg)
16979 {
16980 	u8 opcode = BPF_OP(insn->code);
16981 	s16 off = insn->off;
16982 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
16983 	int ret;
16984 
16985 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
16986 		__mark_reg_unknown(env, dst_reg);
16987 		return 0;
16988 	}
16989 
16990 	if (sanitize_needed(opcode)) {
16991 		ret = sanitize_val_alu(env, insn);
16992 		if (ret < 0)
16993 			return sanitize_err(env, insn, ret);
16994 	}
16995 
16996 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
16997 	 * There are two classes of instructions: The first class we track both
16998 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
16999 	 * greatest amount of precision when alu operations are mixed with jmp32
17000 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
17001 	 * and BPF_OR. This is possible because these ops have fairly easy to
17002 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
17003 	 * See alu32 verifier tests for examples. The second class of
17004 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
17005 	 * with regards to tracking sign/unsigned bounds because the bits may
17006 	 * cross subreg boundaries in the alu64 case. When this happens we mark
17007 	 * the reg unbounded in the subreg bound space and use the resulting
17008 	 * tnum to calculate an approximation of the sign/unsigned bounds.
17009 	 */
17010 	switch (opcode) {
17011 	case BPF_ADD:
17012 		scalar_step_add(dst_reg, dst_reg, &src_reg);
17013 		scalar32_min_max_add(dst_reg, &src_reg);
17014 		scalar_min_max_add(dst_reg, &src_reg);
17015 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
17016 		break;
17017 	case BPF_SUB:
17018 		scalar32_min_max_sub(dst_reg, &src_reg);
17019 		scalar_min_max_sub(dst_reg, &src_reg);
17020 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
17021 		reg_step_reset(dst_reg);
17022 		break;
17023 	case BPF_NEG:
17024 		env->fake_reg[0] = *dst_reg;
17025 		__mark_reg_known(dst_reg, 0);
17026 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
17027 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
17028 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
17029 		reg_step_reset(dst_reg);
17030 		break;
17031 	case BPF_MUL:
17032 		scalar_step_mul(dst_reg, &src_reg);
17033 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
17034 		scalar32_min_max_mul(dst_reg, &src_reg);
17035 		scalar_min_max_mul(dst_reg, &src_reg);
17036 		break;
17037 	case BPF_DIV:
17038 		/* BPF div specification: x / 0 = 0 */
17039 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
17040 			___mark_reg_known(dst_reg, 0);
17041 			break;
17042 		}
17043 		if (alu32)
17044 			if (off == 1)
17045 				scalar32_min_max_sdiv(dst_reg, &src_reg);
17046 			else
17047 				scalar32_min_max_udiv(dst_reg, &src_reg);
17048 		else
17049 			if (off == 1)
17050 				scalar_min_max_sdiv(dst_reg, &src_reg);
17051 			else
17052 				scalar_min_max_udiv(dst_reg, &src_reg);
17053 		reg_step_reset(dst_reg);
17054 		break;
17055 	case BPF_MOD:
17056 		/* BPF mod specification: x % 0 = x */
17057 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
17058 			break;
17059 		if (alu32)
17060 			if (off == 1)
17061 				scalar32_min_max_smod(dst_reg, &src_reg);
17062 			else
17063 				scalar32_min_max_umod(dst_reg, &src_reg);
17064 		else
17065 			if (off == 1)
17066 				scalar_min_max_smod(dst_reg, &src_reg);
17067 			else
17068 				scalar_min_max_umod(dst_reg, &src_reg);
17069 		reg_step_reset(dst_reg);
17070 		break;
17071 	case BPF_AND:
17072 		if (tnum_is_const(src_reg.var_off)) {
17073 			ret = maybe_fork_scalars(env, insn, dst_reg);
17074 			if (ret)
17075 				return ret;
17076 		}
17077 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
17078 		scalar32_min_max_and(dst_reg, &src_reg);
17079 		scalar_min_max_and(dst_reg, &src_reg);
17080 		reg_step_reset(dst_reg);
17081 		break;
17082 	case BPF_OR:
17083 		if (tnum_is_const(src_reg.var_off)) {
17084 			ret = maybe_fork_scalars(env, insn, dst_reg);
17085 			if (ret)
17086 				return ret;
17087 		}
17088 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
17089 		scalar32_min_max_or(dst_reg, &src_reg);
17090 		scalar_min_max_or(dst_reg, &src_reg);
17091 		reg_step_reset(dst_reg);
17092 		break;
17093 	case BPF_XOR:
17094 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
17095 		scalar32_min_max_xor(dst_reg, &src_reg);
17096 		scalar_min_max_xor(dst_reg, &src_reg);
17097 		reg_step_reset(dst_reg);
17098 		break;
17099 	case BPF_LSH:
17100 		scalar_step_lsh(dst_reg, &src_reg);
17101 		if (alu32)
17102 			scalar32_min_max_lsh(dst_reg, &src_reg);
17103 		else
17104 			scalar_min_max_lsh(dst_reg, &src_reg);
17105 		break;
17106 	case BPF_RSH:
17107 		if (alu32)
17108 			scalar32_min_max_rsh(dst_reg, &src_reg);
17109 		else
17110 			scalar_min_max_rsh(dst_reg, &src_reg);
17111 		reg_step_reset(dst_reg);
17112 		break;
17113 	case BPF_ARSH:
17114 		if (alu32)
17115 			scalar32_min_max_arsh(dst_reg, &src_reg);
17116 		else
17117 			scalar_min_max_arsh(dst_reg, &src_reg);
17118 		reg_step_reset(dst_reg);
17119 		break;
17120 	case BPF_END:
17121 		scalar_byte_swap(dst_reg, insn);
17122 		reg_step_reset(dst_reg);
17123 		break;
17124 	default:
17125 		break;
17126 	}
17127 
17128 	/*
17129 	 * ALU32 ops are zero extended into 64bit register.
17130 	 *
17131 	 * BPF_END is already handled inside the helper (truncation),
17132 	 * so skip zext here to avoid unexpected zero extension.
17133 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
17134 	 * This is a 64bit byte swap operation with alu32==true,
17135 	 * but we should not zero extend the result.
17136 	 */
17137 	if (alu32 && opcode != BPF_END)
17138 		zext_32_to_64(dst_reg);
17139 	reg_bounds_sync(dst_reg);
17140 	return 0;
17141 }
17142 
17143 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
17144  * and var_off.
17145  */
17146 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
17147 				   struct bpf_insn *insn)
17148 {
17149 	struct bpf_verifier_state *vstate = env->cur_state;
17150 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
17151 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
17152 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
17153 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
17154 	struct bpf_insn_aux_data *aux = cur_aux(env);
17155 	u8 opcode = BPF_OP(insn->code);
17156 	int err;
17157 
17158 	dst_reg = &regs[insn->dst_reg];
17159 	if (BPF_SRC(insn->code) == BPF_X)
17160 		src_reg = &regs[insn->src_reg];
17161 	else
17162 		src_reg = NULL;
17163 
17164 	/* Case where at least one operand is an arena. */
17165 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
17166 
17167 		if (dst_reg->type != PTR_TO_ARENA)
17168 			*dst_reg = *src_reg;
17169 
17170 		if (BPF_CLASS(insn->code) == BPF_ALU64) {
17171 			/*
17172 			 * Only arena pointers set needs_zext, but doing so
17173 			 * modifies the instruction at fixup time to an ALU32
17174 			 * and makes it unsuitable for 64-bit scalar args. We
17175 			 * prevent zext from being set if the instruction has
17176 			 * been previously called with non-arena registers.
17177 			 */
17178 			if (aux->prevent_zext) {
17179 				verbose(env, "same insn cannot be used with and without arena pointer\n");
17180 				return -EINVAL;
17181 			}
17182 
17183 			/*
17184 			 * 32-bit operations zero upper bits automatically.
17185 			 * 64-bit operations need to be converted to 32.
17186 			 */
17187 			aux->needs_zext = true;
17188 			aux->zext_dst = true;
17189 		}
17190 
17191 		/* Any arithmetic operations are allowed on arena pointers */
17192 		return 0;
17193 	}
17194 
17195 	/* Prevent the instruction from being used with arena pointers (see above). */
17196 	if (env->prog->aux->arena && BPF_CLASS(insn->code) == BPF_ALU64) {
17197 		if (aux->needs_zext) {
17198 			verbose(env, "same insn cannot be used with and without arena pointer\n");
17199 			return -EINVAL;
17200 		}
17201 
17202 		aux->prevent_zext = true;
17203 	}
17204 
17205 	if (dst_reg->type != SCALAR_VALUE)
17206 		ptr_reg = dst_reg;
17207 
17208 	if (BPF_SRC(insn->code) == BPF_X) {
17209 		if (src_reg->type != SCALAR_VALUE) {
17210 			if (dst_reg->type != SCALAR_VALUE) {
17211 				/* Combining two pointers by any ALU op yields
17212 				 * an arbitrary scalar. Disallow all math except
17213 				 * pointer subtraction
17214 				 */
17215 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
17216 					mark_reg_unknown(env, regs, insn->dst_reg);
17217 					return 0;
17218 				}
17219 				verbose(env, "R%d pointer %s pointer prohibited\n",
17220 					insn->dst_reg,
17221 					bpf_alu_string[opcode >> 4]);
17222 				return -EACCES;
17223 			} else {
17224 				/* scalar += pointer
17225 				 * This is legal, but we have to reverse our
17226 				 * src/dest handling in computing the range
17227 				 */
17228 				err = mark_chain_precision(env, insn->dst_reg);
17229 				if (err)
17230 					return err;
17231 				off_reg = *dst_reg;
17232 				return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg,
17233 							       &off_reg);
17234 			}
17235 		} else if (ptr_reg) {
17236 			/* pointer += scalar */
17237 			err = mark_chain_precision(env, insn->src_reg);
17238 			if (err)
17239 				return err;
17240 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg);
17241 		} else if (dst_reg->precise) {
17242 			/* if dst_reg is precise, src_reg should be precise as well */
17243 			err = mark_chain_precision(env, insn->src_reg);
17244 			if (err)
17245 				return err;
17246 		}
17247 	} else {
17248 		/* Pretend the src is a reg with a known value, since we only
17249 		 * need to be able to read from this state.
17250 		 */
17251 		off_reg.type = SCALAR_VALUE;
17252 		__mark_reg_known(&off_reg, insn->imm);
17253 		src_reg = &off_reg;
17254 		if (ptr_reg) /* pointer += K */
17255 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, ptr_reg, src_reg);
17256 	}
17257 
17258 	/* Got here implies adding two SCALAR_VALUEs */
17259 	if (WARN_ON_ONCE(ptr_reg)) {
17260 		print_verifier_state(env, vstate, vstate->curframe, true);
17261 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
17262 		return -EFAULT;
17263 	}
17264 	if (WARN_ON(!src_reg)) {
17265 		print_verifier_state(env, vstate, vstate->curframe, true);
17266 		verbose(env, "verifier internal error: no src_reg\n");
17267 		return -EFAULT;
17268 	}
17269 	/*
17270 	 * For alu32 linked register tracking, we need to check dst_reg's
17271 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
17272 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
17273 	 */
17274 	u64 dst_umax = reg_umax(dst_reg);
17275 
17276 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
17277 	if (err)
17278 		return err;
17279 	/*
17280 	 * Compilers can generate the code
17281 	 * r1 = r2
17282 	 * r1 += 0x1
17283 	 * if r2 < 1000 goto ...
17284 	 * use r1 in memory access
17285 	 * So remember constant delta between r2 and r1 and update r1 after
17286 	 * 'if' condition.
17287 	 */
17288 	if (env->bpf_capable &&
17289 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
17290 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
17291 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
17292 		u64 val = reg_const_value(src_reg, alu32);
17293 		s32 off;
17294 
17295 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
17296 			goto clear_id;
17297 
17298 		if (alu32 && (dst_umax > U32_MAX))
17299 			goto clear_id;
17300 
17301 		off = (s32)val;
17302 
17303 		if (BPF_OP(insn->code) == BPF_SUB) {
17304 			/* Negating S32_MIN would overflow */
17305 			if (off == S32_MIN)
17306 				goto clear_id;
17307 			off = -off;
17308 		}
17309 
17310 		if (dst_reg->id & BPF_ADD_CONST) {
17311 			/*
17312 			 * If the register already went through rX += val
17313 			 * we cannot accumulate another val into rx->off.
17314 			 */
17315 clear_id:
17316 			clear_scalar_id(dst_reg);
17317 		} else {
17318 			if (alu32)
17319 				dst_reg->id |= BPF_ADD_CONST32;
17320 			else
17321 				dst_reg->id |= BPF_ADD_CONST64;
17322 			dst_reg->delta = off;
17323 		}
17324 	} else {
17325 		/*
17326 		 * Make sure ID is cleared otherwise dst_reg min/max could be
17327 		 * incorrectly propagated into other registers by sync_linked_regs()
17328 		 */
17329 		clear_scalar_id(dst_reg);
17330 	}
17331 	return 0;
17332 }
17333 
17334 /*
17335  * Many checks done by this function are quite conservative.
17336  * This is because main verification pass does not maintain
17337  * enough information to track object identities for some
17338  * of the interesting types, e.g. PTR_TO_MEM.
17339  */
17340 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
17341 			    const struct bpf_reg_state *reg_b)
17342 {
17343 	if (reg_a == reg_b)
17344 		return true;
17345 	/* Require matching flags and base types. */
17346 	if (reg_a->type != reg_b->type)
17347 		return false;
17348 	/* NULL can't be compared to some base+offset pointer. */
17349 	if (type_may_be_null(reg_a->type))
17350 		return false;
17351 
17352 	switch (base_type(reg_a->type)) {
17353 	case PTR_TO_STACK:
17354 		return reg_a->frameno == reg_b->frameno;
17355 	case PTR_TO_MAP_VALUE:
17356 		if (reg_a->map_ptr != reg_b->map_ptr || reg_a->map_uid != reg_b->map_uid)
17357 			return false;
17358 		if (reg_a->id && reg_a->id == reg_b->id)
17359 			return true;
17360 		/*
17361 		 * A plain single-element array has one stable value address,
17362 		 * but not when BPF_F_INNER_MAP is set, see arraymap.c:array_map_meta_equal().
17363 		 */
17364 		if (reg_a->map_ptr->map_type == BPF_MAP_TYPE_ARRAY &&
17365 		    reg_a->map_ptr->max_entries == 1 &&
17366 		    !(reg_a->map_ptr->map_flags & BPF_F_INNER_MAP))
17367 			return true;
17368 		/*
17369 		 * The rules above can be simplified / relaxed if:
17370 		 * - fresh IDs would always be assigned for map-value lookups;
17371 		 * - direct map value loads would always have and ID of zero.
17372 		 */
17373 		return false;
17374 	case PTR_TO_MEM:
17375 	case PTR_TO_BUF:
17376 		return reg_a->id && reg_a->id == reg_b->id;
17377 
17378 	default:
17379 		return false;
17380 	}
17381 }
17382 
17383 int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
17384 		      struct cnum64 range, u16 base, u16 step)
17385 {
17386 	reg->r64 = range;
17387 	reg->r32 = CNUM32_UNBOUNDED;
17388 	reg->step = step;
17389 	reg->base = base;
17390 	reg->var_off = tnum_unknown;
17391 	reg_bounds_sync(reg); /* this should infer the tnum alignment */
17392 	return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
17393 }
17394 
17395 /*
17396  * Checks if pointer and packet metadata matches between two registers.
17397  * For use with bpf_reg_union().
17398  */
17399 bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b)
17400 {
17401 	if (a->type != b->type)
17402 		return false;
17403 	if (a->type == SCALAR_VALUE)
17404 		return true;
17405 	return !memcmp(a, b, offsetof(struct bpf_reg_state, var_off)) &&
17406 	       a->id == b->id && a->parent_id == b->parent_id && a->map_uid == b->map_uid;
17407 }
17408 
17409 /*
17410  * Extends acc's scalar range to include src's scalar range.
17411  * Caller must ensure that other kinds of metadata is compatible.
17412  * Caller must clear acc's scalar ID.
17413  */
17414 int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
17415 		  const struct bpf_reg_state *src)
17416 {
17417 	u16 base, step;
17418 
17419 	if (!bpf_reg_union_compatible(acc, src)) {
17420 		verifier_bug(env, "union of incompatible registers");
17421 		return -EFAULT;
17422 	}
17423 	acc->r64 = cnum64_union(acc->r64, src->r64);
17424 	acc->r32 = cnum32_union(acc->r32, src->r32);
17425 	acc->var_off = tnum_union(acc->var_off, src->var_off);
17426 
17427 	/* Retain a common congruence if the bases agree modulo the gcd. */
17428 	step = gcd(acc->step, src->step);
17429 	base = acc->base % step;
17430 	if (base != src->base % step) {
17431 		reg_step_reset(acc);
17432 	} else {
17433 		acc->base = base;
17434 		acc->step = step;
17435 	}
17436 	reg_bounds_sync(acc);
17437 	return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
17438 }
17439 
17440 /* check validity of 32-bit and 64-bit arithmetic operations */
17441 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17442 {
17443 	struct bpf_reg_state *regs = cur_regs(env);
17444 	u8 opcode = BPF_OP(insn->code);
17445 	int err;
17446 
17447 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
17448 
17449 	if (opcode == BPF_END || opcode == BPF_NEG) {
17450 		/* check src operand */
17451 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17452 		if (err)
17453 			return err;
17454 
17455 		if (is_pointer_value(env, insn->dst_reg)) {
17456 			verbose(env, "R%d pointer arithmetic prohibited\n",
17457 				insn->dst_reg);
17458 			return -EACCES;
17459 		}
17460 
17461 		/* check dest operand */
17462 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
17463 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17464 			err = err ?: adjust_scalar_min_max_vals(env, insn,
17465 							 &regs[insn->dst_reg],
17466 							 regs[insn->dst_reg]);
17467 		} else {
17468 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
17469 		}
17470 		if (err)
17471 			return err;
17472 
17473 	} else if (opcode == BPF_MOV) {
17474 
17475 		if (BPF_SRC(insn->code) == BPF_X) {
17476 			if (insn->off == BPF_ADDR_SPACE_CAST) {
17477 				if (!env->prog->aux->arena) {
17478 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
17479 					return -EINVAL;
17480 				}
17481 			}
17482 
17483 			/* check src operand */
17484 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17485 			if (err)
17486 				return err;
17487 		}
17488 
17489 		/* check dest operand, mark as required later */
17490 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17491 		if (err)
17492 			return err;
17493 
17494 		if (BPF_SRC(insn->code) == BPF_X) {
17495 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
17496 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
17497 
17498 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
17499 				if (insn->imm) {
17500 					/* off == BPF_ADDR_SPACE_CAST */
17501 					mark_reg_unknown(env, regs, insn->dst_reg);
17502 					if (insn->imm == 1) /* cast from as(1) to as(0) */
17503 						dst_reg->type = PTR_TO_ARENA;
17504 				} else if (insn->off == 0) {
17505 					/* case: R1 = R2
17506 					 * copy register state to dest reg
17507 					 */
17508 					assign_scalar_id_before_mov(env, src_reg);
17509 					*dst_reg = *src_reg;
17510 				} else {
17511 					/* case: R1 = (s8, s16 s32)R2 */
17512 					if (is_pointer_value(env, insn->src_reg)) {
17513 						verbose(env,
17514 							"R%d sign-extension part of pointer\n",
17515 							insn->src_reg);
17516 						return -EACCES;
17517 					} else if (src_reg->type == SCALAR_VALUE) {
17518 						bool no_sext;
17519 
17520 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
17521 						if (no_sext)
17522 							assign_scalar_id_before_mov(env, src_reg);
17523 						*dst_reg = *src_reg;
17524 						if (!no_sext)
17525 							clear_scalar_id(dst_reg);
17526 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
17527 					} else {
17528 						mark_reg_unknown(env, regs, insn->dst_reg);
17529 					}
17530 				}
17531 			} else {
17532 				/* R1 = (u32) R2 */
17533 				if (is_pointer_value(env, insn->src_reg)) {
17534 					verbose(env,
17535 						"R%d partial copy of pointer\n",
17536 						insn->src_reg);
17537 					return -EACCES;
17538 				} else if (src_reg->type == SCALAR_VALUE) {
17539 					if (insn->off == 0) {
17540 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
17541 
17542 						if (is_src_reg_u32)
17543 							assign_scalar_id_before_mov(env, src_reg);
17544 						*dst_reg = *src_reg;
17545 						/* Make sure ID is cleared if src_reg is not in u32
17546 						 * range otherwise dst_reg min/max could be incorrectly
17547 						 * propagated into src_reg by sync_linked_regs()
17548 						 */
17549 						if (!is_src_reg_u32)
17550 							clear_scalar_id(dst_reg);
17551 					} else {
17552 						/* case: W1 = (s8, s16)W2 */
17553 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
17554 
17555 						if (no_sext)
17556 							assign_scalar_id_before_mov(env, src_reg);
17557 						*dst_reg = *src_reg;
17558 						if (!no_sext)
17559 							clear_scalar_id(dst_reg);
17560 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
17561 					}
17562 				} else {
17563 					mark_reg_unknown(env, regs,
17564 							 insn->dst_reg);
17565 				}
17566 				zext_32_to_64(dst_reg);
17567 				reg_bounds_sync(dst_reg);
17568 			}
17569 		} else {
17570 			/* case: R = imm
17571 			 * remember the value we stored into this reg
17572 			 */
17573 			/* clear any state __mark_reg_known doesn't set */
17574 			mark_reg_unknown(env, regs, insn->dst_reg);
17575 			regs[insn->dst_reg].type = SCALAR_VALUE;
17576 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
17577 				__mark_reg_known(regs + insn->dst_reg,
17578 						 insn->imm);
17579 			} else {
17580 				__mark_reg_known(regs + insn->dst_reg,
17581 						 (u32)insn->imm);
17582 			}
17583 		}
17584 
17585 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
17586 
17587 		if (BPF_SRC(insn->code) == BPF_X) {
17588 			/* check src1 operand */
17589 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17590 			if (err)
17591 				return err;
17592 		}
17593 
17594 		/* check src2 operand */
17595 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17596 		if (err)
17597 			return err;
17598 
17599 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
17600 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
17601 			verbose(env, "div by zero\n");
17602 			return -EINVAL;
17603 		}
17604 
17605 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
17606 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
17607 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
17608 
17609 			if (insn->imm < 0 || insn->imm >= size) {
17610 				verbose(env, "invalid shift %d\n", insn->imm);
17611 				return -EINVAL;
17612 			}
17613 		}
17614 
17615 		/* check dest operand */
17616 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17617 		err = err ?: adjust_reg_min_max_vals(env, insn);
17618 		if (err)
17619 			return err;
17620 	}
17621 
17622 	err = reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
17623 	if (err)
17624 		return err;
17625 
17626 	bpf_diag_mod_end(env);
17627 	return 0;
17628 }
17629 
17630 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
17631 				   struct bpf_reg_state *dst_reg,
17632 				   enum bpf_reg_type type,
17633 				   bool range_right_open)
17634 {
17635 	struct bpf_func_state *state;
17636 	struct bpf_reg_state *reg;
17637 	int new_range;
17638 
17639 	if (reg_umax(dst_reg) == 0 && range_right_open)
17640 		/* This doesn't give us any range */
17641 		return;
17642 
17643 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
17644 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
17645 		 * than pkt_end, but that's because it's also less than pkt.
17646 		 */
17647 		return;
17648 
17649 	new_range = reg_umax(dst_reg);
17650 	if (range_right_open)
17651 		new_range++;
17652 
17653 	/* Examples for register markings:
17654 	 *
17655 	 * pkt_data in dst register:
17656 	 *
17657 	 *   r2 = r3;
17658 	 *   r2 += 8;
17659 	 *   if (r2 > pkt_end) goto <handle exception>
17660 	 *   <access okay>
17661 	 *
17662 	 *   r2 = r3;
17663 	 *   r2 += 8;
17664 	 *   if (r2 < pkt_end) goto <access okay>
17665 	 *   <handle exception>
17666 	 *
17667 	 *   Where:
17668 	 *     r2 == dst_reg, pkt_end == src_reg
17669 	 *     r2=pkt(id=n,off=8,r=0)
17670 	 *     r3=pkt(id=n,off=0,r=0)
17671 	 *
17672 	 * pkt_data in src register:
17673 	 *
17674 	 *   r2 = r3;
17675 	 *   r2 += 8;
17676 	 *   if (pkt_end >= r2) goto <access okay>
17677 	 *   <handle exception>
17678 	 *
17679 	 *   r2 = r3;
17680 	 *   r2 += 8;
17681 	 *   if (pkt_end <= r2) goto <handle exception>
17682 	 *   <access okay>
17683 	 *
17684 	 *   Where:
17685 	 *     pkt_end == dst_reg, r2 == src_reg
17686 	 *     r2=pkt(id=n,off=8,r=0)
17687 	 *     r3=pkt(id=n,off=0,r=0)
17688 	 *
17689 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
17690 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
17691 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
17692 	 * the check.
17693 	 */
17694 
17695 	/* If our ids match, then we must have the same max_value.  And we
17696 	 * don't care about the other reg's fixed offset, since if it's too big
17697 	 * the range won't allow anything.
17698 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
17699 	 */
17700 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
17701 		if (reg->type == type && reg->id == dst_reg->id)
17702 			/* keep the maximum range already checked */
17703 			reg->range = max(reg->range, new_range);
17704 	}));
17705 }
17706 
17707 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
17708 				u8 opcode, bool is_jmp32);
17709 /*
17710  * Learn more information about live branches by simulating refinement on both branches.
17711  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
17712  * that branch is dead.
17713  */
17714 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
17715 {
17716 	/* Fallthrough (FALSE) branch */
17717 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
17718 	reg_bounds_sync(&env->false_reg1);
17719 	reg_bounds_sync(&env->false_reg2);
17720 	/*
17721 	 * If there is a range bounds violation in *any* of the abstract values in either
17722 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
17723 	 * TRUE branch will be taken.
17724 	 */
17725 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
17726 		return 1;
17727 
17728 	/* Jump (TRUE) branch */
17729 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
17730 	reg_bounds_sync(&env->true_reg1);
17731 	reg_bounds_sync(&env->true_reg2);
17732 	/*
17733 	 * If there is a range bounds violation in *any* of the abstract values in either
17734 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
17735 	 * Only FALSE branch will be taken.
17736 	 */
17737 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
17738 		return 0;
17739 
17740 	/* Both branches are possible, we can't determine which one will be taken. */
17741 	return -1;
17742 }
17743 
17744 /*
17745  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
17746  */
17747 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
17748 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
17749 {
17750 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
17751 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
17752 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
17753 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
17754 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
17755 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
17756 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
17757 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
17758 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
17759 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
17760 
17761 	if (reg1 == reg2) {
17762 		switch (opcode) {
17763 		case BPF_JGE:
17764 		case BPF_JLE:
17765 		case BPF_JSGE:
17766 		case BPF_JSLE:
17767 		case BPF_JEQ:
17768 			return 1;
17769 		case BPF_JGT:
17770 		case BPF_JLT:
17771 		case BPF_JSGT:
17772 		case BPF_JSLT:
17773 		case BPF_JNE:
17774 			return 0;
17775 		case BPF_JSET:
17776 			if (tnum_is_const(t1))
17777 				return t1.value != 0;
17778 			else
17779 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
17780 		default:
17781 			return -1;
17782 		}
17783 	}
17784 
17785 	switch (opcode) {
17786 	case BPF_JEQ:
17787 		/* constants, umin/umax and smin/smax checks would be
17788 		 * redundant in this case because they all should match
17789 		 */
17790 		if (tnum_is_const(t1) && tnum_is_const(t2))
17791 			return t1.value == t2.value;
17792 		if (!tnum_overlap(t1, t2))
17793 			return 0;
17794 		/* non-overlapping ranges */
17795 		if (umin1 > umax2 || umax1 < umin2)
17796 			return 0;
17797 		if (smin1 > smax2 || smax1 < smin2)
17798 			return 0;
17799 		if (!is_jmp32) {
17800 			/* if 64-bit ranges are inconclusive, see if we can
17801 			 * utilize 32-bit subrange knowledge to eliminate
17802 			 * branches that can't be taken a priori
17803 			 */
17804 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
17805 			    reg_u32_max(reg1) < reg_u32_min(reg2))
17806 				return 0;
17807 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
17808 			    reg_s32_max(reg1) < reg_s32_min(reg2))
17809 				return 0;
17810 		}
17811 		break;
17812 	case BPF_JNE:
17813 		/* constants, umin/umax and smin/smax checks would be
17814 		 * redundant in this case because they all should match
17815 		 */
17816 		if (tnum_is_const(t1) && tnum_is_const(t2))
17817 			return t1.value != t2.value;
17818 		if (!tnum_overlap(t1, t2))
17819 			return 1;
17820 		/* non-overlapping ranges */
17821 		if (umin1 > umax2 || umax1 < umin2)
17822 			return 1;
17823 		if (smin1 > smax2 || smax1 < smin2)
17824 			return 1;
17825 		if (!is_jmp32) {
17826 			/* if 64-bit ranges are inconclusive, see if we can
17827 			 * utilize 32-bit subrange knowledge to eliminate
17828 			 * branches that can't be taken a priori
17829 			 */
17830 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
17831 			    reg_u32_max(reg1) < reg_u32_min(reg2))
17832 				return 1;
17833 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
17834 			    reg_s32_max(reg1) < reg_s32_min(reg2))
17835 				return 1;
17836 		}
17837 		break;
17838 	case BPF_JSET:
17839 		if (!is_reg_const(reg2, is_jmp32)) {
17840 			swap(reg1, reg2);
17841 			swap(t1, t2);
17842 		}
17843 		if (!is_reg_const(reg2, is_jmp32))
17844 			return -1;
17845 		if ((~t1.mask & t1.value) & t2.value)
17846 			return 1;
17847 		if (!((t1.mask | t1.value) & t2.value))
17848 			return 0;
17849 		break;
17850 	case BPF_JGT:
17851 		if (umin1 > umax2)
17852 			return 1;
17853 		else if (umax1 <= umin2)
17854 			return 0;
17855 		break;
17856 	case BPF_JSGT:
17857 		if (smin1 > smax2)
17858 			return 1;
17859 		else if (smax1 <= smin2)
17860 			return 0;
17861 		break;
17862 	case BPF_JLT:
17863 		if (umax1 < umin2)
17864 			return 1;
17865 		else if (umin1 >= umax2)
17866 			return 0;
17867 		break;
17868 	case BPF_JSLT:
17869 		if (smax1 < smin2)
17870 			return 1;
17871 		else if (smin1 >= smax2)
17872 			return 0;
17873 		break;
17874 	case BPF_JGE:
17875 		if (umin1 >= umax2)
17876 			return 1;
17877 		else if (umax1 < umin2)
17878 			return 0;
17879 		break;
17880 	case BPF_JSGE:
17881 		if (smin1 >= smax2)
17882 			return 1;
17883 		else if (smax1 < smin2)
17884 			return 0;
17885 		break;
17886 	case BPF_JLE:
17887 		if (umax1 <= umin2)
17888 			return 1;
17889 		else if (umin1 > umax2)
17890 			return 0;
17891 		break;
17892 	case BPF_JSLE:
17893 		if (smax1 <= smin2)
17894 			return 1;
17895 		else if (smin1 > smax2)
17896 			return 0;
17897 		break;
17898 	}
17899 
17900 	return simulate_both_branches_taken(env, opcode, is_jmp32);
17901 }
17902 
17903 int bpf_flip_opcode(u32 opcode)
17904 {
17905 	/* How can we transform "a <op> b" into "b <op> a"? */
17906 	static const u8 opcode_flip[16] = {
17907 		/* these stay the same */
17908 		[BPF_JEQ  >> 4] = BPF_JEQ,
17909 		[BPF_JNE  >> 4] = BPF_JNE,
17910 		[BPF_JSET >> 4] = BPF_JSET,
17911 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
17912 		[BPF_JGE  >> 4] = BPF_JLE,
17913 		[BPF_JGT  >> 4] = BPF_JLT,
17914 		[BPF_JLE  >> 4] = BPF_JGE,
17915 		[BPF_JLT  >> 4] = BPF_JGT,
17916 		[BPF_JSGE >> 4] = BPF_JSLE,
17917 		[BPF_JSGT >> 4] = BPF_JSLT,
17918 		[BPF_JSLE >> 4] = BPF_JSGE,
17919 		[BPF_JSLT >> 4] = BPF_JSGT
17920 	};
17921 	return opcode_flip[opcode >> 4];
17922 }
17923 
17924 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
17925 				   struct bpf_reg_state *src_reg,
17926 				   u8 opcode)
17927 {
17928 	struct bpf_reg_state *pkt;
17929 
17930 	if (src_reg->type == PTR_TO_PACKET_END) {
17931 		pkt = dst_reg;
17932 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
17933 		pkt = src_reg;
17934 		opcode = bpf_flip_opcode(opcode);
17935 	} else {
17936 		return -1;
17937 	}
17938 
17939 	if (pkt->range >= 0)
17940 		return -1;
17941 
17942 	switch (opcode) {
17943 	case BPF_JLE:
17944 		/* pkt <= pkt_end */
17945 		fallthrough;
17946 	case BPF_JGT:
17947 		/* pkt > pkt_end */
17948 		if (pkt->range == BEYOND_PKT_END)
17949 			/* pkt has at last one extra byte beyond pkt_end */
17950 			return opcode == BPF_JGT;
17951 		break;
17952 	case BPF_JLT:
17953 		/* pkt < pkt_end */
17954 		fallthrough;
17955 	case BPF_JGE:
17956 		/* pkt >= pkt_end */
17957 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
17958 			return opcode == BPF_JGE;
17959 		break;
17960 	}
17961 	return -1;
17962 }
17963 
17964 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
17965  * and return:
17966  *  1 - branch will be taken and "goto target" will be executed
17967  *  0 - branch will not be taken and fall-through to next insn
17968  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
17969  *      range [0,10]
17970  */
17971 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
17972 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
17973 {
17974 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
17975 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
17976 
17977 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
17978 		u64 val;
17979 
17980 		/*
17981 		 * The low 32 bits of a valid pointer may well be zero, hence
17982 		 * nothing below applies to a 32-bit comparison.
17983 		 */
17984 		if (is_jmp32)
17985 			return -1;
17986 
17987 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
17988 		if (!is_reg_const(reg2, is_jmp32)) {
17989 			opcode = bpf_flip_opcode(opcode);
17990 			swap(reg1, reg2);
17991 		}
17992 		/* and ensure that reg2 is a constant */
17993 		if (!is_reg_const(reg2, is_jmp32))
17994 			return -1;
17995 
17996 		if (!reg_not_null(env, reg1))
17997 			return -1;
17998 
17999 		/* If pointer is valid tests against zero will fail so we can
18000 		 * use this to direct branch taken.
18001 		 */
18002 		val = reg_const_value(reg2, is_jmp32);
18003 		if (val != 0)
18004 			return -1;
18005 
18006 		switch (opcode) {
18007 		case BPF_JEQ:
18008 			return 0;
18009 		case BPF_JNE:
18010 			return 1;
18011 		default:
18012 			return -1;
18013 		}
18014 	}
18015 
18016 	/* now deal with two scalars, but not necessarily constants */
18017 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
18018 }
18019 
18020 /* Opcode that corresponds to a *false* branch condition.
18021  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
18022  */
18023 u8 bpf_rev_opcode(u8 opcode)
18024 {
18025 	switch (opcode) {
18026 	case BPF_JEQ:		return BPF_JNE;
18027 	case BPF_JNE:		return BPF_JEQ;
18028 	/* JSET doesn't have it's reverse opcode in BPF, so add
18029 	 * BPF_X flag to denote the reverse of that operation
18030 	 */
18031 	case BPF_JSET:		return BPF_JSET | BPF_X;
18032 	case BPF_JSET | BPF_X:	return BPF_JSET;
18033 	case BPF_JGE:		return BPF_JLT;
18034 	case BPF_JGT:		return BPF_JLE;
18035 	case BPF_JLE:		return BPF_JGT;
18036 	case BPF_JLT:		return BPF_JGE;
18037 	case BPF_JSGE:		return BPF_JSLT;
18038 	case BPF_JSGT:		return BPF_JSLE;
18039 	case BPF_JSLE:		return BPF_JSGT;
18040 	case BPF_JSLT:		return BPF_JSGE;
18041 	default:		return 0;
18042 	}
18043 }
18044 
18045 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
18046 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
18047 				u8 opcode, bool is_jmp32)
18048 {
18049 	struct tnum t;
18050 	u64 val;
18051 
18052 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
18053 	switch (opcode) {
18054 	case BPF_JGE:
18055 	case BPF_JGT:
18056 	case BPF_JSGE:
18057 	case BPF_JSGT:
18058 		opcode = bpf_flip_opcode(opcode);
18059 		swap(reg1, reg2);
18060 		break;
18061 	default:
18062 		break;
18063 	}
18064 
18065 	switch (opcode) {
18066 	case BPF_JEQ:
18067 		if (is_jmp32) {
18068 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
18069 			reg2->r32 = reg1->r32;
18070 
18071 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
18072 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18073 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
18074 		} else {
18075 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
18076 			reg2->r64 = reg1->r64;
18077 
18078 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
18079 			reg2->var_off = reg1->var_off;
18080 		}
18081 		break;
18082 	case BPF_JNE:
18083 		if (!is_reg_const(reg2, is_jmp32))
18084 			swap(reg1, reg2);
18085 		if (!is_reg_const(reg2, is_jmp32))
18086 			break;
18087 
18088 		/* try to recompute the bound of reg1 if reg2 is a const and
18089 		 * is exactly the edge of reg1.
18090 		 */
18091 		val = reg_const_value(reg2, is_jmp32);
18092 		if (is_jmp32) {
18093 			/* Complement of the range [val, val] as cnum32. */
18094 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
18095 		} else {
18096 			/* Complement of the range [val, val] as cnum64. */
18097 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
18098 		}
18099 		break;
18100 	case BPF_JSET:
18101 		if (!is_reg_const(reg2, is_jmp32))
18102 			swap(reg1, reg2);
18103 		if (!is_reg_const(reg2, is_jmp32))
18104 			break;
18105 		val = reg_const_value(reg2, is_jmp32);
18106 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
18107 		 * requires single bit to learn something useful. E.g., if we
18108 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
18109 		 * are actually set? We can learn something definite only if
18110 		 * it's a single-bit value to begin with.
18111 		 *
18112 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
18113 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
18114 		 * bit 1 is set, which we can readily use in adjustments.
18115 		 */
18116 		if (!is_power_of_2(val))
18117 			break;
18118 		if (is_jmp32) {
18119 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
18120 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18121 		} else {
18122 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
18123 		}
18124 		break;
18125 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see bpf_rev_opcode() */
18126 		if (!is_reg_const(reg2, is_jmp32))
18127 			swap(reg1, reg2);
18128 		if (!is_reg_const(reg2, is_jmp32))
18129 			break;
18130 		val = reg_const_value(reg2, is_jmp32);
18131 		/* Forget the ranges before narrowing tnums, to avoid invariant
18132 		 * violations if we're on a dead branch.
18133 		 */
18134 		__mark_reg_unbounded(reg1);
18135 		reg_step_reset(reg1);
18136 		if (is_jmp32) {
18137 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
18138 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18139 		} else {
18140 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
18141 		}
18142 		break;
18143 	case BPF_JLE:
18144 		if (is_jmp32) {
18145 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
18146 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
18147 		} else {
18148 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
18149 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
18150 		}
18151 		break;
18152 	case BPF_JLT:
18153 		if (is_jmp32) {
18154 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
18155 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
18156 		} else {
18157 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
18158 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
18159 		}
18160 		break;
18161 	case BPF_JSLE:
18162 		if (is_jmp32) {
18163 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
18164 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
18165 		} else {
18166 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
18167 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
18168 		}
18169 		break;
18170 	case BPF_JSLT:
18171 		if (is_jmp32) {
18172 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
18173 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
18174 		} else {
18175 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
18176 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
18177 		}
18178 		break;
18179 	default:
18180 		return;
18181 	}
18182 }
18183 
18184 /* Check for invariant violations on the registers for both branches of a condition */
18185 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
18186 {
18187 	int err;
18188 
18189 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
18190 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
18191 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
18192 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
18193 	return err;
18194 }
18195 
18196 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
18197 				 struct bpf_reg_state *reg, u32 id,
18198 				 bool is_null)
18199 {
18200 	if (type_may_be_null(reg->type) && reg->id == id &&
18201 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
18202 		/* Old offset should have been known-zero, because we don't
18203 		 * allow pointer arithmetic on pointers that might be NULL.
18204 		 * If we see this happening, don't convert the register.
18205 		 *
18206 		 * But in some cases, some helpers that return local kptrs
18207 		 * advance offset for the returned pointer. In those cases,
18208 		 * it is fine to expect to see reg->var_off.
18209 		 */
18210 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
18211 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
18212 			return;
18213 		if (is_null) {
18214 			/* We don't need id from this point
18215 			 * onwards anymore, thus we should better reset it,
18216 			 * so that state pruning has chances to take effect.
18217 			 */
18218 			__mark_reg_known_zero(reg);
18219 			reg->type = SCALAR_VALUE;
18220 
18221 			return;
18222 		}
18223 
18224 		mark_ptr_not_null_reg(reg);
18225 
18226 		/*
18227 		 * reg->id is preserved for object relationship tracking
18228 		 * and spin_lock lock state tracking
18229 		 */
18230 	}
18231 }
18232 
18233 /* The logic is similar to find_good_pkt_pointers(), both could eventually
18234  * be folded together at some point.
18235  */
18236 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
18237 				  bool is_null)
18238 {
18239 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
18240 	struct bpf_reg_state *regs = state->regs, *reg;
18241 	u32 id = regs[regno].id;
18242 
18243 	if (is_null && find_reference_state(vstate, id))
18244 		/* regs[regno] is in the " == NULL" branch.
18245 		 * No one could have freed the reference state before
18246 		 * doing the NULL check.
18247 		 */
18248 		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
18249 
18250 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
18251 		mark_ptr_or_null_reg(state, reg, id, is_null);
18252 	}));
18253 }
18254 
18255 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
18256 				   struct bpf_reg_state *dst_reg,
18257 				   struct bpf_reg_state *src_reg,
18258 				   struct bpf_verifier_state *this_branch,
18259 				   struct bpf_verifier_state *other_branch)
18260 {
18261 	if (BPF_SRC(insn->code) != BPF_X)
18262 		return false;
18263 
18264 	/* Pointers are always 64-bit. */
18265 	if (BPF_CLASS(insn->code) == BPF_JMP32)
18266 		return false;
18267 
18268 	switch (BPF_OP(insn->code)) {
18269 	case BPF_JGT:
18270 		if ((dst_reg->type == PTR_TO_PACKET &&
18271 		     src_reg->type == PTR_TO_PACKET_END) ||
18272 		    (dst_reg->type == PTR_TO_PACKET_META &&
18273 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18274 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
18275 			find_good_pkt_pointers(this_branch, dst_reg,
18276 					       dst_reg->type, false);
18277 			mark_pkt_end(other_branch, insn->dst_reg, true);
18278 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18279 			    src_reg->type == PTR_TO_PACKET) ||
18280 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18281 			    src_reg->type == PTR_TO_PACKET_META)) {
18282 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
18283 			find_good_pkt_pointers(other_branch, src_reg,
18284 					       src_reg->type, true);
18285 			mark_pkt_end(this_branch, insn->src_reg, false);
18286 		} else {
18287 			return false;
18288 		}
18289 		break;
18290 	case BPF_JLT:
18291 		if ((dst_reg->type == PTR_TO_PACKET &&
18292 		     src_reg->type == PTR_TO_PACKET_END) ||
18293 		    (dst_reg->type == PTR_TO_PACKET_META &&
18294 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18295 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
18296 			find_good_pkt_pointers(other_branch, dst_reg,
18297 					       dst_reg->type, true);
18298 			mark_pkt_end(this_branch, insn->dst_reg, false);
18299 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18300 			    src_reg->type == PTR_TO_PACKET) ||
18301 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18302 			    src_reg->type == PTR_TO_PACKET_META)) {
18303 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
18304 			find_good_pkt_pointers(this_branch, src_reg,
18305 					       src_reg->type, false);
18306 			mark_pkt_end(other_branch, insn->src_reg, true);
18307 		} else {
18308 			return false;
18309 		}
18310 		break;
18311 	case BPF_JGE:
18312 		if ((dst_reg->type == PTR_TO_PACKET &&
18313 		     src_reg->type == PTR_TO_PACKET_END) ||
18314 		    (dst_reg->type == PTR_TO_PACKET_META &&
18315 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18316 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
18317 			find_good_pkt_pointers(this_branch, dst_reg,
18318 					       dst_reg->type, true);
18319 			mark_pkt_end(other_branch, insn->dst_reg, false);
18320 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18321 			    src_reg->type == PTR_TO_PACKET) ||
18322 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18323 			    src_reg->type == PTR_TO_PACKET_META)) {
18324 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
18325 			find_good_pkt_pointers(other_branch, src_reg,
18326 					       src_reg->type, false);
18327 			mark_pkt_end(this_branch, insn->src_reg, true);
18328 		} else {
18329 			return false;
18330 		}
18331 		break;
18332 	case BPF_JLE:
18333 		if ((dst_reg->type == PTR_TO_PACKET &&
18334 		     src_reg->type == PTR_TO_PACKET_END) ||
18335 		    (dst_reg->type == PTR_TO_PACKET_META &&
18336 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18337 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
18338 			find_good_pkt_pointers(other_branch, dst_reg,
18339 					       dst_reg->type, false);
18340 			mark_pkt_end(this_branch, insn->dst_reg, true);
18341 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18342 			    src_reg->type == PTR_TO_PACKET) ||
18343 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18344 			    src_reg->type == PTR_TO_PACKET_META)) {
18345 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
18346 			find_good_pkt_pointers(this_branch, src_reg,
18347 					       src_reg->type, true);
18348 			mark_pkt_end(other_branch, insn->src_reg, false);
18349 		} else {
18350 			return false;
18351 		}
18352 		break;
18353 	default:
18354 		return false;
18355 	}
18356 
18357 	return true;
18358 }
18359 
18360 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
18361 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
18362 {
18363 	struct linked_reg *e;
18364 
18365 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
18366 		return;
18367 
18368 	e = linked_regs_push(reg_set);
18369 	if (e) {
18370 		e->frameno = frameno;
18371 		e->is_reg = is_reg;
18372 		e->regno = spi_or_reg;
18373 	} else {
18374 		clear_scalar_id(reg);
18375 	}
18376 }
18377 
18378 /* For all R being scalar registers or spilled scalar registers
18379  * in verifier state, save R in linked_regs if R->id == id.
18380  * If there are too many Rs sharing same id, reset id for leftover Rs.
18381  */
18382 static void collect_linked_regs(struct bpf_verifier_env *env,
18383 				struct bpf_verifier_state *vstate,
18384 				u32 id,
18385 				struct linked_regs *linked_regs)
18386 {
18387 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18388 	struct bpf_func_state *func;
18389 	struct bpf_reg_state *reg;
18390 	u16 live_regs;
18391 	int i, j;
18392 
18393 	id = id & ~BPF_ADD_CONST;
18394 	for (i = vstate->curframe; i >= 0; i--) {
18395 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
18396 		func = vstate->frame[i];
18397 		for (j = 0; j < BPF_REG_FP; j++) {
18398 			if (!(live_regs & BIT(j)))
18399 				continue;
18400 			reg = &func->regs[j];
18401 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
18402 		}
18403 		for (j = 0; j < bpf_stack_nr_slots(func); j++) {
18404 			struct bpf_stack_state *ss = bpf_stack_slot(func, j);
18405 
18406 			if (!bpf_is_spilled_reg(ss))
18407 				continue;
18408 			reg = &ss->spilled_ptr;
18409 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
18410 		}
18411 	}
18412 }
18413 
18414 /* For all R in linked_regs, copy known_reg range into R
18415  * if R->id == known_reg->id.
18416  */
18417 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
18418 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
18419 {
18420 	struct bpf_reg_state fake_reg;
18421 	struct bpf_reg_state *reg;
18422 	struct linked_reg *e;
18423 	int i;
18424 
18425 	for (i = 0; i < linked_regs->cnt; ++i) {
18426 		e = &linked_regs->entries[i];
18427 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
18428 				: &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
18429 		if (reg->type != SCALAR_VALUE || reg == known_reg)
18430 			continue;
18431 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
18432 			continue;
18433 		/*
18434 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
18435 		 * hold across different ALU widths.
18436 		 */
18437 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
18438 			continue;
18439 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
18440 		    reg->delta == known_reg->delta) {
18441 			*reg = *known_reg;
18442 		} else {
18443 			s32 saved_off = reg->delta;
18444 			u32 saved_id = reg->id;
18445 
18446 			fake_reg.type = SCALAR_VALUE;
18447 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
18448 
18449 			/* reg = known_reg; reg += delta */
18450 			*reg = *known_reg;
18451 			/*
18452 			 * Must preserve off and id, otherwise another sync_linked_regs()
18453 			 * will be incorrect.
18454 			 */
18455 			reg->delta = saved_off;
18456 			reg->id = saved_id;
18457 
18458 			scalar_step_add(reg, reg, &fake_reg);
18459 			scalar32_min_max_add(reg, &fake_reg);
18460 			scalar_min_max_add(reg, &fake_reg);
18461 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
18462 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
18463 				zext_32_to_64(reg);
18464 			reg_bounds_sync(reg);
18465 		}
18466 		if (e->is_reg)
18467 			mark_reg_scratched(env, e->regno);
18468 		else
18469 			mark_stack_slot_scratched(env, e->spi);
18470 	}
18471 }
18472 
18473 static int check_cond_jmp_op(struct bpf_verifier_env *env,
18474 			     struct bpf_insn *insn, int *insn_idx)
18475 {
18476 	struct bpf_verifier_state *this_branch = env->cur_state;
18477 	struct bpf_verifier_state *other_branch;
18478 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
18479 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
18480 	struct bpf_reg_state *eq_branch_regs;
18481 	struct linked_regs linked_regs = {};
18482 	u8 opcode = BPF_OP(insn->code);
18483 	int insn_flags = 0;
18484 	bool is_jmp32;
18485 	int pred = -1;
18486 	int err;
18487 
18488 	/* Only conditional jumps are expected to reach here. */
18489 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
18490 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
18491 		return -EINVAL;
18492 	}
18493 
18494 	if (opcode == BPF_JCOND) {
18495 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
18496 		int idx = *insn_idx;
18497 
18498 		prev_st = find_prev_entry(env, cur_st->parent, idx);
18499 
18500 		/* branch out 'fallthrough' insn as a new state to explore */
18501 		queued_st = push_stack(env, idx + 1, idx, false);
18502 		if (IS_ERR(queued_st))
18503 			return PTR_ERR(queued_st);
18504 
18505 		queued_st->may_goto_depth++;
18506 		if (prev_st)
18507 			widen_imprecise_scalars(env, prev_st, queued_st);
18508 		*insn_idx += insn->off;
18509 		return 0;
18510 	}
18511 
18512 	/* check src2 operand */
18513 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18514 	if (err)
18515 		return err;
18516 
18517 	dst_reg = &regs[insn->dst_reg];
18518 	if (BPF_SRC(insn->code) == BPF_X) {
18519 		/* check src1 operand */
18520 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
18521 		if (err)
18522 			return err;
18523 
18524 		src_reg = &regs[insn->src_reg];
18525 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
18526 		    is_pointer_value(env, insn->src_reg)) {
18527 			verbose(env, "R%d pointer comparison prohibited\n",
18528 				insn->src_reg);
18529 			return -EACCES;
18530 		}
18531 
18532 		if (src_reg->type == PTR_TO_STACK)
18533 			insn_flags |= INSN_F_SRC_REG_STACK;
18534 		if (dst_reg->type == PTR_TO_STACK)
18535 			insn_flags |= INSN_F_DST_REG_STACK;
18536 	} else {
18537 		src_reg = &env->fake_reg[0];
18538 		memset(src_reg, 0, sizeof(*src_reg));
18539 		src_reg->type = SCALAR_VALUE;
18540 		__mark_reg_known(src_reg, insn->imm);
18541 
18542 		if (dst_reg->type == PTR_TO_STACK)
18543 			insn_flags |= INSN_F_DST_REG_STACK;
18544 	}
18545 
18546 	if (insn_flags) {
18547 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, NULL, 0);
18548 		if (err)
18549 			return err;
18550 	}
18551 
18552 	/*
18553 	 * Collect the linked registers before env->{true,false}_reg{1,2} setup,
18554 	 * otherwise ids dropped by collect_linked_regs() would be resurrected
18555 	 * when env->{true,false}_reg{1,2} are copied back.
18556 	 */
18557 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
18558 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
18559 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
18560 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
18561 
18562 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
18563 	env->false_reg1 = *dst_reg;
18564 	env->false_reg2 = *src_reg;
18565 	env->true_reg1 = *dst_reg;
18566 	env->true_reg2 = *src_reg;
18567 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
18568 	if (pred >= 0) {
18569 		/* If we get here with a dst_reg pointer type it is because
18570 		 * above is_branch_taken() special cased the 0 comparison.
18571 		 */
18572 		if (!__is_pointer_value(false, dst_reg))
18573 			err = mark_chain_precision(env, insn->dst_reg);
18574 		if (BPF_SRC(insn->code) == BPF_X && !err &&
18575 		    !__is_pointer_value(false, src_reg))
18576 			err = mark_chain_precision(env, insn->src_reg);
18577 		if (err)
18578 			return err;
18579 	}
18580 
18581 	if (pred == 1) {
18582 		/* Only follow the goto, ignore fall-through. If needed, push
18583 		 * the fall-through branch for simulation under speculative
18584 		 * execution.
18585 		 */
18586 		if (!env->bypass_spec_v1) {
18587 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
18588 			if (err < 0)
18589 				return err;
18590 		}
18591 		if (env->log.level & BPF_LOG_LEVEL)
18592 			print_insn_state(env, this_branch, this_branch->curframe);
18593 		*insn_idx += insn->off;
18594 		return 0;
18595 	} else if (pred == 0) {
18596 		/* Only follow the fall-through branch, since that's where the
18597 		 * program will go. If needed, push the goto branch for
18598 		 * simulation under speculative execution.
18599 		 */
18600 		if (!env->bypass_spec_v1) {
18601 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
18602 							*insn_idx);
18603 			if (err < 0)
18604 				return err;
18605 		}
18606 		if (env->log.level & BPF_LOG_LEVEL)
18607 			print_insn_state(env, this_branch, this_branch->curframe);
18608 		return 0;
18609 	}
18610 
18611 	/* Push scalar registers sharing same ID to jump history,
18612 	 * do this before creating 'other_branch', so that both
18613 	 * 'this_branch' and 'other_branch' share this history
18614 	 * if parent state is created.
18615 	 */
18616 	if (linked_regs.cnt > 1) {
18617 		u16 packed[LINKED_REGS_MAX];
18618 
18619 		linked_regs_pack(&linked_regs, packed);
18620 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, packed, linked_regs.cnt);
18621 		if (err)
18622 			return err;
18623 	}
18624 
18625 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
18626 	if (IS_ERR(other_branch))
18627 		return PTR_ERR(other_branch);
18628 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
18629 
18630 	err = regs_bounds_sanity_check_branches(env);
18631 	if (err)
18632 		return err;
18633 
18634 	*dst_reg = env->false_reg1;
18635 	*src_reg = env->false_reg2;
18636 	other_branch_regs[insn->dst_reg] = env->true_reg1;
18637 	if (BPF_SRC(insn->code) == BPF_X)
18638 		other_branch_regs[insn->src_reg] = env->true_reg2;
18639 
18640 	if (BPF_SRC(insn->code) == BPF_X &&
18641 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
18642 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
18643 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
18644 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
18645 				 &linked_regs);
18646 	}
18647 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
18648 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
18649 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
18650 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
18651 				 &linked_regs);
18652 	}
18653 
18654 	/* if one pointer register is compared to another pointer
18655 	 * register check if PTR_MAYBE_NULL could be lifted.
18656 	 * E.g. register A - maybe null
18657 	 *      register B - not null
18658 	 * for JNE A, B, ... - A is not null in the false branch;
18659 	 * for JEQ A, B, ... - A is not null in the true branch.
18660 	 *
18661 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
18662 	 * not need to be null checked by the BPF program, i.e.,
18663 	 * could be null even without PTR_MAYBE_NULL marking, so
18664 	 * only propagate nullness when neither reg is that type.
18665 	 */
18666 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
18667 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
18668 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
18669 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
18670 		eq_branch_regs = NULL;
18671 		switch (opcode) {
18672 		case BPF_JEQ:
18673 			eq_branch_regs = other_branch_regs;
18674 			break;
18675 		case BPF_JNE:
18676 			eq_branch_regs = regs;
18677 			break;
18678 		default:
18679 			/* do nothing */
18680 			break;
18681 		}
18682 		if (eq_branch_regs) {
18683 			/* src == dst && dst != NULL => src != NULL */
18684 			if (reg_not_null(env, dst_reg) && type_may_be_null(src_reg->type))
18685 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
18686 			/* src == dst && src != NULL => dst != NULL */
18687 			if (reg_not_null(env, src_reg) && type_may_be_null(dst_reg->type))
18688 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
18689 		}
18690 	}
18691 
18692 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
18693 	 * Also does the same detection for a register whose the value is
18694 	 * known to be 0.
18695 	 * NOTE: these optimizations below are related with pointer comparison
18696 	 *       which will never be JMP32.
18697 	 */
18698 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
18699 	    type_may_be_null(dst_reg->type) &&
18700 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
18701 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
18702 		/*
18703 		 * For BPF_X the zero is a property of this execution path,
18704 		 * hence src_reg has to be precise.
18705 		 */
18706 		if (BPF_SRC(insn->code) == BPF_X) {
18707 			err = mark_chain_precision(env, insn->src_reg);
18708 			if (err)
18709 				return err;
18710 		}
18711 		/* Mark all identical registers in each branch as either
18712 		 * safe or unknown depending R == 0 or R != 0 conditional.
18713 		 */
18714 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
18715 				      opcode == BPF_JNE);
18716 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
18717 				      opcode == BPF_JEQ);
18718 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
18719 					   this_branch, other_branch) &&
18720 		   is_pointer_value(env, insn->dst_reg)) {
18721 		verbose(env, "R%d pointer comparison prohibited\n",
18722 			insn->dst_reg);
18723 		return -EACCES;
18724 	}
18725 	if (env->log.level & BPF_LOG_LEVEL)
18726 		print_insn_state(env, this_branch, this_branch->curframe);
18727 	return 0;
18728 }
18729 
18730 /* verify BPF_LD_IMM64 instruction */
18731 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
18732 {
18733 	struct bpf_insn_aux_data *aux = cur_aux(env);
18734 	struct bpf_reg_state *regs = cur_regs(env);
18735 	struct bpf_reg_state *dst_reg;
18736 	struct bpf_map *map;
18737 	int err;
18738 
18739 	if (BPF_SIZE(insn->code) != BPF_DW) {
18740 		verbose(env, "invalid BPF_LD_IMM insn\n");
18741 		return -EINVAL;
18742 	}
18743 
18744 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
18745 	if (err)
18746 		return err;
18747 
18748 	dst_reg = &regs[insn->dst_reg];
18749 	bpf_diag_mod_begin(env, dst_reg, NULL, BPF_DIAG_MOD_WRITE);
18750 	if (insn->src_reg == 0) {
18751 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
18752 
18753 		dst_reg->type = SCALAR_VALUE;
18754 		__mark_reg_known(&regs[insn->dst_reg], imm);
18755 		bpf_diag_mod_end(env);
18756 		return 0;
18757 	}
18758 
18759 	/* All special src_reg cases are listed below. From this point onwards
18760 	 * we either succeed and assign a corresponding dst_reg->type after
18761 	 * zeroing the offset, or fail and reject the program.
18762 	 */
18763 	mark_reg_known_zero(env, regs, insn->dst_reg);
18764 
18765 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
18766 		dst_reg->type = aux->btf_var.reg_type;
18767 		switch (base_type(dst_reg->type)) {
18768 		case PTR_TO_MEM:
18769 			dst_reg->mem_size = aux->btf_var.mem_size;
18770 			break;
18771 		case PTR_TO_BTF_ID:
18772 			dst_reg->btf = aux->btf_var.btf;
18773 			dst_reg->btf_id = aux->btf_var.btf_id;
18774 			break;
18775 		default:
18776 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
18777 			return -EFAULT;
18778 		}
18779 		bpf_diag_mod_end(env);
18780 		return 0;
18781 	}
18782 
18783 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
18784 		struct bpf_prog_aux *aux = env->prog->aux;
18785 		u32 subprogno = bpf_find_subprog(env,
18786 						 env->insn_idx + insn->imm + 1);
18787 
18788 		if (!aux->func_info) {
18789 			verbose(env, "missing btf func_info\n");
18790 			return -EINVAL;
18791 		}
18792 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
18793 			verbose(env, "callback function not static\n");
18794 			return -EINVAL;
18795 		}
18796 		/*
18797 		 * When env->subprog_cnt == 1 this instruction won't be rewritten
18798 		 * to hold a real function address. Assume that no usable program
18799 		 * combines e.g. main and timer callback and just reject here.
18800 		 */
18801 		if (subprogno == 0) {
18802 			verbose(env, "callback function cannot be the main program\n");
18803 			return -EINVAL;
18804 		}
18805 
18806 		dst_reg->type = PTR_TO_FUNC;
18807 		dst_reg->subprogno = subprogno;
18808 		bpf_diag_mod_end(env);
18809 		return 0;
18810 	}
18811 
18812 	map = env->used_maps[aux->map_index];
18813 
18814 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
18815 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
18816 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
18817 			__mark_reg_unknown(env, dst_reg);
18818 			dst_reg->map_ptr = map;
18819 			bpf_diag_mod_end(env);
18820 			return 0;
18821 		}
18822 		__mark_reg_known(dst_reg, aux->map_off);
18823 		dst_reg->type = PTR_TO_MAP_VALUE;
18824 		dst_reg->map_ptr = map;
18825 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
18826 			     map->max_entries != 1);
18827 		/* We want reg->id to be same (0) as map_value is not distinct */
18828 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
18829 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
18830 		dst_reg->type = CONST_PTR_TO_MAP;
18831 		dst_reg->map_ptr = map;
18832 	} else {
18833 		verifier_bug(env, "unexpected src reg value for ldimm64");
18834 		return -EFAULT;
18835 	}
18836 
18837 	bpf_diag_mod_end(env);
18838 	return 0;
18839 }
18840 
18841 static bool may_access_skb(enum bpf_prog_type type)
18842 {
18843 	switch (type) {
18844 	case BPF_PROG_TYPE_SOCKET_FILTER:
18845 	case BPF_PROG_TYPE_SCHED_CLS:
18846 	case BPF_PROG_TYPE_SCHED_ACT:
18847 		return true;
18848 	default:
18849 		return false;
18850 	}
18851 }
18852 
18853 /* verify safety of LD_ABS|LD_IND instructions:
18854  * - they can only appear in the programs where ctx == skb
18855  * - since they are wrappers of function calls, they scratch R1-R5 registers,
18856  *   preserve R6-R9, and store return value into R0
18857  *
18858  * Implicit input:
18859  *   ctx == skb == R6 == CTX
18860  *
18861  * Explicit input:
18862  *   SRC == any register
18863  *   IMM == 32-bit immediate
18864  *
18865  * Output:
18866  *   R0 - 8/16/32-bit skb data converted to cpu endianness
18867  */
18868 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
18869 {
18870 	struct bpf_verifier_state *state = env->cur_state;
18871 	struct bpf_reg_state *regs = cur_regs(env);
18872 	static const int ctx_reg = BPF_REG_6;
18873 	u8 mode = BPF_MODE(insn->code);
18874 	int i, err;
18875 
18876 	if (!may_access_skb(resolve_prog_type(env->prog))) {
18877 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
18878 		return -EINVAL;
18879 	}
18880 
18881 	for (i = state->curframe; i; i--) {
18882 		if (state->frame[i]->in_callback_fn) {
18883 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
18884 			return -EINVAL;
18885 		}
18886 	}
18887 
18888 	if (!env->ops->gen_ld_abs) {
18889 		verifier_bug(env, "gen_ld_abs is null");
18890 		return -EFAULT;
18891 	}
18892 
18893 	/* check whether implicit source operand (register R6) is readable */
18894 	err = check_reg_arg(env, ctx_reg, SRC_OP);
18895 	if (err)
18896 		return err;
18897 
18898 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
18899 	 * gen_ld_abs() may terminate the program at runtime, leading to
18900 	 * reference leak.
18901 	 */
18902 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
18903 	if (err)
18904 		return err;
18905 
18906 	if (regs[ctx_reg].type != PTR_TO_CTX) {
18907 		verbose(env,
18908 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
18909 		return -EINVAL;
18910 	}
18911 
18912 	if (mode == BPF_IND) {
18913 		/* check explicit source operand */
18914 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
18915 		if (err)
18916 			return err;
18917 	}
18918 
18919 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
18920 	if (err < 0)
18921 		return err;
18922 
18923 	/* reset caller saved regs to unreadable */
18924 	bpf_diag_record_caller_saved(env, regs);
18925 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
18926 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
18927 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
18928 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
18929 	}
18930 
18931 	/* mark destination R0 register as readable, since it contains
18932 	 * the value fetched from the packet.
18933 	 * Already marked as written above.
18934 	 */
18935 	mark_reg_unknown(env, regs, BPF_REG_0);
18936 	bpf_diag_mod_end(env);
18937 	/*
18938 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
18939 	 * which must be explored by the verifier when in a subprog.
18940 	 */
18941 	if (env->cur_state->curframe) {
18942 		struct bpf_verifier_state *branch;
18943 
18944 		mark_reg_scratched(env, BPF_REG_0);
18945 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
18946 		if (IS_ERR(branch))
18947 			return PTR_ERR(branch);
18948 		mark_reg_known_zero(env, regs, BPF_REG_0);
18949 		err = prepare_func_exit(env, &env->insn_idx);
18950 		if (err)
18951 			return err;
18952 		env->insn_idx--;
18953 	}
18954 	return 0;
18955 }
18956 
18957 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
18958 {
18959 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
18960 
18961 	/* Default return value range. */
18962 	*range = retval_range(0, 1);
18963 
18964 	switch (prog_type) {
18965 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
18966 		switch (env->prog->expected_attach_type) {
18967 		case BPF_CGROUP_UDP4_RECVMSG:
18968 		case BPF_CGROUP_UDP6_RECVMSG:
18969 		case BPF_CGROUP_UNIX_RECVMSG:
18970 		case BPF_CGROUP_INET4_GETPEERNAME:
18971 		case BPF_CGROUP_INET6_GETPEERNAME:
18972 		case BPF_CGROUP_UNIX_GETPEERNAME:
18973 		case BPF_CGROUP_INET4_GETSOCKNAME:
18974 		case BPF_CGROUP_INET6_GETSOCKNAME:
18975 		case BPF_CGROUP_UNIX_GETSOCKNAME:
18976 			*range = retval_range(1, 1);
18977 			break;
18978 		case BPF_CGROUP_INET4_BIND:
18979 		case BPF_CGROUP_INET6_BIND:
18980 			*range = retval_range(0, 3);
18981 			break;
18982 		default:
18983 			break;
18984 		}
18985 		break;
18986 	case BPF_PROG_TYPE_CGROUP_SKB:
18987 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
18988 			*range = retval_range(0, 3);
18989 		break;
18990 	case BPF_PROG_TYPE_CGROUP_SOCK:
18991 	case BPF_PROG_TYPE_SOCK_OPS:
18992 	case BPF_PROG_TYPE_CGROUP_DEVICE:
18993 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
18994 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
18995 		break;
18996 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18997 		if (!env->prog->aux->attach_btf_id)
18998 			return false;
18999 		*range = retval_range(0, 0);
19000 		break;
19001 	case BPF_PROG_TYPE_TRACING:
19002 		switch (env->prog->expected_attach_type) {
19003 		case BPF_TRACE_FENTRY:
19004 		case BPF_TRACE_FEXIT:
19005 		case BPF_TRACE_FSESSION:
19006 		case BPF_TRACE_FENTRY_MULTI:
19007 		case BPF_TRACE_FEXIT_MULTI:
19008 		case BPF_TRACE_FSESSION_MULTI:
19009 			*range = retval_range(0, 0);
19010 			break;
19011 		case BPF_TRACE_RAW_TP:
19012 		case BPF_MODIFY_RETURN:
19013 			return false;
19014 		case BPF_TRACE_ITER:
19015 		default:
19016 			break;
19017 		}
19018 		break;
19019 	case BPF_PROG_TYPE_KPROBE:
19020 		switch (env->prog->expected_attach_type) {
19021 		case BPF_TRACE_KPROBE_SESSION:
19022 		case BPF_TRACE_UPROBE_SESSION:
19023 			break;
19024 		default:
19025 			return false;
19026 		}
19027 		break;
19028 	case BPF_PROG_TYPE_SK_LOOKUP:
19029 		*range = retval_range(SK_DROP, SK_PASS);
19030 		break;
19031 
19032 	case BPF_PROG_TYPE_LSM:
19033 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
19034 			/* no range found, any return value is allowed */
19035 			if (!get_func_retval_range(env->prog, range))
19036 				return false;
19037 			/* no restricted range, any return value is allowed */
19038 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
19039 				return false;
19040 			range->return_32bit = true;
19041 		} else if (!env->prog->aux->attach_func_proto->type) {
19042 			/* Make sure programs that attach to void
19043 			 * hooks don't try to modify return value.
19044 			 */
19045 			*range = retval_range(1, 1);
19046 		}
19047 		break;
19048 
19049 	case BPF_PROG_TYPE_NETFILTER:
19050 		*range = retval_range(NF_DROP, NF_ACCEPT);
19051 		break;
19052 	case BPF_PROG_TYPE_STRUCT_OPS:
19053 		*range = retval_range(0, 0);
19054 		break;
19055 	case BPF_PROG_TYPE_EXT:
19056 		/* freplace program can return anything as its return value
19057 		 * depends on the to-be-replaced kernel func or bpf program.
19058 		 */
19059 	default:
19060 		return false;
19061 	}
19062 
19063 	/* Continue calculating. */
19064 
19065 	return true;
19066 }
19067 
19068 static bool program_returns_void(struct bpf_verifier_env *env)
19069 {
19070 	const struct bpf_prog *prog = env->prog;
19071 	enum bpf_prog_type prog_type = prog->type;
19072 
19073 	switch (prog_type) {
19074 	case BPF_PROG_TYPE_LSM:
19075 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
19076 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
19077 		    !prog->aux->attach_func_proto->type)
19078 			return true;
19079 		break;
19080 	case BPF_PROG_TYPE_STRUCT_OPS:
19081 		if (!prog->aux->attach_func_proto->type)
19082 			return true;
19083 		break;
19084 	case BPF_PROG_TYPE_EXT:
19085 		/*
19086 		 * If the actual program is an extension, let it
19087 		 * return void - attaching will succeed only if the
19088 		 * program being replaced also returns void, and since
19089 		 * it has passed verification its actual type doesn't matter.
19090 		 */
19091 		if (subprog_returns_void(env, 0))
19092 			return true;
19093 		break;
19094 	default:
19095 		break;
19096 	}
19097 	return false;
19098 }
19099 
19100 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
19101 {
19102 	const char *exit_ctx = "At program exit";
19103 	struct tnum enforce_attach_type_range = tnum_unknown;
19104 	const struct bpf_prog *prog = env->prog;
19105 	struct bpf_reg_state *reg = reg_state(env, regno);
19106 	struct bpf_retval_range range = retval_range(0, 1);
19107 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
19108 	struct bpf_func_state *frame = env->cur_state->frame[0];
19109 	const struct btf_type *reg_type, *ret_type = NULL;
19110 	int err;
19111 
19112 	/* LSM and struct_ops func-ptr's return type could be "void" */
19113 	if (!frame->in_async_callback_fn && program_returns_void(env))
19114 		return 0;
19115 
19116 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
19117 		/* Allow a struct_ops program to return a referenced kptr if it
19118 		 * matches the operator's return type and is in its unmodified
19119 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
19120 		 */
19121 		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
19122 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
19123 						prog->aux->attach_func_proto->type,
19124 						NULL);
19125 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
19126 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
19127 	}
19128 
19129 	/* eBPF calling convention is such that R0 is used
19130 	 * to return the value from eBPF program.
19131 	 * Make sure that it's readable at this time
19132 	 * of bpf_exit, which means that program wrote
19133 	 * something into it earlier
19134 	 */
19135 	err = check_reg_arg(env, regno, SRC_OP);
19136 	if (err)
19137 		return err;
19138 
19139 	if (is_pointer_value(env, regno)) {
19140 		verbose(env, "R%d leaks addr as return value\n", regno);
19141 		return -EACCES;
19142 	}
19143 
19144 	if (frame->in_async_callback_fn) {
19145 		exit_ctx = "At async callback return";
19146 		range = frame->callback_ret_range;
19147 		goto enforce_retval;
19148 	}
19149 
19150 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
19151 		return 0;
19152 
19153 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
19154 		enforce_attach_type_range = tnum_range(2, 3);
19155 
19156 	if (!return_retval_range(env, &range))
19157 		return 0;
19158 
19159 enforce_retval:
19160 	if (reg->type != SCALAR_VALUE) {
19161 		verbose(env, "%s the register R%d is not a known value (%s)\n",
19162 			exit_ctx, regno, reg_type_str(env, reg->type));
19163 		return -EINVAL;
19164 	}
19165 
19166 	err = mark_chain_precision(env, regno);
19167 	if (err)
19168 		return err;
19169 
19170 	if (!retval_range_within(range, reg)) {
19171 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
19172 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
19173 		    prog_type == BPF_PROG_TYPE_LSM &&
19174 		    !prog->aux->attach_func_proto->type)
19175 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
19176 		return -EINVAL;
19177 	}
19178 
19179 	if (!tnum_is_unknown(enforce_attach_type_range) &&
19180 	    tnum_in(enforce_attach_type_range, reg->var_off))
19181 		env->prog->enforce_expected_attach_type = 1;
19182 	return 0;
19183 }
19184 
19185 static int check_global_ret_scalar_reg(struct bpf_verifier_env *env, u32 regno)
19186 {
19187 	struct bpf_reg_state *reg;
19188 	int err;
19189 
19190 	err = check_reg_arg(env, regno, SRC_OP);
19191 	if (err)
19192 		return err;
19193 
19194 	/* Pointers to arena are safe to pass between subprograms. */
19195 	if (is_arena_reg(env, regno))
19196 		return 0;
19197 
19198 	if (is_pointer_value(env, regno)) {
19199 		verbose(env, "R%d leaks addr as return value\n", regno);
19200 		return -EACCES;
19201 	}
19202 
19203 	reg = reg_state(env, regno);
19204 	if (reg->type != SCALAR_VALUE) {
19205 		verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
19206 			regno, reg_type_str(env, reg->type));
19207 		return -EINVAL;
19208 	}
19209 
19210 	return 0;
19211 }
19212 
19213 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
19214 {
19215 	struct bpf_func_state *cur_frame = cur_func(env);
19216 	u32 subprog = cur_frame->subprogno;
19217 	u32 i, nregs;
19218 	int err;
19219 
19220 	if (subprog_returns_void(env, subprog))
19221 		return 0;
19222 
19223 	nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
19224 	for (i = 0; i < nregs; i++) {
19225 		err = check_global_ret_scalar_reg(env, ret_regs[i]);
19226 		if (err)
19227 			return err;
19228 	}
19229 
19230 	return 0;
19231 }
19232 
19233 /* Bitmask with 1s for all caller saved registers */
19234 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
19235 
19236 /* True if do_misc_fixups() replaces calls to helper number 'imm',
19237  * replacement patch is presumed to follow bpf_fastcall contract
19238  * (see mark_fastcall_pattern_for_call() below).
19239  */
19240 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
19241 {
19242 	switch (imm) {
19243 #ifdef CONFIG_X86_64
19244 	case BPF_FUNC_get_smp_processor_id:
19245 #ifdef CONFIG_SMP
19246 	case BPF_FUNC_get_current_task_btf:
19247 	case BPF_FUNC_get_current_task:
19248 #endif
19249 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
19250 #endif
19251 	default:
19252 		return false;
19253 	}
19254 }
19255 
19256 /* If @call is a kfunc or helper call, fills @cs and returns true,
19257  * otherwise returns false.
19258  */
19259 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
19260 			  struct bpf_call_summary *cs)
19261 {
19262 	struct bpf_call_arg_meta meta;
19263 	const struct bpf_func_proto *fn;
19264 	int i;
19265 
19266 	if (bpf_helper_call(call)) {
19267 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
19268 			/* error would be reported later */
19269 			return false;
19270 		cs->fastcall = fn->allow_fastcall &&
19271 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
19272 				bpf_jit_inlines_helper_call(call->imm));
19273 		cs->is_void = fn->ret_type == RET_VOID;
19274 		cs->arg_slot_cnt = 0;
19275 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
19276 			if (fn->arg_type[i] == ARG_UNUSED)
19277 				break;
19278 			cs->arg_slot_cnt++;
19279 		}
19280 		return true;
19281 	}
19282 
19283 	if (bpf_pseudo_kfunc_call(call)) {
19284 		int err;
19285 
19286 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
19287 		if (err < 0)
19288 			/* error would be reported later */
19289 			return false;
19290 		cs->arg_slot_cnt = btf_proto_slots(meta.btf, meta.func_proto);
19291 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
19292 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
19293 		return true;
19294 	}
19295 
19296 	return false;
19297 }
19298 
19299 /* LLVM define a bpf_fastcall function attribute.
19300  * This attribute means that function scratches only some of
19301  * the caller saved registers defined by ABI.
19302  * For BPF the set of such registers could be defined as follows:
19303  * - R0 is scratched only if function is non-void;
19304  * - R1-R5 are scratched only if corresponding parameter type is defined
19305  *   in the function prototype.
19306  *
19307  * The contract between kernel and clang allows to simultaneously use
19308  * such functions and maintain backwards compatibility with old
19309  * kernels that don't understand bpf_fastcall calls:
19310  *
19311  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
19312  *   registers are not scratched by the call;
19313  *
19314  * - as a post-processing step, clang visits each bpf_fastcall call and adds
19315  *   spill/fill for every live r0-r5;
19316  *
19317  * - stack offsets used for the spill/fill are allocated as lowest
19318  *   stack offsets in whole function and are not used for any other
19319  *   purposes;
19320  *
19321  * - when kernel loads a program, it looks for such patterns
19322  *   (bpf_fastcall function surrounded by spills/fills) and checks if
19323  *   spill/fill stack offsets are used exclusively in fastcall patterns;
19324  *
19325  * - if so, and if verifier or current JIT inlines the call to the
19326  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
19327  *   spill/fill pairs;
19328  *
19329  * - when old kernel loads a program, presence of spill/fill pairs
19330  *   keeps BPF program valid, albeit slightly less efficient.
19331  *
19332  * For example:
19333  *
19334  *   r1 = 1;
19335  *   r2 = 2;
19336  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19337  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
19338  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19339  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
19340  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
19341  *   r0 = r1;                            exit;
19342  *   r0 += r2;
19343  *   exit;
19344  *
19345  * The purpose of mark_fastcall_pattern_for_call is to:
19346  * - look for such patterns;
19347  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
19348  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
19349  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
19350  *   at which bpf_fastcall spill/fill stack slots start;
19351  * - update env->subprog_info[*]->keep_fastcall_stack.
19352  *
19353  * The .fastcall_pattern and .fastcall_stack_off are used by
19354  * check_fastcall_stack_contract() to check if every stack access to
19355  * fastcall spill/fill stack slot originates from spill/fill
19356  * instructions, members of fastcall patterns.
19357  *
19358  * If such condition holds true for a subprogram, fastcall patterns could
19359  * be rewritten by remove_fastcall_spills_fills().
19360  * Otherwise bpf_fastcall patterns are not changed in the subprogram
19361  * (code, presumably, generated by an older clang version).
19362  *
19363  * For example, it is *not* safe to remove spill/fill below:
19364  *
19365  *   r1 = 1;
19366  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19367  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19368  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
19369  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
19370  *   r0 += r1;                           exit;
19371  *   exit;
19372  *
19373  * Both uses of the marks assume that a pattern is entered at its first
19374  * spill and thus executes as a unit, hence a pattern is not grown past
19375  * an instruction targeted by a jump.
19376  */
19377 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
19378 					   struct bpf_subprog_info *subprog,
19379 					   int insn_idx, s16 lowest_off)
19380 {
19381 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
19382 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
19383 	u32 clobbered_regs_mask;
19384 	struct bpf_call_summary cs;
19385 	u32 expected_regs_mask;
19386 	s16 off;
19387 	int i;
19388 
19389 	if (!bpf_get_call_summary(env, call, &cs))
19390 		return;
19391 
19392 	/* A bitmask specifying which caller saved registers are clobbered
19393 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
19394 	 * bpf_fastcall contract:
19395 	 * - includes R0 if function is non-void;
19396 	 * - includes R1-R5 if corresponding parameter has is described
19397 	 *   in the function prototype.
19398 	 */
19399 	clobbered_regs_mask = GENMASK(cs.arg_slot_cnt, cs.is_void ? 1 : 0);
19400 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
19401 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
19402 
19403 	/* match pairs of form:
19404 	 *
19405 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
19406 	 * ...
19407 	 * call %[to_be_inlined]
19408 	 * ...
19409 	 * rX = *(u64 *)(r10 - Y)
19410 	 */
19411 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
19412 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
19413 			break;
19414 		/* stx/ldx/call must not be a jump targets, a jump to the first stx is fine */
19415 		if (bpf_is_jump_target(env, insn_idx - i + 1) ||
19416 		    bpf_is_jump_target(env, insn_idx + i))
19417 			break;
19418 		stx = &insns[insn_idx - i];
19419 		ldx = &insns[insn_idx + i];
19420 		/* must be a stack spill/fill pair */
19421 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19422 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
19423 		    stx->dst_reg != BPF_REG_10 ||
19424 		    ldx->src_reg != BPF_REG_10)
19425 			break;
19426 		/* must be a spill/fill for the same reg */
19427 		if (stx->src_reg != ldx->dst_reg)
19428 			break;
19429 		/* must be one of the previously unseen registers */
19430 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
19431 			break;
19432 		/* must be a spill/fill for the same expected offset,
19433 		 * no need to check offset alignment, BPF_DW stack access
19434 		 * is always 8-byte aligned.
19435 		 */
19436 		if (stx->off != off || ldx->off != off)
19437 			break;
19438 		expected_regs_mask &= ~BIT(stx->src_reg);
19439 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
19440 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
19441 	}
19442 	if (i == 1)
19443 		return;
19444 
19445 	/* Conditionally set 'fastcall_spills_num' to allow forward
19446 	 * compatibility when more helper functions are marked as
19447 	 * bpf_fastcall at compile time than current kernel supports, e.g:
19448 	 *
19449 	 *   1: *(u64 *)(r10 - 8) = r1
19450 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
19451 	 *   3: r1 = *(u64 *)(r10 - 8)
19452 	 *   4: *(u64 *)(r10 - 8) = r1
19453 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
19454 	 *   6: r1 = *(u64 *)(r10 - 8)
19455 	 *
19456 	 * There is no need to block bpf_fastcall rewrite for such program.
19457 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
19458 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
19459 	 * does not remove spill/fill pair {4,6}.
19460 	 */
19461 	if (cs.fastcall)
19462 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
19463 	else
19464 		subprog->keep_fastcall_stack = 1;
19465 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
19466 }
19467 
19468 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
19469 {
19470 	struct bpf_subprog_info *subprog = env->subprog_info;
19471 	struct bpf_insn *insn;
19472 	s16 lowest_off;
19473 	int s, i;
19474 
19475 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
19476 		/* find lowest stack spill offset used in this subprog */
19477 		lowest_off = 0;
19478 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19479 			insn = env->prog->insnsi + i;
19480 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19481 			    insn->dst_reg != BPF_REG_10)
19482 				continue;
19483 			lowest_off = min(lowest_off, insn->off);
19484 		}
19485 		/* use this offset to find fastcall patterns */
19486 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19487 			insn = env->prog->insnsi + i;
19488 			if (insn->code != (BPF_JMP | BPF_CALL))
19489 				continue;
19490 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
19491 		}
19492 	}
19493 	return 0;
19494 }
19495 
19496 static void adjust_btf_func(struct bpf_verifier_env *env)
19497 {
19498 	struct bpf_prog_aux *aux = env->prog->aux;
19499 	int i;
19500 
19501 	if (!aux->func_info)
19502 		return;
19503 
19504 	/* func_info is not available for hidden subprogs */
19505 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
19506 		aux->func_info[i].insn_off = env->subprog_info[i].start;
19507 }
19508 
19509 /* Find id in idset and increment its count, or add new entry */
19510 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
19511 {
19512 	u32 i;
19513 
19514 	for (i = 0; i < idset->num_ids; i++) {
19515 		if (idset->entries[i].id == id) {
19516 			idset->entries[i].cnt++;
19517 			return;
19518 		}
19519 	}
19520 	/* New id */
19521 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
19522 		idset->entries[idset->num_ids].id = id;
19523 		idset->entries[idset->num_ids].cnt = 1;
19524 		idset->num_ids++;
19525 	}
19526 }
19527 
19528 /* Find id in idset and return its count, or 0 if not found */
19529 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
19530 {
19531 	u32 i;
19532 
19533 	for (i = 0; i < idset->num_ids; i++) {
19534 		if (idset->entries[i].id == id)
19535 			return idset->entries[i].cnt;
19536 	}
19537 	return 0;
19538 }
19539 
19540 /*
19541  * Clear singular scalar ids in a state.
19542  * A register with a non-zero id is called singular if no other register shares
19543  * the same base id. Such registers can be treated as independent (id=0).
19544  */
19545 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
19546 			    struct bpf_verifier_state *st)
19547 {
19548 	struct bpf_idset *idset = &env->idset_scratch;
19549 	struct bpf_func_state *func;
19550 	struct bpf_reg_state *reg;
19551 
19552 	idset->num_ids = 0;
19553 
19554 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19555 		if (reg->type != SCALAR_VALUE)
19556 			continue;
19557 		if (!reg->id)
19558 			continue;
19559 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
19560 	}));
19561 
19562 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19563 		if (reg->type != SCALAR_VALUE)
19564 			continue;
19565 		if (!reg->id)
19566 			continue;
19567 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
19568 			clear_scalar_id(reg);
19569 	}));
19570 }
19571 
19572 /* Return true if it's OK to have the same insn return a different type. */
19573 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19574 {
19575 	switch (base_type(type)) {
19576 	case PTR_TO_CTX:
19577 	case PTR_TO_SOCKET:
19578 	case PTR_TO_SOCK_COMMON:
19579 	case PTR_TO_TCP_SOCK:
19580 	case PTR_TO_XDP_SOCK:
19581 	case PTR_TO_BTF_ID:
19582 	case PTR_TO_ARENA:
19583 		return false;
19584 	case PTR_TO_MEM:
19585 		return !bpf_may_fault_on_deref(type);
19586 	default:
19587 		return true;
19588 	}
19589 }
19590 
19591 /* If an instruction was previously used with particular pointer types, then we
19592  * need to be careful to avoid cases such as the below, where it may be ok
19593  * for one branch accessing the pointer, but not ok for the other branch:
19594  *
19595  * R1 = sock_ptr
19596  * goto X;
19597  * ...
19598  * R1 = some_other_valid_ptr;
19599  * goto X;
19600  * ...
19601  * R2 = *(u32 *)(R1 + 0);
19602  */
19603 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19604 {
19605 	return src != prev && (!reg_type_mismatch_ok(src) ||
19606 			       !reg_type_mismatch_ok(prev));
19607 }
19608 
19609 static bool is_ptr_to_mem(enum bpf_reg_type type)
19610 {
19611 	return base_type(type) == PTR_TO_MEM;
19612 }
19613 
19614 static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a,
19615 					 enum bpf_reg_type type_b)
19616 {
19617 	bool to_mem = is_ptr_to_mem(type_a) || is_ptr_to_mem(type_b);
19618 	enum bpf_reg_type type_merged = to_mem ? PTR_TO_MEM : PTR_TO_BTF_ID;
19619 
19620 	if (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b))
19621 		type_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED :
19622 					PTR_UNTRUSTED;
19623 	else
19624 		type_merged |= ((type_a | type_b) & MEM_RDONLY);
19625 	return type_merged;
19626 }
19627 
19628 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19629 			     bool allow_trust_mismatch)
19630 {
19631 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19632 
19633 	if (*prev_type == NOT_INIT) {
19634 		/* Saw a valid insn
19635 		 * dst_reg = *(u32 *)(src_reg + off)
19636 		 * save type to validate intersecting paths
19637 		 */
19638 		*prev_type = type;
19639 	} else if (reg_type_mismatch(type, *prev_type)) {
19640 		/* Abuser program is trying to use the same insn
19641 		 * dst_reg = *(u32*) (src_reg + off)
19642 		 * with different pointer types:
19643 		 * src_reg == ctx in one branch and
19644 		 * src_reg == stack|map in some other branch.
19645 		 * Reject it.
19646 		 */
19647 		if (allow_trust_mismatch &&
19648 		    bpf_is_ptr_to_mem_or_btf_id(type) &&
19649 		    bpf_is_ptr_to_mem_or_btf_id(*prev_type)) {
19650 			/*
19651 			 * Have to support a use case when one path through
19652 			 * the program yields a TRUSTED pointer while another
19653 			 * is UNTRUSTED. Merge them into a type which keeps
19654 			 * the BPF_PROBE_MEM/BPF_PROBE_MEMSX rewrite when
19655 			 * either side needs it.
19656 			 */
19657 			*prev_type = merge_ptr_types(type, *prev_type);
19658 		} else {
19659 			verbose(env, "same insn cannot be used with different pointers\n");
19660 			return -EINVAL;
19661 		}
19662 	}
19663 
19664 	return 0;
19665 }
19666 
19667 enum {
19668 	PROCESS_BPF_EXIT = 1,
19669 	INSN_IDX_UPDATED = 2,
19670 };
19671 
19672 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19673 				 bool *do_print_state,
19674 				 bool exception_exit)
19675 {
19676 	struct bpf_func_state *cur_frame = cur_func(env);
19677 
19678 	/* We must do check_reference_leak here before
19679 	 * prepare_func_exit to handle the case when
19680 	 * state->curframe > 0, it may be a callback function,
19681 	 * for which reference_state must match caller reference
19682 	 * state when it exits.
19683 	 */
19684 	int err = check_resource_leak(env, exception_exit,
19685 				      exception_exit || !env->cur_state->curframe,
19686 				      exception_exit ? "bpf_throw" :
19687 				      "BPF_EXIT instruction in main prog");
19688 	if (err)
19689 		return err;
19690 
19691 	/* The side effect of the prepare_func_exit which is
19692 	 * being skipped is that it frees bpf_func_state.
19693 	 * Typically, process_bpf_exit will only be hit with
19694 	 * outermost exit. copy_verifier_state in pop_stack will
19695 	 * handle freeing of any extra bpf_func_state left over
19696 	 * from not processing all nested function exits. We
19697 	 * also skip return code checks as they are not needed
19698 	 * for exceptional exits.
19699 	 */
19700 	if (exception_exit)
19701 		return PROCESS_BPF_EXIT;
19702 
19703 	if (env->cur_state->curframe) {
19704 		/* exit from nested function */
19705 		err = prepare_func_exit(env, &env->insn_idx);
19706 		if (err)
19707 			return err;
19708 		*do_print_state = true;
19709 		return INSN_IDX_UPDATED;
19710 	}
19711 
19712 	/*
19713 	 * Return from a regular global subprogram differs from return
19714 	 * from the main program or async/exception callback.
19715 	 * Main program exit implies return code restrictions
19716 	 * that depend on program type.
19717 	 * Exit from exception callback is equivalent to main program exit.
19718 	 * Exit from async callback implies return code restrictions
19719 	 * that depend on async scheduling mechanism.
19720 	 */
19721 	if (cur_frame->subprogno &&
19722 	    !cur_frame->in_async_callback_fn &&
19723 	    !cur_frame->in_exception_callback_fn)
19724 		err = check_global_subprog_return_code(env);
19725 	else
19726 		err = check_return_code(env, BPF_REG_0, "R0");
19727 	if (err)
19728 		return err;
19729 	return PROCESS_BPF_EXIT;
19730 }
19731 
19732 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
19733 				       int regno,
19734 				       struct bpf_map *map,
19735 				       u32 *pmin_index, u32 *pmax_index)
19736 {
19737 	struct bpf_reg_state *reg = reg_state(env, regno);
19738 	u64 min_index = reg_umin(reg);
19739 	u64 max_index = reg_umax(reg);
19740 	const u32 size = 8;
19741 
19742 	if (min_index > (u64) U32_MAX * size) {
19743 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
19744 		return -ERANGE;
19745 	}
19746 	if (max_index > (u64) U32_MAX * size) {
19747 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
19748 		return -ERANGE;
19749 	}
19750 
19751 	min_index /= size;
19752 	max_index /= size;
19753 
19754 	if (max_index >= map->max_entries) {
19755 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
19756 			     regno, min_index, max_index, map->max_entries);
19757 		return -EINVAL;
19758 	}
19759 
19760 	*pmin_index = min_index;
19761 	*pmax_index = max_index;
19762 	return 0;
19763 }
19764 
19765 static int reject_gotox_out_of_subprog(struct bpf_verifier_env *env, u32 target,
19766 				       u32 subprog_start, u32 subprog_end)
19767 {
19768 	verbose(env, "indirect jump from insn %d to %u leaves the subprog [%u,%u)\n",
19769 		env->insn_idx, target, subprog_start, subprog_end);
19770 	bpf_diag_program_structure(
19771 		env, env->insn_idx, "indirect jump leaves subprogram",
19772 		"Keep every reachable jump-table target inside the subprogram of the indirect jump.",
19773 		"Instruction %d can jump indirectly to instruction %u, which is outside its own subprogram [%u,%u).",
19774 		env->insn_idx, target, subprog_start, subprog_end);
19775 	return -EINVAL;
19776 }
19777 
19778 /* gotox *dst_reg */
19779 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
19780 {
19781 	struct bpf_verifier_state *other_branch;
19782 	struct bpf_subprog_info *subprog;
19783 	u32 subprog_start, subprog_end;
19784 	struct bpf_reg_state *dst_reg;
19785 	struct bpf_map *map;
19786 	u32 min_index, max_index;
19787 	int err = 0;
19788 	int n;
19789 	int i;
19790 
19791 	dst_reg = reg_state(env, insn->dst_reg);
19792 	if (dst_reg->type != PTR_TO_INSN) {
19793 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
19794 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
19795 		return -EINVAL;
19796 	}
19797 
19798 	map = dst_reg->map_ptr;
19799 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
19800 		return -EFAULT;
19801 
19802 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
19803 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
19804 		return -EFAULT;
19805 
19806 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
19807 	if (err)
19808 		return err;
19809 
19810 	/* Ensure that the buffer is large enough */
19811 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
19812 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
19813 						        max_index - min_index + 1);
19814 		if (!env->gotox_tmp_buf)
19815 			return -ENOMEM;
19816 	}
19817 
19818 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
19819 	if (n < 0)
19820 		return n;
19821 	if (n == 0) {
19822 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
19823 			     insn->dst_reg, map->id);
19824 		return -EINVAL;
19825 	}
19826 
19827 	subprog = bpf_find_containing_subprog(env, env->insn_idx);
19828 	if (verifier_bug_if(!subprog, env, "no subprog contains insn %d", env->insn_idx))
19829 		return -EFAULT;
19830 	subprog_start = subprog->start;
19831 	subprog_end = (subprog + 1)->start;
19832 
19833 	/*
19834 	 * Maps are confined to a subprog, see compute_subprog_jts(), and the
19835 	 * targets are sorted and free of duplicates, see sort_insn_array_uniq(),
19836 	 * so either all of them belong to this subprog or none of them does.
19837 	 */
19838 	if (env->gotox_tmp_buf->items[0] < subprog_start)
19839 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[0],
19840 						   subprog_start, subprog_end);
19841 	if (env->gotox_tmp_buf->items[n - 1] >= subprog_end)
19842 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[n - 1],
19843 						   subprog_start, subprog_end);
19844 
19845 	for (i = 0; i < n - 1; i++) {
19846 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
19847 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
19848 					  env->insn_idx, env->cur_state->speculative);
19849 		if (IS_ERR(other_branch))
19850 			return PTR_ERR(other_branch);
19851 	}
19852 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
19853 	mark_indirect_target(env, env->insn_idx);
19854 	return INSN_IDX_UPDATED;
19855 }
19856 
19857 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19858 {
19859 	int err;
19860 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19861 	u8 class = BPF_CLASS(insn->code);
19862 
19863 	switch (class) {
19864 	case BPF_ALU:
19865 	case BPF_ALU64:
19866 		return check_alu_op(env, insn);
19867 
19868 	case BPF_LDX:
19869 		return check_load_mem(env, insn, false,
19870 				      BPF_MODE(insn->code) == BPF_MEMSX,
19871 				      true, "ldx");
19872 
19873 	case BPF_STX:
19874 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
19875 			return check_atomic(env, insn);
19876 		return check_store_reg(env, insn, false);
19877 
19878 	case BPF_ST: {
19879 		/* Handle stack arg write (store immediate) */
19880 		if (is_stack_arg_st(insn)) {
19881 			struct bpf_verifier_state *vstate = env->cur_state;
19882 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
19883 
19884 			return check_stack_arg_write(env, state, insn->off, NULL);
19885 		}
19886 
19887 		struct bpf_reg_state arena, *dst_reg;
19888 		enum bpf_reg_type dst_reg_type;
19889 
19890 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19891 		if (err)
19892 			return err;
19893 
19894 		dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
19895 		dst_reg_type = dst_reg->type;
19896 
19897 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
19898 				       insn->off, BPF_SIZE(insn->code),
19899 				       BPF_WRITE, -1, false, false);
19900 		if (err)
19901 			return err;
19902 
19903 		return save_aux_ptr_type(env, dst_reg_type, false);
19904 	}
19905 	case BPF_JMP:
19906 	case BPF_JMP32: {
19907 		u8 opcode = BPF_OP(insn->code);
19908 
19909 		env->jmps_processed++;
19910 		if (opcode == BPF_CALL) {
19911 			if (env->cur_state->active_locks) {
19912 				/* similar to static subprog calls callx is allowed under a lock */
19913 				if (!bpf_is_callx(insn) &&
19914 				    ((insn->src_reg == BPF_REG_0 &&
19915 				      insn->imm != BPF_FUNC_spin_unlock &&
19916 				      insn->imm != BPF_FUNC_kptr_xchg) ||
19917 				     (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19918 				      !kfunc_spin_allowed(env, insn->imm, insn->off)))) {
19919 					verbose(env,
19920 						"function calls are not allowed while holding a lock\n");
19921 					bpf_diag_ctx_active(
19922 						env, env->insn_idx,
19923 						"function call", BPF_DIAG_CONTEXT_LOCK,
19924 						"Release the BPF spin lock before making this call, or move the call outside the locked region.");
19925 					return -EINVAL;
19926 				}
19927 			}
19928 			mark_reg_scratched(env, BPF_REG_0);
19929 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
19930 				cur_func(env)->no_stack_arg_load = true;
19931 			if (bpf_is_callx(insn))
19932 				return check_func_callx(env, insn, &env->insn_idx);
19933 			if (insn->src_reg == BPF_PSEUDO_CALL)
19934 				return check_func_call(env, insn, &env->insn_idx);
19935 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
19936 				return check_kfunc_call(env, insn, &env->insn_idx);
19937 			return check_helper_call(env, insn, &env->insn_idx);
19938 		} else if (opcode == BPF_JA) {
19939 			if (BPF_SRC(insn->code) == BPF_X)
19940 				return check_indirect_jump(env, insn);
19941 
19942 			if (class == BPF_JMP)
19943 				env->insn_idx += insn->off + 1;
19944 			else
19945 				env->insn_idx += insn->imm + 1;
19946 			return INSN_IDX_UPDATED;
19947 		} else if (opcode == BPF_EXIT) {
19948 			return process_bpf_exit_full(env, do_print_state, false);
19949 		}
19950 		return check_cond_jmp_op(env, insn, &env->insn_idx);
19951 	}
19952 	case BPF_LD: {
19953 		u8 mode = BPF_MODE(insn->code);
19954 
19955 		if (mode == BPF_ABS || mode == BPF_IND)
19956 			return check_ld_abs(env, insn);
19957 
19958 		if (mode == BPF_IMM) {
19959 			err = check_ld_imm(env, insn);
19960 			if (err)
19961 				return err;
19962 
19963 			env->insn_idx++;
19964 			sanitize_mark_insn_seen(env);
19965 		}
19966 		return 0;
19967 	}
19968 	}
19969 	/* all class values are handled above. silence compiler warning */
19970 	return -EFAULT;
19971 }
19972 
19973 /*
19974  * Push the loop entered at insn_idx onto the stack. Usually this adds a single
19975  * entry on top of its enclosing loop. However, an edge may enter an inner loop
19976  * directly, bypassing the header(s) of its enclosing loop(s), e.g.:
19977  *
19978  *   1: for (...):       // enclosing loop, header at 1
19979  *   2:   for (...):     // inner loop, header at 2
19980  *        ...
19981  *   3: if ...:
19982  *        goto 2b;       // enters loop 2 without going through header 1
19983  *
19984  * Such a bypass makes the enclosing loop irreducible, so its header is missing
19985  * from the stack and both headers (1) and (2) need to be pushed onto stack.
19986  * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
19987  * the bypassed ancestors are irreducible and pushed as non-terminating.
19988  *
19989  * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
19990  * of the bpf_loop_at_index(env->insn_idx) and whatever was at the top of the loop stack.
19991  */
19992 static int loop_stack_push(struct bpf_verifier_env *env, bool *pushed)
19993 {
19994 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
19995 	struct bpf_func_state *frame = cur_func(env);
19996 	struct loop_stack_entry *loop_stack = frame->loop_stack;
19997 	u32 missing_headers[LOOP_STACK_SIZE];
19998 	u32 cnt = frame->loop_stack_cnt;
19999 	u32 num_missing = 0;
20000 	int h;
20001 
20002 	*pushed = false;
20003 
20004 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
20005 		if (cnt && loop_stack[cnt - 1].loop_id == h)
20006 			break;
20007 		if (num_missing == LOOP_STACK_SIZE)
20008 			goto e2big;
20009 		missing_headers[num_missing] = h;
20010 	}
20011 
20012 	if (num_missing == 0)
20013 		return 0;
20014 	if (cnt + num_missing > LOOP_STACK_SIZE)
20015 		goto e2big;
20016 	frame->loop_stack = realloc_array(frame->loop_stack, cnt, cnt + num_missing,
20017 					 sizeof(*frame->loop_stack));
20018 	if (!frame->loop_stack)
20019 		return -ENOMEM;
20020 	loop_stack = frame->loop_stack;
20021 
20022 	for (; num_missing; num_missing--, cnt++) {
20023 		h = missing_headers[num_missing - 1];
20024 		loop_stack[cnt] = (struct loop_stack_entry){ .loop_id = h };
20025 		if (env->log.level & BPF_LOG_LEVEL2)
20026 			verbose(env, "entering loop %d\n", h);
20027 		*pushed = true;
20028 	}
20029 	frame->loop_stack_cnt = cnt;
20030 	return 0;
20031 
20032 e2big:
20033 	verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
20034 	return -E2BIG;
20035 }
20036 
20037 /*
20038  * An exit from a loop can cross several nested loops, e.g.:
20039  *
20040  *   1: for (...):
20041  *   2:   for (...):
20042  *   3:     for (...):
20043  *            if ...:    // before goto the loop stack is [1, 2, 3 <top>]
20044  *              goto 1b; // after goto it should become [1]
20045  */
20046 static int loop_stack_pop(struct bpf_verifier_env *env)
20047 {
20048 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20049 	struct bpf_func_state *frame = cur_func(env);
20050 	int new_cnt = 0;
20051 	int h, i;
20052 
20053 	/*
20054 	 * Walk the loop nest of insn_idx outwards (innermost first) and stop at
20055 	 * the first loop that is present on the stack - that loop is the common
20056 	 * ancestor and becomes the new top. If no enclosing loop is on the
20057 	 * stack, drop all loops.
20058 	 */
20059 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
20060 		for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
20061 			if (frame->loop_stack[i].loop_id == h) {
20062 				new_cnt = i + 1;
20063 				goto pop;
20064 			}
20065 		}
20066 	}
20067 
20068 pop:
20069 	if (env->log.level & BPF_LOG_LEVEL2)
20070 		for (i = frame->loop_stack_cnt - 1; i >= new_cnt; i--)
20071 			verbose(env, "exiting loop %d\n", frame->loop_stack[i].loop_id);
20072 	frame->loop_stack_cnt = new_cnt;
20073 	return 0;
20074 }
20075 
20076 static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
20077 {
20078 	struct bpf_func_state *frame = cur_func(env);
20079 	struct loop_stack_entry *entry;
20080 
20081 	if (frame->loop_stack_cnt == 0) {
20082 		verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
20083 		return -EFAULT;
20084 	}
20085 
20086 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20087 	if (!entry->terminates)
20088 		return 0;
20089 
20090 	return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state,
20091 				   entry->max_header_count);
20092 }
20093 
20094 static int handle_loop_entry_exit(struct bpf_verifier_env *env)
20095 {
20096 	struct bpf_verifier_state *cur = env->cur_state;
20097 	struct bpf_func_state *frame = cur_func(env);
20098 	struct loop_stack_entry *entry;
20099 	struct bpf_loop_iters iters;
20100 	bool pushed, terminates;
20101 	int err;
20102 
20103 	err = loop_stack_pop(env);
20104 	if (err)
20105 		return err;
20106 
20107 	err = loop_stack_push(env, &pushed);
20108 	if (err)
20109 		return err;
20110 
20111 	if (frame->loop_stack_cnt == 0)
20112 		return 0;
20113 
20114 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20115 	if (env->insn_idx != entry->loop_id)
20116 		return 0;
20117 
20118 	/* If nothing was pushed and env->insn_idx is a loop header, we've taken a backedge. */
20119 	if (!pushed)
20120 		return maybe_clamp_scev_regs(env);
20121 
20122 	err = bpf_compute_loop_iters(env, env->cur_state, &iters);
20123 	if (err < 0)
20124 		return err;
20125 
20126 	terminates = err == 1;
20127 	if (!terminates)
20128 		return 0;
20129 
20130 	/* Create a loop_entry checkpoint before widening */
20131 	err = bpf_split_cur_state(env);
20132 	if (err)
20133 		return err;
20134 
20135 	entry->min_header_count = iters.min_header_count;
20136 	entry->max_header_count = iters.max_header_count;
20137 	entry->entry_state = cur->parent;
20138 	entry->terminates = true;
20139 	err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
20140 	if (err < 0)
20141 		return err;
20142 	return 0;
20143 }
20144 
20145 static int do_check(struct bpf_verifier_env *env)
20146 {
20147 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20148 	struct bpf_verifier_state *state = env->cur_state;
20149 	struct bpf_insn *insns = env->prog->insnsi;
20150 	int insn_cnt = env->prog->len;
20151 	bool do_print_state = false;
20152 	int prev_insn_idx = -1;
20153 
20154 	for (;;) {
20155 		struct bpf_insn *insn;
20156 		struct bpf_insn_aux_data *insn_aux;
20157 		int err;
20158 
20159 		if (signal_pending(current))
20160 			return -EAGAIN;
20161 
20162 		if (need_resched())
20163 			cond_resched();
20164 
20165 		/* reset current history entry on each new instruction */
20166 		env->cur_hist_ent = NULL;
20167 
20168 		env->prev_insn_idx = prev_insn_idx;
20169 		if (env->insn_idx >= insn_cnt) {
20170 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20171 				env->insn_idx, insn_cnt);
20172 			return -EFAULT;
20173 		}
20174 
20175 		insn = &insns[env->insn_idx];
20176 		insn_aux = &env->insn_aux_data[env->insn_idx];
20177 
20178 		account_processed_insn(env);
20179 
20180 		if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20181 			verbose(env,
20182 				"BPF program is too large. Processed %d insn\n",
20183 				env->insn_processed);
20184 			return -E2BIG;
20185 		}
20186 
20187 		state->last_insn_idx = env->prev_insn_idx;
20188 		state->insn_idx = env->insn_idx;
20189 		/*
20190 		 * Record the incoming edge so active and queued paths use the same
20191 		 * branch-recording path. A zero-offset conditional has identical
20192 		 * successors, so its outcome cannot be reconstructed from the edge.
20193 		 */
20194 		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
20195 			struct bpf_insn *prev_insn = &insns[prev_insn_idx];
20196 			int fallthrough_idx = prev_insn_idx + 1;
20197 			int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1;
20198 			u8 class = BPF_CLASS(prev_insn->code);
20199 			u8 opcode = BPF_OP(prev_insn->code);
20200 
20201 			if ((class == BPF_JMP || class == BPF_JMP32) &&
20202 			    opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT &&
20203 			    opcode <= BPF_JCOND && branch_idx != fallthrough_idx) {
20204 				if (env->insn_idx == branch_idx)
20205 					bpf_diag_record_branch(env, prev_insn_idx, true);
20206 				else if (env->insn_idx == fallthrough_idx)
20207 					bpf_diag_record_branch(env, prev_insn_idx, false);
20208 			}
20209 		}
20210 
20211 		/*
20212 		 * Possibly widen the registers before creating a checkpoint
20213 		 * in bpf_is_state_visited(). The next loop iteration will
20214 		 * have a chance to hit this checkpoint and converge.
20215 		 */
20216 		err = handle_loop_entry_exit(env);
20217 		if (err)
20218 			return err;
20219 
20220 		if (bpf_is_prune_point(env, env->insn_idx)) {
20221 			err = bpf_is_state_visited(env, env->insn_idx);
20222 			if (err < 0)
20223 				return err;
20224 			if (err == 1) {
20225 				/* found equivalent state, can prune the search */
20226 				if (env->log.level & BPF_LOG_LEVEL) {
20227 					if (do_print_state)
20228 						verbose(env, "\nfrom %d to %d%s: safe\n",
20229 							env->prev_insn_idx, env->insn_idx,
20230 							env->cur_state->speculative ?
20231 							" (speculative execution)" : "");
20232 					else
20233 						verbose(env, "%d: safe\n", env->insn_idx);
20234 				}
20235 				goto process_bpf_exit;
20236 			}
20237 		}
20238 
20239 		if (bpf_is_jmp_point(env, env->insn_idx)) {
20240 			err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
20241 			if (err)
20242 				return err;
20243 		}
20244 
20245 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20246 			verbose(env, "\nfrom %d to %d%s:",
20247 				env->prev_insn_idx, env->insn_idx,
20248 				env->cur_state->speculative ?
20249 				" (speculative execution)" : "");
20250 			print_verifier_state(env, state, state->curframe, true);
20251 			do_print_state = false;
20252 		}
20253 
20254 		if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
20255 		    cur_func(env)->loop_stack_cnt == 0) {
20256 			verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
20257 				     env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
20258 			return -EFAULT;
20259 		}
20260 
20261 		if (env->log.level & BPF_LOG_LEVEL) {
20262 			if (verifier_state_scratched(env))
20263 				print_insn_state(env, state, state->curframe);
20264 
20265 			verbose_linfo(env, env->insn_idx, "; ");
20266 			env->prev_log_pos = env->log.end_pos;
20267 			verbose(env, "%d: ", env->insn_idx);
20268 			bpf_verbose_insn(env, insn);
20269 			verbose(env, "\n");
20270 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20271 			env->prev_log_pos = env->log.end_pos;
20272 		}
20273 
20274 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20275 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20276 							   env->prev_insn_idx);
20277 			if (err)
20278 				return err;
20279 		}
20280 
20281 		sanitize_mark_insn_seen(env);
20282 		prev_insn_idx = env->insn_idx;
20283 
20284 		/* Sanity check: precomputed constants must match verifier state */
20285 		if (!state->speculative && insn_aux->const_reg_mask) {
20286 			struct bpf_reg_state *regs = cur_regs(env);
20287 			u16 mask = insn_aux->const_reg_mask;
20288 
20289 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
20290 				u32 cval = insn_aux->const_reg_vals[r];
20291 
20292 				if (!(mask & BIT(r)))
20293 					continue;
20294 				if (regs[r].type != SCALAR_VALUE)
20295 					continue;
20296 				if (!tnum_is_const(regs[r].var_off))
20297 					continue;
20298 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
20299 						    env, "const R%d: %u != %llu",
20300 						    r, cval, regs[r].var_off.value))
20301 					return -EFAULT;
20302 			}
20303 		}
20304 
20305 		/* Reduce verification complexity by stopping speculative path
20306 		 * verification when a nospec is encountered.
20307 		 */
20308 		if (state->speculative && insn_aux->nospec)
20309 			goto process_bpf_exit;
20310 
20311 		err = do_check_insn(env, &do_print_state);
20312 		if (error_recoverable_with_nospec(err) && state->speculative) {
20313 			/* Prevent this speculative path from ever reaching the
20314 			 * insn that would have been unsafe to execute.
20315 			 */
20316 			insn_aux->nospec = true;
20317 			/* If it was an ADD/SUB insn, potentially remove any
20318 			 * markings for alu sanitization.
20319 			 */
20320 			insn_aux->alu_state = 0;
20321 			goto process_bpf_exit;
20322 		} else if (err < 0) {
20323 			return err;
20324 		} else if (err == PROCESS_BPF_EXIT) {
20325 			goto process_bpf_exit;
20326 		} else if (err == INSN_IDX_UPDATED) {
20327 		} else if (err == 0) {
20328 			env->insn_idx++;
20329 		}
20330 
20331 		if (state->speculative && insn_aux->nospec_result) {
20332 			/* If we are on a path that performed a jump-op, this
20333 			 * may skip a nospec patched-in after the jump. This can
20334 			 * currently never happen because nospec_result is only
20335 			 * used for the write-ops
20336 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
20337 			 * calls. These must never skip the following insn
20338 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
20339 			 * is false). Still, add a warning to document this in
20340 			 * case nospec_result is used elsewhere in the future.
20341 			 *
20342 			 * All non-branch instructions have a single
20343 			 * fall-through edge. For these, nospec_result should
20344 			 * already work.
20345 			 */
20346 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
20347 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
20348 					    BPF_OP(insn->code) != BPF_CALL, env,
20349 					    "speculation barrier after jump instruction may not have the desired effect"))
20350 				return -EFAULT;
20351 process_bpf_exit:
20352 			account_current_path(env);
20353 			mark_verifier_state_scratched(env);
20354 			err = bpf_update_branch_counts(env, env->cur_state);
20355 			if (err)
20356 				return err;
20357 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20358 					pop_log);
20359 			if (err < 0) {
20360 				if (err != -ENOENT)
20361 					return err;
20362 				break;
20363 			} else {
20364 				do_print_state = true;
20365 				continue;
20366 			}
20367 		}
20368 	}
20369 
20370 	return 0;
20371 }
20372 
20373 static int find_btf_percpu_datasec(struct btf *btf)
20374 {
20375 	const struct btf_type *t;
20376 	const char *tname;
20377 	int i, n;
20378 
20379 	/*
20380 	 * Both vmlinux and module each have their own ".data..percpu"
20381 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20382 	 * types to look at only module's own BTF types.
20383 	 */
20384 	n = btf_nr_types(btf);
20385 	for (i = btf_named_start_id(btf, true); i < n; i++) {
20386 		t = btf_type_by_id(btf, i);
20387 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20388 			continue;
20389 
20390 		tname = btf_name_by_offset(btf, t->name_off);
20391 		if (!strcmp(tname, ".data..percpu"))
20392 			return i;
20393 	}
20394 
20395 	return -ENOENT;
20396 }
20397 
20398 /*
20399  * Add btf to the env->used_btfs array. If needed, refcount the
20400  * corresponding kernel module. To simplify caller's logic
20401  * in case of error or if btf was added before the function
20402  * decreases the btf refcount.
20403  */
20404 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20405 {
20406 	struct btf_mod_pair *btf_mod;
20407 	int ret = 0;
20408 	int i;
20409 
20410 	/* check whether we recorded this BTF (and maybe module) already */
20411 	for (i = 0; i < env->used_btf_cnt; i++)
20412 		if (env->used_btfs[i].btf == btf)
20413 			goto ret_put;
20414 
20415 	if (env->signature) {
20416 		verbose(env, "signed program cannot bind any BTF\n");
20417 		ret = -EACCES;
20418 		goto ret_put;
20419 	}
20420 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20421 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20422 			MAX_USED_BTFS);
20423 		ret = -E2BIG;
20424 		goto ret_put;
20425 	}
20426 
20427 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20428 	btf_mod->btf = btf;
20429 	btf_mod->module = NULL;
20430 
20431 	/* if we reference variables from kernel module, bump its refcount */
20432 	if (btf_is_module(btf)) {
20433 		btf_mod->module = btf_try_get_module(btf);
20434 		if (!btf_mod->module) {
20435 			ret = -ENXIO;
20436 			goto ret_put;
20437 		}
20438 	}
20439 
20440 	env->used_btf_cnt++;
20441 	return 0;
20442 
20443 ret_put:
20444 	/* Either error or this BTF was already added */
20445 	btf_put(btf);
20446 	return ret;
20447 }
20448 
20449 /* replace pseudo btf_id with kernel symbol address */
20450 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20451 				 struct bpf_insn *insn,
20452 				 struct bpf_insn_aux_data *aux,
20453 				 struct btf *btf)
20454 {
20455 	const struct btf_var_secinfo *vsi;
20456 	const struct btf_type *datasec;
20457 	const struct btf_type *t;
20458 	const char *sym_name;
20459 	bool percpu = false;
20460 	u32 type, id = insn->imm;
20461 	s32 datasec_id;
20462 	u64 addr;
20463 	int i;
20464 
20465 	t = btf_type_by_id(btf, id);
20466 	if (!t) {
20467 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20468 		return -ENOENT;
20469 	}
20470 
20471 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20472 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20473 		return -EINVAL;
20474 	}
20475 
20476 	sym_name = btf_name_by_offset(btf, t->name_off);
20477 	addr = kallsyms_lookup_name(sym_name);
20478 	if (!addr) {
20479 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20480 			sym_name);
20481 		return -ENOENT;
20482 	}
20483 	insn[0].imm = (u32)addr;
20484 	insn[1].imm = addr >> 32;
20485 
20486 	if (btf_type_is_func(t)) {
20487 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20488 		aux->btf_var.mem_size = 0;
20489 		return 0;
20490 	}
20491 
20492 	datasec_id = find_btf_percpu_datasec(btf);
20493 	if (datasec_id > 0) {
20494 		datasec = btf_type_by_id(btf, datasec_id);
20495 		for_each_vsi(i, datasec, vsi) {
20496 			if (vsi->type == id) {
20497 				percpu = true;
20498 				break;
20499 			}
20500 		}
20501 	}
20502 
20503 	type = t->type;
20504 	t = btf_type_skip_modifiers(btf, type, NULL);
20505 	if (percpu) {
20506 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20507 		aux->btf_var.btf = btf;
20508 		aux->btf_var.btf_id = type;
20509 	} else if (!btf_type_is_struct(t)) {
20510 		const struct btf_type *ret;
20511 		const char *tname;
20512 		u32 tsize;
20513 
20514 		/* resolve the type size of ksym. */
20515 		ret = btf_resolve_size(btf, t, &tsize);
20516 		if (IS_ERR(ret)) {
20517 			tname = btf_name_by_offset(btf, t->name_off);
20518 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20519 				tname, PTR_ERR(ret));
20520 			return -EINVAL;
20521 		}
20522 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20523 		aux->btf_var.mem_size = tsize;
20524 	} else {
20525 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20526 		aux->btf_var.btf = btf;
20527 		aux->btf_var.btf_id = type;
20528 	}
20529 
20530 	return 0;
20531 }
20532 
20533 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20534 			       struct bpf_insn *insn,
20535 			       struct bpf_insn_aux_data *aux)
20536 {
20537 	struct btf *btf;
20538 	int btf_fd;
20539 	int err;
20540 
20541 	btf_fd = insn[1].imm;
20542 	if (btf_fd) {
20543 		btf = btf_get_by_fd(btf_fd);
20544 		if (IS_ERR(btf)) {
20545 			verbose(env, "invalid module BTF object FD specified.\n");
20546 			return -EINVAL;
20547 		}
20548 	} else {
20549 		if (!btf_vmlinux) {
20550 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20551 			return -EINVAL;
20552 		}
20553 		btf_get(btf_vmlinux);
20554 		btf = btf_vmlinux;
20555 	}
20556 
20557 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20558 	if (err) {
20559 		btf_put(btf);
20560 		return err;
20561 	}
20562 
20563 	return __add_used_btf(env, btf);
20564 }
20565 
20566 static bool is_tracing_prog_type(enum bpf_prog_type type)
20567 {
20568 	switch (type) {
20569 	case BPF_PROG_TYPE_KPROBE:
20570 	case BPF_PROG_TYPE_TRACEPOINT:
20571 	case BPF_PROG_TYPE_PERF_EVENT:
20572 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20573 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20574 		return true;
20575 	default:
20576 		return false;
20577 	}
20578 }
20579 
20580 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20581 {
20582 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20583 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20584 }
20585 
20586 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20587 					struct bpf_map *map,
20588 					struct bpf_prog *prog)
20589 
20590 {
20591 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20592 
20593 	if (map->excl_prog_sha &&
20594 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20595 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20596 		return -EACCES;
20597 	}
20598 
20599 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20600 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20601 		if (is_tracing_prog_type(prog_type)) {
20602 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20603 			return -EINVAL;
20604 		}
20605 	}
20606 
20607 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20608 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20609 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20610 			return -EINVAL;
20611 		}
20612 	}
20613 
20614 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
20615 		if (is_tracing_prog_type(prog_type)) {
20616 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20617 			return -EINVAL;
20618 		}
20619 	}
20620 
20621 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20622 	    !bpf_offload_prog_map_match(prog, map)) {
20623 		verbose(env, "offload device mismatch between prog and map\n");
20624 		return -EINVAL;
20625 	}
20626 
20627 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20628 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20629 		return -EINVAL;
20630 	}
20631 
20632 	if (prog->sleepable)
20633 		switch (map->map_type) {
20634 		case BPF_MAP_TYPE_HASH:
20635 		case BPF_MAP_TYPE_RHASH:
20636 		case BPF_MAP_TYPE_LRU_HASH:
20637 		case BPF_MAP_TYPE_ARRAY:
20638 		case BPF_MAP_TYPE_PERCPU_HASH:
20639 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20640 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20641 		case BPF_MAP_TYPE_LPM_TRIE:
20642 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20643 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20644 		case BPF_MAP_TYPE_RINGBUF:
20645 		case BPF_MAP_TYPE_USER_RINGBUF:
20646 		case BPF_MAP_TYPE_INODE_STORAGE:
20647 		case BPF_MAP_TYPE_SK_STORAGE:
20648 		case BPF_MAP_TYPE_TASK_STORAGE:
20649 		case BPF_MAP_TYPE_CGRP_STORAGE:
20650 		case BPF_MAP_TYPE_QUEUE:
20651 		case BPF_MAP_TYPE_STACK:
20652 		case BPF_MAP_TYPE_ARENA:
20653 		case BPF_MAP_TYPE_INSN_ARRAY:
20654 		case BPF_MAP_TYPE_PROG_ARRAY:
20655 			break;
20656 		default:
20657 			verbose(env,
20658 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20659 			return -EINVAL;
20660 		}
20661 
20662 	if (bpf_map_is_cgroup_storage(map) &&
20663 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20664 		verbose(env, "only one cgroup storage of each type is allowed\n");
20665 		return -EBUSY;
20666 	}
20667 
20668 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20669 		if (env->prog->aux->arena) {
20670 			verbose(env, "Only one arena per program\n");
20671 			return -EBUSY;
20672 		}
20673 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20674 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20675 			return -EPERM;
20676 		}
20677 		if (!env->prog->jit_requested) {
20678 			verbose(env, "JIT is required to use arena\n");
20679 			return -EOPNOTSUPP;
20680 		}
20681 		if (!bpf_jit_supports_arena()) {
20682 			verbose(env, "JIT doesn't support arena\n");
20683 			return -EOPNOTSUPP;
20684 		}
20685 		env->prog->aux->arena = (void *)map;
20686 		env->prog->jit_required = true;
20687 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20688 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20689 			return -EINVAL;
20690 		}
20691 	}
20692 
20693 	return 0;
20694 }
20695 
20696 /*
20697  * Keep track of whether the map is used by one program only. Such program may
20698  * store the addresses of its functions into the map when it's frozen, see
20699  * resolve_func_ptrs(), since nothing else relies on what the map has. After
20700  * that the map is not available to other programs.
20701  */
20702 static int bpf_map_claim(struct bpf_verifier_env *env, struct bpf_map *map)
20703 {
20704 	unsigned long me = (unsigned long)env->prog->aux, old;
20705 
20706 	for (;;) {
20707 		old = READ_ONCE(map->user);
20708 		if (old == me || old == BPF_MAP_USER_MANY)
20709 			return 0;
20710 		if (old & BPF_MAP_USER_PATCHED) {
20711 			verbose(env, "map '%s' has addresses of functions of another program\n",
20712 				map->name);
20713 			return -EBUSY;
20714 		}
20715 		if (cmpxchg(&map->user, old, old ? BPF_MAP_USER_MANY : me) == old)
20716 			return 0;
20717 	}
20718 }
20719 
20720 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20721 {
20722 	int i, err;
20723 
20724 	/* check whether we recorded this map already */
20725 	for (i = 0; i < env->used_map_cnt; i++)
20726 		if (env->used_maps[i] == map)
20727 			return i;
20728 
20729 	if (env->signature &&
20730 	    env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) {
20731 		verbose(env, "signed program cannot bind map '%s' not covered by the signature\n",
20732 			map->name);
20733 		return -EACCES;
20734 	}
20735 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20736 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20737 			MAX_USED_MAPS);
20738 		return -E2BIG;
20739 	}
20740 
20741 	err = check_map_prog_compatibility(env, map, env->prog);
20742 	if (err)
20743 		return err;
20744 
20745 	if (env->prog->sleepable)
20746 		atomic64_inc(&map->sleepable_refcnt);
20747 
20748 	/* hold the map. If the program is rejected by verifier,
20749 	 * the map will be released by release_maps() or it
20750 	 * will be used by the valid program until it's unloaded
20751 	 * and all maps are released in bpf_free_used_maps()
20752 	 */
20753 	bpf_map_inc(map);
20754 
20755 	env->used_maps[env->used_map_cnt++] = map;
20756 
20757 	err = bpf_map_claim(env, map);
20758 	if (err)
20759 		return err;
20760 
20761 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
20762 		err = bpf_insn_array_init(map, env->prog);
20763 		if (err) {
20764 			verbose(env, "Failed to properly initialize insn array\n");
20765 			return err;
20766 		}
20767 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
20768 		env->prog->jit_required = true;
20769 	}
20770 
20771 	return env->used_map_cnt - 1;
20772 }
20773 
20774 /* Add map behind fd to used maps list, if it's not already there, and return
20775  * its index.
20776  * Returns <0 on error, or >= 0 index, on success.
20777  */
20778 static int add_used_map(struct bpf_verifier_env *env, int fd)
20779 {
20780 	struct bpf_map *map;
20781 	CLASS(fd, f)(fd);
20782 
20783 	map = __bpf_map_get(f);
20784 	if (IS_ERR(map)) {
20785 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20786 		return PTR_ERR(map);
20787 	}
20788 
20789 	return __add_used_map(env, map);
20790 }
20791 
20792 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx)
20793 {
20794 	struct bpf_map *map;
20795 
20796 	if (idx >= env->fd_array_cnt) {
20797 		verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n",
20798 			idx, env->fd_array_cnt);
20799 		return -EINVAL;
20800 	}
20801 	map = fd_slot_map(env->fd_array[idx]);
20802 	if (!map) {
20803 		verbose(env, "fd_idx %u is not a map\n", idx);
20804 		return -EINVAL;
20805 	}
20806 	return __add_used_map(env, map);
20807 }
20808 
20809 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx)
20810 {
20811 	int fd;
20812 
20813 	if (copy_from_bpfptr_offset(&fd, env->fd_array_raw,
20814 				    (size_t)idx * sizeof(fd), sizeof(fd)))
20815 		return -EFAULT;
20816 	return add_used_map(env, fd);
20817 }
20818 
20819 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx)
20820 {
20821 	if (env->fd_array)
20822 		return fd_array_get_map_idx_continuous(env, idx);
20823 	if (env->signature) {
20824 		verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n");
20825 		return -EACCES;
20826 	}
20827 	if (!bpfptr_is_null(env->fd_array_raw))
20828 		return fd_array_get_map_idx_sparse(env, idx);
20829 
20830 	verbose(env, "fd_idx without fd_array is invalid\n");
20831 	return -EPROTO;
20832 }
20833 
20834 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
20835 {
20836 	u8 class = BPF_CLASS(insn->code);
20837 	u8 opcode = BPF_OP(insn->code);
20838 
20839 	switch (opcode) {
20840 	case BPF_NEG:
20841 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
20842 		    insn->off != 0 || insn->imm != 0) {
20843 			verbose(env, "BPF_NEG uses reserved fields\n");
20844 			return -EINVAL;
20845 		}
20846 		return 0;
20847 	case BPF_END:
20848 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
20849 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
20850 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
20851 			verbose(env, "BPF_END uses reserved fields\n");
20852 			return -EINVAL;
20853 		}
20854 		return 0;
20855 	case BPF_MOV:
20856 		if (BPF_SRC(insn->code) == BPF_X) {
20857 			if (class == BPF_ALU) {
20858 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
20859 				    insn->imm) {
20860 					verbose(env, "BPF_MOV uses reserved fields\n");
20861 					return -EINVAL;
20862 				}
20863 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
20864 				if (insn->imm != 1 && insn->imm != 1u << 16) {
20865 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
20866 					return -EINVAL;
20867 				}
20868 			} else if ((insn->off != 0 && insn->off != 8 &&
20869 				    insn->off != 16 && insn->off != 32) || insn->imm) {
20870 				verbose(env, "BPF_MOV uses reserved fields\n");
20871 				return -EINVAL;
20872 			}
20873 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
20874 			verbose(env, "BPF_MOV uses reserved fields\n");
20875 			return -EINVAL;
20876 		}
20877 		return 0;
20878 	case BPF_ADD:
20879 	case BPF_SUB:
20880 	case BPF_AND:
20881 	case BPF_OR:
20882 	case BPF_XOR:
20883 	case BPF_LSH:
20884 	case BPF_RSH:
20885 	case BPF_ARSH:
20886 	case BPF_MUL:
20887 	case BPF_DIV:
20888 	case BPF_MOD:
20889 		if (BPF_SRC(insn->code) == BPF_X) {
20890 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
20891 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
20892 				verbose(env, "BPF_ALU uses reserved fields\n");
20893 				return -EINVAL;
20894 			}
20895 		} else if (insn->src_reg != BPF_REG_0 ||
20896 			   (insn->off != 0 && insn->off != 1) ||
20897 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
20898 			verbose(env, "BPF_ALU uses reserved fields\n");
20899 			return -EINVAL;
20900 		}
20901 		return 0;
20902 	default:
20903 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
20904 		return -EINVAL;
20905 	}
20906 }
20907 
20908 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
20909 {
20910 	u8 class = BPF_CLASS(insn->code);
20911 	u8 opcode = BPF_OP(insn->code);
20912 
20913 	switch (opcode) {
20914 	case BPF_CALL:
20915 		if (bpf_is_callx(insn)) {
20916 			/* callx dst_reg */
20917 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
20918 				verbose(env, "BPF_CALL|BPF_X uses reserved fields\n");
20919 				return -EINVAL;
20920 			}
20921 			return 0;
20922 		}
20923 		if (BPF_SRC(insn->code) != BPF_K ||
20924 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
20925 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
20926 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
20927 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
20928 			verbose(env, "BPF_CALL uses reserved fields\n");
20929 			return -EINVAL;
20930 		}
20931 		return 0;
20932 	case BPF_JA:
20933 		if (BPF_SRC(insn->code) == BPF_X) {
20934 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
20935 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
20936 				return -EINVAL;
20937 			}
20938 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
20939 			   (class == BPF_JMP && insn->imm != 0) ||
20940 			   (class == BPF_JMP32 && insn->off != 0)) {
20941 			verbose(env, "BPF_JA uses reserved fields\n");
20942 			return -EINVAL;
20943 		}
20944 		return 0;
20945 	case BPF_EXIT:
20946 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
20947 		    insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
20948 		    class == BPF_JMP32) {
20949 			verbose(env, "BPF_EXIT uses reserved fields\n");
20950 			return -EINVAL;
20951 		}
20952 		return 0;
20953 	case BPF_JCOND:
20954 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO ||
20955 		    insn->dst_reg || insn->imm) {
20956 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
20957 			return -EINVAL;
20958 		}
20959 		return 0;
20960 	default:
20961 		if (BPF_SRC(insn->code) == BPF_X) {
20962 			if (insn->imm != 0) {
20963 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
20964 				return -EINVAL;
20965 			}
20966 		} else if (insn->src_reg != BPF_REG_0) {
20967 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
20968 			return -EINVAL;
20969 		}
20970 		return 0;
20971 	}
20972 }
20973 
20974 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
20975 {
20976 	switch (BPF_CLASS(insn->code)) {
20977 	case BPF_ALU:
20978 	case BPF_ALU64:
20979 		return check_alu_fields(env, insn);
20980 	case BPF_LDX:
20981 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20982 		    insn->imm != 0) {
20983 			verbose(env, "BPF_LDX uses reserved fields\n");
20984 			return -EINVAL;
20985 		}
20986 		return 0;
20987 	case BPF_STX:
20988 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
20989 			return 0;
20990 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20991 			verbose(env, "BPF_STX uses reserved fields\n");
20992 			return -EINVAL;
20993 		}
20994 		return 0;
20995 	case BPF_ST:
20996 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
20997 			verbose(env, "BPF_ST uses reserved fields\n");
20998 			return -EINVAL;
20999 		}
21000 		return 0;
21001 	case BPF_JMP:
21002 	case BPF_JMP32:
21003 		return check_jmp_fields(env, insn);
21004 	case BPF_LD: {
21005 		u8 mode = BPF_MODE(insn->code);
21006 
21007 		if (mode == BPF_ABS || mode == BPF_IND) {
21008 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
21009 			    BPF_SIZE(insn->code) == BPF_DW ||
21010 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
21011 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
21012 				return -EINVAL;
21013 			}
21014 		} else if (mode != BPF_IMM) {
21015 			verbose(env, "invalid BPF_LD mode\n");
21016 			return -EINVAL;
21017 		}
21018 		return 0;
21019 	}
21020 	default:
21021 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
21022 		return -EINVAL;
21023 	}
21024 }
21025 
21026 /*
21027  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
21028  *
21029  * 1. if it accesses map FD, replace it with actual map pointer.
21030  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21031  *
21032  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21033  */
21034 static int check_and_resolve_insns(struct bpf_verifier_env *env)
21035 {
21036 	struct bpf_insn *insn = env->prog->insnsi;
21037 	int insn_cnt = env->prog->len;
21038 	int i, err;
21039 
21040 	err = bpf_prog_calc_tag(env->prog);
21041 	if (err)
21042 		return err;
21043 
21044 	for (i = 0; i < insn_cnt; i++, insn++) {
21045 		if (insn->dst_reg >= MAX_BPF_REG &&
21046 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
21047 			verbose(env, "R%d is invalid\n", insn->dst_reg);
21048 			return -EINVAL;
21049 		}
21050 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
21051 			verbose(env, "R%d is invalid\n", insn->src_reg);
21052 			return -EINVAL;
21053 		}
21054 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21055 			struct bpf_insn_aux_data *aux;
21056 			struct bpf_map *map;
21057 			int map_idx;
21058 			u64 addr;
21059 
21060 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21061 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21062 			    insn[1].off != 0) {
21063 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21064 				return -EINVAL;
21065 			}
21066 
21067 			if (insn[0].off != 0) {
21068 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
21069 				return -EINVAL;
21070 			}
21071 
21072 			if (insn[0].src_reg == 0)
21073 				/* valid generic load 64-bit imm */
21074 				goto next_insn;
21075 
21076 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21077 				aux = &env->insn_aux_data[i];
21078 				err = check_pseudo_btf_id(env, insn, aux);
21079 				if (err)
21080 					return err;
21081 				goto next_insn;
21082 			}
21083 
21084 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21085 				aux = &env->insn_aux_data[i];
21086 				aux->ptr_type = PTR_TO_FUNC;
21087 				goto next_insn;
21088 			}
21089 
21090 			/* In final convert_pseudo_ld_imm64() step, this is
21091 			 * converted into regular 64-bit imm load insn.
21092 			 */
21093 			switch (insn[0].src_reg) {
21094 			case BPF_PSEUDO_MAP_VALUE:
21095 			case BPF_PSEUDO_MAP_IDX_VALUE:
21096 				break;
21097 			case BPF_PSEUDO_MAP_FD:
21098 			case BPF_PSEUDO_MAP_IDX:
21099 				if (insn[1].imm == 0)
21100 					break;
21101 				fallthrough;
21102 			default:
21103 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21104 				return -EINVAL;
21105 			}
21106 
21107 			switch (insn[0].src_reg) {
21108 			case BPF_PSEUDO_MAP_IDX_VALUE:
21109 			case BPF_PSEUDO_MAP_IDX:
21110 				map_idx = fd_array_get_map_idx(env, insn[0].imm);
21111 				break;
21112 			default:
21113 				if (env->signature) {
21114 					verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n");
21115 					return -EINVAL;
21116 				}
21117 				map_idx = add_used_map(env, insn[0].imm);
21118 				break;
21119 			}
21120 
21121 			if (map_idx < 0)
21122 				return map_idx;
21123 			map = env->used_maps[map_idx];
21124 
21125 			aux = &env->insn_aux_data[i];
21126 			aux->map_index = map_idx;
21127 
21128 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21129 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21130 				addr = (unsigned long)map;
21131 			} else {
21132 				u32 off = insn[1].imm;
21133 
21134 				if (!map->ops->map_direct_value_addr) {
21135 					verbose(env, "no direct value access support for this map type\n");
21136 					return -EINVAL;
21137 				}
21138 
21139 				err = map->ops->map_direct_value_addr(map, &addr, off);
21140 				if (err) {
21141 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21142 						map->value_size, off);
21143 					return err;
21144 				}
21145 
21146 				aux->map_off = off;
21147 				addr += off;
21148 			}
21149 
21150 			insn[0].imm = (u32)addr;
21151 			insn[1].imm = addr >> 32;
21152 
21153 next_insn:
21154 			insn++;
21155 			i++;
21156 			continue;
21157 		}
21158 
21159 		/* Basic sanity check before we invest more work here. */
21160 		if (!bpf_opcode_in_insntable(insn->code)) {
21161 			verbose(env, "unknown opcode %02x\n", insn->code);
21162 			return -EINVAL;
21163 		}
21164 
21165 		err = check_insn_fields(env, insn);
21166 		if (err)
21167 			return err;
21168 	}
21169 
21170 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21171 	 * 'struct bpf_map *' into a register instead of user map_fd.
21172 	 * These pointers will be used later by verifier to validate map access.
21173 	 */
21174 	return 0;
21175 }
21176 
21177 /* that many pointers to functions are recognized in the maps of a program at most */
21178 #define BPF_MAX_FUNC_PTRS (1 << 20)
21179 
21180 static int add_func_ptr(struct bpf_verifier_env *env, struct bpf_map *map, u32 map_off,
21181 			u32 xlated_off)
21182 {
21183 	struct bpf_func_ptr *ptrs;
21184 
21185 	if (env->func_ptr_cnt == BPF_MAX_FUNC_PTRS) {
21186 		verbose(env, "too many pointers to functions in maps, the limit is %d\n",
21187 			BPF_MAX_FUNC_PTRS);
21188 		return -E2BIG;
21189 	}
21190 
21191 	/* grow by doubling, the array is sorted and searched later */
21192 	if (!(env->func_ptr_cnt & (env->func_ptr_cnt - 1))) {
21193 		ptrs = kvrealloc(env->func_ptrs,
21194 				 array_size(max(2 * env->func_ptr_cnt, 16U), sizeof(*ptrs)),
21195 				 GFP_KERNEL_ACCOUNT);
21196 		if (!ptrs)
21197 			return -ENOMEM;
21198 		env->func_ptrs = ptrs;
21199 	}
21200 	env->func_ptrs[env->func_ptr_cnt++] = (struct bpf_func_ptr){
21201 		.map = map,
21202 		.map_off = map_off,
21203 		.orig_off = xlated_off,
21204 		.xlated_off = xlated_off,
21205 	};
21206 	return 0;
21207 }
21208 
21209 /*
21210  * Compilers put pointers to functions into read-only data: tables of functions,
21211  * structures of operations, vtables, where they are mixed with other data.
21212  * The loader stores such data in a frozen read-only array map and resolves
21213  * a pointer to a static function to the offset in bytes of its first
21214  * instruction in the program: the address of the function in the program.
21215  *
21216  * Find 64-bit values that look like that in the maps of a program that uses
21217  * callx. It's a guess. When the value is not a pointer, the program either
21218  * fails to load, because it does with a pointer what can be done with
21219  * a number only, or it sees the address of a function instead of the number.
21220  * It's known before the control flow graph of the program is built and the main
21221  * verification pass begins which functions may be called via callx.
21222  *
21223  * When the program is jitted the offsets are replaced with the addresses of
21224  * the functions in the map itself, see jit_subprogs(). Hence the program has to
21225  * be the only user of the map, see bpf_map_claim(): nothing else may rely on
21226  * what the map had.
21227  *
21228  * The program reads the addresses of its functions from there like any other
21229  * data, so it has to be allowed to leak pointers.
21230  */
21231 static int resolve_func_ptrs(struct bpf_verifier_env *env)
21232 {
21233 	int insn_cnt = env->prog->len;
21234 	int i, err, subprog;
21235 	struct bpf_map *map;
21236 	u64 addr, val;
21237 	u32 off;
21238 
21239 	if (!env->has_callx || !env->allow_ptr_leaks)
21240 		return 0;
21241 
21242 	for (i = 0; i < env->used_map_cnt; i++) {
21243 		map = env->used_maps[i];
21244 		/* coincidences in maps that are shared with other programs don't matter */
21245 		if (READ_ONCE(map->user) != (unsigned long)env->prog->aux)
21246 			continue;
21247 		if (map->map_type != BPF_MAP_TYPE_ARRAY || map->max_entries != 1 ||
21248 		    !bpf_map_is_rdonly(map) || !map->ops->map_direct_value_addr ||
21249 		    !IS_ERR_OR_NULL(map->record))
21250 			continue;
21251 		if (map->ops->map_direct_value_addr(map, &addr, 0))
21252 			continue;
21253 
21254 		for (off = 0; off + sizeof(u64) <= map->value_size; off += sizeof(u64)) {
21255 			if (!(off % SZ_64K))
21256 				cond_resched();
21257 			val = *(u64 *)(unsigned long)(addr + off);
21258 			if (!val || val % sizeof(struct bpf_insn) ||
21259 			    val / sizeof(struct bpf_insn) >= insn_cnt)
21260 				continue;
21261 			subprog = bpf_find_subprog(env, val / sizeof(struct bpf_insn));
21262 			if (subprog <= 0 || bpf_subprog_is_global(env, subprog))
21263 				continue;
21264 			err = add_func_ptr(env, map, off, val / sizeof(struct bpf_insn));
21265 			if (err)
21266 				return err;
21267 		}
21268 	}
21269 	if (env->func_ptr_cnt)
21270 		sort(env->func_ptrs, env->func_ptr_cnt, sizeof(*env->func_ptrs),
21271 		     cmp_func_ptrs, NULL);
21272 	return 0;
21273 }
21274 
21275 /* drop refcnt of maps used by the rejected program */
21276 static void release_maps(struct bpf_verifier_env *env)
21277 {
21278 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21279 			     env->used_map_cnt);
21280 }
21281 
21282 /* drop refcnt of maps used by the rejected program */
21283 static void release_btfs(struct bpf_verifier_env *env)
21284 {
21285 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21286 }
21287 
21288 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21289 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21290 {
21291 	struct bpf_insn *insn = env->prog->insnsi;
21292 	int insn_cnt = env->prog->len;
21293 	int i;
21294 
21295 	for (i = 0; i < insn_cnt; i++, insn++) {
21296 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21297 			continue;
21298 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21299 			continue;
21300 		insn->src_reg = 0;
21301 	}
21302 }
21303 
21304 static void release_insn_arrays(struct bpf_verifier_env *env)
21305 {
21306 	int i;
21307 
21308 	for (i = 0; i < env->insn_array_map_cnt; i++)
21309 		bpf_insn_array_release(env->insn_array_maps[i]);
21310 }
21311 
21312 /* The verifier does more data flow analysis than llvm and will not
21313  * explore branches that are dead at run time. Malicious programs can
21314  * have dead code too. Therefore replace all dead at-run-time code
21315  * with 'ja -1'.
21316  *
21317  * Just nops are not optimal, e.g. if they would sit at the end of the
21318  * program and through another bug we would manage to jump there, then
21319  * we'd execute beyond program memory otherwise. Returning exception
21320  * code also wouldn't work since we can have subprogs where the dead
21321  * code could be located.
21322  */
21323 static void sanitize_dead_code(struct bpf_verifier_env *env)
21324 {
21325 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21326 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21327 	struct bpf_insn *insn = env->prog->insnsi;
21328 	const int insn_cnt = env->prog->len;
21329 	int i;
21330 
21331 	for (i = 0; i < insn_cnt; i++) {
21332 		if (aux_data[i].seen)
21333 			continue;
21334 		memcpy(insn + i, &trap, sizeof(trap));
21335 		aux_data[i].zext_dst = false;
21336 	}
21337 }
21338 
21339 static void free_states(struct bpf_verifier_env *env)
21340 {
21341 	struct bpf_verifier_state_list *sl;
21342 	struct list_head *head, *pos, *tmp;
21343 	struct bpf_scc_info *info;
21344 	int i, j;
21345 
21346 	bpf_free_verifier_state(env->cur_state, true);
21347 	env->cur_state = NULL;
21348 	while (!pop_stack(env, NULL, NULL, false));
21349 
21350 	list_for_each_safe(pos, tmp, &env->free_list) {
21351 		sl = container_of(pos, struct bpf_verifier_state_list, node);
21352 		bpf_free_verifier_state(&sl->state, false);
21353 		kfree(sl);
21354 	}
21355 	INIT_LIST_HEAD(&env->free_list);
21356 
21357 	for (i = 0; i < env->scc_cnt; ++i) {
21358 		info = env->scc_info[i];
21359 		if (!info)
21360 			continue;
21361 		for (j = 0; j < info->num_visits; j++)
21362 			bpf_free_backedges(&info->visits[j]);
21363 		kvfree(info);
21364 		env->scc_info[i] = NULL;
21365 	}
21366 
21367 	if (!env->explored_states)
21368 		return;
21369 
21370 	for (i = 0; i < state_htab_size(env); i++) {
21371 		head = &env->explored_states[i];
21372 
21373 		list_for_each_safe(pos, tmp, head) {
21374 			sl = container_of(pos, struct bpf_verifier_state_list, node);
21375 			bpf_free_verifier_state(&sl->state, false);
21376 			kfree(sl);
21377 		}
21378 		INIT_LIST_HEAD(&env->explored_states[i]);
21379 	}
21380 }
21381 
21382 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sleepable)
21383 {
21384 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21385 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
21386 	struct bpf_prog_aux *aux = env->prog->aux;
21387 	struct bpf_verifier_state *state;
21388 	struct bpf_reg_state *regs;
21389 	u32 old_insns_total = sub->insns_total;
21390 	u32 insn_processed = env->insn_processed;
21391 	int ret, i;
21392 
21393 	env->prev_linfo = NULL;
21394 	env->pass_cnt++;
21395 
21396 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
21397 	if (!state)
21398 		return -ENOMEM;
21399 	state->curframe = 0;
21400 	state->speculative = false;
21401 	state->branches = 1;
21402 	state->in_sleepable = is_sleepable;
21403 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
21404 	if (!state->frame[0]) {
21405 		kfree(state);
21406 		return -ENOMEM;
21407 	}
21408 	env->cur_state = state;
21409 	init_func_state(env, state->frame[0],
21410 			BPF_MAIN_FUNC /* callsite */,
21411 			0 /* frameno */,
21412 			subprog);
21413 	state->first_insn_idx = env->subprog_info[subprog].start;
21414 	state->last_insn_idx = -1;
21415 
21416 	regs = state->frame[state->curframe]->regs;
21417 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21418 		const char *sub_name = bpf_subprog_name(env, subprog);
21419 		struct bpf_subprog_arg_info *arg;
21420 		struct bpf_reg_state *reg;
21421 
21422 		if (env->log.level & BPF_LOG_LEVEL)
21423 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21424 		ret = btf_prepare_func_args(env, subprog);
21425 		if (ret)
21426 			goto out;
21427 
21428 		if (subprog_is_exc_cb(env, subprog)) {
21429 			state->frame[0]->in_exception_callback_fn = true;
21430 
21431 			/*
21432 			 * Global functions are scalar or void, make sure
21433 			 * we return a scalar.
21434 			 */
21435 			if (subprog_returns_void(env, subprog)) {
21436 				verbose(env, "exception cb cannot return void\n");
21437 				ret = -EINVAL;
21438 				goto out;
21439 			}
21440 
21441 			/* Also ensure the callback only has a single scalar argument. */
21442 			if (sub->arg_slot_cnt != 1 || sub->args[0].arg_type != ARG_SCALAR) {
21443 				verbose(env, "exception cb only supports single integer argument\n");
21444 				ret = -EINVAL;
21445 				goto out;
21446 			}
21447 		}
21448 		for (i = BPF_REG_1;
21449 		     i <= min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
21450 			arg = &sub->args[i - BPF_REG_1];
21451 			reg = &regs[i];
21452 
21453 			if (arg->arg_type == ARG_PTR_TO_CTX) {
21454 				reg->type = PTR_TO_CTX;
21455 				mark_reg_known_zero(env, regs, i);
21456 			} else if (arg->arg_type == ARG_SCALAR) {
21457 				reg->type = SCALAR_VALUE;
21458 				mark_reg_unknown(env, regs, i);
21459 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
21460 				/* assume unspecial LOCAL dynptr type */
21461 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0);
21462 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
21463 				reg->type = PTR_TO_MEM;
21464 				reg->type |= arg->arg_type &
21465 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
21466 				mark_reg_known_zero(env, regs, i);
21467 				reg->mem_size = arg->mem_size;
21468 				if (arg->arg_type & PTR_MAYBE_NULL)
21469 					reg->id = ++env->id_gen;
21470 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
21471 				reg->type = PTR_TO_BTF_ID;
21472 				if (arg->arg_type & PTR_MAYBE_NULL)
21473 					reg->type |= PTR_MAYBE_NULL;
21474 				if (arg->arg_type & PTR_UNTRUSTED)
21475 					reg->type |= PTR_UNTRUSTED;
21476 				if (arg->arg_type & PTR_TRUSTED)
21477 					reg->type |= PTR_TRUSTED;
21478 				mark_reg_known_zero(env, regs, i);
21479 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
21480 				reg->btf_id = arg->btf_id;
21481 				reg->id = ++env->id_gen;
21482 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
21483 				/* caller can pass either PTR_TO_ARENA or SCALAR */
21484 				mark_reg_unknown(env, regs, i);
21485 			} else {
21486 				verifier_bug(env, "unhandled arg#%d type %d",
21487 					     i - BPF_REG_1 + 1, arg->arg_type);
21488 				ret = -EFAULT;
21489 				goto out;
21490 			}
21491 		}
21492 		if (env->prog->type == BPF_PROG_TYPE_EXT &&
21493 		    sub->arg_slot_cnt > MAX_BPF_FUNC_REG_ARGS) {
21494 			verbose(env, "freplace programs with >%d args not supported yet\n",
21495 				MAX_BPF_FUNC_REG_ARGS);
21496 			ret = -EINVAL;
21497 			goto out;
21498 		}
21499 	} else {
21500 		/* if main BPF program has associated BTF info, validate that
21501 		 * it's matching expected signature, and otherwise mark BTF
21502 		 * info for main program as unreliable
21503 		 */
21504 		if (env->prog->aux->func_info_aux) {
21505 			ret = btf_prepare_func_args(env, 0);
21506 			if (ret || sub->arg_slot_cnt != 1 ||
21507 			    sub->args[0].arg_type != ARG_PTR_TO_CTX) {
21508 				env->prog->aux->func_info_aux[0].unreliable = true;
21509 				sub->arg_slot_cnt = 1;
21510 				sub->stack_arg_cnt = 0;
21511 			}
21512 		}
21513 
21514 		/* 1st arg to a function */
21515 		regs[BPF_REG_1].type = PTR_TO_CTX;
21516 		mark_reg_known_zero(env, regs, BPF_REG_1);
21517 	}
21518 
21519 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
21520 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
21521 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
21522 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
21523 			if (ret < 0)
21524 				goto out;
21525 
21526 			aux->ctx_arg_info[i].ref_id = ret;
21527 		}
21528 	}
21529 
21530 	ret = do_check(env);
21531 out:
21532 	account_current_path(env);
21533 	if (!ret) {
21534 		if (pop_log)
21535 			bpf_vlog_reset(&env->log, 0);
21536 		bpf_diag_event_log_restore(env, 0);
21537 	}
21538 	free_states(env);
21539 
21540 	/*
21541 	 * The override is needed to account for async subprograms, which
21542 	 * are verified with their own set of stack frames and thus are
21543 	 * not accounted as callees by account_current_path().
21544 	 * Accumulate their total counts as total counts of the main or
21545 	 * global subprog hosting the async call.
21546 	 * Start from the saved total of earlier contexts: adding to the current
21547 	 * total would count this pass's synchronous paths twice.
21548 	 */
21549 	sub->insns_total = old_insns_total + (env->insn_processed - insn_processed);
21550 	return ret;
21551 }
21552 
21553 /* Lazily verify all global functions based on their BTF, if they are called
21554  * from main BPF program or any of subprograms transitively.
21555  * BPF global subprogs called from dead code are not validated.
21556  * All callable global functions must pass verification.
21557  * Otherwise the whole program is rejected.
21558  * Consider:
21559  * int bar(int);
21560  * int foo(int f)
21561  * {
21562  *    return bar(f);
21563  * }
21564  * int bar(int b)
21565  * {
21566  *    ...
21567  * }
21568  * foo() will be verified first for R1=any_scalar_value. During verification it
21569  * will be assumed that bar() already verified successfully and call to bar()
21570  * from foo() will be checked for type match only. Later bar() will be verified
21571  * independently to check that it's safe for R1=any_scalar_value.
21572  */
21573 static int do_check_subprogs(struct bpf_verifier_env *env)
21574 {
21575 	struct bpf_prog_aux *aux = env->prog->aux;
21576 	struct bpf_func_info_aux *sub_aux;
21577 	int context, i, ret, new_cnt;
21578 
21579 	if (!aux->func_info)
21580 		return 0;
21581 
21582 	/*
21583 	 * Callbacks cannot throw, so the exception callback always runs in the
21584 	 * main program's context. It is presumed to be always called.
21585 	 */
21586 	if (env->exception_callback_subprog) {
21587 		sub_aux = subprog_aux(env, env->exception_callback_subprog);
21588 		sub_aux->called[env->prog->sleepable] = true;
21589 	}
21590 
21591 again:
21592 	new_cnt = 0;
21593 	for (i = 1; i < env->subprog_cnt; i++) {
21594 		if (!bpf_subprog_is_global(env, i))
21595 			continue;
21596 
21597 		sub_aux = subprog_aux(env, i);
21598 		for (context = 0; context < ARRAY_SIZE(sub_aux->called); context++) {
21599 			if (!sub_aux->called[context] || sub_aux->verified[context])
21600 				continue;
21601 
21602 			env->insn_idx = env->subprog_info[i].start;
21603 			WARN_ON_ONCE(env->insn_idx == 0);
21604 			ret = do_check_common(env, i, context);
21605 			if (ret)
21606 				return ret;
21607 			if (env->log.level & BPF_LOG_LEVEL)
21608 				verbose(env, "Func#%d ('%s') is safe for any args "
21609 					"that match its prototype\n",
21610 					i, bpf_subprog_name(env, i));
21611 
21612 			sub_aux->verified[context] = true;
21613 			new_cnt++;
21614 		}
21615 	}
21616 
21617 	/*
21618 	 * We can't loop forever as each pass verifies at least one new context,
21619 	 * and there are only two contexts per global subprog.
21620 	 */
21621 	if (new_cnt)
21622 		goto again;
21623 
21624 	return 0;
21625 }
21626 
21627 static int do_check_main(struct bpf_verifier_env *env)
21628 {
21629 	int ret;
21630 
21631 	env->insn_idx = 0;
21632 	ret = do_check_common(env, 0, env->prog->sleepable);
21633 	if (!ret)
21634 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21635 	return ret;
21636 }
21637 
21638 static void print_verification_stats(struct bpf_verifier_env *env)
21639 {
21640 	/* Skip over hidden subprogs which are not verified. */
21641 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21642 
21643 	if (env->log.level & BPF_LOG_STATS) {
21644 		verbose(env, "verification time %lld usec\n",
21645 			div_u64(env->verification_time, 1000));
21646 		verbose(env, "stack depth max %d\n", env->max_stack_depth);
21647 		for (i = 0; i < subprog_cnt; i++) {
21648 			const char *name = env->subprog_info[i].name;
21649 			const char *kind;
21650 
21651 			if (!name || !name[0])
21652 				name = "<unknown>";
21653 			kind = i == 0 ? "main" :
21654 			       bpf_subprog_is_global(env, i) ? "global" : "static";
21655 			verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n",
21656 				i, name, kind, env->subprog_info[i].insns_self,
21657 				env->subprog_info[i].insns_total,
21658 				env->subprog_info[i].stack_depth);
21659 		}
21660 	}
21661 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
21662 		"total_states %d peak_states %d mark_read %d\n",
21663 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
21664 		env->max_states_per_insn, env->total_states,
21665 		env->peak_states, env->longest_mark_read_walk);
21666 }
21667 
21668 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
21669 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
21670 {
21671 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
21672 	prog->aux->ctx_arg_info_size = cnt;
21673 
21674 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
21675 }
21676 
21677 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
21678 {
21679 	const struct btf_type *t, *func_proto;
21680 	const struct bpf_struct_ops_desc *st_ops_desc;
21681 	const struct bpf_struct_ops_arg_info *arg_info;
21682 	const struct bpf_struct_ops *st_ops;
21683 	const struct btf_member *member;
21684 	struct bpf_prog *prog = env->prog;
21685 	bool has_refcounted_arg = false;
21686 	u32 btf_id, member_idx, member_off;
21687 	struct btf *btf;
21688 	const char *mname;
21689 	int i, err;
21690 
21691 	if (!prog->gpl_compatible) {
21692 		verbose(env, "struct ops programs must have a GPL compatible license\n");
21693 		return -EINVAL;
21694 	}
21695 
21696 	if (!prog->aux->attach_btf_id)
21697 		return -ENOTSUPP;
21698 
21699 	btf = prog->aux->attach_btf;
21700 	if (btf_is_module(btf)) {
21701 		/* Make sure st_ops is valid through the lifetime of env */
21702 		env->attach_btf_mod = btf_try_get_module(btf);
21703 		if (!env->attach_btf_mod) {
21704 			verbose(env, "struct_ops module %s is not found\n",
21705 				btf_get_name(btf));
21706 			return -ENOTSUPP;
21707 		}
21708 	}
21709 
21710 	btf_id = prog->aux->attach_btf_id;
21711 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
21712 	if (!st_ops_desc) {
21713 		verbose(env, "attach_btf_id %u is not a supported struct\n",
21714 			btf_id);
21715 		return -ENOTSUPP;
21716 	}
21717 	st_ops = st_ops_desc->st_ops;
21718 
21719 	t = st_ops_desc->type;
21720 	member_idx = prog->expected_attach_type;
21721 	if (member_idx >= btf_type_vlen(t)) {
21722 		verbose(env, "attach to invalid member idx %u of struct %s\n",
21723 			member_idx, st_ops->name);
21724 		return -EINVAL;
21725 	}
21726 
21727 	member = &btf_type_member(t)[member_idx];
21728 	mname = btf_name_by_offset(btf, member->name_off);
21729 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
21730 					       NULL);
21731 	if (!func_proto) {
21732 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
21733 			mname, member_idx, st_ops->name);
21734 		return -EINVAL;
21735 	}
21736 
21737 	member_off = __btf_member_bit_offset(t, member) / 8;
21738 	err = bpf_struct_ops_supported(st_ops, member_off);
21739 	if (err) {
21740 		verbose(env, "attach to unsupported member %s of struct %s\n",
21741 			mname, st_ops->name);
21742 		return err;
21743 	}
21744 
21745 	if (st_ops->check_member) {
21746 		err = st_ops->check_member(t, member, prog);
21747 
21748 		if (err) {
21749 			verbose(env, "attach to unsupported member %s of struct %s\n",
21750 				mname, st_ops->name);
21751 			return err;
21752 		}
21753 	}
21754 
21755 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
21756 		verbose(env, "Private stack not supported by jit\n");
21757 		return -EACCES;
21758 	}
21759 
21760 	arg_info = &st_ops_desc->arg_info[member_idx];
21761 	for (i = 0; i < arg_info->cnt; i++) {
21762 		const struct bpf_ctx_arg_aux *info = &arg_info->info[i];
21763 
21764 		if (info->refcounted)
21765 			has_refcounted_arg = true;
21766 		if (base_type(info->reg_type) == PTR_TO_ARENA) {
21767 			if (!bpf_jit_supports_arena_args()) {
21768 				verbose(env, "JIT does not support arena arguments\n");
21769 				return -ENOTSUPP;
21770 			}
21771 			if (!prog->aux->arena) {
21772 				verbose(env,
21773 					"arena argument of %s requires a program with an associated arena\n",
21774 					mname);
21775 				return -EINVAL;
21776 			}
21777 		}
21778 	}
21779 
21780 	/* Tail call is not allowed for programs with refcounted arguments since we
21781 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
21782 	 */
21783 	for (i = 0; i < env->subprog_cnt; i++) {
21784 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
21785 			verbose(env, "program with __ref argument cannot tail call\n");
21786 			return -EINVAL;
21787 		}
21788 	}
21789 
21790 	prog->aux->st_ops = st_ops;
21791 	prog->aux->attach_st_ops_member_off = member_off;
21792 
21793 	prog->aux->attach_func_proto = func_proto;
21794 	prog->aux->attach_func_name = mname;
21795 	env->ops = st_ops->verifier_ops;
21796 
21797 	return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt);
21798 }
21799 #define SECURITY_PREFIX "security_"
21800 
21801 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
21802 
21803 /* list of non-sleepable functions that are otherwise on
21804  * ALLOW_ERROR_INJECTION list
21805  */
21806 BTF_SET_START(btf_non_sleepable_error_inject)
21807 /* Three functions below can be called from sleepable and non-sleepable context.
21808  * Assume non-sleepable from bpf safety point of view.
21809  */
21810 BTF_ID(func, __filemap_add_folio)
21811 #ifdef CONFIG_FAIL_PAGE_ALLOC
21812 BTF_ID(func, should_fail_alloc_page)
21813 #endif
21814 #ifdef CONFIG_FAILSLAB
21815 BTF_ID(func, should_failslab)
21816 #endif
21817 BTF_SET_END(btf_non_sleepable_error_inject)
21818 
21819 static int check_non_sleepable_error_inject(u32 btf_id)
21820 {
21821 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21822 }
21823 
21824 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
21825 {
21826 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
21827 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
21828 	 */
21829 	if (!check_non_sleepable_error_inject(btf_id) &&
21830 	    within_error_injection_list(addr))
21831 		return 0;
21832 
21833 	return -EINVAL;
21834 }
21835 
21836 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21837 {
21838 	if (within_error_injection_list(addr) ||
21839 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21840 		return 0;
21841 
21842 	return -EINVAL;
21843 }
21844 
21845 #else
21846 
21847 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
21848  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
21849  * but that just compares two concrete function names.
21850  */
21851 static bool has_arch_syscall_prefix(const char *func_name)
21852 {
21853 #if defined(__x86_64__)
21854 	return !strncmp(func_name, "__x64_", 6);
21855 #elif defined(__i386__)
21856 	return !strncmp(func_name, "__ia32_", 7);
21857 #elif defined(__s390x__)
21858 	return !strncmp(func_name, "__s390x_", 8);
21859 #elif defined(__aarch64__)
21860 	return !strncmp(func_name, "__arm64_", 8);
21861 #elif defined(__riscv)
21862 	return !strncmp(func_name, "__riscv_", 8);
21863 #elif defined(__powerpc__) || defined(__powerpc64__)
21864 	return !strncmp(func_name, "sys_", 4);
21865 #elif defined(__loongarch__)
21866 	return !strncmp(func_name, "sys_", 4);
21867 #else
21868 	return false;
21869 #endif
21870 }
21871 
21872 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
21873 
21874 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
21875 {
21876 	if (has_arch_syscall_prefix(func_name))
21877 		return 0;
21878 
21879 	return -EINVAL;
21880 }
21881 
21882 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21883 {
21884 	if (has_arch_syscall_prefix(func_name) ||
21885 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21886 		return 0;
21887 
21888 	return -EINVAL;
21889 }
21890 
21891 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
21892 
21893 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
21894 {
21895 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
21896 }
21897 
21898 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
21899 				  const struct btf *btf)
21900 {
21901 	const struct btf_type *t;
21902 	const char *tname;
21903 
21904 	if (!btf_is_kernel(btf))
21905 		return -EINVAL;
21906 
21907 	switch (prog->type) {
21908 	case BPF_PROG_TYPE_TRACING:
21909 		t = btf_type_by_id(btf, btf_id);
21910 		if (!t)
21911 			return -EINVAL;
21912 		tname = btf_name_by_offset(btf, t->name_off);
21913 		if (!tname)
21914 			return -EINVAL;
21915 
21916 		/*
21917 		 * *.multi sleepable programs will pass initial sleepable check,
21918 		 * the actual attached btf ids are checked later during the link
21919 		 * attachment.
21920 		 */
21921 		if (is_tracing_multi_id(prog, btf_id))
21922 			return 0;
21923 		if (!check_attach_sleepable(btf_id, addr, tname))
21924 			return 0;
21925 		/*
21926 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
21927 		 * in the fmodret id set with the KF_SLEEPABLE flag.
21928 		 */
21929 		else {
21930 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
21931 
21932 			if (flags && (*flags & KF_SLEEPABLE))
21933 				return 0;
21934 		}
21935 		break;
21936 	case BPF_PROG_TYPE_LSM:
21937 		/*
21938 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
21939 		 * Only some of them are sleepable.
21940 		 */
21941 		if (bpf_lsm_is_sleepable_hook(btf_id))
21942 			return 0;
21943 		break;
21944 	default:
21945 		break;
21946 	}
21947 	return -EINVAL;
21948 }
21949 
21950 /*
21951  * Resolve the prototype describing a trace target's real ABI. A
21952  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
21953  * prototype, so use the _impl prototype; other targets use their own.
21954  */
21955 static const struct btf_type *
21956 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
21957 {
21958 	const struct btf_type *func;
21959 	struct module *mod = NULL;
21960 	const char *name;
21961 	int implicit;
21962 
21963 	func = btf_type_by_id(btf, func_id);
21964 	if (!func || !btf_type_is_func(func))
21965 		return NULL;
21966 	name = btf_name_by_offset(btf, func->name_off);
21967 
21968 	/*
21969 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
21970 	 * stable only once it is live; hold a module ref across the read to
21971 	 * exclude a concurrent module load.
21972 	 */
21973 	if (btf_is_module(btf)) {
21974 		mod = btf_try_get_module(btf);
21975 		if (!mod)
21976 			return NULL;
21977 	}
21978 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
21979 	module_put(mod);
21980 
21981 	if (implicit == -EINVAL) {
21982 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
21983 		return NULL;
21984 	}
21985 	if (implicit > 0)
21986 		return find_kfunc_impl_proto(log, btf, name);
21987 
21988 	return btf_type_by_id(btf, func->type);
21989 }
21990 
21991 static bool attach_uses_trampoline_retval(enum bpf_attach_type type)
21992 {
21993 	switch (type) {
21994 	case BPF_MODIFY_RETURN:
21995 	case BPF_TRACE_FEXIT:
21996 	case BPF_TRACE_FEXIT_MULTI:
21997 	case BPF_TRACE_FSESSION:
21998 	case BPF_TRACE_FSESSION_MULTI:
21999 		return true;
22000 	default:
22001 		return false;
22002 	}
22003 }
22004 
22005 int bpf_check_attach_target(struct bpf_verifier_log *log,
22006 			    const struct bpf_prog *prog,
22007 			    const struct bpf_prog *tgt_prog,
22008 			    u32 btf_id,
22009 			    struct bpf_attach_target_info *tgt_info)
22010 {
22011 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22012 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22013 	char trace_symbol[KSYM_SYMBOL_LEN];
22014 	const char prefix[] = "btf_trace_";
22015 	struct bpf_raw_event_map *btp;
22016 	int ret = 0, subprog = -1, i;
22017 	const struct btf_type *t;
22018 	bool conservative = true;
22019 	const char *tname, *fname;
22020 	struct btf *btf;
22021 	long addr = 0;
22022 	struct module *mod = NULL;
22023 
22024 	if (!btf_id) {
22025 		bpf_log(log, "Tracing programs must provide btf_id\n");
22026 		return -EINVAL;
22027 	}
22028 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22029 	if (!btf) {
22030 		bpf_log(log,
22031 			"Tracing program can only be attached to another program annotated with BTF\n");
22032 		return -EINVAL;
22033 	}
22034 	t = btf_type_by_id(btf, btf_id);
22035 	if (!t) {
22036 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22037 		return -EINVAL;
22038 	}
22039 	tname = btf_name_by_offset(btf, t->name_off);
22040 	if (!tname) {
22041 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22042 		return -EINVAL;
22043 	}
22044 	if (tgt_prog) {
22045 		struct bpf_prog_aux *aux = tgt_prog->aux;
22046 		bool tgt_changes_pkt_data;
22047 		bool tgt_might_sleep;
22048 
22049 		if (bpf_prog_is_dev_bound(prog->aux) &&
22050 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22051 			bpf_log(log, "Target program bound device mismatch");
22052 			return -EINVAL;
22053 		}
22054 
22055 		for (i = 0; i < aux->func_info_cnt; i++)
22056 			if (aux->func_info[i].type_id == btf_id) {
22057 				subprog = i;
22058 				break;
22059 			}
22060 		if (subprog == -1) {
22061 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22062 			return -EINVAL;
22063 		}
22064 		/*
22065 		 * A struct_ops indirect trampoline converts arena arguments
22066 		 * before invoking its program. A tracing or extension program
22067 		 * attached to the main program would see the converted offset as a
22068 		 * regular BTF pointer.
22069 		 */
22070 		if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) {
22071 			bpf_log(log, "Cannot attach to a target with arena context arguments\n");
22072 			return -EOPNOTSUPP;
22073 		}
22074 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22075 			bpf_log(log,
22076 				"%s programs cannot attach to exception callback\n",
22077 				prog_extension ? "Extension" : "Tracing");
22078 			return -EINVAL;
22079 		}
22080 		conservative = aux->func_info_aux[subprog].unreliable;
22081 		if (prog_extension) {
22082 			if (conservative) {
22083 				bpf_log(log,
22084 					"Cannot replace static functions\n");
22085 				return -EINVAL;
22086 			}
22087 			if (!prog->jit_requested) {
22088 				bpf_log(log,
22089 					"Extension programs should be JITed\n");
22090 				return -EINVAL;
22091 			}
22092 			tgt_changes_pkt_data = aux->func
22093 					       ? aux->func[subprog]->aux->changes_pkt_data
22094 					       : aux->changes_pkt_data;
22095 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
22096 				bpf_log(log,
22097 					"Extension program changes packet data, while original does not\n");
22098 				return -EINVAL;
22099 			}
22100 
22101 			tgt_might_sleep = aux->func
22102 					  ? aux->func[subprog]->aux->might_sleep
22103 					  : aux->might_sleep;
22104 			if (prog->aux->might_sleep && !tgt_might_sleep) {
22105 				bpf_log(log,
22106 					"Extension program may sleep, while original does not\n");
22107 				return -EINVAL;
22108 			}
22109 		}
22110 		if (!tgt_prog->jited) {
22111 			bpf_log(log, "Can attach to only JITed progs\n");
22112 			return -EINVAL;
22113 		}
22114 		if (prog_tracing) {
22115 			if (aux->attach_tracing_prog) {
22116 				/*
22117 				 * Target program is an fentry/fexit which is already attached
22118 				 * to another tracing program. More levels of nesting
22119 				 * attachment are not allowed.
22120 				 */
22121 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22122 				return -EINVAL;
22123 			}
22124 		} else if (tgt_prog->type == prog->type) {
22125 			/*
22126 			 * To avoid potential call chain cycles, prevent attaching of a
22127 			 * program extension to another extension. It's ok to attach
22128 			 * fentry/fexit to extension program.
22129 			 */
22130 			bpf_log(log, "Cannot recursively attach\n");
22131 			return -EINVAL;
22132 		}
22133 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
22134 		    prog_extension &&
22135 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
22136 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
22137 		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
22138 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
22139 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
22140 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
22141 			/* Program extensions can extend all program types
22142 			 * except fentry/fexit. The reason is the following.
22143 			 * The fentry/fexit programs are used for performance
22144 			 * analysis, stats and can be attached to any program
22145 			 * type. When extension program is replacing XDP function
22146 			 * it is necessary to allow performance analysis of all
22147 			 * functions. Both original XDP program and its program
22148 			 * extension. Hence attaching fentry/fexit to
22149 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22150 			 * fentry/fexit was allowed it would be possible to create
22151 			 * long call chain fentry->extension->fentry->extension
22152 			 * beyond reasonable stack size. Hence extending fentry
22153 			 * is not allowed.
22154 			 */
22155 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
22156 			return -EINVAL;
22157 		}
22158 	} else {
22159 		if (prog_extension) {
22160 			bpf_log(log, "Cannot replace kernel functions\n");
22161 			return -EINVAL;
22162 		}
22163 	}
22164 
22165 	switch (prog->expected_attach_type) {
22166 	case BPF_TRACE_RAW_TP:
22167 		if (tgt_prog) {
22168 			bpf_log(log,
22169 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
22170 			return -EINVAL;
22171 		}
22172 		if (!btf_type_is_typedef(t)) {
22173 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22174 				btf_id);
22175 			return -EINVAL;
22176 		}
22177 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22178 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22179 				btf_id, tname);
22180 			return -EINVAL;
22181 		}
22182 		tname += sizeof(prefix) - 1;
22183 
22184 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22185 		 * names. Thus using bpf_raw_event_map to get argument names.
22186 		 */
22187 		btp = bpf_get_raw_tracepoint(tname);
22188 		if (!btp)
22189 			return -EINVAL;
22190 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
22191 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
22192 				tname);
22193 			bpf_put_raw_tracepoint(btp);
22194 			return -EINVAL;
22195 		}
22196 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22197 					trace_symbol);
22198 		bpf_put_raw_tracepoint(btp);
22199 
22200 		if (fname)
22201 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22202 
22203 		if (!fname || ret < 0) {
22204 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22205 				prefix, tname);
22206 			t = btf_type_by_id(btf, t->type);
22207 			if (!btf_type_is_ptr(t))
22208 				/* should never happen in valid vmlinux build */
22209 				return -EINVAL;
22210 		} else {
22211 			t = btf_type_by_id(btf, ret);
22212 			if (!btf_type_is_func(t))
22213 				/* should never happen in valid vmlinux build */
22214 				return -EINVAL;
22215 		}
22216 
22217 		t = btf_type_by_id(btf, t->type);
22218 		if (!btf_type_is_func_proto(t))
22219 			/* should never happen in valid vmlinux build */
22220 			return -EINVAL;
22221 
22222 		break;
22223 	case BPF_TRACE_ITER:
22224 		if (!btf_type_is_func(t)) {
22225 			bpf_log(log, "attach_btf_id %u is not a function\n",
22226 				btf_id);
22227 			return -EINVAL;
22228 		}
22229 		t = btf_type_by_id(btf, t->type);
22230 		if (!btf_type_is_func_proto(t))
22231 			return -EINVAL;
22232 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22233 		if (ret)
22234 			return ret;
22235 		break;
22236 	default:
22237 		if (!prog_extension)
22238 			return -EINVAL;
22239 		fallthrough;
22240 	case BPF_MODIFY_RETURN:
22241 	case BPF_LSM_MAC:
22242 	case BPF_LSM_CGROUP:
22243 	case BPF_TRACE_FENTRY:
22244 	case BPF_TRACE_FEXIT:
22245 	case BPF_TRACE_FSESSION:
22246 	case BPF_TRACE_FSESSION_MULTI:
22247 	case BPF_TRACE_FENTRY_MULTI:
22248 	case BPF_TRACE_FEXIT_MULTI:
22249 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
22250 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
22251 		    !bpf_jit_supports_fsession()) {
22252 			bpf_log(log, "JIT does not support fsession\n");
22253 			return -EOPNOTSUPP;
22254 		}
22255 		if (!btf_type_is_func(t)) {
22256 			bpf_log(log, "attach_btf_id %u is not a function\n",
22257 				btf_id);
22258 			return -EINVAL;
22259 		}
22260 		if (prog_extension &&
22261 		    btf_check_type_match(log, prog, btf, t))
22262 			return -EINVAL;
22263 		t = btf_attach_func_proto(log, btf, btf_id);
22264 		if (!t || !btf_type_is_func_proto(t))
22265 			return -EINVAL;
22266 
22267 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22268 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22269 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22270 			return -EINVAL;
22271 
22272 		if (tgt_prog && conservative)
22273 			t = NULL;
22274 
22275 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22276 		if (ret < 0)
22277 			return ret;
22278 
22279 		if (tgt_info->fmodel.ret_size > 8 &&
22280 		    attach_uses_trampoline_retval(prog->expected_attach_type)) {
22281 			bpf_log(log,
22282 				"Attach to function %s with a >8 byte return value is not supported for this attach type\n",
22283 				tname);
22284 			return -EOPNOTSUPP;
22285 		}
22286 
22287 		/*
22288 		 * *.multi programs don't need an address during program
22289 		 * verification, we just take the module ref if needed.
22290 		 */
22291 		if (is_tracing_multi_id(prog, btf_id)) {
22292 			if (btf_is_module(btf)) {
22293 				mod = btf_try_get_module(btf);
22294 				if (!mod)
22295 					return -ENOENT;
22296 			}
22297 			addr = 0;
22298 		} else if (tgt_prog) {
22299 			if (subprog == 0)
22300 				addr = (long) tgt_prog->bpf_func;
22301 			else
22302 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22303 		} else {
22304 			if (btf_is_module(btf)) {
22305 				mod = btf_try_get_module(btf);
22306 				if (mod)
22307 					addr = find_kallsyms_symbol_value(mod, tname);
22308 				else
22309 					addr = 0;
22310 			} else {
22311 				addr = kallsyms_lookup_name(tname);
22312 			}
22313 			if (!addr) {
22314 				module_put(mod);
22315 				bpf_log(log,
22316 					"The address of function %s cannot be found\n",
22317 					tname);
22318 				return -ENOENT;
22319 			}
22320 		}
22321 
22322 		if (prog->sleepable) {
22323 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
22324 			if (ret) {
22325 				module_put(mod);
22326 				bpf_log(log, "%s is not sleepable\n", tname);
22327 				return ret;
22328 			}
22329 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22330 			if (tgt_prog) {
22331 				module_put(mod);
22332 				bpf_log(log, "can't modify return codes of BPF programs\n");
22333 				return -EINVAL;
22334 			}
22335 			ret = -EINVAL;
22336 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22337 			    !check_attach_modify_return(addr, tname))
22338 				ret = 0;
22339 			if (ret) {
22340 				module_put(mod);
22341 				bpf_log(log, "%s() is not modifiable\n", tname);
22342 				return ret;
22343 			}
22344 		}
22345 
22346 		break;
22347 	}
22348 	tgt_info->tgt_addr = addr;
22349 	tgt_info->tgt_name = tname;
22350 	tgt_info->tgt_type = t;
22351 	tgt_info->tgt_mod = mod;
22352 	return 0;
22353 }
22354 
22355 BTF_SET_START(btf_id_deny)
22356 BTF_ID_UNUSED
22357 #ifdef CONFIG_SMP
22358 BTF_ID(func, ___migrate_enable)
22359 BTF_ID(func, migrate_disable)
22360 BTF_ID(func, migrate_enable)
22361 #endif
22362 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22363 BTF_ID(func, rcu_read_unlock_strict)
22364 #endif
22365 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22366 BTF_ID(func, preempt_count_add)
22367 BTF_ID(func, preempt_count_sub)
22368 #endif
22369 #ifdef CONFIG_PREEMPT_RCU
22370 BTF_ID(func, __rcu_read_lock)
22371 BTF_ID(func, __rcu_read_unlock)
22372 #endif
22373 BTF_SET_END(btf_id_deny)
22374 
22375 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
22376  * Currently, we must manually list all __noreturn functions here. Once a more
22377  * robust solution is implemented, this workaround can be removed.
22378  */
22379 BTF_SET_START(noreturn_deny)
22380 #ifdef CONFIG_IA32_EMULATION
22381 BTF_ID(func, __ia32_sys_exit)
22382 BTF_ID(func, __ia32_sys_exit_group)
22383 #endif
22384 #ifdef CONFIG_KUNIT
22385 BTF_ID(func, __kunit_abort)
22386 BTF_ID(func, kunit_try_catch_throw)
22387 #endif
22388 #ifdef CONFIG_MODULES
22389 BTF_ID(func, __module_put_and_kthread_exit)
22390 #endif
22391 #ifdef CONFIG_X86_64
22392 BTF_ID(func, __x64_sys_exit)
22393 BTF_ID(func, __x64_sys_exit_group)
22394 #endif
22395 BTF_ID(func, do_exit)
22396 BTF_ID(func, do_group_exit)
22397 BTF_ID(func, kthread_complete_and_exit)
22398 BTF_ID(func, make_task_dead)
22399 BTF_SET_END(noreturn_deny)
22400 
22401 static bool can_be_sleepable(struct bpf_prog *prog)
22402 {
22403 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22404 		switch (prog->expected_attach_type) {
22405 		case BPF_TRACE_FENTRY:
22406 		case BPF_TRACE_FEXIT:
22407 		case BPF_MODIFY_RETURN:
22408 		case BPF_TRACE_ITER:
22409 		case BPF_TRACE_FSESSION:
22410 		case BPF_TRACE_RAW_TP:
22411 		case BPF_TRACE_FENTRY_MULTI:
22412 		case BPF_TRACE_FEXIT_MULTI:
22413 		case BPF_TRACE_FSESSION_MULTI:
22414 			return true;
22415 		default:
22416 			return false;
22417 		}
22418 	}
22419 	if (prog->type == BPF_PROG_TYPE_LSM)
22420 		return prog->expected_attach_type != BPF_LSM_CGROUP;
22421 
22422 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22423 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
22424 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
22425 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
22426 }
22427 
22428 static int check_attach_btf_id(struct bpf_verifier_env *env)
22429 {
22430 	struct bpf_prog *prog = env->prog;
22431 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22432 	struct bpf_attach_target_info tgt_info = {};
22433 	u32 btf_id = prog->aux->attach_btf_id;
22434 	struct bpf_trampoline *tr;
22435 	int ret;
22436 	u64 key;
22437 
22438 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22439 		if (prog->sleepable)
22440 			/* attach_btf_id checked to be zero already */
22441 			return 0;
22442 		verbose(env, "Syscall programs can only be sleepable\n");
22443 		return -EINVAL;
22444 	}
22445 
22446 	if (prog->sleepable && !can_be_sleepable(prog)) {
22447 		verbose(env, "Program of this type cannot be sleepable\n");
22448 		return -EINVAL;
22449 	}
22450 
22451 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22452 		return check_struct_ops_btf_id(env);
22453 
22454 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22455 	    prog->type != BPF_PROG_TYPE_LSM &&
22456 	    prog->type != BPF_PROG_TYPE_EXT)
22457 		return 0;
22458 
22459 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22460 	if (ret)
22461 		return ret;
22462 
22463 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22464 		/* to make freplace equivalent to their targets, they need to
22465 		 * inherit env->ops and expected_attach_type for the rest of the
22466 		 * verification
22467 		 */
22468 		env->ops = bpf_verifier_ops[tgt_prog->type];
22469 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22470 	}
22471 
22472 	/* store info about the attachment target that will be used later */
22473 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22474 	prog->aux->attach_func_name = tgt_info.tgt_name;
22475 	prog->aux->mod = tgt_info.tgt_mod;
22476 
22477 	if (tgt_prog) {
22478 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22479 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22480 	}
22481 
22482 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22483 		prog->aux->attach_btf_trace = true;
22484 		return 0;
22485 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22486 		return bpf_iter_prog_supported(prog);
22487 	}
22488 
22489 	if (prog->type == BPF_PROG_TYPE_LSM) {
22490 		ret = bpf_lsm_verify_prog(&env->log, prog);
22491 		if (ret < 0)
22492 			return ret;
22493 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
22494 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
22495 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
22496 			tgt_info.tgt_name);
22497 		return -EINVAL;
22498 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
22499 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
22500 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
22501 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
22502 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
22503 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
22504 			tgt_info.tgt_name);
22505 		return -EINVAL;
22506 	}
22507 
22508 	/*
22509 	 * We don't get trampoline for tracing_multi programs at this point,
22510 	 * it's done when tracing_multi link is created.
22511 	 */
22512 	if (prog->type == BPF_PROG_TYPE_TRACING &&
22513 	    is_tracing_multi(prog->expected_attach_type))
22514 		return 0;
22515 
22516 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22517 	tr = bpf_trampoline_get(key, &tgt_info);
22518 	if (!tr)
22519 		return -ENOMEM;
22520 
22521 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22522 		bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX);
22523 
22524 	prog->aux->dst_trampoline = tr;
22525 	return 0;
22526 }
22527 
22528 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
22529 				  struct bpf_attach_target_info *tgt_info)
22530 {
22531 	const struct btf_type *t;
22532 	unsigned long addr;
22533 	const char *tname;
22534 	int err;
22535 
22536 	if (!btf_id || !btf)
22537 		return -EINVAL;
22538 
22539 	/* Check noreturn attachment. */
22540 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
22541 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
22542 	     btf_id_set_contains(&noreturn_deny, btf_id))
22543 		return -EINVAL;
22544 	/* Check denied attachment. */
22545 	if (btf_id_set_contains(&btf_id_deny, btf_id))
22546 		return -EINVAL;
22547 
22548 	/* Check and get function target data. */
22549 	t = btf_type_by_id(btf, btf_id);
22550 	if (!t)
22551 		return -EINVAL;
22552 	tname = btf_name_by_offset(btf, t->name_off);
22553 	if (!tname)
22554 		return -EINVAL;
22555 	t = btf_attach_func_proto(NULL, btf, btf_id);
22556 	if (!t || !btf_type_is_func_proto(t))
22557 		return -EINVAL;
22558 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
22559 	if (err < 0)
22560 		return err;
22561 	if (tgt_info->fmodel.ret_size > 8 &&
22562 	    attach_uses_trampoline_retval(prog->expected_attach_type))
22563 		return -EOPNOTSUPP;
22564 	if (btf_is_module(btf)) {
22565 		/* The bpf program already holds reference to module. */
22566 		if (WARN_ON_ONCE(!prog->aux->mod))
22567 			return -EINVAL;
22568 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
22569 	} else {
22570 		addr = kallsyms_lookup_name(tname);
22571 	}
22572 	if (!addr || !ftrace_location(addr))
22573 		return -ENOENT;
22574 
22575 	/* Check sleepable program attachment. */
22576 	if (prog->sleepable) {
22577 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
22578 		if (err)
22579 			return err;
22580 	}
22581 	tgt_info->tgt_addr = addr;
22582 	return 0;
22583 }
22584 
22585 struct btf *bpf_get_btf_vmlinux(void)
22586 {
22587 	/* Pairs with the smp_store_release() on the parse path below. */
22588 	struct btf *btf = smp_load_acquire(&btf_vmlinux);
22589 
22590 	if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22591 		mutex_lock(&btf_vmlinux_lock);
22592 		btf = btf_vmlinux;
22593 		if (!btf) {
22594 			btf = btf_parse_vmlinux();
22595 			/*
22596 			 * Order the parsed BTF contents and the globals the
22597 			 * parse populated (e.g. bpf_ctx_convert.t) before
22598 			 * the pointer publication. Pairs with the acquire
22599 			 * on the lockless fast path above.
22600 			 */
22601 			smp_store_release(&btf_vmlinux, btf);
22602 		}
22603 		mutex_unlock(&btf_vmlinux_lock);
22604 	}
22605 	return btf;
22606 }
22607 
22608 /*
22609  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
22610  * this case expect that every file descriptor in the array is either a map or
22611  * a BTF. Everything else is considered to be trash.
22612  */
22613 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd)
22614 {
22615 	struct bpf_map *map;
22616 	struct btf *btf;
22617 	CLASS(fd, f)(fd);
22618 	int err;
22619 
22620 	map = __bpf_map_get(f);
22621 	if (!IS_ERR(map)) {
22622 		err = __add_used_map(env, map);
22623 		if (err < 0)
22624 			return err;
22625 		fd_slot_set_map(&env->fd_array[idx], map);
22626 		return 0;
22627 	}
22628 
22629 	btf = __btf_get_by_fd(f);
22630 	if (!IS_ERR(btf)) {
22631 		btf_get(btf);
22632 		err = __add_used_btf(env, btf);
22633 		if (err < 0)
22634 			return err;
22635 		fd_slot_set_btf(&env->fd_array[idx], btf);
22636 		return 0;
22637 	}
22638 
22639 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
22640 	return PTR_ERR(map);
22641 }
22642 
22643 /*
22644  * A continuous fd_array is resolved into an in-memory cache with one slot
22645  * per entry. The bound here is deliberately generous and not derived from
22646  * the per-program object limits: Duplicate entries /are/ permitted, and
22647  * the number of distinct maps and BTFs a program can bind is enforced when
22648  * each entry is resolved by __add_used_map() and __add_used_btf().
22649  */
22650 #define MAX_FD_ARRAY_CNT 4096
22651 
22652 static int process_fd_array_continuous(struct bpf_verifier_env *env,
22653 				       bpfptr_t fd_array, u32 cnt)
22654 {
22655 	int fd, ret;
22656 	u32 i;
22657 
22658 	if (cnt > MAX_FD_ARRAY_CNT) {
22659 		verbose(env, "fd_array has too many entries (%u, max %u)\n",
22660 			cnt, MAX_FD_ARRAY_CNT);
22661 		return -E2BIG;
22662 	}
22663 
22664 	env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT);
22665 	if (!env->fd_array)
22666 		return -ENOMEM;
22667 	env->fd_array_cnt = cnt;
22668 	for (i = 0; i < cnt; i++) {
22669 		if (copy_from_bpfptr_offset(&fd, fd_array,
22670 					    (size_t)i * sizeof(fd), sizeof(fd)))
22671 			return -EFAULT;
22672 		ret = add_fd_from_fd_array(env, i, fd);
22673 		if (ret)
22674 			return ret;
22675 	}
22676 	return 0;
22677 }
22678 
22679 static int process_fd_array(struct bpf_verifier_env *env,
22680 			    union bpf_attr *attr, bpfptr_t uattr)
22681 {
22682 	bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22683 
22684 	if (bpfptr_is_null(fd_array)) {
22685 		if (attr->fd_array_cnt) {
22686 			verbose(env, "fd_array_cnt %u without fd_array is invalid\n",
22687 				attr->fd_array_cnt);
22688 			return -EINVAL;
22689 		}
22690 		return 0;
22691 	}
22692 	/*
22693 	 * New API: the caller passes fd_array_cnt and a continuous array that
22694 	 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep
22695 	 * the caller's array and resolve entries on the spot at each reference.
22696 	 */
22697 	if (attr->fd_array_cnt)
22698 		return process_fd_array_continuous(env, fd_array,
22699 						   attr->fd_array_cnt);
22700 	env->fd_array_raw = fd_array;
22701 	return 0;
22702 }
22703 
22704 /* replace a generic kfunc with a specialized version if necessary */
22705 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
22706 {
22707 	struct bpf_prog *prog = env->prog;
22708 	bool seen_direct_write;
22709 	void *xdp_kfunc;
22710 	bool is_rdonly;
22711 	u32 func_id = desc->func_id;
22712 	u16 offset = desc->offset;
22713 	unsigned long addr = desc->addr;
22714 
22715 	if (offset) /* return if module BTF is used */
22716 		return 0;
22717 
22718 	if (bpf_dev_bound_kfunc_id(func_id)) {
22719 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
22720 		if (xdp_kfunc)
22721 			addr = (unsigned long)xdp_kfunc;
22722 		/* fallback to default kfunc when not supported by netdev */
22723 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
22724 		seen_direct_write = env->seen_direct_write;
22725 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
22726 
22727 		if (is_rdonly)
22728 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
22729 
22730 		/* restore env->seen_direct_write to its original value, since
22731 		 * may_access_direct_pkt_data mutates it
22732 		 */
22733 		env->seen_direct_write = seen_direct_write;
22734 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
22735 		if (bpf_lsm_has_d_inode_locked(prog))
22736 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
22737 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
22738 		if (bpf_lsm_has_d_inode_locked(prog))
22739 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
22740 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
22741 		if (!env->insn_aux_data[insn_idx].non_sleepable)
22742 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
22743 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
22744 		if (env->insn_aux_data[insn_idx].non_sleepable)
22745 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
22746 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
22747 		if (env->insn_aux_data[insn_idx].non_sleepable)
22748 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
22749 	}
22750 	desc->addr = addr;
22751 	return 0;
22752 }
22753 
22754 static int add_kfunc_desc_target(struct bpf_verifier_env *env,
22755 				 const struct bpf_kfunc_desc *target_desc,
22756 				 u16 base_desc_idx, u16 *desc_idx)
22757 {
22758 	struct bpf_kfunc_desc desc = *target_desc;
22759 	struct bpf_kfunc_desc_tab *new_tab;
22760 	struct bpf_kfunc_desc_tab *tab;
22761 	struct bpf_prog_aux *prog_aux;
22762 	u32 i;
22763 
22764 	prog_aux = env->prog->aux;
22765 	tab = prog_aux->kfunc_tab;
22766 
22767 	if (base_desc_idx >= tab->nr_base_descs) {
22768 		verifier_bug(env, "kfunc desc_idx %d out of bounds (%d descriptors)",
22769 				base_desc_idx, tab->nr_base_descs);
22770 		return -EFAULT;
22771 	}
22772 	if (tab->descs[base_desc_idx].func_id != desc.func_id) {
22773 		verifier_bug(env, "kfunc desc %d has invalid id (expected %d, got %d)",
22774 				base_desc_idx, tab->descs[base_desc_idx].func_id, desc.func_id);
22775 		return -EFAULT;
22776 	}
22777 	if (tab->descs[base_desc_idx].offset != desc.offset) {
22778 		verifier_bug(env, "kfunc desc %d has invalid offset (expected %d, got %d)",
22779 				base_desc_idx, tab->descs[base_desc_idx].offset, desc.offset);
22780 		return -EFAULT;
22781 	}
22782 
22783 	if (tab->descs[base_desc_idx].addr == desc.addr) {
22784 		*desc_idx = base_desc_idx;
22785 		return 0;
22786 	}
22787 
22788 	for (i = tab->nr_base_descs; i < tab->nr_descs; i++) {
22789 		if (tab->descs[i].func_id == desc.func_id &&
22790 		    tab->descs[i].offset == desc.offset &&
22791 		    tab->descs[i].addr == desc.addr) {
22792 			*desc_idx = i;
22793 			return 0;
22794 		}
22795 	}
22796 
22797 	if (tab->nr_descs == MAX_KFUNC_CALL_DESCS) {
22798 		verbose(env, "too many different kernel function call targets\n");
22799 		return -E2BIG;
22800 	}
22801 
22802 	new_tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1),
22803 			   GFP_KERNEL_ACCOUNT);
22804 	if (!new_tab)
22805 		return -ENOMEM;
22806 	tab = new_tab;
22807 	prog_aux->kfunc_tab = tab;
22808 
22809 	*desc_idx = tab->nr_descs;
22810 	tab->descs[tab->nr_descs++] = desc;
22811 	return 0;
22812 }
22813 
22814 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
22815 					    u16 struct_meta_reg,
22816 					    u16 node_offset_reg,
22817 					    struct bpf_insn *insn,
22818 					    struct bpf_insn *insn_buf,
22819 					    int *cnt)
22820 {
22821 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
22822 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
22823 
22824 	insn_buf[0] = addr[0];
22825 	insn_buf[1] = addr[1];
22826 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
22827 	insn_buf[3] = *insn;
22828 	*cnt = 4;
22829 }
22830 
22831 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
22832 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
22833 {
22834 	struct bpf_kfunc_desc desc_copy;
22835 	struct bpf_kfunc_desc *desc;
22836 	unsigned long call_imm;
22837 	u16 base_desc_idx, desc_idx;
22838 	bool near_call;
22839 	int err;
22840 
22841 	if (!insn->imm) {
22842 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
22843 		return -EINVAL;
22844 	}
22845 
22846 	*cnt = 0;
22847 
22848 	/* insn->imm has the btf func_id. Replace it with an offset relative to
22849 	 * __bpf_call_base, unless the JIT needs to call functions that are
22850 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
22851 	 */
22852 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
22853 	if (!desc) {
22854 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
22855 			     insn->imm);
22856 		return -EFAULT;
22857 	}
22858 	base_desc_idx = desc - env->prog->aux->kfunc_tab->descs;
22859 
22860 	near_call = !bpf_jit_supports_far_kfunc_call();
22861 	desc_copy = *desc;
22862 	desc = &desc_copy;
22863 
22864 	err = specialize_kfunc(env, desc, insn_idx);
22865 	if (err)
22866 		return err;
22867 
22868 	if (near_call) {
22869 		call_imm = BPF_CALL_IMM(desc->addr);
22870 		if ((unsigned long)(s32)call_imm != call_imm) {
22871 			verbose(env, "address of kernel func_id %u is out of range\n",
22872 				desc->func_id);
22873 			return -EINVAL;
22874 		}
22875 		insn->imm = call_imm;
22876 	}
22877 
22878 	err = add_kfunc_desc_target(env, desc, base_desc_idx, &desc_idx);
22879 	if (err)
22880 		return err;
22881 	insn->off = desc_idx;
22882 
22883 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
22884 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22885 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22886 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
22887 
22888 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
22889 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22890 				     insn_idx);
22891 			return -EFAULT;
22892 		}
22893 
22894 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
22895 		insn_buf[1] = addr[0];
22896 		insn_buf[2] = addr[1];
22897 		insn_buf[3] = *insn;
22898 		*cnt = 4;
22899 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
22900 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
22901 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
22902 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22903 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22904 
22905 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
22906 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22907 				     insn_idx);
22908 			return -EFAULT;
22909 		}
22910 
22911 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
22912 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22913 				     insn_idx);
22914 			return -EFAULT;
22915 		}
22916 
22917 		insn_buf[0] = addr[0];
22918 		insn_buf[1] = addr[1];
22919 		insn_buf[2] = *insn;
22920 		*cnt = 3;
22921 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
22922 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
22923 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22924 		int struct_meta_reg = BPF_REG_3;
22925 		int node_offset_reg = BPF_REG_4;
22926 
22927 		/* list_add/rbtree_add have an extra arg (prev/less),
22928 		 * so args-to-fixup are in diff regs.
22929 		 */
22930 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
22931 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
22932 			struct_meta_reg = BPF_REG_4;
22933 			node_offset_reg = BPF_REG_5;
22934 		}
22935 
22936 		if (!kptr_struct_meta) {
22937 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22938 				     insn_idx);
22939 			return -EFAULT;
22940 		}
22941 
22942 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
22943 						node_offset_reg, insn, insn_buf, cnt);
22944 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
22945 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
22946 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22947 		*cnt = 1;
22948 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
22949 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
22950 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
22951 
22952 		/*
22953 		 * inline the bpf_session_is_return() for fsession:
22954 		 *   bool bpf_session_is_return(void *ctx)
22955 		 *   {
22956 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
22957 		 *   }
22958 		 */
22959 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22960 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
22961 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
22962 		*cnt = 3;
22963 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
22964 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
22965 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
22966 		/*
22967 		 * inline bpf_session_cookie() for fsession:
22968 		 *   __u64 *bpf_session_cookie(void *ctx)
22969 		 *   {
22970 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
22971 		 *       return &((u64 *)ctx)[-off];
22972 		 *   }
22973 		 */
22974 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22975 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
22976 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
22977 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22978 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
22979 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
22980 		*cnt = 6;
22981 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) {
22982 		/* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */
22983 		int i = 0;
22984 
22985 		/* if (start > end) goto einval; */
22986 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8);
22987 		/* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */
22988 		insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3);
22989 		insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2);
22990 		insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8);
22991 		/* s->cur = start - 1; s->end = end; return 0; */
22992 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1);
22993 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0);
22994 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4);
22995 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
22996 		insn_buf[i++] = BPF_JMP_A(5);
22997 		/* einval: s->cur = s->end = 0; return -EINVAL; */
22998 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
22999 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23000 		insn_buf[i++] = BPF_JMP_A(2);
23001 		/* e2big: s->cur = s->end = 0; return -E2BIG; */
23002 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23003 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
23004 		*cnt = i;
23005 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) {
23006 		/* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */
23007 		int i = 0;
23008 
23009 		/* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */
23010 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0);
23011 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1);
23012 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4);
23013 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3);
23014 		/* s->cur = r0; return &s->cur; */
23015 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0);
23016 		insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23017 		insn_buf[i++] = BPF_JMP_A(2);
23018 		/* done: s->cur = s->end = 0; return NULL; */
23019 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23020 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23021 		*cnt = i;
23022 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) {
23023 		/* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */
23024 		insn_buf[0] = BPF_JMP_A(0);
23025 		*cnt = 1;
23026 	}
23027 
23028 	if (env->insn_aux_data[insn_idx].arg_prog) {
23029 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
23030 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
23031 		int idx = *cnt;
23032 
23033 		insn_buf[idx++] = ld_addrs[0];
23034 		insn_buf[idx++] = ld_addrs[1];
23035 		insn_buf[idx++] = *insn;
23036 		*cnt = idx;
23037 	}
23038 	return 0;
23039 }
23040 
23041 /*
23042  * Upper bound on the PKCS#7 signature blob passed with a program. Comfortably
23043  * above the largest signature the kernel can verify, and far below anything
23044  * that would make rejecting a load expensive. Deliberately a fixed number so
23045  * that what the syscall accepts does not depend on PAGE_SIZE.
23046  */
23047 #define BPF_PROG_MAX_SIGNATURE_SIZE	(64 * 1024)
23048 
23049 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id)
23050 {
23051 	switch (keyring_id) {
23052 	case 0:
23053 		return BPF_SIG_KEYRING_BUILTIN;
23054 	case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING:
23055 		return BPF_SIG_KEYRING_SECONDARY;
23056 	case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING:
23057 		return BPF_SIG_KEYRING_PLATFORM;
23058 	case KEY_SPEC_BPF_KEYRING:
23059 		return BPF_SIG_KEYRING_BPF;
23060 	default:
23061 		return BPF_SIG_KEYRING_USER;
23062 	}
23063 }
23064 
23065 /*
23066  * Verify the PKCS#7 signature of a loaded program. Called from bpf_check()
23067  * once the program's metadata maps have been resolved into used_maps, so
23068  * the exact maps folded into the signature are the ones the program binds.
23069  *
23070  * The signature covers the instructions followed by the frozen contents of
23071  * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the
23072  * verdict and keyring info are recorded on prog->aux.
23073  */
23074 static int bpf_prog_verify_signature(struct bpf_verifier_env *env,
23075 				     union bpf_attr *attr, bool is_kernel)
23076 {
23077 	bpfptr_t usig = make_bpfptr(attr->signature, is_kernel);
23078 	struct bpf_dynptr_kern sig_ptr, data_ptr;
23079 	struct bpf_prog *prog = env->prog;
23080 	struct bpf_map **maps = env->used_maps;
23081 	struct bpf_key *key = NULL;
23082 	void *sig, *data = NULL;
23083 	u32 map_cnt = env->used_map_cnt;
23084 	u32 i, off, insns_sz;
23085 	u64 data_sz;
23086 	int err = 0;
23087 
23088 	if (!attr->signature_size ||
23089 	    attr->signature_size > BPF_PROG_MAX_SIGNATURE_SIZE)
23090 		return -EINVAL;
23091 
23092 	if (system_keyring_id_check(attr->keyring_id) == 0) {
23093 		key = bpf_lookup_system_key(attr->keyring_id);
23094 	} else if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23095 		key = bpf_lookup_keyring();
23096 	} else if (bpf_keyring_enforced()) {
23097 		verbose(env, "caller-supplied keyring refused, use bpf keyring\n");
23098 		return -EPERM;
23099 	} else {
23100 		key = bpf_lookup_user_key(attr->keyring_id, 0);
23101 	}
23102 	if (!key) {
23103 		if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23104 			verbose(env, "the bpf keyring is empty or has not been restricted\n");
23105 			return -ENOKEY;
23106 		}
23107 		verbose(env, "cannot resolve signing keyring with keyring_id %d\n",
23108 			attr->keyring_id);
23109 		return -EINVAL;
23110 	}
23111 
23112 	sig = kvmemdup_bpfptr(usig, attr->signature_size);
23113 	if (IS_ERR(sig)) {
23114 		bpf_key_put(key);
23115 		return PTR_ERR(sig);
23116 	}
23117 
23118 	insns_sz = prog->len * sizeof(struct bpf_insn);
23119 	data_sz = insns_sz;
23120 	for (i = 0; i < map_cnt; i++) {
23121 		struct bpf_map *map = maps[i];
23122 
23123 		if (map->map_type != BPF_MAP_TYPE_ARRAY ||
23124 		    !map->ops->map_direct_value_addr) {
23125 			verbose(env, "signed program metadata map '%s' must be an array\n",
23126 				map->name);
23127 			err = -EINVAL;
23128 			goto out;
23129 		}
23130 		if (!READ_ONCE(map->frozen)) {
23131 			verbose(env, "signed program metadata map '%s' must be frozen\n",
23132 				map->name);
23133 			err = -EPERM;
23134 			goto out;
23135 		}
23136 		if (bpf_map_write_active(map)) {
23137 			verbose(env, "signed program metadata map '%s' has active writers\n",
23138 				map->name);
23139 			err = -EBUSY;
23140 			goto out;
23141 		}
23142 		if (!map->excl_prog_sha) {
23143 			verbose(env, "signed program metadata map '%s' must be exclusive\n",
23144 				map->name);
23145 			err = -EPERM;
23146 			goto out;
23147 		}
23148 		data_sz += map->value_size;
23149 	}
23150 	if (bpf_dynptr_check_size(data_sz)) {
23151 		verbose(env, "signed payload too large: %llu bytes\n", data_sz);
23152 		err = -E2BIG;
23153 		goto out;
23154 	}
23155 	data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
23156 	if (!data) {
23157 		err = -ENOMEM;
23158 		goto out;
23159 	}
23160 	memcpy(data, prog->insnsi, insns_sz);
23161 	off = insns_sz;
23162 	for (i = 0; i < map_cnt; i++) {
23163 		struct bpf_map *map = maps[i];
23164 		u64 addr;
23165 
23166 		err = map->ops->map_direct_value_addr(map, &addr, 0);
23167 		if (err) {
23168 			verbose(env, "failed to read signed metadata map '%s': %d\n",
23169 				map->name, err);
23170 			goto out;
23171 		}
23172 		memcpy(data + off, (void *)(unsigned long)addr,
23173 		       map->value_size);
23174 		off += map->value_size;
23175 	}
23176 
23177 	bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz);
23178 	bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0,
23179 			attr->signature_size);
23180 
23181 	err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr,
23182 					 (struct bpf_dynptr *)&sig_ptr, key);
23183 	if (err) {
23184 		verbose(env, "signature verification failed: %d\n", err);
23185 	} else {
23186 		verbose(env, "signature verification passed\n");
23187 		prog->aux->sig.keyring_serial = bpf_key_serial(key);
23188 		prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id);
23189 		prog->aux->sig.verdict = BPF_SIG_VERIFIED;
23190 	}
23191 out:
23192 	kvfree(data);
23193 	bpf_key_put(key);
23194 	kvfree(sig);
23195 	return err;
23196 }
23197 
23198 /*
23199  * bpf_clone_redirect() transmits from inside the program, so a tc egress or
23200  * lwt_xmit program that redirects to its own device runs again on top of its
23201  * own frame, and again from there, until the datapath's recursion limit drops
23202  * the packet: ten frames deep. Ten MAX_BPF_STACK frames fit the kernel stack
23203  * as they always did; ten MAX_BPF_STACK_JIT frames would not, so a program
23204  * calling it keeps the smaller budget. The redirect helpers that transmit
23205  * after the program has returned leave no frame behind.
23206  */
23207 static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)
23208 {
23209 	const struct bpf_insn *insn = prog->insnsi;
23210 	int i;
23211 
23212 	for (i = 0; i < prog->len; i++, insn++)
23213 		if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_clone_redirect)
23214 			return true;
23215 	return false;
23216 }
23217 
23218 /* Various log level 2 information about the program */
23219 static void log_program(struct bpf_verifier_env *env)
23220 {
23221 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
23222 	struct bpf_insn *insns = env->prog->insnsi;
23223 	u32 insn_cnt = env->prog->len;
23224 	u64 pos, insn_pos;
23225 	u32 i, j;
23226 
23227 	verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
23228 	for (i = 0; i < insn_cnt; ++i) {
23229 		verbose_linfo(env, i, "    ; ");
23230 		if (env->insn_aux_data[i].scc)
23231 			verbose(env, "%3d ", env->insn_aux_data[i].scc);
23232 		else
23233 			verbose(env, "    ");
23234 		if (env->insn_aux_data[i].loop_header >= 0)
23235 			verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
23236 		else
23237 			verbose(env, "    ");
23238 		verbose(env, "%3d ", env->idoms[i]);
23239 		verbose(env, "%3d: ", i);
23240 		for (j = BPF_REG_0; j < BPF_REG_10; ++j)
23241 			if (insn_aux[i].live_regs_before & BIT(j))
23242 				verbose(env, "%d", j);
23243 			else
23244 				verbose(env, ".");
23245 		verbose(env, " ");
23246 		pos = env->log.end_pos;
23247 		bpf_verbose_insn(env, &insns[i]);
23248 		insn_pos = env->log.end_pos;
23249 		if (insn_aux[i].zext_dst)
23250 			verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
23251 		verbose(env, "\n");
23252 		if (bpf_is_ldimm64(&insns[i]))
23253 			i++;
23254 	}
23255 }
23256 
23257 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
23258 	      struct bpf_log_attr *attr_log)
23259 {
23260 	u64 start_time = ktime_get_ns();
23261 	struct bpf_verifier_env *env;
23262 	int i, len, ret = -EINVAL, err;
23263 	bool is_priv;
23264 
23265 	BTF_TYPE_EMIT(enum bpf_features);
23266 
23267 	/* no program is valid */
23268 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
23269 		return -EINVAL;
23270 
23271 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
23272 	 * allocate/free it every time bpf_check() is called
23273 	 */
23274 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
23275 	if (!env)
23276 		return -ENOMEM;
23277 
23278 	env->bt.env = env;
23279 	env->prog = *prog;
23280 	env->ops = bpf_verifier_ops[env->prog->type];
23281 	env->stack_limit = bpf_prog_stack_limit(env->prog);
23282 	if (bpf_prog_reenters_datapath(env->prog))
23283 		env->stack_limit = MAX_BPF_STACK;
23284 
23285 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
23286 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
23287 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
23288 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
23289 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
23290 	env->signature = attr->signature;
23291 
23292 	/* user could have requested verbose verifier output
23293 	 * and supplied buffer to store the verification trace
23294 	 */
23295 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
23296 	if (ret)
23297 		goto err_free_env;
23298 	ret = bpf_diag_init(env);
23299 	if (ret)
23300 		goto err_prep;
23301 	if (env->prog->insnsi[env->prog->len - 1].code == (BPF_LD | BPF_IMM | BPF_DW)) {
23302 		verbose(env, "invalid bpf_ld_imm64 insn\n");
23303 		ret = -EINVAL;
23304 		goto err_prep;
23305 	}
23306 	if (env->signature) {
23307 		ret = bpf_prog_calc_tag(env->prog);
23308 		if (ret < 0)
23309 			goto err_prep;
23310 	}
23311 
23312 	ret = process_fd_array(env, attr, uattr);
23313 	if (ret)
23314 		goto err_prep;
23315 
23316 	if (env->signature) {
23317 		ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel);
23318 		if (ret)
23319 			goto err_prep;
23320 	}
23321 
23322 	ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token,
23323 				     uattr.is_kernel);
23324 	if (ret)
23325 		goto err_prep;
23326 
23327 	bpf_get_btf_vmlinux();
23328 
23329 	/* Serialize verification of unprivileged programs. */
23330 	if (!is_priv)
23331 		mutex_lock(&bpf_verifier_lock);
23332 
23333 	len = env->insn_aux_data_len = env->prog->len;
23334 	env->insn_aux_data =
23335 		__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),
23336 			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
23337 	ret = -ENOMEM;
23338 	if (!env->insn_aux_data)
23339 		goto skip_full_check;
23340 	for (i = 0; i < len; i++)
23341 		env->insn_aux_data[i].orig_idx = i;
23342 	env->succ = bpf_iarray_realloc(NULL, 2);
23343 	if (!env->succ)
23344 		goto skip_full_check;
23345 
23346 	mark_verifier_state_clean(env);
23347 
23348 	if (IS_ERR(btf_vmlinux)) {
23349 		/* Either gcc or pahole or kernel are broken. */
23350 		verbose(env, "in-kernel BTF is malformed\n");
23351 		ret = PTR_ERR(btf_vmlinux);
23352 		goto skip_full_check;
23353 	}
23354 
23355 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
23356 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
23357 		env->strict_alignment = true;
23358 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
23359 		env->strict_alignment = false;
23360 
23361 	if (is_priv)
23362 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
23363 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
23364 	env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
23365 
23366 	env->explored_states = kvzalloc_objs(struct list_head,
23367 					     state_htab_size(env),
23368 					     GFP_KERNEL_ACCOUNT);
23369 	ret = -ENOMEM;
23370 	if (!env->explored_states)
23371 		goto skip_full_check;
23372 
23373 	for (i = 0; i < state_htab_size(env); i++)
23374 		INIT_LIST_HEAD(&env->explored_states[i]);
23375 	INIT_LIST_HEAD(&env->free_list);
23376 
23377 	/* Prepare BTF and func_info needed to discover all subprograms. */
23378 	ret = bpf_prepare_btf_info(env, attr, uattr);
23379 	if (ret < 0)
23380 		goto skip_full_check;
23381 
23382 	/* Apply CO-RE before validating the program's instruction layout. */
23383 	ret = bpf_check_core_relo(env, attr, uattr);
23384 	if (ret < 0)
23385 		goto skip_full_check;
23386 
23387 	/* Discover all subprograms and collect the properties needed by BTF validation. */
23388 	ret = add_subprogs(env);
23389 	if (ret < 0)
23390 		goto skip_full_check;
23391 
23392 	find_subprog_properties(env);
23393 
23394 	/* Validate BTF before reporting subprogram layout errors. */
23395 	ret = bpf_check_btf_info(env, attr, uattr);
23396 	if (ret < 0)
23397 		goto skip_full_check;
23398 
23399 	ret = check_subprogs(env);
23400 	if (ret < 0)
23401 		goto skip_full_check;
23402 
23403 	/* Validate instructions and resolve the program's referenced resources. */
23404 	ret = check_and_resolve_insns(env);
23405 	if (ret < 0)
23406 		goto skip_full_check;
23407 
23408 	/* Find pointers to functions in the read-only maps of the program. */
23409 	ret = resolve_func_ptrs(env);
23410 	if (ret < 0)
23411 		goto skip_full_check;
23412 
23413 	/* Build kfunc prototypes after resolving program resources. */
23414 	ret = add_kfuncs(env);
23415 	if (ret < 0)
23416 		goto skip_full_check;
23417 
23418 	if (bpf_prog_is_offloaded(env->prog->aux)) {
23419 		ret = bpf_prog_offload_verifier_prep(env->prog);
23420 		if (ret)
23421 			goto skip_full_check;
23422 	}
23423 
23424 	ret = bpf_check_cfg(env);
23425 	if (ret < 0)
23426 		goto skip_full_check;
23427 
23428 	ret = bpf_compute_postorder(env);
23429 	if (ret < 0)
23430 		goto skip_full_check;
23431 
23432 	ret = bpf_stack_liveness_init(env);
23433 	if (ret)
23434 		goto skip_full_check;
23435 
23436 	ret = check_attach_btf_id(env);
23437 	if (ret)
23438 		goto skip_full_check;
23439 
23440 	ret = bpf_compute_const_regs(env);
23441 	if (ret < 0)
23442 		goto skip_full_check;
23443 
23444 	ret = bpf_prune_dead_branches(env);
23445 	if (ret < 0)
23446 		goto skip_full_check;
23447 
23448 	ret = sort_subprogs_topo(env);
23449 	if (ret < 0)
23450 		goto skip_full_check;
23451 
23452 	ret = bpf_compute_scc(env);
23453 	if (ret < 0)
23454 		goto skip_full_check;
23455 
23456 	/* must precede the first bpf_ret_reg_pair() user below */
23457 	ret = bpf_compute_subprog_ret_regs(env);
23458 	if (ret < 0)
23459 		goto skip_full_check;
23460 
23461 	prepare_subprog_args(env);
23462 
23463 	ret = bpf_compute_idoms(env);
23464 	if (ret < 0)
23465 		goto skip_full_check;
23466 
23467 	ret = bpf_compute_loops(env);
23468 	if (ret < 0)
23469 		goto skip_full_check;
23470 
23471 	ret = bpf_compute_live_registers(env);
23472 	if (ret < 0)
23473 		goto skip_full_check;
23474 
23475 	if (env->log.level & BPF_LOG_LEVEL2)
23476 		log_program(env);
23477 
23478 	ret = bpf_init_scev(env);
23479 	if (ret < 0)
23480 		goto skip_full_check;
23481 
23482 	ret = bpf_compute_scev(env);
23483 	if (ret < 0)
23484 		goto skip_full_check;
23485 
23486 	ret = mark_fastcall_patterns(env);
23487 	if (ret < 0)
23488 		goto skip_full_check;
23489 
23490 	ret = do_check_main(env);
23491 	ret = ret ?: do_check_subprogs(env);
23492 
23493 	/* reject recursion through the callx edges found by the main pass */
23494 	if (ret == 0 && env->callx_edges)
23495 		ret = sort_subprogs_topo(env);
23496 
23497 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
23498 		ret = bpf_prog_offload_finalize(env);
23499 
23500 skip_full_check:
23501 	kvfree(env->explored_states);
23502 
23503 	/* might decrease stack depth, keep it before passes that
23504 	 * allocate additional slots.
23505 	 */
23506 	if (ret == 0)
23507 		ret = bpf_remove_fastcall_spills_fills(env);
23508 
23509 	if (ret == 0)
23510 		ret = check_max_stack_depth(env);
23511 
23512 	/* instruction rewrites happen after this point */
23513 	if (ret == 0)
23514 		ret = bpf_optimize_bpf_loop(env);
23515 
23516 	if (is_priv) {
23517 		if (ret == 0)
23518 			bpf_opt_hard_wire_dead_code_branches(env);
23519 		if (ret == 0)
23520 			ret = bpf_opt_remove_dead_code(env);
23521 		if (ret == 0)
23522 			ret = bpf_opt_remove_nops(env);
23523 	} else {
23524 		if (ret == 0)
23525 			sanitize_dead_code(env);
23526 	}
23527 
23528 	if (ret == 0)
23529 		/* program is valid, convert *(u32*)(ctx + off) accesses */
23530 		ret = bpf_convert_ctx_accesses(env);
23531 
23532 	if (ret == 0)
23533 		ret = bpf_do_misc_fixups(env);
23534 
23535 	/* do 32-bit optimization after insn patching has done so those patched
23536 	 * insns could be handled correctly.
23537 	 */
23538 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
23539 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
23540 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
23541 								     : false;
23542 	}
23543 
23544 	if (ret == 0)
23545 		ret = bpf_fixup_call_args(env);
23546 
23547 	env->verification_time = ktime_get_ns() - start_time;
23548 	print_verification_stats(env);
23549 	env->prog->aux->verified_insns = env->insn_processed;
23550 
23551 	/* preserve original error even if log finalization is successful */
23552 	err = bpf_log_attr_finalize(attr_log, &env->log);
23553 	if (err)
23554 		ret = err;
23555 
23556 	if (ret)
23557 		goto err_release_maps;
23558 
23559 	if (env->used_map_cnt) {
23560 		/* if program passed verifier, update used_maps in bpf_prog_info */
23561 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
23562 							 env->used_map_cnt,
23563 							 GFP_KERNEL_ACCOUNT);
23564 
23565 		if (!env->prog->aux->used_maps) {
23566 			ret = -ENOMEM;
23567 			goto err_release_maps;
23568 		}
23569 
23570 		memcpy(env->prog->aux->used_maps, env->used_maps,
23571 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
23572 		env->prog->aux->used_map_cnt = env->used_map_cnt;
23573 	}
23574 	if (env->used_btf_cnt) {
23575 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
23576 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
23577 							 env->used_btf_cnt,
23578 							 GFP_KERNEL_ACCOUNT);
23579 		if (!env->prog->aux->used_btfs) {
23580 			ret = -ENOMEM;
23581 			goto err_release_maps;
23582 		}
23583 
23584 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
23585 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
23586 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
23587 	}
23588 	if (env->used_map_cnt || env->used_btf_cnt) {
23589 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
23590 		 * bpf_ld_imm64 instructions
23591 		 */
23592 		convert_pseudo_ld_imm64(env);
23593 	}
23594 
23595 	adjust_btf_func(env);
23596 
23597 	/* extension progs temporarily inherit the attach_type of their targets
23598 	   for verification purposes, so set it back to zero before returning
23599 	 */
23600 	if (env->prog->type == BPF_PROG_TYPE_EXT)
23601 		env->prog->expected_attach_type = 0;
23602 
23603 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
23604 
23605 err_release_maps:
23606 	if (ret)
23607 		release_insn_arrays(env);
23608 	if (!env->prog->aux->used_maps)
23609 		/* if we didn't copy map pointers into bpf_prog_info, release
23610 		 * them now. Otherwise free_used_maps() will release them.
23611 		 */
23612 		release_maps(env);
23613 	if (!env->prog->aux->used_btfs)
23614 		release_btfs(env);
23615 
23616 	*prog = env->prog;
23617 
23618 	module_put(env->attach_btf_mod);
23619 	if (!is_priv)
23620 		mutex_unlock(&bpf_verifier_lock);
23621 	goto err_free_env;
23622 err_prep:
23623 	err = bpf_log_attr_finalize(attr_log, &env->log);
23624 	if (err)
23625 		ret = err;
23626 	release_insn_arrays(env);
23627 	release_maps(env);
23628 	release_btfs(env);
23629 err_free_env:
23630 	bpf_free_subprog_jts(env);
23631 	if (env->insn_aux_data)
23632 		bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
23633 	vfree(env->insn_aux_data);
23634 	kvfree(env->fd_array);
23635 	bpf_free_scev(env);
23636 	bpf_stack_liveness_free(env);
23637 	kvfree(env->cfg.postorder_nums);
23638 	kvfree(env->cfg.insn_postorder);
23639 	kvfree(env->scc_info);
23640 	kvfree(env->succ);
23641 	kvfree(env->gotox_tmp_buf);
23642 	kvfree(env->callx_edges);
23643 	kvfree(env->func_ptrs);
23644 	bpf_diag_free(env);
23645 	kvfree(env->idoms);
23646 	kvfree(env);
23647 	return ret;
23648 }
23649