xref: /linux/kernel/bpf/verifier.c (revision 9b27cd0554c5883318256c32b2aaf060a3e20e0a)
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 bool in_rcu_callback(struct bpf_verifier_env *env);
223 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
224 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
225 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
226 
227 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
228 			      struct bpf_map *map,
229 			      bool unpriv, bool poison)
230 {
231 	unpriv |= bpf_map_ptr_unpriv(aux);
232 	aux->map_ptr_state.unpriv = unpriv;
233 	aux->map_ptr_state.poison = poison;
234 	aux->map_ptr_state.map_ptr = map;
235 }
236 
237 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238 {
239 	bool poisoned = bpf_map_key_poisoned(aux);
240 
241 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
243 }
244 
245 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
246 {
247 	ref_obj->id = reg->id;
248 	ref_obj->parent_id = reg->parent_id;
249 	ref_obj->cnt++;
250 }
251 
252 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
253 {
254 	if (ref_obj->cnt > 1) {
255 		verifier_bug(env, "function expects only one referenced object but got %d\n",
256 			     ref_obj->cnt);
257 		return -EFAULT;
258 	}
259 
260 	return 0;
261 }
262 
263 struct bpf_kfunc_meta {
264 	struct btf *btf;
265 	const struct btf_type *proto;
266 	const char *name;
267 	const u32 *flags;
268 	s32 id;
269 };
270 
271 struct btf *btf_vmlinux;
272 
273 typedef struct argno {
274 	int argno;
275 } argno_t;
276 
277 static argno_t argno_from_reg(u32 regno)
278 {
279 	return (argno_t){ .argno = regno };
280 }
281 
282 static argno_t argno_from_arg(u32 arg)
283 {
284 	return (argno_t){ .argno = -arg };
285 }
286 
287 static int reg_from_argno(argno_t a)
288 {
289 	if (a.argno >= 0)
290 		return a.argno;
291 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
292 		return -a.argno;
293 	return -1;
294 }
295 
296 static int arg_from_argno(argno_t a)
297 {
298 	if (a.argno < 0)
299 		return -a.argno;
300 	return -1;
301 }
302 
303 static int arg_idx_from_argno(argno_t a)
304 {
305 	return arg_from_argno(a) - 1;
306 }
307 
308 /* Normalize helper register numbers and kfunc argument numbers to ABI slots. */
309 static u32 arg_slot_from_argno(argno_t a)
310 {
311 	return abs(a.argno) - 1;
312 }
313 
314 static const char *btf_type_name(const struct btf *btf, u32 id)
315 {
316 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
317 }
318 
319 static DEFINE_MUTEX(bpf_verifier_lock);
320 static DEFINE_MUTEX(btf_vmlinux_lock);
321 static DEFINE_MUTEX(bpf_percpu_ma_lock);
322 
323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324 {
325 	struct bpf_verifier_env *env = private_data;
326 	va_list args;
327 
328 	if (!bpf_verifier_log_needed(&env->log))
329 		return;
330 
331 	va_start(args, fmt);
332 	bpf_verifier_vlog(&env->log, fmt, args);
333 	va_end(args);
334 }
335 
336 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
337 				   struct bpf_reg_state *reg,
338 				   struct bpf_retval_range range, const char *ctx,
339 				   const char *reg_name)
340 {
341 	bool unknown = true;
342 
343 	verbose(env, "%s the register %s has", ctx, reg_name);
344 	if (reg_smin(reg) > S64_MIN) {
345 		verbose(env, " smin=%lld", reg_smin(reg));
346 		unknown = false;
347 	}
348 	if (reg_smax(reg) < S64_MAX) {
349 		verbose(env, " smax=%lld", reg_smax(reg));
350 		unknown = false;
351 	}
352 	if (unknown)
353 		verbose(env, " unknown scalar value");
354 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
355 }
356 
357 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
358 {
359 	enum bpf_reg_type type;
360 
361 	type = reg->type;
362 	if (type_may_be_null(type))
363 		return false;
364 
365 	/*
366 	 * The types below guarantee a non-NULL base, an unbounded offset can
367 	 * still wrap base + offset to zero.
368 	 */
369 	if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF)
370 		return false;
371 
372 	type = base_type(type);
373 	return type == PTR_TO_SOCKET ||
374 		type == PTR_TO_TCP_SOCK ||
375 		type == PTR_TO_XDP_SOCK ||
376 		type == PTR_TO_BUF ||
377 		type == PTR_TO_MAP_VALUE ||
378 		type == PTR_TO_MAP_KEY ||
379 		type == PTR_TO_SOCK_COMMON ||
380 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
381 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
382 		type == CONST_PTR_TO_MAP;
383 }
384 
385 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
386 {
387 	struct btf_record *rec = NULL;
388 	struct btf_struct_meta *meta;
389 
390 	if (reg->type == PTR_TO_MAP_VALUE) {
391 		rec = reg->map_ptr->record;
392 	} else if (type_is_ptr_alloc_obj(reg->type)) {
393 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
394 		if (meta)
395 			rec = meta->record;
396 	}
397 	return rec;
398 }
399 
400 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
401 {
402 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
403 
404 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
405 }
406 
407 static const struct btf_type *subprog_ret_type(struct bpf_verifier_env *env, int subprog)
408 {
409 	const struct btf_type *func, *func_proto;
410 	const struct btf *btf = env->prog->aux->btf;
411 	u32 btf_id;
412 
413 	if (!btf || !env->prog->aux->func_info)
414 		return NULL;
415 
416 	btf_id = env->prog->aux->func_info[subprog].type_id;
417 
418 	/* Both already validated by prepare_btf_func() at prog load. */
419 	func = btf_type_by_id(btf, btf_id);
420 	func_proto = btf_type_by_id(btf, func->type);
421 
422 	return btf_type_skip_modifiers(btf, func_proto->type, NULL);
423 }
424 
425 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
426 {
427 	const struct btf_type *type = subprog_ret_type(env, subprog);
428 
429 	return type && btf_type_is_void(type);
430 }
431 
432 static u32 ret_regs_cnt(u32 size)
433 {
434 	return size > 8 && size <= 16 ? 2 : 1;
435 }
436 
437 /* Registers holding a function return value, in order. See ret_regs_cnt(). */
438 static const int ret_regs[] = { BPF_REG_0, BPF_REG_2 };
439 
440 static int bpf_compute_subprog_ret_regs(struct bpf_verifier_env *env)
441 {
442 	const struct btf *btf = env->prog->aux->btf;
443 	const struct btf_type *type;
444 	int subprog;
445 	u32 size;
446 
447 	if (!env->prog->jit_requested || bpf_prog_is_offloaded(env->prog->aux))
448 		return 0;
449 
450 	/*
451 	 * Skip the main program: its return value is the program's exit code,
452 	 * read out of R0, so it never uses the register pair. An extension does
453 	 * have a real prototype for subprog 0, but btf_check_func_type_match()
454 	 * refuses to replace a function returning more than 8 bytes.
455 	 */
456 	for (subprog = 1; subprog < env->subprog_cnt; subprog++) {
457 		type = subprog_ret_type(env, subprog);
458 		if (!type || btf_type_is_void(type))
459 			continue;
460 		if (verifier_bug_if(IS_ERR(btf_resolve_size(btf, type, &size)), env,
461 				    "cannot size return type of subprog %d", subprog))
462 			return -EFAULT;
463 		if (ret_regs_cnt(size) > 1) {
464 			subprog_info(env, subprog)->ret_reg_pair = true;
465 			env->prog->jit_required = 1;
466 		}
467 	}
468 
469 	return 0;
470 }
471 
472 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)
473 {
474 	struct bpf_func_info *info;
475 
476 	if (!env->prog->aux->func_info)
477 		return "";
478 
479 	info = &env->prog->aux->func_info[subprog];
480 	return btf_type_name(env->prog->aux->btf, info->type_id);
481 }
482 
483 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
484 {
485 	struct bpf_subprog_info *info = subprog_info(env, subprog);
486 
487 	info->is_cb = true;
488 	info->is_async_cb = true;
489 	info->is_exception_cb = true;
490 }
491 
492 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
493 {
494 	return subprog_info(env, subprog)->is_exception_cb;
495 }
496 
497 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498 {
499 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
500 }
501 
502 static bool type_is_rdonly_mem(u32 type)
503 {
504 	return type & MEM_RDONLY;
505 }
506 
507 static bool is_acquire_function(enum bpf_func_id func_id,
508 				const struct bpf_map *map)
509 {
510 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511 
512 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
513 	    func_id == BPF_FUNC_sk_lookup_udp ||
514 	    func_id == BPF_FUNC_skc_lookup_tcp ||
515 	    func_id == BPF_FUNC_ringbuf_reserve ||
516 	    func_id == BPF_FUNC_kptr_xchg)
517 		return true;
518 
519 	if (func_id == BPF_FUNC_map_lookup_elem &&
520 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
521 	     map_type == BPF_MAP_TYPE_SOCKHASH))
522 		return true;
523 
524 	return false;
525 }
526 
527 static bool is_ptr_cast_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_tcp_sock ||
530 		func_id == BPF_FUNC_sk_fullsock ||
531 		func_id == BPF_FUNC_skc_to_tcp_sock ||
532 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
533 		func_id == BPF_FUNC_skc_to_udp6_sock ||
534 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
535 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
537 }
538 
539 static bool is_sync_callback_calling_kfunc(u32 btf_id);
540 static bool is_async_callback_calling_kfunc(u32 btf_id);
541 static bool is_call_rcu_kfunc(u32 btf_id);
542 static bool is_callback_calling_kfunc(u32 btf_id);
543 
544 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
545 static bool is_task_work_add_kfunc(u32 func_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
573 {
574 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
575 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
576 }
577 
578 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
579 {
580 	/* bpf_timer callbacks are never sleepable. */
581 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
582 		return false;
583 
584 	/* bpf_call_rcu and bpf_call_rcu_tasks_trace callbacks are never sleepable. */
585 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && is_call_rcu_kfunc(insn->imm))
586 		return false;
587 
588 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
589 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
590 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
591 		return true;
592 
593 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
594 	return false;
595 }
596 
597 /* From here on the maps of the program count it as a sleepable user. */
598 static void mark_sleepable_async_cb(struct bpf_verifier_env *env)
599 {
600 	int i;
601 
602 	if (bpf_prog_runs_sleepable(env->prog))
603 		return;
604 
605 	env->prog->aux->sleepable_async_cb = true;
606 	for (i = 0; i < env->used_map_cnt; i++)
607 		atomic64_inc(&env->used_maps[i]->sleepable_refcnt);
608 }
609 
610 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
611 {
612 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
613 }
614 
615 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
616 {
617 	int allocated_slots = bpf_stack_nr_slots(state);
618 
619 	/*
620 	 * We need to check that slots between [spi - nr_slots + 1, spi] are
621 	 * within [0, allocated_stack).
622 	 *
623 	 * Please note that the spi grows downwards. For example, a dynptr
624 	 * takes the size of two stack slots; the first slot will be at
625 	 * spi and the second slot will be at spi - 1.
626 	 */
627 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
628 }
629 
630 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
631 			          const char *obj_kind, int nr_slots)
632 {
633 	int off, spi;
634 
635 	if (!tnum_is_const(reg->var_off)) {
636 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
637 		return -EINVAL;
638 	}
639 
640 	off = reg->var_off.value;
641 	if (off >= 0 || off % BPF_REG_SIZE) {
642 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
643 		return -EINVAL;
644 	}
645 
646 	spi = bpf_get_spi(off);
647 	if (spi + 1 < nr_slots) {
648 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
649 		return -EINVAL;
650 	}
651 
652 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
653 		return -ERANGE;
654 	return spi;
655 }
656 
657 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
658 {
659 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
660 }
661 
662 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
663 {
664 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
665 }
666 
667 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
668 {
669 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
670 }
671 
672 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
673 {
674 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
675 	case DYNPTR_TYPE_LOCAL:
676 		return BPF_DYNPTR_TYPE_LOCAL;
677 	case DYNPTR_TYPE_RINGBUF:
678 		return BPF_DYNPTR_TYPE_RINGBUF;
679 	case DYNPTR_TYPE_SKB:
680 		return BPF_DYNPTR_TYPE_SKB;
681 	case DYNPTR_TYPE_XDP:
682 		return BPF_DYNPTR_TYPE_XDP;
683 	case DYNPTR_TYPE_SKB_META:
684 		return BPF_DYNPTR_TYPE_SKB_META;
685 	case DYNPTR_TYPE_FILE:
686 		return BPF_DYNPTR_TYPE_FILE;
687 	default:
688 		return BPF_DYNPTR_TYPE_INVALID;
689 	}
690 }
691 
692 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
693 {
694 	switch (type) {
695 	case BPF_DYNPTR_TYPE_LOCAL:
696 		return DYNPTR_TYPE_LOCAL;
697 	case BPF_DYNPTR_TYPE_RINGBUF:
698 		return DYNPTR_TYPE_RINGBUF;
699 	case BPF_DYNPTR_TYPE_SKB:
700 		return DYNPTR_TYPE_SKB;
701 	case BPF_DYNPTR_TYPE_XDP:
702 		return DYNPTR_TYPE_XDP;
703 	case BPF_DYNPTR_TYPE_SKB_META:
704 		return DYNPTR_TYPE_SKB_META;
705 	case BPF_DYNPTR_TYPE_FILE:
706 		return DYNPTR_TYPE_FILE;
707 	default:
708 		return 0;
709 	}
710 }
711 
712 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
713 {
714 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
715 }
716 
717 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
718 			      enum bpf_dynptr_type type,
719 			      bool first_slot, int id, int parent_id);
720 
721 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
722 				   struct bpf_reg_state *sreg1,
723 				   struct bpf_reg_state *sreg2,
724 				   enum bpf_dynptr_type type, int parent_id)
725 {
726 	int id = ++env->id_gen;
727 
728 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
729 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
730 }
731 
732 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
733 			       struct bpf_reg_state *reg,
734 			       enum bpf_dynptr_type type)
735 {
736 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
737 }
738 
739 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
740 				        struct bpf_func_state *state, int spi);
741 
742 static int destroy_dynptrs_in_stack_slots(struct bpf_verifier_env *env,
743 					  struct bpf_func_state *state,
744 					  int first_spi, int last_spi)
745 {
746 	int spi, err;
747 
748 	for (spi = first_spi; spi <= last_spi; spi++) {
749 		err = destroy_if_dynptr_stack_slot(env, state, spi);
750 		if (err)
751 			return err;
752 	}
753 
754 	return 0;
755 }
756 
757 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
758 				   enum bpf_arg_type arg_type, int insn_idx,
759 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
760 {
761 	struct bpf_func_state *state = bpf_func(env, reg);
762 	int spi, i, err, parent_id = 0;
763 	enum bpf_dynptr_type type;
764 
765 	spi = dynptr_get_spi(env, reg);
766 	if (spi < 0)
767 		return spi;
768 
769 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
770 	 * hence we need to destroy dynptrs in both slots,
771 	 * to ensure that for the following example:
772 	 *	[d1][d1][d2][d2]
773 	 * spi    3   2   1   0
774 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
775 	 * case they do belong to same dynptr, second call won't see slot_type
776 	 * as STACK_DYNPTR and will simply skip destruction.
777 	 */
778 	err = destroy_dynptrs_in_stack_slots(env, state, spi - 1, spi);
779 	if (err)
780 		return err;
781 
782 	for (i = 0; i < BPF_REG_SIZE; i++) {
783 		bpf_stack_slot(state, spi)->slot_type[i] = STACK_DYNPTR;
784 		bpf_stack_slot(state, spi - 1)->slot_type[i] = STACK_DYNPTR;
785 	}
786 
787 	type = arg_to_dynptr_type(arg_type);
788 	if (type == BPF_DYNPTR_TYPE_INVALID)
789 		return -EINVAL;
790 
791 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
792 		err = validate_ref_obj(env, ref_obj);
793 		if (err)
794 			return err;
795 
796 		/* Track parent's id if the parent is a referenced object */
797 		parent_id = ref_obj->id;
798 
799 		if (dynptr_type_referenced(type)) {
800 			int id;
801 
802 			/*
803 			 * Create an intermediate reference that tracks the referenced
804 			 * object for the referenced dynptr. Freeing a referenced dynptr
805 			 * through helpers/kfuncs will invalidate all clones.
806 			 */
807 			id = acquire_reference(env, insn_idx, parent_id);
808 			if (id < 0)
809 				return id;
810 
811 			parent_id = id;
812 		}
813 	} else { /* bpf_dynptr_clone() */
814 		parent_id = dynptr->parent_id;
815 	}
816 
817 	mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr,
818 			       &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id);
819 
820 	return 0;
821 }
822 
823 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
824 {
825 	int i;
826 
827 	for (i = 0; i < BPF_REG_SIZE; i++) {
828 		stack[0].slot_type[i] = STACK_INVALID;
829 		stack[1].slot_type[i] = STACK_INVALID;
830 	}
831 
832 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
833 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
834 }
835 
836 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
837 {
838 	struct bpf_func_state *state = bpf_func(env, reg);
839 	int spi;
840 
841 	spi = dynptr_get_spi(env, reg);
842 	if (spi < 0)
843 		return spi;
844 
845 	/*
846 	 * For referenced dynptr, release the parent ref which cascades to
847 	 * all clones and derived slices. For non-referenced dynptr, only
848 	 * the dynptr and slices derived from it will be invalidated.
849 	 */
850 	reg = &bpf_stack_slot(state, spi)->spilled_ptr;
851 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
852 				      ? reg->parent_id
853 				      : reg->id);
854 }
855 
856 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
857 			       struct bpf_reg_state *reg);
858 
859 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
860 {
861 	if (!env->allow_ptr_leaks)
862 		bpf_mark_reg_not_init(env, reg);
863 	else
864 		__mark_reg_unknown(env, reg);
865 }
866 
867 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
868 {
869 	struct bpf_stack_state *stack;
870 	struct bpf_func_state *state;
871 	struct bpf_reg_state *reg;
872 	int ref_cnt = 0;
873 
874 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
875 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
876 			continue;
877 		if (!stack->spilled_ptr.dynptr.first_slot)
878 			continue;
879 		if (stack->spilled_ptr.parent_id == v_parent_id)
880 			ref_cnt++;
881 	}));
882 
883 	return ref_cnt;
884 }
885 
886 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
887 				        struct bpf_func_state *state, int spi)
888 {
889 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
890 	int err = 0;
891 
892 	/* We always ensure that STACK_DYNPTR is never set partially,
893 	 * hence just checking for slot_type[0] is enough. This is
894 	 * different for STACK_SPILL, where it may be only set for
895 	 * 1 byte, so code has to use is_spilled_reg.
896 	 */
897 	if (slot->slot_type[0] != STACK_DYNPTR)
898 		return 0;
899 
900 	/* Reposition spi to first slot */
901 	if (!slot->spilled_ptr.dynptr.first_slot) {
902 		spi = spi + 1;
903 		slot = bpf_stack_slot(state, spi);
904 	}
905 
906 	/*
907 	 * A referenced dynptr can be overwritten only if there is at
908 	 * least one other dynptr sharing the same virtual ref parent,
909 	 * ensuring the reference can still be properly released.
910 	 */
911 	if (dynptr_type_referenced(slot->spilled_ptr.dynptr.type) &&
912 	    dynptr_ref_cnt(env, slot->spilled_ptr.parent_id) <= 1) {
913 		verbose(env, "cannot overwrite referenced dynptr\n");
914 		bpf_diag_res(
915 			env, env->insn_idx, "referenced dynptr overwrite",
916 			"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.",
917 			"Release or clone the dynptr so another live dynptr still tracks the referenced resource before overwriting this stack slot.");
918 		return -EINVAL;
919 	}
920 
921 	/* Invalidate the dynptr and any derived slices */
922 	err = release_reference(env, slot->spilled_ptr.id);
923 	if (!err) {
924 		mark_stack_slot_scratched(env, spi);
925 		mark_stack_slot_scratched(env, spi - 1);
926 	}
927 
928 	return err;
929 }
930 
931 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
932 {
933 	int spi;
934 
935 	if (reg->type == CONST_PTR_TO_DYNPTR)
936 		return false;
937 
938 	spi = dynptr_get_spi(env, reg);
939 
940 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
941 	 * error because this just means the stack state hasn't been updated yet.
942 	 * We will do check_mem_access to check and update stack bounds later.
943 	 */
944 	if (spi < 0 && spi != -ERANGE)
945 		return false;
946 
947 	/* We don't need to check if the stack slots are marked by previous
948 	 * dynptr initializations because we allow overwriting existing unreferenced
949 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
950 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
951 	 * touching are completely destructed before we reinitialize them for a new
952 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
953 	 * instead of delaying it until the end where the user will get "Unreleased
954 	 * reference" error.
955 	 */
956 	return true;
957 }
958 
959 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
960 {
961 	struct bpf_func_state *state = bpf_func(env, reg);
962 	struct bpf_stack_state *slot;
963 	int i, spi;
964 
965 	/* This already represents first slot of initialized bpf_dynptr.
966 	 *
967 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
968 	 * check_func_arg_reg_off's logic, so we don't need to check its
969 	 * offset and alignment.
970 	 */
971 	if (reg->type == CONST_PTR_TO_DYNPTR)
972 		return true;
973 
974 	spi = dynptr_get_spi(env, reg);
975 	if (spi < 0)
976 		return false;
977 	slot = bpf_stack_slot(state, spi);
978 	if (!slot->spilled_ptr.dynptr.first_slot)
979 		return false;
980 
981 	for (i = 0; i < BPF_REG_SIZE; i++) {
982 		if (slot->slot_type[i] != STACK_DYNPTR ||
983 		    bpf_stack_slot(state, spi - 1)->slot_type[i] != STACK_DYNPTR)
984 			return false;
985 	}
986 
987 	return true;
988 }
989 
990 static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
991 {
992 	struct bpf_func_state *state;
993 	int spi;
994 
995 	if (reg->type == CONST_PTR_TO_DYNPTR)
996 		return reg->dynptr.type;
997 
998 	spi = dynptr_get_spi(env, reg);
999 	if (spi < 0)
1000 		return BPF_DYNPTR_TYPE_INVALID;
1001 	state = bpf_func(env, reg);
1002 	return bpf_stack_slot(state, spi)->spilled_ptr.dynptr.type;
1003 }
1004 
1005 static bool dynptr_write_changes_pkt_data(enum bpf_dynptr_type type)
1006 {
1007 	return type == BPF_DYNPTR_TYPE_SKB || type == BPF_DYNPTR_TYPE_SKB_META;
1008 }
1009 
1010 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1011 				    enum bpf_arg_type arg_type)
1012 {
1013 	/*
1014 	 * ARG_PTR_TO_DYNPTR without a type flag takes any type of dynptr.
1015 	 * Test the flags rather than the whole arg_type, which may carry
1016 	 * unrelated ones such as PTR_MAYBE_NULL.
1017 	 */
1018 	if (!(arg_type & DYNPTR_TYPE_FLAG_MASK))
1019 		return true;
1020 
1021 	return dynptr_reg_type(env, reg) == arg_to_dynptr_type(arg_type);
1022 }
1023 
1024 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1025 
1026 static bool in_rcu_cs(struct bpf_verifier_env *env);
1027 
1028 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta);
1029 
1030 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1031 				 struct bpf_call_arg_meta *meta,
1032 				 struct bpf_reg_state *reg, int insn_idx,
1033 				 struct btf *btf, u32 btf_id, int nr_slots)
1034 {
1035 	struct bpf_func_state *state = bpf_func(env, reg);
1036 	int spi, i, j, id;
1037 
1038 	spi = iter_get_spi(env, reg, nr_slots);
1039 	if (spi < 0)
1040 		return spi;
1041 
1042 	id = acquire_reference(env, insn_idx, 0);
1043 	if (id < 0)
1044 		return id;
1045 
1046 	for (i = 0; i < nr_slots; i++) {
1047 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1048 		struct bpf_reg_state *st = &slot->spilled_ptr;
1049 
1050 		__mark_reg_known_zero(st);
1051 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1052 		if (is_kfunc_rcu_protected(meta)) {
1053 			if (in_rcu_cs(env))
1054 				st->type |= MEM_RCU;
1055 			else
1056 				st->type |= PTR_UNTRUSTED;
1057 		}
1058 		st->id = i == 0 ? id : 0;
1059 		st->iter.btf = btf;
1060 		st->iter.btf_id = btf_id;
1061 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1062 		st->iter.depth = 0;
1063 
1064 		for (j = 0; j < BPF_REG_SIZE; j++)
1065 			slot->slot_type[j] = STACK_ITER;
1066 
1067 		mark_stack_slot_scratched(env, spi - i);
1068 	}
1069 
1070 	return 0;
1071 }
1072 
1073 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1074 				   struct bpf_reg_state *reg, int nr_slots)
1075 {
1076 	struct bpf_func_state *state = bpf_func(env, reg);
1077 	int spi, i, j;
1078 
1079 	spi = iter_get_spi(env, reg, nr_slots);
1080 	if (spi < 0)
1081 		return spi;
1082 
1083 	for (i = 0; i < nr_slots; i++) {
1084 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1085 		struct bpf_reg_state *st = &slot->spilled_ptr;
1086 
1087 		if (i == 0)
1088 			WARN_ON_ONCE(release_reference(env, st->id));
1089 
1090 		bpf_mark_reg_not_init(env, st);
1091 
1092 		for (j = 0; j < BPF_REG_SIZE; j++)
1093 			slot->slot_type[j] = STACK_INVALID;
1094 
1095 		mark_stack_slot_scratched(env, spi - i);
1096 	}
1097 
1098 	return 0;
1099 }
1100 
1101 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1102 				     struct bpf_reg_state *reg, int nr_slots)
1103 {
1104 	struct bpf_func_state *state = bpf_func(env, reg);
1105 	int spi, i, j;
1106 
1107 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1108 	 * will do check_mem_access to check and update stack bounds later, so
1109 	 * return true for that case.
1110 	 */
1111 	spi = iter_get_spi(env, reg, nr_slots);
1112 	if (spi == -ERANGE)
1113 		return true;
1114 	if (spi < 0)
1115 		return false;
1116 
1117 	for (i = 0; i < nr_slots; i++) {
1118 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1119 
1120 		for (j = 0; j < BPF_REG_SIZE; j++)
1121 			if (slot->slot_type[j] == STACK_ITER)
1122 				return false;
1123 	}
1124 
1125 	return true;
1126 }
1127 
1128 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1129 				   struct btf *btf, u32 btf_id, int nr_slots)
1130 {
1131 	struct bpf_func_state *state = bpf_func(env, reg);
1132 	int spi, i, j;
1133 
1134 	spi = iter_get_spi(env, reg, nr_slots);
1135 	if (spi < 0)
1136 		return -EINVAL;
1137 
1138 	for (i = 0; i < nr_slots; i++) {
1139 		struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i);
1140 		struct bpf_reg_state *st = &slot->spilled_ptr;
1141 
1142 		if (st->type & PTR_UNTRUSTED)
1143 			return -EPROTO;
1144 		/* only main (first) slot has id set */
1145 		if (i == 0 && !st->id)
1146 			return -EINVAL;
1147 		if (i != 0 && st->id)
1148 			return -EINVAL;
1149 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1150 			return -EINVAL;
1151 
1152 		for (j = 0; j < BPF_REG_SIZE; j++)
1153 			if (slot->slot_type[j] != STACK_ITER)
1154 				return -EINVAL;
1155 	}
1156 
1157 	return 0;
1158 }
1159 
1160 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1161 static int release_irq_state(struct bpf_verifier_env *env, int id);
1162 
1163 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1164 				     struct bpf_call_arg_meta *meta,
1165 				     struct bpf_reg_state *reg, int insn_idx,
1166 				     int kfunc_class)
1167 {
1168 	struct bpf_func_state *state = bpf_func(env, reg);
1169 	struct bpf_stack_state *slot;
1170 	struct bpf_reg_state *st;
1171 	int spi, i, id;
1172 
1173 	spi = irq_flag_get_spi(env, reg);
1174 	if (spi < 0)
1175 		return spi;
1176 
1177 	id = acquire_irq_state(env, insn_idx);
1178 	if (id < 0)
1179 		return id;
1180 
1181 	slot = bpf_stack_slot(state, spi);
1182 	st = &slot->spilled_ptr;
1183 
1184 	__mark_reg_known_zero(st);
1185 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1186 	st->id = id;
1187 	st->irq.kfunc_class = kfunc_class;
1188 
1189 	for (i = 0; i < BPF_REG_SIZE; i++)
1190 		slot->slot_type[i] = STACK_IRQ_FLAG;
1191 
1192 	mark_stack_slot_scratched(env, spi);
1193 	return 0;
1194 }
1195 
1196 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1197 				      int kfunc_class)
1198 {
1199 	struct bpf_func_state *state = bpf_func(env, reg);
1200 	struct bpf_stack_state *slot;
1201 	struct bpf_reg_state *st;
1202 	int spi, i, err;
1203 
1204 	spi = irq_flag_get_spi(env, reg);
1205 	if (spi < 0)
1206 		return spi;
1207 
1208 	slot = bpf_stack_slot(state, spi);
1209 	st = &slot->spilled_ptr;
1210 
1211 	if (st->irq.kfunc_class != kfunc_class) {
1212 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1213 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1214 		const char *reason;
1215 
1216 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1217 			flag_kfunc, used_kfunc);
1218 		reason = bpf_diag_fmt(env,
1219 				      "This IRQ flag was saved by %s IRQ kfuncs, but the restore call "
1220 			"belongs to the %s IRQ kfunc family. Save and restore operations "
1221 			"must use the same family.",
1222 			flag_kfunc, used_kfunc);
1223 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore mismatch", reason,
1224 			     "Restore the flag with the matching IRQ restore kfunc for the save "
1225 			     "operation that created it.",
1226 			     bpf_diag_irq_depth(env->cur_state));
1227 		return -EINVAL;
1228 	}
1229 
1230 	err = release_irq_state(env, st->id);
1231 	WARN_ON_ONCE(err && err != -EACCES);
1232 	if (err) {
1233 		int insn_idx = 0;
1234 
1235 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1236 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1237 				insn_idx = env->cur_state->refs[i].insn_idx;
1238 				break;
1239 			}
1240 		}
1241 
1242 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1243 			env->cur_state->active_irq_id, insn_idx);
1244 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore out of order",
1245 			     "IRQ-disabled regions must be restored in last-in, first-out order, "
1246 			     "but this restore does not match the currently active IRQ flag.",
1247 			     "Restore nested IRQ flags in the reverse order they were saved.",
1248 			     bpf_diag_irq_depth(env->cur_state));
1249 		return err;
1250 	}
1251 
1252 	bpf_mark_reg_not_init(env, st);
1253 
1254 	for (i = 0; i < BPF_REG_SIZE; i++)
1255 		slot->slot_type[i] = STACK_INVALID;
1256 
1257 	mark_stack_slot_scratched(env, spi);
1258 	return 0;
1259 }
1260 
1261 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1262 {
1263 	struct bpf_func_state *state = bpf_func(env, reg);
1264 	struct bpf_stack_state *slot;
1265 	int spi, i;
1266 
1267 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1268 	 * will do check_mem_access to check and update stack bounds later, so
1269 	 * return true for that case.
1270 	 */
1271 	spi = irq_flag_get_spi(env, reg);
1272 	if (spi == -ERANGE)
1273 		return true;
1274 	if (spi < 0)
1275 		return false;
1276 
1277 	slot = bpf_stack_slot(state, spi);
1278 
1279 	for (i = 0; i < BPF_REG_SIZE; i++)
1280 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1281 			return false;
1282 	return true;
1283 }
1284 
1285 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1286 {
1287 	struct bpf_func_state *state = bpf_func(env, reg);
1288 	struct bpf_stack_state *slot;
1289 	struct bpf_reg_state *st;
1290 	int spi, i;
1291 
1292 	spi = irq_flag_get_spi(env, reg);
1293 	if (spi < 0)
1294 		return -EINVAL;
1295 
1296 	slot = bpf_stack_slot(state, spi);
1297 	st = &slot->spilled_ptr;
1298 
1299 	if (!st->id)
1300 		return -EINVAL;
1301 
1302 	for (i = 0; i < BPF_REG_SIZE; i++)
1303 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1304 			return -EINVAL;
1305 	return 0;
1306 }
1307 
1308 /* Check if given stack slot is "special":
1309  *   - spilled register state (STACK_SPILL);
1310  *   - dynptr state (STACK_DYNPTR);
1311  *   - iter state (STACK_ITER).
1312  *   - irq flag state (STACK_IRQ_FLAG)
1313  */
1314 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1315 {
1316 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1317 
1318 	switch (type) {
1319 	case STACK_SPILL:
1320 	case STACK_DYNPTR:
1321 	case STACK_ITER:
1322 	case STACK_IRQ_FLAG:
1323 		return true;
1324 	case STACK_INVALID:
1325 	case STACK_POISON:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 
1339 /*
1340  * Mark stack slot as STACK_MISC, unless it is already:
1341  * - STACK_INVALID, in which case they are equivalent.
1342  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1343  * - STACK_POISON, which truly forbids access to the slot.
1344  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1345  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1346  * unnecessary as both are considered equivalent when loading data and pruning,
1347  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1348  * slots.
1349  */
1350 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1351 {
1352 	if (*stype == STACK_ZERO)
1353 		return;
1354 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1355 		return;
1356 	*stype = STACK_MISC;
1357 }
1358 
1359 static void scrub_spilled_slot(u8 *stype)
1360 {
1361 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1362 		*stype = STACK_MISC;
1363 }
1364 
1365 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1366  * small to hold src. This is different from krealloc since we don't want to preserve
1367  * the contents of dst.
1368  *
1369  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1370  * not be allocated.
1371  */
1372 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1373 {
1374 	size_t alloc_bytes;
1375 	void *orig = dst;
1376 	size_t bytes;
1377 
1378 	if (ZERO_OR_NULL_PTR(src))
1379 		goto out;
1380 
1381 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1382 		return NULL;
1383 
1384 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1385 	dst = krealloc(orig, alloc_bytes, flags);
1386 	if (!dst) {
1387 		kfree(orig);
1388 		return NULL;
1389 	}
1390 
1391 	memcpy(dst, src, bytes);
1392 out:
1393 	return dst ? dst : ZERO_SIZE_PTR;
1394 }
1395 
1396 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1397  * small to hold new_n items. new items are zeroed out if the array grows.
1398  *
1399  * Contrary to krealloc_array, does not free arr if new_n is zero.
1400  */
1401 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1402 {
1403 	size_t alloc_size;
1404 	void *new_arr;
1405 
1406 	if (!new_n || old_n == new_n)
1407 		goto out;
1408 
1409 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1410 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1411 	if (!new_arr) {
1412 		kfree(arr);
1413 		return NULL;
1414 	}
1415 	arr = new_arr;
1416 
1417 	if (new_n > old_n)
1418 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1419 
1420 out:
1421 	return arr ? arr : ZERO_SIZE_PTR;
1422 }
1423 
1424 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1425 {
1426 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1427 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1428 	if (!dst->refs)
1429 		return -ENOMEM;
1430 
1431 	dst->acquired_refs = src->acquired_refs;
1432 	dst->active_locks = src->active_locks;
1433 	dst->active_preempt_locks = src->active_preempt_locks;
1434 	dst->active_rcu_locks = src->active_rcu_locks;
1435 	dst->active_irq_id = src->active_irq_id;
1436 	dst->active_lock_id = src->active_lock_id;
1437 	dst->active_lock_ptr = src->active_lock_ptr;
1438 	return 0;
1439 }
1440 
1441 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1442 {
1443 	size_t n = bpf_stack_nr_slots(src);
1444 
1445 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1446 				GFP_KERNEL_ACCOUNT);
1447 	if (!dst->stack)
1448 		return -ENOMEM;
1449 
1450 	dst->allocated_stack = src->allocated_stack;
1451 
1452 	/* copy stack args state */
1453 	n = src->out_stack_arg_cnt;
1454 	if (n) {
1455 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1456 						 sizeof(struct bpf_reg_state),
1457 						 GFP_KERNEL_ACCOUNT);
1458 		if (!dst->stack_arg_regs)
1459 			return -ENOMEM;
1460 	}
1461 
1462 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1463 	return 0;
1464 }
1465 
1466 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1467 {
1468 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1469 				    sizeof(struct bpf_reference_state));
1470 	if (!state->refs)
1471 		return -ENOMEM;
1472 
1473 	state->acquired_refs = n;
1474 	return 0;
1475 }
1476 
1477 /* Possibly update state->allocated_stack to be at least size bytes. Also
1478  * possibly update the function's high-water mark in its bpf_subprog_info.
1479  */
1480 int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1481 {
1482 	size_t old_n = bpf_stack_nr_slots(state), n;
1483 
1484 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1485 	size = round_up(size, BPF_REG_SIZE);
1486 	n = size / BPF_REG_SIZE;
1487 
1488 	if (old_n >= n)
1489 		return 0;
1490 
1491 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1492 	if (!state->stack)
1493 		return -ENOMEM;
1494 
1495 	state->allocated_stack = size;
1496 
1497 	/* update known max for given subprogram */
1498 	if (env->subprog_info[state->subprogno].stack_depth < size)
1499 		env->subprog_info[state->subprogno].stack_depth = size;
1500 
1501 	return 0;
1502 }
1503 
1504 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1505 				struct bpf_func_state *state, int cnt)
1506 {
1507 	size_t old_n = state->out_stack_arg_cnt;
1508 
1509 	if (old_n >= cnt)
1510 		return 0;
1511 
1512 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1513 					      sizeof(struct bpf_reg_state));
1514 	if (!state->stack_arg_regs)
1515 		return -ENOMEM;
1516 
1517 	state->out_stack_arg_cnt = cnt;
1518 	return 0;
1519 }
1520 
1521 /* Acquire a pointer id from the env and update the state->refs to include
1522  * this new pointer reference.
1523  * On success, returns a valid pointer id to associate with the register
1524  * On failure, returns a negative errno.
1525  */
1526 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1527 {
1528 	struct bpf_verifier_state *state = env->cur_state;
1529 	int new_ofs = state->acquired_refs;
1530 	int err;
1531 
1532 	err = resize_reference_state(state, state->acquired_refs + 1);
1533 	if (err)
1534 		return NULL;
1535 	state->refs[new_ofs].insn_idx = insn_idx;
1536 
1537 	return &state->refs[new_ofs];
1538 }
1539 
1540 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1541 {
1542 	struct bpf_reference_state *s;
1543 
1544 	s = acquire_reference_state(env, insn_idx);
1545 	if (!s)
1546 		return -ENOMEM;
1547 	s->type = REF_TYPE_PTR;
1548 	s->id = ++env->id_gen;
1549 	s->parent_id = parent_id;
1550 	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
1551 	return s->id;
1552 }
1553 
1554 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1555 			      int id, void *ptr)
1556 {
1557 	struct bpf_verifier_state *state = env->cur_state;
1558 	struct bpf_reference_state *s;
1559 
1560 	s = acquire_reference_state(env, insn_idx);
1561 	if (!s)
1562 		return -ENOMEM;
1563 	s->type = type;
1564 	s->id = id;
1565 	s->ptr = ptr;
1566 
1567 	state->active_locks++;
1568 	state->active_lock_id = id;
1569 	state->active_lock_ptr = ptr;
1570 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_LOCK, true,
1571 				state->active_locks);
1572 	return 0;
1573 }
1574 
1575 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1576 {
1577 	struct bpf_verifier_state *state = env->cur_state;
1578 	struct bpf_reference_state *s;
1579 
1580 	s = acquire_reference_state(env, insn_idx);
1581 	if (!s)
1582 		return -ENOMEM;
1583 	s->type = REF_TYPE_IRQ;
1584 	s->id = ++env->id_gen;
1585 
1586 	state->active_irq_id = s->id;
1587 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true,
1588 				bpf_diag_irq_depth(state));
1589 	return s->id;
1590 }
1591 
1592 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1593 {
1594 	int last_idx;
1595 	size_t rem;
1596 
1597 	/* IRQ state requires the relative ordering of elements remaining the
1598 	 * same, since it relies on the refs array to behave as a stack, so that
1599 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1600 	 * the array instead of swapping the final element into the deleted idx.
1601 	 */
1602 	last_idx = state->acquired_refs - 1;
1603 	rem = state->acquired_refs - idx - 1;
1604 	if (last_idx && idx != last_idx)
1605 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1606 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1607 	state->acquired_refs--;
1608 	return;
1609 }
1610 
1611 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1612 {
1613 	int i;
1614 
1615 	for (i = 0; i < state->acquired_refs; i++) {
1616 		if (state->refs[i].type != REF_TYPE_PTR)
1617 			continue;
1618 		if (state->refs[i].id == id)
1619 			return true;
1620 	}
1621 
1622 	return false;
1623 }
1624 
1625 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1626 {
1627 	return find_reference_state(env->cur_state, reg->id);
1628 }
1629 
1630 static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr)
1631 {
1632 	struct bpf_verifier_state *state = env->cur_state;
1633 	void *prev_ptr = NULL;
1634 	u32 prev_id = 0;
1635 	int i;
1636 
1637 	for (i = 0; i < state->acquired_refs; i++) {
1638 		if (state->refs[i].type == type && state->refs[i].id == id &&
1639 		    state->refs[i].ptr == ptr) {
1640 			release_reference_state(state, i);
1641 			state->active_locks--;
1642 			/* Reassign active lock (id, ptr). */
1643 			state->active_lock_id = prev_id;
1644 			state->active_lock_ptr = prev_ptr;
1645 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_LOCK,
1646 						false, state->active_locks);
1647 			return 0;
1648 		}
1649 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1650 			prev_id = state->refs[i].id;
1651 			prev_ptr = state->refs[i].ptr;
1652 		}
1653 	}
1654 	return -EINVAL;
1655 }
1656 
1657 static int release_irq_state(struct bpf_verifier_env *env, int id)
1658 {
1659 	struct bpf_verifier_state *state = env->cur_state;
1660 	u32 prev_id = 0;
1661 	int i;
1662 
1663 	if (id != state->active_irq_id)
1664 		return -EACCES;
1665 
1666 	for (i = 0; i < state->acquired_refs; i++) {
1667 		if (state->refs[i].type != REF_TYPE_IRQ)
1668 			continue;
1669 		if (state->refs[i].id == id) {
1670 			release_reference_state(state, i);
1671 			state->active_irq_id = prev_id;
1672 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ,
1673 						false, bpf_diag_irq_depth(state));
1674 			return 0;
1675 		} else {
1676 			prev_id = state->refs[i].id;
1677 		}
1678 	}
1679 	return -EINVAL;
1680 }
1681 
1682 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1683 						   int id, void *ptr)
1684 {
1685 	int i;
1686 
1687 	for (i = 0; i < state->acquired_refs; i++) {
1688 		struct bpf_reference_state *s = &state->refs[i];
1689 
1690 		if (!(s->type & type))
1691 			continue;
1692 
1693 		if (s->id == id && s->ptr == ptr)
1694 			return s;
1695 	}
1696 	return NULL;
1697 }
1698 
1699 static void free_func_state(struct bpf_func_state *state)
1700 {
1701 	if (!state)
1702 		return;
1703 	kfree(state->loop_stack);
1704 	kfree(state->stack_arg_regs);
1705 	kfree(state->stack);
1706 	kfree(state);
1707 }
1708 
1709 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1710 {
1711 	kfree(state->jmp_history);
1712 	state->jmp_history = NULL;
1713 	state->jmp_history_cnt = 0;
1714 }
1715 
1716 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1717 			    bool free_self)
1718 {
1719 	int i;
1720 
1721 	for (i = 0; i <= state->curframe; i++) {
1722 		free_func_state(state->frame[i]);
1723 		state->frame[i] = NULL;
1724 	}
1725 	kfree(state->refs);
1726 	bpf_clear_jmp_history(state);
1727 	if (free_self)
1728 		kfree(state);
1729 }
1730 
1731 /* copy verifier state from src to dst growing dst stack space
1732  * when necessary to accommodate larger src stack
1733  */
1734 static int copy_func_state(struct bpf_func_state *dst,
1735 			   const struct bpf_func_state *src)
1736 {
1737 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1738 	/* Instruction accounting is path-local, not part of verifier state. */
1739 	dst->insns_subtotal = 0;
1740 	dst->loop_stack = copy_array(dst->loop_stack, src->loop_stack, src->loop_stack_cnt,
1741 				     sizeof(*src->loop_stack), GFP_KERNEL_ACCOUNT);
1742 	if (!dst->loop_stack)
1743 		return -ENOMEM;
1744 	return copy_stack_state(dst, src);
1745 }
1746 
1747 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1748 			   const struct bpf_verifier_state *src)
1749 {
1750 	struct bpf_func_state *dst;
1751 	int i, err;
1752 
1753 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1754 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1755 					  GFP_KERNEL_ACCOUNT);
1756 	if (!dst_state->jmp_history)
1757 		return -ENOMEM;
1758 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1759 
1760 	/* if dst has more stack frames then src frame, free them, this is also
1761 	 * necessary in case of exceptional exits using bpf_throw.
1762 	 */
1763 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1764 		free_func_state(dst_state->frame[i]);
1765 		dst_state->frame[i] = NULL;
1766 	}
1767 	err = copy_reference_state(dst_state, src);
1768 	if (err)
1769 		return err;
1770 	dst_state->speculative = src->speculative;
1771 	dst_state->in_sleepable = src->in_sleepable;
1772 	dst_state->unwound = src->unwound;
1773 	dst_state->curframe = src->curframe;
1774 	dst_state->branches = src->branches;
1775 	dst_state->parent = src->parent;
1776 	dst_state->first_insn_idx = src->first_insn_idx;
1777 	dst_state->last_insn_idx = src->last_insn_idx;
1778 	dst_state->dfs_depth = src->dfs_depth;
1779 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1780 	dst_state->may_goto_depth = src->may_goto_depth;
1781 	dst_state->equal_state = src->equal_state;
1782 	for (i = 0; i <= src->curframe; i++) {
1783 		dst = dst_state->frame[i];
1784 		if (!dst) {
1785 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1786 			if (!dst)
1787 				return -ENOMEM;
1788 			dst_state->frame[i] = dst;
1789 		}
1790 		err = copy_func_state(dst, src->frame[i]);
1791 		if (err)
1792 			return err;
1793 	}
1794 	return 0;
1795 }
1796 
1797 static u32 state_htab_size(struct bpf_verifier_env *env)
1798 {
1799 	return env->prog->len;
1800 }
1801 
1802 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1803 {
1804 	struct bpf_verifier_state *cur = env->cur_state;
1805 	struct bpf_func_state *state = cur->frame[cur->curframe];
1806 
1807 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1808 }
1809 
1810 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1811 {
1812 	int fr;
1813 
1814 	if (a->curframe != b->curframe)
1815 		return false;
1816 
1817 	for (fr = a->curframe; fr >= 0; fr--)
1818 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1819 			return false;
1820 
1821 	return true;
1822 }
1823 
1824 void bpf_free_backedges(struct bpf_scc_visit *visit)
1825 {
1826 	struct bpf_scc_backedge *backedge, *next;
1827 
1828 	for (backedge = visit->backedges; backedge; backedge = next) {
1829 		bpf_free_verifier_state(&backedge->state, false);
1830 		next = backedge->next;
1831 		kfree(backedge);
1832 	}
1833 	visit->backedges = NULL;
1834 }
1835 
1836 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1837 		     int *insn_idx, bool pop_log)
1838 {
1839 	struct bpf_verifier_state *cur = env->cur_state;
1840 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1841 	int err;
1842 
1843 	if (env->head == NULL)
1844 		return -ENOENT;
1845 
1846 	if (cur) {
1847 		err = bpf_copy_verifier_state(cur, &head->st);
1848 		if (err)
1849 			return err;
1850 		bpf_diag_event_log_restore(env, head->diag_log_pos);
1851 	}
1852 	if (pop_log)
1853 		bpf_vlog_reset(&env->log, head->log_pos);
1854 	if (insn_idx)
1855 		*insn_idx = head->insn_idx;
1856 	if (prev_insn_idx)
1857 		*prev_insn_idx = head->prev_insn_idx;
1858 	elem = head->next;
1859 	bpf_free_verifier_state(&head->st, false);
1860 	kfree(head);
1861 	env->head = elem;
1862 	env->stack_size--;
1863 	return 0;
1864 }
1865 
1866 static bool error_recoverable_with_nospec(int err)
1867 {
1868 	/* Should only return true for non-fatal errors that are allowed to
1869 	 * occur during speculative verification. For these we can insert a
1870 	 * nospec and the program might still be accepted. Do not include
1871 	 * something like ENOMEM because it is likely to re-occur for the next
1872 	 * architectural path once it has been recovered-from in all speculative
1873 	 * paths.
1874 	 */
1875 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1876 }
1877 
1878 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1879 					     int insn_idx, int prev_insn_idx,
1880 					     bool speculative)
1881 {
1882 	struct bpf_verifier_state *cur = env->cur_state;
1883 	struct bpf_verifier_stack_elem *elem;
1884 	int err;
1885 
1886 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1887 	if (!elem)
1888 		return ERR_PTR(-ENOMEM);
1889 
1890 	elem->insn_idx = insn_idx;
1891 	elem->prev_insn_idx = prev_insn_idx;
1892 	elem->next = env->head;
1893 	elem->log_pos = env->log.end_pos;
1894 	elem->diag_log_pos = bpf_diag_event_log_save(env);
1895 	env->head = elem;
1896 	env->stack_size++;
1897 	err = bpf_copy_verifier_state(&elem->st, cur);
1898 	if (err)
1899 		return ERR_PTR(-ENOMEM);
1900 	elem->st.speculative |= speculative;
1901 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1902 		verbose(env, "The sequence of %d jumps is too complex.\n",
1903 			env->stack_size);
1904 		return ERR_PTR(-E2BIG);
1905 	}
1906 	if (elem->st.parent) {
1907 		++elem->st.parent->branches;
1908 		/* WARN_ON(branches > 2) technically makes sense here,
1909 		 * but
1910 		 * 1. speculative states will bump 'branches' for non-branch
1911 		 * instructions
1912 		 * 2. is_state_visited() heuristics may decide not to create
1913 		 * a new state for a sequence of branches and all such current
1914 		 * and cloned states will be pointing to a single parent state
1915 		 * which might have large 'branches' count.
1916 		 */
1917 	}
1918 	return &elem->st;
1919 }
1920 
1921 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1922 {
1923 	char *buf = env->tmp_arg_name;
1924 	int len = sizeof(env->tmp_arg_name);
1925 	int arg, regno = reg_from_argno(argno);
1926 
1927 	if (regno >= 0) {
1928 		snprintf(buf, len, "R%d", regno);
1929 	} else {
1930 		arg = arg_from_argno(argno);
1931 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1932 	}
1933 
1934 	return buf;
1935 }
1936 
1937 static const int caller_saved[CALLER_SAVED_REGS] = {
1938 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1939 };
1940 
1941 static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
1942 					 struct bpf_reg_state *regs)
1943 {
1944 	int i;
1945 
1946 	for (i = 1; i < CALLER_SAVED_REGS; i++) {
1947 		bpf_diag_record_scrub(env, &regs[caller_saved[i]],
1948 				      BPF_DIAG_MOD_CALLER_SAVED);
1949 	}
1950 }
1951 
1952 static void reg_step_reset(struct bpf_reg_state *reg)
1953 {
1954 	reg->base = 0;
1955 	reg->step = 1;
1956 }
1957 
1958 static void scalar_step_add(struct bpf_reg_state *dst_reg,
1959 			    const struct bpf_reg_state *a,
1960 			    const struct bpf_reg_state *b)
1961 {
1962 	const struct bpf_reg_state *reg;
1963 	s64 amount, tmp;
1964 
1965 	if (tnum_is_const(b->var_off)) {
1966 		reg = a;
1967 		amount = (s64)b->var_off.value;
1968 	} else if (tnum_is_const(a->var_off)) {
1969 		reg = b;
1970 		amount = (s64)a->var_off.value;
1971 	} else {
1972 		reg_step_reset(dst_reg);
1973 		return;
1974 	}
1975 
1976 	/*
1977 	 * Let x be a possible signed value of the register,
1978 	 * d = amount, s = reg->step, and b = reg->base.
1979 	 * Then x mod s = b, with s > 0 and 0 <= b < s.
1980 	 * If the addition causes signed underflow, the resulting value
1981 	 * is x + d + 2**64.
1982 	 *
1983 	 * Taking the result modulo s and substituting x mod s = b gives:
1984 	 *   (x + d + 2**64) mod s = (b + d + (2**64 mod s)) mod s      (1)
1985 	 * Keeping reg->step = s and updating reg->base to (b + d) mod s
1986 	 * requires (1) to equal (b + d) mod s, which holds if and only
1987 	 * if 2**64 mod s = 0.
1988 	 * Signed overflow subtracts 2**64 and has the same requirement.
1989 	 *
1990 	 * Conservatively reset the stride if either wrap is possible.
1991 	 */
1992 	if (check_add_overflow(reg_smin(reg), amount, &tmp) ||
1993 	    check_add_overflow(reg_smax(reg), amount, &tmp)) {
1994 		reg_step_reset(dst_reg);
1995 		return;
1996 	}
1997 
1998 	dst_reg->base = (reg->base + imod(amount, reg->step)) % reg->step;
1999 	dst_reg->step = reg->step;
2000 }
2001 
2002 static void scalar_step_scale(struct bpf_reg_state *dst_reg, u64 amount)
2003 {
2004 	u16 step;
2005 	s64 tmp;
2006 
2007 	/*
2008 	 * Using the same notation as scalar_step_add(), with d > 0,
2009 	 * the scaled value satisfies (x * d) mod (s * d) = b * d.
2010 	 * If the multiplication wraps, its signed result can be represented
2011 	 * as x * d - n * 2**64 for some nonzero integer n.
2012 	 *
2013 	 * Taking the result modulo s * d gives:
2014 	 *   (x * d - n * 2**64) mod (s * d) =
2015 	 *   (b * d - (n * 2**64 mod (s * d))) mod (s * d)              (1)
2016 	 * Updating dst_reg->base to b * d and dst_reg->step to s * d
2017 	 * requires (1) to equal b * d, which holds if and only if
2018 	 * n * 2**64 mod (s * d) = 0.
2019 	 *
2020 	 * Conservatively reset the stride if a wrap is possible.
2021 	 */
2022 	if (amount == 0 || check_mul_overflow(dst_reg->step, amount, &step) ||
2023 	    check_mul_overflow(reg_smin(dst_reg), (s64)amount, &tmp) ||
2024 	    check_mul_overflow(reg_smax(dst_reg), (s64)amount, &tmp)) {
2025 		reg_step_reset(dst_reg);
2026 		return;
2027 	}
2028 	/*
2029 	 * The above established that `step = dst_reg->step * amount`
2030 	 * does not overflow, therefore the base < step invariant holds
2031 	 * after assignments below.
2032 	 */
2033 	dst_reg->base = dst_reg->base * amount;
2034 	dst_reg->step = step;
2035 }
2036 
2037 /*
2038  * Let x be a possible signed value of the register,
2039  * s = reg->step, and b = reg->base.
2040  * Then x mod s = b, with s > 0 and 0 <= b < s.
2041  * Truncating to N bits and then zero- or sign-extending x
2042  * is equivalent to computing x + k * 2**N for some integer k.
2043  * For example, sign-extending the low 8 bits of x = 255 can
2044  * be expressed as 255 - 2**8 = -1.
2045  *
2046  * Taking the result modulo s and substituting x mod s = b gives:
2047  *   (x + k * 2**N) mod s = (b + (k * 2**N mod s)) mod s
2048  * Keeping reg->base = b and reg->step = s requires this to equal b,
2049  * which holds if and only if k * 2**N mod s = 0.
2050  * Continuing the example with s = 3 and b = 0, we have 255 mod 3 = 0,
2051  * but (-1) mod 3 = 2, so the original base and step no longer hold.
2052  *
2053  * Conservatively reset the stride unless all possible values fit in
2054  * the range where the conversion leaves them unchanged.
2055  * Call before updating the register's bounds. Requires 0 < bits < 64.
2056  */
2057 static void reg_step_check_unsigned(struct bpf_reg_state *reg, u32 bits)
2058 {
2059 	if (reg_umax(reg) >= (1ULL << bits))
2060 		reg_step_reset(reg);
2061 }
2062 
2063 /* This helper doesn't clear reg->id */
2064 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2065 {
2066 	reg->var_off = tnum_const(imm);
2067 	reg->r64 = cnum64_from_urange(imm, imm);
2068 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2069 	reg_step_reset(reg);
2070 }
2071 
2072 /* Mark the unknown part of a register (variable offset or scalar value) as
2073  * known to have the value @imm.
2074  */
2075 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2076 {
2077 	/* Clear off and union(map_ptr, range) */
2078 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2079 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2080 	reg->id = 0;
2081 	reg->parent_id = 0;
2082 	reg->map_uid = 0;
2083 	___mark_reg_known(reg, imm);
2084 }
2085 
2086 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
2087 {
2088 	__mark_reg_known(reg, imm);
2089 	reg->type = SCALAR_VALUE;
2090 }
2091 
2092 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2093 {
2094 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2095 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
2096 }
2097 
2098 /* Mark the 'variable offset' part of a register as zero.  This should be
2099  * used only on registers holding a pointer type.
2100  */
2101 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2102 {
2103 	__mark_reg_known(reg, 0);
2104 }
2105 
2106 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2107 {
2108 	__mark_reg_known(reg, 0);
2109 	reg->type = SCALAR_VALUE;
2110 	/* all scalars are assumed imprecise initially (unless unprivileged,
2111 	 * in which case everything is forced to be precise)
2112 	 */
2113 	reg->precise = !env->bpf_capable;
2114 }
2115 
2116 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2117 				struct bpf_reg_state *regs, u32 regno)
2118 {
2119 	__mark_reg_known_zero(regs + regno);
2120 }
2121 
2122 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2123 			      bool first_slot, int id, int parent_id)
2124 {
2125 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2126 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2127 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2128 	 */
2129 	__mark_reg_known_zero(reg);
2130 	reg->type = CONST_PTR_TO_DYNPTR;
2131 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2132 	reg->id = id;
2133 	reg->parent_id = parent_id;
2134 	reg->dynptr.type = type;
2135 	reg->dynptr.first_slot = first_slot;
2136 }
2137 
2138 /*
2139  * Refine the return type of the bpf_map_lookup_elem() for special map types:
2140  * map-in-map, xskmap, sockmap and sockhash.
2141  */
2142 static void refine_map_lookup_value(struct bpf_reg_state *reg)
2143 {
2144 	enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL;
2145 	const struct bpf_map *map = reg->map_ptr;
2146 
2147 	if (map->inner_map_meta) {
2148 		reg->type = CONST_PTR_TO_MAP | maybe_null;
2149 		reg->map_ptr = map->inner_map_meta;
2150 		/*
2151 		 * transfer reg's id which is unique for every map_lookup_elem
2152 		 * as UID of the inner map.
2153 		 */
2154 		reg->map_uid = reg->id;
2155 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2156 		reg->type = PTR_TO_XDP_SOCK | maybe_null;
2157 		reg->map_uid = 0;
2158 	} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2159 		   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2160 		reg->type = PTR_TO_SOCKET | maybe_null;
2161 		reg->map_uid = 0;
2162 	}
2163 }
2164 
2165 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2166 {
2167 	reg->type &= ~PTR_MAYBE_NULL;
2168 }
2169 
2170 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2171 				struct btf_field_graph_root *ds_head)
2172 {
2173 	__mark_reg_known(&regs[regno], ds_head->node_offset);
2174 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2175 	regs[regno].btf = ds_head->btf;
2176 	regs[regno].btf_id = ds_head->value_btf_id;
2177 }
2178 
2179 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2180 {
2181 	return type_is_pkt_pointer(reg->type);
2182 }
2183 
2184 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2185 {
2186 	return reg_is_pkt_pointer(reg) ||
2187 	       reg->type == PTR_TO_PACKET_END;
2188 }
2189 
2190 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2191 {
2192 	return base_type(reg->type) == PTR_TO_MEM &&
2193 	       (reg->type &
2194 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2195 }
2196 
2197 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2198 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2199 				    enum bpf_reg_type which)
2200 {
2201 	/* The register can already have a range from prior markings.
2202 	 * This is fine as long as it hasn't been advanced from its
2203 	 * origin.
2204 	 */
2205 	return reg->type == which &&
2206 	       reg->id == 0 &&
2207 	       tnum_equals_const(reg->var_off, 0);
2208 }
2209 
2210 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2211 {
2212 	reg->r32 = CNUM32_UNBOUNDED;
2213 }
2214 
2215 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2216 {
2217 	reg->r64 = CNUM64_UNBOUNDED;
2218 }
2219 
2220 /* Reset the min/max bounds of a register */
2221 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2222 {
2223 	__mark_reg64_unbounded(reg);
2224 	__mark_reg32_unbounded(reg);
2225 }
2226 
2227 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
2228 {
2229 	__mark_reg64_unbounded(reg);
2230 	reg->var_off = tnum_unknown;
2231 }
2232 
2233 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
2234 {
2235 	__mark_reg32_unbounded(reg);
2236 	reg->var_off = tnum_unknown;
2237 }
2238 
2239 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
2240 {
2241 	tnum = tnum_subreg(tnum);
2242 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
2243 		/* min signed is max(sign bit) | min(other bits) */
2244 		/* max signed is min(sign bit) | max(other bits) */
2245 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
2246 					  tnum.value | (tnum.mask & S32_MAX));
2247 	else
2248 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
2249 }
2250 
2251 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
2252 {
2253 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
2254 		/* min signed is max(sign bit) | min(other bits) */
2255 		/* max signed is min(sign bit) | max(other bits) */
2256 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
2257 					  tnum.value | (tnum.mask & S64_MAX));
2258 	else
2259 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
2260 }
2261 
2262 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2263 {
2264 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
2265 }
2266 
2267 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2268 {
2269 	u64 tnum_next, tmax;
2270 	bool umin_in_tnum;
2271 
2272 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2273 
2274 	/* Check if u64 and tnum overlap in a single value */
2275 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2276 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2277 	tmax = reg->var_off.value | reg->var_off.mask;
2278 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2279 		/* The u64 range and the tnum only overlap in umin.
2280 		 * u64:  ---[xxxxxx]-----
2281 		 * tnum: --xx----------x-
2282 		 */
2283 		___mark_reg_known(reg, reg_umin(reg));
2284 	} else if (!umin_in_tnum && tnum_next == tmax) {
2285 		/* The u64 range and the tnum only overlap in the maximum value
2286 		 * represented by the tnum, called tmax.
2287 		 * u64:  ---[xxxxxx]-----
2288 		 * tnum: xx-----x--------
2289 		 */
2290 		___mark_reg_known(reg, tmax);
2291 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2292 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2293 		/* The u64 range and the tnum only overlap in between umin
2294 		 * (excluded) and umax.
2295 		 * u64:  ---[xxxxxx]-----
2296 		 * tnum: xx----x-------x-
2297 		 */
2298 		___mark_reg_known(reg, tnum_next);
2299 	}
2300 }
2301 
2302 static void __update_reg_bounds(struct bpf_reg_state *reg)
2303 {
2304 	__update_reg32_bounds(reg);
2305 	__update_reg64_bounds(reg);
2306 }
2307 
2308 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2309 {
2310 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2311 }
2312 
2313 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2314 {
2315 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2316 }
2317 
2318 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2319 {
2320 	deduce_bounds_32_from_64(reg);
2321 	deduce_bounds_64_from_32(reg);
2322 }
2323 
2324 /* Attempts to improve var_off based on unsigned min/max information */
2325 static void __reg_bound_offset(struct bpf_reg_state *reg)
2326 {
2327 	struct tnum var64_off = tnum_intersect(reg->var_off,
2328 					       tnum_range(reg_umin(reg),
2329 							  reg_umax(reg)));
2330 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2331 					       tnum_range(reg_u32_min(reg),
2332 							  reg_u32_max(reg)));
2333 	u32 trailing_zero_bits;
2334 	u16 base = reg->base;
2335 	u16 step = reg->step;
2336 
2337 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2338 
2339 	if (base == 0)
2340 		trailing_zero_bits = count_trailing_zeros(step);
2341 	else
2342 		trailing_zero_bits = min(count_trailing_zeros(base),
2343 					 count_trailing_zeros(step));
2344 	reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
2345 }
2346 
2347 static void __update_bounds_from_step(struct bpf_reg_state *reg)
2348 {
2349 	reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
2350 	deduce_bounds_32_from_64(reg);
2351 }
2352 
2353 static bool range_bounds_violation(struct bpf_reg_state *reg);
2354 
2355 static void reg_bounds_sync(struct bpf_reg_state *reg)
2356 {
2357 	/* If the input reg_state is invalid, we can exit early */
2358 	if (range_bounds_violation(reg))
2359 		return;
2360 	/* We might have learned new bounds from the var_off. */
2361 	__update_reg_bounds(reg);
2362 	/* We might have learned something about the sign bit. */
2363 	__reg_deduce_bounds(reg);
2364 	__reg_deduce_bounds(reg);
2365 	/* We might have learned some bits from the bounds. */
2366 	__reg_bound_offset(reg);
2367 	/* Intersecting with the old var_off might have improved our bounds
2368 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2369 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2370 	 */
2371 	__update_reg_bounds(reg);
2372 	/*
2373 	 * Both tnum and base+step define a sequence of points,
2374 	 * potentially w/o intersection, or intersecting after N
2375 	 * tnum_step()'s, where N can be large. On the other hand,
2376 	 * step+base *must* be in sync with r64 in order for
2377 	 * array traversal logic starting at reg_smin() to be sound.
2378 	 * Hence, place this as a final step in the reg_bounds_sync().
2379 	 */
2380 	__update_bounds_from_step(reg);
2381 }
2382 
2383 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2384 {
2385 	if (!tnum_is_const(reg->var_off))
2386 		return false;
2387 
2388 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2389 }
2390 
2391 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2392 {
2393 	if (!tnum_subreg_is_const(reg->var_off))
2394 		return false;
2395 
2396 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2397 }
2398 
2399 static bool range_bounds_violation(struct bpf_reg_state *reg)
2400 {
2401 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2402 }
2403 
2404 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2405 				   struct bpf_reg_state *reg, const char *ctx)
2406 {
2407 	const char *msg;
2408 
2409 	if (range_bounds_violation(reg)) {
2410 		msg = "range bounds violation";
2411 		goto out;
2412 	}
2413 
2414 	if (const_tnum_range_mismatch(reg)) {
2415 		msg = "const tnum out of sync with range bounds";
2416 		goto out;
2417 	}
2418 
2419 	if (const_tnum_range_mismatch_32(reg)) {
2420 		msg = "const subreg tnum out of sync with range bounds";
2421 		goto out;
2422 	}
2423 
2424 	if (reg->step == 0 || reg->base >= reg->step) {
2425 		msg = "invalid base/step";
2426 		goto out;
2427 	}
2428 
2429 	return 0;
2430 out:
2431 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2432 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u",
2433 		     ctx, msg,
2434 		     reg->r64.base, reg->r64.size,
2435 		     reg->r32.base, reg->r32.size,
2436 		     reg->var_off.value, reg->var_off.mask,
2437 		     reg->base, reg->step);
2438 	if (env->test_reg_invariants)
2439 		return -EFAULT;
2440 	__mark_reg_unbounded(reg);
2441 	reg_step_reset(reg);
2442 	return 0;
2443 }
2444 
2445 /* Mark a register as having a completely unknown (scalar) value. */
2446 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2447 {
2448 	memset(reg, 0, sizeof(*reg));
2449 	reg->type = SCALAR_VALUE;
2450 	reg->var_off = tnum_unknown;
2451 	__mark_reg_unbounded(reg);
2452 	reg_step_reset(reg);
2453 }
2454 
2455 /* Mark a register as having a completely unknown (scalar) value,
2456  * initialize .precise as true when not bpf capable.
2457  */
2458 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2459 			       struct bpf_reg_state *reg)
2460 {
2461 	bpf_mark_reg_unknown_imprecise(reg);
2462 	reg->precise = !env->bpf_capable;
2463 }
2464 
2465 static void mark_reg_unknown(struct bpf_verifier_env *env,
2466 			     struct bpf_reg_state *regs, u32 regno)
2467 {
2468 	__mark_reg_unknown(env, regs + regno);
2469 }
2470 
2471 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2472 				struct bpf_reg_state *regs,
2473 				u32 regno,
2474 				s32 s32_min,
2475 				s32 s32_max)
2476 {
2477 	struct bpf_reg_state *reg = regs + regno;
2478 
2479 	reg_set_srange32(reg,
2480 			 max_t(s32, reg_s32_min(reg), s32_min),
2481 			 min_t(s32, reg_s32_max(reg), s32_max));
2482 	reg_set_srange64(reg,
2483 			 max_t(s64, reg_smin(reg), s32_min),
2484 			 min_t(s64, reg_smax(reg), s32_max));
2485 
2486 	reg_bounds_sync(reg);
2487 
2488 	return reg_bounds_sanity_check(env, reg, "s32_range");
2489 }
2490 
2491 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2492 			   struct bpf_reg_state *reg)
2493 {
2494 	__mark_reg_unknown(env, reg);
2495 	reg->type = NOT_INIT;
2496 }
2497 
2498 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2499 			   struct bpf_reg_state *regs, u32 regno,
2500 			   enum bpf_reg_type reg_type,
2501 			   struct btf *btf, u32 btf_id,
2502 			   enum bpf_type_flag flag)
2503 {
2504 	switch (reg_type) {
2505 	case SCALAR_VALUE:
2506 		mark_reg_unknown(env, regs, regno);
2507 		return 0;
2508 	case PTR_TO_BTF_ID:
2509 		mark_reg_known_zero(env, regs, regno);
2510 		regs[regno].type = PTR_TO_BTF_ID | flag;
2511 		regs[regno].btf = btf;
2512 		regs[regno].btf_id = btf_id;
2513 		if (type_may_be_null(flag))
2514 			regs[regno].id = ++env->id_gen;
2515 		return 0;
2516 	case PTR_TO_MEM:
2517 		mark_reg_known_zero(env, regs, regno);
2518 		regs[regno].type = PTR_TO_MEM | flag;
2519 		regs[regno].mem_size = 0;
2520 		return 0;
2521 	default:
2522 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2523 		return -EFAULT;
2524 	}
2525 }
2526 
2527 static void init_reg_state(struct bpf_verifier_env *env,
2528 			   struct bpf_func_state *state)
2529 {
2530 	struct bpf_reg_state *regs = state->regs;
2531 	int i;
2532 
2533 	for (i = 0; i < MAX_BPF_REG; i++) {
2534 		bpf_mark_reg_not_init(env, &regs[i]);
2535 	}
2536 
2537 	/* frame pointer */
2538 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2539 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2540 	regs[BPF_REG_FP].frameno = state->frameno;
2541 }
2542 
2543 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2544 {
2545 	/*
2546 	 * return_32bit is set to false by default and set explicitly
2547 	 * by the caller when necessary.
2548 	 */
2549 	return (struct bpf_retval_range){ minval, maxval, false };
2550 }
2551 
2552 static void init_func_state(struct bpf_verifier_env *env,
2553 			    struct bpf_func_state *state,
2554 			    int callsite, int frameno, int subprogno)
2555 {
2556 	state->callsite = callsite;
2557 	state->frameno = frameno;
2558 	bpf_diag_init_frame(env, state);
2559 	state->subprogno = subprogno;
2560 	state->callback_ret_range = retval_range(0, 0);
2561 	init_reg_state(env, state);
2562 	mark_verifier_state_scratched(env);
2563 }
2564 
2565 /* Similar to push_stack(), but for async callbacks */
2566 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2567 						int insn_idx, int prev_insn_idx,
2568 						int subprog, bool is_sleepable)
2569 {
2570 	struct bpf_verifier_stack_elem *elem;
2571 	struct bpf_func_state *frame;
2572 
2573 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2574 	if (!elem)
2575 		return ERR_PTR(-ENOMEM);
2576 
2577 	elem->insn_idx = insn_idx;
2578 	elem->prev_insn_idx = prev_insn_idx;
2579 	elem->next = env->head;
2580 	elem->log_pos = env->log.end_pos;
2581 	elem->diag_log_pos = bpf_diag_event_log_save(env);
2582 	env->head = elem;
2583 	env->stack_size++;
2584 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2585 		verbose(env,
2586 			"The sequence of %d jumps is too complex for async cb.\n",
2587 			env->stack_size);
2588 		return ERR_PTR(-E2BIG);
2589 	}
2590 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2591 	 * The caller state doesn't matter.
2592 	 * This is async callback. It starts in a fresh stack.
2593 	 * Initialize it similar to do_check_common().
2594 	 */
2595 	elem->st.branches = 1;
2596 	elem->st.in_sleepable = is_sleepable;
2597 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2598 	if (!frame)
2599 		return ERR_PTR(-ENOMEM);
2600 	init_func_state(env, frame,
2601 			BPF_MAIN_FUNC /* callsite */,
2602 			0 /* frameno within this callchain */,
2603 			subprog /* subprog number within this prog */);
2604 	elem->st.frame[0] = frame;
2605 	return &elem->st;
2606 }
2607 
2608 static int cmp_subprogs(const void *a, const void *b)
2609 {
2610 	return ((struct bpf_subprog_info *)a)->start -
2611 	       ((struct bpf_subprog_info *)b)->start;
2612 }
2613 
2614 /* Find subprogram that contains instruction at 'off' */
2615 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2616 {
2617 	struct bpf_subprog_info *vals = env->subprog_info;
2618 	int l, r, m;
2619 
2620 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2621 		return NULL;
2622 
2623 	l = 0;
2624 	r = env->subprog_cnt - 1;
2625 	while (l < r) {
2626 		m = l + (r - l + 1) / 2;
2627 		if (vals[m].start <= off)
2628 			l = m;
2629 		else
2630 			r = m - 1;
2631 	}
2632 	return &vals[l];
2633 }
2634 
2635 /* Find subprogram that starts exactly at 'off' */
2636 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2637 {
2638 	struct bpf_subprog_info *p;
2639 
2640 	p = bpf_find_containing_subprog(env, off);
2641 	if (!p || p->start != off)
2642 		return -ENOENT;
2643 	return p - env->subprog_info;
2644 }
2645 
2646 static int add_subprog(struct bpf_verifier_env *env, int off)
2647 {
2648 	int insn_cnt = env->prog->len;
2649 	int ret;
2650 
2651 	if (off >= insn_cnt || off < 0) {
2652 		verbose(env, "call to invalid destination\n");
2653 		return -EINVAL;
2654 	}
2655 	ret = bpf_find_subprog(env, off);
2656 	if (ret >= 0)
2657 		return ret;
2658 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2659 		verbose(env, "too many subprograms\n");
2660 		return -E2BIG;
2661 	}
2662 	/* determine subprog starts. The end is one before the next starts */
2663 	env->subprog_info[env->subprog_cnt].exit_idx = U32_MAX;
2664 	env->subprog_info[env->subprog_cnt++].start = off;
2665 	sort(env->subprog_info, env->subprog_cnt,
2666 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2667 	return env->subprog_cnt - 1;
2668 }
2669 
2670 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2671 {
2672 	struct bpf_prog_aux *aux = env->prog->aux;
2673 	struct btf *btf = aux->btf;
2674 	const struct btf_type *t;
2675 	u32 main_btf_id, id;
2676 	const char *name;
2677 	int ret, i;
2678 
2679 	/* Non-zero func_info_cnt implies valid btf */
2680 	if (!aux->func_info_cnt)
2681 		return 0;
2682 	main_btf_id = aux->func_info[0].type_id;
2683 
2684 	t = btf_type_by_id(btf, main_btf_id);
2685 	if (!t) {
2686 		verbose(env, "invalid btf id for main subprog in func_info\n");
2687 		return -EINVAL;
2688 	}
2689 
2690 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2691 	if (IS_ERR(name)) {
2692 		ret = PTR_ERR(name);
2693 		/* If there is no tag present, there is no exception callback */
2694 		if (ret == -ENOENT)
2695 			ret = 0;
2696 		else if (ret == -EEXIST)
2697 			verbose(env, "multiple exception callback tags for main subprog\n");
2698 		return ret;
2699 	}
2700 
2701 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2702 	if (ret < 0) {
2703 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2704 		return ret;
2705 	}
2706 	id = ret;
2707 	t = btf_type_by_id(btf, id);
2708 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2709 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2710 		return -EINVAL;
2711 	}
2712 	ret = 0;
2713 	for (i = 0; i < aux->func_info_cnt; i++) {
2714 		if (aux->func_info[i].type_id != id)
2715 			continue;
2716 		ret = aux->func_info[i].insn_off;
2717 		/* Further func_info and subprog checks will also happen
2718 		 * later, so assume this is the right insn_off for now.
2719 		 */
2720 		if (!ret) {
2721 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2722 			ret = -EINVAL;
2723 		}
2724 	}
2725 	if (!ret) {
2726 		verbose(env, "exception callback type id not found in func_info\n");
2727 		ret = -EINVAL;
2728 	}
2729 	return ret;
2730 }
2731 
2732 #define MAX_KFUNC_BTFS	256
2733 
2734 struct bpf_kfunc_btf {
2735 	struct btf *btf;
2736 	struct module *module;
2737 	u16 offset;
2738 };
2739 
2740 struct bpf_kfunc_btf_tab {
2741 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2742 	u32 nr_descs;
2743 };
2744 
2745 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2746 {
2747 	const struct bpf_kfunc_desc *d0 = a;
2748 	const struct bpf_kfunc_desc *d1 = b;
2749 
2750 	/* func_id is not greater than BTF_MAX_TYPE */
2751 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2752 }
2753 
2754 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2755 {
2756 	const struct bpf_kfunc_btf *d0 = a;
2757 	const struct bpf_kfunc_btf *d1 = b;
2758 
2759 	return d0->offset - d1->offset;
2760 }
2761 
2762 static struct bpf_kfunc_desc *
2763 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2764 {
2765 	struct bpf_kfunc_desc desc = {
2766 		.func_id = func_id,
2767 		.offset = offset,
2768 	};
2769 	struct bpf_kfunc_desc_tab *tab;
2770 
2771 	tab = prog->aux->kfunc_tab;
2772 	return bsearch(&desc, tab->descs, tab->nr_base_descs,
2773 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2774 }
2775 
2776 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2777 		       u16 desc_idx, u8 **func_addr)
2778 {
2779 	struct bpf_kfunc_desc_tab *tab;
2780 	const struct bpf_kfunc_desc *desc;
2781 
2782 	tab = prog->aux->kfunc_tab;
2783 	if (desc_idx >= tab->nr_descs)
2784 		return -EFAULT;
2785 	desc = &tab->descs[desc_idx];
2786 	if (desc->func_id != func_id)
2787 		return -EFAULT;
2788 
2789 	*func_addr = (u8 *)desc->addr;
2790 	return 0;
2791 }
2792 
2793 #define BPF_FD_SLOT_BTF	1UL
2794 
2795 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map)
2796 {
2797 	slot->val = (unsigned long)map;
2798 }
2799 
2800 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf)
2801 {
2802 	slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF;
2803 }
2804 
2805 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot)
2806 {
2807 	if (slot.val & BPF_FD_SLOT_BTF)
2808 		return NULL;
2809 	return (struct bpf_map *)slot.val;
2810 }
2811 
2812 static struct btf *fd_slot_btf(struct bpf_fd_array slot)
2813 {
2814 	if (!(slot.val & BPF_FD_SLOT_BTF))
2815 		return NULL;
2816 	return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF);
2817 }
2818 
2819 static struct btf *
2820 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx)
2821 {
2822 	struct btf *btf;
2823 
2824 	if (idx >= env->fd_array_cnt) {
2825 		verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n",
2826 			idx, env->fd_array_cnt);
2827 		return ERR_PTR(-EINVAL);
2828 	}
2829 	btf = fd_slot_btf(env->fd_array[idx]);
2830 	if (!btf) {
2831 		verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx);
2832 		return ERR_PTR(-EINVAL);
2833 	}
2834 	btf_get(btf);
2835 	return btf;
2836 }
2837 
2838 static struct btf *
2839 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx)
2840 {
2841 	struct btf *btf;
2842 	int btf_fd;
2843 
2844 	if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw,
2845 				    (size_t)idx * sizeof(btf_fd), sizeof(btf_fd)))
2846 		return ERR_PTR(-EFAULT);
2847 	btf = btf_get_by_fd(btf_fd);
2848 	if (IS_ERR(btf)) {
2849 		verbose(env, "invalid module BTF fd specified\n");
2850 		return btf;
2851 	}
2852 	return btf;
2853 }
2854 
2855 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx)
2856 {
2857 	if (env->signature) {
2858 		verbose(env, "signed program cannot bind any BTF\n");
2859 		return ERR_PTR(-EACCES);
2860 	}
2861 	if (env->fd_array)
2862 		return fd_array_get_btf_continuous(env, idx);
2863 	if (!bpfptr_is_null(env->fd_array_raw))
2864 		return fd_array_get_btf_sparse(env, idx);
2865 
2866 	verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2867 	return ERR_PTR(-EPROTO);
2868 }
2869 
2870 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2871 					 s16 offset)
2872 {
2873 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2874 	struct bpf_kfunc_btf_tab *tab;
2875 	struct bpf_kfunc_btf *b;
2876 	struct module *mod;
2877 	struct btf *btf;
2878 
2879 	tab = env->prog->aux->kfunc_btf_tab;
2880 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2881 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2882 	if (!b) {
2883 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2884 			verbose(env, "too many different module BTFs\n");
2885 			return ERR_PTR(-E2BIG);
2886 		}
2887 
2888 		btf = fd_array_get_btf(env, offset);
2889 		if (IS_ERR(btf))
2890 			return btf;
2891 		if (!btf_is_module(btf)) {
2892 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2893 			btf_put(btf);
2894 			return ERR_PTR(-EINVAL);
2895 		}
2896 
2897 		mod = btf_try_get_module(btf);
2898 		if (!mod) {
2899 			btf_put(btf);
2900 			return ERR_PTR(-ENXIO);
2901 		}
2902 
2903 		b = &tab->descs[tab->nr_descs++];
2904 		b->btf = btf;
2905 		b->module = mod;
2906 		b->offset = offset;
2907 
2908 		/* sort() reorders entries by value, so b may no longer point
2909 		 * to the right entry after this
2910 		 */
2911 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2912 		     kfunc_btf_cmp_by_off, NULL);
2913 	} else {
2914 		btf = b->btf;
2915 	}
2916 
2917 	return btf;
2918 }
2919 
2920 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2921 {
2922 	if (!tab)
2923 		return;
2924 
2925 	while (tab->nr_descs--) {
2926 		module_put(tab->descs[tab->nr_descs].module);
2927 		btf_put(tab->descs[tab->nr_descs].btf);
2928 	}
2929 	kfree(tab);
2930 }
2931 
2932 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2933 {
2934 	if (offset) {
2935 		if (offset < 0) {
2936 			/* In the future, this can be allowed to increase limit
2937 			 * of fd index into fd_array, interpreted as u16.
2938 			 */
2939 			verbose(env, "negative offset disallowed for kernel module function call\n");
2940 			return ERR_PTR(-EINVAL);
2941 		}
2942 
2943 		return __find_kfunc_desc_btf(env, offset);
2944 	}
2945 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2946 }
2947 
2948 static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset)
2949 {
2950 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2951 	struct bpf_kfunc_btf_tab *tab;
2952 	struct bpf_kfunc_btf *b;
2953 
2954 	if (!offset)
2955 		return btf_vmlinux ?: ERR_PTR(-ENOENT);
2956 	if (offset < 0)
2957 		return ERR_PTR(-EINVAL);
2958 
2959 	tab = env->prog->aux->kfunc_btf_tab;
2960 	if (!tab)
2961 		return ERR_PTR(-ENOENT);
2962 
2963 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2964 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2965 	return b ? b->btf : ERR_PTR(-ENOENT);
2966 }
2967 
2968 #define KF_IMPL_SUFFIX "_impl"
2969 
2970 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2971 						    struct btf *btf,
2972 						    const char *func_name)
2973 {
2974 	const struct btf_type *func;
2975 	char buf[KSYM_NAME_LEN];
2976 	s32 impl_id;
2977 	int len;
2978 
2979 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2980 	if (len < 0 || len >= sizeof(buf)) {
2981 		bpf_log(log, "function name %s%s is too long\n",
2982 			func_name, KF_IMPL_SUFFIX);
2983 		return NULL;
2984 	}
2985 
2986 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
2987 	if (impl_id <= 0) {
2988 		bpf_log(log, "cannot find function %s in BTF\n", buf);
2989 		return NULL;
2990 	}
2991 
2992 	func = btf_type_by_id(btf, impl_id);
2993 
2994 	return btf_type_by_id(btf, func->type);
2995 }
2996 
2997 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
2998 			    s32 func_id,
2999 			    s16 offset,
3000 			    struct bpf_kfunc_meta *kfunc)
3001 {
3002 	const struct btf_type *func, *func_proto;
3003 	const char *func_name;
3004 	u32 *kfunc_flags;
3005 	struct btf *btf;
3006 
3007 	if (func_id <= 0) {
3008 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
3009 		return -EINVAL;
3010 	}
3011 
3012 	btf = find_kfunc_desc_btf(env, offset);
3013 	if (IS_ERR(btf)) {
3014 		verbose(env, "failed to find BTF for kernel function\n");
3015 		return PTR_ERR(btf);
3016 	}
3017 
3018 	/*
3019 	 * Note that kfunc_flags may be NULL at this point, which
3020 	 * means that we couldn't find func_id in any relevant
3021 	 * kfunc_id_set. This most likely indicates an invalid kfunc
3022 	 * call.  However we don't fail with an error here,
3023 	 * and let the caller decide what to do with NULL kfunc->flags.
3024 	 */
3025 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
3026 
3027 	func = btf_type_by_id(btf, func_id);
3028 	if (!func || !btf_type_is_func(func)) {
3029 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
3030 		return -EINVAL;
3031 	}
3032 
3033 	func_name = btf_name_by_offset(btf, func->name_off);
3034 
3035 	/*
3036 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
3037 	 * can be found through the counterpart _impl kfunc.
3038 	 */
3039 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
3040 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
3041 	else
3042 		func_proto = btf_type_by_id(btf, func->type);
3043 
3044 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3045 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
3046 			func_id);
3047 		return -EINVAL;
3048 	}
3049 
3050 	memset(kfunc, 0, sizeof(*kfunc));
3051 	kfunc->btf = btf;
3052 	kfunc->id = func_id;
3053 	kfunc->name = func_name;
3054 	kfunc->proto = func_proto;
3055 	kfunc->flags = kfunc_flags;
3056 
3057 	return 0;
3058 }
3059 
3060 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3061 			       const struct btf_func_model *fm, struct bpf_func_proto *proto);
3062 
3063 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
3064 {
3065 	struct bpf_call_arg_meta meta;
3066 	struct bpf_kfunc_btf_tab *btf_tab;
3067 	struct btf_func_model func_model;
3068 	struct bpf_kfunc_desc_tab *tab;
3069 	struct bpf_prog_aux *prog_aux;
3070 	struct bpf_kfunc_meta kfunc;
3071 	struct bpf_kfunc_desc *desc;
3072 	unsigned long addr;
3073 	int err;
3074 
3075 	prog_aux = env->prog->aux;
3076 	tab = prog_aux->kfunc_tab;
3077 	btf_tab = prog_aux->kfunc_btf_tab;
3078 	if (!tab) {
3079 		if (!btf_vmlinux) {
3080 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3081 			return -ENOTSUPP;
3082 		}
3083 
3084 		if (!env->prog->jit_requested) {
3085 			verbose(env, "JIT is required for calling kernel function\n");
3086 			return -ENOTSUPP;
3087 		}
3088 
3089 		if (!bpf_jit_supports_kfunc_call()) {
3090 			verbose(env, "JIT does not support calling kernel function\n");
3091 			return -ENOTSUPP;
3092 		}
3093 
3094 		if (!env->prog->gpl_compatible) {
3095 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3096 			return -EINVAL;
3097 		}
3098 
3099 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
3100 		if (!tab)
3101 			return -ENOMEM;
3102 		prog_aux->kfunc_tab = tab;
3103 	}
3104 
3105 	env->prog->jit_required = 1;
3106 
3107 	/* func_id == 0 is always invalid, but instead of returning an error, be
3108 	 * conservative and wait until the code elimination pass before returning
3109 	 * error, so that invalid calls that get pruned out can be in BPF programs
3110 	 * loaded from userspace.  It is also required that offset be untouched
3111 	 * for such calls.
3112 	 */
3113 	if (!func_id && !offset)
3114 		return 0;
3115 
3116 	if (!btf_tab && offset) {
3117 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
3118 		if (!btf_tab)
3119 			return -ENOMEM;
3120 		prog_aux->kfunc_btf_tab = btf_tab;
3121 	}
3122 
3123 	if (find_kfunc_desc(env->prog, func_id, offset))
3124 		return 0;
3125 
3126 	if (tab->nr_base_descs == MAX_KFUNC_DESCS) {
3127 		verbose(env, "too many different kernel function calls\n");
3128 		return -E2BIG;
3129 	}
3130 	if (tab->nr_descs != tab->nr_base_descs) {
3131 		verifier_bug(env, "unexpected specialized func desc found (%d descs, %d base descs)",
3132 			     tab->nr_descs, tab->nr_base_descs);
3133 		return -EFAULT;
3134 	}
3135 
3136 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
3137 	if (err)
3138 		return err;
3139 
3140 	addr = kallsyms_lookup_name(kfunc.name);
3141 	if (!addr) {
3142 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
3143 		return -EINVAL;
3144 	}
3145 
3146 	if (bpf_dev_bound_kfunc_id(func_id)) {
3147 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3148 		if (err)
3149 			return err;
3150 	}
3151 
3152 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
3153 	if (err)
3154 		return err;
3155 	if (func_model.ret_size > 8) {
3156 		if (kfunc.flags && (*kfunc.flags & KF_FASTCALL)) {
3157 			verbose(env, "kfunc %s with >8-byte return is not supported with KF_FASTCALL\n",
3158 				kfunc.name);
3159 			return -EOPNOTSUPP;
3160 		}
3161 		if (!bpf_jit_supports_kfunc_ret_reg_pair()) {
3162 			verbose(env, "kfunc %s with >8-byte return is not supported by JIT\n",
3163 				kfunc.name);
3164 			return -EOPNOTSUPP;
3165 		}
3166 	}
3167 
3168 	memset(&meta, 0, sizeof(meta));
3169 	meta.btf = kfunc.btf;
3170 	meta.func_id = kfunc.id;
3171 	meta.func_proto = kfunc.proto;
3172 	meta.func_name = kfunc.name;
3173 	meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;
3174 
3175 	tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT);
3176 	if (!tab)
3177 		return -ENOMEM;
3178 	prog_aux->kfunc_tab = tab;
3179 
3180 	desc = &tab->descs[tab->nr_descs];
3181 	memset(desc, 0, sizeof(*desc));
3182 
3183 	err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto);
3184 	if (err)
3185 		return err;
3186 
3187 	desc->func_id = func_id;
3188 	desc->offset = offset;
3189 	desc->addr = addr;
3190 	desc->func_model = func_model;
3191 	tab->nr_descs++;
3192 	tab->nr_base_descs++;
3193 	sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]),
3194 	     kfunc_desc_cmp_by_id_off, NULL);
3195 	return 0;
3196 }
3197 
3198 static int add_subprogs(struct bpf_verifier_env *env)
3199 {
3200 	struct bpf_subprog_info *subprog = env->subprog_info;
3201 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3202 	struct bpf_insn *insn = env->prog->insnsi;
3203 	const char *operation, *suggestion;
3204 
3205 	/* Add entry function. */
3206 	ret = add_subprog(env, 0);
3207 	if (ret)
3208 		return ret;
3209 
3210 	for (i = 0; i < insn_cnt; i++, insn++) {
3211 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
3212 			continue;
3213 
3214 		if (!env->bpf_capable) {
3215 			if (bpf_pseudo_func(insn)) {
3216 				operation = "BPF function reference";
3217 				suggestion = "Load this program with the required capability, or avoid BPF function references in unprivileged programs.";
3218 			} else {
3219 				operation = "BPF-to-BPF function call";
3220 				suggestion = "Load this program with the required capability, or avoid BPF-to-BPF function calls in unprivileged programs.";
3221 			}
3222 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3223 			bpf_diag_policy(
3224 				env, i, operation,
3225 				"loading or calling other BPF functions requires CAP_BPF or CAP_SYS_ADMIN",
3226 				suggestion);
3227 			return -EPERM;
3228 		}
3229 
3230 		ret = add_subprog(env, i + insn->imm + 1);
3231 		if (ret < 0)
3232 			return ret;
3233 	}
3234 
3235 	/*
3236 	 * func_info describes all functions of the program. Those that are
3237 	 * referenced only from data, e.g. from a table of functions to be
3238 	 * called via callx, are not seen by the loop above. They are possible
3239 	 * callees that have to be known upfront as well.
3240 	 */
3241 	if (env->bpf_capable) {
3242 		struct bpf_prog_aux *aux = env->prog->aux;
3243 
3244 		for (i = 1; i < aux->func_info_cnt; i++) {
3245 			ret = add_subprog(env, aux->func_info[i].insn_off);
3246 			if (ret < 0)
3247 				return ret;
3248 		}
3249 	}
3250 
3251 	ret = bpf_find_exception_callback_insn_off(env);
3252 	if (ret < 0)
3253 		return ret;
3254 	ex_cb_insn = ret;
3255 
3256 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3257 	 * marked using BTF decl tag to serve as the exception callback.
3258 	 */
3259 	if (ex_cb_insn) {
3260 		ret = add_subprog(env, ex_cb_insn);
3261 		if (ret < 0)
3262 			return ret;
3263 		for (i = 1; i < env->subprog_cnt; i++) {
3264 			if (env->subprog_info[i].start != ex_cb_insn)
3265 				continue;
3266 			env->exception_callback_subprog = i;
3267 			bpf_mark_subprog_exc_cb(env, i);
3268 			break;
3269 		}
3270 	}
3271 
3272 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3273 	 * logic. 'subprog_cnt' should not be increased.
3274 	 */
3275 	subprog[env->subprog_cnt].start = insn_cnt;
3276 
3277 	if (env->log.level & BPF_LOG_LEVEL2)
3278 		for (i = 0; i < env->subprog_cnt; i++)
3279 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3280 
3281 	return 0;
3282 }
3283 
3284 static int add_kfuncs(struct bpf_verifier_env *env)
3285 {
3286 	struct bpf_insn *insn = env->prog->insnsi;
3287 	int i, ret, insn_cnt = env->prog->len;
3288 
3289 	for (i = 0; i < insn_cnt; i++, insn++) {
3290 		if (!bpf_pseudo_kfunc_call(insn))
3291 			continue;
3292 
3293 		if (!env->bpf_capable) {
3294 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3295 			bpf_diag_policy(
3296 				env, i, "kernel function call",
3297 				"calling kernel functions requires CAP_BPF or CAP_SYS_ADMIN",
3298 				"Load this program with the required capability, or avoid kernel function calls in unprivileged programs.");
3299 			return -EPERM;
3300 		}
3301 
3302 		ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
3303 		if (ret < 0)
3304 			return ret;
3305 	}
3306 
3307 	return 0;
3308 }
3309 
3310 static void find_subprog_properties(struct bpf_verifier_env *env)
3311 {
3312 	struct bpf_subprog_info *subprog = env->subprog_info;
3313 	struct bpf_insn *insn = env->prog->insnsi;
3314 	int cur_subprog;
3315 
3316 	for (cur_subprog = 0; cur_subprog < env->subprog_cnt; cur_subprog++) {
3317 		int i;
3318 
3319 		for (i = subprog[cur_subprog].start;
3320 		     i < subprog[cur_subprog + 1].start; i++) {
3321 			u8 code = insn[i].code;
3322 
3323 			if (code == (BPF_JMP | BPF_CALL) &&
3324 			    insn[i].src_reg == 0 &&
3325 			    insn[i].imm == BPF_FUNC_tail_call) {
3326 				subprog[cur_subprog].has_tail_call = true;
3327 				subprog[cur_subprog].tail_call_reachable = true;
3328 			}
3329 			if (BPF_CLASS(code) == BPF_LD &&
3330 			    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3331 				subprog[cur_subprog].has_ld_abs = true;
3332 			if (bpf_is_callx(&insn[i]))
3333 				env->has_callx = true;
3334 		}
3335 	}
3336 }
3337 
3338 static int check_subprogs(struct bpf_verifier_env *env)
3339 {
3340 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3341 	struct bpf_subprog_info *subprog = env->subprog_info;
3342 	struct bpf_insn *insn = env->prog->insnsi;
3343 	int insn_cnt = env->prog->len;
3344 
3345 	/* now check that all jumps are within the same subprog */
3346 	subprog_start = subprog[cur_subprog].start;
3347 	subprog_end = subprog[cur_subprog + 1].start;
3348 	for (i = 0; i < insn_cnt; i++) {
3349 		u8 code = insn[i].code;
3350 
3351 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3352 			goto next;
3353 		if (BPF_OP(code) == BPF_CALL)
3354 			goto next;
3355 		if (BPF_OP(code) == BPF_EXIT) {
3356 			subprog[cur_subprog].exit_idx = i;
3357 			goto next;
3358 		}
3359 		if (insn_is_gotox(&insn[i]))
3360 			goto next;
3361 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3362 		if (off < subprog_start || off >= subprog_end) {
3363 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3364 			bpf_diag_program_structure(
3365 				env, i, "jump out of range",
3366 				"Keep branch targets within the same subprogram, or use an explicit subprogram call.",
3367 				"Instruction %d jumps to instruction %d, but subprogram %d only contains instructions %d through %d. "
3368 				"A branch target must stay inside the same subprogram.",
3369 				i, off, cur_subprog, subprog_start, subprog_end - 1);
3370 			return -EINVAL;
3371 		}
3372 next:
3373 		if (i == subprog_end - 1) {
3374 			/*
3375 			 * To avoid fall-through from one subprog into another,
3376 			 * the last insn of the subprog should be either exit
3377 			 * or unconditional jump back or bpf_throw call.
3378 			 */
3379 			if (code != (BPF_JMP | BPF_EXIT) &&
3380 			    code != (BPF_JMP32 | BPF_JA) &&
3381 			    code != (BPF_JMP | BPF_JA) &&
3382 			    !insn_is_gotox(&insn[i])) {
3383 				verbose(env, "last insn is not an exit or jmp\n");
3384 				bpf_diag_program_structure(
3385 					env, i, "subprogram can fall through",
3386 					"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
3387 					"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
3388 					cur_subprog, i);
3389 				return -EINVAL;
3390 			}
3391 			subprog_start = subprog_end;
3392 			cur_subprog++;
3393 			if (cur_subprog < env->subprog_cnt)
3394 				subprog_end = subprog[cur_subprog + 1].start;
3395 		}
3396 	}
3397 	return 0;
3398 }
3399 
3400 /*
3401  * The callee of callx is known to the main verification pass only, which
3402  * records the 'caller' -> 'callee' edge of the call graph for the checks
3403  * that follow it: absence of recursion and the maximum stack depth.
3404  */
3405 static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee)
3406 {
3407 	u32 cnt = env->subprog_cnt;
3408 
3409 	if (!env->callx_edges) {
3410 		env->callx_edges = kvcalloc(BITS_TO_LONGS(cnt * cnt), sizeof(long),
3411 					    GFP_KERNEL_ACCOUNT);
3412 		if (!env->callx_edges)
3413 			return -ENOMEM;
3414 	}
3415 	__set_bit(caller * cnt + callee, env->callx_edges);
3416 	return 0;
3417 }
3418 
3419 /*
3420  * Return the first subprog with the number >= 'from' that 'caller' calls
3421  * via callx, or -1 when there is none.
3422  */
3423 static int next_callx_callee(struct bpf_verifier_env *env, int caller, int from)
3424 {
3425 	u32 cnt = env->subprog_cnt;
3426 	unsigned long bit, end = (caller + 1) * cnt;
3427 
3428 	if (!env->callx_edges || from >= cnt)
3429 		return -1;
3430 	bit = find_next_bit(env->callx_edges, end, caller * cnt + from);
3431 	return bit < end ? bit - caller * cnt : -1;
3432 }
3433 
3434 /*
3435  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
3436  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
3437  * address. So unwind_goto has to follow the call and nothing may jump to it.
3438  */
3439 static int check_unwind_insns(struct bpf_verifier_env *env)
3440 {
3441 	struct bpf_insn *insn = env->prog->insnsi;
3442 	bool seen = false;
3443 	int i;
3444 
3445 	for (i = 0; i < env->prog->len; i++, insn++) {
3446 		if (bpf_is_unwind_exit(insn)) {
3447 			bpf_find_containing_subprog(env, i)->can_unwind = true;
3448 			seen = true;
3449 		}
3450 		if (!bpf_is_unwind_goto(insn))
3451 			continue;
3452 		seen = true;
3453 		if (!i || !(bpf_pseudo_call(insn - 1) || bpf_is_callx(insn - 1))) {
3454 			verbose(env, "unwind_goto at insn %d doesn't follow a call of a subprog\n",
3455 				i);
3456 			return -EINVAL;
3457 		}
3458 		if (bpf_is_jump_target(env, i)) {
3459 			verbose(env, "jump to unwind_goto at insn %d\n", i);
3460 			return -EINVAL;
3461 		}
3462 	}
3463 	if (!seen)
3464 		return 0;
3465 	if (!bpf_jit_supports_unwind() || bpf_prog_is_offloaded(env->prog->aux)) {
3466 		verbose(env, "JIT does not support unwinding\n");
3467 		return -ENOTSUPP;
3468 	}
3469 	env->prog->jit_required = 1;
3470 	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind;
3471 	return 0;
3472 }
3473 
3474 /*
3475  * Sort subprogs in topological order so that leaf subprogs come first and
3476  * their callers come later. This is a DFS post-order traversal of the call
3477  * graph. Scan only reachable instructions (those in the computed postorder) of
3478  * the current subprog to discover callees (direct subprogs and sync
3479  * callbacks).
3480  *
3481  * The callees of callx are not known before the main verification pass.
3482  * When callx is used the sort is repeated after it with the recorded callx
3483  * edges added to the call graph to reject recursion through indirect calls.
3484  */
3485 static int sort_subprogs_topo(struct bpf_verifier_env *env)
3486 {
3487 	struct bpf_subprog_info *si = env->subprog_info;
3488 	int *insn_postorder = env->cfg.insn_postorder;
3489 	struct bpf_insn *insn = env->prog->insnsi;
3490 	int cnt = env->subprog_cnt;
3491 	int *dfs_stack = NULL;
3492 	int top = 0, order = 0;
3493 	int i, ret = 0;
3494 	u8 *color = NULL;
3495 
3496 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
3497 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
3498 	if (!color || !dfs_stack) {
3499 		ret = -ENOMEM;
3500 		goto out;
3501 	}
3502 
3503 	/*
3504 	 * DFS post-order traversal.
3505 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
3506 	 */
3507 	for (i = 0; i < cnt; i++) {
3508 		if (color[i])
3509 			continue;
3510 		color[i] = 1;
3511 		dfs_stack[top++] = i;
3512 
3513 		while (top > 0) {
3514 			int cur = dfs_stack[top - 1];
3515 			int po_start = si[cur].postorder_start;
3516 			int po_end = si[cur + 1].postorder_start;
3517 			bool pushed = false;
3518 			int j;
3519 
3520 			for (j = po_start; j < po_end; j++) {
3521 				int idx = insn_postorder[j];
3522 				int callee;
3523 
3524 				if (bpf_is_callx(&insn[idx])) {
3525 					/* find a callee that is not explored yet */
3526 					callee = -1;
3527 					do {
3528 						callee = next_callx_callee(env, cur, callee + 1);
3529 					} while (callee >= 0 && color[callee] == 2);
3530 					if (callee < 0)
3531 						continue;
3532 				} else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) {
3533 					callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
3534 					if (callee < 0) {
3535 						ret = -EFAULT;
3536 						goto out;
3537 					}
3538 				} else {
3539 					continue;
3540 				}
3541 				if (color[callee] == 2)
3542 					continue;
3543 				if (color[callee] == 1) {
3544 					if (bpf_pseudo_func(&insn[idx]))
3545 						continue;
3546 					verbose(env, "recursive call from %s() to %s()\n",
3547 						bpf_subprog_name(env, cur),
3548 						bpf_subprog_name(env, callee));
3549 					bpf_diag_program_structure(
3550 						env, idx, "recursive subprogram call",
3551 						"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
3552 						"This bpf2bpf call would make the subprogram call graph recursive. "
3553 						"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
3554 					ret = -EINVAL;
3555 					goto out;
3556 				}
3557 				color[callee] = 1;
3558 				dfs_stack[top++] = callee;
3559 				pushed = true;
3560 				break;
3561 			}
3562 
3563 			if (!pushed) {
3564 				color[cur] = 2;
3565 				env->subprog_topo_order[order++] = cur;
3566 				top--;
3567 			}
3568 		}
3569 	}
3570 
3571 	if (env->log.level & BPF_LOG_LEVEL2)
3572 		for (i = 0; i < cnt; i++)
3573 			verbose(env, "topo_order[%d] = %s\n",
3574 				i, bpf_subprog_name(env, env->subprog_topo_order[i]));
3575 out:
3576 	kvfree(dfs_stack);
3577 	kvfree(color);
3578 	return ret;
3579 }
3580 
3581 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
3582 				       int spi, int nr_slots)
3583 {
3584 	int i;
3585 
3586 	for (i = 0; i < nr_slots; i++)
3587 		mark_stack_slot_scratched(env, spi - i);
3588 }
3589 
3590 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3591 			   enum bpf_reg_arg_type t)
3592 {
3593 	struct bpf_reg_state *reg;
3594 
3595 	mark_reg_scratched(env, regno);
3596 
3597 	reg = &regs[regno];
3598 	if (t == SRC_OP) {
3599 		/* check whether register used as source operand can be read */
3600 		if (reg->type == NOT_INIT) {
3601 			verbose(env, "R%d !read_ok\n", regno);
3602 			bpf_diag_unreadable_reg(env, env->insn_idx, regno);
3603 			return -EACCES;
3604 		}
3605 		/* We don't need to worry about FP liveness because it's read-only */
3606 		if (regno == BPF_REG_FP)
3607 			return 0;
3608 
3609 		return 0;
3610 	} else {
3611 		/* check whether register used as dest operand can be written to */
3612 		if (regno == BPF_REG_FP) {
3613 			verbose(env, "frame pointer is read only\n");
3614 			return -EACCES;
3615 		}
3616 		if (t == DST_OP)
3617 			mark_reg_unknown(env, regs, regno);
3618 	}
3619 	return 0;
3620 }
3621 
3622 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3623 			 enum bpf_reg_arg_type t)
3624 {
3625 	struct bpf_verifier_state *vstate = env->cur_state;
3626 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3627 
3628 	return __check_reg_arg(env, state->regs, regno, t);
3629 }
3630 
3631 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3632 {
3633 	env->insn_aux_data[idx].indirect_target = true;
3634 }
3635 
3636 static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)
3637 {
3638 	env->insn_aux_data[idx].non_stack_access = true;
3639 }
3640 
3641 /* Layout of one packed linked register in the jump history, see linked_regs_pack() */
3642 #define LR_FRAMENO_BITS	4
3643 #define LR_INDEX_BITS	11
3644 #define LR_FRAMENO_MASK	((1u << LR_FRAMENO_BITS) - 1)
3645 #define LR_IS_REG	BIT(LR_FRAMENO_BITS)
3646 #define LR_INDEX_OFF	(LR_FRAMENO_BITS + 1)
3647 #define LR_INDEX_MASK	((1u << LR_INDEX_BITS) - 1)
3648 #define LINKED_REGS_MAX	BPF_LINKED_REGS_MAX
3649 
3650 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3651 static_assert(MAX_BPF_REG <= (1 << LR_INDEX_BITS));
3652 static_assert(MAX_BPF_STACK_SLOTS <= (1 << LR_INDEX_BITS));
3653 static_assert(LR_INDEX_OFF + LR_INDEX_BITS <= 16);
3654 
3655 struct linked_reg {
3656 	u8 frameno;
3657 	union {
3658 		u16 spi;
3659 		u16 regno;
3660 	};
3661 	bool is_reg;
3662 };
3663 
3664 struct linked_regs {
3665 	int cnt;
3666 	struct linked_reg entries[LINKED_REGS_MAX];
3667 };
3668 
3669 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3670 {
3671 	if (s->cnt < LINKED_REGS_MAX)
3672 		return &s->entries[s->cnt++];
3673 
3674 	return NULL;
3675 }
3676 
3677 /*
3678  * Pack linked registers for a jump history entry, one u16 each:
3679  * - 4 bits frameno
3680  * - 1 bit  is_reg
3681  * - 11 bits register or stack slot index
3682  */
3683 static void linked_regs_pack(const struct linked_regs *s, u16 *packed)
3684 {
3685 	int i;
3686 
3687 	for (i = 0; i < s->cnt; ++i) {
3688 		const struct linked_reg *e = &s->entries[i];
3689 
3690 		packed[i] = e->frameno | (e->is_reg ? LR_IS_REG : 0) | (e->spi << LR_INDEX_OFF);
3691 	}
3692 }
3693 
3694 static void linked_regs_unpack(const struct bpf_jmp_history_entry *hist, struct linked_regs *s)
3695 {
3696 	int i;
3697 
3698 	s->cnt = hist->linked_regs_cnt;
3699 	for (i = 0; i < s->cnt; ++i) {
3700 		struct linked_reg *e = &s->entries[i];
3701 		u16 packed = hist->linked_regs[i];
3702 
3703 		e->frameno = packed & LR_FRAMENO_MASK;
3704 		e->is_reg  = packed & LR_IS_REG;
3705 		e->spi     = (packed >> LR_INDEX_OFF) & LR_INDEX_MASK;
3706 	}
3707 }
3708 
3709 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3710 {
3711 	const struct btf_type *func;
3712 	struct btf *desc_btf;
3713 
3714 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3715 		return NULL;
3716 
3717 	desc_btf = find_kfunc_desc_btf_cached(data, insn->off);
3718 	if (IS_ERR(desc_btf))
3719 		return "<error>";
3720 
3721 	func = btf_type_by_id(desc_btf, insn->imm);
3722 	if (!func || !btf_type_is_func(func))
3723 		return "<error>";
3724 	return btf_name_by_offset(desc_btf, func->name_off);
3725 }
3726 
3727 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3728 {
3729 	const struct bpf_insn_cbs cbs = {
3730 		.cb_call	= bpf_disasm_kfunc_name,
3731 		.cb_print	= verbose,
3732 		.private_data	= env,
3733 	};
3734 
3735 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3736 }
3737 
3738 /* If any register R in hist->linked_regs is marked as precise in bt,
3739  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3740  */
3741 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3742 {
3743 	struct linked_regs linked_regs;
3744 	bool some_precise = false;
3745 	int i;
3746 
3747 	if (!hist || !hist->linked_regs_cnt)
3748 		return;
3749 
3750 	linked_regs_unpack(hist, &linked_regs);
3751 	for (i = 0; i < linked_regs.cnt; ++i) {
3752 		struct linked_reg *e = &linked_regs.entries[i];
3753 
3754 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3755 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3756 			some_precise = true;
3757 			break;
3758 		}
3759 	}
3760 
3761 	if (!some_precise)
3762 		return;
3763 
3764 	for (i = 0; i < linked_regs.cnt; ++i) {
3765 		struct linked_reg *e = &linked_regs.entries[i];
3766 
3767 		if (e->is_reg)
3768 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3769 		else
3770 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3771 	}
3772 }
3773 
3774 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3775 {
3776 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3777 }
3778 
3779 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3780  * desired reg and stack masks across all relevant frames
3781  */
3782 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3783 				      struct bpf_verifier_state *starting_state)
3784 {
3785 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3786 }
3787 
3788 /* check if register is a constant scalar value */
3789 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3790 {
3791 	return reg->type == SCALAR_VALUE &&
3792 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3793 }
3794 
3795 /* assuming is_reg_const() is true, return constant value of a register */
3796 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3797 {
3798 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3799 }
3800 
3801 static bool is_pointer_regtype(enum bpf_reg_type type)
3802 {
3803 	return type != SCALAR_VALUE && type != NOT_INIT;
3804 }
3805 
3806 static bool __is_pointer_value(bool allow_ptr_leaks,
3807 			       const struct bpf_reg_state *reg)
3808 {
3809 	if (allow_ptr_leaks)
3810 		return false;
3811 
3812 	return is_pointer_regtype(reg->type);
3813 }
3814 
3815 static void clear_scalar_id(struct bpf_reg_state *reg)
3816 {
3817 	reg->id = 0;
3818 	reg->delta = 0;
3819 }
3820 
3821 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3822 					struct bpf_reg_state *src_reg)
3823 {
3824 	if (src_reg->type != SCALAR_VALUE)
3825 		return;
3826 	/*
3827 	 * The verifier is processing rX = rY insn and
3828 	 * rY->id has special linked register already.
3829 	 * Cleared it, since multiple rX += const are not supported.
3830 	 */
3831 	if (src_reg->id & BPF_ADD_CONST)
3832 		clear_scalar_id(src_reg);
3833 	/*
3834 	 * Ensure that src_reg has a valid ID that will be copied to
3835 	 * dst_reg and then will be used by sync_linked_regs() to
3836 	 * propagate min/max range.
3837 	 */
3838 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3839 		src_reg->id = ++env->id_gen;
3840 }
3841 
3842 static void save_register_state(struct bpf_verifier_env *env,
3843 				struct bpf_func_state *state,
3844 				int spi, struct bpf_reg_state *reg,
3845 				int size)
3846 {
3847 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3848 	int i;
3849 
3850 	bpf_diag_mod_begin(env, &slot->spilled_ptr, reg, BPF_DIAG_MOD_SPILL);
3851 	slot->spilled_ptr = *reg;
3852 
3853 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3854 		slot->slot_type[i - 1] = STACK_SPILL;
3855 
3856 	/* size < 8 bytes spill */
3857 	for (; i; i--)
3858 		mark_stack_slot_misc(env, &slot->slot_type[i - 1]);
3859 
3860 	bpf_diag_mod_end(env);
3861 }
3862 
3863 static bool is_bpf_st_mem(struct bpf_insn *insn)
3864 {
3865 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3866 }
3867 
3868 static int get_reg_width(struct bpf_reg_state *reg)
3869 {
3870 	return fls64(reg_umax(reg));
3871 }
3872 
3873 /* See comment for mark_fastcall_pattern_for_call() */
3874 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3875 					  struct bpf_func_state *state, int insn_idx, int off)
3876 {
3877 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3878 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3879 	int i;
3880 
3881 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3882 		return;
3883 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3884 	 * from something that is not a part of the fastcall pattern,
3885 	 * disable fastcall rewrites for current subprogram by setting
3886 	 * fastcall_stack_off to a value smaller than any possible offset.
3887 	 */
3888 	subprog->fastcall_stack_off = S16_MIN;
3889 	/* reset fastcall aux flags within subprogram,
3890 	 * happens at most once per subprogram
3891 	 */
3892 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3893 		aux[i].fastcall_spills_num = 0;
3894 		aux[i].fastcall_pattern = 0;
3895 	}
3896 }
3897 
3898 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3899 {
3900 	struct bpf_stack_state *slot = bpf_stack_slot(state, spi);
3901 	int i;
3902 
3903 	/* regular write of data into stack destroys any spilled ptr */
3904 	slot->spilled_ptr.type = NOT_INIT;
3905 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3906 	if (is_stack_slot_special(slot))
3907 		for (i = 0; i < BPF_REG_SIZE; i++)
3908 			scrub_spilled_slot(&slot->slot_type[i]);
3909 }
3910 
3911 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3912  * stack boundary and alignment are checked in check_mem_access()
3913  */
3914 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3915 				       /* stack frame we're writing to */
3916 				       struct bpf_func_state *state,
3917 				       int off, int size, int value_regno,
3918 				       int insn_idx)
3919 {
3920 	struct bpf_func_state *cur; /* state of the current function */
3921 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3922 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3923 	struct bpf_reg_state *reg = NULL;
3924 	int insn_flags = INSN_F_STACK_ACCESS;
3925 	int hist_spi = spi, hist_frame = state->frameno;
3926 	struct bpf_stack_state *ss = bpf_stack_slot(state, spi);
3927 
3928 	/*
3929 	 * caller checked that off % size == 0 and -env->stack_limit <= off < 0,
3930 	 * so it's aligned access and [off, off + size) are within stack limits
3931 	 */
3932 	if (!env->allow_ptr_leaks &&
3933 	    bpf_is_spilled_reg(ss) &&
3934 	    !bpf_is_spilled_scalar_reg(ss) &&
3935 	    size != BPF_REG_SIZE) {
3936 		const char *reason;
3937 
3938 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3939 		reason = bpf_diag_fmt(env,
3940 				      "This store writes %d bytes at stack offset %d into a stack slot that currently holds a spilled pointer. "
3941 			"Partial writes to spilled pointers are rejected because they can corrupt pointer metadata and leak kernel pointers.",
3942 			size, off);
3943 		bpf_diag_memory(
3944 			env, insn_idx, "stack spill corruption", reason,
3945 			"Write the full 8-byte spilled pointer slot, or use a separate stack slot for scalar data before overwriting only part of it.");
3946 		return -EACCES;
3947 	}
3948 
3949 	cur = env->cur_state->frame[env->cur_state->curframe];
3950 	if (value_regno >= 0)
3951 		reg = &cur->regs[value_regno];
3952 	if (!env->bypass_spec_v4) {
3953 		bool sanitize = reg && is_pointer_regtype(reg->type);
3954 
3955 		for (i = 0; i < size; i++) {
3956 			u8 type = ss->slot_type[(slot - i) %
3957 							      BPF_REG_SIZE];
3958 
3959 			if (type != STACK_MISC && type != STACK_ZERO) {
3960 				sanitize = true;
3961 				break;
3962 			}
3963 		}
3964 
3965 		if (sanitize)
3966 			env->insn_aux_data[insn_idx].nospec_result = true;
3967 	}
3968 
3969 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3970 	if (err)
3971 		return err;
3972 
3973 	mark_stack_slot_scratched(env, spi);
3974 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3975 		bool reg_value_fits;
3976 
3977 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3978 		/* Make sure that reg had an ID to build a relation on spill. */
3979 		if (reg_value_fits)
3980 			assign_scalar_id_before_mov(env, reg);
3981 		save_register_state(env, state, spi, reg, size);
3982 		/* Break the relation on a narrowing spill. */
3983 		if (!reg_value_fits)
3984 			clear_scalar_id(&ss->spilled_ptr);
3985 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3986 		   env->bpf_capable) {
3987 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3988 
3989 		memset(tmp_reg, 0, sizeof(*tmp_reg));
3990 		__mark_reg_known(tmp_reg, insn->imm);
3991 		tmp_reg->type = SCALAR_VALUE;
3992 		save_register_state(env, state, spi, tmp_reg, size);
3993 	} else if (reg && is_pointer_regtype(reg->type)) {
3994 		/* register containing pointer is being spilled into stack */
3995 		if (size != BPF_REG_SIZE) {
3996 			verbose_linfo(env, insn_idx, "; ");
3997 			verbose(env, "invalid size of register spill\n");
3998 			return -EACCES;
3999 		}
4000 		if (state != cur && reg->type == PTR_TO_STACK) {
4001 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4002 			return -EINVAL;
4003 		}
4004 		save_register_state(env, state, spi, reg, size);
4005 	} else {
4006 		u8 type = STACK_MISC;
4007 
4008 		if (bpf_is_spilled_reg(ss))
4009 			bpf_diag_record_scrub(env, &ss->spilled_ptr,
4010 					      BPF_DIAG_MOD_WRITE);
4011 		scrub_special_slot(state, spi);
4012 
4013 		/* when we zero initialize stack slots mark them as such */
4014 		if ((reg && bpf_register_is_null(reg)) ||
4015 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4016 			/* STACK_ZERO case happened because register spill
4017 			 * wasn't properly aligned at the stack slot boundary,
4018 			 * so it's not a register spill anymore; force
4019 			 * originating register to be precise to make
4020 			 * STACK_ZERO correct for subsequent states
4021 			 */
4022 			err = mark_chain_precision(env, value_regno);
4023 			if (err)
4024 				return err;
4025 			type = STACK_ZERO;
4026 		}
4027 
4028 		/* Mark slots affected by this stack write. */
4029 		for (i = 0; i < size; i++)
4030 			ss->slot_type[(slot - i) % BPF_REG_SIZE] = type;
4031 		insn_flags = 0; /* not a register spill */
4032 	}
4033 
4034 	if (insn_flags)
4035 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4036 					    hist_spi, hist_frame, NULL, 0);
4037 	return 0;
4038 }
4039 
4040 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
4041  * known to contain a variable offset.
4042  * This function checks whether the write is permitted and conservatively
4043  * tracks the effects of the write, considering that each stack slot in the
4044  * dynamic range is potentially written to.
4045  *
4046  * 'value_regno' can be -1, meaning that an unknown value is being written to
4047  * the stack.
4048  *
4049  * Spilled pointers in range are not marked as written because we don't know
4050  * what's going to be actually written. This means that read propagation for
4051  * future reads cannot be terminated by this write.
4052  *
4053  * For privileged programs, uninitialized stack slots are considered
4054  * initialized by this write (even though we don't know exactly what offsets
4055  * are going to be written to). The idea is that we don't want the verifier to
4056  * reject future reads that access slots written to through variable offsets.
4057  */
4058 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4059 				     /* func where register points to */
4060 				     struct bpf_func_state *state,
4061 				     struct bpf_reg_state *ptr_reg, int off, int size,
4062 				     int value_regno, int insn_idx)
4063 {
4064 	struct bpf_func_state *cur; /* state of the current function */
4065 	int min_off, max_off;
4066 	int i, err;
4067 	struct bpf_reg_state *value_reg = NULL;
4068 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4069 	bool writing_zero = false;
4070 	/* set if the fact that we're writing a zero is used to let any
4071 	 * stack slots remain STACK_ZERO
4072 	 */
4073 	bool zero_used = false;
4074 
4075 	cur = env->cur_state->frame[env->cur_state->curframe];
4076 	min_off = reg_smin(ptr_reg) + off;
4077 	max_off = reg_smax(ptr_reg) + off + size;
4078 	if (value_regno >= 0)
4079 		value_reg = &cur->regs[value_regno];
4080 	if ((value_reg && bpf_register_is_null(value_reg)) ||
4081 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4082 		writing_zero = true;
4083 
4084 	err = destroy_dynptrs_in_stack_slots(env, state, bpf_get_spi(max_off - 1),
4085 					     bpf_get_spi(min_off));
4086 	if (err)
4087 		return err;
4088 
4089 	/* Variable offset writes destroy any spilled pointers in range. */
4090 	for (i = min_off; i < max_off; i++) {
4091 		struct bpf_stack_state *ss;
4092 		u8 new_type, *stype;
4093 		int slot, spi;
4094 
4095 		slot = -i - 1;
4096 		spi = slot / BPF_REG_SIZE;
4097 		ss = bpf_stack_slot(state, spi);
4098 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
4099 		mark_stack_slot_scratched(env, spi);
4100 
4101 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4102 			/* Reject the write if range we may write to has not
4103 			 * been initialized beforehand. If we didn't reject
4104 			 * here, the ptr status would be erased below (even
4105 			 * though not all slots are actually overwritten),
4106 			 * possibly opening the door to leaks.
4107 			 *
4108 			 * We do however catch STACK_INVALID case below, and
4109 			 * only allow reading possibly uninitialized memory
4110 			 * later for CAP_PERFMON, as the write may not happen to
4111 			 * that slot.
4112 			 */
4113 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4114 				insn_idx, i);
4115 			return -EINVAL;
4116 		}
4117 
4118 		/* If writing_zero and the spi slot contains a spill of value 0,
4119 		 * maintain the spill type.
4120 		 */
4121 		if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) {
4122 			struct bpf_reg_state *spill_reg = &ss->spilled_ptr;
4123 
4124 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4125 				zero_used = true;
4126 				continue;
4127 			}
4128 		}
4129 
4130 		/*
4131 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
4132 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
4133 		 * and valid program is rejected by check_stack_read_fixed_off()
4134 		 * with obscure "invalid size of register fill" message.
4135 		 */
4136 		scrub_special_slot(state, spi);
4137 
4138 		/* Update the slot type. */
4139 		new_type = STACK_MISC;
4140 		if (writing_zero && *stype == STACK_ZERO) {
4141 			new_type = STACK_ZERO;
4142 			zero_used = true;
4143 		}
4144 		/* If the slot is STACK_INVALID, we check whether it's OK to
4145 		 * pretend that it will be initialized by this write. The slot
4146 		 * might not actually be written to, and so if we mark it as
4147 		 * initialized future reads might leak uninitialized memory.
4148 		 * For privileged programs, we will accept such reads to slots
4149 		 * that may or may not be written because, if we're reject
4150 		 * them, the error would be too confusing.
4151 		 * Conservatively, treat STACK_POISON in a similar way.
4152 		 */
4153 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
4154 		    !env->allow_uninit_stack) {
4155 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4156 					insn_idx, i);
4157 			return -EINVAL;
4158 		}
4159 		*stype = new_type;
4160 	}
4161 	if (zero_used) {
4162 		/* backtracking doesn't work for STACK_ZERO yet. */
4163 		err = mark_chain_precision(env, value_regno);
4164 		if (err)
4165 			return err;
4166 	}
4167 	bpf_diag_record_scrub_stack(env, state, min_off, max_off,
4168 				    BPF_DIAG_MOD_VAR_WRITE);
4169 	return 0;
4170 }
4171 
4172 /* When register 'dst_regno' is assigned some values from stack[min_off,
4173  * max_off), we set the register's type according to the types of the
4174  * respective stack slots. If all the stack values are known to be zeros, then
4175  * so is the destination reg. Otherwise, the register is considered to be
4176  * SCALAR. This function does not deal with register filling; the caller must
4177  * ensure that all spilled registers in the stack range have been marked as
4178  * read.
4179  *
4180  * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered
4181  * zero bytes. In that case, mark the contributing stack slots precise so
4182  * pruning cannot reuse a zero-spill state for a later non-zero spill state.
4183  *
4184  * Returns an error if precision backtracking fails.
4185  */
4186 static int mark_reg_stack_read(struct bpf_verifier_env *env,
4187 			       /* func where src register points to */
4188 			       struct bpf_func_state *ptr_state,
4189 			       int min_off, int max_off, int dst_regno)
4190 {
4191 	struct bpf_verifier_state *vstate = env->cur_state;
4192 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4193 	int i, slot, spi;
4194 	u8 *stype;
4195 	int zeros = 0, zero_spills = 0;
4196 
4197 	for (i = min_off; i < max_off; i++) {
4198 		slot = -i - 1;
4199 		spi = slot / BPF_REG_SIZE;
4200 		mark_stack_slot_scratched(env, spi);
4201 		stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4202 		if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) {
4203 			zeros++;
4204 			continue;
4205 		}
4206 		if (stype[slot % BPF_REG_SIZE] == STACK_SPILL &&
4207 		    bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) {
4208 			zero_spills++;
4209 			zeros++;
4210 			continue;
4211 		}
4212 		break;
4213 	}
4214 	if (zeros == max_off - min_off) {
4215 		/* Any access_size read into register is zero extended,
4216 		 * so the whole register == const_zero.
4217 		 */
4218 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4219 		if (zero_spills) {
4220 			for (i = min_off; i < max_off; i++) {
4221 				slot = -i - 1;
4222 				spi = slot / BPF_REG_SIZE;
4223 				stype = bpf_stack_slot(ptr_state, spi)->slot_type;
4224 				if (stype[slot % BPF_REG_SIZE] == STACK_SPILL)
4225 					bpf_bt_set_frame_slot(&env->bt, ptr_state->frameno, spi);
4226 			}
4227 			return mark_chain_precision_batch(env, env->cur_state);
4228 		}
4229 	} else {
4230 		/* have read misc data from the stack */
4231 		mark_reg_unknown(env, state->regs, dst_regno);
4232 	}
4233 
4234 	return 0;
4235 }
4236 
4237 static void bpf_diag_stack_read_invalid(struct bpf_verifier_env *env, int off, int i, int size,
4238 					enum bpf_stack_slot_type type)
4239 {
4240 	const char *problem, *reason, *suggestion, *kind;
4241 
4242 	if (type == STACK_INVALID) {
4243 		reason = bpf_diag_fmt(
4244 			env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range is uninitialized on this path. "
4245 			"Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.",
4246 			size, off, i);
4247 		bpf_diag_memory(
4248 			env, env->insn_idx, "uninitialized stack read", reason,
4249 			"Initialize every byte in the stack range before reading it, adjust the offset and size so the read covers only initialized bytes, "
4250 			"or load with CAP_PERFMON if uninitialized stack reads are intended.");
4251 		return;
4252 	}
4253 
4254 	switch (type) {
4255 	case STACK_DYNPTR:
4256 		kind = "dynptr";
4257 		suggestion = "Use dynptr helpers or kfuncs to access the object represented by the dynptr instead of reading the dynptr state directly.";
4258 		break;
4259 	case STACK_ITER:
4260 		kind = "iterator";
4261 		suggestion = "Use iterator kfuncs to advance or destroy the iterator instead of reading its state directly.";
4262 		break;
4263 	case STACK_IRQ_FLAG:
4264 		kind = "IRQ flag";
4265 		suggestion = "Pass the saved IRQ flag to the matching restore kfunc instead of reading its state directly.";
4266 		break;
4267 	default:
4268 		return;
4269 	}
4270 
4271 	problem = bpf_diag_fmt(env, "direct read of %s stack state", kind);
4272 	reason = bpf_diag_fmt(
4273 		env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range belongs to verifier-managed %s state. "
4274 		"This state has an opaque representation that BPF programs cannot read directly.",
4275 		size, off, i, kind);
4276 	bpf_diag_memory(env, env->insn_idx, problem, reason, suggestion);
4277 }
4278 
4279 /* Read the stack at 'off' and put the results into the register indicated by
4280  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4281  * spilled reg.
4282  *
4283  * 'dst_regno' can be -1, meaning that the read value is not going to a
4284  * register.
4285  *
4286  * The access is assumed to be within the current stack bounds.
4287  */
4288 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4289 				      /* func where src register points to */
4290 				      struct bpf_func_state *reg_state,
4291 				      int off, int size, int dst_regno)
4292 {
4293 	struct bpf_verifier_state *vstate = env->cur_state;
4294 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4295 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4296 	struct bpf_reg_state *reg;
4297 	u8 *stype, type;
4298 	int err;
4299 	int insn_flags = INSN_F_STACK_ACCESS;
4300 	int hist_spi = spi, hist_frame = reg_state->frameno;
4301 	struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi);
4302 
4303 	stype = ss->slot_type;
4304 	reg = &ss->spilled_ptr;
4305 
4306 	mark_stack_slot_scratched(env, spi);
4307 
4308 	/*
4309 	 * Refine the in-progress load record's origin to the source stack slot.
4310 	 */
4311 	if (dst_regno >= 0)
4312 		bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE);
4313 
4314 	if (bpf_is_spilled_reg(ss)) {
4315 		u8 spill_size = bpf_spill_size(ss);
4316 
4317 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4318 			if (reg->type != SCALAR_VALUE) {
4319 				verbose_linfo(env, env->insn_idx, "; ");
4320 				verbose(env, "invalid size of register fill\n");
4321 				return -EACCES;
4322 			}
4323 
4324 			if (size <= spill_size &&
4325 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4326 				if (dst_regno < 0)
4327 					return 0;
4328 
4329 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
4330 				    get_reg_width(reg) <= 32)
4331 					/* Ensure stack slot has an ID to build a relation
4332 					 * with the destination register on fill.
4333 					 */
4334 					assign_scalar_id_before_mov(env, reg);
4335 				state->regs[dst_regno] = *reg;
4336 
4337 				/* Break the relation on a narrowing fill.
4338 				 * coerce_reg_to_size will adjust the boundaries.
4339 				 */
4340 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4341 					clear_scalar_id(&state->regs[dst_regno]);
4342 			} else {
4343 				int spill_cnt = 0, zero_cnt = 0;
4344 
4345 				for (i = 0; i < size; i++) {
4346 					type = stype[(slot - i) % BPF_REG_SIZE];
4347 					if (type == STACK_SPILL) {
4348 						spill_cnt++;
4349 						continue;
4350 					}
4351 					if (type == STACK_MISC)
4352 						continue;
4353 					if (type == STACK_ZERO) {
4354 						zero_cnt++;
4355 						continue;
4356 					}
4357 					if (type == STACK_INVALID && env->allow_uninit_stack)
4358 						continue;
4359 					if (type == STACK_POISON) {
4360 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4361 							off, i, size);
4362 					} else {
4363 						verbose(env, "invalid read from stack off %d+%d size %d\n",
4364 							off, i, size);
4365 						bpf_diag_stack_read_invalid(env, off, i, size, type);
4366 					}
4367 					return -EACCES;
4368 				}
4369 
4370 				if (dst_regno < 0)
4371 					return 0;
4372 
4373 				if (spill_cnt == size &&
4374 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4375 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4376 					/* this IS register fill, so keep insn_flags */
4377 				} else if (zero_cnt == size) {
4378 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4379 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4380 					insn_flags = 0; /* not restoring original register state */
4381 				} else {
4382 					err = mark_reg_stack_read(env, reg_state, off, off + size,
4383 								  dst_regno);
4384 					if (err)
4385 						return err;
4386 					insn_flags = 0; /* not restoring original register state */
4387 				}
4388 			}
4389 		} else if (dst_regno >= 0) {
4390 			/* restore register state from stack */
4391 			if (env->bpf_capable)
4392 				/* Ensure stack slot has an ID to build a relation
4393 				 * with the destination register on fill.
4394 				 */
4395 				assign_scalar_id_before_mov(env, reg);
4396 			state->regs[dst_regno] = *reg;
4397 			/* mark reg as written since spilled pointer state likely
4398 			 * has its liveness marks cleared by is_state_visited()
4399 			 * which resets stack/reg liveness for state transitions
4400 			 */
4401 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4402 			/* If dst_regno==-1, the caller is asking us whether
4403 			 * it is acceptable to use this value as a SCALAR_VALUE
4404 			 * (e.g. for XADD).
4405 			 * We must not allow unprivileged callers to do that
4406 			 * with spilled pointers.
4407 			 */
4408 			verbose(env, "leaking pointer from stack off %d\n",
4409 				off);
4410 			return -EACCES;
4411 		}
4412 	} else {
4413 		for (i = 0; i < size; i++) {
4414 			type = stype[(slot - i) % BPF_REG_SIZE];
4415 			if (type == STACK_MISC)
4416 				continue;
4417 			if (type == STACK_ZERO)
4418 				continue;
4419 			if (type == STACK_INVALID && env->allow_uninit_stack)
4420 				continue;
4421 			if (type == STACK_POISON) {
4422 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
4423 					off, i, size);
4424 			} else {
4425 				verbose(env, "invalid read from stack off %d+%d size %d\n",
4426 					off, i, size);
4427 				bpf_diag_stack_read_invalid(env, off, i, size, type);
4428 			}
4429 			return -EACCES;
4430 		}
4431 		if (dst_regno >= 0) {
4432 			err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4433 			if (err)
4434 				return err;
4435 		}
4436 		insn_flags = 0; /* we are not restoring spilled register */
4437 	}
4438 	if (insn_flags)
4439 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4440 					    hist_spi, hist_frame, NULL, 0);
4441 	return 0;
4442 }
4443 
4444 enum bpf_access_src {
4445 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4446 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4447 };
4448 
4449 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4450 					 argno_t argno, int off, int access_size,
4451 					 bool zero_size_allowed,
4452 					 enum bpf_access_type type,
4453 					 struct bpf_call_arg_meta *meta);
4454 
4455 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4456 {
4457 	return cur_regs(env) + regno;
4458 }
4459 
4460 /* Read the stack at 'reg + off' and put the result into the register
4461  * 'dst_regno'.
4462  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
4463  * but not its variable offset.
4464  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4465  *
4466  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4467  * filling registers (i.e. reads of spilled register cannot be detected when
4468  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4469  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
4470  * offset; for a fixed offset check_stack_read_fixed_off should be used
4471  * instead.
4472  */
4473 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4474 				    argno_t ptr_argno, int off, int size, int dst_regno)
4475 {
4476 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
4477 	int err;
4478 	int min_off, max_off;
4479 
4480 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4481 	 */
4482 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
4483 					    false, BPF_READ, NULL);
4484 	if (err)
4485 		return err;
4486 
4487 	min_off = reg_smin(reg) + off;
4488 	max_off = reg_smax(reg) + off;
4489 	err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size,
4490 				  dst_regno);
4491 	if (err)
4492 		return err;
4493 	return 0;
4494 }
4495 
4496 /* check_stack_read dispatches to check_stack_read_fixed_off or
4497  * check_stack_read_var_off.
4498  *
4499  * The caller must ensure that the offset falls within the allocated stack
4500  * bounds.
4501  *
4502  * 'dst_regno' is a register which will receive the value from the stack. It
4503  * can be -1, meaning that the read value is not going to a register.
4504  */
4505 static int check_stack_read(struct bpf_verifier_env *env,
4506 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
4507 			    int dst_regno)
4508 {
4509 	struct bpf_func_state *state = bpf_func(env, reg);
4510 	int err;
4511 	/* Some accesses are only permitted with a static offset. */
4512 	bool var_off = !tnum_is_const(reg->var_off);
4513 
4514 	/* The offset is required to be static when reads don't go to a
4515 	 * register, in order to not leak pointers (see
4516 	 * check_stack_read_fixed_off).
4517 	 */
4518 	if (dst_regno < 0 && var_off) {
4519 		const char *reason;
4520 		char tn_buf[48];
4521 
4522 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4523 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4524 			tn_buf, off, size);
4525 		reason = bpf_diag_fmt(
4526 			env, "The instruction would access the stack through variable offset %s plus fixed offset %d and size %d. "
4527 			"This stack access requires a constant stack offset and a precise initialized range.",
4528 			tn_buf, off, size);
4529 		bpf_diag_memory(
4530 			env, env->insn_idx, "variable-offset stack access", reason,
4531 			"Use a fixed stack offset for the instruction, selecting the target stack slot on separate control-flow paths if necessary.");
4532 		return -EACCES;
4533 	}
4534 	/* Variable offset is prohibited for unprivileged mode for simplicity
4535 	 * since it requires corresponding support in Spectre masking for stack
4536 	 * ALU. See also retrieve_ptr_limit(). The check in
4537 	 * check_stack_access_for_ptr_arithmetic() called by
4538 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4539 	 * with variable offsets, therefore no check is required here. Further,
4540 	 * just checking it here would be insufficient as speculative stack
4541 	 * writes could still lead to unsafe speculative behaviour.
4542 	 */
4543 	if (!var_off) {
4544 		off += reg->var_off.value;
4545 		err = check_stack_read_fixed_off(env, state, off, size,
4546 						 dst_regno);
4547 	} else {
4548 		/* Variable offset stack reads need more conservative handling
4549 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4550 		 * branch.
4551 		 */
4552 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
4553 					       dst_regno);
4554 	}
4555 	return err;
4556 }
4557 
4558 /* check_stack_write dispatches to check_stack_write_fixed_off or
4559  * check_stack_write_var_off.
4560  *
4561  * 'reg' is the register used as a pointer into the stack.
4562  * 'value_regno' is the register whose value we're writing to the stack. It can
4563  * be -1, meaning that we're not writing from a register.
4564  *
4565  * The caller must ensure that the offset falls within the maximum stack size.
4566  */
4567 static int check_stack_write(struct bpf_verifier_env *env,
4568 			     struct bpf_reg_state *reg, int off, int size,
4569 			     int value_regno, int insn_idx)
4570 {
4571 	struct bpf_func_state *state = bpf_func(env, reg);
4572 	int err;
4573 
4574 	if (tnum_is_const(reg->var_off)) {
4575 		off += reg->var_off.value;
4576 		err = check_stack_write_fixed_off(env, state, off, size,
4577 						  value_regno, insn_idx);
4578 	} else {
4579 		/* Variable offset stack reads need more conservative handling
4580 		 * than fixed offset ones.
4581 		 */
4582 		err = check_stack_write_var_off(env, state,
4583 						reg, off, size,
4584 						value_regno, insn_idx);
4585 	}
4586 	return err;
4587 }
4588 
4589 /*
4590  * Write a value to the outgoing stack arg area.
4591  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4592  */
4593 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4594 				 int off, struct bpf_reg_state *value_reg)
4595 {
4596 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4597 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4598 	int spi = -off / BPF_REG_SIZE - 1;
4599 	struct bpf_reg_state *arg;
4600 	int err;
4601 
4602 	if (spi >= max_stack_arg_regs) {
4603 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4604 			off, max_stack_arg_regs);
4605 		return -EINVAL;
4606 	}
4607 
4608 	err = grow_stack_arg_slots(env, state, spi + 1);
4609 	if (err)
4610 		return err;
4611 
4612 	/* Track the max outgoing stack arg slot count. */
4613 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4614 		subprog->max_out_stack_arg_cnt = spi + 1;
4615 
4616 	arg = &state->stack_arg_regs[spi];
4617 	bpf_diag_mod_begin(env, arg, value_reg, BPF_DIAG_MOD_WRITE);
4618 
4619 	if (value_reg) {
4620 		state->stack_arg_regs[spi] = *value_reg;
4621 	} else {
4622 		/* BPF_ST: store immediate, treat as scalar */
4623 		arg->type = SCALAR_VALUE;
4624 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4625 	}
4626 	bpf_diag_mod_end(env);
4627 	state->no_stack_arg_load = true;
4628 	return bpf_push_jmp_history(env, env->cur_state,
4629 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4630 }
4631 
4632 /*
4633  * Read a value from the incoming stack arg area.
4634  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4635  */
4636 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4637 				int off, int dst_regno)
4638 {
4639 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4640 	struct bpf_verifier_state *vstate = env->cur_state;
4641 	int spi = off / BPF_REG_SIZE - 1;
4642 	struct bpf_func_state *caller, *cur;
4643 	struct bpf_reg_state *arg;
4644 
4645 	if (state->no_stack_arg_load) {
4646 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4647 		return -EINVAL;
4648 	}
4649 
4650 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4651 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4652 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4653 		return -EACCES;
4654 	}
4655 
4656 	caller = vstate->frame[vstate->curframe - 1];
4657 	arg = &caller->stack_arg_regs[spi];
4658 	cur = vstate->frame[vstate->curframe];
4659 	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
4660 	cur->regs[dst_regno] = *arg;
4661 	bpf_diag_mod_end(env);
4662 	return bpf_push_jmp_history(env, env->cur_state,
4663 				    INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0);
4664 }
4665 
4666 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4667 {
4668 	struct bpf_func_state *caller = cur_func(env);
4669 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4670 
4671 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4672 	return mark_chain_precision_batch(env, env->cur_state);
4673 }
4674 
4675 static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)
4676 {
4677 	int regno = reg_from_argno(argno);
4678 
4679 	if (regno >= 0)
4680 		return mark_chain_precision(env, regno);
4681 	return mark_stack_arg_precision(env, arg_idx_from_argno(argno));
4682 }
4683 
4684 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4685 				     int nargs, const char *callee_name, const struct btf *btf,
4686 				     const struct btf_param *args)
4687 {
4688 	int i, spi;
4689 
4690 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4691 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4692 		if (spi >= caller->out_stack_arg_cnt ||
4693 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4694 			const char *arg_name = NULL;
4695 
4696 			if (args && args[i].name_off)
4697 				arg_name = btf_name_by_offset(btf, args[i].name_off);
4698 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4699 				nargs, spi + 1);
4700 			bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi,
4701 						  callee_name, arg_name);
4702 			return -EFAULT;
4703 		}
4704 	}
4705 
4706 	return 0;
4707 }
4708 
4709 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4710 					      struct bpf_reg_state *regs, int arg)
4711 {
4712 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4713 		return &regs[arg + 1];
4714 
4715 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4716 }
4717 
4718 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4719 				 int off, int size, enum bpf_access_type type)
4720 {
4721 	struct bpf_map *map = reg->map_ptr;
4722 	u32 cap = bpf_map_flags_to_cap(map);
4723 
4724 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4725 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4726 			map->value_size, reg_smin(reg) + off, size);
4727 		return -EACCES;
4728 	}
4729 
4730 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4731 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4732 			map->value_size, reg_smin(reg) + off, size);
4733 		return -EACCES;
4734 	}
4735 
4736 	return 0;
4737 }
4738 
4739 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4740 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4741 			      int off, int size, u32 mem_size,
4742 			      bool zero_size_allowed)
4743 {
4744 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4745 
4746 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4747 		return 0;
4748 
4749 	switch (reg->type) {
4750 	case PTR_TO_MAP_KEY:
4751 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4752 			mem_size, off, size);
4753 		break;
4754 	case PTR_TO_MAP_VALUE:
4755 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4756 			mem_size, off, size);
4757 		break;
4758 	case PTR_TO_PACKET:
4759 	case PTR_TO_PACKET_META:
4760 	case PTR_TO_PACKET_END:
4761 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4762 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4763 		break;
4764 	case PTR_TO_CTX:
4765 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4766 			mem_size, off, size);
4767 		break;
4768 	case PTR_TO_MEM:
4769 	default:
4770 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4771 			mem_size, off, size);
4772 	}
4773 
4774 	return -EACCES;
4775 }
4776 
4777 /* check read/write into a memory region with possible variable offset */
4778 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4779 				   int off, int size, u32 mem_size,
4780 				   bool zero_size_allowed)
4781 {
4782 	const char *proof = "";
4783 	const char *start;
4784 	s64 max_start, max_end;
4785 	int err;
4786 
4787 	/* We may have adjusted the register pointing to memory region, so we
4788 	 * need to try adding each of min_value and max_value to off
4789 	 * to make sure our theoretical access will be safe.
4790 	 *
4791 	 * The minimum value is only important with signed
4792 	 * comparisons where we can't assume the floor of a
4793 	 * value is 0.  If we are using signed variables for our
4794 	 * index'es we need to make sure that whatever we use
4795 	 * will have a set floor within our range.
4796 	 */
4797 	if (reg_smin(reg) < 0 &&
4798 	    (reg_smin(reg) == S64_MIN ||
4799 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4800 	      reg_smin(reg) + off < 0)) {
4801 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4802 			reg_arg_name(env, argno));
4803 		err = -EACCES;
4804 		if (bpf_diag_enabled(env)) {
4805 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4806 			proof = bpf_diag_fmt(
4807 				env, "the minimal bound for a memory access is a negative value: %s",
4808 				start);
4809 		}
4810 		goto report_error;
4811 	}
4812 
4813 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4814 				 mem_size, zero_size_allowed);
4815 	if (err) {
4816 		verbose(env, "%s min value is outside of the allowed memory range\n",
4817 			reg_arg_name(env, argno));
4818 		if (bpf_diag_enabled(env)) {
4819 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4820 			proof = bpf_diag_fmt(
4821 				env, "the minimal bound for a memory access is %s and is outside of the object of size %u",
4822 				start, mem_size);
4823 		}
4824 		goto report_error;
4825 	}
4826 
4827 	/* If we haven't set a max value then we need to bail since we can't be
4828 	 * sure we won't do bad things.
4829 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4830 	 */
4831 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4832 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4833 			reg_arg_name(env, argno));
4834 		err = -EACCES;
4835 		if (bpf_diag_enabled(env))
4836 			proof = bpf_diag_fmt(
4837 				env, "the maximal bound for a memory access is %llu and exceeds maximum allowed offset of %u",
4838 				reg_umax(reg), BPF_MAX_VAR_OFF);
4839 		goto report_error;
4840 	}
4841 
4842 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4843 				 mem_size, zero_size_allowed);
4844 	if (err) {
4845 		verbose(env, "%s max value is outside of the allowed memory range\n",
4846 			reg_arg_name(env, argno));
4847 		if (bpf_diag_enabled(env)) {
4848 			max_start = (s64)reg_umax(reg) + off;
4849 			max_end = max_start + size;
4850 			proof = bpf_diag_fmt(
4851 				env, "the maximal bound for a memory access is %lld: start %lld + access_size %d, beyond object_size %u",
4852 				max_end, max_start, size, mem_size);
4853 		}
4854 		goto report_error;
4855 	}
4856 
4857 	return 0;
4858 
4859 report_error:
4860 	bpf_diag_mem_bounds(env, env->insn_idx, reg_from_argno(argno),
4861 			    reg_arg_name(env, argno), reg_type_str(env, reg->type), proof,
4862 			    off, size, mem_size, reg);
4863 	return err;
4864 }
4865 
4866 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4867 			       const struct bpf_reg_state *reg, argno_t argno,
4868 			       bool fixed_off_ok)
4869 {
4870 	/* Access to this pointer-typed register or passing it to a helper
4871 	 * is only allowed in its original, unmodified form.
4872 	 */
4873 
4874 	if (!tnum_is_const(reg->var_off)) {
4875 		char tn_buf[48];
4876 
4877 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4878 		verbose(env, "variable %s access var_off=%s disallowed\n",
4879 			reg_type_str(env, reg->type), tn_buf);
4880 		return -EACCES;
4881 	}
4882 
4883 	if (reg_smin(reg) < 0) {
4884 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4885 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4886 		return -EACCES;
4887 	}
4888 
4889 	if (!fixed_off_ok && reg->var_off.value != 0) {
4890 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4891 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4892 		bpf_diag_invalid_deref(env, env->insn_idx, reg_from_argno(argno),
4893 				       reg_arg_name(env, argno), reg,
4894 					      BPF_DIAG_DEREF_MODIFIED_PTR, reg->var_off.value);
4895 		return -EACCES;
4896 	}
4897 
4898 	return 0;
4899 }
4900 
4901 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4902 		             const struct bpf_reg_state *reg, int regno)
4903 {
4904 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4905 }
4906 
4907 static int map_kptr_match_type(struct bpf_verifier_env *env,
4908 			       struct btf_field *kptr_field,
4909 			       struct bpf_reg_state *reg, u32 regno)
4910 {
4911 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4912 	int perm_flags;
4913 	const char *reg_name = "";
4914 
4915 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4916 		goto bad_type;
4917 
4918 	if (btf_is_kernel(reg->btf)) {
4919 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4920 
4921 		/* Only unreferenced case accepts untrusted pointers */
4922 		if (kptr_field->type == BPF_KPTR_UNREF)
4923 			perm_flags |= PTR_UNTRUSTED;
4924 	} else {
4925 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4926 		if (kptr_field->type == BPF_KPTR_PERCPU)
4927 			perm_flags |= MEM_PERCPU;
4928 	}
4929 
4930 	if (type_flag(reg->type) & ~perm_flags)
4931 		goto bad_type;
4932 
4933 	/*
4934 	 * A BPF_KPTR_PERCPU field is read back as MEM_PERCPU, so the value
4935 	 * stored in it must carry the same flag.
4936 	 */
4937 	if ((kptr_field->type == BPF_KPTR_PERCPU) != !!(reg->type & MEM_PERCPU))
4938 		goto bad_type;
4939 
4940 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4941 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4942 
4943 	/* For ref_ptr case, release function check should ensure we get one
4944 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4945 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4946 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4947 	 * reg->id is not needed here.
4948 	 */
4949 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4950 		return -EACCES;
4951 
4952 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4953 	 * we also need to take into account the reg->var_off.
4954 	 *
4955 	 * We want to support cases like:
4956 	 *
4957 	 * struct foo {
4958 	 *         struct bar br;
4959 	 *         struct baz bz;
4960 	 * };
4961 	 *
4962 	 * struct foo *v;
4963 	 * v = func();	      // PTR_TO_BTF_ID
4964 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
4965 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
4966 	 *                    // first member type of struct after comparison fails
4967 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
4968 	 *                    // to match type
4969 	 *
4970 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
4971 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4972 	 * the struct to match type against first member of struct, i.e. reject
4973 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4974 	 * strict mode to true for type match.
4975 	 */
4976 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
4977 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4978 				  kptr_field->type != BPF_KPTR_UNREF,
4979 				  !type_is_alloc(reg->type)))
4980 		goto bad_type;
4981 	return 0;
4982 bad_type:
4983 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4984 		reg_type_str(env, reg->type), reg_name);
4985 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4986 	if (kptr_field->type == BPF_KPTR_UNREF)
4987 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4988 			targ_name);
4989 	else
4990 		verbose(env, "\n");
4991 	return -EINVAL;
4992 }
4993 
4994 static bool in_sleepable(struct bpf_verifier_env *env)
4995 {
4996 	return env->cur_state->in_sleepable;
4997 }
4998 
4999 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5000  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5001  */
5002 static bool in_rcu_cs(struct bpf_verifier_env *env)
5003 {
5004 	return env->cur_state->active_rcu_locks ||
5005 	       env->cur_state->active_preempt_locks ||
5006 	       env->cur_state->active_locks ||
5007 	       env->cur_state->active_irq_id ||
5008 	       !in_sleepable(env);
5009 }
5010 
5011 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5012 BTF_SET_START(rcu_protected_types)
5013 #ifdef CONFIG_NET
5014 BTF_ID(struct, prog_test_ref_kfunc)
5015 #endif
5016 #ifdef CONFIG_CGROUPS
5017 BTF_ID(struct, cgroup)
5018 #endif
5019 #ifdef CONFIG_BPF_JIT
5020 BTF_ID(struct, bpf_cpumask)
5021 #endif
5022 BTF_ID(struct, task_struct)
5023 #ifdef CONFIG_BPF_CRYPTO
5024 BTF_ID(struct, bpf_crypto_ctx)
5025 #endif
5026 #ifdef CONFIG_INET
5027 BTF_ID(struct, bpf_ksock)
5028 #endif
5029 BTF_SET_END(rcu_protected_types)
5030 
5031 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5032 {
5033 	if (!btf_is_kernel(btf))
5034 		return true;
5035 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5036 }
5037 
5038 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5039 {
5040 	struct btf_struct_meta *meta;
5041 
5042 	if (btf_is_kernel(kptr_field->kptr.btf))
5043 		return NULL;
5044 
5045 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5046 				    kptr_field->kptr.btf_id);
5047 
5048 	return meta ? meta->record : NULL;
5049 }
5050 
5051 static bool rcu_safe_kptr(const struct btf_field *field)
5052 {
5053 	const struct btf_field_kptr *kptr = &field->kptr;
5054 
5055 	return field->type == BPF_KPTR_PERCPU ||
5056 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5057 }
5058 
5059 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5060 {
5061 	struct btf_record *rec;
5062 	u32 ret;
5063 
5064 	ret = PTR_MAYBE_NULL;
5065 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5066 		ret |= MEM_RCU;
5067 		if (kptr_field->type == BPF_KPTR_PERCPU)
5068 			ret |= MEM_PERCPU;
5069 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5070 			ret |= MEM_ALLOC;
5071 
5072 		rec = kptr_pointee_btf_record(kptr_field);
5073 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5074 			ret |= NON_OWN_REF;
5075 	} else {
5076 		ret |= PTR_UNTRUSTED;
5077 	}
5078 
5079 	return ret;
5080 }
5081 
5082 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5083 			    struct btf_field *field)
5084 {
5085 	struct bpf_reg_state *reg;
5086 	const struct btf_type *t;
5087 
5088 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5089 	mark_reg_known_zero(env, cur_regs(env), regno);
5090 	reg = reg_state(env, regno);
5091 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5092 	reg->mem_size = t->size;
5093 	reg->id = ++env->id_gen;
5094 
5095 	return 0;
5096 }
5097 
5098 static int check_map_kptr_access(struct bpf_verifier_env *env,
5099 				 int value_regno, int insn_idx,
5100 				 struct btf_field *kptr_field)
5101 {
5102 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5103 	int class = BPF_CLASS(insn->code);
5104 	struct bpf_reg_state *val_reg;
5105 	int ret;
5106 
5107 	/* Things we already checked for in check_map_access and caller:
5108 	 *  - Reject cases where variable offset may touch kptr
5109 	 *  - size of access (must be BPF_DW)
5110 	 *  - tnum_is_const(reg->var_off)
5111 	 *  - kptr_field->offset == off + reg->var_off.value
5112 	 */
5113 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5114 	if (BPF_MODE(insn->code) != BPF_MEM) {
5115 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5116 		return -EACCES;
5117 	}
5118 
5119 	/* We only allow loading referenced kptr, since it will be marked as
5120 	 * untrusted, similar to unreferenced kptr.
5121 	 */
5122 	if (class != BPF_LDX &&
5123 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5124 		verbose(env, "store to referenced kptr disallowed\n");
5125 		return -EACCES;
5126 	}
5127 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5128 		verbose(env, "store to uptr disallowed\n");
5129 		return -EACCES;
5130 	}
5131 
5132 	if (class == BPF_LDX) {
5133 		if (kptr_field->type == BPF_UPTR)
5134 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5135 
5136 		/* We can simply mark the value_regno receiving the pointer
5137 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5138 		 */
5139 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5140 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5141 				      btf_ld_kptr_type(env, kptr_field));
5142 		if (ret < 0)
5143 			return ret;
5144 	} else if (class == BPF_STX) {
5145 		val_reg = reg_state(env, value_regno);
5146 		if (bpf_register_is_null(val_reg)) {
5147 			/*
5148 			 * This store is valid only because the scalar is known to be
5149 			 * zero. Mark it precise so another scalar cannot be pruned
5150 			 * against this state.
5151 			 */
5152 			return mark_chain_precision(env, value_regno);
5153 		}
5154 		if (map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5155 			return -EACCES;
5156 	} else if (class == BPF_ST) {
5157 		if (insn->imm) {
5158 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5159 				kptr_field->offset);
5160 			return -EACCES;
5161 		}
5162 	} else {
5163 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5164 		return -EACCES;
5165 	}
5166 	return 0;
5167 }
5168 
5169 /*
5170  * Return the size of the memory region accessible from a pointer to map value.
5171  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
5172  */
5173 static u32 map_mem_size(const struct bpf_map *map)
5174 {
5175 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5176 		return map->max_entries * sizeof(long);
5177 
5178 	return map->value_size;
5179 }
5180 
5181 /* check read/write into a map element with possible variable offset */
5182 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
5183 			    int off, int size, bool zero_size_allowed,
5184 			    enum bpf_access_src src)
5185 {
5186 	struct bpf_map *map = reg->map_ptr;
5187 	u32 mem_size = map_mem_size(map);
5188 	struct btf_record *rec;
5189 	int err, i;
5190 
5191 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
5192 	if (err)
5193 		return err;
5194 
5195 	if (IS_ERR_OR_NULL(map->record))
5196 		return 0;
5197 	rec = map->record;
5198 	for (i = 0; i < rec->cnt; i++) {
5199 		struct btf_field *field = &rec->fields[i];
5200 		u32 p = field->offset;
5201 
5202 		/* If any part of a field  can be touched by load/store, reject
5203 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5204 		 * it is sufficient to check x1 < y2 && y1 < x2.
5205 		 */
5206 		if (reg_smin(reg) + off < p + field->size &&
5207 		    p < reg_umax(reg) + off + size) {
5208 			switch (field->type) {
5209 			case BPF_KPTR_UNREF:
5210 			case BPF_KPTR_REF:
5211 			case BPF_KPTR_PERCPU:
5212 			case BPF_UPTR:
5213 				if (src != ACCESS_DIRECT) {
5214 					verbose(env, "%s cannot be accessed indirectly by helper\n",
5215 						btf_field_type_name(field->type));
5216 					return -EACCES;
5217 				}
5218 				if (!tnum_is_const(reg->var_off)) {
5219 					verbose(env, "%s access cannot have variable offset\n",
5220 						btf_field_type_name(field->type));
5221 					return -EACCES;
5222 				}
5223 				if (p != off + reg->var_off.value) {
5224 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
5225 						btf_field_type_name(field->type),
5226 						p, off + reg->var_off.value);
5227 					return -EACCES;
5228 				}
5229 				if (size != bpf_size_to_bytes(BPF_DW)) {
5230 					verbose(env, "%s access size must be BPF_DW\n",
5231 						btf_field_type_name(field->type));
5232 					return -EACCES;
5233 				}
5234 				break;
5235 			default:
5236 				verbose(env, "%s cannot be accessed directly by load/store\n",
5237 					btf_field_type_name(field->type));
5238 				return -EACCES;
5239 			}
5240 		}
5241 	}
5242 	return 0;
5243 }
5244 
5245 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5246 			       const struct bpf_call_arg_meta *meta,
5247 			       enum bpf_access_type t)
5248 {
5249 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5250 
5251 	switch (prog_type) {
5252 	/* Program types only with direct read access go here! */
5253 	case BPF_PROG_TYPE_LWT_IN:
5254 	case BPF_PROG_TYPE_LWT_OUT:
5255 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5256 	case BPF_PROG_TYPE_SK_REUSEPORT:
5257 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5258 	case BPF_PROG_TYPE_CGROUP_SKB:
5259 		if (t == BPF_WRITE)
5260 			return false;
5261 		fallthrough;
5262 
5263 	/* Program types with direct read + write access go here! */
5264 	case BPF_PROG_TYPE_SCHED_CLS:
5265 	case BPF_PROG_TYPE_SCHED_ACT:
5266 	case BPF_PROG_TYPE_XDP:
5267 	case BPF_PROG_TYPE_LWT_XMIT:
5268 	case BPF_PROG_TYPE_SK_SKB:
5269 	case BPF_PROG_TYPE_SK_MSG:
5270 		if (meta && !meta->btf && meta->func_id)
5271 			return meta->fn->pkt_access;
5272 
5273 		if (t == BPF_WRITE)
5274 			env->seen_direct_write = true;
5275 		return true;
5276 
5277 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5278 		if (t == BPF_WRITE)
5279 			env->seen_direct_write = true;
5280 
5281 		return true;
5282 
5283 	default:
5284 		return false;
5285 	}
5286 }
5287 
5288 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
5289 			       int size, bool zero_size_allowed)
5290 {
5291 	int err;
5292 
5293 	if (reg->range < 0) {
5294 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
5295 		return -EINVAL;
5296 	}
5297 
5298 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
5299 	if (err)
5300 		return err;
5301 
5302 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5303 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
5304 	 * otherwise find_good_pkt_pointers would have refused to set range info
5305 	 * that __check_mem_access would have rejected this pkt access.
5306 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
5307 	 */
5308 	env->prog->aux->max_pkt_offset =
5309 		max_t(u32, env->prog->aux->max_pkt_offset,
5310 		      off + reg_umax(reg) + size - 1);
5311 
5312 	return 0;
5313 }
5314 
5315 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
5316 {
5317 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
5318 }
5319 
5320 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5321 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5322 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
5323 {
5324 	if (env->ops->is_valid_access &&
5325 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
5326 		/* A non zero info.ctx_field_size indicates that this field is a
5327 		 * candidate for later verifier transformation to load the whole
5328 		 * field and then apply a mask when accessed with a narrower
5329 		 * access than actual ctx access size. A zero info.ctx_field_size
5330 		 * will only allow for whole field access and rejects any other
5331 		 * type of narrower access.
5332 		 */
5333 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
5334 			if (info->ref_id &&
5335 			    !find_reference_state(env->cur_state, info->ref_id)) {
5336 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
5337 					off);
5338 				return -EACCES;
5339 			}
5340 		} else {
5341 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
5342 		}
5343 		/* remember the offset of last byte accessed in ctx */
5344 		if (env->prog->aux->max_ctx_offset < off + size)
5345 			env->prog->aux->max_ctx_offset = off + size;
5346 		return 0;
5347 	}
5348 
5349 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5350 	return -EACCES;
5351 }
5352 
5353 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
5354 			    int off, int access_size, enum bpf_access_type t,
5355 			    struct bpf_insn_access_aux *info)
5356 {
5357 	/*
5358 	 * Program types that don't rewrite ctx accesses can safely
5359 	 * dereference ctx pointers with fixed offsets.
5360 	 */
5361 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
5362 	bool fixed_off_ok = !env->ops->convert_ctx_access;
5363 	int err;
5364 
5365 	if (var_off_ok)
5366 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
5367 	else
5368 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
5369 	if (err)
5370 		return err;
5371 	off += reg_umax(reg);
5372 
5373 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
5374 	if (err)
5375 		verbose_linfo(env, insn_idx, "; ");
5376 	return err;
5377 }
5378 
5379 static int check_flow_keys_access(struct bpf_verifier_env *env,
5380 				  struct bpf_reg_state *reg, argno_t argno,
5381 				  int off, int size)
5382 {
5383 	/* Only a constant offset is allowed here; fold it into off. */
5384 	if (!tnum_is_const(reg->var_off)) {
5385 		char tn_buf[48];
5386 
5387 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5388 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
5389 			reg_arg_name(env, argno), off, tn_buf);
5390 		return -EACCES;
5391 	}
5392 	off += reg->var_off.value;
5393 
5394 	if (size < 0 || off < 0 ||
5395 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5396 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5397 			off, size);
5398 		return -EACCES;
5399 	}
5400 	return 0;
5401 }
5402 
5403 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5404 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
5405 			     enum bpf_access_type t)
5406 {
5407 	struct bpf_insn_access_aux info = {};
5408 	bool valid;
5409 
5410 	if (reg_smin(reg) < 0) {
5411 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5412 			reg_arg_name(env, argno));
5413 		return -EACCES;
5414 	}
5415 
5416 	switch (reg->type) {
5417 	case PTR_TO_SOCK_COMMON:
5418 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5419 		break;
5420 	case PTR_TO_SOCKET:
5421 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5422 		break;
5423 	case PTR_TO_TCP_SOCK:
5424 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5425 		break;
5426 	case PTR_TO_XDP_SOCK:
5427 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5428 		break;
5429 	default:
5430 		valid = false;
5431 	}
5432 
5433 	if (valid) {
5434 		env->insn_aux_data[insn_idx].ctx_field_size =
5435 			info.ctx_field_size;
5436 		return 0;
5437 	}
5438 
5439 	verbose(env, "%s invalid %s access off=%d size=%d\n",
5440 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
5441 
5442 	return -EACCES;
5443 }
5444 
5445 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5446 {
5447 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5448 }
5449 
5450 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5451 {
5452 	const struct bpf_reg_state *reg = reg_state(env, regno);
5453 
5454 	return reg->type == PTR_TO_CTX;
5455 }
5456 
5457 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5458 {
5459 	const struct bpf_reg_state *reg = reg_state(env, regno);
5460 
5461 	return type_is_sk_pointer(reg->type);
5462 }
5463 
5464 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5465 {
5466 	const struct bpf_reg_state *reg = reg_state(env, regno);
5467 
5468 	return type_is_pkt_pointer(reg->type);
5469 }
5470 
5471 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5472 {
5473 	const struct bpf_reg_state *reg = reg_state(env, regno);
5474 
5475 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5476 	return reg->type == PTR_TO_FLOW_KEYS;
5477 }
5478 
5479 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5480 {
5481 	const struct bpf_reg_state *reg = reg_state(env, regno);
5482 
5483 	return reg->type == PTR_TO_ARENA;
5484 }
5485 
5486 /*
5487  * There are no address spaces in Rust, addresses of arena are plain numbers.
5488  * When the program is loaded with BPF_F_ARENA_SCALAR and has an arena a load or
5489  * a store through a number is an access to arena at the low 32 bits of it,
5490  * like the access through PTR_TO_ARENA is. The register stays a number.
5491  */
5492 static bool is_arena_scalar(struct bpf_verifier_env *env, int regno)
5493 {
5494 	const struct bpf_reg_state *reg = reg_state(env, regno);
5495 
5496 	return reg->type == SCALAR_VALUE && env->arena_scalar && env->prog->aux->arena;
5497 }
5498 
5499 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno,
5500 			       struct bpf_insn *insn)
5501 {
5502 	const struct bpf_reg_state *reg = reg_state(env, regno);
5503 
5504 	/*
5505 	 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the
5506 	 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load
5507 	 * with no exception table entry, so a fault (e.g. NULL deref) crashes
5508 	 * the kernel instead of being handled. Reject the source pointer types
5509 	 * that would have needed that protection, the remaining ones stay
5510 	 * allowed.
5511 	 */
5512 	return insn->imm == BPF_LOAD_ACQ && bpf_may_fault_on_deref(reg->type);
5513 }
5514 
5515 /* Return false if @regno contains a pointer whose type isn't supported for
5516  * atomic instruction @insn.
5517  */
5518 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
5519 			       struct bpf_insn *insn)
5520 {
5521 	if (is_ctx_reg(env, regno))
5522 		return false;
5523 	if (is_pkt_reg(env, regno))
5524 		return false;
5525 	if (is_flow_key_reg(env, regno))
5526 		return false;
5527 	if (is_sk_reg(env, regno))
5528 		return false;
5529 	if (is_arena_reg(env, regno) || is_arena_scalar(env, regno))
5530 		return bpf_jit_supports_insn(insn, true);
5531 	if (is_load_acq_unsafe(env, regno, insn))
5532 		return false;
5533 	return true;
5534 }
5535 
5536 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5537 #ifdef CONFIG_NET
5538 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5539 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5540 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5541 #endif
5542 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5543 };
5544 
5545 static bool is_trusted_reg_type(struct bpf_verifier_env *env,
5546 				const struct bpf_reg_state *reg,
5547 				enum bpf_reg_type type)
5548 {
5549 	/* A referenced register is always trusted. */
5550 	if (reg_is_referenced(env, reg))
5551 		return true;
5552 
5553 	/* Types listed in the reg2btf_ids are always trusted */
5554 	if (reg2btf_ids[base_type(type)] &&
5555 	    !bpf_type_has_unsafe_modifiers(type))
5556 		return true;
5557 
5558 	/* If a register is not referenced, it is trusted if it has the
5559 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5560 	 * other type modifiers may be safe, but we elect to take an opt-in
5561 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5562 	 * not.
5563 	 *
5564 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5565 	 * for whether a register is trusted.
5566 	 */
5567 	return type_flag(type) & BPF_REG_TRUSTED_MODIFIERS &&
5568 	       !bpf_type_has_unsafe_modifiers(type);
5569 }
5570 
5571 static bool is_trusted_reg(struct bpf_verifier_env *env,
5572 			   const struct bpf_reg_state *reg)
5573 {
5574 	return is_trusted_reg_type(env, reg, reg->type);
5575 }
5576 
5577 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5578 {
5579 	return reg->type & MEM_RCU;
5580 }
5581 
5582 static void clear_trusted_flags(enum bpf_type_flag *flag)
5583 {
5584 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5585 }
5586 
5587 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5588 				   const struct bpf_reg_state *reg,
5589 				   int off, int size, bool strict)
5590 {
5591 	struct tnum reg_off;
5592 	int ip_align;
5593 
5594 	/* Byte size accesses are always allowed. */
5595 	if (!strict || size == 1)
5596 		return 0;
5597 
5598 	/* For platforms that do not have a Kconfig enabling
5599 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5600 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5601 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5602 	 * to this code only in strict mode where we want to emulate
5603 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5604 	 * unconditional IP align value of '2'.
5605 	 */
5606 	ip_align = 2;
5607 
5608 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
5609 	if (!tnum_is_aligned(reg_off, size)) {
5610 		char tn_buf[48];
5611 
5612 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5613 		verbose(env,
5614 			"misaligned packet access off %d+%s+%d size %d\n",
5615 			ip_align, tn_buf, off, size);
5616 		return -EACCES;
5617 	}
5618 
5619 	return 0;
5620 }
5621 
5622 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5623 				       const struct bpf_reg_state *reg,
5624 				       const char *pointer_desc,
5625 				       int off, int size, bool strict)
5626 {
5627 	struct tnum reg_off;
5628 
5629 	/* Byte size accesses are always allowed. */
5630 	if (!strict || size == 1)
5631 		return 0;
5632 
5633 	reg_off = tnum_add(reg->var_off, tnum_const(off));
5634 	if (!tnum_is_aligned(reg_off, size)) {
5635 		char tn_buf[48];
5636 
5637 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5638 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
5639 			pointer_desc, tn_buf, off, size);
5640 		return -EACCES;
5641 	}
5642 
5643 	return 0;
5644 }
5645 
5646 static int check_ptr_alignment(struct bpf_verifier_env *env,
5647 			       const struct bpf_reg_state *reg, int off,
5648 			       int size, bool strict_alignment_once)
5649 {
5650 	bool strict = env->strict_alignment || strict_alignment_once;
5651 	const char *pointer_desc = "";
5652 
5653 	switch (reg->type) {
5654 	case PTR_TO_PACKET:
5655 	case PTR_TO_PACKET_META:
5656 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5657 		 * right in front, treat it the very same way.
5658 		 */
5659 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5660 	case PTR_TO_FLOW_KEYS:
5661 		pointer_desc = "flow keys ";
5662 		break;
5663 	case PTR_TO_MAP_KEY:
5664 		pointer_desc = "key ";
5665 		break;
5666 	case PTR_TO_MAP_VALUE:
5667 		pointer_desc = "value ";
5668 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5669 			strict = true;
5670 		break;
5671 	case PTR_TO_CTX:
5672 		pointer_desc = "context ";
5673 		break;
5674 	case PTR_TO_STACK:
5675 		pointer_desc = "stack ";
5676 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5677 		 * and check_stack_read_fixed_off() relies on stack accesses being
5678 		 * aligned.
5679 		 */
5680 		strict = true;
5681 		break;
5682 	case PTR_TO_SOCKET:
5683 		pointer_desc = "sock ";
5684 		break;
5685 	case PTR_TO_SOCK_COMMON:
5686 		pointer_desc = "sock_common ";
5687 		break;
5688 	case PTR_TO_TCP_SOCK:
5689 		pointer_desc = "tcp_sock ";
5690 		break;
5691 	case PTR_TO_XDP_SOCK:
5692 		pointer_desc = "xdp_sock ";
5693 		break;
5694 	case PTR_TO_ARENA:
5695 		return 0;
5696 	default:
5697 		break;
5698 	}
5699 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5700 					   strict);
5701 }
5702 
5703 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5704 {
5705 	if (!bpf_jit_supports_private_stack())
5706 		return NO_PRIV_STACK;
5707 
5708 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5709 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5710 	 * explicitly.
5711 	 */
5712 	switch (prog->type) {
5713 	case BPF_PROG_TYPE_KPROBE:
5714 	case BPF_PROG_TYPE_TRACEPOINT:
5715 	case BPF_PROG_TYPE_PERF_EVENT:
5716 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5717 		return PRIV_STACK_ADAPTIVE;
5718 	case BPF_PROG_TYPE_TRACING:
5719 	case BPF_PROG_TYPE_LSM:
5720 	case BPF_PROG_TYPE_STRUCT_OPS:
5721 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5722 			return PRIV_STACK_ADAPTIVE;
5723 		fallthrough;
5724 	default:
5725 		break;
5726 	}
5727 
5728 	return NO_PRIV_STACK;
5729 }
5730 
5731 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5732 {
5733 	if (env->prog->jit_requested)
5734 		return round_up(stack_depth, 16);
5735 
5736 	/* round up to 32-bytes, since this is granularity
5737 	 * of interpreter stack size
5738 	 */
5739 	return round_up(max_t(u32, stack_depth, 1), 32);
5740 }
5741 
5742 /* temporary state used for call frame depth calculation */
5743 struct bpf_subprog_call_depth_info {
5744 	int ret_insn; /* caller instruction where we return to. */
5745 	int caller; /* caller subprogram idx */
5746 	int frame; /* # of consecutive static call stack frames on top of stack */
5747 	int callx_insn; /* callx instruction whose callees are being walked */
5748 	int callx_next; /* next callee of callx_insn to walk */
5749 	bool via_callx; /* the subprogram is entered via callx */
5750 };
5751 
5752 /* starting from main bpf function walk all instructions of the function
5753  * and recursively walk all callees that given function can call.
5754  * Ignore jump and exit insns.
5755  */
5756 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5757 					 struct bpf_subprog_call_depth_info *dinfo,
5758 					 bool priv_stack_supported)
5759 {
5760 	struct bpf_subprog_info *subprog = env->subprog_info;
5761 	struct bpf_insn *insn = env->prog->insnsi;
5762 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5763 	bool tail_call_reachable = false;
5764 	int total;
5765 	int tmp;
5766 
5767 	/* no caller idx */
5768 	dinfo[idx].caller = -1;
5769 	dinfo[idx].via_callx = false;
5770 
5771 	i = subprog[idx].start;
5772 	if (!priv_stack_supported)
5773 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5774 process_func:
5775 	dinfo[idx].callx_insn = -1;
5776 	if (subprog[idx].has_ld_abs) {
5777 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5778 			if (subprog[tmp].is_cb) {
5779 				verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
5780 				return -EINVAL;
5781 			}
5782 		}
5783 	}
5784 
5785 	/* protect against potential stack overflow that might happen when
5786 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5787 	 * depth for such case down to 256 so that the worst case scenario
5788 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5789 	 * 8k).
5790 	 *
5791 	 * To get the idea what might happen, see an example:
5792 	 * func1 -> sub rsp, 128
5793 	 *  subfunc1 -> sub rsp, 256
5794 	 *  tailcall1 -> add rsp, 256
5795 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5796 	 *   subfunc2 -> sub rsp, 64
5797 	 *   subfunc22 -> sub rsp, 128
5798 	 *   tailcall2 -> add rsp, 128
5799 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5800 	 *
5801 	 * tailcall will unwind the current stack frame but it will not get rid
5802 	 * of caller's stack as shown on the example above.
5803 	 */
5804 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5805 		verbose(env,
5806 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5807 			depth);
5808 		return -EACCES;
5809 	}
5810 
5811 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5812 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5813 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5814 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5815 	} else if (priv_stack_supported) {
5816 		/* Request private stack support only if the subprog stack
5817 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5818 		 * avoid jit penalty if the stack usage is small.
5819 		 */
5820 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5821 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5822 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5823 	}
5824 
5825 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5826 		if (subprog_depth > env->max_stack_depth)
5827 			env->max_stack_depth = subprog_depth;
5828 		if (subprog_depth > env->stack_limit) {
5829 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5830 				idx, subprog_depth);
5831 			return -EACCES;
5832 		}
5833 	} else {
5834 		depth += subprog_depth;
5835 		if (depth > env->max_stack_depth)
5836 			env->max_stack_depth = depth;
5837 		if (depth > env->stack_limit) {
5838 			total = 0;
5839 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5840 				total++;
5841 
5842 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5843 				total, depth);
5844 			return -EACCES;
5845 		}
5846 	}
5847 continue_func:
5848 	subprog_end = subprog[idx + 1].start;
5849 	for (; i < subprog_end; i++) {
5850 		int next_insn, sidx;
5851 
5852 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off &&
5853 		    bpf_is_throw_kfunc(insn + i)) {
5854 			bool err = false;
5855 
5856 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5857 				if (subprog[tmp].is_cb) {
5858 					err = true;
5859 					break;
5860 				}
5861 			}
5862 			if (!err)
5863 				continue;
5864 			verbose(env,
5865 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5866 				i, idx);
5867 			return -EINVAL;
5868 		}
5869 
5870 		if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i)) {
5871 			/*
5872 			 * Walk the callees and the callbacks recorded by
5873 			 * the main verification pass one by one, returning to
5874 			 * this insn after each.
5875 			 */
5876 			if (dinfo[idx].callx_insn != i) {
5877 				dinfo[idx].callx_insn = i;
5878 				dinfo[idx].callx_next = 0;
5879 			}
5880 			sidx = next_callx_callee(env, idx, dinfo[idx].callx_next);
5881 			if (sidx < 0)
5882 				continue;
5883 			dinfo[idx].callx_next = sidx + 1;
5884 			dinfo[idx].ret_insn = i;
5885 			next_insn = subprog[sidx].start;
5886 		} else if (bpf_pseudo_call(insn + i) || bpf_pseudo_func(insn + i)) {
5887 			/* find the callee */
5888 			next_insn = i + insn[i].imm + 1;
5889 			sidx = bpf_find_subprog(env, next_insn);
5890 			if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5891 				return -EFAULT;
5892 			if (subprog[sidx].is_async_cb) {
5893 				/* async callbacks don't increase bpf prog stack size unless called directly */
5894 				if (!bpf_pseudo_call(insn + i))
5895 					continue;
5896 				if (subprog[sidx].is_exception_cb) {
5897 					verbose(env, "insn %d cannot call exception cb directly", i);
5898 					return -EINVAL;
5899 				}
5900 			}
5901 			/* remember insn to return to */
5902 			dinfo[idx].ret_insn = i + 1;
5903 		} else {
5904 			continue;
5905 		}
5906 
5907 		/*
5908 		 * sort_subprogs_topo() tolerates cycles in the call graph that
5909 		 * go through the address of a function being taken, since it
5910 		 * doesn't know what it is taken for. Such cycle is a recursion
5911 		 * unless it's an async callback, which are skipped above.
5912 		 * The main verification pass limits the depth of the recursion,
5913 		 * but it doesn't follow calls of global functions.
5914 		 */
5915 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5916 			if (tmp != sidx)
5917 				continue;
5918 			verbose(env, "recursive call from %s() to %s()\n",
5919 				bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx));
5920 			bpf_diag_program_structure(
5921 				env, i, "recursive subprogram call",
5922 				"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
5923 				"This call or callback would make the subprogram call graph recursive. "
5924 				"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
5925 			return -EINVAL;
5926 		}
5927 
5928 		/* store caller info for after we return from callee */
5929 		dinfo[idx].frame = frame;
5930 
5931 		/* push caller idx into callee's dinfo */
5932 		dinfo[sidx].caller = idx;
5933 		dinfo[sidx].via_callx = bpf_is_callx(insn + i);
5934 
5935 		i = next_insn;
5936 
5937 		idx = sidx;
5938 		if (!priv_stack_supported)
5939 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5940 
5941 		/* sync tail_call_reachable with callee state on entry */
5942 		tail_call_reachable = subprog[idx].has_tail_call;
5943 
5944 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5945 		if (frame >= MAX_CALL_FRAMES) {
5946 			verbose(env, "the call stack of %d frames is too deep !\n",
5947 				frame);
5948 			return -E2BIG;
5949 		}
5950 		goto process_func;
5951 	}
5952 	/* if tail call got detected across bpf2bpf calls then mark each of the
5953 	 * currently present subprog frames as tail call reachable subprogs;
5954 	 * this info will be utilized by JIT so that we will be preserving the
5955 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5956 	 */
5957 	if (tail_call_reachable) {
5958 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5959 			if (subprog[tmp].is_cb) {
5960 				verbose(env, "cannot tail call within callback\n");
5961 				return -EINVAL;
5962 			}
5963 			if (subprog[tmp].stack_arg_cnt) {
5964 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5965 				return -EINVAL;
5966 			}
5967 			/*
5968 			 * JITs pass tail call counter in a register that is
5969 			 * not available when the callee is called via callx.
5970 			 */
5971 			if (dinfo[tmp].via_callx) {
5972 				verbose(env, "tail_calls are not allowed in functions called via callx\n");
5973 				return -EINVAL;
5974 			}
5975 			subprog[tmp].tail_call_reachable = true;
5976 		}
5977 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
5978 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
5979 		return -EINVAL;
5980 	}
5981 
5982 	if (subprog[0].tail_call_reachable)
5983 		env->prog->aux->tail_call_reachable = true;
5984 
5985 	/* end of for() loop means the last insn of the 'subprog'
5986 	 * was reached. Doesn't matter whether it was JA or EXIT
5987 	 */
5988 	if (frame == 0 && dinfo[idx].caller < 0)
5989 		return 0;
5990 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
5991 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5992 
5993 	/* pop caller idx from callee */
5994 	idx = dinfo[idx].caller;
5995 
5996 	/* retrieve caller state from its frame */
5997 	frame = dinfo[idx].frame;
5998 	i = dinfo[idx].ret_insn;
5999 
6000 	/* reset tail_call_reachable to the parent's actual state */
6001 	tail_call_reachable = subprog[idx].tail_call_reachable;
6002 
6003 	goto continue_func;
6004 }
6005 
6006 static int check_max_stack_depth(struct bpf_verifier_env *env)
6007 {
6008 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6009 	struct bpf_subprog_call_depth_info *dinfo;
6010 	struct bpf_subprog_info *si = env->subprog_info;
6011 	bool priv_stack_supported;
6012 	int ret;
6013 
6014 	dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
6015 	if (!dinfo)
6016 		return -ENOMEM;
6017 
6018 	for (int i = 0; i < env->subprog_cnt; i++) {
6019 		if (si[i].has_tail_call) {
6020 			priv_stack_mode = NO_PRIV_STACK;
6021 			break;
6022 		}
6023 	}
6024 
6025 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6026 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6027 
6028 	/* All async_cb subprogs use normal kernel stack. If a particular
6029 	 * subprog appears in both main prog and async_cb subtree, that
6030 	 * subprog will use normal kernel stack to avoid potential nesting.
6031 	 * The reverse subprog traversal ensures when main prog subtree is
6032 	 * checked, the subprogs appearing in async_cb subtrees are already
6033 	 * marked as using normal kernel stack, so stack size checking can
6034 	 * be done properly.
6035 	 */
6036 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6037 		if (!i || si[i].is_async_cb) {
6038 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6039 			ret = check_max_stack_depth_subprog(env, i, dinfo,
6040 					priv_stack_supported);
6041 			if (ret < 0) {
6042 				kvfree(dinfo);
6043 				return ret;
6044 			}
6045 		}
6046 	}
6047 
6048 	for (int i = 0; i < env->subprog_cnt; i++) {
6049 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6050 			env->prog->aux->jits_use_priv_stack = true;
6051 			break;
6052 		}
6053 	}
6054 
6055 	kvfree(dinfo);
6056 
6057 	return 0;
6058 }
6059 
6060 static int __check_buffer_access(struct bpf_verifier_env *env,
6061 				 const char *buf_info,
6062 				 const struct bpf_reg_state *reg,
6063 				 argno_t argno, int off, int size,
6064 				 u32 *access_end)
6065 {
6066 	s64 start;
6067 
6068 	if (!tnum_is_const(reg->var_off)) {
6069 		char tn_buf[48];
6070 
6071 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6072 		verbose(env,
6073 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
6074 			reg_arg_name(env, argno), off, tn_buf);
6075 		return -EACCES;
6076 	}
6077 
6078 	start = (s64)reg->var_off.value + off;
6079 	if (start < 0) {
6080 		verbose(env,
6081 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
6082 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
6083 		return -EACCES;
6084 	}
6085 
6086 	*access_end = start + size;
6087 	return 0;
6088 }
6089 
6090 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6091 				  const struct bpf_reg_state *reg,
6092 				  argno_t argno, int off, int size)
6093 {
6094 	u32 access_end;
6095 	int err;
6096 
6097 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
6098 	if (err)
6099 		return err;
6100 
6101 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
6102 
6103 	return 0;
6104 }
6105 
6106 static int check_buffer_access(struct bpf_verifier_env *env,
6107 			       const struct bpf_reg_state *reg,
6108 			       argno_t argno, int off, int size,
6109 			       bool zero_size_allowed,
6110 			       u32 *max_access, bool write)
6111 {
6112 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6113 	struct bpf_prog_aux *aux = env->prog->aux;
6114 	u32 access_end;
6115 	int err;
6116 
6117 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
6118 	if (err)
6119 		return err;
6120 
6121 	*max_access = max(access_end, *max_access);
6122 	if (write && size) {
6123 		if (!aux->max_rdwr_write || access_end - size < aux->min_rdwr_write)
6124 			aux->min_rdwr_write = access_end - size;
6125 		aux->max_rdwr_write = max(access_end, aux->max_rdwr_write);
6126 	}
6127 
6128 	return 0;
6129 }
6130 
6131 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6132 static void zext_32_to_64(struct bpf_reg_state *reg)
6133 {
6134 	reg_step_check_unsigned(reg, 32);
6135 	reg->var_off = tnum_subreg(reg->var_off);
6136 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
6137 }
6138 
6139 /* truncate register to smaller size (in bytes)
6140  * must be called with size < BPF_REG_SIZE
6141  */
6142 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6143 {
6144 	u64 mask = (1ULL << (size * 8)) - 1;
6145 
6146 	reg_step_check_unsigned(reg, size * 8);
6147 
6148 	/* clear high bits in bit representation */
6149 	reg->var_off = tnum_cast(reg->var_off, size);
6150 
6151 	/* fix arithmetic bounds */
6152 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
6153 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
6154 	else
6155 		reg_set_urange64(reg, 0, mask);
6156 
6157 	/* If size is smaller than 32bit register the 32bit register
6158 	 * values are also truncated so we push 64-bit bounds into
6159 	 * 32-bit bounds. Above were truncated < 32-bits already.
6160 	 */
6161 	if (size < 4)
6162 		__mark_reg32_unbounded(reg);
6163 
6164 	reg_bounds_sync(reg);
6165 }
6166 
6167 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6168 {
6169 	if (size == 1) {
6170 		reg_set_srange64(reg, S8_MIN, S8_MAX);
6171 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6172 	} else if (size == 2) {
6173 		reg_set_srange64(reg, S16_MIN, S16_MAX);
6174 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6175 	} else {
6176 		/* size == 4 */
6177 		reg_set_srange64(reg, S32_MIN, S32_MAX);
6178 		reg_set_srange32(reg, S32_MIN, S32_MAX);
6179 	}
6180 	reg->var_off = tnum_unknown;
6181 }
6182 
6183 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6184 {
6185 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6186 	u64 top_smax_value, top_smin_value;
6187 	u64 num_bits = size * 8;
6188 	s64 limit = 1LL << (num_bits - 1);
6189 
6190 	/* If every value fits the signed N-bit range sign extension is a noop. */
6191 	if (reg_smin(reg) >= -limit && reg_smax(reg) < limit)
6192 		return;
6193 
6194 	/* See commen at reg_step_check_unsigned(). */
6195 	reg_step_reset(reg);
6196 
6197 	if (tnum_is_const(reg->var_off)) {
6198 		u64_cval = reg->var_off.value;
6199 		if (size == 1)
6200 			reg->var_off = tnum_const((s8)u64_cval);
6201 		else if (size == 2)
6202 			reg->var_off = tnum_const((s16)u64_cval);
6203 		else
6204 			/* size == 4 */
6205 			reg->var_off = tnum_const((s32)u64_cval);
6206 
6207 		u64_cval = reg->var_off.value;
6208 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
6209 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
6210 		return;
6211 	}
6212 
6213 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
6214 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
6215 
6216 	if (top_smax_value != top_smin_value)
6217 		goto out;
6218 
6219 	/* find the s64_min and s64_min after sign extension */
6220 	if (size == 1) {
6221 		init_s64_max = (s8)reg_smax(reg);
6222 		init_s64_min = (s8)reg_smin(reg);
6223 	} else if (size == 2) {
6224 		init_s64_max = (s16)reg_smax(reg);
6225 		init_s64_min = (s16)reg_smin(reg);
6226 	} else {
6227 		init_s64_max = (s32)reg_smax(reg);
6228 		init_s64_min = (s32)reg_smin(reg);
6229 	}
6230 
6231 	s64_max = max(init_s64_max, init_s64_min);
6232 	s64_min = min(init_s64_max, init_s64_min);
6233 
6234 	/* both of s64_max/s64_min positive or negative */
6235 	if ((s64_max >= 0) == (s64_min >= 0)) {
6236 		reg_set_srange64(reg, s64_min, s64_max);
6237 		reg_set_srange32(reg, s64_min, s64_max);
6238 		reg->var_off = tnum_range(s64_min, s64_max);
6239 		return;
6240 	}
6241 
6242 out:
6243 	set_sext64_default_val(reg, size);
6244 }
6245 
6246 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6247 {
6248 	if (size == 1)
6249 		reg_set_srange32(reg, S8_MIN, S8_MAX);
6250 	else
6251 		/* size == 2 */
6252 		reg_set_srange32(reg, S16_MIN, S16_MAX);
6253 	reg->var_off = tnum_subreg(tnum_unknown);
6254 }
6255 
6256 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6257 {
6258 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6259 	u32 top_smax_value, top_smin_value;
6260 	u32 num_bits = size * 8;
6261 
6262 	/*
6263 	 * If value fits the non-negative half of the signed N-bit range,
6264 	 * sign extension is a noop.
6265 	 */
6266 	if (reg_umax(reg) < (1ULL << (num_bits - 1)))
6267 		return;
6268 
6269 	/* See comment at reg_step_check_unsigned(). */
6270 	reg_step_reset(reg);
6271 
6272 	if (tnum_is_const(reg->var_off)) {
6273 		u32_val = reg->var_off.value;
6274 		if (size == 1)
6275 			reg->var_off = tnum_const((s8)u32_val);
6276 		else
6277 			reg->var_off = tnum_const((s16)u32_val);
6278 
6279 		u32_val = reg->var_off.value;
6280 		reg_set_srange32(reg, u32_val, u32_val);
6281 		return;
6282 	}
6283 
6284 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
6285 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
6286 
6287 	if (top_smax_value != top_smin_value)
6288 		goto out;
6289 
6290 	/* find the s32_min and s32_min after sign extension */
6291 	if (size == 1) {
6292 		init_s32_max = (s8)reg_s32_max(reg);
6293 		init_s32_min = (s8)reg_s32_min(reg);
6294 	} else {
6295 		/* size == 2 */
6296 		init_s32_max = (s16)reg_s32_max(reg);
6297 		init_s32_min = (s16)reg_s32_min(reg);
6298 	}
6299 	s32_max = max(init_s32_max, init_s32_min);
6300 	s32_min = min(init_s32_max, init_s32_min);
6301 
6302 	if ((s32_min >= 0) == (s32_max >= 0)) {
6303 		reg_set_srange32(reg, s32_min, s32_max);
6304 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6305 		return;
6306 	}
6307 
6308 out:
6309 	set_sext32_default_val(reg, size);
6310 }
6311 
6312 bool bpf_map_is_rdonly(const struct bpf_map *map)
6313 {
6314 	/* A map is considered read-only if the following condition are true:
6315 	 *
6316 	 * 1) BPF program side cannot change any of the map content. The
6317 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6318 	 *    and was set at map creation time.
6319 	 * 2) The map value(s) have been initialized from user space by a
6320 	 *    loader and then "frozen", such that no new map update/delete
6321 	 *    operations from syscall side are possible for the rest of
6322 	 *    the map's lifetime from that point onwards.
6323 	 * 3) Any parallel/pending map update/delete operations from syscall
6324 	 *    side have been completed. Only after that point, it's safe to
6325 	 *    assume that map value(s) are immutable.
6326 	 */
6327 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6328 	       READ_ONCE(map->frozen) &&
6329 	       !bpf_map_write_active(map);
6330 }
6331 
6332 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6333 			bool is_ldsx)
6334 {
6335 	void *ptr;
6336 	u64 addr;
6337 	int err;
6338 
6339 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY || map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
6340 		return -EINVAL;
6341 	err = map->ops->map_direct_value_addr(map, &addr, off);
6342 	if (err)
6343 		return err;
6344 	ptr = (void *)(long)addr + off;
6345 
6346 	switch (size) {
6347 	case sizeof(u8):
6348 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6349 		break;
6350 	case sizeof(u16):
6351 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6352 		break;
6353 	case sizeof(u32):
6354 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6355 		break;
6356 	case sizeof(u64):
6357 		*val = *(u64 *)ptr;
6358 		break;
6359 	default:
6360 		return -EINVAL;
6361 	}
6362 	return 0;
6363 }
6364 
6365 static int cmp_func_ptrs(const void *_a, const void *_b)
6366 {
6367 	const struct bpf_func_ptr *a = _a, *b = _b;
6368 
6369 	if (a->map != b->map)
6370 		return a->map < b->map ? -1 : 1;
6371 	if (a->map_off != b->map_off)
6372 		return a->map_off < b->map_off ? -1 : 1;
6373 	return 0;
6374 }
6375 
6376 /* Find the first pointer to a function at or after 'off' in the value of 'map' */
6377 static u32 func_ptr_lower_bound(struct bpf_verifier_env *env, const struct bpf_map *map, u64 off)
6378 {
6379 	u32 l = 0, r = env->func_ptr_cnt, m;
6380 	struct bpf_func_ptr *p;
6381 
6382 	while (l < r) {
6383 		m = l + (r - l) / 2;
6384 		p = &env->func_ptrs[m];
6385 		if (p->map < map || (p->map == map && p->map_off < off))
6386 			l = m + 1;
6387 		else
6388 			r = m;
6389 	}
6390 	return l;
6391 }
6392 
6393 /*
6394  * Return pointers to functions that overlap with 'size' bytes at offset 'off'
6395  * of the value of 'map' and their number in 'cnt'.
6396  */
6397 struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env,
6398 					     const struct bpf_map *map,
6399 					     u64 off, u64 size, u32 *cnt)
6400 {
6401 	u32 first, last;
6402 
6403 	*cnt = 0;
6404 	if (!env->func_ptr_cnt || !size)
6405 		return NULL;
6406 
6407 	/* a pointer that starts up to 7 bytes before 'off' overlaps too */
6408 	first = func_ptr_lower_bound(env, map, off >= sizeof(u64) ? off - sizeof(u64) + 1 : 0);
6409 	last = func_ptr_lower_bound(env, map, off + size);
6410 	if (first >= last)
6411 		return NULL;
6412 
6413 	*cnt = last - first;
6414 	return &env->func_ptrs[first];
6415 }
6416 
6417 /* Return all pointers to functions in the value of 'map' */
6418 struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
6419 				       const struct bpf_map *map, u32 *cnt)
6420 {
6421 	return bpf_map_range_func_ptrs(env, map, 0, (u64)map->value_size, cnt);
6422 }
6423 
6424 /* instructions [off, off + len) replaced the instruction at 'off' */
6425 void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len)
6426 {
6427 	struct bpf_func_ptr *p;
6428 	u32 i;
6429 
6430 	if (len <= 1)
6431 		return;
6432 
6433 	for (i = 0; i < env->func_ptr_cnt; i++) {
6434 		p = &env->func_ptrs[i];
6435 		if (p->xlated_off <= off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6436 			continue;
6437 		p->xlated_off += len - 1;
6438 	}
6439 }
6440 
6441 /*
6442  * Instructions [off, off + len) are about to be removed. It's called before
6443  * the starts of subprogs are adjusted. A subprog is gone when all of its
6444  * instructions are. Otherwise, e.g. when its first instruction is a nop,
6445  * it starts where the removed instructions did.
6446  */
6447 void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
6448 {
6449 	struct bpf_func_ptr *p;
6450 	int subprog;
6451 	u32 i;
6452 
6453 	for (i = 0; i < env->func_ptr_cnt; i++) {
6454 		p = &env->func_ptrs[i];
6455 		if (p->xlated_off < off || p->xlated_off == BPF_FUNC_PTR_DELETED)
6456 			continue;
6457 		if (p->xlated_off >= off + len) {
6458 			p->xlated_off -= len;
6459 			continue;
6460 		}
6461 		subprog = bpf_find_subprog(env, p->xlated_off);
6462 		if (subprog > 0 && env->subprog_info[subprog + 1].start > off + len)
6463 			p->xlated_off = off;
6464 		else
6465 			p->xlated_off = BPF_FUNC_PTR_DELETED;
6466 	}
6467 }
6468 
6469 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6470 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6471 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6472 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6473 
6474 /*
6475  * Allow list few fields as RCU trusted or full trusted.
6476  * This logic doesn't allow mix tagging and will be removed once GCC supports
6477  * btf_type_tag.
6478  */
6479 
6480 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6481 BTF_TYPE_SAFE_RCU(struct task_struct) {
6482 	const cpumask_t *cpus_ptr;
6483 	struct css_set __rcu *cgroups;
6484 	struct task_struct __rcu *real_parent;
6485 	struct task_struct *group_leader;
6486 };
6487 
6488 BTF_TYPE_SAFE_RCU(struct cgroup) {
6489 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6490 	struct kernfs_node *kn;
6491 };
6492 
6493 BTF_TYPE_SAFE_RCU(struct css_set) {
6494 	struct cgroup *dfl_cgrp;
6495 };
6496 
6497 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
6498 	struct cgroup *cgroup;
6499 };
6500 
6501 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6502 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6503 	struct file __rcu *exe_file;
6504 #ifdef CONFIG_MEMCG
6505 	struct task_struct __rcu *owner;
6506 #endif
6507 };
6508 
6509 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6510  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6511  */
6512 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6513 	struct sock *sk;
6514 };
6515 
6516 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6517 	struct sock *sk;
6518 };
6519 
6520 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6521 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6522 	struct seq_file *seq;
6523 };
6524 
6525 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6526 	struct bpf_iter_meta *meta;
6527 	struct task_struct *task;
6528 };
6529 
6530 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6531 	struct file *file;
6532 };
6533 
6534 BTF_TYPE_SAFE_TRUSTED(struct file) {
6535 	struct inode *f_inode;
6536 };
6537 
6538 /*
6539  * The pointer fields in the sched_ext ops argument containers are pinned by the
6540  * callers for the duration of the ops calls and are never NULL.
6541  */
6542 BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) {
6543 #ifdef CONFIG_EXT_GROUP_SCHED
6544 	struct cgroup *cgroup;
6545 #endif
6546 };
6547 
6548 BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) {
6549 	struct task_struct *task;
6550 };
6551 
6552 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) {
6553 	struct sched_ext_ops *ops;
6554 };
6555 
6556 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) {
6557 	struct sched_ext_ops *ops;
6558 };
6559 
6560 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
6561 	struct inode *d_inode;
6562 };
6563 
6564 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm) {
6565 	struct mm_struct *mm;
6566 };
6567 
6568 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6569 	struct sock *sk;
6570 };
6571 
6572 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
6573 	struct mm_struct *vm_mm;
6574 	struct file *vm_file;
6575 };
6576 
6577 static bool type_is_rcu(struct bpf_verifier_env *env,
6578 			struct bpf_reg_state *reg,
6579 			const char *field_name, u32 btf_id)
6580 {
6581 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6582 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6583 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6584 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
6585 
6586 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6587 }
6588 
6589 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6590 				struct bpf_reg_state *reg,
6591 				const char *field_name, u32 btf_id)
6592 {
6593 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6594 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6595 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6596 
6597 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6598 }
6599 
6600 static bool type_is_trusted(struct bpf_verifier_env *env,
6601 			    struct bpf_reg_state *reg,
6602 			    const char *field_name, u32 btf_id)
6603 {
6604 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6605 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6606 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6607 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6608 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args));
6609 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args));
6610 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args));
6611 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args));
6612 
6613 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6614 }
6615 
6616 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6617 				    struct bpf_reg_state *reg,
6618 				    const char *field_name, u32 btf_id)
6619 {
6620 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6621 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
6622 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm));
6623 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
6624 
6625 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6626 					  "__safe_trusted_or_null");
6627 }
6628 
6629 /*
6630  * The member holds the kernel address of arena memory, which the rewritten
6631  * load turns into an arena pointer, see arena_member_fixup(). NULL needs no
6632  * tracking, PTR_TO_ARENA covers it.
6633  */
6634 static int check_arena_member_load(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
6635 				   int value_regno, enum bpf_type_flag flag, const char *tname,
6636 				   const char *field_name)
6637 {
6638 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx];
6639 	struct bpf_insn *insn;
6640 
6641 	/* a helper reading the member as bytes needs no rewrite */
6642 	if (value_regno < 0)
6643 		return 0;
6644 	if (!env->prog->aux->arena) {
6645 		verbose(env,
6646 			"arena pointer member %s of struct %s requires a program with an associated arena\n",
6647 			field_name, tname);
6648 		return -EINVAL;
6649 	}
6650 	/* only a plain load or an acquire load is rewritten */
6651 	insn = &env->prog->insnsi[env->insn_idx];
6652 	if (BPF_CLASS(insn->code) != BPF_LDX &&
6653 	    !(insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW) && insn->imm == BPF_LOAD_ACQ)) {
6654 		verbose(env,
6655 			"arena pointer member %s of struct %s can only be read with a plain or an acquire load\n",
6656 			field_name, tname);
6657 		return -EACCES;
6658 	}
6659 
6660 	aux->arena_member = true;
6661 	if (flag & PTR_MAYBE_NULL)
6662 		aux->arena_member_nullable = true;
6663 	mark_reg_unknown(env, regs, value_regno);
6664 	regs[value_regno].type = PTR_TO_ARENA;
6665 	return 0;
6666 }
6667 
6668 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6669 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6670 				   argno_t argno, int off, int size,
6671 				   enum bpf_access_type atype,
6672 				   int value_regno)
6673 {
6674 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6675 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6676 	const char *field_name = NULL;
6677 	enum bpf_type_flag flag = 0;
6678 	u32 btf_id = 0;
6679 	s64 min_off;
6680 	int ret;
6681 
6682 	if (!env->allow_ptr_leaks) {
6683 		verbose(env,
6684 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6685 			tname);
6686 		return -EPERM;
6687 	}
6688 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6689 		verbose(env,
6690 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6691 			tname);
6692 		return -EINVAL;
6693 	}
6694 
6695 	if (check_add_overflow(reg_smin(reg), off, &min_off)) {
6696 		verbose(env,
6697 			"%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n",
6698 			reg_arg_name(env, argno), tname, reg_smin(reg), off);
6699 		return -EACCES;
6700 	}
6701 
6702 	if (min_off < 0) {
6703 		verbose(env,
6704 			"%s is ptr_%s invalid negative access: off=%lld\n",
6705 			reg_arg_name(env, argno), tname, min_off);
6706 		return -EACCES;
6707 	}
6708 
6709 	if (reg->type & MEM_USER) {
6710 		verbose(env,
6711 			"%s is ptr_%s access user memory\n",
6712 			reg_arg_name(env, argno), tname);
6713 		return -EACCES;
6714 	}
6715 
6716 	if (reg->type & MEM_PERCPU) {
6717 		verbose(env,
6718 			"%s is ptr_%s access percpu memory\n",
6719 			reg_arg_name(env, argno), tname);
6720 		return -EACCES;
6721 	}
6722 
6723 	if (atype != BPF_READ && bpf_may_fault_on_deref(reg->type)) {
6724 		verbose(env, "only read is supported\n");
6725 		return -EACCES;
6726 	}
6727 
6728 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6729 		if (!tnum_is_const(reg->var_off)) {
6730 			char tn_buf[48];
6731 
6732 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6733 			verbose(env,
6734 				"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6735 				reg_arg_name(env, argno), tname, off, tn_buf);
6736 			return -EACCES;
6737 		}
6738 
6739 		off += reg->var_off.value;
6740 
6741 		if (!btf_is_kernel(reg->btf)) {
6742 			verifier_bug(env, "reg->btf must be kernel btf");
6743 			return -EFAULT;
6744 		}
6745 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6746 		if (ret < 0)
6747 			verbose(env,
6748 				"%s cannot write into ptr_%s at off=%d size=%d\n",
6749 				reg_arg_name(env, argno), tname, off, size);
6750 	} else {
6751 		/* Writes are permitted with default btf_struct_access for
6752 		 * program allocated objects (which always have id > 0).
6753 		 */
6754 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6755 			verbose(env, "only read is supported\n");
6756 			return -EACCES;
6757 		}
6758 
6759 		/*
6760 		 * A fault-prone allocated object may still be read through a
6761 		 * BPF_PROBE_MEM load after its lifetime protection ends. Writes
6762 		 * through such pointers were rejected above.
6763 		 */
6764 		if (type_is_alloc(reg->type) && !bpf_may_fault_on_deref(reg->type) &&
6765 		    !type_is_non_owning_ref(reg->type) &&
6766 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
6767 			verifier_bug(env, "allocated object must have a referenced id");
6768 			return -EFAULT;
6769 		}
6770 
6771 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6772 	}
6773 
6774 	if (ret < 0)
6775 		return ret;
6776 
6777 	if (ret == PTR_TO_ARENA)
6778 		return check_arena_member_load(env, regs, value_regno, flag, tname, field_name);
6779 
6780 	if (ret != PTR_TO_BTF_ID) {
6781 		/* just mark; */
6782 
6783 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6784 		/* If this is an untrusted pointer, all pointers formed by walking it
6785 		 * also inherit the untrusted flag.
6786 		 */
6787 		flag = PTR_UNTRUSTED;
6788 
6789 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
6790 		/* By default any pointer obtained from walking a trusted pointer is no
6791 		 * longer trusted, unless the field being accessed has explicitly been
6792 		 * marked as inheriting its parent's state of trust (either full or RCU).
6793 		 * For example:
6794 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6795 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6796 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6797 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6798 		 *
6799 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6800 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6801 		 */
6802 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6803 			flag |= PTR_TRUSTED;
6804 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6805 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6806 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6807 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6808 				/* ignore __rcu tag and mark it MEM_RCU */
6809 				flag |= MEM_RCU;
6810 			} else if (flag & MEM_RCU ||
6811 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6812 				/* __rcu tagged pointers can be NULL */
6813 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6814 
6815 				/* We always trust them */
6816 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6817 				    flag & PTR_UNTRUSTED)
6818 					flag &= ~PTR_UNTRUSTED;
6819 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6820 				/* keep as-is */
6821 			} else {
6822 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6823 				clear_trusted_flags(&flag);
6824 			}
6825 		} else {
6826 			/*
6827 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6828 			 * aggressively mark as untrusted otherwise such
6829 			 * pointers will be plain PTR_TO_BTF_ID without flags
6830 			 * and will be allowed to be passed into helpers for
6831 			 * compat reasons.
6832 			 */
6833 			flag = PTR_UNTRUSTED;
6834 		}
6835 	} else {
6836 		/* Old compat. Deprecated */
6837 		clear_trusted_flags(&flag);
6838 	}
6839 
6840 	/*
6841 	 * A __nullable member only matters where NULL would otherwise be
6842 	 * assumed away, which is anywhere but on a plain or an untrusted
6843 	 * pointer: those are probed on a dereference, which tolerates NULL, and
6844 	 * the BTF_TYPE_SAFE_*_OR_NULL lists never applied to them either. A
6845 	 * per-CPU pointer counts, per_cpu_ptr() does not check for NULL.
6846 	 */
6847 	if (bpf_may_fault_on_deref(PTR_TO_BTF_ID | (flag & ~PTR_MAYBE_NULL)))
6848 		flag &= ~PTR_MAYBE_NULL;
6849 
6850 	if (atype == BPF_READ && value_regno >= 0) {
6851 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6852 		if (ret < 0)
6853 			return ret;
6854 	}
6855 
6856 	return 0;
6857 }
6858 
6859 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6860 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6861 				   argno_t argno, int off, int size,
6862 				   enum bpf_access_type atype,
6863 				   int value_regno)
6864 {
6865 	struct bpf_map *map = reg->map_ptr;
6866 	struct bpf_reg_state map_reg;
6867 	enum bpf_type_flag flag = 0;
6868 	const struct btf_type *t;
6869 	const char *tname;
6870 	u32 btf_id;
6871 	int ret;
6872 
6873 	if (!btf_vmlinux) {
6874 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6875 		return -ENOTSUPP;
6876 	}
6877 
6878 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6879 		verbose(env, "map_ptr access not supported for map type %d\n",
6880 			map->map_type);
6881 		return -ENOTSUPP;
6882 	}
6883 
6884 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6885 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6886 
6887 	if (!env->allow_ptr_leaks) {
6888 		verbose(env,
6889 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6890 			tname);
6891 		return -EPERM;
6892 	}
6893 
6894 	if (off < 0) {
6895 		verbose(env, "%s is %s invalid negative access: off=%d\n",
6896 			reg_arg_name(env, argno), tname, off);
6897 		return -EACCES;
6898 	}
6899 
6900 	if (atype != BPF_READ) {
6901 		verbose(env, "only read from %s is supported\n", tname);
6902 		return -EACCES;
6903 	}
6904 
6905 	/* Simulate access to a PTR_TO_BTF_ID */
6906 	memset(&map_reg, 0, sizeof(map_reg));
6907 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
6908 			      btf_vmlinux, *map->ops->map_btf_id, 0);
6909 	if (ret < 0)
6910 		return ret;
6911 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6912 	if (ret < 0)
6913 		return ret;
6914 
6915 	if (value_regno >= 0) {
6916 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6917 		if (ret < 0)
6918 			return ret;
6919 	}
6920 
6921 	return 0;
6922 }
6923 
6924 /*
6925  * Check that the stack access at the given offset is within bounds. The
6926  * maximum valid offset is -1.
6927  *
6928  * The minimum valid offset is -env->stack_limit for writes, and
6929  * -state->allocated_stack for reads.
6930  */
6931 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6932                                           s64 off,
6933                                           struct bpf_func_state *state,
6934                                           enum bpf_access_type t)
6935 {
6936 	int min_valid_off;
6937 
6938 	if (t == BPF_WRITE || env->allow_uninit_stack)
6939 		min_valid_off = -(int)env->stack_limit;
6940 	else
6941 		min_valid_off = -state->allocated_stack;
6942 
6943 	if (off < min_valid_off || off > -1)
6944 		return -EACCES;
6945 	return 0;
6946 }
6947 
6948 /* Check that the stack access at 'regno + off' falls within the maximum stack
6949  * bounds.
6950  *
6951  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6952  */
6953 static int check_stack_access_within_bounds(
6954 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6955 		argno_t argno, int off, int access_size,
6956 		enum bpf_access_type type)
6957 {
6958 	struct bpf_func_state *state = bpf_func(env, reg);
6959 	s64 min_off, max_off;
6960 	int err;
6961 	char *err_extra;
6962 
6963 	if (type == BPF_READ)
6964 		err_extra = " read from";
6965 	else
6966 		err_extra = " write to";
6967 
6968 	if (tnum_is_const(reg->var_off)) {
6969 		min_off = (s64)reg->var_off.value + off;
6970 		max_off = min_off + access_size;
6971 	} else {
6972 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
6973 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
6974 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
6975 				err_extra, reg_arg_name(env, argno));
6976 			return -EACCES;
6977 		}
6978 		min_off = reg_smin(reg) + off;
6979 		max_off = reg_smax(reg) + off + access_size;
6980 	}
6981 
6982 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6983 	if (!err && max_off > 0)
6984 		err = -EINVAL; /* out of stack access into non-negative offsets */
6985 	if (!err && access_size < 0)
6986 		/* access_size should not be negative (or overflow an int); others checks
6987 		 * along the way should have prevented such an access.
6988 		 */
6989 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6990 
6991 	if (err) {
6992 		if (tnum_is_const(reg->var_off)) {
6993 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
6994 				err_extra, reg_arg_name(env, argno), min_off, access_size);
6995 		} else {
6996 			char tn_buf[48];
6997 
6998 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6999 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
7000 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
7001 		}
7002 		return err;
7003 	}
7004 
7005 	/*
7006 	 * Every stack access passes through here, including buffers passed to
7007 	 * helpers and kfuncs and accesses into a caller's frame, so check the
7008 	 * fastcall contract of the frame that owns the slots once for all of
7009 	 * them. Zero-sized accesses touch no stack and keep the rewrite enabled.
7010 	 */
7011 	if (access_size)
7012 		check_fastcall_stack_contract(env, state, env->insn_idx, min_off);
7013 
7014 	/* Note that there is no stack access with offset zero, so the needed stack
7015 	 * size is -min_off, not -min_off+1.
7016 	 */
7017 	return bpf_grow_stack_state(env, state, -min_off /* size */);
7018 }
7019 
7020 static bool get_func_retval_range(struct bpf_prog *prog,
7021 				  struct bpf_retval_range *range)
7022 {
7023 	if (prog->type == BPF_PROG_TYPE_LSM &&
7024 		prog->expected_attach_type == BPF_LSM_MAC &&
7025 		!bpf_lsm_get_retval_range(prog, range)) {
7026 		return true;
7027 	}
7028 	return false;
7029 }
7030 
7031 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
7032 {
7033 	struct bpf_reg_state fake_reg;
7034 
7035 	if (!val)
7036 		return;
7037 
7038 	fake_reg.type = SCALAR_VALUE;
7039 	__mark_reg_known(&fake_reg, val);
7040 
7041 	scalar_step_add(dst_reg, dst_reg, &fake_reg);
7042 	scalar32_min_max_add(dst_reg, &fake_reg);
7043 	scalar_min_max_add(dst_reg, &fake_reg);
7044 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
7045 
7046 	reg_bounds_sync(dst_reg);
7047 }
7048 
7049 /* there is no support for callx in the interpreter */
7050 static int require_callx_jit(struct bpf_verifier_env *env)
7051 {
7052 	if (!env->prog->jit_requested) {
7053 		verbose(env, "JIT is required to use callx\n");
7054 		return -EOPNOTSUPP;
7055 	}
7056 	if (!bpf_jit_supports_callx()) {
7057 		verbose(env, "JIT doesn't support callx\n");
7058 		return -EOPNOTSUPP;
7059 	}
7060 	env->prog->jit_required = true;
7061 	return 0;
7062 }
7063 
7064 static void mark_reg_func_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
7065 			      int regno, int subprog)
7066 {
7067 	mark_reg_known_zero(env, regs, regno);
7068 	regs[regno].type = PTR_TO_FUNC;
7069 	regs[regno].subprogno = subprog;
7070 }
7071 
7072 /* a read from a table of functions branches into that many states at most */
7073 #define BPF_MAX_FUNC_PTR_TARGETS 64
7074 /* and that many pointers at most are next to what is read at variable offset */
7075 #define BPF_MAX_FUNC_PTR_RANGE 4096
7076 
7077 /* Count up to 'limit' offsets in [min_off, max_off] that the read is possible at */
7078 static u32 count_read_offsets(struct tnum offs, u64 min_off, u64 max_off, u32 limit)
7079 {
7080 	u64 o = min_off, next;
7081 	u32 cnt = 0;
7082 
7083 	if (!tnum_in(offs, tnum_const(o))) {
7084 		next = tnum_step(offs, o);
7085 		if (next <= o)
7086 			return 0;
7087 		o = next;
7088 	}
7089 	while (o <= max_off && cnt < limit) {
7090 		cnt++;
7091 		next = tnum_step(offs, o);
7092 		if (next <= o)
7093 			break;
7094 		o = next;
7095 	}
7096 	return cnt;
7097 }
7098 
7099 /*
7100  * A read from a frozen read-only map that has pointers to functions, see
7101  * resolve_func_ptrs(). The bounds and var_off of the offset tell where the read
7102  * is possible at, e.g. var_off is the stride of the elements of an array.
7103  * A read of exactly one pointer yields PTR_TO_FUNC. When the offset is variable
7104  * and only pointers can be read, which is how an element of a table of
7105  * functions is loaded, the verification continues with each of them. Other
7106  * reads that overlap with a pointer are rejected, because their result is not
7107  * known until the program is jitted.
7108  *
7109  * Return -ENOENT if there are no pointers to functions in the bytes that are read.
7110  */
7111 static int check_func_ptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
7112 			       int size, int value_regno)
7113 {
7114 	u64 min_off = reg_umin(reg) + off, max_off = reg_umax(reg) + off;
7115 	struct tnum offs = tnum_add(reg->var_off, tnum_const(off));
7116 	struct bpf_reg_state *regs = cur_regs(env);
7117 	struct bpf_map *map = reg->map_ptr;
7118 	struct bpf_verifier_state *branch;
7119 	int subprog, targets[BPF_MAX_FUNC_PTR_TARGETS];
7120 	struct bpf_func_ptr *ptrs;
7121 	u32 i, cnt, n = 0;
7122 	u64 o, lo, hi;
7123 	int err;
7124 
7125 	ptrs = bpf_map_range_func_ptrs(env, map, min_off, max_off - min_off + size, &cnt);
7126 	if (!ptrs)
7127 		return -ENOENT;
7128 	if (cnt > BPF_MAX_FUNC_PTR_RANGE)
7129 		goto overlap;
7130 
7131 	for (i = 0; i < cnt; i++) {
7132 		/* the offsets at which the read overlaps with the pointer */
7133 		lo = ptrs[i].map_off >= size ? ptrs[i].map_off - size + 1 : 0;
7134 		lo = max(lo, min_off);
7135 		hi = min(ptrs[i].map_off + sizeof(u64) - 1, max_off);
7136 		for (o = lo; o <= hi; o++) {
7137 			if (!tnum_in(offs, tnum_const(o)))
7138 				continue;
7139 			if (o != ptrs[i].map_off || size != sizeof(u64) || value_regno < 0)
7140 				goto overlap;
7141 			if (n == BPF_MAX_FUNC_PTR_TARGETS) {
7142 				verbose(env, "read from map '%s' may yield more than %d pointers to functions\n",
7143 					map->name, BPF_MAX_FUNC_PTR_TARGETS);
7144 				return -E2BIG;
7145 			}
7146 			subprog = bpf_find_subprog(env, ptrs[i].xlated_off);
7147 			if (verifier_bug_if(subprog <= 0, env,
7148 					    "no function at insn %u for map '%s' offset %u",
7149 					    ptrs[i].xlated_off, map->name, ptrs[i].map_off))
7150 				return -EFAULT;
7151 			targets[n++] = subprog;
7152 		}
7153 	}
7154 	/* pointers are next to what is read, e.g. the data of an array of vtables */
7155 	if (!n)
7156 		return -ENOENT;
7157 	/* either every offset that the read is possible at is a pointer or none */
7158 	if (count_read_offsets(offs, min_off, max_off, n + 1) != n)
7159 		goto overlap;
7160 
7161 	/* the map has the offset of the function until the program is jitted */
7162 	err = require_callx_jit(env);
7163 	if (err)
7164 		return err;
7165 
7166 	for (i = 0; i < n - 1; i++) {
7167 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx,
7168 				    env->cur_state->speculative);
7169 		if (IS_ERR(branch))
7170 			return PTR_ERR(branch);
7171 		mark_reg_func_ptr(env, branch->frame[branch->curframe]->regs, value_regno,
7172 				  targets[i]);
7173 	}
7174 	mark_reg_func_ptr(env, regs, value_regno, targets[n - 1]);
7175 	return 0;
7176 
7177 overlap:
7178 	verbose(env, "read of %d bytes at offset [%llu,%llu] of map '%s' overlaps with a pointer to a function\n",
7179 		size, min_off, max_off, map->name);
7180 	return -EACCES;
7181 }
7182 
7183 static int check_map_mem_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
7184 			      int bpf_size, int value_regno, bool is_ldsx)
7185 {
7186 	struct bpf_reg_state *regs = cur_regs(env);
7187 	int size = bpf_size_to_bytes(bpf_size);
7188 	struct bpf_map *map = reg->map_ptr;
7189 	int err;
7190 
7191 	switch (map->map_type) {
7192 	case BPF_MAP_TYPE_INSN_ARRAY:
7193 		if (bpf_size != BPF_DW) {
7194 			verbose(env, "Invalid read of %d bytes from insn_array\n", size);
7195 			return -EACCES;
7196 		}
7197 		regs[value_regno] = *reg;
7198 		add_scalar_to_reg(&regs[value_regno], off);
7199 		regs[value_regno].type = PTR_TO_INSN;
7200 		return 0;
7201 	case BPF_MAP_TYPE_PERCPU_ARRAY:
7202 		goto reg_unknown;
7203 	default:
7204 		break;
7205 	}
7206 
7207 	if (env->func_ptr_cnt) {
7208 		err = check_func_ptr_read(env, reg, off, size, value_regno);
7209 		if (err != -ENOENT)
7210 			return err;
7211 	}
7212 
7213 	/* If map is read-only, track its contents as scalars. */
7214 	if (tnum_is_const(reg->var_off) &&
7215 	    bpf_map_is_rdonly(map) &&
7216 	    map->ops->map_direct_value_addr) {
7217 		int map_off = off + reg->var_off.value;
7218 		u64 val = 0;
7219 
7220 		err = bpf_map_direct_read(map, map_off, size, &val, is_ldsx);
7221 		if (err)
7222 			return err;
7223 
7224 		regs[value_regno].type = SCALAR_VALUE;
7225 		__mark_reg_known(&regs[value_regno], val);
7226 		return 0;
7227 	}
7228 
7229 reg_unknown:
7230 	mark_reg_unknown(env, regs, value_regno);
7231 	return 0;
7232 }
7233 
7234 /* check whether memory at (regno + off) is accessible for t = (read | write)
7235  * if t==write, value_regno is a register which value is stored into memory
7236  * if t==read, value_regno is a register which will receive the value from memory
7237  * if t==write && value_regno==-1, some unknown value is stored into memory
7238  * if t==read && value_regno==-1, don't care what we read from memory
7239  */
7240 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
7241 			    int off, int bpf_size, enum bpf_access_type t,
7242 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7243 {
7244 	struct bpf_reg_state *regs = cur_regs(env);
7245 	enum bpf_reg_type ptr_type = reg->type;
7246 	int size, err = 0;
7247 
7248 	size = bpf_size_to_bytes(bpf_size);
7249 	if (size < 0)
7250 		return size;
7251 
7252 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7253 	if (err)
7254 		return err;
7255 
7256 	if (reg->type == PTR_TO_MAP_KEY) {
7257 		if (t == BPF_WRITE) {
7258 			verbose(env, "write to change key %s not allowed\n",
7259 				reg_arg_name(env, argno));
7260 			return -EACCES;
7261 		}
7262 
7263 		err = check_mem_region_access(env, reg, argno, off, size,
7264 					      reg->map_ptr->key_size, false);
7265 		if (err)
7266 			return err;
7267 		if (value_regno >= 0)
7268 			mark_reg_unknown(env, regs, value_regno);
7269 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7270 		struct btf_field *kptr_field = NULL;
7271 
7272 		if (t == BPF_WRITE && value_regno >= 0 &&
7273 		    is_pointer_value(env, value_regno)) {
7274 			verbose(env, "R%d leaks addr into map\n", value_regno);
7275 			return -EACCES;
7276 		}
7277 		err = check_map_access_type(env, reg, off, size, t);
7278 		if (err)
7279 			return err;
7280 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
7281 		if (err)
7282 			return err;
7283 		if (tnum_is_const(reg->var_off))
7284 			kptr_field = btf_record_find(reg->map_ptr->record,
7285 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7286 		if (kptr_field) {
7287 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
7288 		} else if (t == BPF_READ && value_regno >= 0) {
7289 			err = check_map_mem_read(env, reg, off, bpf_size, value_regno, is_ldsx);
7290 		}
7291 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7292 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7293 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7294 
7295 		if (type_may_be_null(reg->type)) {
7296 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7297 				reg_type_str(env, reg->type));
7298 			bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7299 					       reg_arg_name(env, argno), reg,
7300 						      BPF_DIAG_DEREF_NULLABLE_PTR, 0);
7301 			return -EACCES;
7302 		}
7303 
7304 		if (t == BPF_WRITE && rdonly_mem) {
7305 			verbose(env, "%s cannot write into %s\n",
7306 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7307 			return -EACCES;
7308 		}
7309 
7310 		if (t == BPF_WRITE && value_regno >= 0 &&
7311 		    is_pointer_value(env, value_regno)) {
7312 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7313 			return -EACCES;
7314 		}
7315 
7316 		if (rdonly_untrusted && !env->allow_ptr_leaks) {
7317 			verbose(env, "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7318 				reg_type_str(env, reg->type));
7319 			bpf_diag_policy(env, insn_idx, "read from untrusted read-only memory",
7320 					"the access requires CAP_PERFMON",
7321 					"Load the program with CAP_PERFMON, or avoid dereferencing untrusted pointers.");
7322 			return -EPERM;
7323 		}
7324 
7325 		/*
7326 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7327 		 * instructions, hence no need to check bounds in that case.
7328 		 */
7329 		if (!rdonly_untrusted)
7330 			err = check_mem_region_access(env, reg, argno, off, size,
7331 						      reg->mem_size, false);
7332 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7333 			mark_reg_unknown(env, regs, value_regno);
7334 	} else if (reg->type == PTR_TO_CTX) {
7335 		struct bpf_insn_access_aux info = {
7336 			.reg_type = SCALAR_VALUE,
7337 			.is_ldsx = is_ldsx,
7338 			.log = &env->log,
7339 		};
7340 		struct bpf_retval_range range;
7341 
7342 		if (t == BPF_WRITE && value_regno >= 0 &&
7343 		    is_pointer_value(env, value_regno)) {
7344 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7345 			return -EACCES;
7346 		}
7347 
7348 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
7349 		if (!err && t == BPF_READ && value_regno >= 0) {
7350 			/* ctx access returns either a scalar, or a
7351 			 * PTR_TO_PACKET[_META,_END]. In the latter
7352 			 * case, we know the offset is zero.
7353 			 */
7354 			if (info.reg_type == SCALAR_VALUE) {
7355 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7356 					mark_reg_unknown(env, regs, value_regno);
7357 					err = __mark_reg_s32_range(env, regs, value_regno,
7358 								   range.minval, range.maxval);
7359 					if (err)
7360 						return err;
7361 				} else {
7362 					mark_reg_unknown(env, regs, value_regno);
7363 				}
7364 			} else {
7365 				mark_reg_known_zero(env, regs,
7366 						    value_regno);
7367 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7368 					regs[value_regno].btf = info.btf;
7369 					regs[value_regno].btf_id = info.btf_id;
7370 					regs[value_regno].id = info.ref_id;
7371 				} else if (base_type(info.reg_type) == PTR_TO_MEM) {
7372 					regs[value_regno].mem_size = info.mem_size;
7373 				}
7374 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
7375 					regs[value_regno].id = ++env->id_gen;
7376 			}
7377 			regs[value_regno].type = info.reg_type;
7378 		}
7379 
7380 	} else if (reg->type == PTR_TO_STACK) {
7381 		/* Basic bounds checks. */
7382 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
7383 		if (err)
7384 			return err;
7385 
7386 		if (t == BPF_READ)
7387 			err = check_stack_read(env, reg, argno, off, size,
7388 					       value_regno);
7389 		else
7390 			err = check_stack_write(env, reg, off, size,
7391 						value_regno, insn_idx);
7392 	} else if (reg_is_pkt_pointer(reg)) {
7393 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7394 			verbose(env, "cannot write into packet\n");
7395 			return -EACCES;
7396 		}
7397 		if (t == BPF_WRITE && value_regno >= 0 &&
7398 		    is_pointer_value(env, value_regno)) {
7399 			verbose(env, "R%d leaks addr into packet\n",
7400 				value_regno);
7401 			return -EACCES;
7402 		}
7403 		err = check_packet_access(env, reg, argno, off, size, false);
7404 		if (!err && t == BPF_READ && value_regno >= 0)
7405 			mark_reg_unknown(env, regs, value_regno);
7406 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7407 		if (t == BPF_WRITE && value_regno >= 0 &&
7408 		    is_pointer_value(env, value_regno)) {
7409 			verbose(env, "R%d leaks addr into flow keys\n",
7410 				value_regno);
7411 			return -EACCES;
7412 		}
7413 
7414 		err = check_flow_keys_access(env, reg, argno, off, size);
7415 		if (!err && t == BPF_READ && value_regno >= 0)
7416 			mark_reg_unknown(env, regs, value_regno);
7417 	} else if (type_is_sk_pointer(reg->type)) {
7418 		if (t == BPF_WRITE) {
7419 			verbose(env, "%s cannot write into %s\n",
7420 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7421 			return -EACCES;
7422 		}
7423 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
7424 		if (!err && value_regno >= 0)
7425 			mark_reg_unknown(env, regs, value_regno);
7426 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7427 		err = check_tp_buffer_access(env, reg, argno, off, size);
7428 		if (!err && t == BPF_READ && value_regno >= 0)
7429 			mark_reg_unknown(env, regs, value_regno);
7430 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7431 		   !type_may_be_null(reg->type)) {
7432 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
7433 					      value_regno);
7434 	} else if (reg->type == CONST_PTR_TO_MAP) {
7435 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
7436 					      value_regno);
7437 	} else if (base_type(reg->type) == PTR_TO_BUF &&
7438 		   !type_may_be_null(reg->type)) {
7439 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7440 		u32 *max_access;
7441 
7442 		if (rdonly_mem) {
7443 			if (t == BPF_WRITE) {
7444 				verbose(env, "%s cannot write into %s\n",
7445 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7446 				return -EACCES;
7447 			}
7448 			max_access = &env->prog->aux->max_rdonly_access;
7449 		} else {
7450 			max_access = &env->prog->aux->max_rdwr_access;
7451 		}
7452 
7453 		err = check_buffer_access(env, reg, argno, off, size, false,
7454 					  max_access, t == BPF_WRITE);
7455 
7456 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7457 			mark_reg_unknown(env, regs, value_regno);
7458 	} else if (reg->type == PTR_TO_ARENA) {
7459 		if (t == BPF_READ && value_regno >= 0)
7460 			mark_reg_unknown(env, regs, value_regno);
7461 	} else {
7462 		enum bpf_diag_invalid_deref_kind kind = BPF_DIAG_DEREF_INVALID_PTR;
7463 
7464 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
7465 			reg_type_str(env, reg->type));
7466 		if (reg->type == SCALAR_VALUE)
7467 			kind = BPF_DIAG_DEREF_SCALAR;
7468 		else if (type_may_be_null(reg->type))
7469 			kind = BPF_DIAG_DEREF_NULLABLE_PTR;
7470 		bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
7471 				       reg_arg_name(env, argno), reg, kind, 0);
7472 		return -EACCES;
7473 	}
7474 
7475 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7476 	    regs[value_regno].type == SCALAR_VALUE) {
7477 		if (!is_ldsx) {
7478 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7479 			coerce_reg_to_size(&regs[value_regno], size);
7480 		} else {
7481 			/*
7482 			 * Sign-extension can change the register value relative
7483 			 * to a scalar it is linked with by id (e.g. a zero-
7484 			 * extending fill of the same spilled stack slot), thus
7485 			 * drop the shared id in that case.
7486 			 */
7487 			bool no_sext = reg_umax(&regs[value_regno]) <
7488 					(1ULL << (size * BITS_PER_BYTE - 1));
7489 
7490 			coerce_reg_to_size_sx(&regs[value_regno], size);
7491 			if (!no_sext)
7492 				clear_scalar_id(&regs[value_regno]);
7493 		}
7494 	}
7495 
7496 	if (!err && bpf_is_mem_insn(&env->prog->insnsi[insn_idx]) && ptr_type != PTR_TO_STACK)
7497 		mark_non_stack_access(env, insn_idx);
7498 
7499 	return err;
7500 }
7501 
7502 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7503 			     bool allow_trust_mismatch);
7504 
7505 /*
7506  * Returns the register to check the access of the current insn with.
7507  * For a number in a program with an arena that is 'arena'.
7508  */
7509 static struct bpf_reg_state *mem_access_reg(struct bpf_verifier_env *env, int regno,
7510 					    struct bpf_reg_state *arena)
7511 {
7512 	if (!is_arena_scalar(env, regno))
7513 		return cur_regs(env) + regno;
7514 
7515 	memset(arena, 0, sizeof(*arena));
7516 	arena->type = PTR_TO_ARENA;
7517 	env->insn_aux_data[env->insn_idx].arena_scalar = true;
7518 	return arena;
7519 }
7520 
7521 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7522 			  bool strict_alignment_once, bool is_ldsx,
7523 			  bool allow_trust_mismatch, const char *ctx)
7524 {
7525 	struct bpf_verifier_state *vstate = env->cur_state;
7526 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7527 	struct bpf_reg_state *regs = cur_regs(env);
7528 	struct bpf_reg_state arena, *src_reg;
7529 	enum bpf_reg_type src_reg_type;
7530 	int err;
7531 
7532 	/* Handle stack arg read */
7533 	if (is_stack_arg_ldx(insn)) {
7534 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7535 		if (err)
7536 			return err;
7537 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
7538 	}
7539 
7540 	/* check src operand */
7541 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7542 	if (err)
7543 		return err;
7544 
7545 	/* check dst operand */
7546 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7547 	if (err)
7548 		return err;
7549 
7550 	src_reg = mem_access_reg(env, insn->src_reg, &arena);
7551 	src_reg_type = src_reg->type;
7552 
7553 	/*
7554 	 * check_stack_read_fixed_off() may refine the modification's origin to
7555 	 * the source stack slot.
7556 	 */
7557 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
7558 	err = check_mem_access(env, env->insn_idx, src_reg, argno_from_reg(insn->src_reg),
7559 			       insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7560 			       strict_alignment_once, is_ldsx);
7561 	/*
7562 	 * Paths through a kernel struct pointer and through other pointers
7563 	 * may share the insn, see save_aux_ptr_type(). Record a load that did
7564 	 * not produce an arena pointer from an __arena member, the only load
7565 	 * through a kernel struct pointer that does, next to the one
7566 	 * check_arena_member_load() records, so that arena_member_fixup() can
7567 	 * tell when the paths disagree.
7568 	 */
7569 	if (!err && !(base_type(src_reg_type) == PTR_TO_BTF_ID &&
7570 		      regs[insn->dst_reg].type == PTR_TO_ARENA))
7571 		env->insn_aux_data[env->insn_idx].non_arena_load = true;
7572 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7573 				       allow_trust_mismatch);
7574 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7575 	if (!err)
7576 		bpf_diag_mod_end(env);
7577 
7578 	return err;
7579 }
7580 
7581 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7582 			   bool strict_alignment_once)
7583 {
7584 	struct bpf_verifier_state *vstate = env->cur_state;
7585 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7586 	struct bpf_reg_state *regs = cur_regs(env);
7587 	struct bpf_reg_state arena, *dst_reg;
7588 	enum bpf_reg_type dst_reg_type;
7589 	int err;
7590 
7591 	/* Handle stack arg write */
7592 	if (is_stack_arg_stx(insn)) {
7593 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
7594 		if (err)
7595 			return err;
7596 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
7597 	}
7598 
7599 	/* check src1 operand */
7600 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7601 	if (err)
7602 		return err;
7603 
7604 	/* check src2 operand */
7605 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7606 	if (err)
7607 		return err;
7608 
7609 	dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
7610 	dst_reg_type = dst_reg->type;
7611 
7612 	/* Check if (dst_reg + off) is writeable. */
7613 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
7614 			       insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7615 			       strict_alignment_once, false);
7616 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7617 
7618 	return err;
7619 }
7620 
7621 static int check_atomic_rmw(struct bpf_verifier_env *env,
7622 			    struct bpf_insn *insn)
7623 {
7624 	struct bpf_reg_state arena, *dst_reg;
7625 	int load_reg;
7626 	int err;
7627 
7628 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7629 		verbose(env, "invalid atomic operand size\n");
7630 		return -EINVAL;
7631 	}
7632 
7633 	/* check src1 operand */
7634 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7635 	if (err)
7636 		return err;
7637 
7638 	/* check src2 operand */
7639 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7640 	if (err)
7641 		return err;
7642 
7643 	if (insn->imm == BPF_CMPXCHG) {
7644 		/* Check comparison of R0 with memory location */
7645 		const u32 aux_reg = BPF_REG_0;
7646 
7647 		err = check_reg_arg(env, aux_reg, SRC_OP);
7648 		if (err)
7649 			return err;
7650 
7651 		if (is_pointer_value(env, aux_reg)) {
7652 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7653 			return -EACCES;
7654 		}
7655 	}
7656 
7657 	if (is_pointer_value(env, insn->src_reg)) {
7658 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7659 		return -EACCES;
7660 	}
7661 
7662 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7663 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7664 			insn->dst_reg,
7665 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7666 		return -EACCES;
7667 	}
7668 
7669 	/* load_reg may be dst_reg. Look at dst_reg before it's marked as unknown. */
7670 	dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
7671 
7672 	load_reg = bpf_atomic_load_reg(insn);
7673 	if (load_reg >= 0) {
7674 		/* check and record load of old value */
7675 		err = check_reg_arg(env, load_reg, DST_OP);
7676 		if (err)
7677 			return err;
7678 	}
7679 
7680 	/* Check whether we can read the memory, with second call for fetch
7681 	 * case to simulate the register fill.
7682 	 */
7683 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7684 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7685 	if (!err && load_reg >= 0) {
7686 		bpf_diag_mod_begin(env, cur_regs(env) + load_reg, NULL, BPF_DIAG_MOD_WRITE);
7687 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
7688 				       insn->off, BPF_SIZE(insn->code),
7689 				       BPF_READ, load_reg, true, false);
7690 		if (!err)
7691 			bpf_diag_mod_end(env);
7692 	}
7693 	if (err)
7694 		return err;
7695 
7696 	err = save_aux_ptr_type(env, dst_reg->type, false);
7697 	if (err)
7698 		return err;
7699 	/* Check whether we can write into the same memory. */
7700 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
7701 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7702 	if (err)
7703 		return err;
7704 	return 0;
7705 }
7706 
7707 static int check_atomic_load(struct bpf_verifier_env *env,
7708 			     struct bpf_insn *insn)
7709 {
7710 	int err;
7711 
7712 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7713 	if (err)
7714 		return err;
7715 
7716 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7717 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7718 			insn->src_reg,
7719 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7720 		return -EACCES;
7721 	}
7722 
7723 	return check_load_mem(env, insn, true, false, false, "atomic_load");
7724 }
7725 
7726 static int check_atomic_store(struct bpf_verifier_env *env,
7727 			      struct bpf_insn *insn)
7728 {
7729 	int err;
7730 
7731 	err = check_store_reg(env, insn, true);
7732 	if (err)
7733 		return err;
7734 
7735 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7736 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7737 			insn->dst_reg,
7738 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7739 		return -EACCES;
7740 	}
7741 
7742 	return 0;
7743 }
7744 
7745 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7746 {
7747 	switch (insn->imm) {
7748 	case BPF_ADD:
7749 	case BPF_ADD | BPF_FETCH:
7750 	case BPF_AND:
7751 	case BPF_AND | BPF_FETCH:
7752 	case BPF_OR:
7753 	case BPF_OR | BPF_FETCH:
7754 	case BPF_XOR:
7755 	case BPF_XOR | BPF_FETCH:
7756 	case BPF_XCHG:
7757 	case BPF_CMPXCHG:
7758 		return check_atomic_rmw(env, insn);
7759 	case BPF_LOAD_ACQ:
7760 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7761 			verbose(env,
7762 				"64-bit load-acquires are only supported on 64-bit arches\n");
7763 			return -EOPNOTSUPP;
7764 		}
7765 		return check_atomic_load(env, insn);
7766 	case BPF_STORE_REL:
7767 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7768 			verbose(env,
7769 				"64-bit store-releases are only supported on 64-bit arches\n");
7770 			return -EOPNOTSUPP;
7771 		}
7772 		return check_atomic_store(env, insn);
7773 	default:
7774 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7775 			insn->imm);
7776 		return -EINVAL;
7777 	}
7778 }
7779 
7780 /* When register 'regno' is used to read the stack (either directly or through
7781  * a helper function) make sure that it's within stack boundary and, depending
7782  * on the access type and privileges, that all elements of the stack are
7783  * initialized.
7784  *
7785  * All registers that have been spilled on the stack in the slots within the
7786  * read offsets are marked as read.
7787  */
7788 static int check_stack_range_initialized(
7789 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
7790 		int access_size, bool zero_size_allowed,
7791 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7792 {
7793 	struct bpf_func_state *state = bpf_func(env, reg);
7794 	int err, min_off, max_off, i, j, slot, spi;
7795 	/* Some accesses can write anything into the stack, others are
7796 	 * read-only.
7797 	 */
7798 	bool clobber = type == BPF_WRITE;
7799 	/*
7800 	 * Negative access_size signals global subprog arg check where
7801 	 * STACK_POISON slots are acceptable. static stack liveness
7802 	 * might have determined that subprog doesn't read them,
7803 	 * but BTF based global subprog validation isn't accurate enough.
7804 	 */
7805 	bool allow_poison = access_size < 0 || clobber;
7806 	u32 arg_slot = arg_slot_from_argno(argno);
7807 	bool uninit = clobber && meta && arg_slot < MAX_BPF_FUNC_ARGS &&
7808 		      (meta->arg_raw_mem.mask & BIT(arg_slot));
7809 	bool raw_mode = uninit && env->allow_uninit_stack &&
7810 			!(meta->arg_raw_mem.var_size_mask & BIT(arg_slot));
7811 
7812 	access_size = abs(access_size);
7813 
7814 	if (access_size == 0 && !zero_size_allowed) {
7815 		verbose(env, "invalid zero-sized read\n");
7816 		return -EACCES;
7817 	}
7818 
7819 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
7820 	if (err)
7821 		return err;
7822 
7823 	if (tnum_is_const(reg->var_off)) {
7824 		min_off = max_off = reg->var_off.value + off;
7825 	} else {
7826 		/* Variable offset is prohibited for unprivileged mode for
7827 		 * simplicity since it requires corresponding support in
7828 		 * Spectre masking for stack ALU.
7829 		 * See also retrieve_ptr_limit().
7830 		 */
7831 		if (!env->bypass_spec_v1) {
7832 			char tn_buf[48];
7833 
7834 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7835 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
7836 				reg_arg_name(env, argno), tn_buf);
7837 			return -EACCES;
7838 		}
7839 		/*
7840 		 * The call may touch any byte in the possible range, but does not
7841 		 * definitely initialize all of it. Fall back to ordinary stack checks.
7842 		 */
7843 		raw_mode = false;
7844 
7845 		min_off = reg_smin(reg) + off;
7846 		max_off = reg_smax(reg) + off;
7847 	}
7848 
7849 	/* Unprivileged outputs retain each byte's initialization state. */
7850 	if (raw_mode) {
7851 		meta->arg_raw_mem.size[arg_slot] = access_size;
7852 		return 0;
7853 	}
7854 
7855 	for (i = min_off; i < max_off + access_size; i++) {
7856 		struct bpf_stack_state *ss;
7857 		u8 *stype;
7858 
7859 		slot = -i - 1;
7860 		spi = slot / BPF_REG_SIZE;
7861 		if (state->allocated_stack <= slot) {
7862 			verbose(env, "allocated_stack too small\n");
7863 			return -EFAULT;
7864 		}
7865 
7866 		ss = bpf_stack_slot(state, spi);
7867 		stype = &ss->slot_type[slot % BPF_REG_SIZE];
7868 		if (*stype == STACK_MISC)
7869 			goto mark;
7870 		if ((*stype == STACK_ZERO) ||
7871 		    (*stype == STACK_INVALID && (uninit || env->allow_uninit_stack))) {
7872 			if (clobber && (*stype != STACK_INVALID || env->allow_uninit_stack)) {
7873 				/* helper can write anything into the stack */
7874 				*stype = STACK_MISC;
7875 			}
7876 			goto mark;
7877 		}
7878 
7879 		/*
7880 		 * Only the bytes marked STACK_SPILL hold the spilled register.
7881 		 * The rest of a narrowly spilled slot keeps its previous type
7882 		 * and must be initialized on its own.
7883 		 */
7884 		if (*stype == STACK_SPILL &&
7885 		    (ss->spilled_ptr.type == SCALAR_VALUE ||
7886 		     env->allow_ptr_leaks)) {
7887 			if (clobber) {
7888 				__mark_reg_unknown(env, &ss->spilled_ptr);
7889 				for (j = 0; j < BPF_REG_SIZE; j++)
7890 					scrub_spilled_slot(&ss->slot_type[j]);
7891 			}
7892 			goto mark;
7893 		}
7894 
7895 		if (*stype == STACK_POISON) {
7896 			if (allow_poison) {
7897 				if (uninit && env->allow_uninit_stack)
7898 					*stype = STACK_MISC;
7899 				goto mark;
7900 			}
7901 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
7902 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7903 		} else if (tnum_is_const(reg->var_off)) {
7904 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
7905 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
7906 		} else {
7907 			char tn_buf[48];
7908 
7909 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7910 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
7911 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
7912 		}
7913 		return -EACCES;
7914 mark:
7915 		;
7916 	}
7917 	return 0;
7918 }
7919 
7920 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7921 				   argno_t argno, int access_size,
7922 				   enum bpf_access_type access_type, bool zero_size_allowed,
7923 				   struct bpf_call_arg_meta *meta, bool *known_memory)
7924 {
7925 	struct bpf_reg_state *regs = cur_regs(env);
7926 	u32 *max_access;
7927 
7928 	if (known_memory)
7929 		*known_memory = true;
7930 
7931 	switch (base_type(reg->type)) {
7932 	case PTR_TO_PACKET:
7933 	case PTR_TO_PACKET_META:
7934 		if (!may_access_direct_pkt_data(env, meta, access_type)) {
7935 			verbose(env, "function access to the packet is not allowed\n");
7936 			return -EACCES;
7937 		}
7938 		return check_packet_access(env, reg, argno, 0, access_size,
7939 					   zero_size_allowed);
7940 	case PTR_TO_MAP_KEY:
7941 		if (access_type == BPF_WRITE) {
7942 			verbose(env, "%s cannot write into %s\n",
7943 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7944 			return -EACCES;
7945 		}
7946 		return check_mem_region_access(env, reg, argno, 0, access_size,
7947 					       reg->map_ptr->key_size, false);
7948 	case PTR_TO_MAP_VALUE:
7949 		if (check_map_access_type(env, reg, 0, access_size, access_type))
7950 			return -EACCES;
7951 		return check_map_access(env, reg, argno, 0, access_size,
7952 					zero_size_allowed, ACCESS_HELPER);
7953 	case PTR_TO_MEM:
7954 		if (type_is_rdonly_mem(reg->type)) {
7955 			if (access_type == BPF_WRITE) {
7956 				verbose(env, "%s cannot write into %s\n",
7957 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7958 				return -EACCES;
7959 			}
7960 		}
7961 		return check_mem_region_access(env, reg, argno, 0,
7962 					       access_size, reg->mem_size,
7963 					       zero_size_allowed);
7964 	case PTR_TO_BUF:
7965 		if (type_is_rdonly_mem(reg->type)) {
7966 			if (access_type == BPF_WRITE) {
7967 				verbose(env, "%s cannot write into %s\n",
7968 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7969 				return -EACCES;
7970 			}
7971 
7972 			max_access = &env->prog->aux->max_rdonly_access;
7973 		} else {
7974 			max_access = &env->prog->aux->max_rdwr_access;
7975 		}
7976 		return check_buffer_access(env, reg, argno, 0,
7977 					   access_size, zero_size_allowed,
7978 					   max_access, access_type == BPF_WRITE);
7979 	case PTR_TO_STACK:
7980 		return check_stack_range_initialized(
7981 				env, reg,
7982 				argno, 0, access_size,
7983 				zero_size_allowed, access_type, meta);
7984 	case PTR_TO_BTF_ID:
7985 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
7986 					       access_size, access_type, -1);
7987 	case PTR_TO_CTX:
7988 		/* Only permit reading or writing syscall context using helper calls. */
7989 		if (is_var_ctx_off_allowed(env->prog)) {
7990 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
7991 							  zero_size_allowed);
7992 			if (err)
7993 				return err;
7994 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
7995 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
7996 			return 0;
7997 		}
7998 		fallthrough;
7999 	default: /* scalar_value or invalid ptr */
8000 		/* Allow zero-byte read from NULL, regardless of pointer type */
8001 		if (zero_size_allowed && access_size == 0 &&
8002 		    bpf_register_is_null(reg))
8003 			return 0;
8004 		if (known_memory && base_type(reg->type) != PTR_TO_CTX)
8005 			*known_memory = false;
8006 
8007 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
8008 			reg_type_str(env, reg->type));
8009 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8010 		return -EACCES;
8011 	}
8012 }
8013 
8014 enum bpf_mem_size_failure {
8015 	BPF_MEM_SIZE_FAIL_NONE,
8016 	BPF_MEM_SIZE_FAIL_MEMORY,
8017 	BPF_MEM_SIZE_FAIL_SIZE,
8018 };
8019 
8020 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8021  * size.
8022  *
8023  * @mem_reg contains the pointer, @size_reg contains the access size.
8024  */
8025 static int check_mem_size_reg(struct bpf_verifier_env *env,
8026 			      struct bpf_reg_state *mem_reg,
8027 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
8028 			      argno_t size_argno, u32 access_type,
8029 			      bool zero_size_allowed,
8030 			      struct bpf_call_arg_meta *meta,
8031 			      enum bpf_mem_size_failure *failure)
8032 {
8033 	int err = 0;
8034 
8035 	if (failure)
8036 		*failure = BPF_MEM_SIZE_FAIL_NONE;
8037 
8038 	/* This is used to refine r0 return value bounds for helpers
8039 	 * that enforce this value as an upper bound on return values.
8040 	 * See do_refine_retval_range() for helpers that can refine
8041 	 * the return value. C type of helper is u32 so we pull register
8042 	 * bound from umax_value however, if negative verifier errors
8043 	 * out. Only upper bounds can be learned because retval is an
8044 	 * int type and negative retvals are allowed.
8045 	 */
8046 	meta->msize_max_value = reg_umax(size_reg);
8047 
8048 	/*
8049 	 * Check variable ranges byte by byte instead of using raw mode. Keep the
8050 	 * MEM_UNINIT annotation so invalid bytes are accepted without marking them
8051 	 * initialized when the caller cannot read uninitialized stack memory.
8052 	 */
8053 	if (!tnum_is_const(size_reg->var_off))
8054 		meta->arg_raw_mem.var_size_mask |= BIT(arg_slot_from_argno(mem_argno));
8055 
8056 	if (reg_smin(size_reg) < 0) {
8057 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
8058 			reg_arg_name(env, size_argno));
8059 		err = -EACCES;
8060 		goto size_error;
8061 	}
8062 
8063 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
8064 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
8065 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
8066 		err = -EACCES;
8067 		goto size_error;
8068 	}
8069 
8070 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
8071 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8072 			reg_arg_name(env, size_argno));
8073 		err = -EACCES;
8074 		goto size_error;
8075 	}
8076 
8077 	if (access_type & BPF_READ)
8078 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
8079 					      BPF_READ, zero_size_allowed, meta, NULL);
8080 	if (!err && access_type & BPF_WRITE)
8081 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
8082 					      BPF_WRITE, zero_size_allowed, meta, NULL);
8083 	if (err && failure)
8084 		*failure = BPF_MEM_SIZE_FAIL_MEMORY;
8085 
8086 	if (!err)
8087 		err = mark_arg_precision(env, size_argno);
8088 
8089 	return err;
8090 
8091 size_error:
8092 	if (failure)
8093 		*failure = BPF_MEM_SIZE_FAIL_SIZE;
8094 	return err;
8095 }
8096 
8097 static bool is_subprog(const struct bpf_call_arg_meta *meta)
8098 {
8099 	return meta->btf && !meta->func_id;
8100 }
8101 
8102 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8103 			 argno_t argno, u32 mem_size, enum bpf_access_type access_type,
8104 			 struct bpf_call_arg_meta *meta, bool *known_memory)
8105 {
8106 	int size, err = 0;
8107 
8108 	if (bpf_register_is_null(reg))
8109 		return mark_arg_precision(env, argno);
8110 	if (known_memory)
8111 		*known_memory = true;
8112 
8113 	if (mem_size > S32_MAX) {
8114 		verbose(env, "%s memory size %u is too large\n",
8115 			reg_arg_name(env, argno), mem_size);
8116 		return -EACCES;
8117 	}
8118 
8119 	/*
8120 	 * Only a global subprog may read poisoned stack slots:
8121 	 * its static stack liveness proved the callee body skips them.
8122 	 */
8123 	size = (is_subprog(meta) &&
8124 		base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size;
8125 
8126 	if (access_type & BPF_READ)
8127 		err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta,
8128 					      known_memory);
8129 	if (!err && (access_type & BPF_WRITE))
8130 		err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta,
8131 					      known_memory);
8132 
8133 	return err;
8134 }
8135 
8136 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8137 					argno_t argno, struct ret_mem_desc *ret_mem)
8138 {
8139 	int regno = reg_from_argno(argno);
8140 	int err;
8141 
8142 	if (ret_mem->found) {
8143 		verifier_bug(env, "only one allocation size argument permitted");
8144 		return -EFAULT;
8145 	}
8146 
8147 	if (!tnum_is_const(reg->var_off)) {
8148 		verbose(env, "%s is not a const\n", reg_arg_name(env, argno));
8149 		return -EINVAL;
8150 	}
8151 
8152 	if (reg->var_off.value > U32_MAX) {
8153 		verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno));
8154 		return -EINVAL;
8155 	}
8156 
8157 	if (regno >= 0)
8158 		err = mark_chain_precision(env, regno);
8159 	else
8160 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8161 	if (err)
8162 		return err;
8163 
8164 	ret_mem->size = reg->var_off.value;
8165 	ret_mem->found = true;
8166 
8167 	return 0;
8168 }
8169 
8170 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8171 			     argno_t argno, struct bpf_call_arg_meta *meta)
8172 {
8173 	int regno = reg_from_argno(argno);
8174 	int err;
8175 
8176 	if (meta->arg_constant.found) {
8177 		verifier_bug(env, "only one constant argument permitted");
8178 		return -EFAULT;
8179 	}
8180 
8181 	if (!tnum_is_const(reg->var_off)) {
8182 		verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno));
8183 		return -EINVAL;
8184 	}
8185 
8186 	if (regno >= 0)
8187 		err = mark_chain_precision(env, regno);
8188 	else
8189 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
8190 	if (err < 0)
8191 		return err;
8192 
8193 	meta->arg_constant.found = true;
8194 	meta->arg_constant.value = reg->var_off.value;
8195 
8196 	return 0;
8197 }
8198 
8199 enum {
8200 	PROCESS_SPIN_LOCK = (1 << 0),
8201 	PROCESS_RES_LOCK  = (1 << 1),
8202 	PROCESS_LOCK_IRQ  = (1 << 2),
8203 };
8204 
8205 /* Implementation details:
8206  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8207  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8208  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8209  * Two separate bpf_obj_new will also have different reg->id.
8210  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8211  * clears reg->id after value_or_null->value transition, since the verifier only
8212  * cares about the range of access to valid map value pointer and doesn't care
8213  * about actual address of the map element.
8214  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8215  * reg->id > 0 after value_or_null->value transition. By doing so
8216  * two bpf_map_lookups will be considered two different pointers that
8217  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8218  * returned from bpf_obj_new.
8219  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8220  * dead-locks.
8221  * Since only one bpf_spin_lock is allowed the checks are simpler than
8222  * reg_is_refcounted() logic. The verifier needs to remember only
8223  * one spin_lock instead of array of acquired_refs.
8224  * env->cur_state->active_locks remembers which map value element or allocated
8225  * object got locked and clears it after bpf_spin_unlock.
8226  */
8227 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
8228 {
8229 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8230 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8231 	struct bpf_verifier_state *cur = env->cur_state;
8232 	struct bpf_reference_state *lock;
8233 	bool is_const = tnum_is_const(reg->var_off);
8234 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8235 	u64 val = reg->var_off.value;
8236 	struct bpf_map *map = NULL;
8237 	struct btf *btf = NULL;
8238 	struct btf_record *rec;
8239 	u32 spin_lock_off;
8240 	int err;
8241 
8242 	if (!is_const) {
8243 		verbose(env,
8244 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
8245 			reg_arg_name(env, argno), lock_str);
8246 		return -EINVAL;
8247 	}
8248 	if (reg->type == PTR_TO_MAP_VALUE) {
8249 		map = reg->map_ptr;
8250 		if (!map->btf) {
8251 			verbose(env,
8252 				"map '%s' has to have BTF in order to use %s_lock\n",
8253 				map->name, lock_str);
8254 			return -EINVAL;
8255 		}
8256 	} else {
8257 		btf = reg->btf;
8258 	}
8259 
8260 	rec = reg_btf_record(reg);
8261 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8262 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8263 			map ? map->name : "kptr", lock_str);
8264 		return -EINVAL;
8265 	}
8266 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8267 	if (spin_lock_off != val) {
8268 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8269 			val, lock_str, spin_lock_off);
8270 		return -EINVAL;
8271 	}
8272 	if (is_lock) {
8273 		void *ptr;
8274 		int type;
8275 
8276 		if (map)
8277 			ptr = map;
8278 		else
8279 			ptr = btf;
8280 
8281 		if (!is_res_lock && cur->active_locks) {
8282 			lock = find_lock_state(cur, REF_TYPE_LOCK, 0, NULL);
8283 			if (lock) {
8284 				verbose(env,
8285 					"Locking two bpf_spin_locks are not allowed\n");
8286 				bpf_diag_lock(
8287 					env, env->insn_idx, "nested spin lock",
8288 					"This path already holds a bpf_spin_lock. The verifier allows only one regular BPF spin lock at a time.",
8289 					"Unlock the current bpf_spin_lock before taking another one.", lock);
8290 				return -EINVAL;
8291 			}
8292 		} else if (is_res_lock && cur->active_locks) {
8293 			lock = find_lock_state(cur, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
8294 					       reg->id, ptr);
8295 			if (lock) {
8296 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8297 				bpf_diag_lock(
8298 					env, env->insn_idx, "recursive resource spin lock",
8299 					"This path already holds the same resource spin lock. Taking it again would deadlock.",
8300 					"Avoid reacquiring the same resource spin lock before it is unlocked.", lock);
8301 				return -EINVAL;
8302 			}
8303 		}
8304 
8305 		if (is_res_lock && is_irq)
8306 			type = REF_TYPE_RES_LOCK_IRQ;
8307 		else if (is_res_lock)
8308 			type = REF_TYPE_RES_LOCK;
8309 		else
8310 			type = REF_TYPE_LOCK;
8311 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8312 		if (err < 0) {
8313 			verbose(env, "Failed to acquire lock state\n");
8314 			return err;
8315 		}
8316 	} else {
8317 		void *ptr;
8318 		int type;
8319 
8320 		if (map)
8321 			ptr = map;
8322 		else
8323 			ptr = btf;
8324 
8325 		if (!cur->active_locks) {
8326 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8327 			bpf_diag_res(
8328 				env, env->insn_idx, "unlock without lock",
8329 				"This unlock operation has no matching active lock on the current path.",
8330 				"Take the matching lock before this unlock, or remove the unmatched unlock path.");
8331 			return -EINVAL;
8332 		}
8333 
8334 		if (is_res_lock && is_irq)
8335 			type = REF_TYPE_RES_LOCK_IRQ;
8336 		else if (is_res_lock)
8337 			type = REF_TYPE_RES_LOCK;
8338 		else
8339 			type = REF_TYPE_LOCK;
8340 
8341 		lock = find_lock_state(cur, type, reg->id, ptr);
8342 		if (!lock) {
8343 			verbose(env, "%s_unlock of different lock\n", lock_str);
8344 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8345 					       cur->active_lock_ptr);
8346 			bpf_diag_lock(
8347 				env, env->insn_idx, "unlock of a different lock",
8348 				"This unlock does not match any active lock with the same tracked identity on the current path.",
8349 				"Unlock the same lock object that was most recently acquired.", lock);
8350 			return -EINVAL;
8351 		}
8352 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8353 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8354 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
8355 					       cur->active_lock_ptr);
8356 			bpf_diag_lock(
8357 				env, env->insn_idx, "unlock out of order",
8358 				"Locks must be released in last-in, first-out order, but this unlock does not match the currently active lock.",
8359 				"Release nested locks in the reverse order they were acquired.", lock);
8360 			return -EINVAL;
8361 		}
8362 		if (release_lock_state(env, type, reg->id, ptr)) {
8363 			verbose(env, "%s_unlock of different lock\n", lock_str);
8364 			bpf_diag_lock(
8365 				env, env->insn_idx, "unlock of a different lock",
8366 				"The verifier could not release a lock state matching this unlock operation.",
8367 				"Pass the same lock object and lock kind that were used for the matching lock operation.",
8368 				lock);
8369 			return -EINVAL;
8370 		}
8371 		/*
8372 		 * Invalidate non-owning refs before RCU demotion clears their
8373 		 * NON_OWN_REF flag.
8374 		 */
8375 		invalidate_non_owning_refs(env);
8376 
8377 		if (!in_rcu_cs(env))
8378 			invalidate_rcu_protected_refs(env);
8379 	}
8380 	return 0;
8381 }
8382 
8383 /* Check if @regno is a pointer to a specific field in a map value */
8384 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8385 				   enum btf_field_type field_type,
8386 				   struct bpf_map_desc *map_desc)
8387 {
8388 	bool is_const = tnum_is_const(reg->var_off);
8389 	struct bpf_map *map = reg->map_ptr;
8390 	u64 val = reg->var_off.value;
8391 	const char *struct_name = btf_field_type_name(field_type);
8392 	int field_off = -1;
8393 
8394 	if (!is_const) {
8395 		verbose(env,
8396 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
8397 			reg_arg_name(env, argno), struct_name);
8398 		return -EINVAL;
8399 	}
8400 	if (!map->btf) {
8401 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8402 			struct_name);
8403 		return -EINVAL;
8404 	}
8405 	if (!btf_record_has_field(map->record, field_type)) {
8406 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8407 		return -EINVAL;
8408 	}
8409 	switch (field_type) {
8410 	case BPF_TIMER:
8411 		field_off = map->record->timer_off;
8412 		break;
8413 	case BPF_TASK_WORK:
8414 		field_off = map->record->task_work_off;
8415 		break;
8416 	case BPF_RCU_HEAD:
8417 		field_off = map->record->rcu_head_off;
8418 		break;
8419 	case BPF_WORKQUEUE:
8420 		field_off = map->record->wq_off;
8421 		break;
8422 	default:
8423 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8424 		return -EINVAL;
8425 	}
8426 	if (field_off != val) {
8427 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8428 			val, struct_name, field_off);
8429 		return -EINVAL;
8430 	}
8431 	if (map_desc->ptr) {
8432 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
8433 		return -EFAULT;
8434 	}
8435 	map_desc->uid = reg->map_uid;
8436 	map_desc->ptr = map;
8437 	return 0;
8438 }
8439 
8440 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8441 			      struct bpf_map_desc *map)
8442 {
8443 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8444 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8445 		return -EOPNOTSUPP;
8446 	}
8447 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
8448 }
8449 
8450 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8451 			     struct bpf_call_arg_meta *meta)
8452 {
8453 	struct bpf_reg_state *reg = reg_state(env, regno);
8454 	struct btf_field *kptr_field;
8455 	struct bpf_map *map_ptr;
8456 	struct btf_record *rec;
8457 	u32 kptr_off;
8458 
8459 	if (type_is_ptr_alloc_obj(reg->type)) {
8460 		rec = reg_btf_record(reg);
8461 	} else { /* PTR_TO_MAP_VALUE */
8462 		map_ptr = reg->map_ptr;
8463 		if (!map_ptr->btf) {
8464 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8465 				map_ptr->name);
8466 			return -EINVAL;
8467 		}
8468 		rec = map_ptr->record;
8469 		meta->map.ptr = map_ptr;
8470 	}
8471 
8472 	if (!tnum_is_const(reg->var_off)) {
8473 		verbose(env,
8474 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8475 			regno);
8476 		return -EINVAL;
8477 	}
8478 
8479 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8480 		verbose(env, "R%d has no valid kptr\n", regno);
8481 		return -EINVAL;
8482 	}
8483 
8484 	kptr_off = reg->var_off.value;
8485 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8486 	if (!kptr_field) {
8487 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8488 		return -EACCES;
8489 	}
8490 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8491 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8492 		return -EACCES;
8493 	}
8494 	meta->kptr_field = kptr_field;
8495 	return 0;
8496 }
8497 
8498 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
8499 			      const char *call_name, const char *reason, const char *suggestion);
8500 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
8501 						 argno_t argno, const char *call_name,
8502 						 const char *suggestion, const char *fmt, ...);
8503 
8504 /*
8505  * Validate dynptr arguments for helper, kfunc and subprog.
8506  *
8507  * @meta carries the dynptr and referenced-object state. The dynptr is populated
8508  * when the argument is tagged with MEM_UNINIT (i.e., the dynptr argument that
8509  * will be constructed) and consumed when the argument is expected to be an
8510  * initialized dynptr. The reference tracks the parent object (e.g., file or skb
8511  * in qdisc program) when constructing a dynptr.
8512  *
8513  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8514  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8515  *
8516  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8517  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8518  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8519  *
8520  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
8521  * dynptr points to. At the first level, the verifier will make sure a
8522  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
8523  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
8524  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
8525  * and checked dynamically during runtime.
8526  */
8527 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8528 			       argno_t argno, int insn_idx, enum bpf_arg_type arg_type,
8529 			       struct bpf_call_arg_meta *meta)
8530 {
8531 	int spi, err = 0;
8532 
8533 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8534 	 *		 constructing a mutable bpf_dynptr object.
8535 	 *
8536 	 *		 Currently, this is only possible with PTR_TO_STACK
8537 	 *		 pointing to a region of at least 16 bytes which doesn't
8538 	 *		 contain an existing bpf_dynptr.
8539 	 *
8540 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
8541 	 *		  destroyed.
8542 	 *
8543 	 *  None       - Points to a initialized dynptr that cannot be
8544 	 *		 reinitialized or destroyed. However, the view of the
8545 	 *		 dynptr and the memory it points to may be mutated.
8546 	 */
8547 	if (arg_type & MEM_UNINIT) {
8548 		int i;
8549 
8550 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8551 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8552 			bpf_diag_res(
8553 				env, insn_idx, "dynptr is already initialized",
8554 				"This function constructs a dynptr and requires an uninitialized dynptr stack slot, but the selected slot already holds dynptr state.",
8555 				"Use a fresh stack dynptr slot, or release/destroy the existing dynptr before reusing the slot.");
8556 			return -EINVAL;
8557 		}
8558 
8559 		/* we write BPF_DW bits (8 bytes) at a time */
8560 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8561 			err = check_mem_access(env, insn_idx, reg, argno,
8562 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8563 			if (err)
8564 				return err;
8565 		}
8566 
8567 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx,
8568 					      &meta->ref_obj, &meta->dynptr);
8569 	} else /* OBJ_RELEASE and None case from above */ {
8570 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8571 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
8572 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
8573 			bpf_diag_res(
8574 				env, insn_idx, "const dynptr release",
8575 				"This release operation was given a const dynptr. Const dynptr values are verifier-provided views and cannot be released by the program.",
8576 				"Release only mutable dynptrs that the program initialized or reserved.");
8577 			return -EINVAL;
8578 		}
8579 
8580 		if (!is_dynptr_reg_valid_init(env, reg)) {
8581 			verbose(env, "Expected an initialized dynptr as %s\n",
8582 				reg_arg_name(env, argno));
8583 			bpf_diag_res(
8584 				env, insn_idx, "uninitialized dynptr use",
8585 				"This operation requires an initialized dynptr, but the stack slot does not currently hold a valid dynptr on this path.",
8586 				"Initialize the dynptr on every path before this call, and avoid overwriting or releasing it before this use.");
8587 			return -EINVAL;
8588 		}
8589 
8590 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
8591 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
8592 			enum bpf_dynptr_type expected_type = arg_to_dynptr_type(arg_type);
8593 			enum bpf_dynptr_type actual_type = dynptr_reg_type(env, reg);
8594 
8595 			verbose(env, "Expected a dynptr of type %s as %s\n",
8596 				dynptr_type_str(expected_type), reg_arg_name(env, argno));
8597 			bpf_diag_call_arg_fmt(
8598 				env, insn_idx, argno, meta->func_name,
8599 				"Use a dynptr constructor that matches this operation, or call an operation that accepts the dynptr's current type.",
8600 				"the dynptr is initialized with backing object type %s, but this operation expects dynptr type %s",
8601 				dynptr_type_str(actual_type), dynptr_type_str(expected_type));
8602 			return -EINVAL;
8603 		}
8604 
8605 		if (reg->type != CONST_PTR_TO_DYNPTR) {
8606 			struct bpf_func_state *state = bpf_func(env, reg);
8607 
8608 			spi = dynptr_get_spi(env, reg);
8609 			if (spi < 0)
8610 				return spi;
8611 
8612 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
8613 
8614 			reg = &bpf_stack_slot(state, spi)->spilled_ptr;
8615 		}
8616 
8617 		meta->dynptr.type = reg->dynptr.type;
8618 		meta->dynptr.id = reg->id;
8619 		meta->dynptr.parent_id = reg->parent_id;
8620 	}
8621 	return err;
8622 }
8623 
8624 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta)
8625 {
8626 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8627 }
8628 
8629 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta)
8630 {
8631 	return meta->kfunc_flags & KF_ITER_NEW;
8632 }
8633 
8634 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta)
8635 {
8636 	return meta->kfunc_flags & KF_ITER_DESTROY;
8637 }
8638 
8639 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx,
8640 			      const struct btf_param *arg)
8641 {
8642 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8643 	 * kfunc is iter state pointer
8644 	 */
8645 	if (is_iter_kfunc(meta))
8646 		return arg_idx == 0;
8647 
8648 	/* iter passed as an argument to a generic kfunc */
8649 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8650 }
8651 
8652 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8653 			    u32 arg, argno_t argno, int insn_idx,
8654 			    struct bpf_call_arg_meta *meta)
8655 {
8656 	struct bpf_func_state *state = bpf_func(env, reg);
8657 	const struct btf_type *t;
8658 	int spi, err, i, nr_slots, btf_id;
8659 
8660 	if (reg->type != PTR_TO_STACK) {
8661 		verbose(env, "%s expected pointer to an iterator on stack\n",
8662 			reg_arg_name(env, argno));
8663 		bpf_diag_call_arg_fmt(
8664 			env, insn_idx, argno, meta->func_name,
8665 			"Pass the address of a stack iterator object for iterator new, next, and destroy calls.",
8666 			"iterator state must live in verifier-tracked stack memory, but %s is %s",
8667 			reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type));
8668 		return -EINVAL;
8669 	}
8670 
8671 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8672 	 * ensures struct convention, so we wouldn't need to do any BTF
8673 	 * validation here. But given iter state can be passed as a parameter
8674 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8675 	 * conservative here.
8676 	 */
8677 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg);
8678 	if (btf_id < 0) {
8679 		verbose(env, "expected valid iter pointer as %s\n",
8680 			reg_arg_name(env, argno));
8681 		bpf_diag_call_arg(
8682 			env, insn_idx, argno, meta->func_name,
8683 			"the function expects a recognized iterator state pointer, but this argument does not match a valid iterator type",
8684 			"Pass the exact iterator state type expected by this function.");
8685 		return -EINVAL;
8686 	}
8687 	t = btf_type_by_id(meta->btf, btf_id);
8688 	nr_slots = t->size / BPF_REG_SIZE;
8689 
8690 	if (is_iter_new_kfunc(meta)) {
8691 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8692 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8693 			verbose(env, "expected uninitialized iter_%s as %s\n",
8694 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8695 			bpf_diag_res(
8696 				env, insn_idx, "iterator is already initialized",
8697 				"Iterator creation requires an uninitialized iterator stack object, but this stack range already contains iterator state.",
8698 				"Use a fresh iterator stack slot, or destroy the existing iterator before reusing the slot.");
8699 			return -EINVAL;
8700 		}
8701 
8702 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8703 			err = check_mem_access(env, insn_idx, reg, argno,
8704 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8705 			if (err)
8706 				return err;
8707 		}
8708 
8709 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8710 		if (err)
8711 			return err;
8712 	} else {
8713 		/* iter_next() or iter_destroy(), as well as any kfunc
8714 		 * accepting iter argument, expect initialized iter state
8715 		 */
8716 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8717 		switch (err) {
8718 		case 0:
8719 			break;
8720 		case -EINVAL:
8721 			verbose(env, "expected an initialized iter_%s as %s\n",
8722 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
8723 			bpf_diag_res(
8724 				env, insn_idx, "uninitialized iterator use",
8725 				"This iterator operation requires an initialized iterator state object, but the stack range does not contain a live iterator on this path.",
8726 				"Call the matching iterator new kfunc on every path before calling next or destroy, and do not destroy the iterator before this use.");
8727 			return err;
8728 		case -EPROTO:
8729 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8730 			bpf_diag_ctx_required(
8731 				env, insn_idx, meta->func_name, BPF_DIAG_CONTEXT_RCU,
8732 				"Wrap iterator use in bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
8733 			return err;
8734 		default:
8735 			return err;
8736 		}
8737 
8738 		spi = iter_get_spi(env, reg, nr_slots);
8739 		if (spi < 0)
8740 			return spi;
8741 
8742 		mark_stack_slots_scratched(env, spi, nr_slots);
8743 
8744 		/* remember meta->iter info for process_iter_next_call() */
8745 		meta->iter.spi = spi;
8746 		meta->iter.frameno = reg->frameno;
8747 		update_ref_obj(&meta->ref_obj, &bpf_stack_slot(state, spi)->spilled_ptr);
8748 
8749 		if (is_iter_destroy_kfunc(meta)) {
8750 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8751 			if (err)
8752 				return err;
8753 		}
8754 	}
8755 
8756 	return 0;
8757 }
8758 
8759 /* Look for a previous loop entry at insn_idx: nearest parent state
8760  * stopped at insn_idx with callsites matching those in cur->frame.
8761  */
8762 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8763 						  struct bpf_verifier_state *cur,
8764 						  int insn_idx)
8765 {
8766 	struct bpf_verifier_state_list *sl;
8767 	struct bpf_verifier_state *st;
8768 	struct list_head *pos, *head;
8769 
8770 	/* Explored states are pushed in stack order, most recent states come first */
8771 	head = bpf_explored_state(env, insn_idx);
8772 	list_for_each(pos, head) {
8773 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8774 		/* If st->branches != 0 state is a part of current DFS verification path,
8775 		 * hence cur & st for a loop.
8776 		 */
8777 		st = &sl->state;
8778 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8779 		    st->dfs_depth < cur->dfs_depth)
8780 			return st;
8781 	}
8782 
8783 	return NULL;
8784 }
8785 
8786 /*
8787  * Check if scalar registers are exact for the purpose of not widening.
8788  * More lenient than regs_exact()
8789  */
8790 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
8791 				    const struct bpf_reg_state *rcur)
8792 {
8793 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
8794 }
8795 
8796 static void maybe_widen_reg(struct bpf_verifier_env *env,
8797 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
8798 {
8799 	if (rold->type != SCALAR_VALUE)
8800 		return;
8801 	if (rold->type != rcur->type)
8802 		return;
8803 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
8804 		return;
8805 	__mark_reg_unknown(env, rcur);
8806 }
8807 
8808 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8809 				   struct bpf_verifier_state *old,
8810 				   struct bpf_verifier_state *cur)
8811 {
8812 	struct bpf_func_state *fold, *fcur;
8813 	int i, fr, num_slots;
8814 
8815 	for (fr = old->curframe; fr >= 0; fr--) {
8816 		fold = old->frame[fr];
8817 		fcur = cur->frame[fr];
8818 
8819 		for (i = 0; i < MAX_BPF_REG; i++)
8820 			maybe_widen_reg(env,
8821 					&fold->regs[i],
8822 					&fcur->regs[i]);
8823 
8824 		num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur));
8825 		for (i = 0; i < num_slots; i++) {
8826 			struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i);
8827 			struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i);
8828 
8829 			if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss))
8830 				continue;
8831 
8832 			maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr);
8833 		}
8834 	}
8835 	return 0;
8836 }
8837 
8838 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8839 						 struct bpf_call_arg_meta *meta)
8840 {
8841 	int iter_frameno = meta->iter.frameno;
8842 	int iter_spi = meta->iter.spi;
8843 
8844 	return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr;
8845 }
8846 
8847 /* process_iter_next_call() is called when verifier gets to iterator's next
8848  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8849  * to it as just "iter_next()" in comments below.
8850  *
8851  * BPF verifier relies on a crucial contract for any iter_next()
8852  * implementation: it should *eventually* return NULL, and once that happens
8853  * it should keep returning NULL. That is, once iterator exhausts elements to
8854  * iterate, it should never reset or spuriously return new elements.
8855  *
8856  * With the assumption of such contract, process_iter_next_call() simulates
8857  * a fork in the verifier state to validate loop logic correctness and safety
8858  * without having to simulate infinite amount of iterations.
8859  *
8860  * In current state, we first assume that iter_next() returned NULL and
8861  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8862  * conditions we should not form an infinite loop and should eventually reach
8863  * exit.
8864  *
8865  * Besides that, we also fork current state and enqueue it for later
8866  * verification. In a forked state we keep iterator state as ACTIVE
8867  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8868  * also bump iteration depth to prevent erroneous infinite loop detection
8869  * later on (see iter_active_depths_differ() comment for details). In this
8870  * state we assume that we'll eventually loop back to another iter_next()
8871  * calls (it could be in exactly same location or in some other instruction,
8872  * it doesn't matter, we don't make any unnecessary assumptions about this,
8873  * everything revolves around iterator state in a stack slot, not which
8874  * instruction is calling iter_next()). When that happens, we either will come
8875  * to iter_next() with equivalent state and can conclude that next iteration
8876  * will proceed in exactly the same way as we just verified, so it's safe to
8877  * assume that loop converges. If not, we'll go on another iteration
8878  * simulation with a different input state, until all possible starting states
8879  * are validated or we reach maximum number of instructions limit.
8880  *
8881  * This way, we will either exhaustively discover all possible input states
8882  * that iterator loop can start with and eventually will converge, or we'll
8883  * effectively regress into bounded loop simulation logic and either reach
8884  * maximum number of instructions if loop is not provably convergent, or there
8885  * is some statically known limit on number of iterations (e.g., if there is
8886  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8887  *
8888  * Iteration convergence logic in is_state_visited() relies on exact
8889  * states comparison, which ignores read and precision marks.
8890  * This is necessary because read and precision marks are not finalized
8891  * while in the loop. Exact comparison might preclude convergence for
8892  * simple programs like below:
8893  *
8894  *     i = 0;
8895  *     while(iter_next(&it))
8896  *       i++;
8897  *
8898  * At each iteration step i++ would produce a new distinct state and
8899  * eventually instruction processing limit would be reached.
8900  *
8901  * To avoid such behavior speculatively forget (widen) range for
8902  * imprecise scalar registers, if those registers were not precise at the
8903  * end of the previous iteration and do not match exactly.
8904  *
8905  * This is a conservative heuristic that allows to verify wide range of programs,
8906  * however it precludes verification of programs that conjure an
8907  * imprecise value on the first loop iteration and use it as precise on a second.
8908  * For example, the following safe program would fail to verify:
8909  *
8910  *     struct bpf_num_iter it;
8911  *     int arr[10];
8912  *     int i = 0, a = 0;
8913  *     bpf_iter_num_new(&it, 0, 10);
8914  *     while (bpf_iter_num_next(&it)) {
8915  *       if (a == 0) {
8916  *         a = 1;
8917  *         i = 7; // Because i changed verifier would forget
8918  *                // it's range on second loop entry.
8919  *       } else {
8920  *         arr[i] = 42; // This would fail to verify.
8921  *       }
8922  *     }
8923  *     bpf_iter_num_destroy(&it);
8924  */
8925 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8926 				  struct bpf_call_arg_meta *meta)
8927 {
8928 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8929 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8930 	struct bpf_reg_state *cur_iter, *queued_iter;
8931 
8932 	BTF_TYPE_EMIT(struct bpf_iter);
8933 
8934 	cur_iter = get_iter_from_state(cur_st, meta);
8935 
8936 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8937 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8938 		verifier_bug(env, "unexpected iterator state %d (%s)",
8939 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8940 		return -EFAULT;
8941 	}
8942 
8943 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8944 		/* Because iter_next() call is a checkpoint is_state_visitied()
8945 		 * should guarantee parent state with same call sites and insn_idx.
8946 		 */
8947 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8948 		    !same_callsites(cur_st->parent, cur_st)) {
8949 			verifier_bug(env, "bad parent state for iter next call");
8950 			return -EFAULT;
8951 		}
8952 		/* Note cur_st->parent in the call below, it is necessary to skip
8953 		 * checkpoint created for cur_st by is_state_visited()
8954 		 * right at this instruction.
8955 		 */
8956 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8957 		/* branch out active iter state */
8958 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8959 		if (IS_ERR(queued_st))
8960 			return PTR_ERR(queued_st);
8961 
8962 		queued_iter = get_iter_from_state(queued_st, meta);
8963 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8964 		queued_iter->iter.depth++;
8965 		if (prev_st)
8966 			widen_imprecise_scalars(env, prev_st, queued_st);
8967 
8968 		queued_fr = queued_st->frame[queued_st->curframe];
8969 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8970 	}
8971 
8972 	/* switch to DRAINED state, but keep the depth unchanged */
8973 	/* mark current iter state as drained and assume returned NULL */
8974 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8975 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8976 
8977 	return 0;
8978 }
8979 
8980 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8981 {
8982 	return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO;
8983 }
8984 
8985 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8986 {
8987 	/*
8988 	 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw
8989 	 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be
8990 	 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized().
8991 	 */
8992 	return (base_type(type) == ARG_PTR_TO_MEM ||
8993 		base_type(type) == ARG_PTR_TO_MAP_VALUE) &&
8994 	       type & MEM_UNINIT;
8995 }
8996 
8997 static bool arg_type_is_release(enum bpf_arg_type type)
8998 {
8999 	return type & OBJ_RELEASE;
9000 }
9001 
9002 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9003 {
9004 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9005 }
9006 
9007 /*
9008  * An argument that only ever takes a scalar, so a zero register passed to it
9009  * is a value rather than a NULL pointer.
9010  */
9011 static bool arg_type_is_scalar(enum bpf_arg_type type)
9012 {
9013 	switch (base_type(type)) {
9014 	case ARG_SCALAR:
9015 	case ARG_CONST_SCALAR:
9016 	case ARG_MEM_SIZE:
9017 	case ARG_MEM_SIZE_OR_ZERO:
9018 	case ARG_CONST_MEM_SIZE:
9019 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9020 		return true;
9021 	default:
9022 		return false;
9023 	}
9024 }
9025 
9026 /*
9027  * A helper has no BTF and a nonzero function ID. A kfunc has both, while a
9028  * BPF subprogram has BTF and a zero function ID.
9029  */
9030 static bool is_helper(const struct bpf_call_arg_meta *meta)
9031 {
9032 	return !meta->btf && meta->func_id;
9033 }
9034 
9035 static bool is_helper_call(const struct bpf_call_arg_meta *meta, enum bpf_func_id func_id)
9036 {
9037 	return is_helper(meta) && meta->func_id == func_id;
9038 }
9039 
9040 static bool is_kfunc(const struct bpf_call_arg_meta *meta)
9041 {
9042 	return meta->btf && meta->func_id;
9043 }
9044 
9045 static bool is_kfunc_call(const struct bpf_call_arg_meta *meta, u32 btf_id)
9046 {
9047 	return is_kfunc(meta) && meta->func_id == btf_id;
9048 }
9049 
9050 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9051 				const struct bpf_call_arg_meta *meta,
9052 				enum bpf_arg_type *arg_type)
9053 {
9054 	if (!meta->map.ptr) {
9055 		/* kernel subsystem misconfigured verifier */
9056 		verifier_bug(env, "invalid map_ptr to access map->type");
9057 		return -EFAULT;
9058 	}
9059 
9060 	switch (meta->map.ptr->map_type) {
9061 	case BPF_MAP_TYPE_SOCKMAP:
9062 	case BPF_MAP_TYPE_SOCKHASH:
9063 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9064 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9065 		} else {
9066 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9067 			return -EINVAL;
9068 		}
9069 		break;
9070 	case BPF_MAP_TYPE_BLOOM_FILTER:
9071 		if (is_helper_call(meta, BPF_FUNC_map_peek_elem))
9072 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9073 		break;
9074 	default:
9075 		break;
9076 	}
9077 	return 0;
9078 }
9079 
9080 static int resolve_func_arg_type(struct bpf_verifier_env *env,
9081 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
9082 				 struct bpf_call_arg_meta *meta,
9083 				 enum bpf_arg_type *arg_type, u32 *arg_size);
9084 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9085 				     argno_t argno, enum bpf_arg_type arg_type,
9086 				     const struct btf *arg_btf, u32 arg_btf_id,
9087 				     struct bpf_call_arg_meta *meta, int insn_idx);
9088 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf,
9089 					const struct btf_param *arg);
9090 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9091 					  const struct btf_param *arg,
9092 					  const char *name);
9093 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta);
9094 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta);
9095 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta);
9096 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta);
9097 static bool is_bpf_obj_drop_kfunc(u32 func_id);
9098 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id);
9099 static bool is_bpf_rbtree_add_kfunc(u32 func_id);
9100 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta);
9101 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);
9102 static int process_irq_flag(struct bpf_verifier_env *env,
9103 			    struct bpf_reg_state *reg, argno_t argno,
9104 			    struct bpf_call_arg_meta *meta);
9105 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
9106 					   struct bpf_reg_state *reg,
9107 					   argno_t argno,
9108 					   struct bpf_call_arg_meta *meta);
9109 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
9110 					     struct bpf_reg_state *reg,
9111 					     argno_t argno,
9112 					     struct bpf_call_arg_meta *meta);
9113 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
9114 					   struct bpf_reg_state *reg,
9115 					   argno_t argno,
9116 					   struct bpf_call_arg_meta *meta);
9117 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
9118 					     struct bpf_reg_state *reg,
9119 					     argno_t argno,
9120 					     struct bpf_call_arg_meta *meta);
9121 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env);
9122 
9123 struct bpf_reg_types {
9124 	const enum bpf_reg_type types[10];
9125 	u32 *btf_id;
9126 };
9127 
9128 static const struct bpf_reg_types sock_types = {
9129 	.types = {
9130 		PTR_TO_SOCK_COMMON,
9131 		PTR_TO_SOCKET,
9132 		PTR_TO_TCP_SOCK,
9133 		PTR_TO_XDP_SOCK,
9134 	},
9135 };
9136 
9137 #ifdef CONFIG_NET
9138 static const struct bpf_reg_types btf_id_sock_common_types = {
9139 	.types = {
9140 		PTR_TO_SOCK_COMMON,
9141 		PTR_TO_SOCKET,
9142 		PTR_TO_TCP_SOCK,
9143 		PTR_TO_XDP_SOCK,
9144 		PTR_TO_BTF_ID,
9145 		PTR_TO_BTF_ID | PTR_TRUSTED,
9146 	},
9147 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9148 };
9149 #endif
9150 
9151 static const struct bpf_reg_types mem_types = {
9152 	.types = {
9153 		PTR_TO_STACK,
9154 		PTR_TO_PACKET,
9155 		PTR_TO_PACKET_META,
9156 		PTR_TO_MAP_KEY,
9157 		PTR_TO_MAP_VALUE,
9158 		PTR_TO_MEM,
9159 		PTR_TO_MEM | MEM_RINGBUF,
9160 		PTR_TO_BUF,
9161 		PTR_TO_BTF_ID | PTR_TRUSTED,
9162 		PTR_TO_CTX,
9163 	},
9164 };
9165 
9166 static const struct bpf_reg_types map_value_or_alloc_obj_types = {
9167 	.types = {
9168 		PTR_TO_MAP_VALUE,
9169 		PTR_TO_BTF_ID | MEM_ALLOC,
9170 	}
9171 };
9172 
9173 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9174 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9175 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9176 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9177 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9178 static const struct bpf_reg_types btf_ptr_types = {
9179 	.types = {
9180 		PTR_TO_BTF_ID,
9181 		PTR_TO_BTF_ID | PTR_TRUSTED,
9182 		PTR_TO_BTF_ID | MEM_RCU,
9183 	},
9184 };
9185 static const struct bpf_reg_types percpu_btf_ptr_types = {
9186 	.types = {
9187 		PTR_TO_BTF_ID | MEM_PERCPU,
9188 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9189 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9190 	}
9191 };
9192 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9193 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9194 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9195 static const struct bpf_reg_types map_value_types = { .types = { PTR_TO_MAP_VALUE } };
9196 static const struct bpf_reg_types arena_types = {
9197 	.types = {
9198 		PTR_TO_ARENA,
9199 		SCALAR_VALUE,
9200 	}
9201 };
9202 static const struct bpf_reg_types ctx_out_types = {
9203 	.types = { PTR_TO_MEM | MEM_RDONLY | PTR_TRUSTED },
9204 };
9205 
9206 static const struct bpf_reg_types alloc_obj_drop_types = {
9207 	.types = {
9208 		PTR_TO_BTF_ID | MEM_ALLOC,
9209 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU,
9210 	}
9211 };
9212 
9213 static const struct bpf_reg_types alloc_obj_types = {
9214 	.types = {
9215 		PTR_TO_BTF_ID | MEM_ALLOC,
9216 		PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU,
9217 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9218 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9219 	}
9220 };
9221 
9222 static const struct bpf_reg_types kptr_xchg_dest_types = {
9223 	.types = {
9224 		PTR_TO_MAP_VALUE,
9225 		PTR_TO_BTF_ID | MEM_ALLOC,
9226 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
9227 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
9228 	}
9229 };
9230 static const struct bpf_reg_types dynptr_types = {
9231 	.types = {
9232 		PTR_TO_STACK,
9233 		CONST_PTR_TO_DYNPTR,
9234 	}
9235 };
9236 
9237 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9238 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9239 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9240 	[ARG_MEM_SIZE]			= &scalar_types,
9241 	[ARG_MEM_SIZE_OR_ZERO]		= &scalar_types,
9242 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9243 	[ARG_SCALAR]			= &scalar_types,
9244 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9245 	[ARG_PTR_TO_CTX]		= &context_types,
9246 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9247 #ifdef CONFIG_NET
9248 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9249 #endif
9250 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9251 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9252 	[ARG_PTR_TO_SPIN_LOCK]		= &map_value_or_alloc_obj_types,
9253 	[ARG_PTR_TO_MEM]		= &mem_types,
9254 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9255 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9256 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9257 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9258 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9259 	[ARG_PTR_TO_TIMER]		= &map_value_types,
9260 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9261 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9262 	[ARG_CONST_SCALAR]		= &scalar_types,
9263 	[ARG_CONST_MEM_SIZE]		= &scalar_types,
9264 	[ARG_PTR_TO_ALLOC_BTF_ID]	= &alloc_obj_drop_types,
9265 	[ARG_PTR_TO_REFCOUNTED_KPTR]	= &alloc_obj_types,
9266 	[ARG_PTR_TO_ITER]		= &stack_ptr_types,
9267 	[ARG_PTR_TO_LIST_HEAD]		= &map_value_or_alloc_obj_types,
9268 	[ARG_PTR_TO_LIST_NODE]		= &alloc_obj_types,
9269 	[ARG_PTR_TO_RB_ROOT]		= &map_value_or_alloc_obj_types,
9270 	[ARG_PTR_TO_RB_NODE]		= &alloc_obj_types,
9271 	[ARG_PTR_TO_RES_SPIN_LOCK]	= &map_value_or_alloc_obj_types,
9272 	[ARG_PTR_TO_WORKQUEUE]		= &map_value_types,
9273 	[ARG_PTR_TO_TASK_WORK]		= &map_value_types,
9274 	[ARG_PTR_TO_RCU_HEAD]		= &map_value_types,
9275 	[ARG_PTR_TO_IRQ_FLAG]		= &stack_ptr_types,
9276 	[ARG_PTR_TO_ARENA]		= &arena_types,
9277 	[ARG_PTR_TO_CTX_OUT]		= &ctx_out_types,
9278 };
9279 
9280 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
9281 			      const char *call_name, const char *reason,
9282 			      const char *suggestion)
9283 {
9284 	int arg = arg_from_argno(argno);
9285 	int regno = reg_from_argno(argno);
9286 	int stack_slot = -1;
9287 
9288 	if (arg < 0 && regno >= BPF_REG_1 && regno <= BPF_REG_5)
9289 		arg = regno;
9290 	if (arg > MAX_BPF_FUNC_REG_ARGS)
9291 		stack_slot = arg - MAX_BPF_FUNC_REG_ARGS - 1;
9292 
9293 	bpf_diag_call_type(env, insn_idx, arg, regno, stack_slot,
9294 			   call_name && *call_name ? call_name : "call",
9295 			   reg_arg_name(env, argno), reason, suggestion);
9296 }
9297 
9298 static const char *bpf_diag_arg_name(struct bpf_verifier_env *env, argno_t argno)
9299 {
9300 	return bpf_diag_fmt(env, "%s", reg_arg_name(env, argno));
9301 }
9302 
9303 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
9304 						 argno_t argno, const char *call_name,
9305 						 const char *suggestion, const char *fmt, ...)
9306 {
9307 	const char *reason;
9308 	va_list args;
9309 
9310 	va_start(args, fmt);
9311 	reason = bpf_diag_vfmt(env, fmt, args);
9312 	va_end(args);
9313 
9314 	bpf_diag_call_arg(env, insn_idx, argno, call_name, reason, suggestion);
9315 }
9316 
9317 static int check_func_arg_nullability(struct bpf_verifier_env *env,
9318 				      struct bpf_reg_state *reg, u32 arg, argno_t argno,
9319 				      enum bpf_arg_type arg_type,
9320 				      struct bpf_call_arg_meta *meta, int insn_idx)
9321 {
9322 	const char *expected_type = "pointer";
9323 
9324 	if (arg_type_is_scalar(arg_type) || type_may_be_null(arg_type) ||
9325 	    (!bpf_register_is_null(reg) && !type_may_be_null(reg->type)))
9326 		return 0;
9327 
9328 	if (meta->btf) {
9329 		u32 arg_btf_id;
9330 
9331 		arg_btf_id = btf_params(meta->func_proto)[arg].type;
9332 		expected_type = bpf_diag_fmt(env, "value of type %s",
9333 					     bpf_diag_fmt_btf_type(env, meta->btf, arg_btf_id));
9334 	}
9335 
9336 	verbose(env, "Possibly NULL pointer passed to trusted %s\n",
9337 		reg_arg_name(env, argno));
9338 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9339 			      "Add a NULL check and make the call only on the non-NULL path.",
9340 			      "the pointer may be NULL, but this call requires a non-NULL %s",
9341 			      expected_type);
9342 	return -EACCES;
9343 }
9344 
9345 static int check_func_arg_release(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9346 				  u32 arg, argno_t argno, enum bpf_arg_type arg_type,
9347 				  struct bpf_call_arg_meta *meta, int insn_idx)
9348 {
9349 	const char *expected_type = "pointer";
9350 
9351 	if (!arg_type_is_release(arg_type))
9352 		return 0;
9353 
9354 	if (arg_type_is_dynptr(arg_type) || reg_is_referenced(env, reg) ||
9355 	    bpf_register_is_null(reg))
9356 		return 0;
9357 
9358 	verbose(env, "release function %s expects referenced PTR_TO_BTF_ID passed to %s\n",
9359 		meta->func_name, reg_arg_name(env, argno));
9360 
9361 	if (is_kfunc(meta)) {
9362 		const struct btf_param *btf_arg;
9363 		const struct btf_type *t;
9364 		u32 ref_id;
9365 
9366 		btf_arg = &btf_params(meta->func_proto)[arg];
9367 		ref_id = btf_arg->type;
9368 		t = btf_type_skip_modifiers(meta->btf, btf_arg->type, NULL);
9369 		if (btf_type_is_ptr(t))
9370 			btf_type_skip_modifiers(meta->btf, t->type, &ref_id);
9371 		expected_type = bpf_diag_fmt(env, "value of type %s",
9372 					     bpf_diag_fmt_btf_type(env, meta->btf, ref_id));
9373 	}
9374 
9375 	bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9376 			      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.",
9377 					   expected_type),
9378 			      "release functions require a value that owns a live resource returned by a matching acquire function");
9379 	return -EINVAL;
9380 }
9381 
9382 static const char *bpf_diag_expected_reg_types(struct bpf_verifier_env *env,
9383 					       const enum bpf_reg_type *types, int count)
9384 {
9385 	size_t len = 0, size = 1;
9386 	char *buf;
9387 	int i;
9388 
9389 	for (i = 0; i < count; i++)
9390 		size += strlen(reg_type_str(env, types[i])) + (i ? 2 : 0);
9391 
9392 	buf = bpf_diag_fmt_buf(env, size);
9393 	if (!buf)
9394 		return "";
9395 
9396 	for (i = 0; i < count; i++)
9397 		len += scnprintf(buf + len, size - len, "%s%s", i ? ", " : "",
9398 				 reg_type_str(env, types[i]));
9399 	return buf;
9400 }
9401 
9402 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
9403 			  enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
9404 {
9405 	enum bpf_reg_type expected, type = reg->type;
9406 	const struct bpf_reg_types *compatible;
9407 	const char *actual, *accepted;
9408 	int i, j;
9409 
9410 	compatible = compatible_reg_types[base_type(arg_type)];
9411 	if (!compatible) {
9412 		verifier_bug(env, "unsupported arg type %d", arg_type);
9413 		return -EFAULT;
9414 	}
9415 	if (is_kfunc(meta) && base_type(arg_type) == ARG_PTR_TO_BTF_ID &&
9416 	    (base_type(type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(type)]))
9417 		goto found;
9418 
9419 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9420 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9421 	 *
9422 	 * Same for MAYBE_NULL:
9423 	 *
9424 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9425 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9426 	 *
9427 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9428 	 *
9429 	 * Therefore we fold these flags depending on the arg_type before comparison.
9430 	 */
9431 	if (arg_type & MEM_RDONLY)
9432 		type &= ~MEM_RDONLY;
9433 	if (arg_type & PTR_MAYBE_NULL)
9434 		type &= ~PTR_MAYBE_NULL;
9435 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9436 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9437 	/* Allow allocated memory for BTF-defined ARG_PTR_TO_MEM but not helpers. */
9438 	if (!is_helper(meta) && base_type(arg_type) == ARG_PTR_TO_MEM &&
9439 	    type_is_ptr_alloc_obj(type))
9440 		type = PTR_TO_MEM;
9441 
9442 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9443 	if (is_helper_call(meta, BPF_FUNC_kptr_xchg) && type_is_alloc(type) &&
9444 	    reg_from_argno(argno) == BPF_REG_2) {
9445 		type &= ~MEM_ALLOC;
9446 		type &= ~MEM_PERCPU;
9447 	}
9448 
9449 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9450 		expected = compatible->types[i];
9451 		if (expected == NOT_INIT)
9452 			break;
9453 
9454 		if (type == expected)
9455 			goto found;
9456 	}
9457 
9458 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
9459 	for (j = 0; j + 1 < i; j++)
9460 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9461 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9462 	actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type));
9463 	accepted = bpf_diag_expected_reg_types(env, compatible->types, i);
9464 	bpf_diag_call_arg_fmt(env, env->insn_idx, argno, meta->func_name,
9465 			      bpf_diag_fmt(env, "Pass %s.", bpf_diag_arg_type_plain(arg_type)),
9466 			      "it has type %s, but this argument accepts %s",
9467 			      actual, accepted);
9468 	return -EACCES;
9469 
9470 found:
9471 	return 0;
9472 }
9473 
9474 static struct btf_field *
9475 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9476 {
9477 	struct btf_field *field;
9478 	struct btf_record *rec;
9479 
9480 	rec = reg_btf_record(reg);
9481 	if (!rec)
9482 		return NULL;
9483 
9484 	field = btf_record_find(rec, off, fields);
9485 	if (!field)
9486 		return NULL;
9487 
9488 	return field;
9489 }
9490 
9491 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9492 				  const struct bpf_reg_state *reg, argno_t argno,
9493 				  enum bpf_arg_type arg_type)
9494 {
9495 	u32 type = reg->type;
9496 
9497 	/* When referenced register is passed to release function, its fixed
9498 	 * offset must be 0.
9499 	 *
9500 	 * We will check arg_type_is_release reg has id when storing
9501 	 * meta->release_regno.
9502 	 */
9503 	if (arg_type_is_release(arg_type)) {
9504 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9505 		 * may not directly point to the object being released, but to
9506 		 * dynptr pointing to such object, which might be at some offset
9507 		 * on the stack. In that case, we simply to fallback to the
9508 		 * default handling.
9509 		 */
9510 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9511 			return 0;
9512 
9513 		/* Doing check_ptr_off_reg check for the offset will catch this
9514 		 * because fixed_off_ok is false, but checking here allows us
9515 		 * to give the user a better error message.
9516 		 */
9517 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
9518 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
9519 				reg_arg_name(env, argno));
9520 			return -EINVAL;
9521 		}
9522 	}
9523 
9524 	switch (type) {
9525 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9526 	case PTR_TO_STACK:
9527 	case PTR_TO_PACKET:
9528 	case PTR_TO_PACKET_META:
9529 	case PTR_TO_MAP_KEY:
9530 	case PTR_TO_MAP_VALUE:
9531 	case PTR_TO_MEM:
9532 	case PTR_TO_MEM | MEM_RDONLY:
9533 	case PTR_TO_MEM | MEM_RINGBUF:
9534 	case PTR_TO_BUF:
9535 	case PTR_TO_BUF | MEM_RDONLY:
9536 	case PTR_TO_ARENA:
9537 	case SCALAR_VALUE:
9538 		return 0;
9539 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9540 	 * fixed offset.
9541 	 */
9542 	case PTR_TO_BTF_ID:
9543 	case PTR_TO_BTF_ID | MEM_ALLOC:
9544 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9545 	case PTR_TO_BTF_ID | MEM_RCU:
9546 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9547 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9548 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9549 		 * its fixed offset must be 0. bpf_refcount_acquire() returns the
9550 		 * pointer it was given while incrementing the refcount at the
9551 		 * refcount field offset, so it needs a zero offset too. In the
9552 		 * other cases, fixed offset can be non-zero. var_off always must
9553 		 * be 0 for PTR_TO_BTF_ID, hence we still need to do checks
9554 		 * instead of returning.
9555 		 */
9556 		return __check_ptr_off_reg(env, reg, argno,
9557 					   base_type(arg_type) != ARG_PTR_TO_REFCOUNTED_KPTR);
9558 	case PTR_TO_CTX:
9559 		/*
9560 		 * Allow fixed and variable offsets for syscall context, but
9561 		 * only when the argument is passed as memory, not ctx,
9562 		 * otherwise we may get modified ctx in tail called programs and
9563 		 * global subprogs (that may act as extension prog hooks).
9564 		 */
9565 		if (base_type(arg_type) != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
9566 			return 0;
9567 		fallthrough;
9568 	default:
9569 		return __check_ptr_off_reg(env, reg, argno, false);
9570 	}
9571 }
9572 
9573 static int check_arg_const_str(struct bpf_verifier_env *env,
9574 			       struct bpf_reg_state *reg, argno_t argno)
9575 {
9576 	struct bpf_map *map = reg->map_ptr;
9577 	int err;
9578 	int map_off;
9579 	u64 map_addr;
9580 	char *str_ptr;
9581 	u32 cnt;
9582 
9583 	if (reg->type != PTR_TO_MAP_VALUE)
9584 		return -EINVAL;
9585 
9586 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9587 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
9588 			reg_arg_name(env, argno));
9589 		return -EACCES;
9590 	}
9591 
9592 	if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
9593 		verbose(env, "%s points to percpu_array map which cannot be used as const string\n",
9594 			reg_arg_name(env, argno));
9595 		return -EACCES;
9596 	}
9597 
9598 	if (!bpf_map_is_rdonly(map)) {
9599 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
9600 		return -EACCES;
9601 	}
9602 
9603 	if (!tnum_is_const(reg->var_off)) {
9604 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
9605 		return -EACCES;
9606 	}
9607 
9608 	if (!map->ops->map_direct_value_addr) {
9609 		verbose(env, "no direct value access support for this map type\n");
9610 		return -EACCES;
9611 	}
9612 
9613 	err = check_map_access(env, reg, argno, 0,
9614 			       map->value_size - reg->var_off.value, false,
9615 			       ACCESS_HELPER);
9616 	if (err)
9617 		return err;
9618 
9619 	map_off = reg->var_off.value;
9620 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9621 	if (err) {
9622 		verbose(env, "direct value access on string failed\n");
9623 		return err;
9624 	}
9625 
9626 	str_ptr = (char *)(long)(map_addr);
9627 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9628 		verbose(env, "string is not zero-terminated\n");
9629 		return -EINVAL;
9630 	}
9631 	/* the bytes of a pointer to a function are not known until the program is jitted */
9632 	if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) {
9633 		verbose(env, "string overlaps with a pointer to a function\n");
9634 		return -EACCES;
9635 	}
9636 	return 0;
9637 }
9638 
9639 /* Returns constant key value in `value` if possible, else negative error */
9640 static int get_constant_map_key(struct bpf_verifier_env *env,
9641 				struct bpf_reg_state *key,
9642 				u32 key_size,
9643 				s64 *value)
9644 {
9645 	struct bpf_func_state *state = bpf_func(env, key);
9646 	struct bpf_stack_state *ss;
9647 	struct bpf_reg_state *reg;
9648 	int slot, spi, off;
9649 	int spill_size = 0;
9650 	int zero_size = 0;
9651 	int stack_off;
9652 	int i, err;
9653 	u8 *stype;
9654 
9655 	if (!env->bpf_capable)
9656 		return -EOPNOTSUPP;
9657 	if (key->type != PTR_TO_STACK)
9658 		return -EOPNOTSUPP;
9659 	if (!tnum_is_const(key->var_off))
9660 		return -EOPNOTSUPP;
9661 
9662 	stack_off = key->var_off.value;
9663 	slot = -stack_off - 1;
9664 	spi = slot / BPF_REG_SIZE;
9665 	off = slot % BPF_REG_SIZE;
9666 	ss = bpf_stack_slot(state, spi);
9667 	stype = ss->slot_type;
9668 
9669 	/* First handle precisely tracked STACK_ZERO */
9670 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9671 		zero_size++;
9672 	if (zero_size >= key_size) {
9673 		*value = 0;
9674 		return 0;
9675 	}
9676 
9677 	/* Check that stack contains a scalar spill of expected size */
9678 	if (!bpf_is_spilled_scalar_reg(ss))
9679 		return -EOPNOTSUPP;
9680 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9681 		spill_size++;
9682 	if (spill_size != key_size)
9683 		return -EOPNOTSUPP;
9684 
9685 	reg = &ss->spilled_ptr;
9686 	if (!tnum_is_const(reg->var_off))
9687 		/* Stack value not statically known */
9688 		return -EOPNOTSUPP;
9689 
9690 	/* We are relying on a constant value. So mark as precise
9691 	 * to prevent pruning on it.
9692 	 */
9693 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
9694 	err = mark_chain_precision_batch(env, env->cur_state);
9695 	if (err < 0)
9696 		return err;
9697 
9698 	*value = reg->var_off.value;
9699 	return 0;
9700 }
9701 
9702 static bool can_elide_value_nullness(const struct bpf_map *map);
9703 
9704 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
9705 			       argno_t argno, struct bpf_call_arg_meta *meta)
9706 {
9707 	/* Use map_uid (which is unique id of inner map) to reject:
9708 	 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9709 	 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9710 	 * if (inner_map1 && inner_map2) {
9711 	 *     timer = bpf_map_lookup_elem(inner_map1);
9712 	 *     if (timer)
9713 	 *         // mismatch would have been allowed
9714 	 *         bpf_timer_init(timer, inner_map2);
9715 	 * }
9716 	 *
9717 	 * Comparing map_ptr is enough to distinguish normal and outer maps.
9718 	 */
9719 	if (meta->map.ptr &&
9720 	    (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) {
9721 		argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1);
9722 		struct btf_record *rec = meta->map.ptr->record;
9723 		const char *obj_name = "workqueue";
9724 
9725 		if (rec->timer_off >= 0)
9726 			obj_name = "timer";
9727 		else if (rec->task_work_off >= 0)
9728 			obj_name = "bpf_task_work";
9729 		else if (rec->rcu_head_off >= 0)
9730 			obj_name = "bpf_rcu_head";
9731 
9732 		verbose(env, "%s pointer in %s map_uid=%d ",
9733 			obj_name, reg_arg_name(env, obj_argno), meta->map.uid);
9734 		verbose(env, "doesn't match map pointer in %s map_uid=%d\n",
9735 			reg_arg_name(env, argno), reg->map_uid);
9736 		return -EINVAL;
9737 	}
9738 
9739 	meta->map.ptr = reg->map_ptr;
9740 	meta->map.uid = reg->map_uid;
9741 	return 0;
9742 }
9743 
9744 /*
9745  * MEM_WRITE alone denotes an input/output buffer. MEM_UNINIT marks an output
9746  * whose incoming contents are not read.
9747  */
9748 static enum bpf_access_type func_arg_access_type(enum bpf_arg_type arg_type)
9749 {
9750 	if (!(arg_type & MEM_WRITE))
9751 		return BPF_READ;
9752 	if (arg_type & MEM_UNINIT)
9753 		return BPF_WRITE;
9754 	return BPF_READ | BPF_WRITE;
9755 }
9756 
9757 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,
9758 			  struct bpf_call_arg_meta *meta,
9759 			  int insn_idx)
9760 {
9761 	const struct btf_param *btf_arg = is_kfunc(meta) ?
9762 					  &btf_params(meta->func_proto)[arg] : NULL;
9763 	const struct bpf_func_proto *fn = meta->fn;
9764 	struct bpf_func_state *caller = cur_func(env);
9765 	struct bpf_reg_state *regs = cur_regs(env);
9766 	argno_t argno = argno_from_arg(slot + 1);
9767 	struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, slot);
9768 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9769 	int regno = reg_from_argno(argno);
9770 	u32 arg_size = arg_type & MEM_FIXED_SIZE ? fn->arg_size[arg] : 0;
9771 	u32 key_size;
9772 	int err = 0;
9773 
9774 	if (arg_type == ARG_PTR_TO_PROG_AUX) {
9775 		cur_aux(env)->arg_prog = regno;
9776 		return 0;
9777 	}
9778 
9779 	if (arg_type == ARG_IGNORE)
9780 		return 0;
9781 
9782 	if (regno >= 0) {
9783 		err = check_reg_arg(env, regno, SRC_OP);
9784 		if (err)
9785 			return err;
9786 	}
9787 
9788 	/* Preserve the legacy helper behavior for privileged pointer leaks. */
9789 	if (arg_type == ARG_ANYTHING) {
9790 		if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
9791 			verbose(env, "%s leaks addr into helper function\n",
9792 				reg_arg_name(env, argno));
9793 			return -EACCES;
9794 		}
9795 		return 0;
9796 	}
9797 
9798 	err = resolve_func_arg_type(env, reg, arg, argno, meta, &arg_type, &arg_size);
9799 	if (err)
9800 		return err;
9801 
9802 	/*
9803 	 * A slice of a packet is packet data under another name. A helper which
9804 	 * may reallocate the packet must not go on reading from the old one.
9805 	 */
9806 	if (is_helper(meta) && reg_is_dynptr_slice_pkt(reg) &&
9807 	    bpf_helper_changes_pkt_data(meta->func_id)) {
9808 		verbose(env, "function access to the packet is not allowed\n");
9809 		return -EACCES;
9810 	}
9811 
9812 	if (arg_type_is_raw_mem(arg_type))
9813 		meta->arg_raw_mem.mask |= BIT(slot);
9814 
9815 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) {
9816 		err = mark_arg_precision(env, argno);
9817 		if (err)
9818 			return err;
9819 		return 0;
9820 	}
9821 
9822 	err = check_func_arg_nullability(env, reg, arg, argno, arg_type, meta, insn_idx);
9823 	if (err)
9824 		return err;
9825 
9826 	err = check_reg_type(env, reg, argno, arg_type, meta);
9827 	if (err)
9828 		return err;
9829 
9830 	err = check_func_arg_reg_off(env, reg, argno, arg_type);
9831 	if (err)
9832 		return err;
9833 
9834 	err = check_func_arg_release(env, reg, arg, argno, arg_type, meta, insn_idx);
9835 	if (err)
9836 		return err;
9837 
9838 	if (reg_is_referenced(env, reg))
9839 		update_ref_obj(&meta->ref_obj, reg);
9840 
9841 	switch (base_type(arg_type)) {
9842 	case ARG_CONST_SCALAR:
9843 		err = process_const_arg(env, reg, argno, meta);
9844 		if (err < 0) {
9845 			if (err == -EINVAL)
9846 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9847 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
9848 						      "the function requires this scalar argument to be a verifier-known constant, but %s is variable on this path",
9849 						      reg_arg_name(env, argno));
9850 			return err;
9851 		}
9852 		break;
9853 	case ARG_SCALAR:
9854 		break;
9855 	case ARG_CONST_MAP_PTR:
9856 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9857 		err = process_map_ptr_arg(env, reg, argno, meta);
9858 		if (err)
9859 			return err;
9860 		break;
9861 	case ARG_PTR_TO_MAP_KEY:
9862 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9863 		 * check that [key, key + map->key_size) are within
9864 		 * stack limits and initialized
9865 		 */
9866 		if (!meta->map.ptr) {
9867 			/* in function declaration map_ptr must come before
9868 			 * map_key, so that it's verified and known before
9869 			 * we have to check map_key here. Otherwise it means
9870 			 * that kernel subsystem misconfigured verifier
9871 			 */
9872 			verifier_bug(env, "invalid map_ptr to access map->key");
9873 			return -EFAULT;
9874 		}
9875 		key_size = meta->map.ptr->key_size;
9876 		err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, meta,
9877 					      NULL);
9878 		if (err)
9879 			return err;
9880 		if (can_elide_value_nullness(meta->map.ptr)) {
9881 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9882 			if (err < 0) {
9883 				meta->const_map_key = -1;
9884 				if (err == -EOPNOTSUPP)
9885 					err = 0;
9886 				else
9887 					return err;
9888 			}
9889 		}
9890 		break;
9891 	case ARG_PTR_TO_MAP_VALUE:
9892 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
9893 			return 0;
9894 
9895 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9896 		 * check [value, value + map->value_size) validity
9897 		 */
9898 		if (!meta->map.ptr) {
9899 			/* kernel subsystem misconfigured verifier */
9900 			verifier_bug(env, "invalid map_ptr to access map->value");
9901 			return -EFAULT;
9902 		}
9903 
9904 		err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size,
9905 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9906 					      false, meta, NULL);
9907 		break;
9908 	case ARG_PTR_TO_BTF_ID:
9909 	case ARG_PTR_TO_BTF_ID_SOCK_COMMON:
9910 	{
9911 		const u32 *arg_btf_id = fn->arg_btf_id[arg];
9912 		const struct btf *arg_btf = is_kfunc(meta) ? meta->btf : btf_vmlinux;
9913 		enum bpf_reg_type reg_type;
9914 
9915 		if (!meta->btf) {
9916 			const struct bpf_reg_types *compatible;
9917 
9918 			if (base_type(reg->type) != PTR_TO_BTF_ID)
9919 				break;
9920 
9921 			if (is_helper_call(meta, BPF_FUNC_kptr_xchg))
9922 				return map_kptr_match_type(env, meta->kptr_field, reg, regno) ?
9923 				       -EACCES : 0;
9924 
9925 			if (!arg_btf_id) {
9926 				compatible = compatible_reg_types[base_type(arg_type)];
9927 				if (!compatible->btf_id) {
9928 					verifier_bug(env, "missing arg compatible BTF ID");
9929 					return -EFAULT;
9930 				}
9931 				arg_btf_id = compatible->btf_id;
9932 			}
9933 			if (arg_btf_id == BPF_PTR_POISON) {
9934 				verbose(env, "verifier internal error:");
9935 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
9936 					reg_arg_name(env, argno));
9937 				return -EACCES;
9938 			}
9939 		}
9940 
9941 		reg_type = reg->type & ~(arg_type & PTR_MAYBE_NULL);
9942 		if ((arg_type & PTR_TRUSTED) &&
9943 		    (!is_trusted_reg_type(env, reg, reg_type) ||
9944 		     bpf_type_has_unsafe_modifiers(reg_type))) {
9945 			if (!(arg_type & MEM_RCU)) {
9946 				const char *actual_type, *arg_name, *expected_type;
9947 
9948 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
9949 				verbose(env, "%s must be referenced or trusted\n",
9950 					reg_arg_name(env, argno));
9951 				arg_name = reg_arg_name(env, argno);
9952 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
9953 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9954 						      "Pass a pointer acquired from a verifier-tracked source, or call this function only inside the required protection if it accepts RCU pointers.",
9955 						      "the function requires a trusted or resource-owning pointer to %s, but %s is %s",
9956 						      expected_type, arg_name, actual_type);
9957 				return -EINVAL;
9958 			}
9959 			if (!is_rcu_reg(reg)) {
9960 				const char *actual_type, *arg_name, *expected_type;
9961 
9962 				expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id);
9963 				verbose(env, "%s must be a rcu pointer\n",
9964 					reg_arg_name(env, argno));
9965 				arg_name = reg_arg_name(env, argno);
9966 				actual_type = bpf_diag_reg_type_plain(env, reg->type);
9967 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
9968 						      "Use this function with a pointer that is valid in an RCU read lock region.",
9969 						      "the function requires an RCU-protected pointer to %s, but %s is %s",
9970 						      expected_type, arg_name, actual_type);
9971 				return -EINVAL;
9972 			}
9973 		}
9974 
9975 		err = process_arg_ptr_to_btf_id(env, reg, argno, arg_type, arg_btf,
9976 						*arg_btf_id, meta, insn_idx);
9977 		if (err < 0)
9978 			return err;
9979 		break;
9980 	}
9981 	case ARG_PTR_TO_PERCPU_BTF_ID:
9982 		if (!reg->btf_id) {
9983 			verbose(env, "Helper has invalid btf_id in %s\n", reg_arg_name(env, argno));
9984 			return -EACCES;
9985 		}
9986 		meta->ret_btf = reg->btf;
9987 		meta->ret_btf_id = reg->btf_id;
9988 		break;
9989 	case ARG_PTR_TO_SPIN_LOCK:
9990 		if (in_rbtree_lock_required_cb(env)) {
9991 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9992 			return -EACCES;
9993 		}
9994 		if (is_helper_call(meta, BPF_FUNC_spin_lock)) {
9995 			err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK);
9996 			if (err)
9997 				return err;
9998 		} else if (is_helper_call(meta, BPF_FUNC_spin_unlock)) {
9999 			err = process_spin_lock(env, reg, argno, 0);
10000 			if (err)
10001 				return err;
10002 		} else {
10003 			verifier_bug(env, "spin lock arg on unexpected helper");
10004 			return -EFAULT;
10005 		}
10006 		break;
10007 	case ARG_PTR_TO_TIMER:
10008 		err = process_timer_func(env, reg, argno, &meta->map);
10009 		if (err)
10010 			return err;
10011 		break;
10012 	case ARG_PTR_TO_CTX:
10013 		if (is_bpf_cast_to_kern_ctx_kfunc(meta)) {
10014 			err = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10015 			if (err < 0)
10016 				return -EINVAL;
10017 			meta->ret_btf_id = err;
10018 		}
10019 		break;
10020 	case ARG_PTR_TO_ARENA:
10021 		break;
10022 	case ARG_PTR_TO_ALLOC_BTF_ID:
10023 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
10024 			if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
10025 				verbose(env, "%s expected for bpf_obj_drop()\n",
10026 					reg_arg_name(env, argno));
10027 				return -EINVAL;
10028 			}
10029 		} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
10030 			if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
10031 				verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
10032 					reg_arg_name(env, argno));
10033 				return -EINVAL;
10034 			}
10035 		}
10036 		if (!reg_is_referenced(env, reg)) {
10037 			verbose(env, "allocated object must be referenced\n");
10038 			bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10039 					      "Pass the owned object pointer before it is released or transferred.",
10040 					      "the allocated object pointer in %s must still carry verifier-tracked ownership, but this pointer no longer owns a live resource",
10041 					      reg_arg_name(env, argno));
10042 			return -EINVAL;
10043 		}
10044 		if (meta->btf == btf_vmlinux) {
10045 			meta->arg_btf = reg->btf;
10046 			meta->arg_btf_id = reg->btf_id;
10047 		}
10048 		break;
10049 	case ARG_PTR_TO_FUNC:
10050 		meta->subprogno = reg->subprogno;
10051 		break;
10052 	case ARG_PTR_TO_MEM:
10053 	{
10054 		enum bpf_access_type access_type;
10055 		bool known_memory;
10056 
10057 		/* The access to this pointer is only checked when we hit the
10058 		 * next is_mem_size argument below.
10059 		 */
10060 		if (!(arg_type & MEM_FIXED_SIZE))
10061 			break;
10062 
10063 		access_type = func_arg_access_type(arg_type);
10064 
10065 		err = check_mem_reg(env, reg, argno, arg_size, access_type, meta, &known_memory);
10066 		if (err < 0) {
10067 			if (known_memory)
10068 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10069 					"Pass memory with at least the required number of accessible bytes and suitable read or write access.",
10070 					"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",
10071 					arg_size,
10072 					bpf_diag_reg_type_plain(env, reg->type));
10073 			else
10074 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10075 					"Pass stack, map, context, or other verifier-known memory of the expected type and size, not an integer cast to a pointer.",
10076 					"the function expects %u bytes of memory, but it is %s and not verifier-known memory",
10077 					arg_size,
10078 					bpf_diag_reg_type_plain(env, reg->type));
10079 			return err;
10080 		}
10081 		/*
10082 		 * PTR_TO_PACKET gets passed as PTR_TO_MEM, preventing us from adjusting
10083 		 * bounds tracking information.
10084 		 */
10085 		if (is_subprog(meta) && meta->subprog_may_change_pkt &&
10086 		    (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))) {
10087 			verbose(env,
10088 				"cannot pass packet pointer %s to %s(): function may change packet data\n",
10089 				reg_arg_name(env, argno), meta->func_name);
10090 			return -EINVAL;
10091 		}
10092 		if (arg_type & MEM_ALIGNED)
10093 			err = check_ptr_alignment(env, reg, 0, arg_size, true);
10094 		break;
10095 	}
10096 	case ARG_CONST_MEM_SIZE:
10097 		err = process_const_arg(env, reg, argno, meta);
10098 		if (err < 0) {
10099 			if (err == -EINVAL)
10100 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10101 						      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
10102 						      "the function requires this memory size to be a verifier-known constant, but %s is variable on this path",
10103 						      reg_arg_name(env, argno));
10104 			return err;
10105 		}
10106 		fallthrough;
10107 	case ARG_MEM_SIZE:
10108 	case ARG_MEM_SIZE_OR_ZERO:
10109 	{
10110 		struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, prev_slot);
10111 		argno_t buff_argno = argno_from_arg(prev_slot + 1);
10112 		enum bpf_mem_size_failure failure;
10113 		const char *buff_arg, *size_arg;
10114 		bool zero_size_allowed;
10115 		u32 access_type;
10116 
10117 		if (meta->btf && bpf_register_is_null(buff_reg))
10118 			break;
10119 
10120 		access_type = func_arg_access_type(fn->arg_type[arg - 1]);
10121 
10122 		zero_size_allowed = meta->btf || base_type(arg_type) == ARG_MEM_SIZE_OR_ZERO;
10123 
10124 		err = check_mem_size_reg(env, buff_reg, reg, buff_argno, argno,
10125 					 access_type, zero_size_allowed, meta, &failure);
10126 		if (!err)
10127 			break;
10128 
10129 		buff_arg = bpf_diag_arg_name(env, buff_argno);
10130 		size_arg = bpf_diag_arg_name(env, argno);
10131 		verbose(env, "%s and ", reg_arg_name(env, buff_argno));
10132 		verbose(env, "%s memory, len pair leads to invalid memory access\n",
10133 			reg_arg_name(env, argno));
10134 		if (failure == BPF_MEM_SIZE_FAIL_MEMORY) {
10135 			bpf_diag_call_arg_fmt(env, insn_idx, buff_argno, meta->func_name,
10136 					      "Pass a stack, map, context, or other verifier-known memory pointer, and keep the paired length within that object.",
10137 					      "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",
10138 					      size_arg, buff_arg);
10139 		} else if (failure == BPF_MEM_SIZE_FAIL_SIZE) {
10140 			if (reg_smin(reg) < 0)
10141 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10142 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
10143 					"the memory size in %s may be negative because its signed minimum is %lld",
10144 					size_arg, reg_smin(reg));
10145 			else if (!zero_size_allowed && reg_umin(reg) == 0)
10146 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10147 					"Ensure the memory size is non-zero before this call.",
10148 					"the memory size in %s may be zero, but the function requires a non-zero size",
10149 					size_arg);
10150 			else
10151 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10152 					"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
10153 					"the memory size in %s may reach %llu bytes, but variable memory accesses must stay below %u bytes",
10154 					size_arg, reg_umax(reg), BPF_MAX_VAR_SIZ);
10155 		}
10156 		break;
10157 	}
10158 	case ARG_PTR_TO_DYNPTR: {
10159 		if (is_bpf_dynptr_clone_kfunc(meta) &&
10160 		    (arg_type & MEM_UNINIT)) {
10161 			enum bpf_dynptr_type parent_type = meta->dynptr.type;
10162 
10163 			if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10164 				verifier_bug(env, "no dynptr type for parent of clone");
10165 				return -EFAULT;
10166 			}
10167 
10168 			arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10169 		}
10170 
10171 		err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, meta);
10172 		if (err)
10173 			return err;
10174 		if (!arg && is_kfunc_dynptr_write(meta))
10175 			meta->dynptr_write_type = meta->dynptr.type;
10176 		break;
10177 	}
10178 	case ARG_PTR_TO_ITER:
10179 		if (is_bpf_iter_css_task_new_kfunc(meta) &&
10180 		    !check_css_task_iter_allowlist(env)) {
10181 			verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
10182 			return -EINVAL;
10183 		}
10184 		err = process_iter_arg(env, reg, arg, argno, insn_idx, meta);
10185 		if (err < 0)
10186 			return err;
10187 		break;
10188 	case ARG_PTR_TO_LIST_HEAD:
10189 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10190 		    !reg_is_referenced(env, reg)) {
10191 			verbose(env, "allocated object must be referenced\n");
10192 			return -EINVAL;
10193 		}
10194 		err = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
10195 		if (err < 0)
10196 			return err;
10197 		break;
10198 	case ARG_PTR_TO_RB_ROOT:
10199 		if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
10200 		    !reg_is_referenced(env, reg)) {
10201 			verbose(env, "allocated object must be referenced\n");
10202 			return -EINVAL;
10203 		}
10204 		err = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
10205 		if (err < 0)
10206 			return err;
10207 		break;
10208 	case ARG_PTR_TO_LIST_NODE:
10209 		if (!(is_kfunc_arg_nonown_allowed(meta->btf, btf_arg) &&
10210 		      type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg))) {
10211 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10212 				verbose(env, "%s expected pointer to allocated object\n",
10213 					reg_arg_name(env, argno));
10214 				return -EINVAL;
10215 			}
10216 			if (!reg_is_referenced(env, reg)) {
10217 				verbose(env, "allocated object must be referenced\n");
10218 				return -EINVAL;
10219 			}
10220 		}
10221 		err = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
10222 		if (err < 0)
10223 			return err;
10224 		break;
10225 	case ARG_PTR_TO_RB_NODE:
10226 		if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
10227 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10228 				verbose(env, "%s expected pointer to allocated object\n",
10229 					reg_arg_name(env, argno));
10230 				return -EINVAL;
10231 			}
10232 			if (!reg_is_referenced(env, reg)) {
10233 				verbose(env, "allocated object must be referenced\n");
10234 				return -EINVAL;
10235 			}
10236 		} else {
10237 			if (!type_is_non_owning_ref(reg->type) &&
10238 			    !reg_is_referenced(env, reg)) {
10239 				verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n",
10240 					meta->func_name);
10241 				return -EINVAL;
10242 			}
10243 			if (in_rbtree_lock_required_cb(env)) {
10244 				verbose(env, "%s not allowed in rbtree cb\n", meta->func_name);
10245 				return -EINVAL;
10246 			}
10247 		}
10248 		err = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
10249 		if (err < 0)
10250 			return err;
10251 		break;
10252 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
10253 		if (meta->btf && is_kfunc_arg_scalar_with_name(meta->btf, btf_arg,
10254 							       "rdonly_buf_size"))
10255 			meta->r0_rdonly = true;
10256 		err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem);
10257 		if (err < 0) {
10258 			if (meta->btf && err == -EINVAL)
10259 				bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name,
10260 						      "Pass a verifier-known constant size for this function's buffer argument.",
10261 						      "the function uses this argument as a return-buffer size, but %s is invalid or variable on this path",
10262 						      reg_arg_name(env, argno));
10263 			return err;
10264 		}
10265 		break;
10266 	case ARG_PTR_TO_REFCOUNTED_KPTR:
10267 	{
10268 		struct btf_record *rec;
10269 
10270 		if (!type_is_non_owning_ref(reg->type) && reg_is_referenced(env, reg))
10271 			meta->arg_owning_ref = true;
10272 
10273 		rec = reg_btf_record(reg);
10274 		if (!rec) {
10275 			verifier_bug(env, "Couldn't find btf_record");
10276 			return -EFAULT;
10277 		}
10278 
10279 		if (rec->refcount_off < 0) {
10280 			verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
10281 				reg_arg_name(env, argno));
10282 			return -EINVAL;
10283 		}
10284 
10285 		meta->arg_btf = reg->btf;
10286 		meta->arg_btf_id = reg->btf_id;
10287 		break;
10288 	}
10289 	case ARG_PTR_TO_CONST_STR:
10290 	{
10291 		err = check_arg_const_str(env, reg, argno);
10292 		if (err)
10293 			return err;
10294 		break;
10295 	}
10296 	case ARG_PTR_TO_WORKQUEUE:
10297 		err = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
10298 		if (err < 0)
10299 			return err;
10300 		break;
10301 	case ARG_PTR_TO_TASK_WORK:
10302 		err = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
10303 		if (err < 0)
10304 			return err;
10305 		break;
10306 	case ARG_PTR_TO_RCU_HEAD:
10307 		err = check_map_field_pointer(env, reg, argno, BPF_RCU_HEAD, &meta->map);
10308 		if (err < 0)
10309 			return err;
10310 		break;
10311 	case ARG_PTR_TO_IRQ_FLAG:
10312 		err = process_irq_flag(env, reg, argno, meta);
10313 		if (err < 0)
10314 			return err;
10315 		break;
10316 	case ARG_PTR_TO_CTX_OUT:
10317 		if (reg->mem_size != arg_size) {
10318 			verbose(env, "%s expected %u bytes of ctx-provided memory, got %u\n",
10319 				reg_arg_name(env, argno), arg_size, reg->mem_size);
10320 			return -EINVAL;
10321 		}
10322 		break;
10323 	case ARG_PTR_TO_RES_SPIN_LOCK:
10324 	{
10325 		int flags;
10326 
10327 		if (in_rbtree_lock_required_cb(env)) {
10328 			verbose(env, "can't res_spin_{lock,unlock} in rbtree cb\n");
10329 			return -EACCES;
10330 		}
10331 
10332 		flags = get_bpf_res_spin_lock_kfunc_flags(meta);
10333 		if (!flags)
10334 			return -EFAULT;
10335 		err = process_spin_lock(env, reg, argno, flags);
10336 		if (err < 0)
10337 			return err;
10338 		break;
10339 	}
10340 	case ARG_KPTR_XCHG_DEST:
10341 		err = process_kptr_func(env, regno, meta);
10342 		if (err)
10343 			return err;
10344 		break;
10345 	}
10346 
10347 	return err;
10348 }
10349 
10350 /*
10351  * The slots a parameter takes, from its BTF type. This has to agree with
10352  * btf_func_model_arg_slots(), which answers the same from the size the
10353  * func model recorded, or the verifier would check an argument at a slot
10354  * the JIT does not place it at.
10355  */
10356 static u32 btf_arg_slots(const struct btf_type *t)
10357 {
10358 	if (btf_type_is_int(t) || btf_type_is_struct(t))
10359 		return (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE;
10360 	return 1;
10361 }
10362 
10363 static u32 btf_proto_slots(const struct btf *btf, const struct btf_type *func_proto)
10364 {
10365 	const struct btf_param *args = btf_params(func_proto);
10366 	u32 i, nargs = btf_type_vlen(func_proto), slots_used = 0;
10367 
10368 	for (i = 0; i < nargs; i++)
10369 		slots_used += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
10370 
10371 	return slots_used;
10372 }
10373 
10374 /* The argument slot @slot holds an eightbyte of a by-value argument. */
10375 static int check_arg_extra_slot(struct bpf_verifier_env *env, struct bpf_func_state *caller,
10376 				u32 slot, struct bpf_call_arg_meta *meta)
10377 {
10378 	struct bpf_reg_state *reg = get_func_arg_reg(caller, cur_regs(env), slot);
10379 	argno_t argno = argno_from_arg(slot + 1);
10380 	int regno = reg_from_argno(argno);
10381 	int err;
10382 
10383 	if (regno >= 0) {
10384 		err = check_reg_arg(env, regno, SRC_OP);
10385 		if (err)
10386 			return err;
10387 	}
10388 
10389 	return check_reg_type(env, reg, argno, ARG_SCALAR, meta);
10390 }
10391 
10392 static int check_func_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10393 			   int insn_idx)
10394 {
10395 	u32 slot = 0, prev_slot = 0, proto_slots, nslots;
10396 	struct bpf_func_state *caller = cur_func(env);
10397 	const struct btf_param *args = NULL;
10398 	u32 arg, nargs = MAX_BPF_FUNC_REG_ARGS;
10399 	int err;
10400 
10401 	if (meta->btf) {
10402 		args = btf_params(meta->func_proto);
10403 		nargs = btf_type_vlen(meta->func_proto);
10404 	}
10405 
10406 	/*
10407 	 * A by-value argument of more than one eightbyte takes a slot per
10408 	 * eightbyte, so the slots a call occupies are no longer its parameter
10409 	 * count. Only a proto whose parameters take a slot each can name the
10410 	 * argument a stack slot belongs to.
10411 	 */
10412 	proto_slots = meta->btf ? btf_proto_slots(meta->btf, meta->func_proto) : nargs;
10413 
10414 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
10415 		err = check_outgoing_stack_args(env, caller, proto_slots, meta->func_name,
10416 						meta->btf, proto_slots == nargs ? args : NULL);
10417 		if (err)
10418 			return err;
10419 	}
10420 
10421 	for (arg = 0; arg < nargs; arg++, prev_slot = slot, slot += nslots) {
10422 		const struct btf_type *t;
10423 		u32 k;
10424 
10425 		nslots = 1;
10426 		if (args) {
10427 			t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
10428 			nslots = btf_arg_slots(t);
10429 		}
10430 
10431 		if (meta->fn->arg_type[arg] == ARG_UNUSED)
10432 			break;
10433 		err = check_func_arg(env, arg, slot, prev_slot, meta, insn_idx);
10434 		if (err)
10435 			return err;
10436 
10437 		/*
10438 		 * check_func_arg() took the first slot. A parameter of more
10439 		 * than one eightbyte is always a scalar, so every slot it
10440 		 * takes beyond the first holds one too.
10441 		 */
10442 		for (k = 1; k < nslots; k++) {
10443 			err = check_arg_extra_slot(env, caller, slot + k, meta);
10444 			if (err)
10445 				return err;
10446 		}
10447 	}
10448 
10449 	return 0;
10450 }
10451 
10452 static int mark_raw_stack(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10453 			  int insn_idx)
10454 {
10455 	struct bpf_func_state *caller = cur_func(env);
10456 	u32 slot;
10457 	int i, err;
10458 
10459 	/*
10460 	 * Validate every argument before initializing outputs: an input argument
10461 	 * may alias an output buffer. Use the normal stack-write checks to discard
10462 	 * stale spills and preserve the rules for special stack objects.
10463 	 */
10464 	for (slot = 0; slot < MAX_BPF_FUNC_ARGS; slot++) {
10465 		struct bpf_reg_state *reg;
10466 		argno_t argno = argno_from_arg(slot + 1);
10467 
10468 		if (!meta->arg_raw_mem.size[slot])
10469 			continue;
10470 		reg = get_func_arg_reg(caller, cur_regs(env), slot);
10471 
10472 		for (i = 0; i < meta->arg_raw_mem.size[slot]; i++) {
10473 			err = check_mem_access(env, insn_idx, reg, argno, i, BPF_B,
10474 					       BPF_WRITE, -1, false, false);
10475 			if (err)
10476 				return err;
10477 		}
10478 	}
10479 
10480 	return 0;
10481 }
10482 
10483 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
10484 {
10485 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
10486 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10487 
10488 	if (func_id != BPF_FUNC_map_update_elem &&
10489 	    func_id != BPF_FUNC_map_delete_elem)
10490 		return false;
10491 
10492 	/* It's not possible to get access to a locked struct sock in these
10493 	 * contexts, so updating is safe.
10494 	 */
10495 	switch (type) {
10496 	case BPF_PROG_TYPE_TRACING:
10497 		if (eatype == BPF_TRACE_ITER)
10498 			return true;
10499 		break;
10500 	case BPF_PROG_TYPE_SOCK_OPS:
10501 		/* map_update allowed only via dedicated helpers with event type checks */
10502 		if (func_id == BPF_FUNC_map_delete_elem)
10503 			return true;
10504 		break;
10505 	case BPF_PROG_TYPE_SK_REUSEPORT:
10506 	case BPF_PROG_TYPE_SK_LOOKUP:
10507 		return true;
10508 	default:
10509 		break;
10510 	}
10511 
10512 	verbose(env, "cannot update sockmap in this context\n");
10513 	return false;
10514 }
10515 
10516 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10517 {
10518 	return env->prog->jit_requested &&
10519 	       bpf_jit_supports_subprog_tailcalls();
10520 }
10521 
10522 /*
10523  * Is rcu_read_lock_held() true at run time? Unlike for in_rcu_cs(), disabled
10524  * preemption or interrupts will not do.
10525  */
10526 static bool has_rcu_read_lock(struct bpf_verifier_env *env)
10527 {
10528 	struct bpf_verifier_state *state = env->cur_state;
10529 
10530 	if (state->active_rcu_locks || in_rcu_callback(env))
10531 		return true;
10532 	if (in_sleepable(env))
10533 		return false;
10534 	return !env->no_rcu_read_lock || state->frame[0]->in_async_callback_fn;
10535 }
10536 
10537 /* May the map be used outside of an RCU read side critical section? */
10538 static bool map_needs_no_rcu(const struct bpf_map *map)
10539 {
10540 	switch (map->map_type) {
10541 	case BPF_MAP_TYPE_HASH:
10542 	case BPF_MAP_TYPE_RHASH:
10543 	case BPF_MAP_TYPE_LRU_HASH:
10544 	case BPF_MAP_TYPE_ARRAY:
10545 	case BPF_MAP_TYPE_PERCPU_HASH:
10546 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10547 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10548 	case BPF_MAP_TYPE_LPM_TRIE:
10549 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10550 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10551 	case BPF_MAP_TYPE_RINGBUF:
10552 	case BPF_MAP_TYPE_USER_RINGBUF:
10553 	case BPF_MAP_TYPE_INODE_STORAGE:
10554 	case BPF_MAP_TYPE_SK_STORAGE:
10555 	case BPF_MAP_TYPE_TASK_STORAGE:
10556 	case BPF_MAP_TYPE_CGRP_STORAGE:
10557 	case BPF_MAP_TYPE_QUEUE:
10558 	case BPF_MAP_TYPE_STACK:
10559 	case BPF_MAP_TYPE_ARENA:
10560 	case BPF_MAP_TYPE_INSN_ARRAY:
10561 	case BPF_MAP_TYPE_PROG_ARRAY:
10562 	case BPF_MAP_TYPE_BLOOM_FILTER:
10563 		return true;
10564 	default:
10565 		return false;
10566 	}
10567 }
10568 
10569 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10570 					struct bpf_map *map, int func_id)
10571 {
10572 	if (!map)
10573 		return 0;
10574 
10575 	/*
10576 	 * check_map_prog_compatibility() asks the program.  That misses the
10577 	 * sleepable callback of another program, and an inner map.  They may
10578 	 * use any map under the RCU read lock.  Disabled preemption or
10579 	 * interrupts will not do: the maps ask for rcu_read_lock_held().
10580 	 */
10581 	if (!has_rcu_read_lock(env) && !map_needs_no_rcu(map)) {
10582 		verbose(env, "map '%s' needs bpf_rcu_read_lock() in sleepable context\n",
10583 			map->name);
10584 		return -EINVAL;
10585 	}
10586 
10587 	/* We need a two way check, first is from map perspective ... */
10588 	switch (map->map_type) {
10589 	case BPF_MAP_TYPE_PROG_ARRAY:
10590 		if (func_id != BPF_FUNC_tail_call)
10591 			goto error;
10592 		break;
10593 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10594 		if (func_id != BPF_FUNC_perf_event_read &&
10595 		    func_id != BPF_FUNC_perf_event_output &&
10596 		    func_id != BPF_FUNC_skb_output &&
10597 		    func_id != BPF_FUNC_perf_event_read_value &&
10598 		    func_id != BPF_FUNC_xdp_output)
10599 			goto error;
10600 		break;
10601 	case BPF_MAP_TYPE_RINGBUF:
10602 		if (func_id != BPF_FUNC_ringbuf_output &&
10603 		    func_id != BPF_FUNC_ringbuf_reserve &&
10604 		    func_id != BPF_FUNC_ringbuf_query &&
10605 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10606 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10607 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
10608 			goto error;
10609 		break;
10610 	case BPF_MAP_TYPE_USER_RINGBUF:
10611 		if (func_id != BPF_FUNC_user_ringbuf_drain)
10612 			goto error;
10613 		break;
10614 	case BPF_MAP_TYPE_STACK_TRACE:
10615 		if (func_id != BPF_FUNC_get_stackid)
10616 			goto error;
10617 		break;
10618 	case BPF_MAP_TYPE_CGROUP_ARRAY:
10619 		if (func_id != BPF_FUNC_skb_under_cgroup &&
10620 		    func_id != BPF_FUNC_current_task_under_cgroup)
10621 			goto error;
10622 		break;
10623 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10624 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10625 		if (func_id != BPF_FUNC_get_local_storage)
10626 			goto error;
10627 		break;
10628 	case BPF_MAP_TYPE_DEVMAP:
10629 	case BPF_MAP_TYPE_DEVMAP_HASH:
10630 		if (func_id != BPF_FUNC_redirect_map &&
10631 		    func_id != BPF_FUNC_map_lookup_elem)
10632 			goto error;
10633 		break;
10634 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10635 	 * appear.
10636 	 */
10637 	case BPF_MAP_TYPE_CPUMAP:
10638 		if (func_id != BPF_FUNC_redirect_map)
10639 			goto error;
10640 		break;
10641 	case BPF_MAP_TYPE_XSKMAP:
10642 		if (func_id != BPF_FUNC_redirect_map &&
10643 		    func_id != BPF_FUNC_map_lookup_elem)
10644 			goto error;
10645 		break;
10646 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10647 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10648 		if (func_id != BPF_FUNC_map_lookup_elem)
10649 			goto error;
10650 		break;
10651 	case BPF_MAP_TYPE_SOCKMAP:
10652 		if (func_id != BPF_FUNC_sk_redirect_map &&
10653 		    func_id != BPF_FUNC_sock_map_update &&
10654 		    func_id != BPF_FUNC_msg_redirect_map &&
10655 		    func_id != BPF_FUNC_sk_select_reuseport &&
10656 		    func_id != BPF_FUNC_map_lookup_elem &&
10657 		    !may_update_sockmap(env, func_id))
10658 			goto error;
10659 		break;
10660 	case BPF_MAP_TYPE_SOCKHASH:
10661 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10662 		    func_id != BPF_FUNC_sock_hash_update &&
10663 		    func_id != BPF_FUNC_msg_redirect_hash &&
10664 		    func_id != BPF_FUNC_sk_select_reuseport &&
10665 		    func_id != BPF_FUNC_map_lookup_elem &&
10666 		    !may_update_sockmap(env, func_id))
10667 			goto error;
10668 		break;
10669 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10670 		if (func_id != BPF_FUNC_sk_select_reuseport)
10671 			goto error;
10672 		break;
10673 	case BPF_MAP_TYPE_QUEUE:
10674 	case BPF_MAP_TYPE_STACK:
10675 		if (func_id != BPF_FUNC_map_peek_elem &&
10676 		    func_id != BPF_FUNC_map_pop_elem &&
10677 		    func_id != BPF_FUNC_map_push_elem)
10678 			goto error;
10679 		break;
10680 	case BPF_MAP_TYPE_SK_STORAGE:
10681 		if (func_id != BPF_FUNC_sk_storage_get &&
10682 		    func_id != BPF_FUNC_sk_storage_delete &&
10683 		    func_id != BPF_FUNC_kptr_xchg)
10684 			goto error;
10685 		break;
10686 	case BPF_MAP_TYPE_INODE_STORAGE:
10687 		if (func_id != BPF_FUNC_inode_storage_get &&
10688 		    func_id != BPF_FUNC_inode_storage_delete &&
10689 		    func_id != BPF_FUNC_kptr_xchg)
10690 			goto error;
10691 		break;
10692 	case BPF_MAP_TYPE_TASK_STORAGE:
10693 		if (func_id != BPF_FUNC_task_storage_get &&
10694 		    func_id != BPF_FUNC_task_storage_delete &&
10695 		    func_id != BPF_FUNC_kptr_xchg)
10696 			goto error;
10697 		break;
10698 	case BPF_MAP_TYPE_CGRP_STORAGE:
10699 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10700 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10701 		    func_id != BPF_FUNC_kptr_xchg)
10702 			goto error;
10703 		break;
10704 	case BPF_MAP_TYPE_BLOOM_FILTER:
10705 		if (func_id != BPF_FUNC_map_peek_elem &&
10706 		    func_id != BPF_FUNC_map_push_elem)
10707 			goto error;
10708 		break;
10709 	case BPF_MAP_TYPE_INSN_ARRAY:
10710 		goto error;
10711 	default:
10712 		break;
10713 	}
10714 
10715 	/* ... and second from the function itself. */
10716 	switch (func_id) {
10717 	case BPF_FUNC_tail_call:
10718 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10719 			goto error;
10720 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
10721 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10722 			return -EINVAL;
10723 		}
10724 		break;
10725 	case BPF_FUNC_perf_event_read:
10726 	case BPF_FUNC_perf_event_output:
10727 	case BPF_FUNC_perf_event_read_value:
10728 	case BPF_FUNC_skb_output:
10729 	case BPF_FUNC_xdp_output:
10730 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10731 			goto error;
10732 		break;
10733 	case BPF_FUNC_ringbuf_output:
10734 	case BPF_FUNC_ringbuf_reserve:
10735 	case BPF_FUNC_ringbuf_query:
10736 	case BPF_FUNC_ringbuf_reserve_dynptr:
10737 	case BPF_FUNC_ringbuf_submit_dynptr:
10738 	case BPF_FUNC_ringbuf_discard_dynptr:
10739 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10740 			goto error;
10741 		break;
10742 	case BPF_FUNC_user_ringbuf_drain:
10743 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10744 			goto error;
10745 		break;
10746 	case BPF_FUNC_get_stackid:
10747 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10748 			goto error;
10749 		break;
10750 	case BPF_FUNC_current_task_under_cgroup:
10751 	case BPF_FUNC_skb_under_cgroup:
10752 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10753 			goto error;
10754 		break;
10755 	case BPF_FUNC_redirect_map:
10756 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10757 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10758 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10759 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10760 			goto error;
10761 		break;
10762 	case BPF_FUNC_sk_redirect_map:
10763 	case BPF_FUNC_msg_redirect_map:
10764 	case BPF_FUNC_sock_map_update:
10765 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10766 			goto error;
10767 		break;
10768 	case BPF_FUNC_sk_redirect_hash:
10769 	case BPF_FUNC_msg_redirect_hash:
10770 	case BPF_FUNC_sock_hash_update:
10771 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10772 			goto error;
10773 		break;
10774 	case BPF_FUNC_get_local_storage:
10775 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10776 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10777 			goto error;
10778 		break;
10779 	case BPF_FUNC_sk_select_reuseport:
10780 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10781 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10782 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10783 			goto error;
10784 		break;
10785 	case BPF_FUNC_map_pop_elem:
10786 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10787 		    map->map_type != BPF_MAP_TYPE_STACK)
10788 			goto error;
10789 		break;
10790 	case BPF_FUNC_map_peek_elem:
10791 	case BPF_FUNC_map_push_elem:
10792 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10793 		    map->map_type != BPF_MAP_TYPE_STACK &&
10794 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10795 			goto error;
10796 		break;
10797 	case BPF_FUNC_map_lookup_percpu_elem:
10798 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10799 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10800 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10801 			goto error;
10802 		break;
10803 	case BPF_FUNC_sk_storage_get:
10804 	case BPF_FUNC_sk_storage_delete:
10805 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10806 			goto error;
10807 		break;
10808 	case BPF_FUNC_inode_storage_get:
10809 	case BPF_FUNC_inode_storage_delete:
10810 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10811 			goto error;
10812 		break;
10813 	case BPF_FUNC_task_storage_get:
10814 	case BPF_FUNC_task_storage_delete:
10815 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10816 			goto error;
10817 		break;
10818 	case BPF_FUNC_cgrp_storage_get:
10819 	case BPF_FUNC_cgrp_storage_delete:
10820 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10821 			goto error;
10822 		break;
10823 	default:
10824 		break;
10825 	}
10826 
10827 	return 0;
10828 error:
10829 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10830 		map->map_type, func_id_name(func_id), func_id);
10831 	return -EINVAL;
10832 }
10833 
10834 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10835 {
10836 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10837 	bool has_size = fn->arg_size[arg] != 0;
10838 	bool is_next_size = false;
10839 
10840 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10841 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10842 
10843 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10844 		return is_next_size;
10845 
10846 	return has_size == is_next_size || is_next_size == is_fixed;
10847 }
10848 
10849 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10850 {
10851 	/* bpf_xxx(..., buf, len) call will access 'len'
10852 	 * bytes from memory 'buf'. Both arg types need
10853 	 * to be paired, so make sure there's no buggy
10854 	 * helper function specification.
10855 	 */
10856 	if (arg_type_is_mem_size(fn->arg1_type) ||
10857 	    check_args_pair_invalid(fn, 0) ||
10858 	    check_args_pair_invalid(fn, 1) ||
10859 	    check_args_pair_invalid(fn, 2) ||
10860 	    check_args_pair_invalid(fn, 3) ||
10861 	    check_args_pair_invalid(fn, 4))
10862 		return false;
10863 
10864 	return true;
10865 }
10866 
10867 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10868 {
10869 	int i;
10870 
10871 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10872 		if (fn->arg_type[i] == ARG_UNUSED)
10873 			break;
10874 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10875 			return !!fn->arg_btf_id[i];
10876 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10877 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10878 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10879 		    /* arg_btf_id and arg_size are in a union. */
10880 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10881 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10882 			return false;
10883 	}
10884 
10885 	return true;
10886 }
10887 
10888 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
10889 {
10890 	int i;
10891 
10892 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10893 		enum bpf_arg_type arg_type = fn->arg_type[i];
10894 
10895 		if (arg_type == ARG_UNUSED)
10896 			break;
10897 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
10898 			continue;
10899 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
10900 			return false;
10901 	}
10902 
10903 	return true;
10904 }
10905 
10906 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
10907 {
10908 	int i;
10909 
10910 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10911 		enum bpf_arg_type arg_type = fn->arg_type[i];
10912 
10913 		if (arg_type == ARG_UNUSED)
10914 			break;
10915 		if (arg_type_is_release(arg_type)) {
10916 			if (meta->release_regno)
10917 				return false;
10918 			meta->release_regno = i + 1;
10919 		}
10920 	}
10921 
10922 	return true;
10923 }
10924 
10925 static bool check_arg_prog_aux(struct bpf_verifier_env *env,
10926 			       const struct bpf_func_proto *proto)
10927 {
10928 	bool seen = false;
10929 	argno_t argno;
10930 	u32 i;
10931 
10932 	for (i = 0; i < ARRAY_SIZE(proto->arg_type); i++) {
10933 		if (proto->arg_type[i] == ARG_UNUSED)
10934 			break;
10935 		if (proto->arg_type[i] != ARG_PTR_TO_PROG_AUX)
10936 			continue;
10937 
10938 		if (seen) {
10939 			verifier_bug(env, "Only 1 prog->aux argument supported");
10940 			return false;
10941 		}
10942 
10943 		argno = argno_from_arg(i + 1);
10944 		if (reg_from_argno(argno) < 0) {
10945 			verbose(env, "%s prog->aux cannot be a stack argument\n",
10946 				reg_arg_name(env, argno));
10947 			return false;
10948 		}
10949 
10950 		seen = true;
10951 	}
10952 
10953 	return true;
10954 }
10955 
10956 static int check_func_proto(struct bpf_verifier_env *env, const struct bpf_func_proto *fn,
10957 			    struct bpf_call_arg_meta *meta)
10958 {
10959 	return check_arg_prog_aux(env, fn) &&
10960 	       check_arg_pair_ok(fn) &&
10961 	       check_mem_arg_rw_flag_ok(fn) &&
10962 	       check_proto_release_reg(fn, meta) &&
10963 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10964 }
10965 
10966 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10967  * are now invalid, so turn them into unknown SCALAR_VALUE.
10968  *
10969  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10970  * since these slices point to packet data.
10971  */
10972 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10973 {
10974 	struct bpf_func_state *state;
10975 	struct bpf_reg_state *reg;
10976 
10977 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10978 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) {
10979 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_PKT_DATA_CHANGE);
10980 			mark_reg_invalid(env, reg);
10981 		}
10982 	}));
10983 }
10984 
10985 static bool holds_pkt_pointers(struct bpf_verifier_env *env)
10986 {
10987 	struct bpf_func_state *state;
10988 	struct bpf_reg_state *reg;
10989 	bool ret = false;
10990 
10991 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10992 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10993 			ret = true;
10994 	}));
10995 
10996 	return ret;
10997 }
10998 
10999 enum {
11000 	AT_PKT_END = -1,
11001 	BEYOND_PKT_END = -2,
11002 };
11003 
11004 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
11005 {
11006 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
11007 	struct bpf_reg_state *reg = &state->regs[regn];
11008 
11009 	if (reg->type != PTR_TO_PACKET)
11010 		/* PTR_TO_PACKET_META is not supported yet */
11011 		return;
11012 
11013 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
11014 	 * How far beyond pkt_end it goes is unknown.
11015 	 * if (!range_open) it's the case of pkt >= pkt_end
11016 	 * if (range_open) it's the case of pkt > pkt_end
11017 	 * hence this pointer is at least 1 byte bigger than pkt_end
11018 	 */
11019 	if (range_open)
11020 		reg->range = BEYOND_PKT_END;
11021 	else
11022 		reg->range = AT_PKT_END;
11023 }
11024 
11025 static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
11026 {
11027 	int i;
11028 
11029 	for (i = 0; i < state->acquired_refs; i++) {
11030 		if (state->refs[i].type != REF_TYPE_PTR)
11031 			continue;
11032 		if (state->refs[i].id == id) {
11033 			release_reference_state(state, i);
11034 			return 0;
11035 		}
11036 	}
11037 	return -EINVAL;
11038 }
11039 
11040 static int release_reference_nomark(struct bpf_verifier_env *env, int id)
11041 {
11042 	int err;
11043 
11044 	err = __release_reference_nomark(env->cur_state, id);
11045 	if (!err)
11046 		bpf_diag_record_ref_release(env, env->insn_idx, id);
11047 	return err;
11048 }
11049 
11050 static int idstack_push(struct bpf_idmap *idmap, u32 id)
11051 {
11052 	int i;
11053 
11054 	if (!id)
11055 		return 0;
11056 
11057 	for (i = 0; i < idmap->cnt; i++)
11058 		if (idmap->map[i].old == id)
11059 			return 0;
11060 
11061 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
11062 		return -EFAULT;
11063 
11064 	idmap->map[idmap->cnt++].old = id;
11065 	return 0;
11066 }
11067 
11068 static int idstack_pop(struct bpf_idmap *idmap)
11069 {
11070 	if (!idmap->cnt)
11071 		return 0;
11072 
11073 	return idmap->map[--idmap->cnt].old;
11074 }
11075 
11076 /* Release id and objects derived from it iteratively in a DFS manner */
11077 static int release_reference(struct bpf_verifier_env *env, int id)
11078 {
11079 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
11080 	struct bpf_verifier_state *vstate = env->cur_state;
11081 	struct bpf_idmap *idstack = &env->idmap_scratch;
11082 	struct bpf_stack_state *stack;
11083 	struct bpf_func_state *state;
11084 	struct bpf_reg_state *reg;
11085 	int i, err;
11086 
11087 	idstack->cnt = 0;
11088 	err = idstack_push(idstack, id);
11089 	if (err)
11090 		return err;
11091 
11092 	if (find_reference_state(vstate, id)) {
11093 		err = release_reference_nomark(env, id);
11094 		WARN_ON_ONCE(err);
11095 	}
11096 
11097 	while ((id = idstack_pop(idstack))) {
11098 		/*
11099 		 * Child references are inaccessible after parent is released,
11100 		 * any child references that exist at this point are a leak.
11101 		 */
11102 		for (i = 0; i < vstate->acquired_refs; i++) {
11103 			if (vstate->refs[i].type != REF_TYPE_PTR)
11104 				continue;
11105 			if (vstate->refs[i].parent_id != id)
11106 				continue;
11107 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
11108 				vstate->refs[i].id, vstate->refs[i].insn_idx);
11109 			return -EINVAL;
11110 		}
11111 
11112 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
11113 			if (reg->id != id && reg->parent_id != id)
11114 				continue;
11115 
11116 			/* Free objects derived from the current object */
11117 			if (reg->parent_id == id) {
11118 				err = idstack_push(idstack, reg->id);
11119 				if (err)
11120 					return err;
11121 			}
11122 
11123 			/*
11124 			 * A dynptr occupies two stack slots that invalidate_dynptr()
11125 			 * clears together. Record both scrubs before invalidating it.
11126 			 */
11127 			if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) {
11128 				struct bpf_stack_state *dyn_stack = stack;
11129 
11130 				if (reg->dynptr.first_slot)
11131 					dyn_stack--;
11132 				bpf_diag_record_scrub(env, &dyn_stack[0].spilled_ptr,
11133 						      BPF_DIAG_MOD_REF_RELEASE);
11134 				bpf_diag_record_scrub(env, &dyn_stack[1].spilled_ptr,
11135 						      BPF_DIAG_MOD_REF_RELEASE);
11136 				invalidate_dynptr(env, dyn_stack);
11137 				continue;
11138 			}
11139 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_REF_RELEASE);
11140 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
11141 				mark_reg_invalid(env, reg);
11142 		}));
11143 	}
11144 
11145 	return 0;
11146 }
11147 
11148 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
11149 {
11150 	struct bpf_func_state *unused;
11151 	struct bpf_reg_state *reg;
11152 
11153 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11154 		if (type_is_non_owning_ref(reg->type)) {
11155 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_NON_OWN_REF);
11156 			mark_reg_invalid(env, reg);
11157 		}
11158 	}));
11159 }
11160 
11161 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
11162 {
11163 	struct bpf_stack_state *stack;
11164 	struct bpf_func_state *state;
11165 	struct bpf_reg_state *reg;
11166 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
11167 
11168 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
11169 		if (reg->type & MEM_RCU) {
11170 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
11171 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL | NON_OWN_REF);
11172 			reg->type |= PTR_UNTRUSTED;
11173 			bpf_diag_mod_end(env);
11174 		}
11175 	}));
11176 }
11177 
11178 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
11179 {
11180 	struct bpf_func_state *state;
11181 	struct bpf_reg_state *reg;
11182 	int err;
11183 
11184 	err = release_reference_nomark(env, id);
11185 	if (err)
11186 		return err;
11187 
11188 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11189 		if (reg->id != id)
11190 			continue;
11191 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11192 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
11193 			if (!type_may_be_null(reg->type))
11194 				reg->id = 0;
11195 			reg->type &= ~MEM_ALLOC;
11196 			reg->type |= MEM_RCU;
11197 			bpf_diag_mod_end(env);
11198 		}
11199 	}));
11200 
11201 	return err;
11202 }
11203 
11204 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
11205 				    struct bpf_reg_state *regs)
11206 {
11207 	int i;
11208 
11209 	bpf_diag_record_caller_saved(env, regs);
11210 
11211 	/* after the call registers r0 - r5 were scratched */
11212 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11213 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
11214 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
11215 	}
11216 }
11217 
11218 static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,
11219 					   struct bpf_func_state *state)
11220 {
11221 	int i, nslots = state->out_stack_arg_cnt;
11222 
11223 	for (i = 0; i < nslots; i++) {
11224 		bpf_diag_record_scrub(env, &state->stack_arg_regs[i], BPF_DIAG_MOD_CALLER_SAVED);
11225 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
11226 	}
11227 }
11228 
11229 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
11230 				   struct bpf_func_state *caller,
11231 				   struct bpf_func_state *callee,
11232 				   int insn_idx);
11233 
11234 static int set_callee_state(struct bpf_verifier_env *env,
11235 			    struct bpf_func_state *caller,
11236 			    struct bpf_func_state *callee, int insn_idx);
11237 
11238 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
11239 			    set_callee_state_fn set_callee_state_cb,
11240 			    struct bpf_verifier_state *state)
11241 {
11242 	struct bpf_func_state *caller, *callee;
11243 	int err;
11244 
11245 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
11246 		verbose(env, "the call stack of %d frames is too deep\n",
11247 			state->curframe + 2);
11248 		return -E2BIG;
11249 	}
11250 
11251 	if (state->frame[state->curframe + 1]) {
11252 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
11253 		return -EFAULT;
11254 	}
11255 
11256 	caller = state->frame[state->curframe];
11257 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
11258 	if (!callee)
11259 		return -ENOMEM;
11260 	state->frame[state->curframe + 1] = callee;
11261 
11262 	/* callee cannot access r0, r6 - r9 for reading and has to write
11263 	 * into its own stack before reading from it.
11264 	 * callee can read/write into caller's stack
11265 	 */
11266 	init_func_state(env, callee,
11267 			/* remember the callsite, it will be used by bpf_exit */
11268 			callsite,
11269 			state->curframe + 1 /* frameno within this callchain */,
11270 			subprog /* subprog number within this prog */);
11271 	err = set_callee_state_cb(env, caller, callee, callsite);
11272 	if (err)
11273 		goto err_out;
11274 
11275 	/* only increment it after check_reg_arg() finished */
11276 	state->curframe++;
11277 
11278 	return 0;
11279 
11280 err_out:
11281 	free_func_state(callee);
11282 	state->frame[state->curframe + 1] = NULL;
11283 	return err;
11284 }
11285 
11286 static void gen_subprog_arg_proto(const struct bpf_subprog_info *sub, const struct btf *btf,
11287 				  const struct btf_type *func_proto, struct bpf_func_proto *proto)
11288 {
11289 	const struct btf_param *args = btf_params(func_proto);
11290 	u32 arg, slot = 0;
11291 
11292 	memset(proto, 0, sizeof(*proto));
11293 	for (arg = 0; arg < btf_type_vlen(func_proto); arg++) {
11294 		enum bpf_arg_type arg_type = sub->args[slot].arg_type;
11295 		const struct btf_type *t;
11296 
11297 		if (arg_type & PTR_UNTRUSTED) {
11298 			/*
11299 			 * An __arg_untrusted argument accepts any caller value. The
11300 			 * callee treats it as read-only and uses probe-read instructions
11301 			 * to protect against invalid memory access.
11302 			 */
11303 			arg_type = ARG_IGNORE;
11304 		} else if (base_type(arg_type) == ARG_PTR_TO_ARENA) {
11305 			arg_type |= PTR_MAYBE_NULL;
11306 		} else if (base_type(arg_type) == ARG_PTR_TO_MEM) {
11307 			proto->arg_size[arg] = sub->args[slot].mem_size;
11308 			arg_type |= MEM_FIXED_SIZE | MEM_WRITE;
11309 		} else if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
11310 			proto->arg_btf_id[arg] = &sub->args[slot].btf_id;
11311 		}
11312 		proto->arg_type[arg] = arg_type;
11313 		t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
11314 		slot += btf_arg_slots(t);
11315 	}
11316 }
11317 
11318 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, struct btf *btf)
11319 {
11320 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
11321 	struct bpf_func_state *caller = cur_func(env);
11322 	const struct btf_type *func, *func_proto;
11323 	struct bpf_call_arg_meta meta;
11324 	struct bpf_func_proto *fn;
11325 	int ret, err;
11326 	u32 i;
11327 
11328 	memset(&meta, 0, sizeof(meta));
11329 	meta.btf = btf;
11330 	meta.subprog_may_change_pkt = sub->changes_pkt_data;
11331 	meta.func_name = bpf_subprog_name(env, subprog);
11332 
11333 	ret = btf_prepare_func_args(env, subprog);
11334 	if (ret) {
11335 		if (bpf_in_stack_arg_cnt(sub) > 0) {
11336 			err = check_outgoing_stack_args(env, caller, sub->arg_slot_cnt,
11337 							bpf_subprog_name(env, subprog),
11338 							NULL, NULL);
11339 			if (err)
11340 				return err;
11341 		}
11342 		return ret;
11343 	}
11344 
11345 	func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id);
11346 	func_proto = btf_type_by_id(btf, func->type);
11347 
11348 	fn = &env->bpf_subprog_scratch;
11349 	gen_subprog_arg_proto(sub, btf, func_proto, fn);
11350 	meta.fn = fn;
11351 	meta.func_proto = func_proto;
11352 
11353 	/*
11354 	 * Check if all register arguments declared in BTF are initialized.
11355 	 * If they aren't the BTF is unreliable.
11356 	 */
11357 	if (!bpf_subprog_is_global(env, subprog)) {
11358 		for (i = 0; i < min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++)
11359 			if (caller->regs[BPF_REG_1 + i].type == NOT_INIT)
11360 				return -EINVAL;
11361 	}
11362 	return check_func_args(env, &meta, env->insn_idx);
11363 }
11364 
11365 /*
11366  * Check that call-site argument states match a subprog's BTF signature.
11367  *
11368  * Returns:
11369  * EFAULT - there is a verifier bug. Abort verification.
11370  * Other errors - there is a type mismatch or BTF is not available.
11371  * 0 - BTF matches with what bpf_reg_state expects.
11372  */
11373 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog)
11374 {
11375 	struct bpf_prog *prog = env->prog;
11376 	struct btf *btf = prog->aux->btf;
11377 	u32 btf_id;
11378 	int err;
11379 
11380 	if (!prog->aux->func_info)
11381 		return -EINVAL;
11382 
11383 	btf_id = prog->aux->func_info[subprog].type_id;
11384 	if (!btf_id)
11385 		return -EFAULT;
11386 
11387 	if (prog->aux->func_info_aux[subprog].unreliable)
11388 		return -EINVAL;
11389 
11390 	err = btf_check_func_arg_match(env, subprog, btf);
11391 	/* Compiler optimizations can remove arguments from static functions
11392 	 * or mismatched type can be passed into a global function.
11393 	 * In such cases mark the function as unreliable from BTF point of view.
11394 	 */
11395 	if (err)
11396 		prog->aux->func_info_aux[subprog].unreliable = true;
11397 	return err;
11398 }
11399 
11400 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11401 			      int insn_idx, int subprog,
11402 			      set_callee_state_fn set_callee_state_cb)
11403 {
11404 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
11405 	struct bpf_func_state *caller, *callee;
11406 	int err;
11407 
11408 	caller = state->frame[state->curframe];
11409 	err = btf_check_subprog_call(env, subprog);
11410 	if (err == -EFAULT)
11411 		return err;
11412 
11413 	/* set_callee_state is used for direct subprog calls, but we are
11414 	 * interested in validating only BPF helpers that can call subprogs as
11415 	 * callbacks
11416 	 */
11417 	env->subprog_info[subprog].is_cb = true;
11418 	if (bpf_pseudo_kfunc_call(insn) &&
11419 	    !is_callback_calling_kfunc(insn->imm)) {
11420 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
11421 			     func_id_name(insn->imm), insn->imm);
11422 		return -EFAULT;
11423 	} else if (!bpf_pseudo_kfunc_call(insn) &&
11424 		   !is_callback_calling_function(insn->imm)) { /* helper */
11425 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
11426 			     func_id_name(insn->imm), insn->imm);
11427 		return -EFAULT;
11428 	}
11429 
11430 	if (bpf_is_async_callback_calling_insn(insn)) {
11431 		struct bpf_verifier_state *async_cb;
11432 
11433 		/* there is no real recursion here. timer and workqueue callbacks are async */
11434 		env->subprog_info[subprog].is_async_cb = true;
11435 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
11436 					 insn_idx, subprog,
11437 					 is_async_cb_sleepable(env, insn));
11438 		if (IS_ERR(async_cb))
11439 			return PTR_ERR(async_cb);
11440 		if (is_async_cb_sleepable(env, insn))
11441 			mark_sleepable_async_cb(env);
11442 		callee = async_cb->frame[0];
11443 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
11444 
11445 		/* Convert bpf_timer_set_callback() args into timer callback args */
11446 		err = set_callee_state_cb(env, caller, callee, insn_idx);
11447 		if (err)
11448 			return err;
11449 
11450 		return 0;
11451 	}
11452 
11453 	/*
11454 	 * The address of the callback might be taken in another function or
11455 	 * read from a map, see check_func_ptr_read(). Like with callx it's
11456 	 * known here what is called.
11457 	 */
11458 	err = record_callx_edge(env, caller->subprogno, subprog);
11459 	if (err)
11460 		return err;
11461 
11462 	/* for callback functions enqueue entry to callback and
11463 	 * proceed with next instruction within current frame.
11464 	 */
11465 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
11466 	if (IS_ERR(callback_state))
11467 		return PTR_ERR(callback_state);
11468 
11469 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
11470 			       callback_state);
11471 	if (err)
11472 		return err;
11473 
11474 	callback_state->callback_unroll_depth++;
11475 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
11476 	caller->callback_depth = 0;
11477 	return 0;
11478 }
11479 
11480 static int process_bpf_exit_full(struct bpf_verifier_env *env,
11481 				 bool *do_print_state, bool exception_exit);
11482 
11483 /*
11484  * Call of a static subprog. The callee is verified in the context of
11485  * the caller, hence set up a new frame and continue from the first
11486  * instruction of the callee.
11487  */
11488 static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
11489 				  int *insn_idx)
11490 {
11491 	struct bpf_verifier_state *state = env->cur_state;
11492 	struct bpf_subprog_info *caller_info;
11493 	u16 callee_incoming, stack_arg_cnt;
11494 	struct bpf_func_state *caller;
11495 	int err;
11496 
11497 	caller = state->frame[state->curframe];
11498 
11499 	/*
11500 	 * Track caller's total stack arg count (incoming + max outgoing).
11501 	 * This is needed so the JIT knows how much stack arg space to allocate.
11502 	 */
11503 	caller_info = &env->subprog_info[caller->subprogno];
11504 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
11505 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
11506 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
11507 		caller_info->stack_arg_cnt = stack_arg_cnt;
11508 
11509 	/*
11510 	 * For regular function entry setup new frame and continue
11511 	 * from that frame.
11512 	 */
11513 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
11514 	if (err)
11515 		return err;
11516 
11517 	bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11518 	clear_caller_saved_regs(env, caller->regs);
11519 
11520 	/* and go analyze first insn of the callee */
11521 	*insn_idx = env->subprog_info[subprog].start - 1;
11522 
11523 	if (env->log.level & BPF_LOG_LEVEL) {
11524 		verbose(env, "caller:\n");
11525 		print_verifier_state(env, state, caller->frameno, true);
11526 		verbose(env, "callee:\n");
11527 		print_verifier_state(env, state, state->curframe, true);
11528 	}
11529 
11530 	return 0;
11531 }
11532 
11533 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11534 			   int *insn_idx)
11535 {
11536 	struct bpf_verifier_state *state = env->cur_state;
11537 	struct bpf_func_state *caller;
11538 	int err, subprog, target_insn;
11539 	u32 i, nregs;
11540 
11541 	target_insn = *insn_idx + insn->imm + 1;
11542 	subprog = bpf_find_subprog(env, target_insn);
11543 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
11544 			    target_insn))
11545 		return -EFAULT;
11546 
11547 	caller = state->frame[state->curframe];
11548 	err = btf_check_subprog_call(env, subprog);
11549 	if (err == -EFAULT)
11550 		return err;
11551 	if (bpf_subprog_is_global(env, subprog)) {
11552 		struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog);
11553 		const char *sub_name = bpf_subprog_name(env, subprog);
11554 		const char *operation;
11555 		bool returns_void;
11556 
11557 		if (env->cur_state->active_locks) {
11558 			verbose(env, "global function calls are not allowed while holding a lock,\n"
11559 				     "use static function instead\n");
11560 			operation = bpf_diag_fmt(env, "global function %s()", sub_name);
11561 			bpf_diag_ctx_active(env, *insn_idx, operation, BPF_DIAG_CONTEXT_LOCK,
11562 					    "Release the lock before calling the global function, or use a static function instead.");
11563 			return -EINVAL;
11564 		}
11565 
11566 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
11567 			const char *suggestion;
11568 
11569 			verbose(env, "sleepable global function %s() called in %s\n",
11570 				sub_name, non_sleepable_context_description(env));
11571 			if (in_sleepable(env))
11572 				suggestion = "Move the call outside the critical section, or use a non-sleepable function.";
11573 			else
11574 				suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable function.";
11575 			operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name);
11576 			bpf_diag_ctx_forbidden(env, *insn_idx, operation, suggestion);
11577 			return -EINVAL;
11578 		}
11579 
11580 		if (err) {
11581 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
11582 				subprog, sub_name);
11583 			return err;
11584 		}
11585 
11586 		if (env->log.level & BPF_LOG_LEVEL)
11587 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
11588 				subprog, sub_name);
11589 		if (in_sleepable_context(env))
11590 			sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = true;
11591 		else if (has_rcu_read_lock(env))
11592 			sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = true;
11593 		else
11594 			sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = true;
11595 		returns_void = subprog_returns_void(env, subprog);
11596 		if (env->subprog_info[subprog].changes_pkt_data)
11597 			clear_all_pkt_pointers(env);
11598 		if (returns_void)
11599 			bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
11600 		else
11601 			bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
11602 		clear_caller_saved_regs(env, caller->regs);
11603 		invalidate_outgoing_stack_args(env, cur_func(env));
11604 		/*
11605 		 * What the callers of a global function hold is not known
11606 		 * while it is verified.
11607 		 */
11608 		if (!env->subprog_info[subprog].changes_pkt_data &&
11609 		    (state->frame[0]->subprogno || holds_pkt_pointers(env)))
11610 			sub_aux->called_with_pkt_ptrs = true;
11611 
11612 		/*
11613 		 * A non-void global function returns a 64-bit SCALAR_VALUE in
11614 		 * R0, or a >8 byte SCALAR_VALUE in the R0:R2 register pair.
11615 		 */
11616 		if (!returns_void) {
11617 			nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
11618 			mark_reg_unknown(env, caller->regs, ret_regs[0]);
11619 			bpf_diag_mod_end(env);
11620 			for (i = 1; i < nregs; i++) {
11621 				bpf_diag_mod_begin(env, &caller->regs[ret_regs[i]], NULL,
11622 						   BPF_DIAG_MOD_WRITE);
11623 				mark_reg_unknown(env, caller->regs, ret_regs[i]);
11624 				bpf_diag_mod_end(env);
11625 			}
11626 		}
11627 
11628 		if (env->subprog_info[subprog].can_unwind) {
11629 			struct bpf_verifier_state *branch;
11630 
11631 			if (!bpf_is_unwind_goto(insn + 1)) {
11632 				verbose(env, "no unwind_goto after the call of %s()\n", sub_name);
11633 				return -EINVAL;
11634 			}
11635 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
11636 			if (IS_ERR(branch))
11637 				return PTR_ERR(branch);
11638 			branch->unwound = true;
11639 		}
11640 
11641 		if (env->subprog_info[subprog].might_throw) {
11642 			struct bpf_verifier_state *branch;
11643 
11644 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
11645 			if (IS_ERR(branch)) {
11646 				verbose(env, "failed to push state for global subprog exception path\n");
11647 				return PTR_ERR(branch);
11648 			}
11649 			return process_bpf_exit_full(env, NULL, true);
11650 		}
11651 
11652 		/* continue with next insn after call */
11653 		return 0;
11654 	}
11655 
11656 	return check_static_func_call(env, subprog, insn_idx);
11657 }
11658 
11659 /*
11660  * callx dst_reg: call a bpf subprog whose address is in dst_reg.
11661  *
11662  * The address of a subprog is either loaded into a register by ld_imm64 with
11663  * src_reg == BPF_PSEUDO_FUNC, or it is read from a frozen read-only map, see
11664  * resolve_func_ptrs(). Both are possible for static subprogs only. Hence all
11665  * possible callees of callx are discovered by add_subprogs() and are reachable
11666  * in the control flow graph before the main verification pass begins.
11667  * PTR_TO_FUNC register identifies the callee, so from here on callx is verified
11668  * as a direct call of that static subprog.
11669  */
11670 static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn,
11671 			    int *insn_idx)
11672 {
11673 	struct bpf_func_state *caller = cur_func(env);
11674 	struct bpf_reg_state *reg;
11675 	const char *reason;
11676 	int err, subprog;
11677 
11678 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11679 	if (err)
11680 		return err;
11681 
11682 	reg = reg_state(env, insn->dst_reg);
11683 	if (reg->type != PTR_TO_FUNC) {
11684 		verbose(env, "R%d has type %s, expected func\n", insn->dst_reg,
11685 			reg_type_str(env, reg->type));
11686 		reason = bpf_diag_fmt(
11687 			env, "R%d holds %s, but callx can only call through the address of a static BPF function.",
11688 			insn->dst_reg, bpf_diag_reg_type_plain(env, reg->type));
11689 		bpf_diag_register_type(
11690 			env, *insn_idx, insn->dst_reg, "indirect call through a non-function pointer", reason,
11691 			"Load the address of a static BPF function into the register before callx.");
11692 		return -EACCES;
11693 	}
11694 
11695 	/*
11696 	 * Arithmetic on PTR_TO_FUNC is allowed, but only unmodified address
11697 	 * of a subprog can be called.
11698 	 */
11699 	err = check_ptr_off_reg(env, reg, insn->dst_reg);
11700 	if (err)
11701 		return err;
11702 
11703 	/* the callx is valid, but only a JIT can execute it */
11704 	err = require_callx_jit(env);
11705 	if (err)
11706 		return err;
11707 
11708 	/* PTR_TO_FUNC is a pointer to a static subprog */
11709 	subprog = reg->subprogno;
11710 	err = btf_check_subprog_call(env, subprog);
11711 	if (err == -EFAULT)
11712 		return err;
11713 
11714 	err = record_callx_edge(env, caller->subprogno, subprog);
11715 	if (err)
11716 		return err;
11717 
11718 	return check_static_func_call(env, subprog, insn_idx);
11719 }
11720 
11721 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
11722 				   struct bpf_func_state *caller,
11723 				   struct bpf_func_state *callee)
11724 {
11725 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
11726 	 *      void *callback_ctx, u64 flags);
11727 	 * callback_fn(struct bpf_map *map, void *key, void *value,
11728 	 *      void *callback_ctx);
11729 	 */
11730 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11731 
11732 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11733 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11734 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11735 	callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid;
11736 
11737 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11738 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11739 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
11740 	callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid;
11741 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11742 
11743 	/* pointer to stack or null */
11744 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
11745 
11746 	/* unused */
11747 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11748 	return 0;
11749 }
11750 
11751 static int set_callee_state(struct bpf_verifier_env *env,
11752 			    struct bpf_func_state *caller,
11753 			    struct bpf_func_state *callee, int insn_idx)
11754 {
11755 	int i;
11756 
11757 	/* copy r1 - r5 args that callee can access.  The copy includes parent
11758 	 * pointers, which connects us up to the liveness chain
11759 	 */
11760 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
11761 		callee->regs[i] = caller->regs[i];
11762 	return 0;
11763 }
11764 
11765 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
11766 				       struct bpf_func_state *caller,
11767 				       struct bpf_func_state *callee,
11768 				       int insn_idx)
11769 {
11770 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
11771 	struct bpf_map *map;
11772 	int err;
11773 
11774 	/* valid map_ptr and poison value does not matter */
11775 	map = insn_aux->map_ptr_state.map_ptr;
11776 	if (!map->ops->map_set_for_each_callback_args ||
11777 	    !map->ops->map_for_each_callback) {
11778 		verbose(env, "callback function not allowed for map\n");
11779 		return -ENOTSUPP;
11780 	}
11781 
11782 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
11783 	if (err)
11784 		return err;
11785 
11786 	switch (map->map_type) {
11787 	case BPF_MAP_TYPE_HASH:
11788 	case BPF_MAP_TYPE_PERCPU_HASH:
11789 	case BPF_MAP_TYPE_LRU_HASH:
11790 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11791 	case BPF_MAP_TYPE_RHASH:
11792 		/* Hash tables run the callback under rcu_read_lock(). */
11793 		callee->in_rcu_callback_fn = true;
11794 		break;
11795 	default:
11796 		break;
11797 	}
11798 
11799 	callee->in_callback_fn = true;
11800 	callee->callback_ret_range = retval_range(0, 1);
11801 	return 0;
11802 }
11803 
11804 static int set_loop_callback_state(struct bpf_verifier_env *env,
11805 				   struct bpf_func_state *caller,
11806 				   struct bpf_func_state *callee,
11807 				   int insn_idx)
11808 {
11809 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
11810 	 *	    u64 flags);
11811 	 * callback_fn(u64 index, void *callback_ctx);
11812 	 */
11813 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
11814 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11815 
11816 	/* unused */
11817 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11818 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11819 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11820 
11821 	callee->in_callback_fn = true;
11822 	callee->callback_ret_range = retval_range(0, 1);
11823 	return 0;
11824 }
11825 
11826 static int set_timer_callback_state(struct bpf_verifier_env *env,
11827 				    struct bpf_func_state *caller,
11828 				    struct bpf_func_state *callee,
11829 				    int insn_idx)
11830 {
11831 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
11832 	u32 map_uid = caller->regs[BPF_REG_1].map_uid;
11833 
11834 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
11835 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11836 	 */
11837 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11838 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11839 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11840 	callee->regs[BPF_REG_1].map_uid = map_uid;
11841 
11842 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11843 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11844 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11845 	callee->regs[BPF_REG_2].map_uid = map_uid;
11846 
11847 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11848 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11849 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11850 	callee->regs[BPF_REG_3].map_uid = map_uid;
11851 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11852 
11853 	/* unused */
11854 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11855 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11856 	callee->in_async_callback_fn = true;
11857 	callee->callback_ret_range = retval_range(0, 0);
11858 	return 0;
11859 }
11860 
11861 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
11862 				       struct bpf_func_state *caller,
11863 				       struct bpf_func_state *callee,
11864 				       int insn_idx)
11865 {
11866 	/* bpf_find_vma(struct task_struct *task, u64 addr,
11867 	 *               void *callback_fn, void *callback_ctx, u64 flags)
11868 	 * (callback_fn)(struct task_struct *task,
11869 	 *               struct vm_area_struct *vma, void *callback_ctx);
11870 	 */
11871 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
11872 
11873 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
11874 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11875 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
11876 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
11877 
11878 	/* pointer to stack or null */
11879 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
11880 
11881 	/* unused */
11882 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11883 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11884 	callee->in_callback_fn = true;
11885 	/* bpf_find_vma() runs the callback under mmap_lock and RCU. */
11886 	callee->in_rcu_callback_fn = true;
11887 	callee->callback_ret_range = retval_range(0, 1);
11888 	return 0;
11889 }
11890 
11891 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
11892 					   struct bpf_func_state *caller,
11893 					   struct bpf_func_state *callee,
11894 					   int insn_idx)
11895 {
11896 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
11897 	 *			  callback_ctx, u64 flags);
11898 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
11899 	 */
11900 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
11901 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
11902 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
11903 
11904 	/* unused */
11905 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11906 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11907 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11908 
11909 	callee->in_callback_fn = true;
11910 	callee->callback_ret_range = retval_range(0, 1);
11911 	return 0;
11912 }
11913 
11914 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
11915 					 struct bpf_func_state *caller,
11916 					 struct bpf_func_state *callee,
11917 					 int insn_idx)
11918 {
11919 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
11920 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
11921 	 *
11922 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
11923 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
11924 	 * by this point, so look at 'root'
11925 	 */
11926 	struct btf_field *field;
11927 
11928 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
11929 				      caller->regs[BPF_REG_1].var_off.value,
11930 				      BPF_RB_ROOT);
11931 	if (!field || !field->graph_root.value_btf_id)
11932 		return -EFAULT;
11933 
11934 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
11935 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
11936 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
11937 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
11938 
11939 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11940 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11941 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11942 	callee->in_callback_fn = true;
11943 	callee->callback_ret_range = retval_range(0, 1);
11944 	return 0;
11945 }
11946 
11947 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11948 						 struct bpf_func_state *caller,
11949 						 struct bpf_func_state *callee,
11950 						 int insn_idx)
11951 {
11952 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11953 	u32 map_uid = caller->regs[BPF_REG_3].map_uid;
11954 
11955 	/*
11956 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11957 	 */
11958 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11959 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11960 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11961 	callee->regs[BPF_REG_1].map_uid = map_uid;
11962 
11963 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11964 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11965 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
11966 	callee->regs[BPF_REG_2].map_uid = map_uid;
11967 
11968 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11969 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11970 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
11971 	callee->regs[BPF_REG_3].map_uid = map_uid;
11972 	callee->regs[BPF_REG_3].id = ++env->id_gen;
11973 
11974 	/* unused */
11975 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11976 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11977 	callee->in_async_callback_fn = true;
11978 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11979 	return 0;
11980 }
11981 
11982 static int set_rcu_callback_state(struct bpf_verifier_env *env,
11983 				  struct bpf_func_state *caller,
11984 				  struct bpf_func_state *callee,
11985 				  int insn_idx)
11986 {
11987 	struct bpf_map *map_ptr = caller->regs[BPF_REG_2].map_ptr;
11988 	u32 map_uid = caller->regs[BPF_REG_2].map_uid;
11989 
11990 	/*
11991 	 * callback_fn(struct bpf_map *map, void *key, void *value);
11992 	 */
11993 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11994 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11995 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
11996 	callee->regs[BPF_REG_1].map_uid = map_uid;
11997 
11998 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11999 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
12000 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
12001 	callee->regs[BPF_REG_2].map_uid = map_uid;
12002 
12003 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
12004 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
12005 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
12006 	callee->regs[BPF_REG_3].map_uid = map_uid;
12007 
12008 	/* unused */
12009 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
12010 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
12011 	callee->in_async_callback_fn = true;
12012 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
12013 	return 0;
12014 }
12015 
12016 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
12017 
12018 static void account_processed_insn(struct bpf_verifier_env *env)
12019 {
12020 	struct bpf_func_state *frame = cur_func(env);
12021 
12022 	env->insn_processed++;
12023 	frame->insns_subtotal++;
12024 	env->subprog_info[frame->subprogno].insns_self++;
12025 }
12026 
12027 static void account_processed_insns(struct bpf_verifier_env *env,
12028 				    struct bpf_func_state *callee,
12029 				    struct bpf_func_state *caller)
12030 {
12031 	u32 insns;
12032 
12033 	if (!callee)
12034 		return;
12035 
12036 	insns = callee->insns_subtotal;
12037 
12038 	env->subprog_info[callee->subprogno].insns_total += insns;
12039 	if (caller)
12040 		caller->insns_subtotal += insns;
12041 	callee->insns_subtotal = 0;
12042 }
12043 
12044 static void account_current_path(struct bpf_verifier_env *env)
12045 {
12046 	struct bpf_verifier_state *state = env->cur_state;
12047 	int frame;
12048 
12049 	for (frame = state->curframe; frame >= 0; frame--)
12050 		account_processed_insns(env, state->frame[frame],
12051 					frame ? state->frame[frame - 1] : NULL);
12052 }
12053 
12054 /*
12055  * Are we currently verifying the callback for an rbtree kfunc that must
12056  * be called with a lock held, or one of that callback's subprogs? If so,
12057  * no need to complain about an unreleased lock.
12058  */
12059 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
12060 {
12061 	struct bpf_verifier_state *state = env->cur_state;
12062 	struct bpf_insn *insn = env->prog->insnsi;
12063 	struct bpf_func_state *callee;
12064 	int kfunc_btf_id;
12065 	u32 frame;
12066 
12067 	for (frame = state->curframe; frame; frame--) {
12068 		callee = state->frame[frame];
12069 		if (!callee->in_callback_fn)
12070 			continue;
12071 
12072 		kfunc_btf_id = insn[callee->callsite].imm;
12073 		if (is_rbtree_lock_required_kfunc(kfunc_btf_id))
12074 			return true;
12075 	}
12076 
12077 	return false;
12078 }
12079 
12080 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
12081 {
12082 	if (range.return_32bit)
12083 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
12084 	else
12085 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
12086 }
12087 
12088 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
12089 {
12090 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
12091 	struct bpf_func_state *caller, *callee;
12092 	struct bpf_reg_state *r0;
12093 	bool in_callback_fn;
12094 	u32 i, nregs;
12095 	int err;
12096 
12097 	callee = state->frame[state->curframe];
12098 	r0 = &callee->regs[BPF_REG_0];
12099 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
12100 	for (i = 0; i < nregs; i++) {
12101 		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
12102 			continue;
12103 		/* technically it's ok to return caller's stack pointer
12104 		 * (or caller's caller's pointer) back to the caller,
12105 		 * since these pointers are valid. Only current stack
12106 		 * pointer will be invalid as soon as function exits,
12107 		 * but let's be conservative
12108 		 */
12109 		verbose(env, "cannot return stack pointer to the caller\n");
12110 		return -EINVAL;
12111 	}
12112 
12113 	caller = state->frame[state->curframe - 1];
12114 	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx])) {
12115 		/* the helper or the kfunc that called it doesn't expect that */
12116 		if (callee->in_callback_fn) {
12117 			verbose(env, "callback cannot unwind\n");
12118 			return -EINVAL;
12119 		}
12120 		if (!bpf_is_unwind_goto(&env->prog->insnsi[callee->callsite + 1])) {
12121 			verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
12122 				callee->callsite);
12123 			return -EINVAL;
12124 		}
12125 		state->unwound = true;
12126 	}
12127 	if (callee->in_callback_fn) {
12128 		if (r0->type != SCALAR_VALUE) {
12129 			verbose(env, "R0 not a scalar value\n");
12130 			return -EACCES;
12131 		}
12132 
12133 		/* we are going to rely on register's precise value */
12134 		err = mark_chain_precision(env, BPF_REG_0);
12135 		if (err)
12136 			return err;
12137 
12138 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
12139 		if (!retval_range_within(callee->callback_ret_range, r0)) {
12140 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
12141 					       "At callback return", "R0");
12142 			return -EINVAL;
12143 		}
12144 		if (!bpf_calls_callback(env, callee->callsite)) {
12145 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
12146 				     *insn_idx, callee->callsite);
12147 			return -EFAULT;
12148 		}
12149 	} else {
12150 		/*
12151 		 * return to the caller whatever the callee had in the
12152 		 * return register(s)
12153 		 */
12154 		for (i = 0; i < nregs; i++) {
12155 			u32 regno = ret_regs[i];
12156 
12157 			bpf_diag_mod_begin(env, &caller->regs[regno], &callee->regs[regno],
12158 					   BPF_DIAG_MOD_WRITE);
12159 			caller->regs[regno] = callee->regs[regno];
12160 			bpf_diag_mod_end(env);
12161 		}
12162 	}
12163 
12164 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
12165 	err = destroy_dynptrs_in_stack_slots(env, callee, 0,
12166 					     callee->allocated_stack / BPF_REG_SIZE - 1);
12167 	if (err)
12168 		return err;
12169 
12170 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
12171 	 * there function call logic would reschedule callback visit. If iteration
12172 	 * converges is_state_visited() would prune that visit eventually.
12173 	 */
12174 	in_callback_fn = callee->in_callback_fn;
12175 	if (in_callback_fn)
12176 		*insn_idx = callee->callsite;
12177 	else
12178 		*insn_idx = callee->callsite + 1;
12179 
12180 	if (env->log.level & BPF_LOG_LEVEL) {
12181 		verbose(env, "returning from callee:\n");
12182 		print_verifier_state(env, state, callee->frameno, true);
12183 		verbose(env, "to caller at %d:\n", *insn_idx);
12184 		print_verifier_state(env, state, caller->frameno, true);
12185 	}
12186 	account_processed_insns(env, callee, caller);
12187 	/* clear everything in the callee. In case of exceptional exits using
12188 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
12189 	free_func_state(callee);
12190 	state->frame[state->curframe--] = NULL;
12191 	invalidate_outgoing_stack_args(env, caller);
12192 
12193 	/* for callbacks widen imprecise scalars to make programs like below verify:
12194 	 *
12195 	 *   struct ctx { int i; }
12196 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
12197 	 *   ...
12198 	 *   struct ctx = { .i = 0; }
12199 	 *   bpf_loop(100, cb, &ctx, 0);
12200 	 *
12201 	 * This is similar to what is done in process_iter_next_call() for open
12202 	 * coded iterators.
12203 	 */
12204 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
12205 	if (prev_st) {
12206 		err = widen_imprecise_scalars(env, prev_st, state);
12207 		if (err)
12208 			return err;
12209 	}
12210 	return 0;
12211 }
12212 
12213 static int do_refine_retval_range(struct bpf_verifier_env *env,
12214 				  struct bpf_reg_state *regs, int ret_type,
12215 				  int func_id,
12216 				  struct bpf_call_arg_meta *meta)
12217 {
12218 	struct bpf_retval_range range;
12219 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
12220 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12221 
12222 	if (ret_type != RET_INTEGER)
12223 		return 0;
12224 
12225 	switch (func_id) {
12226 	case BPF_FUNC_get_stack:
12227 	case BPF_FUNC_get_task_stack:
12228 	case BPF_FUNC_probe_read_str:
12229 	case BPF_FUNC_probe_read_kernel_str:
12230 	case BPF_FUNC_probe_read_user_str:
12231 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
12232 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
12233 		reg_bounds_sync(ret_reg);
12234 		break;
12235 	case BPF_FUNC_get_smp_processor_id:
12236 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
12237 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
12238 		reg_bounds_sync(ret_reg);
12239 		break;
12240 	case BPF_FUNC_get_retval:
12241 		/*
12242 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
12243 		 * CGROUP_GETSOCKOPT type.
12244 		 */
12245 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
12246 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
12247 			break;
12248 
12249 		if (prog_type == BPF_PROG_TYPE_LSM &&
12250 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
12251 			if (!env->prog->aux->attach_func_proto->type)
12252 				break;
12253 			bpf_lsm_get_retval_range(env->prog, &range);
12254 		} else {
12255 			range.minval = -MAX_ERRNO;
12256 			range.maxval = 0;
12257 		}
12258 
12259 		reg_set_srange64(ret_reg, range.minval, range.maxval);
12260 		reg_set_srange32(ret_reg, range.minval, range.maxval);
12261 		reg_bounds_sync(ret_reg);
12262 		break;
12263 	}
12264 
12265 	return reg_bounds_sanity_check(env, ret_reg, "retval");
12266 }
12267 
12268 static int
12269 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12270 		int func_id, int insn_idx)
12271 {
12272 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12273 	struct bpf_map *map = meta->map.ptr;
12274 
12275 	if (func_id != BPF_FUNC_tail_call &&
12276 	    func_id != BPF_FUNC_map_lookup_elem &&
12277 	    func_id != BPF_FUNC_map_update_elem &&
12278 	    func_id != BPF_FUNC_map_delete_elem &&
12279 	    func_id != BPF_FUNC_map_push_elem &&
12280 	    func_id != BPF_FUNC_map_pop_elem &&
12281 	    func_id != BPF_FUNC_map_peek_elem &&
12282 	    func_id != BPF_FUNC_for_each_map_elem &&
12283 	    func_id != BPF_FUNC_redirect_map &&
12284 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
12285 		return 0;
12286 
12287 	if (map == NULL) {
12288 		verifier_bug(env, "expected map for helper call");
12289 		return -EFAULT;
12290 	}
12291 
12292 	/* In case of read-only, some additional restrictions
12293 	 * need to be applied in order to prevent altering the
12294 	 * state of the map from program side.
12295 	 */
12296 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
12297 	    (func_id == BPF_FUNC_map_delete_elem ||
12298 	     func_id == BPF_FUNC_map_update_elem ||
12299 	     func_id == BPF_FUNC_map_push_elem ||
12300 	     func_id == BPF_FUNC_map_pop_elem)) {
12301 		verbose(env, "write into map forbidden\n");
12302 		return -EACCES;
12303 	}
12304 
12305 	if (!aux->map_ptr_state.map_ptr)
12306 		bpf_map_ptr_store(aux, meta->map.ptr,
12307 				  !meta->map.ptr->bypass_spec_v1, false);
12308 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
12309 		bpf_map_ptr_store(aux, meta->map.ptr,
12310 				  !meta->map.ptr->bypass_spec_v1, true);
12311 	return 0;
12312 }
12313 
12314 static int
12315 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12316 		int func_id, int insn_idx)
12317 {
12318 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12319 	struct bpf_reg_state *reg;
12320 	struct bpf_map *map = meta->map.ptr;
12321 	u64 val, max;
12322 	int err;
12323 
12324 	if (func_id != BPF_FUNC_tail_call)
12325 		return 0;
12326 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
12327 		verbose(env, "expected prog array map for tail call");
12328 		return -EINVAL;
12329 	}
12330 
12331 	reg = reg_state(env, BPF_REG_3);
12332 	val = reg->var_off.value;
12333 	max = map->max_entries;
12334 
12335 	if (!(is_reg_const(reg, false) && val < max)) {
12336 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12337 		return 0;
12338 	}
12339 
12340 	err = mark_chain_precision(env, BPF_REG_3);
12341 	if (err)
12342 		return err;
12343 	if (bpf_map_key_unseen(aux))
12344 		bpf_map_key_store(aux, val);
12345 	else if (!bpf_map_key_poisoned(aux) &&
12346 		  bpf_map_key_immediate(aux) != val)
12347 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
12348 	return 0;
12349 }
12350 
12351 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
12352 {
12353 	struct bpf_verifier_state *state = env->cur_state;
12354 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12355 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
12356 	bool refs_lingering = false;
12357 	int i;
12358 
12359 	if (!exception_exit && cur_func(env)->frameno)
12360 		return 0;
12361 
12362 	for (i = 0; i < state->acquired_refs; i++) {
12363 		if (state->refs[i].type != REF_TYPE_PTR)
12364 			continue;
12365 		/* Allow struct_ops programs to return a referenced kptr back to
12366 		 * kernel. Type checks are performed later in check_return_code.
12367 		 */
12368 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
12369 		    reg->id == state->refs[i].id)
12370 			continue;
12371 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
12372 			state->refs[i].id, state->refs[i].insn_idx);
12373 		bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx);
12374 		refs_lingering = true;
12375 	}
12376 	return refs_lingering ? -EINVAL : 0;
12377 }
12378 
12379 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
12380 {
12381 	int err;
12382 
12383 	if (check_lock && env->cur_state->active_locks) {
12384 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
12385 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_LOCK,
12386 				    "Release the BPF spin lock before this operation on every path.");
12387 		return -EINVAL;
12388 	}
12389 
12390 	err = check_reference_leak(env, exception_exit);
12391 	if (err) {
12392 		verbose(env, "%s would lead to reference leak\n", prefix);
12393 		return err;
12394 	}
12395 
12396 	if (check_lock && env->cur_state->active_irq_id) {
12397 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
12398 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_IRQ,
12399 				    "Restore the saved IRQ state before this operation on every path.");
12400 		return -EINVAL;
12401 	}
12402 
12403 	if (check_lock && env->cur_state->active_rcu_locks) {
12404 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
12405 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_RCU,
12406 				    "Call bpf_rcu_read_unlock() before this operation on every path.");
12407 		return -EINVAL;
12408 	}
12409 
12410 	if (check_lock && env->cur_state->active_preempt_locks) {
12411 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
12412 		bpf_diag_ctx_active(
12413 			env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_PREEMPT,
12414 			"Call bpf_preempt_enable() before this operation on every path.");
12415 		return -EINVAL;
12416 	}
12417 
12418 	return 0;
12419 }
12420 
12421 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
12422 				   struct bpf_reg_state *regs)
12423 {
12424 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
12425 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
12426 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
12427 	struct bpf_bprintf_data data = {};
12428 	int err, fmt_map_off, num_args;
12429 	u64 fmt_addr;
12430 	char *fmt;
12431 
12432 	/* data must be an array of u64 */
12433 	if (data_len_reg->var_off.value % 8)
12434 		return -EINVAL;
12435 	num_args = data_len_reg->var_off.value / 8;
12436 
12437 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
12438 	 * and map_direct_value_addr is set.
12439 	 */
12440 	fmt_map_off = fmt_reg->var_off.value;
12441 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
12442 						  fmt_map_off);
12443 	if (err) {
12444 		verbose(env, "failed to retrieve map value address\n");
12445 		return -EFAULT;
12446 	}
12447 	fmt = (char *)(long)fmt_addr + fmt_map_off;
12448 
12449 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
12450 	 * can focus on validating the format specifiers.
12451 	 */
12452 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
12453 	if (err < 0)
12454 		verbose(env, "Invalid format string\n");
12455 
12456 	return err;
12457 }
12458 
12459 static int check_get_func_ip(struct bpf_verifier_env *env)
12460 {
12461 	enum bpf_prog_type type = resolve_prog_type(env->prog);
12462 	int func_id = BPF_FUNC_get_func_ip;
12463 
12464 	if (type == BPF_PROG_TYPE_TRACING) {
12465 		if (!bpf_prog_has_trampoline(env->prog)) {
12466 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
12467 				func_id_name(func_id), func_id);
12468 			return -ENOTSUPP;
12469 		}
12470 		return 0;
12471 	} else if (type == BPF_PROG_TYPE_KPROBE) {
12472 		return 0;
12473 	}
12474 
12475 	verbose(env, "func %s#%d not supported for program type %d\n",
12476 		func_id_name(func_id), func_id, type);
12477 	return -ENOTSUPP;
12478 }
12479 
12480 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
12481 {
12482 	return &env->insn_aux_data[env->insn_idx];
12483 }
12484 
12485 /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */
12486 static int loop_flag_is_zero(struct bpf_verifier_env *env)
12487 {
12488 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
12489 	int err;
12490 
12491 	if (!bpf_register_is_null(reg))
12492 		return 0;
12493 
12494 	err = mark_chain_precision(env, BPF_REG_4);
12495 	if (err)
12496 		return err;
12497 	return 1;
12498 }
12499 
12500 static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
12501 {
12502 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
12503 	int flag_is_zero;
12504 
12505 	if (!state->initialized) {
12506 		flag_is_zero = loop_flag_is_zero(env);
12507 		if (flag_is_zero < 0)
12508 			return flag_is_zero;
12509 		state->initialized = 1;
12510 		state->fit_for_inline = flag_is_zero;
12511 		state->callback_subprogno = subprogno;
12512 		return 0;
12513 	}
12514 
12515 	if (!state->fit_for_inline)
12516 		return 0;
12517 
12518 	flag_is_zero = loop_flag_is_zero(env);
12519 	if (flag_is_zero < 0)
12520 		return flag_is_zero;
12521 	state->fit_for_inline = (flag_is_zero &&
12522 				 state->callback_subprogno == subprogno);
12523 	return 0;
12524 }
12525 
12526 /* Returns whether or not the given map can potentially elide
12527  * lookup return value nullness check. This is possible if the key
12528  * is statically known.
12529  */
12530 static bool can_elide_value_nullness(const struct bpf_map *map)
12531 {
12532 	if (map->map_flags & BPF_F_INNER_MAP)
12533 		return false;
12534 
12535 	switch (map->map_type) {
12536 	case BPF_MAP_TYPE_ARRAY:
12537 	case BPF_MAP_TYPE_PERCPU_ARRAY:
12538 		return true;
12539 	default:
12540 		return false;
12541 	}
12542 }
12543 
12544 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
12545 			 const struct bpf_func_proto **ptr)
12546 {
12547 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
12548 		return -ERANGE;
12549 
12550 	if (!env->ops->get_func_proto)
12551 		return -EINVAL;
12552 
12553 	*ptr = env->ops->get_func_proto(func_id, env->prog);
12554 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
12555 }
12556 
12557 /* Is any frame on the current path a callback that runs under RCU? */
12558 static bool in_rcu_callback(struct bpf_verifier_env *env)
12559 {
12560 	struct bpf_verifier_state *state = env->cur_state;
12561 	int i;
12562 
12563 	for (i = 0; i <= state->curframe; i++)
12564 		if (state->frame[i]->in_rcu_callback_fn)
12565 			return true;
12566 	return false;
12567 }
12568 
12569 /* Check if we're in a sleepable context. */
12570 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
12571 {
12572 	return !in_rcu_cs(env) && !in_rcu_callback(env);
12573 }
12574 
12575 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
12576 {
12577 	if (in_sleepable(env)) {
12578 		if (env->cur_state->active_rcu_locks)
12579 			return "rcu_read_lock region";
12580 		if (env->cur_state->active_preempt_locks)
12581 			return "non-preemptible region";
12582 		if (env->cur_state->active_irq_id)
12583 			return "IRQ-disabled region";
12584 		if (env->cur_state->active_locks)
12585 			return "lock region";
12586 		return "callback running under rcu_read_lock";
12587 	}
12588 	return "non-sleepable prog";
12589 }
12590 
12591 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
12592 		       bool convert_rcu, bool release_dynptr)
12593 {
12594 	int err = -EINVAL;
12595 
12596 	if (bpf_register_is_null(reg))
12597 		return 0;
12598 
12599 	if (release_dynptr)
12600 		err = unmark_stack_slots_dynptr(env, reg);
12601 	else if (convert_rcu)
12602 		err = ref_convert_alloc_rcu_protected(env, reg->id);
12603 	else if (reg_is_referenced(env, reg))
12604 		err = release_reference(env, reg->id);
12605 
12606 	return err;
12607 }
12608 
12609 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12610 			     int *insn_idx_p)
12611 {
12612 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12613 	bool returns_cpu_specific_alloc_ptr = false;
12614 	const struct bpf_func_proto *fn = NULL;
12615 	enum bpf_return_type ret_type;
12616 	enum bpf_type_flag ret_flag;
12617 	struct bpf_reg_state *regs;
12618 	struct bpf_call_arg_meta meta;
12619 	const char *operation;
12620 	int insn_idx = *insn_idx_p;
12621 	bool changes_data;
12622 	int i, err, func_id;
12623 
12624 	/* find function prototype */
12625 	func_id = insn->imm;
12626 	err = bpf_get_helper_proto(env, insn->imm, &fn);
12627 	if (err == -ERANGE) {
12628 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
12629 		return -EINVAL;
12630 	}
12631 
12632 	if (err) {
12633 		verbose(env, "program of this type cannot use helper %s#%d\n",
12634 			func_id_name(func_id), func_id);
12635 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12636 		bpf_diag_policy(
12637 			env, insn_idx, operation, "this program type does not allow the helper",
12638 			"Use a helper allowed for this program type, or move the logic to a compatible program type.");
12639 		return err;
12640 	}
12641 
12642 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
12643 	if (!env->prog->gpl_compatible && fn->gpl_only) {
12644 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
12645 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12646 		bpf_diag_policy(
12647 			env, insn_idx, operation,
12648 			"this helper is restricted to GPL-compatible programs",
12649 			"Use a GPL-compatible license, or replace the helper with one that is available to non-GPL programs.");
12650 		return -EINVAL;
12651 	}
12652 
12653 	if (fn->allowed && !fn->allowed(env->prog)) {
12654 		verbose(env, "helper call is not allowed in probe\n");
12655 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
12656 		bpf_diag_policy(
12657 			env, insn_idx, operation,
12658 			"the helper-specific policy callback rejected this program",
12659 			"Use the helper only from an allowed attach point or program configuration.");
12660 		return -EINVAL;
12661 	}
12662 
12663 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
12664 	changes_data = bpf_helper_changes_pkt_data(func_id);
12665 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
12666 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
12667 		return -EFAULT;
12668 	}
12669 
12670 	memset(&meta, 0, sizeof(meta));
12671 
12672 	err = check_func_proto(env, fn, &meta);
12673 	if (err) {
12674 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
12675 		return err;
12676 	}
12677 
12678 	if (fn->might_sleep && !in_sleepable_context(env)) {
12679 		const char *suggestion;
12680 
12681 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
12682 			non_sleepable_context_description(env));
12683 		if (in_sleepable(env))
12684 			suggestion = "Move the helper call outside the critical section, or use a non-sleepable helper.";
12685 		else
12686 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable helper.";
12687 		operation = bpf_diag_fmt(env, "sleepable helper %s#%d",
12688 					 func_id_name(func_id), func_id);
12689 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
12690 		return -EINVAL;
12691 	}
12692 
12693 	/* Track non-sleepable context for helpers. */
12694 	if (!in_sleepable_context(env))
12695 		env->insn_aux_data[insn_idx].non_sleepable = true;
12696 
12697 	meta.func_id = func_id;
12698 	meta.func_name = func_id_name(func_id);
12699 	meta.fn = fn;
12700 	err = check_func_args(env, &meta, insn_idx);
12701 	if (err)
12702 		return err;
12703 
12704 	err = record_func_map(env, &meta, func_id, insn_idx);
12705 	if (err)
12706 		return err;
12707 
12708 	err = record_func_key(env, &meta, func_id, insn_idx);
12709 	if (err)
12710 		return err;
12711 
12712 	regs = cur_regs(env);
12713 
12714 	err = mark_raw_stack(env, &meta, insn_idx);
12715 	if (err)
12716 		return err;
12717 
12718 	if (meta.release_regno) {
12719 		struct bpf_reg_state *reg = &regs[meta.release_regno];
12720 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
12721 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
12722 
12723 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
12724 		if (err)
12725 			return err;
12726 	}
12727 
12728 	switch (func_id) {
12729 	case BPF_FUNC_tail_call:
12730 		err = check_resource_leak(env, false, true, "tail_call");
12731 		if (err)
12732 			return err;
12733 		break;
12734 	case BPF_FUNC_get_local_storage:
12735 		/* check that flags argument in get_local_storage(map, flags) is 0,
12736 		 * this is required because get_local_storage() can't return an error.
12737 		 */
12738 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
12739 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
12740 			return -EINVAL;
12741 		}
12742 		err = mark_chain_precision(env, BPF_REG_2);
12743 		if (err)
12744 			return err;
12745 		break;
12746 	case BPF_FUNC_for_each_map_elem:
12747 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12748 					 set_map_elem_callback_state);
12749 		break;
12750 	case BPF_FUNC_timer_set_callback:
12751 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12752 					 set_timer_callback_state);
12753 		break;
12754 	case BPF_FUNC_find_vma:
12755 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12756 					 set_find_vma_callback_state);
12757 		break;
12758 	case BPF_FUNC_snprintf:
12759 		err = check_bpf_snprintf_call(env, regs);
12760 		break;
12761 	case BPF_FUNC_loop:
12762 		err = update_loop_inline_state(env, meta.subprogno);
12763 		if (err)
12764 			return err;
12765 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
12766 		 * is finished, thus mark it precise.
12767 		 */
12768 		err = mark_chain_precision(env, BPF_REG_1);
12769 		if (err)
12770 			return err;
12771 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
12772 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12773 						 set_loop_callback_state);
12774 		} else {
12775 			cur_func(env)->callback_depth = 0;
12776 			if (env->log.level & BPF_LOG_LEVEL2)
12777 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
12778 					env->cur_state->curframe);
12779 		}
12780 		break;
12781 	case BPF_FUNC_dynptr_from_mem:
12782 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
12783 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
12784 				reg_type_str(env, regs[BPF_REG_1].type));
12785 			return -EACCES;
12786 		}
12787 		break;
12788 	case BPF_FUNC_set_retval:
12789 	{
12790 		struct bpf_retval_range range = {
12791 			.minval = -MAX_ERRNO,
12792 			.maxval = 0,
12793 			.return_32bit = true
12794 		};
12795 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
12796 
12797 		if (r1->type != SCALAR_VALUE) {
12798 			verbose(env, "R1 is not a scalar\n");
12799 			return -EINVAL;
12800 		}
12801 
12802 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
12803 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
12804 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
12805 			break;
12806 
12807 		if (prog_type == BPF_PROG_TYPE_LSM &&
12808 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
12809 			if (!env->prog->aux->attach_func_proto->type) {
12810 				/* Make sure programs that attach to void
12811 				 * hooks don't try to modify return value.
12812 				 */
12813 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
12814 				return -EINVAL;
12815 			}
12816 			bpf_lsm_get_retval_range(env->prog, &range);
12817 		}
12818 
12819 		err = mark_chain_precision(env, BPF_REG_1);
12820 		if (err)
12821 			return err;
12822 
12823 		if (!retval_range_within(range, r1)) {
12824 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
12825 			return -EINVAL;
12826 		}
12827 
12828 		break;
12829 	}
12830 	case BPF_FUNC_dynptr_write:
12831 	{
12832 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
12833 
12834 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
12835 			return -EFAULT;
12836 
12837 		if (dynptr_write_changes_pkt_data(dynptr_type))
12838 			/* this will trigger clear_all_pkt_pointers(), which will
12839 			 * invalidate all dynptr slices associated with the skb
12840 			 */
12841 			changes_data = true;
12842 
12843 		break;
12844 	}
12845 	case BPF_FUNC_per_cpu_ptr:
12846 	case BPF_FUNC_this_cpu_ptr:
12847 	{
12848 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
12849 		const struct btf_type *type;
12850 
12851 		if (reg->type & MEM_RCU) {
12852 			type = btf_type_by_id(reg->btf, reg->btf_id);
12853 			if (!type || !btf_type_is_struct(type)) {
12854 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
12855 				return -EFAULT;
12856 			}
12857 			returns_cpu_specific_alloc_ptr = true;
12858 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
12859 		}
12860 		break;
12861 	}
12862 	case BPF_FUNC_user_ringbuf_drain:
12863 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12864 					 set_user_ringbuf_callback_state);
12865 		break;
12866 	}
12867 
12868 	if (err)
12869 		return err;
12870 
12871 	/* reset caller saved regs */
12872 	bpf_diag_record_caller_saved(env, regs);
12873 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
12874 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
12875 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
12876 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
12877 	}
12878 	invalidate_outgoing_stack_args(env, cur_func(env));
12879 
12880 	/* update return register (already marked as written above) */
12881 	ret_type = fn->ret_type;
12882 	ret_flag = type_flag(ret_type);
12883 
12884 	switch (base_type(ret_type)) {
12885 	case RET_INTEGER:
12886 		/* sets type to SCALAR_VALUE */
12887 		mark_reg_unknown(env, regs, BPF_REG_0);
12888 		break;
12889 	case RET_VOID:
12890 		regs[BPF_REG_0].type = NOT_INIT;
12891 		break;
12892 	case RET_PTR_TO_MAP_VALUE:
12893 		/* There is no offset yet applied, variable or fixed */
12894 		mark_reg_known_zero(env, regs, BPF_REG_0);
12895 		/* remember map_ptr, so that check_map_access()
12896 		 * can check 'value_size' boundary of memory access
12897 		 * to map element returned from bpf_map_lookup_elem()
12898 		 */
12899 		if (meta.map.ptr == NULL) {
12900 			verifier_bug(env, "unexpected null map_ptr");
12901 			return -EFAULT;
12902 		}
12903 
12904 		if (func_id == BPF_FUNC_map_lookup_elem &&
12905 		    can_elide_value_nullness(meta.map.ptr) &&
12906 		    meta.const_map_key >= 0 &&
12907 		    meta.const_map_key < meta.map.ptr->max_entries)
12908 			ret_flag &= ~PTR_MAYBE_NULL;
12909 
12910 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
12911 		regs[BPF_REG_0].map_uid = meta.map.uid;
12912 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
12913 		if (type_may_be_null(ret_flag) ||
12914 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
12915 			regs[BPF_REG_0].id = ++env->id_gen;
12916 		}
12917 		/* requires regs[BPF_REG_0].id to be set because of the map-in-map case */
12918 		refine_map_lookup_value(&regs[BPF_REG_0]);
12919 		break;
12920 	case RET_PTR_TO_SOCKET:
12921 		mark_reg_known_zero(env, regs, BPF_REG_0);
12922 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
12923 		break;
12924 	case RET_PTR_TO_SOCK_COMMON:
12925 		mark_reg_known_zero(env, regs, BPF_REG_0);
12926 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
12927 		break;
12928 	case RET_PTR_TO_TCP_SOCK:
12929 		mark_reg_known_zero(env, regs, BPF_REG_0);
12930 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
12931 		break;
12932 	case RET_PTR_TO_MEM:
12933 		mark_reg_known_zero(env, regs, BPF_REG_0);
12934 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
12935 		regs[BPF_REG_0].mem_size = meta.ret_mem.size;
12936 		break;
12937 	case RET_PTR_TO_MEM_OR_BTF_ID:
12938 	{
12939 		const struct btf_type *t;
12940 
12941 		mark_reg_known_zero(env, regs, BPF_REG_0);
12942 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
12943 		if (!btf_type_is_struct(t)) {
12944 			u32 tsize;
12945 			const struct btf_type *ret;
12946 			const char *tname;
12947 
12948 			/* resolve the type size of ksym. */
12949 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
12950 			if (IS_ERR(ret)) {
12951 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
12952 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
12953 					tname, PTR_ERR(ret));
12954 				return -EINVAL;
12955 			}
12956 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
12957 			regs[BPF_REG_0].mem_size = tsize;
12958 		} else {
12959 			if (returns_cpu_specific_alloc_ptr) {
12960 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
12961 			} else {
12962 				/* MEM_RDONLY may be carried from ret_flag, but it
12963 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
12964 				 * it will confuse the check of PTR_TO_BTF_ID in
12965 				 * check_mem_access().
12966 				 */
12967 				ret_flag &= ~MEM_RDONLY;
12968 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
12969 			}
12970 
12971 			regs[BPF_REG_0].btf = meta.ret_btf;
12972 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12973 		}
12974 		break;
12975 	}
12976 	case RET_PTR_TO_BTF_ID:
12977 	{
12978 		struct btf *ret_btf;
12979 		int ret_btf_id;
12980 
12981 		mark_reg_known_zero(env, regs, BPF_REG_0);
12982 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
12983 		if (func_id == BPF_FUNC_kptr_xchg) {
12984 			ret_btf = meta.kptr_field->kptr.btf;
12985 			ret_btf_id = meta.kptr_field->kptr.btf_id;
12986 			if (!btf_is_kernel(ret_btf)) {
12987 				regs[BPF_REG_0].type |= MEM_ALLOC;
12988 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
12989 					regs[BPF_REG_0].type |= MEM_PERCPU;
12990 			}
12991 		} else {
12992 			if (fn->ret_btf_id == BPF_PTR_POISON) {
12993 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
12994 					     func_id_name(func_id));
12995 				return -EFAULT;
12996 			}
12997 			ret_btf = btf_vmlinux;
12998 			ret_btf_id = *fn->ret_btf_id;
12999 		}
13000 		if (ret_btf_id == 0) {
13001 			verbose(env, "invalid return type %u of func %s#%d\n",
13002 				base_type(ret_type), func_id_name(func_id),
13003 				func_id);
13004 			return -EINVAL;
13005 		}
13006 		regs[BPF_REG_0].btf = ret_btf;
13007 		regs[BPF_REG_0].btf_id = ret_btf_id;
13008 		break;
13009 	}
13010 	default:
13011 		verbose(env, "unknown return type %u of func %s#%d\n",
13012 			base_type(ret_type), func_id_name(func_id), func_id);
13013 		return -EINVAL;
13014 	}
13015 
13016 	if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id)
13017 		regs[BPF_REG_0].id = ++env->id_gen;
13018 
13019 	if (is_ptr_cast_function(func_id) &&
13020 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
13021 		struct bpf_verifier_state *branch;
13022 		struct bpf_reg_state *r0;
13023 
13024 		err = validate_ref_obj(env, &meta.ref_obj);
13025 		if (err)
13026 			return err;
13027 
13028 		bpf_diag_mod_end(env);
13029 
13030 		/*
13031 		 * In order for a release of any of the original or cast pointers
13032 		 * to invalidate all other pointers, reuse the same reference id for
13033 		 * the cast result.
13034 		 * This reference id can't be used for nullness propagation,
13035 		 * as cast might return NULL for a non-NULL input.
13036 		 * Hence, explore the NULL case as a separate branch.
13037 		 */
13038 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13039 		if (IS_ERR(branch))
13040 			return PTR_ERR(branch);
13041 
13042 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
13043 		__mark_reg_known_zero(r0);
13044 		r0->type = SCALAR_VALUE;
13045 
13046 		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
13047 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
13048 		regs[BPF_REG_0].id = meta.ref_obj.id;
13049 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
13050 		int id = acquire_reference(env, insn_idx, 0);
13051 
13052 		if (id < 0)
13053 			return id;
13054 
13055 		regs[BPF_REG_0].id = id;
13056 	}
13057 
13058 	if (func_id == BPF_FUNC_dynptr_data)
13059 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
13060 
13061 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
13062 	if (err)
13063 		return err;
13064 
13065 	bpf_diag_mod_end(env);
13066 
13067 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
13068 	if (err)
13069 		return err;
13070 
13071 	if ((func_id == BPF_FUNC_get_stack ||
13072 	     func_id == BPF_FUNC_get_task_stack) &&
13073 	    !env->prog->has_callchain_buf) {
13074 		const char *err_str;
13075 
13076 #ifdef CONFIG_PERF_EVENTS
13077 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
13078 		err_str = "cannot get callchain buffer for func %s#%d\n";
13079 #else
13080 		err = -ENOTSUPP;
13081 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
13082 #endif
13083 		if (err) {
13084 			verbose(env, err_str, func_id_name(func_id), func_id);
13085 			return err;
13086 		}
13087 
13088 		env->prog->has_callchain_buf = true;
13089 	}
13090 
13091 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
13092 		env->prog->call_get_stack = true;
13093 
13094 	if (func_id == BPF_FUNC_get_func_ip) {
13095 		if (check_get_func_ip(env))
13096 			return -ENOTSUPP;
13097 		env->prog->call_get_func_ip = true;
13098 	}
13099 
13100 	if (func_id == BPF_FUNC_tail_call) {
13101 		if (env->cur_state->curframe) {
13102 			struct bpf_verifier_state *branch;
13103 
13104 			/*
13105 			 * A taken tail call is modeled as a return from the current
13106 			 * frame. A callback frame cannot be left that way because
13107 			 * prepare_func_exit() would apply its return contract to the
13108 			 * unknown R0 synthesized below. Stack-depth validation rejects
13109 			 * this construct anyway.
13110 			 */
13111 			if (cur_func(env)->in_callback_fn) {
13112 				verbose(env, "cannot tail call within callback\n");
13113 				return -EINVAL;
13114 			}
13115 			mark_reg_scratched(env, BPF_REG_0);
13116 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13117 			if (IS_ERR(branch))
13118 				return PTR_ERR(branch);
13119 			clear_all_pkt_pointers(env);
13120 			mark_reg_unknown(env, regs, BPF_REG_0);
13121 			err = prepare_func_exit(env, &env->insn_idx);
13122 			if (err)
13123 				return err;
13124 			env->insn_idx--;
13125 		} else {
13126 			changes_data = false;
13127 		}
13128 	}
13129 
13130 	if (changes_data)
13131 		clear_all_pkt_pointers(env);
13132 	return 0;
13133 }
13134 
13135 /*
13136  * Mark the register(s) holding a @size byte kfunc return value as unknown
13137  * scalars and return how many registers that took. Both halves of a register
13138  * pair are treated the same way.
13139  *
13140  * R0 is written in the diagnostic modification scope the caller opened before
13141  * the caller-saved scrub, since R0 gets no scrub record of its own and that
13142  * scope is what carries its pre-call value into the history. A scope tracks a
13143  * single register and does not nest, so close it before recording the rest of
13144  * the return value. A value that fits in R0 leaves the caller's scope open for
13145  * the caller to close, so a later write to R0 still lands in it.
13146  */
13147 static u32 mark_kfunc_ret_regs(struct bpf_verifier_env *env,
13148 			       struct bpf_reg_state *regs, u32 size)
13149 {
13150 	u32 i, nregs = ret_regs_cnt(size);
13151 
13152 	mark_reg_unknown(env, regs, ret_regs[0]);
13153 	if (nregs == 1)
13154 		return nregs;
13155 
13156 	bpf_diag_mod_end(env);
13157 	for (i = 1; i < nregs; i++) {
13158 		bpf_diag_mod_begin(env, &regs[ret_regs[i]], NULL, BPF_DIAG_MOD_WRITE);
13159 		mark_reg_unknown(env, regs, ret_regs[i]);
13160 		bpf_diag_mod_end(env);
13161 	}
13162 
13163 	return nregs;
13164 }
13165 
13166 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta)
13167 {
13168 	return meta->kfunc_flags & KF_ACQUIRE;
13169 }
13170 
13171 static bool is_kfunc_release(struct bpf_call_arg_meta *meta)
13172 {
13173 	return meta->kfunc_flags & KF_RELEASE;
13174 }
13175 
13176 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta)
13177 {
13178 	return meta->kfunc_flags & KF_DESTRUCTIVE;
13179 }
13180 
13181 static bool is_kfunc_perfmon(struct bpf_call_arg_meta *meta)
13182 {
13183 	return meta->kfunc_flags & KF_PERFMON;
13184 }
13185 
13186 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta)
13187 {
13188 	return meta->kfunc_flags & KF_RCU;
13189 }
13190 
13191 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta)
13192 {
13193 	return meta->kfunc_flags & KF_RCU_PROTECTED;
13194 }
13195 
13196 static bool is_kfunc_arg_mem_size(const struct btf *btf,
13197 				  const struct btf_param *arg)
13198 {
13199 	const struct btf_type *t;
13200 
13201 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13202 	if (!btf_type_is_scalar(t))
13203 		return false;
13204 
13205 	return btf_param_match_suffix(btf, arg, "__sz");
13206 }
13207 
13208 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
13209 					const struct btf_param *arg)
13210 {
13211 	const struct btf_type *t;
13212 
13213 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13214 	if (!btf_type_is_scalar(t))
13215 		return false;
13216 
13217 	return btf_param_match_suffix(btf, arg, "__szk");
13218 }
13219 
13220 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
13221 {
13222 	return btf_param_match_suffix(btf, arg, "__k");
13223 }
13224 
13225 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
13226 {
13227 	return btf_param_match_suffix(btf, arg, "__ign");
13228 }
13229 
13230 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
13231 {
13232 	return btf_param_match_suffix(btf, arg, "__map");
13233 }
13234 
13235 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg)
13236 {
13237 	return btf_param_match_suffix(btf, arg, "__const_map");
13238 }
13239 
13240 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
13241 {
13242 	return btf_param_match_suffix(btf, arg, "__alloc");
13243 }
13244 
13245 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
13246 {
13247 	return btf_param_match_suffix(btf, arg, "__uninit");
13248 }
13249 
13250 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
13251 {
13252 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
13253 }
13254 
13255 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
13256 {
13257 	return btf_param_match_suffix(btf, arg, "__nullable") ||
13258 	       btf_param_match_suffix(btf, arg, "__arena");
13259 }
13260 
13261 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
13262 {
13263 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
13264 }
13265 
13266 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
13267 {
13268 	return btf_param_match_suffix(btf, arg, "__str");
13269 }
13270 
13271 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
13272 {
13273 	return btf_param_match_suffix(btf, arg, "__irq_flag");
13274 }
13275 
13276 static bool is_kfunc_arg_ctx_out(const struct btf *btf, const struct btf_param *arg)
13277 {
13278 	return btf_param_match_suffix(btf, arg, "__ctx_out");
13279 }
13280 
13281 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg)
13282 {
13283 	return btf_param_match_suffix(btf, arg, "__arena__nullable") ||
13284 	       btf_param_match_suffix(btf, arg, "__arena");
13285 }
13286 
13287 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
13288 					  const struct btf_param *arg,
13289 					  const char *name)
13290 {
13291 	int len, target_len = strlen(name);
13292 	const char *param_name;
13293 
13294 	param_name = btf_name_by_offset(btf, arg->name_off);
13295 	if (str_is_empty(param_name))
13296 		return false;
13297 	len = strlen(param_name);
13298 	if (len != target_len)
13299 		return false;
13300 	if (strcmp(param_name, name))
13301 		return false;
13302 
13303 	return true;
13304 }
13305 
13306 enum {
13307 	KF_ARG_DYNPTR_ID,
13308 	KF_ARG_LIST_HEAD_ID,
13309 	KF_ARG_LIST_NODE_ID,
13310 	KF_ARG_RB_ROOT_ID,
13311 	KF_ARG_RB_NODE_ID,
13312 	KF_ARG_WORKQUEUE_ID,
13313 	KF_ARG_RES_SPIN_LOCK_ID,
13314 	KF_ARG_TASK_WORK_ID,
13315 	KF_ARG_PROG_AUX_ID,
13316 	KF_ARG_TIMER_ID,
13317 	KF_ARG_RCU_HEAD_ID
13318 };
13319 
13320 BTF_ID_LIST(kf_arg_btf_ids)
13321 BTF_ID(struct, bpf_dynptr)
13322 BTF_ID(struct, bpf_list_head)
13323 BTF_ID(struct, bpf_list_node)
13324 BTF_ID(struct, bpf_rb_root)
13325 BTF_ID(struct, bpf_rb_node)
13326 BTF_ID(struct, bpf_wq)
13327 BTF_ID(struct, bpf_res_spin_lock)
13328 BTF_ID(struct, bpf_task_work)
13329 BTF_ID(struct, bpf_prog_aux)
13330 BTF_ID(struct, bpf_timer)
13331 BTF_ID(struct, bpf_rcu_head)
13332 
13333 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
13334 				    const struct btf_param *arg, int type)
13335 {
13336 	const struct btf_type *t;
13337 	u32 res_id;
13338 
13339 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
13340 	if (!t)
13341 		return false;
13342 	if (!btf_type_is_ptr(t))
13343 		return false;
13344 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
13345 	if (!t)
13346 		return false;
13347 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
13348 }
13349 
13350 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
13351 {
13352 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
13353 }
13354 
13355 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
13356 {
13357 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
13358 }
13359 
13360 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
13361 {
13362 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
13363 }
13364 
13365 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
13366 {
13367 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
13368 }
13369 
13370 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
13371 {
13372 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
13373 }
13374 
13375 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
13376 {
13377 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
13378 }
13379 
13380 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
13381 {
13382 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
13383 }
13384 
13385 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
13386 {
13387 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
13388 }
13389 
13390 static bool is_kfunc_arg_rcu_head(const struct btf *btf, const struct btf_param *arg)
13391 {
13392 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RCU_HEAD_ID);
13393 }
13394 
13395 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
13396 {
13397 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
13398 }
13399 
13400 static bool is_rbtree_node_type(const struct btf_type *t)
13401 {
13402 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
13403 }
13404 
13405 static bool is_list_node_type(const struct btf_type *t)
13406 {
13407 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
13408 }
13409 
13410 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
13411 				  const struct btf_param *arg)
13412 {
13413 	const struct btf_type *t;
13414 
13415 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
13416 	if (!t)
13417 		return false;
13418 
13419 	return true;
13420 }
13421 
13422 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
13423 {
13424 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
13425 }
13426 
13427 /*
13428  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
13429  *   - the _impl prototype with full arg list (meta->func_proto)
13430  *   - the BPF API prototype w/o implicit args (func->type in BTF)
13431  * To determine whether an argument is implicit, we compare its position
13432  * against the number of arguments in the prototype w/o implicit args.
13433  */
13434 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx)
13435 {
13436 	const struct btf_type *func, *func_proto;
13437 	u32 argn;
13438 
13439 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
13440 		return false;
13441 
13442 	func = btf_type_by_id(meta->btf, meta->func_id);
13443 	func_proto = btf_type_by_id(meta->btf, func->type);
13444 	argn = btf_type_vlen(func_proto);
13445 
13446 	return argn <= arg_idx;
13447 }
13448 
13449 #define BTF_MEMBER_MAX_DEPTH	4
13450 #define BTF_MEMBER_PATH_LEN	64
13451 
13452 struct btf_member_path {
13453 	const struct btf_member *member[BTF_MEMBER_MAX_DEPTH];
13454 	bool in_array[BTF_MEMBER_MAX_DEPTH];
13455 	const struct btf_type *bad_type;
13456 	int depth;
13457 	bool too_deep;
13458 };
13459 
13460 static bool btf_member_kind_allowed(const struct btf *btf, const struct btf_type *t,
13461 				    u32 member_kinds)
13462 {
13463 	if ((member_kinds & BTF_MEMBER_SCALAR) && btf_type_is_scalar(t))
13464 		return true;
13465 	if ((member_kinds & BTF_MEMBER_ARENA_PTR) && btf_type_is_arena_ptr(btf, t))
13466 		return true;
13467 	return false;
13468 }
13469 
13470 /*
13471  * Returns true if every member of struct @t is of a kind listed in
13472  * @member_kinds, 4 levels of nesting allowed. An array member counts as its
13473  * element type.
13474  */
13475 static bool btf_struct_member_walk(struct bpf_verifier_env *env, const struct btf *btf,
13476 				   const struct btf_type *t, u32 member_kinds, int rec,
13477 				   struct btf_member_path *path)
13478 {
13479 	const struct btf_type *member_type;
13480 	const struct btf_member *member;
13481 	bool in_array;
13482 	u32 i;
13483 
13484 	if (!btf_type_is_struct(t))
13485 		return false;
13486 
13487 	for_each_member(i, t, member) {
13488 		const struct btf_array *array;
13489 
13490 		in_array = false;
13491 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
13492 		/*
13493 		 * Every element of an array is laid out in the value being
13494 		 * returned, so an array counts as its element type however many
13495 		 * dimensions deep that is.
13496 		 */
13497 		while (btf_type_is_array(member_type)) {
13498 			array = btf_array(member_type);
13499 			if (!array->nelems) {
13500 				member_type = NULL;
13501 				goto bad_member;
13502 			}
13503 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
13504 			in_array = true;
13505 		}
13506 		if (btf_type_is_struct(member_type)) {
13507 			if (rec >= BTF_MEMBER_MAX_DEPTH - 1) {
13508 				verbose(env, "max struct nesting depth exceeded\n");
13509 				if (path)
13510 					path->too_deep = true;
13511 				return false;
13512 			}
13513 			if (!btf_struct_member_walk(env, btf, member_type, member_kinds,
13514 						    rec + 1, path))
13515 				goto bad_path;
13516 			continue;
13517 		}
13518 		if (!btf_member_kind_allowed(btf, member_type, member_kinds))
13519 			goto bad_member;
13520 	}
13521 	return true;
13522 
13523 bad_member:
13524 	if (path) {
13525 		path->depth = rec + 1;
13526 		path->bad_type = member_type;
13527 	}
13528 bad_path:
13529 	if (path && path->depth) {
13530 		path->member[rec] = member;
13531 		path->in_array[rec] = in_array;
13532 	}
13533 	return false;
13534 }
13535 
13536 bool btf_struct_is_composed_of(struct bpf_verifier_env *env,
13537 			       const struct btf *btf,
13538 			       const struct btf_type *t, u32 member_kinds)
13539 {
13540 	return btf_struct_member_walk(env, btf, t, member_kinds, 0, NULL);
13541 }
13542 
13543 static bool btf_type_is_scalar_struct(struct bpf_verifier_env *env,
13544 				      const struct btf *btf,
13545 				      const struct btf_type *t)
13546 {
13547 	return btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR);
13548 }
13549 
13550 static int resolve_func_arg_type(struct bpf_verifier_env *env,
13551 				 struct bpf_reg_state *reg, u32 arg, argno_t argno,
13552 				 struct bpf_call_arg_meta *meta,
13553 				 enum bpf_arg_type *arg_type, u32 *arg_size)
13554 {
13555 	const struct btf_param *args;
13556 	const struct btf_type *ref_t, *resolve_ret;
13557 	const struct btf *btf;
13558 	const char *ref_tname;
13559 	u32 ref_id;
13560 
13561 	if (base_type(*arg_type) == ARG_PTR_TO_MAP_VALUE)
13562 		return resolve_map_arg_type(env, meta, arg_type);
13563 
13564 	if (base_type(*arg_type) != ARG_PTR_TO_BTF_ID)
13565 		return 0;
13566 
13567 	if (!is_kfunc(meta) || arg_type_is_release(*arg_type) ||
13568 	    base_type(reg->type) == PTR_TO_BTF_ID ||
13569 	    reg2btf_ids[base_type(reg->type)])
13570 		return 0;
13571 
13572 	args = btf_params(meta->func_proto);
13573 	ref_id = *meta->fn->arg_btf_id[arg];
13574 	btf = is_kfunc_arg_map(meta->btf, &args[arg]) ? btf_vmlinux : meta->btf;
13575 	ref_t = btf_type_skip_modifiers(btf, ref_id, &ref_id);
13576 	ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13577 
13578 	if (!btf_type_is_scalar_struct(env, btf, ref_t))
13579 		return 0;
13580 
13581 	resolve_ret = btf_resolve_size(btf, ref_t, arg_size);
13582 	if (IS_ERR(resolve_ret)) {
13583 		verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
13584 			reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname,
13585 			PTR_ERR(resolve_ret));
13586 		return -EINVAL;
13587 	}
13588 	*arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE |
13589 		    (*arg_type & (PTR_MAYBE_NULL | MEM_UNINIT));
13590 
13591 	return 0;
13592 }
13593 
13594 static void btf_member_path_str(const struct btf *btf, const struct btf_member_path *path,
13595 				char *buf, size_t buf_sz)
13596 {
13597 	size_t len = 0;
13598 	int i;
13599 
13600 	buf[0] = '\0';
13601 	for (i = 0; i < path->depth; i++) {
13602 		const char *name = btf_name_by_offset(btf, path->member[i]->name_off);
13603 
13604 		/* An anonymous struct or union has no name to spell. */
13605 		if (!name || !name[0])
13606 			continue;
13607 		len += scnprintf(buf + len, buf_sz - len, "%s%s", len ? "." : "", name);
13608 		if (path->in_array[i])
13609 			len += scnprintf(buf + len, buf_sz - len, "[]");
13610 	}
13611 }
13612 
13613 enum special_kfunc_type {
13614 	KF_bpf_obj_new_impl,
13615 	KF_bpf_obj_new,
13616 	KF_bpf_obj_drop_impl,
13617 	KF_bpf_obj_drop,
13618 	KF_bpf_refcount_acquire_impl,
13619 	KF_bpf_refcount_acquire,
13620 	KF_bpf_list_push_front_impl,
13621 	KF_bpf_list_push_front,
13622 	KF_bpf_list_push_back_impl,
13623 	KF_bpf_list_push_back,
13624 	KF_bpf_list_add,
13625 	KF_bpf_list_pop_front,
13626 	KF_bpf_list_pop_back,
13627 	KF_bpf_list_del,
13628 	KF_bpf_list_front,
13629 	KF_bpf_list_back,
13630 	KF_bpf_list_is_first,
13631 	KF_bpf_list_is_last,
13632 	KF_bpf_list_empty,
13633 	KF_bpf_cast_to_kern_ctx,
13634 	KF_bpf_rdonly_cast,
13635 	KF_bpf_rcu_read_lock,
13636 	KF_bpf_rcu_read_unlock,
13637 	KF_bpf_rbtree_remove,
13638 	KF_bpf_rbtree_add_impl,
13639 	KF_bpf_rbtree_add,
13640 	KF_bpf_rbtree_first,
13641 	KF_bpf_rbtree_root,
13642 	KF_bpf_rbtree_left,
13643 	KF_bpf_rbtree_right,
13644 	KF_bpf_dynptr_from_skb,
13645 	KF_bpf_dynptr_from_xdp,
13646 	KF_bpf_dynptr_from_skb_meta,
13647 	KF_bpf_xdp_pull_data,
13648 	KF_bpf_dynptr_slice,
13649 	KF_bpf_dynptr_slice_rdwr,
13650 	KF_bpf_dynptr_clone,
13651 	KF_bpf_percpu_obj_new_impl,
13652 	KF_bpf_percpu_obj_new,
13653 	KF_bpf_percpu_obj_drop_impl,
13654 	KF_bpf_percpu_obj_drop,
13655 	KF_bpf_throw,
13656 	KF_bpf_wq_set_callback,
13657 	KF_bpf_preempt_disable,
13658 	KF_bpf_preempt_enable,
13659 	KF_bpf_iter_css_task_new,
13660 	KF_bpf_session_cookie,
13661 	KF_bpf_get_kmem_cache,
13662 	KF_bpf_local_irq_save,
13663 	KF_bpf_local_irq_restore,
13664 	KF_bpf_iter_num_new,
13665 	KF_bpf_iter_num_next,
13666 	KF_bpf_iter_num_destroy,
13667 	KF_bpf_set_dentry_xattr,
13668 	KF_bpf_remove_dentry_xattr,
13669 	KF_bpf_res_spin_lock,
13670 	KF_bpf_res_spin_unlock,
13671 	KF_bpf_res_spin_lock_irqsave,
13672 	KF_bpf_res_spin_unlock_irqrestore,
13673 	KF_bpf_dynptr_from_file,
13674 	KF_bpf_dynptr_file_discard,
13675 	KF___bpf_trap,
13676 	KF_bpf_task_work_schedule_signal,
13677 	KF_bpf_task_work_schedule_resume,
13678 	KF_bpf_call_rcu,
13679 	KF_bpf_call_rcu_tasks_trace,
13680 	KF_bpf_arena_alloc_pages,
13681 	KF_bpf_arena_free_pages,
13682 	KF_bpf_session_is_return,
13683 };
13684 
13685 BTF_ID_LIST(special_kfunc_list)
13686 BTF_ID(func, bpf_obj_new_impl)
13687 BTF_ID(func, bpf_obj_new)
13688 BTF_ID(func, bpf_obj_drop_impl)
13689 BTF_ID(func, bpf_obj_drop)
13690 BTF_ID(func, bpf_refcount_acquire_impl)
13691 BTF_ID(func, bpf_refcount_acquire)
13692 BTF_ID(func, bpf_list_push_front_impl)
13693 BTF_ID(func, bpf_list_push_front)
13694 BTF_ID(func, bpf_list_push_back_impl)
13695 BTF_ID(func, bpf_list_push_back)
13696 BTF_ID(func, bpf_list_add)
13697 BTF_ID(func, bpf_list_pop_front)
13698 BTF_ID(func, bpf_list_pop_back)
13699 BTF_ID(func, bpf_list_del)
13700 BTF_ID(func, bpf_list_front)
13701 BTF_ID(func, bpf_list_back)
13702 BTF_ID(func, bpf_list_is_first)
13703 BTF_ID(func, bpf_list_is_last)
13704 BTF_ID(func, bpf_list_empty)
13705 BTF_ID(func, bpf_cast_to_kern_ctx)
13706 BTF_ID(func, bpf_rdonly_cast)
13707 BTF_ID(func, bpf_rcu_read_lock)
13708 BTF_ID(func, bpf_rcu_read_unlock)
13709 BTF_ID(func, bpf_rbtree_remove)
13710 BTF_ID(func, bpf_rbtree_add_impl)
13711 BTF_ID(func, bpf_rbtree_add)
13712 BTF_ID(func, bpf_rbtree_first)
13713 BTF_ID(func, bpf_rbtree_root)
13714 BTF_ID(func, bpf_rbtree_left)
13715 BTF_ID(func, bpf_rbtree_right)
13716 #ifdef CONFIG_NET
13717 BTF_ID(func, bpf_dynptr_from_skb)
13718 BTF_ID(func, bpf_dynptr_from_xdp)
13719 BTF_ID(func, bpf_dynptr_from_skb_meta)
13720 BTF_ID(func, bpf_xdp_pull_data)
13721 #else
13722 BTF_ID_UNUSED
13723 BTF_ID_UNUSED
13724 BTF_ID_UNUSED
13725 BTF_ID_UNUSED
13726 #endif
13727 BTF_ID(func, bpf_dynptr_slice)
13728 BTF_ID(func, bpf_dynptr_slice_rdwr)
13729 BTF_ID(func, bpf_dynptr_clone)
13730 BTF_ID(func, bpf_percpu_obj_new_impl)
13731 BTF_ID(func, bpf_percpu_obj_new)
13732 BTF_ID(func, bpf_percpu_obj_drop_impl)
13733 BTF_ID(func, bpf_percpu_obj_drop)
13734 BTF_ID(func, bpf_throw)
13735 BTF_ID(func, bpf_wq_set_callback)
13736 BTF_ID(func, bpf_preempt_disable)
13737 BTF_ID(func, bpf_preempt_enable)
13738 #ifdef CONFIG_CGROUPS
13739 BTF_ID(func, bpf_iter_css_task_new)
13740 #else
13741 BTF_ID_UNUSED
13742 #endif
13743 #ifdef CONFIG_BPF_EVENTS
13744 BTF_ID(func, bpf_session_cookie)
13745 #else
13746 BTF_ID_UNUSED
13747 #endif
13748 BTF_ID(func, bpf_get_kmem_cache)
13749 BTF_ID(func, bpf_local_irq_save)
13750 BTF_ID(func, bpf_local_irq_restore)
13751 BTF_ID(func, bpf_iter_num_new)
13752 BTF_ID(func, bpf_iter_num_next)
13753 BTF_ID(func, bpf_iter_num_destroy)
13754 #ifdef CONFIG_BPF_LSM
13755 BTF_ID(func, bpf_set_dentry_xattr)
13756 BTF_ID(func, bpf_remove_dentry_xattr)
13757 #else
13758 BTF_ID_UNUSED
13759 BTF_ID_UNUSED
13760 #endif
13761 BTF_ID(func, bpf_res_spin_lock)
13762 BTF_ID(func, bpf_res_spin_unlock)
13763 BTF_ID(func, bpf_res_spin_lock_irqsave)
13764 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
13765 BTF_ID(func, bpf_dynptr_from_file)
13766 BTF_ID(func, bpf_dynptr_file_discard)
13767 BTF_ID(func, __bpf_trap)
13768 BTF_ID(func, bpf_task_work_schedule_signal)
13769 BTF_ID(func, bpf_task_work_schedule_resume)
13770 BTF_ID(func, bpf_call_rcu)
13771 BTF_ID(func, bpf_call_rcu_tasks_trace)
13772 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
13773 BTF_ID(func, bpf_arena_alloc_pages)
13774 BTF_ID(func, bpf_arena_free_pages)
13775 #else
13776 BTF_ID_UNUSED
13777 BTF_ID_UNUSED
13778 #endif
13779 #ifdef CONFIG_BPF_EVENTS
13780 BTF_ID(func, bpf_session_is_return)
13781 #else
13782 BTF_ID_UNUSED
13783 #endif
13784 
13785 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta)
13786 {
13787 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]);
13788 }
13789 
13790 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta)
13791 {
13792 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_clone]);
13793 }
13794 
13795 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta)
13796 {
13797 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_iter_css_task_new]);
13798 }
13799 
13800 static bool is_bpf_obj_new_kfunc(u32 func_id)
13801 {
13802 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
13803 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
13804 }
13805 
13806 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
13807 {
13808 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
13809 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
13810 }
13811 
13812 static bool is_bpf_obj_drop_kfunc(u32 func_id)
13813 {
13814 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
13815 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
13816 }
13817 
13818 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
13819 {
13820 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
13821 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
13822 }
13823 
13824 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
13825 {
13826 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
13827 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
13828 }
13829 
13830 static bool is_bpf_list_push_kfunc(u32 func_id)
13831 {
13832 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
13833 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13834 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
13835 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13836 	       func_id == special_kfunc_list[KF_bpf_list_add];
13837 }
13838 
13839 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
13840 {
13841 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
13842 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
13843 }
13844 
13845 static bool is_call_rcu_kfunc(u32 func_id)
13846 {
13847 	return func_id == special_kfunc_list[KF_bpf_call_rcu] ||
13848 	       func_id == special_kfunc_list[KF_bpf_call_rcu_tasks_trace];
13849 }
13850 
13851 static bool is_task_work_add_kfunc(u32 func_id)
13852 {
13853 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
13854 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
13855 }
13856 
13857 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta)
13858 {
13859 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
13860 		return false;
13861 
13862 	return meta->kfunc_flags & KF_RET_NULL;
13863 }
13864 
13865 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta)
13866 {
13867 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_lock]);
13868 }
13869 
13870 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta)
13871 {
13872 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_unlock]);
13873 }
13874 
13875 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta)
13876 {
13877 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_disable]);
13878 }
13879 
13880 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta)
13881 {
13882 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_enable]);
13883 }
13884 
13885 /* These write to what their first argument, a dynptr, points to */
13886 BTF_SET_START(dynptr_write_kfuncs)
13887 BTF_ID(func, bpf_dynptr_copy)
13888 BTF_ID(func, bpf_dynptr_memset)
13889 #ifdef CONFIG_BPF_EVENTS
13890 BTF_ID(func, bpf_probe_read_user_dynptr)
13891 BTF_ID(func, bpf_probe_read_kernel_dynptr)
13892 BTF_ID(func, bpf_probe_read_user_str_dynptr)
13893 BTF_ID(func, bpf_probe_read_kernel_str_dynptr)
13894 BTF_ID(func, bpf_copy_from_user_dynptr)
13895 BTF_ID(func, bpf_copy_from_user_str_dynptr)
13896 BTF_ID(func, bpf_copy_from_user_task_dynptr)
13897 BTF_ID(func, bpf_copy_from_user_task_str_dynptr)
13898 #endif
13899 BTF_SET_END(dynptr_write_kfuncs)
13900 
13901 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta)
13902 {
13903 	return meta->btf == btf_vmlinux &&
13904 	       btf_id_set_contains(&dynptr_write_kfuncs, meta->func_id);
13905 }
13906 
13907 /*
13908  * A write through the dynptr of an skb may reallocate its head. Before the
13909  * arguments are checked nobody knows what kind of dynptr it is.
13910  */
13911 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta)
13912 {
13913 	return is_kfunc_call(meta, special_kfunc_list[KF_bpf_xdp_pull_data]) ||
13914 	       is_kfunc_dynptr_write(meta);
13915 }
13916 
13917 static u32 kfunc_abi_slots(const struct btf_func_model *fm)
13918 {
13919 	const struct bpf_jit_arg_abi *abi = bpf_jit_arg_abi();
13920 	u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS];
13921 	u32 i, nslots, slots = 0;
13922 
13923 	for (i = 0; i < fm->nr_args; i++)
13924 		slots += btf_func_model_arg_slots(fm, i);
13925 
13926 	if (!abi)
13927 		return slots;
13928 
13929 	nslots = bpf_jit_place_args(abi, fm, pos_of_slot);
13930 	for (i = 0; i < nslots; i++)
13931 		if (pos_of_slot[i] + 1 > slots)
13932 			slots = pos_of_slot[i] + 1;
13933 
13934 	return slots;
13935 }
13936 
13937 static u32 __btf_func_arg_align(const struct btf *btf, const struct btf_type *t, int rec)
13938 {
13939 	const struct btf_member *member;
13940 	const struct btf_type *mt;
13941 	u32 align, i;
13942 
13943 	while (btf_type_is_array(t))
13944 		t = btf_type_skip_modifiers(btf, btf_array(t)->type, NULL);
13945 
13946 	if (btf_type_is_int(t))
13947 		return t->size > BPF_REG_SIZE ? t->size : BPF_REG_SIZE;
13948 	if (!btf_type_is_struct(t))
13949 		return BPF_REG_SIZE;
13950 	if (rec >= BTF_MEMBER_MAX_DEPTH)
13951 		return 0;
13952 
13953 	for_each_member(i, t, member) {
13954 		mt = btf_type_skip_modifiers(btf, member->type, NULL);
13955 		align = __btf_func_arg_align(btf, mt, rec + 1);
13956 		if (!align)
13957 			return 0;
13958 		if (align > BPF_REG_SIZE)
13959 			return 2 * BPF_REG_SIZE;
13960 	}
13961 	return BPF_REG_SIZE;
13962 }
13963 
13964 u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t)
13965 {
13966 	return __btf_func_arg_align(btf, t, 0);
13967 }
13968 
13969 static int
13970 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
13971 		   const struct btf_param *args, int arg, int nargs, u32 slot,
13972 		   struct bpf_func_proto *proto)
13973 {
13974 	const struct btf_type *t, *ref_t = NULL, *resolve_ret;
13975 	const u32 *ref_id_ptr = NULL;
13976 	argno_t argno = argno_from_arg(slot + 1);
13977 	const char *ref_tname = NULL;
13978 	u32 ref_id, type_size;
13979 	int arg_type;
13980 
13981 	proto->arg_btf_id[arg] = NULL;
13982 
13983 	if (is_kfunc_arg_prog_aux(meta->btf, &args[arg]))
13984 		return ARG_PTR_TO_PROG_AUX;
13985 
13986 	if (is_kfunc_arg_ignore(meta->btf, &args[arg]) || is_kfunc_arg_implicit(meta, arg))
13987 		return ARG_IGNORE;
13988 
13989 	t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
13990 
13991 	/* Scalar arguments are classified from their BTF suffix/name alone. */
13992 	if (btf_type_is_scalar(t)) {
13993 		if (is_kfunc_arg_constant(meta->btf, &args[arg]))
13994 			return ARG_CONST_SCALAR;
13995 		if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg]))
13996 			return ARG_CONST_MEM_SIZE;
13997 		if (is_kfunc_arg_mem_size(meta->btf, &args[arg]))
13998 			return ARG_MEM_SIZE;
13999 		if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") ||
14000 		    is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size"))
14001 			return ARG_CONST_ALLOC_SIZE_OR_ZERO;
14002 		return ARG_SCALAR;
14003 	}
14004 
14005 	if (btf_type_is_struct(t)) {
14006 		if (!t->size || t->size > 2 * BPF_REG_SIZE) {
14007 			verbose(env,
14008 				"%s type %s has size %u, only 1 to %d bytes "
14009 				"can be passed by value\n",
14010 				reg_arg_name(env, argno), btf_type_str(t), t->size,
14011 				2 * BPF_REG_SIZE);
14012 			return -EINVAL;
14013 		}
14014 		if (!btf_type_is_scalar_struct(env, meta->btf, t)) {
14015 			verbose(env, "%s type %s is not composed of scalars\n",
14016 				reg_arg_name(env, argno), btf_type_str(t));
14017 			return -EINVAL;
14018 		}
14019 		return ARG_SCALAR;
14020 	}
14021 
14022 	if (!btf_type_is_ptr(t)) {
14023 		verbose(env, "Unrecognized %s type %s\n",
14024 			reg_arg_name(env, argno), btf_type_str(t));
14025 		return -EINVAL;
14026 	}
14027 	/* Keep a pointer to the BTF field containing the resolved referent ID. */
14028 	ref_id_ptr = &t->type;
14029 	ref_t = btf_type_skip_modifiers(meta->btf, *ref_id_ptr, &ref_id);
14030 	while (*ref_id_ptr != ref_id)
14031 		ref_id_ptr = &btf_type_by_id(meta->btf, *ref_id_ptr)->type;
14032 	ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
14033 
14034 	/* In this function, we verify the kfunc's BTF as per the argument type,
14035 	 * leaving the rest of the verification with respect to the register
14036 	 * type to our caller. When a set of conditions hold in the BTF type of
14037 	 * arguments, we resolve it to a known bpf_arg_type.
14038 	 */
14039 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]) ||
14040 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_is_return]) ||
14041 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_cookie]))
14042 		arg_type = ARG_PTR_TO_CTX;
14043 	else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
14044 		arg_type = ARG_PTR_TO_CTX;
14045 	else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
14046 		arg_type = ARG_PTR_TO_ALLOC_BTF_ID;
14047 	else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
14048 		arg_type = ARG_PTR_TO_REFCOUNTED_KPTR;
14049 	else if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) {
14050 		arg_type = ARG_PTR_TO_DYNPTR;
14051 
14052 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb]))
14053 			arg_type |= DYNPTR_TYPE_SKB;
14054 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_xdp]))
14055 			arg_type |= DYNPTR_TYPE_XDP;
14056 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb_meta]))
14057 			arg_type |= DYNPTR_TYPE_SKB_META;
14058 		else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_file]) ||
14059 			 is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_file_discard]))
14060 			/* OBJ_RELEASE for the latter comes from KF_RELEASE below */
14061 			arg_type |= DYNPTR_TYPE_FILE;
14062 	} else if (is_kfunc_arg_iter(meta, arg, &args[arg]))
14063 		arg_type = ARG_PTR_TO_ITER;
14064 	else if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
14065 		arg_type = ARG_PTR_TO_LIST_HEAD;
14066 	else if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
14067 		arg_type = ARG_PTR_TO_LIST_NODE;
14068 	else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
14069 		arg_type = ARG_PTR_TO_RB_ROOT;
14070 	else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
14071 		arg_type = ARG_PTR_TO_RB_NODE;
14072 	else if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
14073 		arg_type = ARG_PTR_TO_CONST_STR;
14074 	else if (is_kfunc_arg_const_map(meta->btf, &args[arg]))
14075 		arg_type = ARG_CONST_MAP_PTR;
14076 	else if (is_kfunc_arg_map(meta->btf, &args[arg]))
14077 		arg_type = ARG_PTR_TO_BTF_ID;
14078 	else if (is_kfunc_arg_wq(meta->btf, &args[arg]))
14079 		arg_type = ARG_PTR_TO_WORKQUEUE;
14080 	else if (is_kfunc_arg_timer(meta->btf, &args[arg]))
14081 		arg_type = ARG_PTR_TO_TIMER;
14082 	else if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
14083 		arg_type = ARG_PTR_TO_TASK_WORK;
14084 	else if (is_kfunc_arg_rcu_head(meta->btf, &args[arg]))
14085 		arg_type = ARG_PTR_TO_RCU_HEAD;
14086 	else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
14087 		arg_type = ARG_PTR_TO_IRQ_FLAG;
14088 	else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
14089 		arg_type = ARG_PTR_TO_RES_SPIN_LOCK;
14090 	else if (is_kfunc_arg_ctx_out(meta->btf, &args[arg])) {
14091 		if (!btf_type_is_scalar(ref_t)) {
14092 			verbose(env, "%s __ctx_out argument must point to a scalar\n",
14093 				reg_arg_name(env, argno));
14094 			return -EINVAL;
14095 		}
14096 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
14097 		if (IS_ERR(resolve_ret)) {
14098 			verbose(env,
14099 				"%s reference type('%s %s') size cannot be determined: %ld\n",
14100 				reg_arg_name(env, argno), btf_type_str(ref_t),
14101 				ref_tname, PTR_ERR(resolve_ret));
14102 			return -EINVAL;
14103 		}
14104 		proto->arg_size[arg] = type_size;
14105 		arg_type = ARG_PTR_TO_CTX_OUT | MEM_FIXED_SIZE;
14106 	} else if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
14107 		arg_type = ARG_PTR_TO_FUNC;
14108 	else if (is_kfunc_arg_arena(meta->btf, &args[arg])) {
14109 		if (!bpf_jit_supports_arena_args()) {
14110 			verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n",
14111 				meta->func_name);
14112 			return -ENOTSUPP;
14113 		}
14114 		if (!env->prog->aux->arena) {
14115 			verbose(env,
14116 				"%s arena pointer requires a program with an associated arena\n",
14117 				reg_arg_name(env, argno));
14118 			return -EINVAL;
14119 		}
14120 		if (reg_from_argno(argno) < 0) {
14121 			verbose(env, "%s arena pointer cannot be a stack argument\n",
14122 				reg_arg_name(env, argno));
14123 			return -EINVAL;
14124 		}
14125 		/*
14126 		 * Both suffixes accept a constant zero. The function model determines
14127 		 * whether the JIT rebases it to the arena base or preserves NULL.
14128 		 * The common nullable path below records that verifier property.
14129 		 */
14130 		arg_type = ARG_PTR_TO_ARENA;
14131 	} else if (arg + 1 < nargs &&
14132 		 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) ||
14133 		  is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) {
14134 		if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) &&
14135 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
14136 			verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n",
14137 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
14138 			return -EINVAL;
14139 		}
14140 		arg_type = ARG_PTR_TO_MEM | MEM_WRITE;
14141 	} else if (btf_type_is_struct(ref_t))
14142 		/* A pointer to a struct without a size argument is classified as ARG_PTR_TO_BTF_ID */
14143 		arg_type = ARG_PTR_TO_BTF_ID;
14144 	else {
14145 		/*
14146 		 * Otherwise this is a fixed-size memory buffer supported by
14147 		 * check_helper_mem_access(): a pointer to a scalar or a struct of
14148 		 * scalars. The access size is derived from the pointed-to BTF type.
14149 		 */
14150 		if (!btf_type_is_scalar(ref_t) &&
14151 		    !btf_type_is_scalar_struct(env, meta->btf, ref_t)) {
14152 			verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n",
14153 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
14154 			return -EINVAL;
14155 		}
14156 		resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size);
14157 		if (IS_ERR(resolve_ret)) {
14158 			verbose(env,
14159 				"%s reference type('%s %s') size cannot be determined: %ld\n",
14160 				reg_arg_name(env, argno), btf_type_str(ref_t),
14161 				ref_tname, PTR_ERR(resolve_ret));
14162 			return -EINVAL;
14163 		}
14164 		proto->arg_size[arg] = type_size;
14165 		arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE;
14166 	}
14167 
14168 	if (is_kfunc_arg_uninit(meta->btf, &args[arg]))
14169 		arg_type |= MEM_UNINIT;
14170 
14171 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]))
14172 		arg_type |= PTR_MAYBE_NULL;
14173 
14174 	/*
14175 	 * Only the first argument of a KF_RELEASE kfunc releases anything, and
14176 	 * bpf_fetch_kfunc_arg_meta() only ever records BPF_REG_1 for it.
14177 	 */
14178 	if (is_kfunc_release(meta) && arg == 0)
14179 		arg_type |= OBJ_RELEASE;
14180 
14181 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) {
14182 		if (is_kfunc_arg_map(meta->btf, &args[arg]))
14183 			proto->arg_btf_id[arg] = reg2btf_ids[CONST_PTR_TO_MAP];
14184 		else
14185 			proto->arg_btf_id[arg] = ref_id_ptr;
14186 
14187 		arg_type |= PTR_TRUSTED;
14188 
14189 		/*
14190 		 * A KF_RCU kfunc accepts an RCU-protected pointer where it would
14191 		 * otherwise demand a referenced or trusted one. Other argument kinds
14192 		 * have their own provenance requirements and must not inherit MEM_RCU.
14193 		 */
14194 		if (is_kfunc_rcu(meta))
14195 			arg_type |= MEM_RCU;
14196 	}
14197 
14198 	return arg_type;
14199 }
14200 
14201 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
14202 			       const struct btf_func_model *fm, struct bpf_func_proto *proto)
14203 {
14204 	const struct bpf_jit_arg_abi *abi;
14205 	const struct btf *btf = meta->btf;
14206 	const struct btf_param *args;
14207 	const struct btf_type *t;
14208 	u32 i, nargs, slots_used;
14209 	int arg_type;
14210 
14211 	args = (const struct btf_param *)(meta->func_proto + 1);
14212 	nargs = btf_type_vlen(meta->func_proto);
14213 	if (nargs > MAX_BPF_FUNC_ARGS) {
14214 		verbose(env, "Function %s has %d > %d args\n", meta->func_name,
14215 			nargs, MAX_BPF_FUNC_ARGS);
14216 		return -EINVAL;
14217 	}
14218 
14219 	for (i = 0, slots_used = 0; i < nargs; i++) {
14220 		u32 nslots = btf_func_model_arg_slots(fm, i);
14221 
14222 		if (nslots > 1) {
14223 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
14224 			if (!btf_func_arg_align(btf, t)) {
14225 				verbose(env,
14226 					"Function %s arg#%d type %s nests structs more than "
14227 					"%d levels deep\n",
14228 					meta->func_name, i, btf_type_str(t),
14229 					BTF_MEMBER_MAX_DEPTH);
14230 				return -EINVAL;
14231 			}
14232 		}
14233 		slots_used += nslots;
14234 	}
14235 
14236 	if (slots_used > MAX_BPF_FUNC_ARGS) {
14237 		verbose(env, "Function %s needs %d > %d argument slots\n", meta->func_name,
14238 			slots_used, MAX_BPF_FUNC_ARGS);
14239 		return -EINVAL;
14240 	}
14241 
14242 	abi = bpf_jit_arg_abi();
14243 
14244 	for (i = 0, slots_used = 0; i < nargs; i++) {
14245 		u32 nslots = btf_func_model_arg_slots(fm, i);
14246 
14247 		if (!abi && nslots > 1) {
14248 			t = btf_type_skip_modifiers(btf, args[i].type, NULL);
14249 			verbose(env,
14250 				"Function %s arg#%d type %s cannot be passed at "
14251 				"argument slot %d on this architecture\n",
14252 				meta->func_name, i, btf_type_str(t), slots_used);
14253 			return -EINVAL;
14254 		}
14255 		slots_used += nslots;
14256 
14257 		arg_type = get_kfunc_arg_type(env, meta, args, i, nargs,
14258 					      slots_used - nslots, proto);
14259 		if (arg_type < 0)
14260 			return arg_type;
14261 
14262 		proto->arg_type[i] = arg_type;
14263 	}
14264 
14265 	if (slots_used > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
14266 		verbose(env, "JIT does not support kfunc %s() with %d argument slots\n",
14267 			meta->func_name, slots_used);
14268 		return -ENOTSUPP;
14269 	}
14270 
14271 	return check_arg_prog_aux(env, proto) ? 0 : -EINVAL;
14272 }
14273 
14274 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
14275 				     argno_t argno, enum bpf_arg_type arg_type,
14276 				     const struct btf *arg_btf, u32 arg_btf_id,
14277 				     struct bpf_call_arg_meta *meta, int insn_idx)
14278 {
14279 	bool taking_projection, struct_same, strict_type_match = false;
14280 	const struct btf_type *arg_t, *reg_t;
14281 	const char *arg_tname, *reg_tname;
14282 	const struct btf *reg_btf;
14283 	u32 reg_btf_id;
14284 
14285 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
14286 		reg_btf = reg->btf;
14287 		reg_btf_id = reg->btf_id;
14288 	} else {
14289 		reg_btf = btf_vmlinux;
14290 		reg_btf_id = *reg2btf_ids[base_type(reg->type)];
14291 	}
14292 
14293 	/*
14294 	 * Enforce strict type matching for arguments that release a reference,
14295 	 * or are no-cast aliases. We do _not_ enforce strict matching by default,
14296 	 * as we want to enable BPF programs to pass types that are bitwise
14297 	 * equivalent without forcing them to explicitly cast with something
14298 	 * like bpf_cast_to_kern_ctx().
14299 	 *
14300 	 * For example, say we had a type like the following:
14301 	 *
14302 	 * struct bpf_cpumask {
14303 	 *	cpumask_t cpumask;
14304 	 *	refcount_t usage;
14305 	 * };
14306 	 *
14307 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
14308 	 * to a struct cpumask, so it would be safe to pass a struct
14309 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
14310 	 *
14311 	 * The philosophy here is similar to how we allow scalars of different
14312 	 * types to be passed to kfuncs as long as the size is the same. The
14313 	 * only difference here is that we're simply allowing
14314 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
14315 	 * resolve types.
14316 	 */
14317 	if ((arg_type_is_release(arg_type) && !is_helper_call(meta, BPF_FUNC_sk_release)) ||
14318 	    (is_kfunc(meta) && btf_type_ids_nocast_alias(&env->log, reg_btf, reg_btf_id,
14319 						    arg_btf, arg_btf_id)))
14320 		strict_type_match = true;
14321 
14322 	arg_t = btf_type_skip_modifiers(arg_btf, arg_btf_id, &arg_btf_id);
14323 	arg_tname = btf_name_by_offset(arg_btf, arg_t->name_off);
14324 	reg_t = btf_type_skip_modifiers(reg_btf, reg_btf_id, &reg_btf_id);
14325 	reg_tname = btf_name_by_offset(reg_btf, reg_t->name_off);
14326 
14327 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_btf_id,
14328 					  reg->var_off.value, arg_btf, arg_btf_id,
14329 					  strict_type_match, !type_is_alloc(reg->type));
14330 
14331 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
14332 	 * actually use it -- it must cast to the underlying type. So we allow
14333 	 * caller to pass in the underlying type.
14334 	 */
14335 	taking_projection = is_kfunc(meta) && btf_is_projection_of(arg_tname, reg_tname);
14336 	if (!taking_projection && !struct_same) {
14337 		verbose(env, "%s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
14338 			meta->func_name, reg_arg_name(env, argno),
14339 			btf_type_str(arg_t), arg_tname,
14340 			reg_arg_name(env, argno), btf_type_str(reg_t), reg_tname);
14341 		return -EINVAL;
14342 	}
14343 	return 0;
14344 }
14345 
14346 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
14347 			     struct bpf_call_arg_meta *meta)
14348 {
14349 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
14350 	bool irq_save;
14351 
14352 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_save]) ||
14353 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
14354 		irq_save = true;
14355 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14356 			kfunc_class = IRQ_LOCK_KFUNC;
14357 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_restore]) ||
14358 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) {
14359 		irq_save = false;
14360 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14361 			kfunc_class = IRQ_LOCK_KFUNC;
14362 	} else {
14363 		verifier_bug(env, "unknown irq flags kfunc");
14364 		return -EFAULT;
14365 	}
14366 
14367 	if (irq_save) {
14368 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
14369 			verbose(env, "expected uninitialized irq flag as %s\n",
14370 				reg_arg_name(env, argno));
14371 			bpf_diag_res(env, env->insn_idx, "IRQ flag is already initialized",
14372 				     "Saving IRQ state requires an uninitialized stack slot for "
14373 				     "the IRQ flag, but this slot already contains tracked IRQ "
14374 				     "flag state.",
14375 				     "Use a fresh stack slot for this save operation, or restore "
14376 				     "the existing IRQ flag before reusing the slot.");
14377 			return -EINVAL;
14378 		}
14379 
14380 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
14381 				       BPF_WRITE, -1, false, false);
14382 		if (err)
14383 			return err;
14384 
14385 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
14386 		if (err)
14387 			return err;
14388 	} else {
14389 		err = is_irq_flag_reg_valid_init(env, reg);
14390 		if (err) {
14391 			verbose(env, "expected an initialized irq flag as %s\n",
14392 				reg_arg_name(env, argno));
14393 			bpf_diag_res(env, env->insn_idx, "uninitialized IRQ flag restore",
14394 				     "Restoring IRQ state requires a stack slot that was "
14395 				     "initialized by a matching IRQ save operation on this path.",
14396 				     "Pass the same stack slot that was previously initialized by "
14397 				     "the matching IRQ save kfunc.");
14398 			return err;
14399 		}
14400 
14401 		spi = irq_flag_get_spi(env, reg);
14402 		if (spi < 0)
14403 			return spi;
14404 
14405 		mark_stack_slots_scratched(env, spi, 1);
14406 
14407 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
14408 		if (err)
14409 			return err;
14410 
14411 		if (!in_rcu_cs(env))
14412 			invalidate_rcu_protected_refs(env);
14413 	}
14414 	return 0;
14415 }
14416 
14417 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14418 {
14419 	struct btf_record *rec = reg_btf_record(reg);
14420 
14421 	if (!env->cur_state->active_locks) {
14422 		verifier_bug(env, "%s w/o active lock", __func__);
14423 		return -EFAULT;
14424 	}
14425 
14426 	if (type_flag(reg->type) & NON_OWN_REF) {
14427 		verifier_bug(env, "NON_OWN_REF already set");
14428 		return -EFAULT;
14429 	}
14430 
14431 	reg->type |= NON_OWN_REF;
14432 	if (rec->refcount_off >= 0)
14433 		reg->type |= MEM_RCU;
14434 
14435 	return 0;
14436 }
14437 
14438 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
14439 {
14440 	struct bpf_func_state *unused;
14441 	struct bpf_reg_state *reg;
14442 	int err;
14443 
14444 	err = release_reference_nomark(env, id);
14445 	WARN_ON_ONCE(err);
14446 
14447 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
14448 		if (reg->id == id) {
14449 			reg->id = 0;
14450 			ref_set_non_owning(env, reg);
14451 		}
14452 	}));
14453 
14454 	return;
14455 }
14456 
14457 /* Implementation details:
14458  *
14459  * Each register points to some region of memory, which we define as an
14460  * allocation. Each allocation may embed a bpf_spin_lock which protects any
14461  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
14462  * allocation. The lock and the data it protects are colocated in the same
14463  * memory region.
14464  *
14465  * Hence, everytime a register holds a pointer value pointing to such
14466  * allocation, the verifier preserves a unique reg->id for it.
14467  *
14468  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
14469  * bpf_spin_lock is called.
14470  *
14471  * To enable this, lock state in the verifier captures two values:
14472  *	active_lock.ptr = Register's type specific pointer
14473  *	active_lock.id  = A unique ID for each register pointer value
14474  *
14475  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
14476  * supported register types.
14477  *
14478  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
14479  * allocated objects is the reg->btf pointer.
14480  *
14481  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
14482  * can establish the provenance of the map value statically for each distinct
14483  * lookup into such maps. They always contain a single map value hence unique
14484  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
14485  *
14486  * So, in case of global variables, they use array maps with max_entries = 1,
14487  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
14488  * into the same map value as max_entries is 1, as described above).
14489  *
14490  * In case of inner map lookups, the inner map pointer has same map_ptr as the
14491  * outer map pointer (in verifier context), but each lookup into an inner map
14492  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
14493  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
14494  * will get different reg->id assigned to each lookup, hence different
14495  * active_lock.id.
14496  *
14497  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
14498  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
14499  * returned from bpf_obj_new. Each allocation receives a new reg->id.
14500  */
14501 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
14502 {
14503 	struct bpf_reference_state *s;
14504 	void *ptr;
14505 	u32 id;
14506 
14507 	switch ((int)reg->type) {
14508 	case PTR_TO_MAP_VALUE:
14509 		ptr = reg->map_ptr;
14510 		break;
14511 	case PTR_TO_BTF_ID | MEM_ALLOC:
14512 		ptr = reg->btf;
14513 		break;
14514 	default:
14515 		verifier_bug(env, "unknown reg type for lock check");
14516 		return -EFAULT;
14517 	}
14518 	id = reg->id;
14519 
14520 	if (!env->cur_state->active_locks)
14521 		return -EINVAL;
14522 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
14523 	if (!s) {
14524 		verbose(env, "held lock and object are not in the same allocation\n");
14525 		return -EINVAL;
14526 	}
14527 	return 0;
14528 }
14529 
14530 static bool is_bpf_list_api_kfunc(u32 btf_id)
14531 {
14532 	return is_bpf_list_push_kfunc(btf_id) ||
14533 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
14534 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
14535 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
14536 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
14537 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
14538 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14539 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
14540 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
14541 }
14542 
14543 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
14544 {
14545 	return is_bpf_rbtree_add_kfunc(btf_id) ||
14546 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14547 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
14548 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
14549 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14550 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
14551 }
14552 
14553 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta)
14554 {
14555 	int flags = PROCESS_RES_LOCK;
14556 
14557 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock]) ||
14558 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14559 		flags |= PROCESS_SPIN_LOCK;
14560 	else if (!is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock]) &&
14561 		 !is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14562 		return 0;
14563 	if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) ||
14564 	    is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]))
14565 		flags |= PROCESS_LOCK_IRQ;
14566 	return flags;
14567 }
14568 
14569 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset)
14570 {
14571 	struct bpf_kfunc_meta kfunc;
14572 	int err;
14573 
14574 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
14575 	if (err || !kfunc.flags)
14576 		return false;
14577 
14578 	return *kfunc.flags & KF_SPINLOCK_SAFE;
14579 }
14580 
14581 /*
14582  * True if insn calls a helper/kfunc that requires one of its arguments to
14583  * be a stack pointer with a constant offset.
14584  */
14585 bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
14586 {
14587 	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
14588 	const struct bpf_func_proto *fn;
14589 	struct bpf_kfunc_desc *desc;
14590 	u32 *flags, btf_id;
14591 	int i;
14592 
14593 	if (bpf_helper_call(insn)) {
14594 		if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
14595 			return false;
14596 	} else if (bpf_pseudo_kfunc_call(insn)) {
14597 		desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14598 		if (!desc)
14599 			return false;
14600 		fn = &desc->proto;
14601 	} else {
14602 		return false;
14603 	}
14604 
14605 	/* Both initialized and uninitialized stack dynptrs need a fixed offset. */
14606 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++)
14607 		if (arg_type_is_dynptr(fn->arg_type[i]))
14608 			return true;
14609 
14610 	/* vmlinux kfuncs only */
14611 	if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
14612 		return false;
14613 	btf_id = insn->imm;
14614 
14615 	flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
14616 	if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
14617 		return true;
14618 
14619 	if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14620 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
14621 	    btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
14622 	    btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
14623 	    btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
14624 	    btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
14625 		return true;
14626 
14627 	return false;
14628 }
14629 
14630 static bool is_sync_callback_calling_kfunc(u32 btf_id)
14631 {
14632 	return is_bpf_rbtree_add_kfunc(btf_id);
14633 }
14634 
14635 static bool is_async_callback_calling_kfunc(u32 btf_id)
14636 {
14637 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
14638 	       is_task_work_add_kfunc(btf_id) ||
14639 	       is_call_rcu_kfunc(btf_id);
14640 }
14641 
14642 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
14643 {
14644 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
14645 	       insn->imm == special_kfunc_list[KF_bpf_throw];
14646 }
14647 
14648 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
14649 {
14650 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
14651 }
14652 
14653 static bool is_callback_calling_kfunc(u32 btf_id)
14654 {
14655 	return is_sync_callback_calling_kfunc(btf_id) ||
14656 	       is_async_callback_calling_kfunc(btf_id);
14657 }
14658 
14659 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
14660 {
14661 	return is_bpf_rbtree_api_kfunc(btf_id);
14662 }
14663 
14664 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
14665 					  enum btf_field_type head_field_type,
14666 					  u32 kfunc_btf_id)
14667 {
14668 	bool ret;
14669 
14670 	switch (head_field_type) {
14671 	case BPF_LIST_HEAD:
14672 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
14673 		break;
14674 	case BPF_RB_ROOT:
14675 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
14676 		break;
14677 	default:
14678 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
14679 			btf_field_type_name(head_field_type));
14680 		return false;
14681 	}
14682 
14683 	if (!ret)
14684 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
14685 			btf_field_type_name(head_field_type));
14686 	return ret;
14687 }
14688 
14689 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
14690 					  enum btf_field_type node_field_type,
14691 					  u32 kfunc_btf_id)
14692 {
14693 	bool ret;
14694 
14695 	switch (node_field_type) {
14696 	case BPF_LIST_NODE:
14697 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
14698 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
14699 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
14700 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
14701 		break;
14702 	case BPF_RB_NODE:
14703 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
14704 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
14705 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
14706 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
14707 		break;
14708 	default:
14709 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
14710 			btf_field_type_name(node_field_type));
14711 		return false;
14712 	}
14713 
14714 	if (!ret)
14715 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
14716 			btf_field_type_name(node_field_type));
14717 	return ret;
14718 }
14719 
14720 static int
14721 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
14722 				   struct bpf_reg_state *reg, argno_t argno,
14723 				   struct bpf_call_arg_meta *meta,
14724 				   enum btf_field_type head_field_type,
14725 				   struct btf_field **head_field)
14726 {
14727 	const char *head_type_name;
14728 	struct btf_field *field;
14729 	struct btf_record *rec;
14730 	u32 head_off;
14731 
14732 	if (meta->btf != btf_vmlinux) {
14733 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14734 		return -EFAULT;
14735 	}
14736 
14737 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
14738 		return -EFAULT;
14739 
14740 	head_type_name = btf_field_type_name(head_field_type);
14741 	if (!tnum_is_const(reg->var_off)) {
14742 		verbose(env,
14743 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14744 			reg_arg_name(env, argno), head_type_name);
14745 		return -EINVAL;
14746 	}
14747 
14748 	rec = reg_btf_record(reg);
14749 	head_off = reg->var_off.value;
14750 	field = btf_record_find(rec, head_off, head_field_type);
14751 	if (!field) {
14752 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
14753 		return -EINVAL;
14754 	}
14755 
14756 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
14757 	if (check_reg_allocation_locked(env, reg)) {
14758 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
14759 			rec->spin_lock_off, head_type_name);
14760 		return -EINVAL;
14761 	}
14762 
14763 	if (*head_field) {
14764 		verifier_bug(env, "repeating %s arg", head_type_name);
14765 		return -EFAULT;
14766 	}
14767 	*head_field = field;
14768 	return 0;
14769 }
14770 
14771 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
14772 					   struct bpf_reg_state *reg, argno_t argno,
14773 					   struct bpf_call_arg_meta *meta)
14774 {
14775 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
14776 							  &meta->arg_list_head.field);
14777 }
14778 
14779 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
14780 					     struct bpf_reg_state *reg, argno_t argno,
14781 					     struct bpf_call_arg_meta *meta)
14782 {
14783 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
14784 							  &meta->arg_rbtree_root.field);
14785 }
14786 
14787 static int
14788 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
14789 				   struct bpf_reg_state *reg, argno_t argno,
14790 				   struct bpf_call_arg_meta *meta,
14791 				   enum btf_field_type head_field_type,
14792 				   enum btf_field_type node_field_type,
14793 				   struct btf_field **node_field)
14794 {
14795 	const char *node_type_name;
14796 	const struct btf_type *et, *t;
14797 	struct btf_field *field;
14798 	u32 node_off;
14799 
14800 	if (meta->btf != btf_vmlinux) {
14801 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
14802 		return -EFAULT;
14803 	}
14804 
14805 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
14806 		return -EFAULT;
14807 
14808 	node_type_name = btf_field_type_name(node_field_type);
14809 	if (!tnum_is_const(reg->var_off)) {
14810 		verbose(env,
14811 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
14812 			reg_arg_name(env, argno), node_type_name);
14813 		return -EINVAL;
14814 	}
14815 
14816 	node_off = reg->var_off.value;
14817 	field = reg_find_field_offset(reg, node_off, node_field_type);
14818 	if (!field) {
14819 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
14820 		return -EINVAL;
14821 	}
14822 
14823 	field = *node_field;
14824 
14825 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
14826 	t = btf_type_by_id(reg->btf, reg->btf_id);
14827 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
14828 				  field->graph_root.value_btf_id, true,
14829 				  !type_is_alloc(reg->type))) {
14830 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
14831 			"in struct %s, but arg is at offset=%d in struct %s\n",
14832 			btf_field_type_name(head_field_type),
14833 			btf_field_type_name(node_field_type),
14834 			field->graph_root.node_offset,
14835 			btf_name_by_offset(field->graph_root.btf, et->name_off),
14836 			node_off, btf_name_by_offset(reg->btf, t->name_off));
14837 		return -EINVAL;
14838 	}
14839 	meta->arg_btf = reg->btf;
14840 	meta->arg_btf_id = reg->btf_id;
14841 
14842 	if (node_off != field->graph_root.node_offset) {
14843 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
14844 			node_off, btf_field_type_name(node_field_type),
14845 			field->graph_root.node_offset,
14846 			btf_name_by_offset(field->graph_root.btf, et->name_off));
14847 		return -EINVAL;
14848 	}
14849 
14850 	return 0;
14851 }
14852 
14853 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
14854 					   struct bpf_reg_state *reg, argno_t argno,
14855 					   struct bpf_call_arg_meta *meta)
14856 {
14857 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14858 						  BPF_LIST_HEAD, BPF_LIST_NODE,
14859 						  &meta->arg_list_head.field);
14860 }
14861 
14862 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
14863 					     struct bpf_reg_state *reg, argno_t argno,
14864 					     struct bpf_call_arg_meta *meta)
14865 {
14866 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
14867 						  BPF_RB_ROOT, BPF_RB_NODE,
14868 						  &meta->arg_rbtree_root.field);
14869 }
14870 
14871 /*
14872  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
14873  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
14874  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
14875  * them can only be attached to some specific hook points.
14876  */
14877 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
14878 {
14879 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14880 
14881 	switch (prog_type) {
14882 	case BPF_PROG_TYPE_LSM:
14883 		return true;
14884 	case BPF_PROG_TYPE_TRACING:
14885 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
14886 			return true;
14887 		fallthrough;
14888 	default:
14889 		return in_sleepable(env);
14890 	}
14891 }
14892 
14893 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
14894 			     s32 func_id,
14895 			     s16 offset,
14896 			     struct bpf_call_arg_meta *meta)
14897 {
14898 	struct bpf_kfunc_meta kfunc;
14899 	int err;
14900 
14901 	memset(meta, 0, sizeof(*meta));
14902 
14903 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
14904 	if (err)
14905 		return err;
14906 
14907 	meta->btf = kfunc.btf;
14908 	meta->func_id = kfunc.id;
14909 	meta->func_proto = kfunc.proto;
14910 	meta->func_name = kfunc.name;
14911 
14912 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
14913 		return -EACCES;
14914 
14915 	meta->kfunc_flags = *kfunc.flags;
14916 
14917 	/* Only support release referenced argument passed by register */
14918 	if (is_kfunc_release(meta))
14919 		meta->release_regno = BPF_REG_1;
14920 
14921 	return 0;
14922 }
14923 
14924 /*
14925  * Describe a helper's stack access through argument @arg (0-based, R1-R5).
14926  * must_write means the verifier destroys prior state throughout size bytes.
14927  * In other words, must_write follows the verifier's model of the
14928  * function's behaviour, which is safe to use for is_state_visited() pruning.
14929  */
14930 struct arg_access_info
14931 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
14932 			      int arg, int insn_idx)
14933 {
14934 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
14935 	struct arg_access_info info = {
14936 		.size = U32_MAX,
14937 		.may_read = true,
14938 		.may_write = true,
14939 	};
14940 	const struct bpf_func_proto *fn;
14941 	enum bpf_access_type access_type;
14942 	enum bpf_arg_type at;
14943 	bool exact_size = true;
14944 	u64 size = U32_MAX;
14945 
14946 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
14947 		return info;
14948 
14949 	at = fn->arg_type[arg];
14950 	access_type = func_arg_access_type(at);
14951 
14952 	switch (base_type(at)) {
14953 	case ARG_PTR_TO_MAP_KEY:
14954 	case ARG_PTR_TO_MAP_VALUE: {
14955 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
14956 		u64 val;
14957 		int i, map_reg;
14958 
14959 		for (i = 0; i < arg; i++) {
14960 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
14961 				break;
14962 		}
14963 		if (i >= arg)
14964 			goto scan_all_maps;
14965 
14966 		map_reg = BPF_REG_1 + i;
14967 
14968 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
14969 			goto scan_all_maps;
14970 
14971 		i = aux->const_reg_vals[map_reg];
14972 		if (i < env->used_map_cnt) {
14973 			/* Bloom-filter peek reads the value buffer. */
14974 			if (!is_key && insn->imm == BPF_FUNC_map_peek_elem &&
14975 			    env->used_maps[i]->map_type == BPF_MAP_TYPE_BLOOM_FILTER)
14976 				access_type = BPF_READ;
14977 			size = is_key ? env->used_maps[i]->key_size
14978 				      : env->used_maps[i]->value_size;
14979 			goto out;
14980 		}
14981 scan_all_maps:
14982 		/*
14983 		 * Map pointer is not known at this call site (e.g. different
14984 		 * maps on merged paths).  Conservatively return the largest
14985 		 * key_size or value_size across all maps used by the program.
14986 		 * This is only an upper bound, so it cannot establish a definite
14987 		 * write. Map-dependent argument types can also turn an output
14988 		 * into an input, so conservatively retain a read dependency.
14989 		 */
14990 		exact_size = false;
14991 		access_type |= BPF_READ;
14992 		val = 0;
14993 		for (i = 0; i < env->used_map_cnt; i++) {
14994 			struct bpf_map *map = env->used_maps[i];
14995 			u32 sz = is_key ? map->key_size : map->value_size;
14996 
14997 			if (sz > val)
14998 				val = sz;
14999 			if (map->inner_map_meta) {
15000 				sz = is_key ? map->inner_map_meta->key_size
15001 					    : map->inner_map_meta->value_size;
15002 				if (sz > val)
15003 					val = sz;
15004 			}
15005 		}
15006 		if (!val)
15007 			return info;
15008 		size = val;
15009 		goto out;
15010 	}
15011 	case ARG_PTR_TO_MEM:
15012 		if (at & MEM_FIXED_SIZE) {
15013 			size = fn->arg_size[arg];
15014 			goto out;
15015 		}
15016 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
15017 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
15018 			int size_reg = BPF_REG_1 + arg + 1;
15019 
15020 			if (aux->const_reg_mask & BIT(size_reg)) {
15021 				size = aux->const_reg_vals[size_reg];
15022 				goto out;
15023 			}
15024 		}
15025 		/* Preserve access directions even when the extent is unknown. */
15026 		goto out;
15027 	case ARG_PTR_TO_DYNPTR:
15028 		size = BPF_DYNPTR_SIZE;
15029 		break;
15030 	case ARG_PTR_TO_STACK:
15031 		/*
15032 		 * Only used by bpf_calls_callback() helpers. The helper itself
15033 		 * doesn't access stack. The callback subprog does and it's
15034 		 * analyzed separately.
15035 		 */
15036 		return (struct arg_access_info) {};
15037 	default:
15038 		return info;
15039 	}
15040 out:
15041 	info.size = min_t(u64, size, U32_MAX);
15042 	info.may_read = !!(access_type & BPF_READ);
15043 	info.may_write = !!(access_type & BPF_WRITE);
15044 	info.must_write = info.may_write && exact_size && info.size != U32_MAX;
15045 	/* Generic unprivileged outputs retain prior initialization state. */
15046 	if (!env->allow_uninit_stack && arg_type_is_raw_mem(at)) {
15047 		info.may_read = true;
15048 		info.must_write = false;
15049 	}
15050 	return info;
15051 }
15052 
15053 /*
15054  * Describe a kfunc's stack access through argument slot @arg (0-based).
15055  * As for helpers, must_write describes destruction of prior verifier state,
15056  * rather than a guarantee that the callee writes every byte at runtime.
15057  */
15058 struct arg_access_info
15059 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
15060 			     int arg, int insn_idx)
15061 {
15062 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
15063 	struct arg_access_info info = {
15064 		.size = U32_MAX,
15065 		.may_read = true,
15066 		.may_write = true,
15067 	};
15068 	struct bpf_call_arg_meta meta;
15069 	const struct btf_param *args;
15070 	const struct btf_type *t, *ref_t;
15071 	const struct btf *btf;
15072 	u32 i, slot, nargs, type_size;
15073 	u64 size;
15074 
15075 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
15076 		return info;
15077 
15078 	btf = meta.btf;
15079 	args = btf_params(meta.func_proto);
15080 	nargs = btf_type_vlen(meta.func_proto);
15081 
15082 	/*
15083 	 * @arg is an argument slot and a 16-byte parameter takes two of them,
15084 	 * so walk the parameters to find the one that starts at this slot. A
15085 	 * slot holding the upper eightbyte of such a parameter belongs to no
15086 	 * pointer, and neither does a slot past the last parameter.
15087 	 */
15088 	for (i = 0, slot = 0; i < nargs && slot < arg; i++)
15089 		slot += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL));
15090 	if (i >= nargs || slot != arg)
15091 		return (struct arg_access_info) {};
15092 
15093 	t = btf_type_skip_modifiers(btf, args[i].type, NULL);
15094 	if (!btf_type_is_ptr(t))
15095 		return (struct arg_access_info) {};
15096 
15097 	/* dynptr: fixed 16-byte on-stack representation */
15098 	if (is_kfunc_arg_dynptr(btf, &args[i])) {
15099 		size = BPF_DYNPTR_SIZE;
15100 		goto out;
15101 	}
15102 
15103 	/* ptr + __sz/__szk pair: the size follows the pointer */
15104 	if (i + 1 < nargs &&
15105 	    (btf_param_match_suffix(btf, &args[i + 1], "__sz") ||
15106 	     btf_param_match_suffix(btf, &args[i + 1], "__szk"))) {
15107 		int size_reg = BPF_REG_1 + arg + 1;
15108 
15109 		if (size_reg <= MAX_BPF_FUNC_REG_ARGS &&
15110 		    (aux->const_reg_mask & BIT(size_reg))) {
15111 			size = aux->const_reg_vals[size_reg];
15112 			goto out;
15113 		}
15114 		/* Unknown size: the read may extend anywhere up to the frame top. */
15115 		return info;
15116 	}
15117 
15118 	/* fixed-size pointed-to type: resolve via BTF */
15119 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
15120 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
15121 		size = type_size;
15122 		goto out;
15123 	}
15124 
15125 	return info;
15126 out:
15127 	info.size = min_t(u64, size, U32_MAX);
15128 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
15129 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
15130 		info.may_read = false;
15131 	if (is_kfunc_arg_uninit(btf, &args[i]) &&
15132 	    (is_kfunc_arg_dynptr(btf, &args[i]) || env->allow_uninit_stack))
15133 		info.may_read = false;
15134 	info.must_write = !info.may_read && info.size != U32_MAX;
15135 	return info;
15136 }
15137 
15138 /*
15139  * Called before dead code elimination, some subprograms may be genuinely unreachable.
15140  * Suppress diagnostics so callers can use a conservative result on error.
15141  * The main pass would report errors for reachable subprograms.
15142  */
15143 static bool try_btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
15144 {
15145 	struct bpf_prog *prog = env->prog;
15146 	u32 log_level = env->log.level;
15147 	int err;
15148 
15149 	if (!prog->aux->func_info || !prog->aux->func_info[subprog].type_id)
15150 		return false;
15151 
15152 	env->log.level = 0;
15153 	err = btf_prepare_func_args(env, subprog);
15154 	env->log.level = log_level;
15155 	return !err;
15156 }
15157 
15158 /* Prepare argument metadata for liveness; the main program is handled separately. */
15159 static void prepare_subprog_args(struct bpf_verifier_env *env)
15160 {
15161 	int i;
15162 
15163 	for (i = 1; i < env->subprog_cnt; i++) {
15164 		if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i))
15165 			/* Keep all argument registers live if the prototype is unavailable. */
15166 			env->subprog_info[i].arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS;
15167 	}
15168 }
15169 
15170 /*
15171  * Derive stack effects for a global subprog's argument slot @arg (0-based)
15172  * from its declared type, matching the main pass's argument checks.
15173  */
15174 struct arg_access_info
15175 bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
15176 				      int arg, int insn_idx)
15177 {
15178 	struct arg_access_info info = {
15179 		.size = U32_MAX,
15180 		.may_read = true,
15181 		.may_write = true,
15182 	};
15183 	struct bpf_subprog_info *sub;
15184 	int callee;
15185 
15186 	callee = bpf_find_subprog(env, insn_idx + insn->imm + 1);
15187 	if (callee < 0)
15188 		return info;
15189 	sub = subprog_info(env, callee);
15190 	if (!try_btf_prepare_func_args(env, callee))
15191 		return info;
15192 
15193 	switch (base_type(sub->args[arg].arg_type)) {
15194 	case ARG_UNUSED:	/* Not an argument slot. */
15195 	case ARG_SCALAR:	/* A scalar, the callee can't dereference it. */
15196 		return (struct arg_access_info) {};
15197 	case ARG_PTR_TO_BTF_ID:
15198 		/*
15199 		 * Trusted arguments cannot be stack pointers.
15200 		 * Untrusted arguments use ARG_IGNORE:
15201 		 * probe reads need no caller stack state, writes are prohibited.
15202 		 */
15203 		return (struct arg_access_info) {};
15204 	case ARG_PTR_TO_MEM:
15205 		/* mem_size is zero for untrusted pointers of unknown size. */
15206 		if (sub->args[arg].mem_size) {
15207 			info.size = sub->args[arg].mem_size;
15208 			info.must_write = true;
15209 		}
15210 		return info;
15211 	case ARG_PTR_TO_DYNPTR:
15212 		/* The callee may adjust the view, but cannot reinitialize the dynptr. */
15213 		info.size = BPF_DYNPTR_SIZE;
15214 		return info;
15215 	default:
15216 		return info;
15217 	}
15218 }
15219 
15220 /* check special kfuncs and return:
15221  *  1  - not fall-through to 'else' branch, continue verification
15222  *  0  - fall-through to 'else' branch
15223  * < 0 - not fall-through to 'else' branch, return error
15224  */
15225 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
15226 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
15227 			       const struct btf_type *ptr_type, struct btf *desc_btf)
15228 {
15229 	const struct btf_type *ret_t;
15230 	int err = 0;
15231 
15232 	if (meta->btf != btf_vmlinux)
15233 		return 0;
15234 
15235 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15236 		struct btf_struct_meta *struct_meta;
15237 		struct btf *ret_btf;
15238 		u32 ret_btf_id;
15239 
15240 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
15241 			return -ENOMEM;
15242 
15243 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
15244 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
15245 			return -EINVAL;
15246 		}
15247 
15248 		ret_btf = env->prog->aux->btf;
15249 		ret_btf_id = meta->arg_constant.value;
15250 
15251 		/* This may be NULL due to user not supplying a BTF */
15252 		if (!ret_btf) {
15253 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
15254 			return -EINVAL;
15255 		}
15256 
15257 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
15258 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
15259 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
15260 			return -EINVAL;
15261 		}
15262 
15263 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15264 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
15265 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
15266 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
15267 				return -EINVAL;
15268 			}
15269 
15270 			if (!bpf_global_percpu_ma_set) {
15271 				mutex_lock(&bpf_percpu_ma_lock);
15272 				if (!bpf_global_percpu_ma_set) {
15273 					/* Charge memory allocated with bpf_global_percpu_ma to
15274 					 * root memcg. The obj_cgroup for root memcg is NULL.
15275 					 */
15276 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
15277 					if (!err)
15278 						bpf_global_percpu_ma_set = true;
15279 				}
15280 				mutex_unlock(&bpf_percpu_ma_lock);
15281 				if (err)
15282 					return err;
15283 			}
15284 
15285 			mutex_lock(&bpf_percpu_ma_lock);
15286 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
15287 			mutex_unlock(&bpf_percpu_ma_lock);
15288 			if (err)
15289 				return err;
15290 		}
15291 
15292 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
15293 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
15294 			if (!btf_type_is_scalar_struct(env, ret_btf, ret_t)) {
15295 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
15296 				return -EINVAL;
15297 			}
15298 
15299 			if (struct_meta) {
15300 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
15301 				return -EINVAL;
15302 			}
15303 		}
15304 
15305 		mark_reg_known_zero(env, regs, BPF_REG_0);
15306 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
15307 		regs[BPF_REG_0].btf = ret_btf;
15308 		regs[BPF_REG_0].btf_id = ret_btf_id;
15309 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
15310 			regs[BPF_REG_0].type |= MEM_PERCPU;
15311 
15312 		insn_aux->obj_new_size = ret_t->size;
15313 		insn_aux->kptr_struct_meta = struct_meta;
15314 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
15315 		mark_reg_known_zero(env, regs, BPF_REG_0);
15316 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
15317 		regs[BPF_REG_0].btf = meta->arg_btf;
15318 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
15319 
15320 		insn_aux->kptr_struct_meta =
15321 			btf_find_struct_meta(meta->arg_btf,
15322 					     meta->arg_btf_id);
15323 	} else if (is_list_node_type(ptr_type)) {
15324 		struct btf_field *field = meta->arg_list_head.field;
15325 
15326 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15327 	} else if (is_rbtree_node_type(ptr_type)) {
15328 		struct btf_field *field = meta->arg_rbtree_root.field;
15329 
15330 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
15331 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx])) {
15332 		mark_reg_known_zero(env, regs, BPF_REG_0);
15333 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
15334 		regs[BPF_REG_0].btf = desc_btf;
15335 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
15336 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_rdonly_cast])) {
15337 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
15338 		if (!ret_t) {
15339 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
15340 				meta->arg_constant.value);
15341 			return -EINVAL;
15342 		} else if (btf_type_is_struct(ret_t)) {
15343 			mark_reg_known_zero(env, regs, BPF_REG_0);
15344 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15345 			regs[BPF_REG_0].btf = desc_btf;
15346 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
15347 		} else if (btf_type_is_void(ret_t)) {
15348 			mark_reg_known_zero(env, regs, BPF_REG_0);
15349 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
15350 			regs[BPF_REG_0].mem_size = 0;
15351 		} else {
15352 			verbose(env,
15353 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
15354 			return -EINVAL;
15355 		}
15356 	} else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
15357 		   is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice_rdwr])) {
15358 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
15359 
15360 		mark_reg_known_zero(env, regs, BPF_REG_0);
15361 
15362 		if (!meta->arg_constant.found) {
15363 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
15364 			return -EFAULT;
15365 		}
15366 
15367 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
15368 
15369 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
15370 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
15371 
15372 		if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice])) {
15373 			regs[BPF_REG_0].type |= MEM_RDONLY;
15374 		} else {
15375 			/* this will set env->seen_direct_write to true */
15376 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
15377 				verbose(env, "the prog does not allow writes to packet data\n");
15378 				return -EINVAL;
15379 			}
15380 		}
15381 
15382 		if (!meta->dynptr.id) {
15383 			verifier_bug(env, "no dynptr id");
15384 			return -EFAULT;
15385 		}
15386 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
15387 	} else {
15388 		return 0;
15389 	}
15390 
15391 	return 1;
15392 }
15393 
15394 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
15395 
15396 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
15397 			    int *insn_idx_p)
15398 {
15399 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
15400 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15401 	struct bpf_reg_state *regs = cur_regs(env);
15402 	const char *func_name, *ptr_type_name;
15403 	const struct btf_type *t, *ptr_type;
15404 	struct bpf_call_arg_meta meta;
15405 	struct bpf_insn_aux_data *insn_aux;
15406 	const char *operation;
15407 	int err, insn_idx = *insn_idx_p;
15408 	u32 i, proto_slots, ptr_type_id, ret_nregs = 1;
15409 	struct bpf_kfunc_desc *desc;
15410 	struct btf *desc_btf;
15411 	int id;
15412 
15413 	/* skip for now, but return error when we find this in fixup_kfunc_call */
15414 	if (!insn->imm)
15415 		return 0;
15416 
15417 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
15418 	if (err == -EACCES && meta.func_name) {
15419 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
15420 		operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name);
15421 		bpf_diag_policy(
15422 			env, insn_idx, operation, "this program cannot call the kfunc",
15423 			"Use a kfunc allowed for this program type and attach point, or change the program context.");
15424 	}
15425 	if (err)
15426 		return err;
15427 	desc_btf = meta.btf;
15428 	func_name = meta.func_name;
15429 	insn_aux = &env->insn_aux_data[insn_idx];
15430 
15431 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
15432 	if (!desc) {
15433 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
15434 		return -EFAULT;
15435 	}
15436 	meta.fn = &desc->proto;
15437 
15438 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
15439 
15440 	if (!insn->off &&
15441 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
15442 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
15443 		struct bpf_verifier_state *branch;
15444 		struct bpf_reg_state *regs;
15445 
15446 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
15447 		if (IS_ERR(branch)) {
15448 			verbose(env, "failed to push state for failed lock acquisition\n");
15449 			return PTR_ERR(branch);
15450 		}
15451 
15452 		regs = branch->frame[branch->curframe]->regs;
15453 
15454 		/* Clear r0-r5 registers in forked state */
15455 		for (i = 0; i < CALLER_SAVED_REGS; i++)
15456 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
15457 
15458 		mark_reg_unknown(env, regs, BPF_REG_0);
15459 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
15460 		if (err) {
15461 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
15462 			return err;
15463 		}
15464 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
15465 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
15466 		return -EFAULT;
15467 	}
15468 
15469 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
15470 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
15471 		operation = bpf_diag_fmt(env, "destructive kfunc %s", meta.func_name);
15472 		bpf_diag_policy(
15473 			env, insn_idx, operation, "destructive kfuncs require CAP_SYS_BOOT",
15474 			"Load the program with CAP_SYS_BOOT, or avoid destructive kfuncs.");
15475 		return -EACCES;
15476 	}
15477 
15478 	if (is_kfunc_perfmon(&meta) && !env->allow_ptr_leaks) {
15479 		verbose(env, "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
15480 			func_name);
15481 		operation = bpf_diag_fmt(env, "kfunc %s", func_name);
15482 		bpf_diag_policy(env, insn_idx, operation, "the kfunc requires CAP_PERFMON",
15483 				"Load the program with CAP_PERFMON, or avoid the kfunc.");
15484 		return -EPERM;
15485 	}
15486 
15487 	sleepable = bpf_is_kfunc_sleepable(&meta);
15488 	if (sleepable && !in_sleepable_context(env)) {
15489 		const char *suggestion;
15490 
15491 		if (in_sleepable(env)) {
15492 			verbose(env, "kernel func %s is sleepable within %s\n",
15493 				func_name, non_sleepable_context_description(env));
15494 			suggestion = "Move the kfunc call outside the critical section, or use a non-sleepable kfunc.";
15495 		} else {
15496 			verbose(env, "program must be sleepable to call sleepable kfunc %s\n",
15497 				func_name);
15498 			suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc.";
15499 		}
15500 		operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name);
15501 		bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion);
15502 		return -EACCES;
15503 	}
15504 
15505 	/* Track non-sleepable context for kfuncs, same as for helpers. */
15506 	if (!in_sleepable_context(env))
15507 		insn_aux->non_sleepable = true;
15508 
15509 	/* Check the arguments */
15510 	err = check_func_args(env, &meta, insn_idx);
15511 	if (err < 0)
15512 		return err;
15513 
15514 	err = mark_raw_stack(env, &meta, insn_idx);
15515 	if (err)
15516 		return err;
15517 
15518 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
15519 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
15520 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
15521 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
15522 	      && !env->prog->sleepable))) {
15523 		struct btf_struct_meta *struct_meta;
15524 
15525 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15526 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
15527 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
15528 				func_name);
15529 			return -EINVAL;
15530 		}
15531 	}
15532 
15533 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
15534 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15535 					 set_rbtree_add_callback_state);
15536 		if (err) {
15537 			verbose(env, "kfunc %s#%d failed callback verification\n",
15538 				func_name, meta.func_id);
15539 			return err;
15540 		}
15541 	}
15542 
15543 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
15544 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15545 					 set_timer_callback_state);
15546 		if (err) {
15547 			verbose(env, "kfunc %s#%d failed callback verification\n",
15548 				func_name, meta.func_id);
15549 			return err;
15550 		}
15551 	}
15552 
15553 	if (is_task_work_add_kfunc(meta.func_id)) {
15554 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15555 					 set_task_work_schedule_callback_state);
15556 		if (err) {
15557 			verbose(env, "kfunc %s#%d failed callback verification\n",
15558 				func_name, meta.func_id);
15559 			return err;
15560 		}
15561 	}
15562 
15563 	if (is_call_rcu_kfunc(meta.func_id)) {
15564 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
15565 					 set_rcu_callback_state);
15566 		if (err) {
15567 			verbose(env, "kfunc %s#%d failed callback verification\n",
15568 				func_name, meta.func_id);
15569 			return err;
15570 		}
15571 	}
15572 
15573 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
15574 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
15575 
15576 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
15577 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
15578 
15579 	if (rcu_lock) {
15580 		env->cur_state->active_rcu_locks++;
15581 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true,
15582 					env->cur_state->active_rcu_locks);
15583 	} else if (rcu_unlock) {
15584 		if (env->cur_state->active_rcu_locks == 0) {
15585 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
15586 			bpf_diag_ctx_underflow(
15587 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15588 				"Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region.");
15589 			return -EINVAL;
15590 		}
15591 		env->cur_state->active_rcu_locks--;
15592 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
15593 					env->cur_state->active_rcu_locks);
15594 		if (!in_rcu_cs(env))
15595 			invalidate_rcu_protected_refs(env);
15596 	} else if (preempt_disable) {
15597 		env->cur_state->active_preempt_locks++;
15598 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true,
15599 					env->cur_state->active_preempt_locks);
15600 	} else if (preempt_enable) {
15601 		if (env->cur_state->active_preempt_locks == 0) {
15602 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
15603 			bpf_diag_ctx_underflow(
15604 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_PREEMPT,
15605 				"Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption.");
15606 			return -EINVAL;
15607 		}
15608 		env->cur_state->active_preempt_locks--;
15609 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
15610 					env->cur_state->active_preempt_locks);
15611 		if (!in_rcu_cs(env))
15612 			invalidate_rcu_protected_refs(env);
15613 	}
15614 
15615 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
15616 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
15617 		return -EACCES;
15618 	}
15619 
15620 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
15621 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
15622 		bpf_diag_ctx_required(
15623 			env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
15624 			"Call this kfunc between bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
15625 		return -EACCES;
15626 	}
15627 
15628 	/* In case of release function, we get register number of refcounted
15629 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
15630 	 */
15631 	if (meta.release_regno) {
15632 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
15633 		if (err)
15634 			return err;
15635 	}
15636 
15637 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
15638 		id = regs[BPF_REG_2].id;
15639 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
15640 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
15641 		ref_convert_owning_non_owning(env, id);
15642 	}
15643 
15644 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
15645 		if (!bpf_jit_supports_exceptions()) {
15646 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
15647 				func_name, meta.func_id);
15648 			return -ENOTSUPP;
15649 		}
15650 		env->seen_exception = true;
15651 
15652 		/* In the case of the default callback, the cookie value passed
15653 		 * to bpf_throw becomes the return value of the program.
15654 		 */
15655 		if (!env->exception_callback_subprog) {
15656 			err = check_return_code(env, BPF_REG_1, "R1");
15657 			if (err < 0)
15658 				return err;
15659 		}
15660 	}
15661 
15662 	bpf_diag_record_caller_saved(env, regs);
15663 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
15664 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15665 		u32 regno = caller_saved[i];
15666 
15667 		bpf_mark_reg_not_init(env, &regs[regno]);
15668 	}
15669 	invalidate_outgoing_stack_args(env, cur_func(env));
15670 
15671 	/* Check return type */
15672 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
15673 
15674 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
15675 		if (meta.btf != btf_vmlinux ||
15676 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
15677 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
15678 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
15679 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
15680 			return -EINVAL;
15681 		}
15682 	}
15683 
15684 	if (btf_type_is_scalar(t)) {
15685 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15686 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
15687 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
15688 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
15689 	} else if (btf_type_is_struct(t)) {
15690 		struct btf_member_path path = {};
15691 		const char *member_note = "";
15692 
15693 		/*
15694 		 * The returned struct comes back as raw register bits modeled
15695 		 * as an unknown scalar, so a pointer member would be laundered
15696 		 * into a scalar and escape provenance and reference tracking.
15697 		 * Only scalars and arena pointers are allowed; see
15698 		 * btf_validate_return_type() in btf.c for why an arena pointer
15699 		 * is safe here.
15700 		 */
15701 		if (!btf_struct_member_walk(env, desc_btf, t,
15702 					    BTF_MEMBER_SCALAR | BTF_MEMBER_ARENA_PTR, 0, &path)) {
15703 			verbose(env,
15704 				"kernel function %s returns %s %s that is not composed of scalars or arena pointers\n",
15705 				func_name, btf_type_str(t),
15706 				btf_name_by_offset(desc_btf, t->name_off));
15707 			if (path.too_deep) {
15708 				member_note = bpf_diag_fmt(
15709 					env, " It nests structs more than %d levels deep.",
15710 					BTF_MEMBER_MAX_DEPTH);
15711 			} else if (path.depth) {
15712 				char bad_name[BTF_MEMBER_PATH_LEN];
15713 
15714 				btf_member_path_str(desc_btf, &path, bad_name, sizeof(bad_name));
15715 				if (!path.bad_type) {
15716 					verbose(env, "member '%s' is a zero-length array\n",
15717 						bad_name);
15718 					member_note = bpf_diag_fmt(
15719 						env, " Its member '%s' is a zero-length array.",
15720 						bad_name);
15721 				} else {
15722 					verbose(env, "member '%s' has type %s\n", bad_name,
15723 						btf_type_str(path.bad_type));
15724 					member_note = bpf_diag_fmt(
15725 						env,
15726 						" Its member '%s' is %s, not a scalar or an arena pointer.",
15727 						bad_name, btf_type_str(path.bad_type));
15728 				}
15729 			}
15730 			bpf_diag_program_structure(
15731 				env, insn_idx, "unsupported kernel function return type",
15732 				"Call a kernel function that returns only scalars or arena pointers by value.",
15733 				"%s() returns %s %s by value.%s "
15734 				"Only kfuncs returning scalar values or arena pointers, or "
15735 				"structures composed of scalar values or arena pointers are "
15736 				"supported.",
15737 				func_name, btf_type_str(t),
15738 				btf_name_by_offset(desc_btf, t->name_off), member_note);
15739 			return -EINVAL;
15740 		}
15741 		ret_nregs = mark_kfunc_ret_regs(env, regs, t->size);
15742 	} else if (btf_type_is_ptr(t)) {
15743 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
15744 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
15745 		if (err) {
15746 			if (err < 0)
15747 				return err;
15748 		} else if (btf_type_is_void(ptr_type)) {
15749 			/* kfunc returning 'void *' is equivalent to returning scalar */
15750 			mark_reg_unknown(env, regs, BPF_REG_0);
15751 		} else if (!__btf_type_is_struct(ptr_type)) {
15752 			if (!meta.ret_mem.found) {
15753 				__u32 sz;
15754 
15755 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
15756 					meta.ret_mem.found = true;
15757 					meta.ret_mem.size = sz;
15758 					meta.r0_rdonly = true;
15759 				}
15760 
15761 				if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
15762 					meta.r0_rdonly = false;
15763 			}
15764 			if (!meta.ret_mem.found) {
15765 				ptr_type_name = btf_name_by_offset(desc_btf,
15766 								   ptr_type->name_off);
15767 				verbose(env,
15768 					"kernel function %s returns pointer type %s %s is not supported\n",
15769 					func_name,
15770 					btf_type_str(ptr_type),
15771 					ptr_type_name);
15772 				return -EINVAL;
15773 			}
15774 
15775 			mark_reg_known_zero(env, regs, BPF_REG_0);
15776 			regs[BPF_REG_0].type = PTR_TO_MEM;
15777 			regs[BPF_REG_0].mem_size = meta.ret_mem.size;
15778 
15779 			if (meta.r0_rdonly)
15780 				regs[BPF_REG_0].type |= MEM_RDONLY;
15781 
15782 			/* Ensures we don't access the memory after a release_reference() */
15783 			if (meta.ref_obj.id) {
15784 				err = validate_ref_obj(env, &meta.ref_obj);
15785 				if (err)
15786 					return err;
15787 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
15788 			}
15789 
15790 			if (is_kfunc_rcu_protected(&meta))
15791 				regs[BPF_REG_0].type |= MEM_RCU;
15792 		} else {
15793 			enum bpf_reg_type type = PTR_TO_BTF_ID;
15794 
15795 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
15796 				type |= PTR_UNTRUSTED;
15797 			else if (is_kfunc_rcu_protected(&meta) ||
15798 				 (bpf_is_iter_next_kfunc(&meta) &&
15799 				  (get_iter_from_state(env->cur_state, &meta)
15800 					   ->type & MEM_RCU))) {
15801 				/*
15802 				 * If the iterator's constructor (the _new
15803 				 * function e.g., bpf_iter_task_new) has been
15804 				 * annotated with BPF kfunc flag
15805 				 * KF_RCU_PROTECTED and was called within a RCU
15806 				 * read-side critical section, also propagate
15807 				 * the MEM_RCU flag to the pointer returned from
15808 				 * the iterator's next function (e.g.,
15809 				 * bpf_iter_task_next).
15810 				 */
15811 				type |= MEM_RCU;
15812 			} else {
15813 				/*
15814 				 * Any PTR_TO_BTF_ID that is returned from a BPF
15815 				 * kfunc should by default be treated as
15816 				 * implicitly trusted.
15817 				 */
15818 				type |= PTR_TRUSTED;
15819 			}
15820 
15821 			mark_reg_known_zero(env, regs, BPF_REG_0);
15822 			regs[BPF_REG_0].btf = desc_btf;
15823 			regs[BPF_REG_0].type = type;
15824 			regs[BPF_REG_0].btf_id = ptr_type_id;
15825 		}
15826 
15827 		if (is_kfunc_ret_null(&meta)) {
15828 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
15829 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
15830 			regs[BPF_REG_0].id = ++env->id_gen;
15831 		}
15832 		if (is_kfunc_acquire(&meta)) {
15833 			id = acquire_reference(env, insn_idx, 0);
15834 			if (id < 0)
15835 				return id;
15836 			regs[BPF_REG_0].id = id;
15837 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
15838 			ref_set_non_owning(env, &regs[BPF_REG_0]);
15839 		}
15840 
15841 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
15842 			regs[BPF_REG_0].id = ++env->id_gen;
15843 	} else if (btf_type_is_void(t)) {
15844 		if (meta.btf == btf_vmlinux) {
15845 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
15846 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
15847 				insn_aux->kptr_struct_meta =
15848 					btf_find_struct_meta(meta.arg_btf,
15849 							     meta.arg_btf_id);
15850 			}
15851 		}
15852 	}
15853 
15854 	if (is_kfunc_dynptr_write(&meta) ?
15855 	    dynptr_write_changes_pkt_data(meta.dynptr_write_type) :
15856 	    bpf_is_kfunc_pkt_changing(&meta))
15857 		clear_all_pkt_pointers(env);
15858 
15859 	/*
15860 	 * These kfuncs write to the head of the skb in place if what they write
15861 	 * to is linear. Like a direct write that takes bpf_unclone_prologue().
15862 	 */
15863 	if (is_kfunc_dynptr_write(&meta) &&
15864 	    dynptr_write_changes_pkt_data(meta.dynptr_write_type))
15865 		may_access_direct_pkt_data(env, NULL, BPF_WRITE);
15866 
15867 	proto_slots = kfunc_abi_slots(&desc->func_model);
15868 	if (proto_slots > MAX_BPF_FUNC_REG_ARGS) {
15869 		struct bpf_func_state *caller = cur_func(env);
15870 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
15871 		u16 out_stack_arg_cnt = proto_slots - MAX_BPF_FUNC_REG_ARGS;
15872 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
15873 
15874 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
15875 			caller_info->stack_arg_cnt = stack_arg_cnt;
15876 	}
15877 
15878 	/*
15879 	 * Record R0 before process_iter_next_call() snapshots the alternate
15880 	 * iterator path's diagnostic position.
15881 	 */
15882 	if (ret_nregs == 1)
15883 		bpf_diag_mod_end(env);
15884 
15885 	if (bpf_is_iter_next_kfunc(&meta)) {
15886 		err = process_iter_next_call(env, insn_idx, &meta);
15887 		if (err)
15888 			return err;
15889 	}
15890 
15891 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
15892 		env->prog->call_session_cookie = true;
15893 
15894 	if (bpf_is_throw_kfunc(insn))
15895 		return process_bpf_exit_full(env, NULL, true);
15896 
15897 	return 0;
15898 }
15899 
15900 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
15901 					 const struct bpf_reg_state *reg,
15902 					 enum bpf_reg_type type)
15903 {
15904 	bool known = tnum_is_const(reg->var_off);
15905 	s64 val = reg->var_off.value;
15906 	s64 smin = reg_smin(reg);
15907 
15908 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
15909 		verbose(env, "math between %s pointer and %lld is not allowed\n",
15910 			reg_type_str(env, type), val);
15911 		return false;
15912 	}
15913 
15914 	if (smin == S64_MIN) {
15915 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
15916 			reg_type_str(env, type));
15917 		return false;
15918 	}
15919 
15920 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
15921 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
15922 			smin, reg_type_str(env, type));
15923 		return false;
15924 	}
15925 
15926 	return true;
15927 }
15928 
15929 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
15930 				      const struct bpf_reg_state *reg,
15931 				      enum bpf_reg_type type)
15932 {
15933 	bool known = tnum_is_const(reg->var_off);
15934 	s64 val = reg->var_off.value;
15935 	s64 smin = reg_smin(reg);
15936 
15937 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
15938 		verbose(env, "%s pointer offset %lld is not allowed\n",
15939 			reg_type_str(env, type), val);
15940 		return false;
15941 	}
15942 
15943 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
15944 		verbose(env, "%s pointer offset %lld is not allowed\n",
15945 			reg_type_str(env, type), smin);
15946 		return false;
15947 	}
15948 
15949 	return true;
15950 }
15951 
15952 enum {
15953 	REASON_BOUNDS	= -1,
15954 	REASON_TYPE	= -2,
15955 	REASON_PATHS	= -3,
15956 	REASON_LIMIT	= -4,
15957 	REASON_STACK	= -5,
15958 };
15959 
15960 static int retrieve_ptr_limit(const struct bpf_verifier_env *env,
15961 			      const struct bpf_reg_state *ptr_reg,
15962 			      u32 *alu_limit, bool mask_to_left)
15963 {
15964 	u32 max = 0, ptr_limit = 0;
15965 
15966 	switch (ptr_reg->type) {
15967 	case PTR_TO_STACK:
15968 		/* Offset 0 is out-of-bounds, but acceptable start for the
15969 		 * left direction, see BPF_REG_FP. Also, unknown scalar
15970 		 * offset where we would need to deal with min/max bounds is
15971 		 * currently prohibited for unprivileged.
15972 		 */
15973 		max = env->stack_limit + mask_to_left;
15974 		ptr_limit = -ptr_reg->var_off.value;
15975 		break;
15976 	case PTR_TO_MAP_VALUE:
15977 		max = ptr_reg->map_ptr->value_size;
15978 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
15979 		break;
15980 	default:
15981 		return REASON_TYPE;
15982 	}
15983 
15984 	if (ptr_limit >= max)
15985 		return REASON_LIMIT;
15986 	*alu_limit = ptr_limit;
15987 	return 0;
15988 }
15989 
15990 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
15991 				    const struct bpf_insn *insn)
15992 {
15993 	return env->bypass_spec_v1 ||
15994 		BPF_SRC(insn->code) == BPF_K ||
15995 		cur_aux(env)->nospec;
15996 }
15997 
15998 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
15999 				       u32 alu_state, u32 alu_limit)
16000 {
16001 	/* If we arrived here from different branches with different
16002 	 * state or limits to sanitize, then this won't work.
16003 	 */
16004 	if (aux->alu_state &&
16005 	    (aux->alu_state != alu_state ||
16006 	     aux->alu_limit != alu_limit))
16007 		return REASON_PATHS;
16008 
16009 	/* Corresponding fixup done in do_misc_fixups(). */
16010 	aux->alu_state = alu_state;
16011 	aux->alu_limit = alu_limit;
16012 	return 0;
16013 }
16014 
16015 static int sanitize_val_alu(struct bpf_verifier_env *env,
16016 			    struct bpf_insn *insn)
16017 {
16018 	struct bpf_insn_aux_data *aux = cur_aux(env);
16019 
16020 	if (can_skip_alu_sanitation(env, insn))
16021 		return 0;
16022 
16023 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
16024 }
16025 
16026 static bool sanitize_needed(u8 opcode)
16027 {
16028 	return opcode == BPF_ADD || opcode == BPF_SUB;
16029 }
16030 
16031 struct bpf_sanitize_info {
16032 	struct bpf_insn_aux_data aux;
16033 	bool mask_to_left;
16034 };
16035 
16036 static int sanitize_speculative_path(struct bpf_verifier_env *env,
16037 				     const struct bpf_insn *insn,
16038 				     u32 next_idx, u32 curr_idx)
16039 {
16040 	struct bpf_verifier_state *branch;
16041 	struct bpf_reg_state *regs;
16042 
16043 	branch = push_stack(env, next_idx, curr_idx, true);
16044 	if (!IS_ERR(branch) && insn) {
16045 		regs = branch->frame[branch->curframe]->regs;
16046 		if (BPF_SRC(insn->code) == BPF_K) {
16047 			mark_reg_unknown(env, regs, insn->dst_reg);
16048 		} else if (BPF_SRC(insn->code) == BPF_X) {
16049 			mark_reg_unknown(env, regs, insn->dst_reg);
16050 			mark_reg_unknown(env, regs, insn->src_reg);
16051 		}
16052 	}
16053 	return PTR_ERR_OR_ZERO(branch);
16054 }
16055 
16056 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
16057 			    struct bpf_insn *insn,
16058 			    const struct bpf_reg_state *ptr_reg,
16059 			    const struct bpf_reg_state *off_reg,
16060 			    struct bpf_reg_state *dst_reg,
16061 			    struct bpf_sanitize_info *info,
16062 			    const bool commit_window)
16063 {
16064 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
16065 	struct bpf_verifier_state *vstate = env->cur_state;
16066 	bool off_is_imm = tnum_is_const(off_reg->var_off);
16067 	bool off_is_neg = reg_smin(off_reg) < 0;
16068 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
16069 	u8 opcode = BPF_OP(insn->code);
16070 	u32 alu_state, alu_limit;
16071 	struct bpf_reg_state tmp;
16072 	int err;
16073 
16074 	if (can_skip_alu_sanitation(env, insn))
16075 		return 0;
16076 
16077 	/* We already marked aux for masking from non-speculative
16078 	 * paths, thus we got here in the first place. We only care
16079 	 * to explore bad access from here.
16080 	 */
16081 	if (vstate->speculative)
16082 		goto do_sim;
16083 
16084 	if (!commit_window) {
16085 		if (!tnum_is_const(off_reg->var_off) &&
16086 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
16087 			return REASON_BOUNDS;
16088 
16089 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
16090 				     (opcode == BPF_SUB && !off_is_neg);
16091 	}
16092 
16093 	err = retrieve_ptr_limit(env, ptr_reg, &alu_limit, info->mask_to_left);
16094 	if (err < 0)
16095 		return err;
16096 
16097 	if (commit_window) {
16098 		/* In commit phase we narrow the masking window based on
16099 		 * the observed pointer move after the simulated operation.
16100 		 */
16101 		alu_state = info->aux.alu_state;
16102 		alu_limit = abs(info->aux.alu_limit - alu_limit);
16103 	} else {
16104 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
16105 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
16106 		alu_state |= ptr_is_dst_reg ?
16107 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
16108 
16109 		/* Limit pruning on unknown scalars to enable deep search for
16110 		 * potential masking differences from other program paths.
16111 		 */
16112 		if (!off_is_imm)
16113 			env->explore_alu_limits = true;
16114 	}
16115 
16116 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
16117 	if (err < 0)
16118 		return err;
16119 do_sim:
16120 	/* If we're in commit phase, we're done here given we already
16121 	 * pushed the truncated dst_reg into the speculative verification
16122 	 * stack.
16123 	 *
16124 	 * Also, when register is a known constant, we rewrite register-based
16125 	 * operation to immediate-based, and thus do not need masking (and as
16126 	 * a consequence, do not need to simulate the zero-truncation either).
16127 	 */
16128 	if (commit_window || off_is_imm)
16129 		return 0;
16130 
16131 	/* Simulate and find potential out-of-bounds access under
16132 	 * speculative execution from truncation as a result of
16133 	 * masking when off was not within expected range. If off
16134 	 * sits in dst, then we temporarily need to move ptr there
16135 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
16136 	 * for cases where we use K-based arithmetic in one direction
16137 	 * and truncated reg-based in the other in order to explore
16138 	 * bad access.
16139 	 */
16140 	if (!ptr_is_dst_reg) {
16141 		tmp = *dst_reg;
16142 		*dst_reg = *ptr_reg;
16143 	}
16144 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
16145 	if (err < 0)
16146 		return REASON_STACK;
16147 	if (!ptr_is_dst_reg)
16148 		*dst_reg = tmp;
16149 	return 0;
16150 }
16151 
16152 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
16153 {
16154 	struct bpf_verifier_state *vstate = env->cur_state;
16155 
16156 	/* If we simulate paths under speculation, we don't update the
16157 	 * insn as 'seen' such that when we verify unreachable paths in
16158 	 * the non-speculative domain, sanitize_dead_code() can still
16159 	 * rewrite/sanitize them.
16160 	 */
16161 	if (!vstate->speculative)
16162 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
16163 }
16164 
16165 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason)
16166 {
16167 	static const char *err = "pointer arithmetic with it prohibited for !root";
16168 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
16169 	u32 dst = insn->dst_reg, src = insn->src_reg;
16170 	struct bpf_reg_state *regs = cur_regs(env);
16171 
16172 	switch (reason) {
16173 	case REASON_BOUNDS:
16174 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
16175 			regs[src].type == SCALAR_VALUE ? src : dst, err);
16176 		break;
16177 	case REASON_TYPE:
16178 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
16179 			regs[src].type == SCALAR_VALUE ? dst : src, err);
16180 		break;
16181 	case REASON_PATHS:
16182 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
16183 			dst, op, err);
16184 		break;
16185 	case REASON_LIMIT:
16186 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
16187 			dst, op, err);
16188 		break;
16189 	case REASON_STACK:
16190 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
16191 			dst, err);
16192 		return -ENOMEM;
16193 	default:
16194 		verifier_bug(env, "unknown reason (%d)", reason);
16195 		break;
16196 	}
16197 
16198 	return -EACCES;
16199 }
16200 
16201 /* check that stack access falls within stack limits and that 'reg' doesn't
16202  * have a variable offset.
16203  *
16204  * Variable offset is prohibited for unprivileged mode for simplicity since it
16205  * requires corresponding support in Spectre masking for stack ALU.  See also
16206  * retrieve_ptr_limit().
16207  */
16208 static int check_stack_access_for_ptr_arithmetic(
16209 				struct bpf_verifier_env *env,
16210 				int regno,
16211 				const struct bpf_reg_state *reg,
16212 				int off)
16213 {
16214 	if (!tnum_is_const(reg->var_off)) {
16215 		char tn_buf[48];
16216 
16217 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
16218 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
16219 			regno, tn_buf, off);
16220 		return -EACCES;
16221 	}
16222 
16223 	if (off >= 0 || off < -(int)env->stack_limit) {
16224 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
16225 			"prohibited for !root; off=%d\n", regno, off);
16226 		return -EACCES;
16227 	}
16228 
16229 	return 0;
16230 }
16231 
16232 static int sanitize_check_bounds(struct bpf_verifier_env *env,
16233 				 const struct bpf_insn *insn,
16234 				 struct bpf_reg_state *dst_reg)
16235 {
16236 	u32 dst = insn->dst_reg;
16237 
16238 	/* For unprivileged we require that resulting offset must be in bounds
16239 	 * in order to be able to sanitize access later on.
16240 	 */
16241 	if (env->bypass_spec_v1)
16242 		return 0;
16243 
16244 	switch (dst_reg->type) {
16245 	case PTR_TO_STACK:
16246 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
16247 							  dst_reg->var_off.value))
16248 			return -EACCES;
16249 		break;
16250 	case PTR_TO_MAP_VALUE:
16251 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
16252 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
16253 				"prohibited for !root\n", dst);
16254 			return -EACCES;
16255 		}
16256 		break;
16257 	default:
16258 		return -EOPNOTSUPP;
16259 	}
16260 
16261 	return 0;
16262 }
16263 
16264 static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
16265 {
16266 	if (tnum_is_const(src_reg->var_off))
16267 		scalar_step_scale(dst_reg, src_reg->var_off.value);
16268 	else
16269 		reg_step_reset(dst_reg);
16270 }
16271 
16272 static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
16273 {
16274 	u64 amount = src_reg->var_off.value;
16275 
16276 	if (tnum_is_const(src_reg->var_off) && amount < 64)
16277 		scalar_step_scale(dst_reg, 1ULL << amount);
16278 	else
16279 		reg_step_reset(dst_reg);
16280 }
16281 
16282 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
16283  * Caller should also handle BPF_MOV case separately.
16284  * If we return -EACCES, caller may want to try again treating pointer as a
16285  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
16286  */
16287 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
16288 				   u32 ptr_regno, const struct bpf_reg_state *ptr_reg,
16289 				   const struct bpf_reg_state *off_reg)
16290 {
16291 	struct bpf_verifier_state *vstate = env->cur_state;
16292 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16293 	struct bpf_reg_state *regs = state->regs, *dst_reg;
16294 	bool known = tnum_is_const(off_reg->var_off);
16295 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
16296 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
16297 	struct bpf_sanitize_info info = {};
16298 	u8 opcode = BPF_OP(insn->code);
16299 	u32 dst = insn->dst_reg;
16300 	const char *reason;
16301 	int ret, bounds_ret;
16302 	bool to_scalar;
16303 
16304 	dst_reg = &regs[dst];
16305 	/*
16306 	 * Only += and -= keep a pointer. Any other op makes a number of it,
16307 	 * which is fine when the program may see values of pointers anyway.
16308 	 */
16309 	to_scalar = opcode != BPF_ADD && opcode != BPF_SUB && env->allow_ptr_leaks;
16310 
16311 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
16312 	    smin_val > smax_val || umin_val > umax_val) {
16313 		/* Taint dst register if offset had invalid bounds derived from
16314 		 * e.g. dead branches.
16315 		 */
16316 		__mark_reg_unknown(env, dst_reg);
16317 		return 0;
16318 	}
16319 
16320 	if (BPF_CLASS(insn->code) != BPF_ALU64 && !to_scalar) {
16321 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
16322 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
16323 			__mark_reg_unknown(env, dst_reg);
16324 			return 0;
16325 		}
16326 
16327 		verbose(env,
16328 			"R%d 32-bit pointer arithmetic prohibited\n",
16329 			dst);
16330 		reason = bpf_diag_fmt(
16331 			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.",
16332 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
16333 		bpf_diag_register_type(
16334 			env, env->insn_idx, ptr_regno, "32-bit pointer arithmetic", reason,
16335 			"Use a 64-bit ALU instruction with an allowed, bounded scalar offset.");
16336 		return -EACCES;
16337 	}
16338 
16339 	if (ptr_reg->type & PTR_MAYBE_NULL) {
16340 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
16341 			dst, reg_type_str(env, ptr_reg->type));
16342 		reason = bpf_diag_fmt(
16343 			env, "R%d may be NULL (%s). Pointer arithmetic is allowed only after the program proves the pointer is non-NULL on this path.",
16344 			ptr_regno, reg_type_str(env, ptr_reg->type));
16345 		bpf_diag_register_type(
16346 			env, env->insn_idx, ptr_regno, "pointer arithmetic before NULL check", reason,
16347 			"Make sure that a NULL check precedes any arithmetic performed on the pointer.");
16348 		return -EACCES;
16349 	}
16350 
16351 	switch (base_type(ptr_reg->type)) {
16352 	case PTR_TO_CTX:
16353 	case PTR_TO_MAP_VALUE:
16354 	case PTR_TO_MAP_KEY:
16355 	case PTR_TO_STACK:
16356 	case PTR_TO_PACKET_META:
16357 	case PTR_TO_PACKET:
16358 	case PTR_TO_TP_BUFFER:
16359 	case PTR_TO_BTF_ID:
16360 	case PTR_TO_MEM:
16361 	case PTR_TO_BUF:
16362 	case PTR_TO_FUNC:
16363 	case CONST_PTR_TO_DYNPTR:
16364 		break;
16365 	case PTR_TO_FLOW_KEYS:
16366 		if (known)
16367 			break;
16368 		fallthrough;
16369 	case CONST_PTR_TO_MAP:
16370 		/* smin_val represents the known value */
16371 		if (known && smin_val == 0 && opcode == BPF_ADD)
16372 			break;
16373 		fallthrough;
16374 	default:
16375 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
16376 			dst, reg_type_str(env, ptr_reg->type));
16377 		reason = bpf_diag_fmt(
16378 			env, "R%d holds %s. This pointer kind does not allow offset arithmetic.",
16379 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
16380 		bpf_diag_register_type(
16381 			env, env->insn_idx, ptr_regno, "pointer arithmetic is not allowed", reason,
16382 			"Do not change this pointer's offset; use it only in operations accepted for its kind.");
16383 		return -EACCES;
16384 	}
16385 
16386 	if (to_scalar) {
16387 		__mark_reg_unknown(env, dst_reg);
16388 		return 0;
16389 	}
16390 
16391 	/* For 'scalar += pointer', dst_reg inherits the complete pointer
16392 	 * register state. Individual fields may be adjusted later by pointer
16393 	 * arithmetic. Callers guarantee that below does not overwrite off_reg.
16394 	 */
16395 	if (dst_reg != ptr_reg)
16396 		*dst_reg = *ptr_reg;
16397 
16398 	/*
16399 	 * Accesses to untrusted PTR_TO_MEM are done through probe
16400 	 * instructions, hence no need to track offsets.
16401 	 */
16402 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
16403 		return 0;
16404 
16405 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) {
16406 		reason = bpf_diag_fmt(
16407 			env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].",
16408 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF);
16409 		bpf_diag_register_type(
16410 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16411 			"Clamp or bounds-check the scalar offset before applying it to the pointer.");
16412 		return -EINVAL;
16413 	}
16414 	if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) {
16415 		reason = bpf_diag_fmt(
16416 			env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.",
16417 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16418 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16419 		bpf_diag_register_type(
16420 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16421 			"Keep the base pointer within the verifier's allowed offset range before applying more arithmetic.");
16422 		return -EINVAL;
16423 	}
16424 
16425 	if (sanitize_needed(opcode)) {
16426 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
16427 				       &info, false);
16428 		if (ret < 0)
16429 			return sanitize_err(env, insn, ret);
16430 	}
16431 
16432 	/*
16433 	 * Pointer types do not carry 32-bit bounds at the moment. Blank r32
16434 	 * only after sanitize_ptr_alu() may have snapshotted dst_reg into a
16435 	 * speculative path: otherwise reg_bounds_sanity_check() might hit some
16436 	 * constraints violations.
16437 	 */
16438 	__mark_reg32_unbounded(dst_reg);
16439 
16440 	switch (opcode) {
16441 	case BPF_ADD:
16442 		/*
16443 		 * dst_reg gets the pointer type and since some positive
16444 		 * integer value was added to the pointer, give it a new 'id'
16445 		 * if it's a PTR_TO_PACKET.
16446 		 * this creates a new 'base' pointer, off_reg (variable) gets
16447 		 * added into the variable offset, and we copy the fixed offset
16448 		 * from ptr_reg.
16449 		 */
16450 		scalar_step_add(dst_reg, ptr_reg, off_reg);
16451 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
16452 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
16453 		dst_reg->raw = ptr_reg->raw;
16454 		if (reg_is_pkt_pointer(ptr_reg)) {
16455 			if (!known)
16456 				dst_reg->id = ++env->id_gen;
16457 			/*
16458 			 * Clear range for unknown addends since we can't know
16459 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
16460 			 * BEYOND_PKT_END from prior comparison as any pointer
16461 			 * arithmetic invalidates them.
16462 			 */
16463 			if (!known || dst_reg->range < 0)
16464 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16465 		}
16466 		break;
16467 	case BPF_SUB:
16468 		if (dst_reg != ptr_reg) {
16469 			/* scalar -= pointer.  Creates an unknown scalar */
16470 			verbose(env, "R%d tried to subtract pointer from scalar\n",
16471 				dst);
16472 			reason = bpf_diag_fmt(
16473 				env, "This operation subtracts pointer register R%d from scalar register R%d. "
16474 				"The verifier only tracks pointer-minus-scalar arithmetic for allowed pointer types.",
16475 				ptr_regno, dst);
16476 			bpf_diag_register_type(
16477 				env, env->insn_idx, ptr_regno, "pointer subtracted from scalar", reason,
16478 				"Keep the pointer as the base; only add or subtract bounded scalars when permitted.");
16479 			return -EACCES;
16480 		}
16481 		/* We don't allow subtraction from FP, because (according to
16482 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
16483 		 * be able to deal with it.
16484 		 */
16485 		if (ptr_reg->type == PTR_TO_STACK) {
16486 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
16487 				dst);
16488 			reason = bpf_diag_fmt(
16489 				env, "R%d is a stack pointer. The verifier does not allow BPF_SUB to move stack pointers.",
16490 				ptr_regno);
16491 			bpf_diag_register_type(
16492 				env, env->insn_idx, ptr_regno, "subtraction from stack pointer", reason,
16493 				"Use addition from R10 to form stack addresses within the tracked stack frame.");
16494 			return -EACCES;
16495 		}
16496 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
16497 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
16498 		dst_reg->raw = ptr_reg->raw;
16499 		if (reg_is_pkt_pointer(ptr_reg)) {
16500 			if (!known)
16501 				dst_reg->id = ++env->id_gen;
16502 			/*
16503 			 * Clear range if the subtrahend may be negative since
16504 			 * pkt pointer could move past its bounds. A positive
16505 			 * subtrahend moves it backwards keeping positive range
16506 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
16507 			 * prior comparison as arithmetic invalidates them.
16508 			 */
16509 			if ((!known && smin_val < 0) || dst_reg->range < 0)
16510 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
16511 		}
16512 		reg_step_reset(dst_reg);
16513 		break;
16514 	case BPF_AND:
16515 	case BPF_OR:
16516 	case BPF_XOR:
16517 		/* bitwise ops on pointers are troublesome, prohibit. */
16518 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
16519 			dst, bpf_alu_string[opcode >> 4]);
16520 		reason = bpf_diag_fmt(
16521 			env, "R%d holds %s. Bitwise operator %s would destroy the pointer value the verifier is tracking.",
16522 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16523 			bpf_alu_string[opcode >> 4]);
16524 		bpf_diag_register_type(
16525 			env, env->insn_idx, ptr_regno, "bitwise operation on pointer", reason,
16526 			"Do bitwise operations on scalar values, not on pointer-valued registers.");
16527 		return -EACCES;
16528 	default:
16529 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
16530 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
16531 			dst, bpf_alu_string[opcode >> 4]);
16532 		reason = bpf_diag_fmt(
16533 			env, "R%d holds %s. Operator %s is not one of the limited pointer arithmetic operations the verifier can track.",
16534 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
16535 			bpf_alu_string[opcode >> 4]);
16536 		bpf_diag_register_type(
16537 			env, env->insn_idx, ptr_regno, "invalid pointer arithmetic operator", reason,
16538 			"Use only verifier-supported addition or subtraction with a bounded scalar offset, or perform this operation on a scalar value.");
16539 		return -EACCES;
16540 	}
16541 
16542 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) {
16543 		reason = bpf_diag_fmt(
16544 			env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.",
16545 			dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
16546 			bpf_diag_reg_type_plain(env, ptr_reg->type));
16547 		bpf_diag_register_type(
16548 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
16549 			"Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range.");
16550 		return -EINVAL;
16551 	}
16552 	/*
16553 	 * A packet pointer that keeps its id or range is checked against a
16554 	 * range set from the checked pointer's umax, so var_off must not tighten
16555 	 * its umax. r32 must still match var_off for reg_bounds_sanity_check().
16556 	 */
16557 	if (reg_is_pkt_pointer(dst_reg) && (known || dst_reg->range > 0))
16558 		__update_reg32_bounds(dst_reg);
16559 	else
16560 		reg_bounds_sync(dst_reg);
16561 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
16562 	if (bounds_ret == -EACCES)
16563 		return bounds_ret;
16564 	if (sanitize_needed(opcode)) {
16565 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
16566 				       &info, true);
16567 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
16568 				    && !env->cur_state->speculative
16569 				    && bounds_ret
16570 				    && !ret,
16571 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
16572 			return -EFAULT;
16573 		}
16574 		if (ret < 0)
16575 			return sanitize_err(env, insn, ret);
16576 	}
16577 
16578 	return 0;
16579 }
16580 
16581 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
16582 				 struct bpf_reg_state *src_reg)
16583 {
16584 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
16585 }
16586 
16587 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
16588 			       struct bpf_reg_state *src_reg)
16589 {
16590 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
16591 }
16592 
16593 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
16594 				 struct bpf_reg_state *src_reg)
16595 {
16596 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
16597 }
16598 
16599 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
16600 			       struct bpf_reg_state *src_reg)
16601 {
16602 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
16603 }
16604 
16605 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
16606 				 struct bpf_reg_state *src_reg)
16607 {
16608 	s32 smin = reg_s32_min(dst_reg);
16609 	s32 smax = reg_s32_max(dst_reg);
16610 	u32 umin = reg_u32_min(dst_reg);
16611 	u32 umax = reg_u32_max(dst_reg);
16612 	s32 tmp_prod[4];
16613 
16614 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
16615 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
16616 		/* Overflow possible, we know nothing */
16617 		umin = 0;
16618 		umax = U32_MAX;
16619 	}
16620 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
16621 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
16622 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
16623 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
16624 		/* Overflow possible, we know nothing */
16625 		smin = S32_MIN;
16626 		smax = S32_MAX;
16627 	} else {
16628 		smin = min_array(tmp_prod, 4);
16629 		smax = max_array(tmp_prod, 4);
16630 	}
16631 
16632 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
16633 					cnum32_from_srange(smin, smax));
16634 }
16635 
16636 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
16637 			       struct bpf_reg_state *src_reg)
16638 {
16639 	s64 smin = reg_smin(dst_reg);
16640 	s64 smax = reg_smax(dst_reg);
16641 	u64 umin = reg_umin(dst_reg);
16642 	u64 umax = reg_umax(dst_reg);
16643 	s64 tmp_prod[4];
16644 
16645 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
16646 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
16647 		/* Overflow possible, we know nothing */
16648 		umin = 0;
16649 		umax = U64_MAX;
16650 	}
16651 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
16652 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
16653 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
16654 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
16655 		/* Overflow possible, we know nothing */
16656 		smin = S64_MIN;
16657 		smax = S64_MAX;
16658 	} else {
16659 		smin = min_array(tmp_prod, 4);
16660 		smax = max_array(tmp_prod, 4);
16661 	}
16662 
16663 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
16664 					cnum64_from_srange(smin, smax));
16665 }
16666 
16667 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
16668 				  struct bpf_reg_state *src_reg)
16669 {
16670 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16671 
16672 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
16673 			 reg_u32_max(dst_reg) / src_val);
16674 
16675 	/* Reset other ranges/tnum to unbounded/unknown. */
16676 	reset_reg64_and_tnum(dst_reg);
16677 }
16678 
16679 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
16680 				struct bpf_reg_state *src_reg)
16681 {
16682 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16683 
16684 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
16685 			 div64_u64(reg_umax(dst_reg), src_val));
16686 
16687 	/* Reset other ranges/tnum to unbounded/unknown. */
16688 	reset_reg32_and_tnum(dst_reg);
16689 }
16690 
16691 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
16692 				  struct bpf_reg_state *src_reg)
16693 {
16694 	s32 smin = reg_s32_min(dst_reg);
16695 	s32 smax = reg_s32_max(dst_reg);
16696 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16697 	s32 res1, res2;
16698 
16699 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
16700 	if (smin == S32_MIN && src_val == -1) {
16701 		/*
16702 		 * If the dividend range contains more than just S32_MIN,
16703 		 * we cannot precisely track the result, so it becomes unbounded.
16704 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
16705 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
16706 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
16707 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
16708 		 */
16709 		if (smax != S32_MIN) {
16710 			smin = S32_MIN;
16711 			smax = S32_MAX;
16712 		}
16713 		goto reset;
16714 	}
16715 
16716 	res1 = smin / src_val;
16717 	res2 = smax / src_val;
16718 	smin = min(res1, res2);
16719 	smax = max(res1, res2);
16720 
16721 reset:
16722 	reg_set_srange32(dst_reg, smin, smax);
16723 	/* Reset other ranges/tnum to unbounded/unknown. */
16724 	reset_reg64_and_tnum(dst_reg);
16725 }
16726 
16727 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
16728 				struct bpf_reg_state *src_reg)
16729 {
16730 	s64 smin = reg_smin(dst_reg);
16731 	s64 smax = reg_smax(dst_reg);
16732 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16733 	s64 res1, res2;
16734 
16735 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
16736 	if (smin == S64_MIN && src_val == -1) {
16737 		/*
16738 		 * If the dividend range contains more than just S64_MIN,
16739 		 * we cannot precisely track the result, so it becomes unbounded.
16740 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
16741 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
16742 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
16743 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
16744 		 */
16745 		if (smax != S64_MIN) {
16746 			smin = S64_MIN;
16747 			smax = S64_MAX;
16748 		}
16749 		goto reset;
16750 	}
16751 
16752 	res1 = div64_s64(smin, src_val);
16753 	res2 = div64_s64(smax, src_val);
16754 	smin = min(res1, res2);
16755 	smax = max(res1, res2);
16756 
16757 reset:
16758 	reg_set_srange64(dst_reg, smin, smax);
16759 	/* Reset other ranges/tnum to unbounded/unknown. */
16760 	reset_reg32_and_tnum(dst_reg);
16761 }
16762 
16763 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
16764 				  struct bpf_reg_state *src_reg)
16765 {
16766 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
16767 	u32 res_max = src_val - 1;
16768 
16769 	/*
16770 	 * If dst_umax <= res_max, the result remains unchanged.
16771 	 * e.g., [2, 5] % 10 = [2, 5].
16772 	 */
16773 	if (reg_u32_max(dst_reg) <= res_max)
16774 		return;
16775 
16776 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
16777 
16778 	/* Reset other ranges/tnum to unbounded/unknown. */
16779 	reset_reg64_and_tnum(dst_reg);
16780 }
16781 
16782 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
16783 				struct bpf_reg_state *src_reg)
16784 {
16785 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
16786 	u64 res_max = src_val - 1;
16787 
16788 	/*
16789 	 * If dst_umax <= res_max, the result remains unchanged.
16790 	 * e.g., [2, 5] % 10 = [2, 5].
16791 	 */
16792 	if (reg_umax(dst_reg) <= res_max)
16793 		return;
16794 
16795 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
16796 
16797 	/* Reset other ranges/tnum to unbounded/unknown. */
16798 	reset_reg32_and_tnum(dst_reg);
16799 }
16800 
16801 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
16802 				  struct bpf_reg_state *src_reg)
16803 {
16804 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
16805 
16806 	/*
16807 	 * Safe absolute value calculation:
16808 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
16809 	 * Here use unsigned integer to avoid overflow.
16810 	 */
16811 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
16812 
16813 	/*
16814 	 * Calculate the maximum possible absolute value of the result.
16815 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
16816 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
16817 	 */
16818 	s32 res_max_abs = src_abs - 1;
16819 
16820 	/*
16821 	 * If the dividend is already within the result range,
16822 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16823 	 */
16824 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
16825 		return;
16826 
16827 	/* General case: result has the same sign as the dividend. */
16828 	if (reg_s32_min(dst_reg) >= 0) {
16829 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
16830 	} else if (reg_s32_max(dst_reg) <= 0) {
16831 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
16832 	} else {
16833 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
16834 	}
16835 
16836 	/* Reset other ranges/tnum to unbounded/unknown. */
16837 	reset_reg64_and_tnum(dst_reg);
16838 }
16839 
16840 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
16841 				struct bpf_reg_state *src_reg)
16842 {
16843 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
16844 
16845 	/*
16846 	 * Safe absolute value calculation:
16847 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
16848 	 * Here use unsigned integer to avoid overflow.
16849 	 */
16850 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
16851 
16852 	/*
16853 	 * Calculate the maximum possible absolute value of the result.
16854 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
16855 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
16856 	 */
16857 	s64 res_max_abs = src_abs - 1;
16858 
16859 	/*
16860 	 * If the dividend is already within the result range,
16861 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
16862 	 */
16863 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
16864 		return;
16865 
16866 	/* General case: result has the same sign as the dividend. */
16867 	if (reg_smin(dst_reg) >= 0) {
16868 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
16869 	} else if (reg_smax(dst_reg) <= 0) {
16870 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
16871 	} else {
16872 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
16873 	}
16874 
16875 	/* Reset other ranges/tnum to unbounded/unknown. */
16876 	reset_reg32_and_tnum(dst_reg);
16877 }
16878 
16879 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
16880 				 struct bpf_reg_state *src_reg)
16881 {
16882 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16883 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16884 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16885 	u32 umax_val = reg_u32_max(src_reg);
16886 
16887 	if (src_known && dst_known) {
16888 		__mark_reg32_known(dst_reg, var32_off.value);
16889 		return;
16890 	}
16891 
16892 	/* We get our minimum from the var_off, since that's inherently
16893 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
16894 	 */
16895 	reg_set_urange32(dst_reg,
16896 			 var32_off.value,
16897 			 min(reg_u32_max(dst_reg), umax_val));
16898 }
16899 
16900 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
16901 			       struct bpf_reg_state *src_reg)
16902 {
16903 	bool src_known = tnum_is_const(src_reg->var_off);
16904 	bool dst_known = tnum_is_const(dst_reg->var_off);
16905 	u64 umax_val = reg_umax(src_reg);
16906 
16907 	if (src_known && dst_known) {
16908 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16909 		return;
16910 	}
16911 
16912 	/* We get our minimum from the var_off, since that's inherently
16913 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
16914 	 */
16915 	reg_set_urange64(dst_reg,
16916 			 dst_reg->var_off.value,
16917 			 min(reg_umax(dst_reg), umax_val));
16918 
16919 	/* We may learn something more from the var_off */
16920 	__update_reg_bounds(dst_reg);
16921 }
16922 
16923 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
16924 				struct bpf_reg_state *src_reg)
16925 {
16926 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16927 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16928 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16929 	u32 umin_val = reg_u32_min(src_reg);
16930 
16931 	if (src_known && dst_known) {
16932 		__mark_reg32_known(dst_reg, var32_off.value);
16933 		return;
16934 	}
16935 
16936 	/* We get our maximum from the var_off, and our minimum is the
16937 	 * maximum of the operands' minima
16938 	 */
16939 	reg_set_urange32(dst_reg,
16940 			 max(reg_u32_min(dst_reg), umin_val),
16941 			 var32_off.value | var32_off.mask);
16942 }
16943 
16944 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
16945 			      struct bpf_reg_state *src_reg)
16946 {
16947 	bool src_known = tnum_is_const(src_reg->var_off);
16948 	bool dst_known = tnum_is_const(dst_reg->var_off);
16949 	u64 umin_val = reg_umin(src_reg);
16950 
16951 	if (src_known && dst_known) {
16952 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16953 		return;
16954 	}
16955 
16956 	/* We get our maximum from the var_off, and our minimum is the
16957 	 * maximum of the operands' minima
16958 	 */
16959 	reg_set_urange64(dst_reg,
16960 			 max(reg_umin(dst_reg), umin_val),
16961 			 dst_reg->var_off.value | dst_reg->var_off.mask);
16962 
16963 	/* We may learn something more from the var_off */
16964 	__update_reg_bounds(dst_reg);
16965 }
16966 
16967 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
16968 				 struct bpf_reg_state *src_reg)
16969 {
16970 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
16971 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
16972 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
16973 
16974 	if (src_known && dst_known) {
16975 		__mark_reg32_known(dst_reg, var32_off.value);
16976 		return;
16977 	}
16978 
16979 	/* We get both minimum and maximum from the var32_off. */
16980 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
16981 }
16982 
16983 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
16984 			       struct bpf_reg_state *src_reg)
16985 {
16986 	bool src_known = tnum_is_const(src_reg->var_off);
16987 	bool dst_known = tnum_is_const(dst_reg->var_off);
16988 
16989 	if (src_known && dst_known) {
16990 		/* dst_reg->var_off.value has been updated earlier */
16991 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
16992 		return;
16993 	}
16994 
16995 	/* We get both minimum and maximum from the var_off. */
16996 	reg_set_urange64(dst_reg,
16997 			 dst_reg->var_off.value,
16998 			 dst_reg->var_off.value | dst_reg->var_off.mask);
16999 }
17000 
17001 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
17002 				   u64 umin_val, u64 umax_val)
17003 {
17004 	/* If we might shift our top bit out, then we know nothing */
17005 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
17006 		reg_set_urange32(dst_reg, 0, U32_MAX);
17007 	else
17008 		/* We lose all sign bit information (except what we can pick
17009 		 * up from var_off)
17010 		 */
17011 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
17012 				 reg_u32_max(dst_reg) << umax_val);
17013 }
17014 
17015 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
17016 				 struct bpf_reg_state *src_reg)
17017 {
17018 	u32 umax_val = reg_u32_max(src_reg);
17019 	u32 umin_val = reg_u32_min(src_reg);
17020 	/* u32 alu operation will zext upper bits */
17021 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
17022 
17023 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
17024 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
17025 	/* Not required but being careful mark reg64 bounds as unknown so
17026 	 * that we are forced to pick them up from tnum and zext later and
17027 	 * if some path skips this step we are still safe.
17028 	 */
17029 	__mark_reg64_unbounded(dst_reg);
17030 	__update_reg32_bounds(dst_reg);
17031 }
17032 
17033 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
17034 				   u64 umin_val, u64 umax_val)
17035 {
17036 	struct cnum64 u, s;
17037 
17038 	/* Special case <<32 because it is a common compiler pattern to sign
17039 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
17040 	 * because s32 bounds don't flip sign when shifting to the left by
17041 	 * 32bits.
17042 	 */
17043 	if (umin_val == 32 && umax_val == 32)
17044 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
17045 				       (s64)reg_s32_max(dst_reg) << 32);
17046 	else
17047 		s = CNUM64_UNBOUNDED;
17048 
17049 	/* If we might shift our top bit out, then we know nothing */
17050 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
17051 		u = CNUM64_UNBOUNDED;
17052 	else
17053 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
17054 				       reg_umax(dst_reg) << umax_val);
17055 
17056 	dst_reg->r64 = cnum64_intersect(u, s);
17057 }
17058 
17059 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
17060 			       struct bpf_reg_state *src_reg)
17061 {
17062 	u64 umax_val = reg_umax(src_reg);
17063 	u64 umin_val = reg_umin(src_reg);
17064 
17065 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
17066 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
17067 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
17068 
17069 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
17070 	/* We may learn something more from the var_off */
17071 	__update_reg_bounds(dst_reg);
17072 }
17073 
17074 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
17075 				 struct bpf_reg_state *src_reg)
17076 {
17077 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
17078 	u32 umax_val = reg_u32_max(src_reg);
17079 	u32 umin_val = reg_u32_min(src_reg);
17080 
17081 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
17082 	 * be negative, then either:
17083 	 * 1) src_reg might be zero, so the sign bit of the result is
17084 	 *    unknown, so we lose our signed bounds
17085 	 * 2) it's known negative, thus the unsigned bounds capture the
17086 	 *    signed bounds
17087 	 * 3) the signed bounds cross zero, so they tell us nothing
17088 	 *    about the result
17089 	 * If the value in dst_reg is known nonnegative, then again the
17090 	 * unsigned bounds capture the signed bounds.
17091 	 * Thus, in all cases it suffices to blow away our signed bounds
17092 	 * and rely on inferring new ones from the unsigned bounds and
17093 	 * var_off of the result.
17094 	 */
17095 
17096 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
17097 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
17098 			 reg_u32_max(dst_reg) >> umin_val);
17099 
17100 	__mark_reg64_unbounded(dst_reg);
17101 	__update_reg32_bounds(dst_reg);
17102 }
17103 
17104 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
17105 			       struct bpf_reg_state *src_reg)
17106 {
17107 	u64 umax_val = reg_umax(src_reg);
17108 	u64 umin_val = reg_umin(src_reg);
17109 
17110 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
17111 	 * be negative, then either:
17112 	 * 1) src_reg might be zero, so the sign bit of the result is
17113 	 *    unknown, so we lose our signed bounds
17114 	 * 2) it's known negative, thus the unsigned bounds capture the
17115 	 *    signed bounds
17116 	 * 3) the signed bounds cross zero, so they tell us nothing
17117 	 *    about the result
17118 	 * If the value in dst_reg is known nonnegative, then again the
17119 	 * unsigned bounds capture the signed bounds.
17120 	 * Thus, in all cases it suffices to blow away our signed bounds
17121 	 * and rely on inferring new ones from the unsigned bounds and
17122 	 * var_off of the result.
17123 	 */
17124 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
17125 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
17126 			 reg_umax(dst_reg) >> umin_val);
17127 
17128 	/* Its not easy to operate on alu32 bounds here because it depends
17129 	 * on bits being shifted in. Take easy way out and mark unbounded
17130 	 * so we can recalculate later from tnum.
17131 	 */
17132 	__mark_reg32_unbounded(dst_reg);
17133 	__update_reg_bounds(dst_reg);
17134 }
17135 
17136 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
17137 				  struct bpf_reg_state *src_reg)
17138 {
17139 	u64 umin_val = reg_u32_min(src_reg);
17140 
17141 	/* Upon reaching here, src_known is true and
17142 	 * umax_val is equal to umin_val.
17143 	 * Blow away the dst_reg umin_value/umax_value and rely on
17144 	 * dst_reg var_off to refine the result.
17145 	 */
17146 	reg_set_srange32(dst_reg,
17147 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
17148 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
17149 
17150 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
17151 
17152 	__mark_reg64_unbounded(dst_reg);
17153 	__update_reg32_bounds(dst_reg);
17154 }
17155 
17156 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
17157 				struct bpf_reg_state *src_reg)
17158 {
17159 	u64 umin_val = reg_umin(src_reg);
17160 
17161 	/* Upon reaching here, src_known is true and umax_val is equal
17162 	 * to umin_val.
17163 	 */
17164 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
17165 			 reg_smax(dst_reg) >> umin_val);
17166 
17167 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
17168 
17169 	/* Its not easy to operate on alu32 bounds here because it depends
17170 	 * on bits being shifted in from upper 32-bits. Take easy way out
17171 	 * and mark unbounded so we can recalculate later from tnum.
17172 	 */
17173 	__mark_reg32_unbounded(dst_reg);
17174 	__update_reg_bounds(dst_reg);
17175 }
17176 
17177 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
17178 {
17179 	/*
17180 	 * Byte swap operation - update var_off using tnum_bswap.
17181 	 * Three cases:
17182 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
17183 	 *    unconditional swap
17184 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
17185 	 *    swap on big-endian, truncation or no-op on little-endian
17186 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
17187 	 *    swap on little-endian, truncation or no-op on big-endian
17188 	 */
17189 
17190 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
17191 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
17192 	bool is_big_endian;
17193 #ifdef CONFIG_CPU_BIG_ENDIAN
17194 	is_big_endian = true;
17195 #else
17196 	is_big_endian = false;
17197 #endif
17198 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
17199 	bool need_bswap = alu64 || (to_le == is_big_endian);
17200 
17201 	/*
17202 	 * If the register is mutated, manually reset its scalar ID to break
17203 	 * any existing ties and avoid incorrect bounds propagation.
17204 	 */
17205 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
17206 		clear_scalar_id(dst_reg);
17207 
17208 	if (need_bswap) {
17209 		if (insn->imm == 16)
17210 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
17211 		else if (insn->imm == 32)
17212 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
17213 		else if (insn->imm == 64)
17214 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
17215 		/*
17216 		 * Byteswap scrambles the range, so we must reset bounds.
17217 		 * Bounds will be re-derived from the new tnum later.
17218 		 */
17219 		__mark_reg_unbounded(dst_reg);
17220 		reg_step_reset(dst_reg);
17221 	}
17222 	/* For bswap16/32, truncate dst register to match the swapped size */
17223 	if (insn->imm == 16 || insn->imm == 32)
17224 		coerce_reg_to_size(dst_reg, insn->imm / 8);
17225 }
17226 
17227 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
17228 					     const struct bpf_reg_state *src_reg)
17229 {
17230 	bool src_is_const = false;
17231 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
17232 
17233 	if (insn_bitness == 32) {
17234 		if (tnum_subreg_is_const(src_reg->var_off)
17235 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
17236 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
17237 			src_is_const = true;
17238 	} else {
17239 		if (tnum_is_const(src_reg->var_off)
17240 		    && reg_smin(src_reg) == reg_smax(src_reg)
17241 		    && reg_umin(src_reg) == reg_umax(src_reg))
17242 			src_is_const = true;
17243 	}
17244 
17245 	switch (BPF_OP(insn->code)) {
17246 	case BPF_ADD:
17247 	case BPF_SUB:
17248 	case BPF_NEG:
17249 	case BPF_AND:
17250 	case BPF_XOR:
17251 	case BPF_OR:
17252 	case BPF_MUL:
17253 	case BPF_END:
17254 		return true;
17255 
17256 	/*
17257 	 * Division and modulo operators range is only safe to compute when the
17258 	 * divisor is a constant.
17259 	 */
17260 	case BPF_DIV:
17261 	case BPF_MOD:
17262 		return src_is_const;
17263 
17264 	/* Shift operators range is only computable if shift dimension operand
17265 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
17266 	 * includes shifts by a negative number.
17267 	 */
17268 	case BPF_LSH:
17269 	case BPF_RSH:
17270 	case BPF_ARSH:
17271 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
17272 	default:
17273 		return false;
17274 	}
17275 }
17276 
17277 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
17278 			      struct bpf_reg_state *dst_reg)
17279 {
17280 	struct bpf_verifier_state *branch;
17281 	struct bpf_reg_state *regs;
17282 	bool alu32;
17283 
17284 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
17285 		alu32 = false;
17286 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
17287 		alu32 = true;
17288 	else
17289 		return 0;
17290 
17291 	branch = push_stack(env, env->insn_idx, env->insn_idx, false);
17292 	if (IS_ERR(branch))
17293 		return PTR_ERR(branch);
17294 
17295 	regs = branch->frame[branch->curframe]->regs;
17296 	if (alu32) {
17297 		__mark_reg32_known(&regs[insn->dst_reg], 0);
17298 		__mark_reg32_known(dst_reg, -1ull);
17299 	} else {
17300 		__mark_reg_known(&regs[insn->dst_reg], 0);
17301 		__mark_reg_known(dst_reg, -1ull);
17302 	}
17303 	return 0;
17304 }
17305 
17306 /* WARNING: This function does calculations on 64-bit values, but the actual
17307  * execution may occur on 32-bit values. Therefore, things like bitshifts
17308  * need extra checks in the 32-bit case.
17309  */
17310 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
17311 				      struct bpf_insn *insn,
17312 				      struct bpf_reg_state *dst_reg,
17313 				      struct bpf_reg_state src_reg)
17314 {
17315 	u8 opcode = BPF_OP(insn->code);
17316 	s16 off = insn->off;
17317 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
17318 	int ret;
17319 
17320 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
17321 		__mark_reg_unknown(env, dst_reg);
17322 		return 0;
17323 	}
17324 
17325 	if (sanitize_needed(opcode)) {
17326 		ret = sanitize_val_alu(env, insn);
17327 		if (ret < 0)
17328 			return sanitize_err(env, insn, ret);
17329 	}
17330 
17331 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
17332 	 * There are two classes of instructions: The first class we track both
17333 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
17334 	 * greatest amount of precision when alu operations are mixed with jmp32
17335 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
17336 	 * and BPF_OR. This is possible because these ops have fairly easy to
17337 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
17338 	 * See alu32 verifier tests for examples. The second class of
17339 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
17340 	 * with regards to tracking sign/unsigned bounds because the bits may
17341 	 * cross subreg boundaries in the alu64 case. When this happens we mark
17342 	 * the reg unbounded in the subreg bound space and use the resulting
17343 	 * tnum to calculate an approximation of the sign/unsigned bounds.
17344 	 */
17345 	switch (opcode) {
17346 	case BPF_ADD:
17347 		scalar_step_add(dst_reg, dst_reg, &src_reg);
17348 		scalar32_min_max_add(dst_reg, &src_reg);
17349 		scalar_min_max_add(dst_reg, &src_reg);
17350 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
17351 		break;
17352 	case BPF_SUB:
17353 		scalar32_min_max_sub(dst_reg, &src_reg);
17354 		scalar_min_max_sub(dst_reg, &src_reg);
17355 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
17356 		reg_step_reset(dst_reg);
17357 		break;
17358 	case BPF_NEG:
17359 		env->fake_reg[0] = *dst_reg;
17360 		__mark_reg_known(dst_reg, 0);
17361 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
17362 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
17363 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
17364 		reg_step_reset(dst_reg);
17365 		break;
17366 	case BPF_MUL:
17367 		scalar_step_mul(dst_reg, &src_reg);
17368 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
17369 		scalar32_min_max_mul(dst_reg, &src_reg);
17370 		scalar_min_max_mul(dst_reg, &src_reg);
17371 		break;
17372 	case BPF_DIV:
17373 		/* BPF div specification: x / 0 = 0 */
17374 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
17375 			___mark_reg_known(dst_reg, 0);
17376 			break;
17377 		}
17378 		if (alu32)
17379 			if (off == 1)
17380 				scalar32_min_max_sdiv(dst_reg, &src_reg);
17381 			else
17382 				scalar32_min_max_udiv(dst_reg, &src_reg);
17383 		else
17384 			if (off == 1)
17385 				scalar_min_max_sdiv(dst_reg, &src_reg);
17386 			else
17387 				scalar_min_max_udiv(dst_reg, &src_reg);
17388 		reg_step_reset(dst_reg);
17389 		break;
17390 	case BPF_MOD:
17391 		/* BPF mod specification: x % 0 = x */
17392 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
17393 			break;
17394 		if (alu32)
17395 			if (off == 1)
17396 				scalar32_min_max_smod(dst_reg, &src_reg);
17397 			else
17398 				scalar32_min_max_umod(dst_reg, &src_reg);
17399 		else
17400 			if (off == 1)
17401 				scalar_min_max_smod(dst_reg, &src_reg);
17402 			else
17403 				scalar_min_max_umod(dst_reg, &src_reg);
17404 		reg_step_reset(dst_reg);
17405 		break;
17406 	case BPF_AND:
17407 		if (tnum_is_const(src_reg.var_off)) {
17408 			ret = maybe_fork_scalars(env, insn, dst_reg);
17409 			if (ret)
17410 				return ret;
17411 		}
17412 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
17413 		scalar32_min_max_and(dst_reg, &src_reg);
17414 		scalar_min_max_and(dst_reg, &src_reg);
17415 		reg_step_reset(dst_reg);
17416 		break;
17417 	case BPF_OR:
17418 		if (tnum_is_const(src_reg.var_off)) {
17419 			ret = maybe_fork_scalars(env, insn, dst_reg);
17420 			if (ret)
17421 				return ret;
17422 		}
17423 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
17424 		scalar32_min_max_or(dst_reg, &src_reg);
17425 		scalar_min_max_or(dst_reg, &src_reg);
17426 		reg_step_reset(dst_reg);
17427 		break;
17428 	case BPF_XOR:
17429 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
17430 		scalar32_min_max_xor(dst_reg, &src_reg);
17431 		scalar_min_max_xor(dst_reg, &src_reg);
17432 		reg_step_reset(dst_reg);
17433 		break;
17434 	case BPF_LSH:
17435 		scalar_step_lsh(dst_reg, &src_reg);
17436 		if (alu32)
17437 			scalar32_min_max_lsh(dst_reg, &src_reg);
17438 		else
17439 			scalar_min_max_lsh(dst_reg, &src_reg);
17440 		break;
17441 	case BPF_RSH:
17442 		if (alu32)
17443 			scalar32_min_max_rsh(dst_reg, &src_reg);
17444 		else
17445 			scalar_min_max_rsh(dst_reg, &src_reg);
17446 		reg_step_reset(dst_reg);
17447 		break;
17448 	case BPF_ARSH:
17449 		if (alu32)
17450 			scalar32_min_max_arsh(dst_reg, &src_reg);
17451 		else
17452 			scalar_min_max_arsh(dst_reg, &src_reg);
17453 		reg_step_reset(dst_reg);
17454 		break;
17455 	case BPF_END:
17456 		scalar_byte_swap(dst_reg, insn);
17457 		reg_step_reset(dst_reg);
17458 		break;
17459 	default:
17460 		break;
17461 	}
17462 
17463 	/*
17464 	 * ALU32 ops are zero extended into 64bit register.
17465 	 *
17466 	 * BPF_END is already handled inside the helper (truncation),
17467 	 * so skip zext here to avoid unexpected zero extension.
17468 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
17469 	 * This is a 64bit byte swap operation with alu32==true,
17470 	 * but we should not zero extend the result.
17471 	 */
17472 	if (alu32 && opcode != BPF_END)
17473 		zext_32_to_64(dst_reg);
17474 	reg_bounds_sync(dst_reg);
17475 	return 0;
17476 }
17477 
17478 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
17479  * and var_off.
17480  */
17481 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
17482 				   struct bpf_insn *insn)
17483 {
17484 	struct bpf_verifier_state *vstate = env->cur_state;
17485 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
17486 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
17487 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
17488 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
17489 	struct bpf_insn_aux_data *aux = cur_aux(env);
17490 	u8 opcode = BPF_OP(insn->code);
17491 	int err;
17492 
17493 	dst_reg = &regs[insn->dst_reg];
17494 	if (BPF_SRC(insn->code) == BPF_X)
17495 		src_reg = &regs[insn->src_reg];
17496 	else
17497 		src_reg = NULL;
17498 
17499 	/* Case where at least one operand is an arena. */
17500 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
17501 
17502 		if (dst_reg->type != PTR_TO_ARENA)
17503 			*dst_reg = *src_reg;
17504 
17505 		if (BPF_CLASS(insn->code) == BPF_ALU64) {
17506 			/*
17507 			 * Only arena pointers set needs_zext, but doing so
17508 			 * modifies the instruction at fixup time to an ALU32
17509 			 * and makes it unsuitable for 64-bit scalar args. We
17510 			 * prevent zext from being set if the instruction has
17511 			 * been previously called with non-arena registers.
17512 			 */
17513 			if (aux->prevent_zext) {
17514 				verbose(env, "same insn cannot be used with and without arena pointer\n");
17515 				return -EINVAL;
17516 			}
17517 
17518 			/*
17519 			 * 32-bit operations zero upper bits automatically.
17520 			 * 64-bit operations need to be converted to 32.
17521 			 */
17522 			aux->needs_zext = true;
17523 			aux->zext_dst = true;
17524 		}
17525 
17526 		/* Any arithmetic operations are allowed on arena pointers */
17527 		return 0;
17528 	}
17529 
17530 	/* Prevent the instruction from being used with arena pointers (see above). */
17531 	if (env->prog->aux->arena && BPF_CLASS(insn->code) == BPF_ALU64) {
17532 		if (aux->needs_zext) {
17533 			verbose(env, "same insn cannot be used with and without arena pointer\n");
17534 			return -EINVAL;
17535 		}
17536 
17537 		aux->prevent_zext = true;
17538 	}
17539 
17540 	if (dst_reg->type != SCALAR_VALUE)
17541 		ptr_reg = dst_reg;
17542 
17543 	if (BPF_SRC(insn->code) == BPF_X) {
17544 		if (src_reg->type != SCALAR_VALUE) {
17545 			if (dst_reg->type != SCALAR_VALUE) {
17546 				/* Combining two pointers by any ALU op yields
17547 				 * an arbitrary scalar. Disallow all math except
17548 				 * pointer subtraction
17549 				 */
17550 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
17551 					mark_reg_unknown(env, regs, insn->dst_reg);
17552 					return 0;
17553 				}
17554 				verbose(env, "R%d pointer %s pointer prohibited\n",
17555 					insn->dst_reg,
17556 					bpf_alu_string[opcode >> 4]);
17557 				return -EACCES;
17558 			} else {
17559 				/* scalar += pointer
17560 				 * This is legal, but we have to reverse our
17561 				 * src/dest handling in computing the range
17562 				 */
17563 				err = mark_chain_precision(env, insn->dst_reg);
17564 				if (err)
17565 					return err;
17566 				off_reg = *dst_reg;
17567 				return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg,
17568 							       &off_reg);
17569 			}
17570 		} else if (ptr_reg) {
17571 			/* pointer += scalar */
17572 			err = mark_chain_precision(env, insn->src_reg);
17573 			if (err)
17574 				return err;
17575 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg);
17576 		} else if (dst_reg->precise) {
17577 			/* if dst_reg is precise, src_reg should be precise as well */
17578 			err = mark_chain_precision(env, insn->src_reg);
17579 			if (err)
17580 				return err;
17581 		}
17582 	} else {
17583 		/* Pretend the src is a reg with a known value, since we only
17584 		 * need to be able to read from this state.
17585 		 */
17586 		off_reg.type = SCALAR_VALUE;
17587 		__mark_reg_known(&off_reg, insn->imm);
17588 		src_reg = &off_reg;
17589 		if (ptr_reg) /* pointer += K */
17590 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, ptr_reg, src_reg);
17591 	}
17592 
17593 	/* Got here implies adding two SCALAR_VALUEs */
17594 	if (WARN_ON_ONCE(ptr_reg)) {
17595 		print_verifier_state(env, vstate, vstate->curframe, true);
17596 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
17597 		return -EFAULT;
17598 	}
17599 	if (WARN_ON(!src_reg)) {
17600 		print_verifier_state(env, vstate, vstate->curframe, true);
17601 		verbose(env, "verifier internal error: no src_reg\n");
17602 		return -EFAULT;
17603 	}
17604 	/*
17605 	 * For alu32 linked register tracking, we need to check dst_reg's
17606 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
17607 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
17608 	 */
17609 	u64 dst_umax = reg_umax(dst_reg);
17610 
17611 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
17612 	if (err)
17613 		return err;
17614 	/*
17615 	 * Compilers can generate the code
17616 	 * r1 = r2
17617 	 * r1 += 0x1
17618 	 * if r2 < 1000 goto ...
17619 	 * use r1 in memory access
17620 	 * So remember constant delta between r2 and r1 and update r1 after
17621 	 * 'if' condition.
17622 	 */
17623 	if (env->bpf_capable &&
17624 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
17625 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
17626 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
17627 		u64 val = reg_const_value(src_reg, alu32);
17628 		s32 off;
17629 
17630 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
17631 			goto clear_id;
17632 
17633 		if (alu32 && (dst_umax > U32_MAX))
17634 			goto clear_id;
17635 
17636 		off = (s32)val;
17637 
17638 		if (BPF_OP(insn->code) == BPF_SUB) {
17639 			/* Negating S32_MIN would overflow */
17640 			if (off == S32_MIN)
17641 				goto clear_id;
17642 			off = -off;
17643 		}
17644 
17645 		if (dst_reg->id & BPF_ADD_CONST) {
17646 			/*
17647 			 * If the register already went through rX += val
17648 			 * we cannot accumulate another val into rx->off.
17649 			 */
17650 clear_id:
17651 			clear_scalar_id(dst_reg);
17652 		} else {
17653 			if (alu32)
17654 				dst_reg->id |= BPF_ADD_CONST32;
17655 			else
17656 				dst_reg->id |= BPF_ADD_CONST64;
17657 			dst_reg->delta = off;
17658 		}
17659 	} else {
17660 		/*
17661 		 * Make sure ID is cleared otherwise dst_reg min/max could be
17662 		 * incorrectly propagated into other registers by sync_linked_regs()
17663 		 */
17664 		clear_scalar_id(dst_reg);
17665 	}
17666 	return 0;
17667 }
17668 
17669 /*
17670  * Many checks done by this function are quite conservative.
17671  * This is because main verification pass does not maintain
17672  * enough information to track object identities for some
17673  * of the interesting types, e.g. PTR_TO_MEM.
17674  */
17675 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
17676 			    const struct bpf_reg_state *reg_b)
17677 {
17678 	if (reg_a == reg_b)
17679 		return true;
17680 	/* Require matching flags and base types. */
17681 	if (reg_a->type != reg_b->type)
17682 		return false;
17683 	/* NULL can't be compared to some base+offset pointer. */
17684 	if (type_may_be_null(reg_a->type))
17685 		return false;
17686 
17687 	switch (base_type(reg_a->type)) {
17688 	case PTR_TO_STACK:
17689 		return reg_a->frameno == reg_b->frameno;
17690 	case PTR_TO_MAP_VALUE:
17691 		if (reg_a->map_ptr != reg_b->map_ptr || reg_a->map_uid != reg_b->map_uid)
17692 			return false;
17693 		if (reg_a->id && reg_a->id == reg_b->id)
17694 			return true;
17695 		/*
17696 		 * A plain single-element array has one stable value address,
17697 		 * but not when BPF_F_INNER_MAP is set, see arraymap.c:array_map_meta_equal().
17698 		 */
17699 		if (reg_a->map_ptr->map_type == BPF_MAP_TYPE_ARRAY &&
17700 		    reg_a->map_ptr->max_entries == 1 &&
17701 		    !(reg_a->map_ptr->map_flags & BPF_F_INNER_MAP))
17702 			return true;
17703 		/*
17704 		 * The rules above can be simplified / relaxed if:
17705 		 * - fresh IDs would always be assigned for map-value lookups;
17706 		 * - direct map value loads would always have and ID of zero.
17707 		 */
17708 		return false;
17709 	case PTR_TO_MEM:
17710 	case PTR_TO_BUF:
17711 		return reg_a->id && reg_a->id == reg_b->id;
17712 
17713 	default:
17714 		return false;
17715 	}
17716 }
17717 
17718 int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
17719 		      struct cnum64 r64, struct cnum32 r32, u16 base, u16 step)
17720 {
17721 	reg->r64 = r64;
17722 	reg->r32 = r32;
17723 	reg->step = step;
17724 	reg->base = base;
17725 	reg->var_off = tnum_unknown;
17726 	reg_bounds_sync(reg); /* this should infer the tnum alignment */
17727 	return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
17728 }
17729 
17730 /*
17731  * Checks if pointer and packet metadata matches between two registers.
17732  * For use with bpf_reg_union().
17733  */
17734 bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b)
17735 {
17736 	if (a->type != b->type)
17737 		return false;
17738 	if (a->type == SCALAR_VALUE)
17739 		return true;
17740 	return !memcmp(a, b, offsetof(struct bpf_reg_state, var_off)) &&
17741 	       a->id == b->id && a->parent_id == b->parent_id && a->map_uid == b->map_uid;
17742 }
17743 
17744 /*
17745  * Extends acc's scalar range to include src's scalar range.
17746  * Caller must ensure that other kinds of metadata is compatible.
17747  * Caller must clear acc's scalar ID.
17748  */
17749 int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
17750 		  const struct bpf_reg_state *src)
17751 {
17752 	u16 base, step;
17753 
17754 	if (!bpf_reg_union_compatible(acc, src)) {
17755 		verifier_bug(env, "union of incompatible registers");
17756 		return -EFAULT;
17757 	}
17758 	acc->r64 = cnum64_union(acc->r64, src->r64);
17759 	acc->r32 = cnum32_union(acc->r32, src->r32);
17760 	acc->var_off = tnum_union(acc->var_off, src->var_off);
17761 
17762 	/* Retain a common congruence if the bases agree modulo the gcd. */
17763 	step = gcd(acc->step, src->step);
17764 	base = acc->base % step;
17765 	if (base != src->base % step) {
17766 		reg_step_reset(acc);
17767 	} else {
17768 		acc->base = base;
17769 		acc->step = step;
17770 	}
17771 	reg_bounds_sync(acc);
17772 	return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
17773 }
17774 
17775 /* check validity of 32-bit and 64-bit arithmetic operations */
17776 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17777 {
17778 	struct bpf_reg_state *regs = cur_regs(env);
17779 	u8 opcode = BPF_OP(insn->code);
17780 	int err;
17781 
17782 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
17783 
17784 	if (opcode == BPF_END || opcode == BPF_NEG) {
17785 		/* check src operand */
17786 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17787 		if (err)
17788 			return err;
17789 
17790 		if (is_pointer_value(env, insn->dst_reg)) {
17791 			verbose(env, "R%d pointer arithmetic prohibited\n",
17792 				insn->dst_reg);
17793 			return -EACCES;
17794 		}
17795 
17796 		/* check dest operand */
17797 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
17798 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17799 			err = err ?: adjust_scalar_min_max_vals(env, insn,
17800 							 &regs[insn->dst_reg],
17801 							 regs[insn->dst_reg]);
17802 		} else {
17803 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
17804 		}
17805 		if (err)
17806 			return err;
17807 
17808 	} else if (opcode == BPF_MOV) {
17809 
17810 		if (BPF_SRC(insn->code) == BPF_X) {
17811 			if (insn->off == BPF_ADDR_SPACE_CAST) {
17812 				if (!env->prog->aux->arena) {
17813 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
17814 					return -EINVAL;
17815 				}
17816 			}
17817 
17818 			/* check src operand */
17819 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17820 			if (err)
17821 				return err;
17822 		}
17823 
17824 		/* check dest operand, mark as required later */
17825 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17826 		if (err)
17827 			return err;
17828 
17829 		if (BPF_SRC(insn->code) == BPF_X) {
17830 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
17831 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
17832 
17833 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
17834 				if (insn->imm) {
17835 					/* off == BPF_ADDR_SPACE_CAST */
17836 					mark_reg_unknown(env, regs, insn->dst_reg);
17837 					if (insn->imm == 1) /* cast from as(1) to as(0) */
17838 						dst_reg->type = PTR_TO_ARENA;
17839 				} else if (insn->off == 0) {
17840 					/* case: R1 = R2
17841 					 * copy register state to dest reg
17842 					 */
17843 					assign_scalar_id_before_mov(env, src_reg);
17844 					*dst_reg = *src_reg;
17845 				} else {
17846 					/* case: R1 = (s8, s16 s32)R2 */
17847 					if (is_pointer_value(env, insn->src_reg)) {
17848 						verbose(env,
17849 							"R%d sign-extension part of pointer\n",
17850 							insn->src_reg);
17851 						return -EACCES;
17852 					} else if (src_reg->type == SCALAR_VALUE) {
17853 						bool no_sext;
17854 
17855 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
17856 						if (no_sext)
17857 							assign_scalar_id_before_mov(env, src_reg);
17858 						*dst_reg = *src_reg;
17859 						if (!no_sext)
17860 							clear_scalar_id(dst_reg);
17861 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
17862 					} else {
17863 						mark_reg_unknown(env, regs, insn->dst_reg);
17864 					}
17865 				}
17866 			} else {
17867 				/* R1 = (u32) R2 */
17868 				if (is_pointer_value(env, insn->src_reg)) {
17869 					verbose(env,
17870 						"R%d partial copy of pointer\n",
17871 						insn->src_reg);
17872 					return -EACCES;
17873 				} else if (src_reg->type == SCALAR_VALUE) {
17874 					if (insn->off == 0) {
17875 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
17876 
17877 						if (is_src_reg_u32)
17878 							assign_scalar_id_before_mov(env, src_reg);
17879 						*dst_reg = *src_reg;
17880 						/* Make sure ID is cleared if src_reg is not in u32
17881 						 * range otherwise dst_reg min/max could be incorrectly
17882 						 * propagated into src_reg by sync_linked_regs()
17883 						 */
17884 						if (!is_src_reg_u32)
17885 							clear_scalar_id(dst_reg);
17886 					} else {
17887 						/* case: W1 = (s8, s16)W2 */
17888 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
17889 
17890 						if (no_sext)
17891 							assign_scalar_id_before_mov(env, src_reg);
17892 						*dst_reg = *src_reg;
17893 						if (!no_sext)
17894 							clear_scalar_id(dst_reg);
17895 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
17896 					}
17897 				} else {
17898 					mark_reg_unknown(env, regs,
17899 							 insn->dst_reg);
17900 				}
17901 				zext_32_to_64(dst_reg);
17902 				reg_bounds_sync(dst_reg);
17903 			}
17904 		} else {
17905 			/* case: R = imm
17906 			 * remember the value we stored into this reg
17907 			 */
17908 			/* clear any state __mark_reg_known doesn't set */
17909 			mark_reg_unknown(env, regs, insn->dst_reg);
17910 			regs[insn->dst_reg].type = SCALAR_VALUE;
17911 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
17912 				__mark_reg_known(regs + insn->dst_reg,
17913 						 insn->imm);
17914 			} else {
17915 				__mark_reg_known(regs + insn->dst_reg,
17916 						 (u32)insn->imm);
17917 			}
17918 		}
17919 
17920 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
17921 
17922 		if (BPF_SRC(insn->code) == BPF_X) {
17923 			/* check src1 operand */
17924 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17925 			if (err)
17926 				return err;
17927 		}
17928 
17929 		/* check src2 operand */
17930 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17931 		if (err)
17932 			return err;
17933 
17934 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
17935 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
17936 			verbose(env, "div by zero\n");
17937 			return -EINVAL;
17938 		}
17939 
17940 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
17941 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
17942 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
17943 
17944 			if (insn->imm < 0 || insn->imm >= size) {
17945 				verbose(env, "invalid shift %d\n", insn->imm);
17946 				return -EINVAL;
17947 			}
17948 		}
17949 
17950 		/* check dest operand */
17951 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17952 		err = err ?: adjust_reg_min_max_vals(env, insn);
17953 		if (err)
17954 			return err;
17955 	}
17956 
17957 	err = reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
17958 	if (err)
17959 		return err;
17960 
17961 	bpf_diag_mod_end(env);
17962 	return 0;
17963 }
17964 
17965 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
17966 				   struct bpf_reg_state *dst_reg,
17967 				   enum bpf_reg_type type,
17968 				   bool range_right_open)
17969 {
17970 	struct bpf_func_state *state;
17971 	struct bpf_reg_state *reg;
17972 	int new_range;
17973 
17974 	if (reg_umax(dst_reg) == 0 && range_right_open)
17975 		/* This doesn't give us any range */
17976 		return;
17977 
17978 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
17979 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
17980 		 * than pkt_end, but that's because it's also less than pkt.
17981 		 */
17982 		return;
17983 
17984 	new_range = reg_umax(dst_reg);
17985 	if (range_right_open)
17986 		new_range++;
17987 
17988 	/* Examples for register markings:
17989 	 *
17990 	 * pkt_data in dst register:
17991 	 *
17992 	 *   r2 = r3;
17993 	 *   r2 += 8;
17994 	 *   if (r2 > pkt_end) goto <handle exception>
17995 	 *   <access okay>
17996 	 *
17997 	 *   r2 = r3;
17998 	 *   r2 += 8;
17999 	 *   if (r2 < pkt_end) goto <access okay>
18000 	 *   <handle exception>
18001 	 *
18002 	 *   Where:
18003 	 *     r2 == dst_reg, pkt_end == src_reg
18004 	 *     r2=pkt(id=n,off=8,r=0)
18005 	 *     r3=pkt(id=n,off=0,r=0)
18006 	 *
18007 	 * pkt_data in src register:
18008 	 *
18009 	 *   r2 = r3;
18010 	 *   r2 += 8;
18011 	 *   if (pkt_end >= r2) goto <access okay>
18012 	 *   <handle exception>
18013 	 *
18014 	 *   r2 = r3;
18015 	 *   r2 += 8;
18016 	 *   if (pkt_end <= r2) goto <handle exception>
18017 	 *   <access okay>
18018 	 *
18019 	 *   Where:
18020 	 *     pkt_end == dst_reg, r2 == src_reg
18021 	 *     r2=pkt(id=n,off=8,r=0)
18022 	 *     r3=pkt(id=n,off=0,r=0)
18023 	 *
18024 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
18025 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
18026 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
18027 	 * the check.
18028 	 */
18029 
18030 	/* If our ids match, then we must have the same max_value.  And we
18031 	 * don't care about the other reg's fixed offset, since if it's too big
18032 	 * the range won't allow anything.
18033 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
18034 	 */
18035 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
18036 		if (reg->type == type && reg->id == dst_reg->id)
18037 			/* keep the maximum range already checked */
18038 			reg->range = max(reg->range, new_range);
18039 	}));
18040 }
18041 
18042 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
18043 				u8 opcode, bool is_jmp32);
18044 /*
18045  * Learn more information about live branches by simulating refinement on both branches.
18046  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
18047  * that branch is dead.
18048  */
18049 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
18050 {
18051 	/* Fallthrough (FALSE) branch */
18052 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
18053 	reg_bounds_sync(&env->false_reg1);
18054 	reg_bounds_sync(&env->false_reg2);
18055 	/*
18056 	 * If there is a range bounds violation in *any* of the abstract values in either
18057 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
18058 	 * TRUE branch will be taken.
18059 	 */
18060 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
18061 		return 1;
18062 
18063 	/* Jump (TRUE) branch */
18064 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
18065 	reg_bounds_sync(&env->true_reg1);
18066 	reg_bounds_sync(&env->true_reg2);
18067 	/*
18068 	 * If there is a range bounds violation in *any* of the abstract values in either
18069 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
18070 	 * Only FALSE branch will be taken.
18071 	 */
18072 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
18073 		return 0;
18074 
18075 	/* Both branches are possible, we can't determine which one will be taken. */
18076 	return -1;
18077 }
18078 
18079 /*
18080  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
18081  */
18082 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
18083 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
18084 {
18085 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
18086 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
18087 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
18088 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
18089 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
18090 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
18091 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
18092 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
18093 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
18094 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
18095 
18096 	if (reg1 == reg2) {
18097 		switch (opcode) {
18098 		case BPF_JGE:
18099 		case BPF_JLE:
18100 		case BPF_JSGE:
18101 		case BPF_JSLE:
18102 		case BPF_JEQ:
18103 			return 1;
18104 		case BPF_JGT:
18105 		case BPF_JLT:
18106 		case BPF_JSGT:
18107 		case BPF_JSLT:
18108 		case BPF_JNE:
18109 			return 0;
18110 		case BPF_JSET:
18111 			if (tnum_is_const(t1))
18112 				return t1.value != 0;
18113 			else
18114 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
18115 		default:
18116 			return -1;
18117 		}
18118 	}
18119 
18120 	switch (opcode) {
18121 	case BPF_JEQ:
18122 		/* constants, umin/umax and smin/smax checks would be
18123 		 * redundant in this case because they all should match
18124 		 */
18125 		if (tnum_is_const(t1) && tnum_is_const(t2))
18126 			return t1.value == t2.value;
18127 		if (!tnum_overlap(t1, t2))
18128 			return 0;
18129 		/* non-overlapping ranges */
18130 		if (umin1 > umax2 || umax1 < umin2)
18131 			return 0;
18132 		if (smin1 > smax2 || smax1 < smin2)
18133 			return 0;
18134 		if (!is_jmp32) {
18135 			/* if 64-bit ranges are inconclusive, see if we can
18136 			 * utilize 32-bit subrange knowledge to eliminate
18137 			 * branches that can't be taken a priori
18138 			 */
18139 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
18140 			    reg_u32_max(reg1) < reg_u32_min(reg2))
18141 				return 0;
18142 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
18143 			    reg_s32_max(reg1) < reg_s32_min(reg2))
18144 				return 0;
18145 		}
18146 		break;
18147 	case BPF_JNE:
18148 		/* constants, umin/umax and smin/smax checks would be
18149 		 * redundant in this case because they all should match
18150 		 */
18151 		if (tnum_is_const(t1) && tnum_is_const(t2))
18152 			return t1.value != t2.value;
18153 		if (!tnum_overlap(t1, t2))
18154 			return 1;
18155 		/* non-overlapping ranges */
18156 		if (umin1 > umax2 || umax1 < umin2)
18157 			return 1;
18158 		if (smin1 > smax2 || smax1 < smin2)
18159 			return 1;
18160 		if (!is_jmp32) {
18161 			/* if 64-bit ranges are inconclusive, see if we can
18162 			 * utilize 32-bit subrange knowledge to eliminate
18163 			 * branches that can't be taken a priori
18164 			 */
18165 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
18166 			    reg_u32_max(reg1) < reg_u32_min(reg2))
18167 				return 1;
18168 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
18169 			    reg_s32_max(reg1) < reg_s32_min(reg2))
18170 				return 1;
18171 		}
18172 		break;
18173 	case BPF_JSET:
18174 		if (!is_reg_const(reg2, is_jmp32)) {
18175 			swap(reg1, reg2);
18176 			swap(t1, t2);
18177 		}
18178 		if (!is_reg_const(reg2, is_jmp32))
18179 			return -1;
18180 		if ((~t1.mask & t1.value) & t2.value)
18181 			return 1;
18182 		if (!((t1.mask | t1.value) & t2.value))
18183 			return 0;
18184 		break;
18185 	case BPF_JGT:
18186 		if (umin1 > umax2)
18187 			return 1;
18188 		else if (umax1 <= umin2)
18189 			return 0;
18190 		break;
18191 	case BPF_JSGT:
18192 		if (smin1 > smax2)
18193 			return 1;
18194 		else if (smax1 <= smin2)
18195 			return 0;
18196 		break;
18197 	case BPF_JLT:
18198 		if (umax1 < umin2)
18199 			return 1;
18200 		else if (umin1 >= umax2)
18201 			return 0;
18202 		break;
18203 	case BPF_JSLT:
18204 		if (smax1 < smin2)
18205 			return 1;
18206 		else if (smin1 >= smax2)
18207 			return 0;
18208 		break;
18209 	case BPF_JGE:
18210 		if (umin1 >= umax2)
18211 			return 1;
18212 		else if (umax1 < umin2)
18213 			return 0;
18214 		break;
18215 	case BPF_JSGE:
18216 		if (smin1 >= smax2)
18217 			return 1;
18218 		else if (smax1 < smin2)
18219 			return 0;
18220 		break;
18221 	case BPF_JLE:
18222 		if (umax1 <= umin2)
18223 			return 1;
18224 		else if (umin1 > umax2)
18225 			return 0;
18226 		break;
18227 	case BPF_JSLE:
18228 		if (smax1 <= smin2)
18229 			return 1;
18230 		else if (smin1 > smax2)
18231 			return 0;
18232 		break;
18233 	}
18234 
18235 	return simulate_both_branches_taken(env, opcode, is_jmp32);
18236 }
18237 
18238 int bpf_flip_opcode(u32 opcode)
18239 {
18240 	/* How can we transform "a <op> b" into "b <op> a"? */
18241 	static const u8 opcode_flip[16] = {
18242 		/* these stay the same */
18243 		[BPF_JEQ  >> 4] = BPF_JEQ,
18244 		[BPF_JNE  >> 4] = BPF_JNE,
18245 		[BPF_JSET >> 4] = BPF_JSET,
18246 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
18247 		[BPF_JGE  >> 4] = BPF_JLE,
18248 		[BPF_JGT  >> 4] = BPF_JLT,
18249 		[BPF_JLE  >> 4] = BPF_JGE,
18250 		[BPF_JLT  >> 4] = BPF_JGT,
18251 		[BPF_JSGE >> 4] = BPF_JSLE,
18252 		[BPF_JSGT >> 4] = BPF_JSLT,
18253 		[BPF_JSLE >> 4] = BPF_JSGE,
18254 		[BPF_JSLT >> 4] = BPF_JSGT
18255 	};
18256 	return opcode_flip[opcode >> 4];
18257 }
18258 
18259 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
18260 				   struct bpf_reg_state *src_reg,
18261 				   u8 opcode)
18262 {
18263 	struct bpf_reg_state *pkt;
18264 
18265 	if (src_reg->type == PTR_TO_PACKET_END) {
18266 		pkt = dst_reg;
18267 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
18268 		pkt = src_reg;
18269 		opcode = bpf_flip_opcode(opcode);
18270 	} else {
18271 		return -1;
18272 	}
18273 
18274 	if (pkt->range >= 0)
18275 		return -1;
18276 
18277 	switch (opcode) {
18278 	case BPF_JLE:
18279 		/* pkt <= pkt_end */
18280 		fallthrough;
18281 	case BPF_JGT:
18282 		/* pkt > pkt_end */
18283 		if (pkt->range == BEYOND_PKT_END)
18284 			/* pkt has at last one extra byte beyond pkt_end */
18285 			return opcode == BPF_JGT;
18286 		break;
18287 	case BPF_JLT:
18288 		/* pkt < pkt_end */
18289 		fallthrough;
18290 	case BPF_JGE:
18291 		/* pkt >= pkt_end */
18292 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
18293 			return opcode == BPF_JGE;
18294 		break;
18295 	}
18296 	return -1;
18297 }
18298 
18299 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
18300  * and return:
18301  *  1 - branch will be taken and "goto target" will be executed
18302  *  0 - branch will not be taken and fall-through to next insn
18303  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
18304  *      range [0,10]
18305  */
18306 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
18307 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
18308 {
18309 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
18310 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
18311 
18312 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
18313 		u64 val;
18314 
18315 		/*
18316 		 * The low 32 bits of a valid pointer may well be zero, hence
18317 		 * nothing below applies to a 32-bit comparison.
18318 		 */
18319 		if (is_jmp32)
18320 			return -1;
18321 
18322 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
18323 		if (!is_reg_const(reg2, is_jmp32)) {
18324 			opcode = bpf_flip_opcode(opcode);
18325 			swap(reg1, reg2);
18326 		}
18327 		/* and ensure that reg2 is a constant */
18328 		if (!is_reg_const(reg2, is_jmp32))
18329 			return -1;
18330 
18331 		if (!reg_not_null(env, reg1))
18332 			return -1;
18333 
18334 		/* If pointer is valid tests against zero will fail so we can
18335 		 * use this to direct branch taken.
18336 		 */
18337 		val = reg_const_value(reg2, is_jmp32);
18338 		if (val != 0)
18339 			return -1;
18340 
18341 		switch (opcode) {
18342 		case BPF_JEQ:
18343 			return 0;
18344 		case BPF_JNE:
18345 			return 1;
18346 		default:
18347 			return -1;
18348 		}
18349 	}
18350 
18351 	/* now deal with two scalars, but not necessarily constants */
18352 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
18353 }
18354 
18355 /* Opcode that corresponds to a *false* branch condition.
18356  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
18357  */
18358 u8 bpf_rev_opcode(u8 opcode)
18359 {
18360 	switch (opcode) {
18361 	case BPF_JEQ:		return BPF_JNE;
18362 	case BPF_JNE:		return BPF_JEQ;
18363 	/* JSET doesn't have it's reverse opcode in BPF, so add
18364 	 * BPF_X flag to denote the reverse of that operation
18365 	 */
18366 	case BPF_JSET:		return BPF_JSET | BPF_X;
18367 	case BPF_JSET | BPF_X:	return BPF_JSET;
18368 	case BPF_JGE:		return BPF_JLT;
18369 	case BPF_JGT:		return BPF_JLE;
18370 	case BPF_JLE:		return BPF_JGT;
18371 	case BPF_JLT:		return BPF_JGE;
18372 	case BPF_JSGE:		return BPF_JSLT;
18373 	case BPF_JSGT:		return BPF_JSLE;
18374 	case BPF_JSLE:		return BPF_JSGT;
18375 	case BPF_JSLT:		return BPF_JSGE;
18376 	default:		return 0;
18377 	}
18378 }
18379 
18380 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
18381 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
18382 				u8 opcode, bool is_jmp32)
18383 {
18384 	struct tnum t;
18385 	u64 val;
18386 
18387 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
18388 	switch (opcode) {
18389 	case BPF_JGE:
18390 	case BPF_JGT:
18391 	case BPF_JSGE:
18392 	case BPF_JSGT:
18393 		opcode = bpf_flip_opcode(opcode);
18394 		swap(reg1, reg2);
18395 		break;
18396 	default:
18397 		break;
18398 	}
18399 
18400 	switch (opcode) {
18401 	case BPF_JEQ:
18402 		if (is_jmp32) {
18403 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
18404 			reg2->r32 = reg1->r32;
18405 
18406 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
18407 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18408 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
18409 		} else {
18410 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
18411 			reg2->r64 = reg1->r64;
18412 
18413 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
18414 			reg2->var_off = reg1->var_off;
18415 		}
18416 		break;
18417 	case BPF_JNE:
18418 		if (!is_reg_const(reg2, is_jmp32))
18419 			swap(reg1, reg2);
18420 		if (!is_reg_const(reg2, is_jmp32))
18421 			break;
18422 
18423 		/* try to recompute the bound of reg1 if reg2 is a const and
18424 		 * is exactly the edge of reg1.
18425 		 */
18426 		val = reg_const_value(reg2, is_jmp32);
18427 		if (is_jmp32) {
18428 			/* Complement of the range [val, val] as cnum32. */
18429 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
18430 		} else {
18431 			/* Complement of the range [val, val] as cnum64. */
18432 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
18433 		}
18434 		break;
18435 	case BPF_JSET:
18436 		if (!is_reg_const(reg2, is_jmp32))
18437 			swap(reg1, reg2);
18438 		if (!is_reg_const(reg2, is_jmp32))
18439 			break;
18440 		val = reg_const_value(reg2, is_jmp32);
18441 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
18442 		 * requires single bit to learn something useful. E.g., if we
18443 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
18444 		 * are actually set? We can learn something definite only if
18445 		 * it's a single-bit value to begin with.
18446 		 *
18447 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
18448 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
18449 		 * bit 1 is set, which we can readily use in adjustments.
18450 		 */
18451 		if (hweight64(val) != 1)
18452 			break;
18453 		if (is_jmp32) {
18454 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
18455 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18456 		} else {
18457 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
18458 		}
18459 		break;
18460 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see bpf_rev_opcode() */
18461 		if (!is_reg_const(reg2, is_jmp32))
18462 			swap(reg1, reg2);
18463 		if (!is_reg_const(reg2, is_jmp32))
18464 			break;
18465 		val = reg_const_value(reg2, is_jmp32);
18466 		/* Forget the ranges before narrowing tnums, to avoid invariant
18467 		 * violations if we're on a dead branch.
18468 		 */
18469 		__mark_reg_unbounded(reg1);
18470 		reg_step_reset(reg1);
18471 		if (is_jmp32) {
18472 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
18473 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
18474 		} else {
18475 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
18476 		}
18477 		break;
18478 	case BPF_JLE:
18479 		if (is_jmp32) {
18480 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
18481 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
18482 		} else {
18483 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
18484 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
18485 		}
18486 		break;
18487 	case BPF_JLT:
18488 		if (is_jmp32) {
18489 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
18490 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
18491 		} else {
18492 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
18493 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
18494 		}
18495 		break;
18496 	case BPF_JSLE:
18497 		if (is_jmp32) {
18498 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
18499 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
18500 		} else {
18501 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
18502 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
18503 		}
18504 		break;
18505 	case BPF_JSLT:
18506 		if (is_jmp32) {
18507 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
18508 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
18509 		} else {
18510 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
18511 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
18512 		}
18513 		break;
18514 	default:
18515 		return;
18516 	}
18517 }
18518 
18519 /* Check for invariant violations on the registers for both branches of a condition */
18520 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
18521 {
18522 	int err;
18523 
18524 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
18525 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
18526 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
18527 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
18528 	return err;
18529 }
18530 
18531 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
18532 				 struct bpf_reg_state *reg, u32 id,
18533 				 bool is_null)
18534 {
18535 	if (type_may_be_null(reg->type) && reg->id == id &&
18536 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
18537 		/* Old offset should have been known-zero, because we don't
18538 		 * allow pointer arithmetic on pointers that might be NULL.
18539 		 * If we see this happening, don't convert the register.
18540 		 *
18541 		 * But in some cases, some helpers that return local kptrs
18542 		 * advance offset for the returned pointer. In those cases,
18543 		 * it is fine to expect to see reg->var_off.
18544 		 */
18545 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
18546 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
18547 			return;
18548 		if (is_null) {
18549 			/* We don't need id from this point
18550 			 * onwards anymore, thus we should better reset it,
18551 			 * so that state pruning has chances to take effect.
18552 			 */
18553 			__mark_reg_known_zero(reg);
18554 			reg->type = SCALAR_VALUE;
18555 
18556 			return;
18557 		}
18558 
18559 		mark_ptr_not_null_reg(reg);
18560 
18561 		/*
18562 		 * reg->id is preserved for object relationship tracking
18563 		 * and spin_lock lock state tracking
18564 		 */
18565 	}
18566 }
18567 
18568 /* The logic is similar to find_good_pkt_pointers(), both could eventually
18569  * be folded together at some point.
18570  */
18571 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
18572 				  bool is_null)
18573 {
18574 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
18575 	struct bpf_reg_state *regs = state->regs, *reg;
18576 	u32 id = regs[regno].id;
18577 
18578 	if (is_null && find_reference_state(vstate, id))
18579 		/* regs[regno] is in the " == NULL" branch.
18580 		 * No one could have freed the reference state before
18581 		 * doing the NULL check.
18582 		 */
18583 		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
18584 
18585 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
18586 		mark_ptr_or_null_reg(state, reg, id, is_null);
18587 	}));
18588 }
18589 
18590 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
18591 				   struct bpf_reg_state *dst_reg,
18592 				   struct bpf_reg_state *src_reg,
18593 				   struct bpf_verifier_state *this_branch,
18594 				   struct bpf_verifier_state *other_branch)
18595 {
18596 	if (BPF_SRC(insn->code) != BPF_X)
18597 		return false;
18598 
18599 	/* Pointers are always 64-bit. */
18600 	if (BPF_CLASS(insn->code) == BPF_JMP32)
18601 		return false;
18602 
18603 	switch (BPF_OP(insn->code)) {
18604 	case BPF_JGT:
18605 		if ((dst_reg->type == PTR_TO_PACKET &&
18606 		     src_reg->type == PTR_TO_PACKET_END) ||
18607 		    (dst_reg->type == PTR_TO_PACKET_META &&
18608 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18609 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
18610 			find_good_pkt_pointers(this_branch, dst_reg,
18611 					       dst_reg->type, false);
18612 			mark_pkt_end(other_branch, insn->dst_reg, true);
18613 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18614 			    src_reg->type == PTR_TO_PACKET) ||
18615 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18616 			    src_reg->type == PTR_TO_PACKET_META)) {
18617 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
18618 			find_good_pkt_pointers(other_branch, src_reg,
18619 					       src_reg->type, true);
18620 			mark_pkt_end(this_branch, insn->src_reg, false);
18621 		} else {
18622 			return false;
18623 		}
18624 		break;
18625 	case BPF_JLT:
18626 		if ((dst_reg->type == PTR_TO_PACKET &&
18627 		     src_reg->type == PTR_TO_PACKET_END) ||
18628 		    (dst_reg->type == PTR_TO_PACKET_META &&
18629 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18630 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
18631 			find_good_pkt_pointers(other_branch, dst_reg,
18632 					       dst_reg->type, true);
18633 			mark_pkt_end(this_branch, insn->dst_reg, false);
18634 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18635 			    src_reg->type == PTR_TO_PACKET) ||
18636 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18637 			    src_reg->type == PTR_TO_PACKET_META)) {
18638 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
18639 			find_good_pkt_pointers(this_branch, src_reg,
18640 					       src_reg->type, false);
18641 			mark_pkt_end(other_branch, insn->src_reg, true);
18642 		} else {
18643 			return false;
18644 		}
18645 		break;
18646 	case BPF_JGE:
18647 		if ((dst_reg->type == PTR_TO_PACKET &&
18648 		     src_reg->type == PTR_TO_PACKET_END) ||
18649 		    (dst_reg->type == PTR_TO_PACKET_META &&
18650 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18651 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
18652 			find_good_pkt_pointers(this_branch, dst_reg,
18653 					       dst_reg->type, true);
18654 			mark_pkt_end(other_branch, insn->dst_reg, false);
18655 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18656 			    src_reg->type == PTR_TO_PACKET) ||
18657 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18658 			    src_reg->type == PTR_TO_PACKET_META)) {
18659 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
18660 			find_good_pkt_pointers(other_branch, src_reg,
18661 					       src_reg->type, false);
18662 			mark_pkt_end(this_branch, insn->src_reg, true);
18663 		} else {
18664 			return false;
18665 		}
18666 		break;
18667 	case BPF_JLE:
18668 		if ((dst_reg->type == PTR_TO_PACKET &&
18669 		     src_reg->type == PTR_TO_PACKET_END) ||
18670 		    (dst_reg->type == PTR_TO_PACKET_META &&
18671 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
18672 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
18673 			find_good_pkt_pointers(other_branch, dst_reg,
18674 					       dst_reg->type, false);
18675 			mark_pkt_end(this_branch, insn->dst_reg, true);
18676 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
18677 			    src_reg->type == PTR_TO_PACKET) ||
18678 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
18679 			    src_reg->type == PTR_TO_PACKET_META)) {
18680 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
18681 			find_good_pkt_pointers(this_branch, src_reg,
18682 					       src_reg->type, true);
18683 			mark_pkt_end(other_branch, insn->src_reg, false);
18684 		} else {
18685 			return false;
18686 		}
18687 		break;
18688 	default:
18689 		return false;
18690 	}
18691 
18692 	return true;
18693 }
18694 
18695 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
18696 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
18697 {
18698 	struct linked_reg *e;
18699 
18700 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
18701 		return;
18702 
18703 	e = linked_regs_push(reg_set);
18704 	if (e) {
18705 		e->frameno = frameno;
18706 		e->is_reg = is_reg;
18707 		e->regno = spi_or_reg;
18708 	} else {
18709 		clear_scalar_id(reg);
18710 	}
18711 }
18712 
18713 /* For all R being scalar registers or spilled scalar registers
18714  * in verifier state, save R in linked_regs if R->id == id.
18715  * If there are too many Rs sharing same id, reset id for leftover Rs.
18716  */
18717 static void collect_linked_regs(struct bpf_verifier_env *env,
18718 				struct bpf_verifier_state *vstate,
18719 				u32 id,
18720 				struct linked_regs *linked_regs)
18721 {
18722 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18723 	struct bpf_func_state *func;
18724 	struct bpf_reg_state *reg;
18725 	u16 live_regs;
18726 	int i, j;
18727 
18728 	id = id & ~BPF_ADD_CONST;
18729 	for (i = vstate->curframe; i >= 0; i--) {
18730 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
18731 		func = vstate->frame[i];
18732 		for (j = 0; j < BPF_REG_FP; j++) {
18733 			if (!(live_regs & BIT(j)))
18734 				continue;
18735 			reg = &func->regs[j];
18736 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
18737 		}
18738 		for (j = 0; j < bpf_stack_nr_slots(func); j++) {
18739 			struct bpf_stack_state *ss = bpf_stack_slot(func, j);
18740 
18741 			if (!bpf_is_spilled_reg(ss))
18742 				continue;
18743 			reg = &ss->spilled_ptr;
18744 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
18745 		}
18746 	}
18747 }
18748 
18749 /* For all R in linked_regs, copy known_reg range into R
18750  * if R->id == known_reg->id.
18751  */
18752 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
18753 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
18754 {
18755 	struct bpf_reg_state fake_reg;
18756 	struct bpf_reg_state *reg;
18757 	struct linked_reg *e;
18758 	int i;
18759 
18760 	for (i = 0; i < linked_regs->cnt; ++i) {
18761 		e = &linked_regs->entries[i];
18762 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
18763 				: &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr;
18764 		if (reg->type != SCALAR_VALUE || reg == known_reg)
18765 			continue;
18766 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
18767 			continue;
18768 		/*
18769 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
18770 		 * hold across different ALU widths.
18771 		 */
18772 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
18773 			continue;
18774 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
18775 		    reg->delta == known_reg->delta) {
18776 			*reg = *known_reg;
18777 		} else {
18778 			s32 saved_off = reg->delta;
18779 			u32 saved_id = reg->id;
18780 
18781 			fake_reg.type = SCALAR_VALUE;
18782 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
18783 
18784 			/* reg = known_reg; reg += delta */
18785 			*reg = *known_reg;
18786 			/*
18787 			 * Must preserve off and id, otherwise another sync_linked_regs()
18788 			 * will be incorrect.
18789 			 */
18790 			reg->delta = saved_off;
18791 			reg->id = saved_id;
18792 
18793 			scalar_step_add(reg, reg, &fake_reg);
18794 			scalar32_min_max_add(reg, &fake_reg);
18795 			scalar_min_max_add(reg, &fake_reg);
18796 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
18797 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
18798 				zext_32_to_64(reg);
18799 			reg_bounds_sync(reg);
18800 		}
18801 		if (e->is_reg)
18802 			mark_reg_scratched(env, e->regno);
18803 		else
18804 			mark_stack_slot_scratched(env, e->spi);
18805 	}
18806 }
18807 
18808 static int check_cond_jmp_op(struct bpf_verifier_env *env,
18809 			     struct bpf_insn *insn, int *insn_idx)
18810 {
18811 	struct bpf_verifier_state *this_branch = env->cur_state;
18812 	struct bpf_verifier_state *other_branch;
18813 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
18814 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
18815 	struct bpf_reg_state *eq_branch_regs;
18816 	struct linked_regs linked_regs = {};
18817 	u8 opcode = BPF_OP(insn->code);
18818 	int insn_flags = 0;
18819 	bool is_jmp32;
18820 	int pred = -1;
18821 	int err;
18822 
18823 	/* Only conditional jumps are expected to reach here. */
18824 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
18825 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
18826 		return -EINVAL;
18827 	}
18828 
18829 	if (bpf_is_unwind_goto(insn)) {
18830 		if (!env->cur_state->unwound)
18831 			return 0;
18832 		env->cur_state->unwound = false;
18833 		/*
18834 		 * unwind_exit changed its return address, so the return is
18835 		 * mispredicted and what follows unwind_goto runs speculatively.
18836 		 */
18837 		if (!env->bypass_spec_v1) {
18838 			err = sanitize_speculative_path(env, NULL, *insn_idx + 1, *insn_idx);
18839 			if (err)
18840 				return err;
18841 		}
18842 		*insn_idx += insn->off;
18843 		return 0;
18844 	}
18845 
18846 	if (opcode == BPF_JCOND) {
18847 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
18848 		int idx = *insn_idx;
18849 
18850 		prev_st = find_prev_entry(env, cur_st->parent, idx);
18851 
18852 		/* branch out 'fallthrough' insn as a new state to explore */
18853 		queued_st = push_stack(env, idx + 1, idx, false);
18854 		if (IS_ERR(queued_st))
18855 			return PTR_ERR(queued_st);
18856 
18857 		queued_st->may_goto_depth++;
18858 		if (prev_st)
18859 			widen_imprecise_scalars(env, prev_st, queued_st);
18860 		*insn_idx += insn->off;
18861 		return 0;
18862 	}
18863 
18864 	/* check src2 operand */
18865 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18866 	if (err)
18867 		return err;
18868 
18869 	dst_reg = &regs[insn->dst_reg];
18870 	if (BPF_SRC(insn->code) == BPF_X) {
18871 		/* check src1 operand */
18872 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
18873 		if (err)
18874 			return err;
18875 
18876 		src_reg = &regs[insn->src_reg];
18877 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
18878 		    is_pointer_value(env, insn->src_reg)) {
18879 			verbose(env, "R%d pointer comparison prohibited\n",
18880 				insn->src_reg);
18881 			return -EACCES;
18882 		}
18883 
18884 		if (src_reg->type == PTR_TO_STACK)
18885 			insn_flags |= INSN_F_SRC_REG_STACK;
18886 		if (dst_reg->type == PTR_TO_STACK)
18887 			insn_flags |= INSN_F_DST_REG_STACK;
18888 	} else {
18889 		src_reg = &env->fake_reg[0];
18890 		memset(src_reg, 0, sizeof(*src_reg));
18891 		src_reg->type = SCALAR_VALUE;
18892 		__mark_reg_known(src_reg, insn->imm);
18893 
18894 		if (dst_reg->type == PTR_TO_STACK)
18895 			insn_flags |= INSN_F_DST_REG_STACK;
18896 	}
18897 
18898 	if (insn_flags) {
18899 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, NULL, 0);
18900 		if (err)
18901 			return err;
18902 	}
18903 
18904 	/*
18905 	 * Collect the linked registers before env->{true,false}_reg{1,2} setup,
18906 	 * otherwise ids dropped by collect_linked_regs() would be resurrected
18907 	 * when env->{true,false}_reg{1,2} are copied back.
18908 	 */
18909 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
18910 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
18911 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
18912 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
18913 
18914 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
18915 	env->false_reg1 = *dst_reg;
18916 	env->false_reg2 = *src_reg;
18917 	env->true_reg1 = *dst_reg;
18918 	env->true_reg2 = *src_reg;
18919 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
18920 	if (pred >= 0) {
18921 		/* If we get here with a dst_reg pointer type it is because
18922 		 * above is_branch_taken() special cased the 0 comparison.
18923 		 */
18924 		if (!__is_pointer_value(false, dst_reg))
18925 			err = mark_chain_precision(env, insn->dst_reg);
18926 		if (BPF_SRC(insn->code) == BPF_X && !err &&
18927 		    !__is_pointer_value(false, src_reg))
18928 			err = mark_chain_precision(env, insn->src_reg);
18929 		if (err)
18930 			return err;
18931 	}
18932 
18933 	if (pred == 1) {
18934 		/* Only follow the goto, ignore fall-through. If needed, push
18935 		 * the fall-through branch for simulation under speculative
18936 		 * execution.
18937 		 */
18938 		if (!env->bypass_spec_v1) {
18939 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
18940 			if (err < 0)
18941 				return err;
18942 		}
18943 		if (env->log.level & BPF_LOG_LEVEL)
18944 			print_insn_state(env, this_branch, this_branch->curframe);
18945 		*insn_idx += insn->off;
18946 		return 0;
18947 	} else if (pred == 0) {
18948 		/* Only follow the fall-through branch, since that's where the
18949 		 * program will go. If needed, push the goto branch for
18950 		 * simulation under speculative execution.
18951 		 */
18952 		if (!env->bypass_spec_v1) {
18953 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
18954 							*insn_idx);
18955 			if (err < 0)
18956 				return err;
18957 		}
18958 		if (env->log.level & BPF_LOG_LEVEL)
18959 			print_insn_state(env, this_branch, this_branch->curframe);
18960 		return 0;
18961 	}
18962 
18963 	/* Push scalar registers sharing same ID to jump history,
18964 	 * do this before creating 'other_branch', so that both
18965 	 * 'this_branch' and 'other_branch' share this history
18966 	 * if parent state is created.
18967 	 */
18968 	if (linked_regs.cnt > 1) {
18969 		u16 packed[LINKED_REGS_MAX];
18970 
18971 		linked_regs_pack(&linked_regs, packed);
18972 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, packed, linked_regs.cnt);
18973 		if (err)
18974 			return err;
18975 	}
18976 
18977 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
18978 	if (IS_ERR(other_branch))
18979 		return PTR_ERR(other_branch);
18980 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
18981 
18982 	err = regs_bounds_sanity_check_branches(env);
18983 	if (err)
18984 		return err;
18985 
18986 	*dst_reg = env->false_reg1;
18987 	*src_reg = env->false_reg2;
18988 	other_branch_regs[insn->dst_reg] = env->true_reg1;
18989 	if (BPF_SRC(insn->code) == BPF_X)
18990 		other_branch_regs[insn->src_reg] = env->true_reg2;
18991 
18992 	if (BPF_SRC(insn->code) == BPF_X &&
18993 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
18994 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
18995 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
18996 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
18997 				 &linked_regs);
18998 	}
18999 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
19000 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
19001 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
19002 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
19003 				 &linked_regs);
19004 	}
19005 
19006 	/* if one pointer register is compared to another pointer
19007 	 * register check if PTR_MAYBE_NULL could be lifted.
19008 	 * E.g. register A - maybe null
19009 	 *      register B - not null
19010 	 * for JNE A, B, ... - A is not null in the false branch;
19011 	 * for JEQ A, B, ... - A is not null in the true branch.
19012 	 *
19013 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
19014 	 * not need to be null checked by the BPF program, i.e.,
19015 	 * could be null even without PTR_MAYBE_NULL marking, so
19016 	 * only propagate nullness when neither reg is that type.
19017 	 */
19018 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
19019 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
19020 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
19021 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
19022 		eq_branch_regs = NULL;
19023 		switch (opcode) {
19024 		case BPF_JEQ:
19025 			eq_branch_regs = other_branch_regs;
19026 			break;
19027 		case BPF_JNE:
19028 			eq_branch_regs = regs;
19029 			break;
19030 		default:
19031 			/* do nothing */
19032 			break;
19033 		}
19034 		if (eq_branch_regs) {
19035 			/* src == dst && dst != NULL => src != NULL */
19036 			if (reg_not_null(env, dst_reg) && type_may_be_null(src_reg->type))
19037 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
19038 			/* src == dst && src != NULL => dst != NULL */
19039 			if (reg_not_null(env, src_reg) && type_may_be_null(dst_reg->type))
19040 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
19041 		}
19042 	}
19043 
19044 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
19045 	 * Also does the same detection for a register whose the value is
19046 	 * known to be 0.
19047 	 * NOTE: these optimizations below are related with pointer comparison
19048 	 *       which will never be JMP32.
19049 	 */
19050 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
19051 	    type_may_be_null(dst_reg->type) &&
19052 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
19053 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
19054 		/*
19055 		 * For BPF_X the zero is a property of this execution path,
19056 		 * hence src_reg has to be precise.
19057 		 */
19058 		if (BPF_SRC(insn->code) == BPF_X) {
19059 			err = mark_chain_precision(env, insn->src_reg);
19060 			if (err)
19061 				return err;
19062 		}
19063 		/* Mark all identical registers in each branch as either
19064 		 * safe or unknown depending R == 0 or R != 0 conditional.
19065 		 */
19066 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
19067 				      opcode == BPF_JNE);
19068 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
19069 				      opcode == BPF_JEQ);
19070 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
19071 					   this_branch, other_branch) &&
19072 		   is_pointer_value(env, insn->dst_reg)) {
19073 		verbose(env, "R%d pointer comparison prohibited\n",
19074 			insn->dst_reg);
19075 		return -EACCES;
19076 	}
19077 	if (env->log.level & BPF_LOG_LEVEL)
19078 		print_insn_state(env, this_branch, this_branch->curframe);
19079 	return 0;
19080 }
19081 
19082 /* verify BPF_LD_IMM64 instruction */
19083 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
19084 {
19085 	struct bpf_insn_aux_data *aux = cur_aux(env);
19086 	struct bpf_reg_state *regs = cur_regs(env);
19087 	struct bpf_reg_state *dst_reg;
19088 	struct bpf_map *map;
19089 	int err;
19090 
19091 	if (BPF_SIZE(insn->code) != BPF_DW) {
19092 		verbose(env, "invalid BPF_LD_IMM insn\n");
19093 		return -EINVAL;
19094 	}
19095 
19096 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
19097 	if (err)
19098 		return err;
19099 
19100 	dst_reg = &regs[insn->dst_reg];
19101 	bpf_diag_mod_begin(env, dst_reg, NULL, BPF_DIAG_MOD_WRITE);
19102 	if (insn->src_reg == 0) {
19103 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
19104 
19105 		dst_reg->type = SCALAR_VALUE;
19106 		__mark_reg_known(&regs[insn->dst_reg], imm);
19107 		bpf_diag_mod_end(env);
19108 		return 0;
19109 	}
19110 
19111 	/* All special src_reg cases are listed below. From this point onwards
19112 	 * we either succeed and assign a corresponding dst_reg->type after
19113 	 * zeroing the offset, or fail and reject the program.
19114 	 */
19115 	mark_reg_known_zero(env, regs, insn->dst_reg);
19116 
19117 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
19118 		dst_reg->type = aux->btf_var.reg_type;
19119 		switch (base_type(dst_reg->type)) {
19120 		case PTR_TO_MEM:
19121 			dst_reg->mem_size = aux->btf_var.mem_size;
19122 			break;
19123 		case PTR_TO_BTF_ID:
19124 			dst_reg->btf = aux->btf_var.btf;
19125 			dst_reg->btf_id = aux->btf_var.btf_id;
19126 			break;
19127 		default:
19128 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
19129 			return -EFAULT;
19130 		}
19131 		bpf_diag_mod_end(env);
19132 		return 0;
19133 	}
19134 
19135 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
19136 		struct bpf_prog_aux *aux = env->prog->aux;
19137 		u32 subprogno = bpf_find_subprog(env,
19138 						 env->insn_idx + insn->imm + 1);
19139 
19140 		if (!aux->func_info) {
19141 			verbose(env, "missing btf func_info\n");
19142 			return -EINVAL;
19143 		}
19144 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
19145 			verbose(env, "callback function not static\n");
19146 			return -EINVAL;
19147 		}
19148 		/*
19149 		 * When env->subprog_cnt == 1 this instruction won't be rewritten
19150 		 * to hold a real function address. Assume that no usable program
19151 		 * combines e.g. main and timer callback and just reject here.
19152 		 */
19153 		if (subprogno == 0) {
19154 			verbose(env, "callback function cannot be the main program\n");
19155 			return -EINVAL;
19156 		}
19157 
19158 		dst_reg->type = PTR_TO_FUNC;
19159 		dst_reg->subprogno = subprogno;
19160 		bpf_diag_mod_end(env);
19161 		return 0;
19162 	}
19163 
19164 	map = env->used_maps[aux->map_index];
19165 
19166 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
19167 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
19168 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
19169 			__mark_reg_unknown(env, dst_reg);
19170 			dst_reg->map_ptr = map;
19171 			bpf_diag_mod_end(env);
19172 			return 0;
19173 		}
19174 		__mark_reg_known(dst_reg, aux->map_off);
19175 		dst_reg->type = PTR_TO_MAP_VALUE;
19176 		dst_reg->map_ptr = map;
19177 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
19178 			     map->max_entries != 1);
19179 		/* We want reg->id to be same (0) as map_value is not distinct */
19180 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
19181 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
19182 		dst_reg->type = CONST_PTR_TO_MAP;
19183 		dst_reg->map_ptr = map;
19184 	} else {
19185 		verifier_bug(env, "unexpected src reg value for ldimm64");
19186 		return -EFAULT;
19187 	}
19188 
19189 	bpf_diag_mod_end(env);
19190 	return 0;
19191 }
19192 
19193 static bool may_access_skb(enum bpf_prog_type type)
19194 {
19195 	switch (type) {
19196 	case BPF_PROG_TYPE_SOCKET_FILTER:
19197 	case BPF_PROG_TYPE_SCHED_CLS:
19198 	case BPF_PROG_TYPE_SCHED_ACT:
19199 		return true;
19200 	default:
19201 		return false;
19202 	}
19203 }
19204 
19205 /* verify safety of LD_ABS|LD_IND instructions:
19206  * - they can only appear in the programs where ctx == skb
19207  * - since they are wrappers of function calls, they scratch R1-R5 registers,
19208  *   preserve R6-R9, and store return value into R0
19209  *
19210  * Implicit input:
19211  *   ctx == skb == R6 == CTX
19212  *
19213  * Explicit input:
19214  *   SRC == any register
19215  *   IMM == 32-bit immediate
19216  *
19217  * Output:
19218  *   R0 - 8/16/32-bit skb data converted to cpu endianness
19219  */
19220 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
19221 {
19222 	struct bpf_verifier_state *state = env->cur_state;
19223 	struct bpf_reg_state *regs = cur_regs(env);
19224 	static const int ctx_reg = BPF_REG_6;
19225 	u8 mode = BPF_MODE(insn->code);
19226 	int i, err;
19227 
19228 	if (!may_access_skb(resolve_prog_type(env->prog))) {
19229 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
19230 		return -EINVAL;
19231 	}
19232 
19233 	for (i = state->curframe; i; i--) {
19234 		if (state->frame[i]->in_callback_fn) {
19235 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
19236 			return -EINVAL;
19237 		}
19238 	}
19239 
19240 	if (!env->ops->gen_ld_abs) {
19241 		verifier_bug(env, "gen_ld_abs is null");
19242 		return -EFAULT;
19243 	}
19244 
19245 	/* check whether implicit source operand (register R6) is readable */
19246 	err = check_reg_arg(env, ctx_reg, SRC_OP);
19247 	if (err)
19248 		return err;
19249 
19250 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
19251 	 * gen_ld_abs() may terminate the program at runtime, leading to
19252 	 * reference leak.
19253 	 */
19254 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
19255 	if (err)
19256 		return err;
19257 
19258 	if (regs[ctx_reg].type != PTR_TO_CTX) {
19259 		verbose(env,
19260 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
19261 		return -EINVAL;
19262 	}
19263 
19264 	if (mode == BPF_IND) {
19265 		/* check explicit source operand */
19266 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
19267 		if (err)
19268 			return err;
19269 	}
19270 
19271 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
19272 	if (err < 0)
19273 		return err;
19274 
19275 	/* reset caller saved regs to unreadable */
19276 	bpf_diag_record_caller_saved(env, regs);
19277 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
19278 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
19279 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
19280 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
19281 	}
19282 
19283 	/* mark destination R0 register as readable, since it contains
19284 	 * the value fetched from the packet.
19285 	 * Already marked as written above.
19286 	 */
19287 	mark_reg_unknown(env, regs, BPF_REG_0);
19288 	bpf_diag_mod_end(env);
19289 	/*
19290 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
19291 	 * which must be explored by the verifier when in a subprog.
19292 	 */
19293 	if (env->cur_state->curframe) {
19294 		struct bpf_verifier_state *branch;
19295 
19296 		mark_reg_scratched(env, BPF_REG_0);
19297 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
19298 		if (IS_ERR(branch))
19299 			return PTR_ERR(branch);
19300 		mark_reg_known_zero(env, regs, BPF_REG_0);
19301 		err = prepare_func_exit(env, &env->insn_idx);
19302 		if (err)
19303 			return err;
19304 		env->insn_idx--;
19305 	}
19306 	return 0;
19307 }
19308 
19309 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
19310 {
19311 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
19312 
19313 	/* Default return value range. */
19314 	*range = retval_range(0, 1);
19315 
19316 	switch (prog_type) {
19317 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
19318 		switch (env->prog->expected_attach_type) {
19319 		case BPF_CGROUP_UDP4_RECVMSG:
19320 		case BPF_CGROUP_UDP6_RECVMSG:
19321 		case BPF_CGROUP_UNIX_RECVMSG:
19322 		case BPF_CGROUP_INET4_GETPEERNAME:
19323 		case BPF_CGROUP_INET6_GETPEERNAME:
19324 		case BPF_CGROUP_UNIX_GETPEERNAME:
19325 		case BPF_CGROUP_INET4_GETSOCKNAME:
19326 		case BPF_CGROUP_INET6_GETSOCKNAME:
19327 		case BPF_CGROUP_UNIX_GETSOCKNAME:
19328 			*range = retval_range(1, 1);
19329 			break;
19330 		case BPF_CGROUP_INET4_BIND:
19331 		case BPF_CGROUP_INET6_BIND:
19332 			*range = retval_range(0, 3);
19333 			break;
19334 		default:
19335 			break;
19336 		}
19337 		break;
19338 	case BPF_PROG_TYPE_CGROUP_SKB:
19339 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
19340 			*range = retval_range(0, 3);
19341 		break;
19342 	case BPF_PROG_TYPE_CGROUP_SOCK:
19343 	case BPF_PROG_TYPE_SOCK_OPS:
19344 	case BPF_PROG_TYPE_CGROUP_DEVICE:
19345 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
19346 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
19347 		break;
19348 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
19349 		if (!env->prog->aux->attach_btf_id)
19350 			return false;
19351 		*range = retval_range(0, 0);
19352 		break;
19353 	case BPF_PROG_TYPE_TRACING:
19354 		switch (env->prog->expected_attach_type) {
19355 		case BPF_TRACE_FENTRY:
19356 		case BPF_TRACE_FEXIT:
19357 		case BPF_TRACE_FSESSION:
19358 		case BPF_TRACE_FENTRY_MULTI:
19359 		case BPF_TRACE_FEXIT_MULTI:
19360 		case BPF_TRACE_FSESSION_MULTI:
19361 			*range = retval_range(0, 0);
19362 			break;
19363 		case BPF_TRACE_RAW_TP:
19364 		case BPF_MODIFY_RETURN:
19365 			return false;
19366 		case BPF_TRACE_ITER:
19367 		default:
19368 			break;
19369 		}
19370 		break;
19371 	case BPF_PROG_TYPE_KPROBE:
19372 		switch (env->prog->expected_attach_type) {
19373 		case BPF_TRACE_KPROBE_SESSION:
19374 		case BPF_TRACE_UPROBE_SESSION:
19375 			break;
19376 		default:
19377 			return false;
19378 		}
19379 		break;
19380 	case BPF_PROG_TYPE_SK_LOOKUP:
19381 		*range = retval_range(SK_DROP, SK_PASS);
19382 		break;
19383 
19384 	case BPF_PROG_TYPE_LSM:
19385 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
19386 			/* no range found, any return value is allowed */
19387 			if (!get_func_retval_range(env->prog, range))
19388 				return false;
19389 			/* no restricted range, any return value is allowed */
19390 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
19391 				return false;
19392 			range->return_32bit = true;
19393 		} else if (!env->prog->aux->attach_func_proto->type) {
19394 			/* Make sure programs that attach to void
19395 			 * hooks don't try to modify return value.
19396 			 */
19397 			*range = retval_range(1, 1);
19398 		}
19399 		break;
19400 
19401 	case BPF_PROG_TYPE_NETFILTER:
19402 		*range = retval_range(NF_DROP, NF_ACCEPT);
19403 		break;
19404 	case BPF_PROG_TYPE_STRUCT_OPS:
19405 		*range = retval_range(0, 0);
19406 		break;
19407 	case BPF_PROG_TYPE_EXT:
19408 		/* freplace program can return anything as its return value
19409 		 * depends on the to-be-replaced kernel func or bpf program.
19410 		 */
19411 	default:
19412 		return false;
19413 	}
19414 
19415 	/* Continue calculating. */
19416 
19417 	return true;
19418 }
19419 
19420 static bool program_returns_void(struct bpf_verifier_env *env)
19421 {
19422 	const struct bpf_prog *prog = env->prog;
19423 	enum bpf_prog_type prog_type = prog->type;
19424 
19425 	switch (prog_type) {
19426 	case BPF_PROG_TYPE_LSM:
19427 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
19428 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
19429 		    !prog->aux->attach_func_proto->type)
19430 			return true;
19431 		break;
19432 	case BPF_PROG_TYPE_STRUCT_OPS:
19433 		if (!prog->aux->attach_func_proto->type)
19434 			return true;
19435 		break;
19436 	case BPF_PROG_TYPE_EXT:
19437 		/*
19438 		 * If the actual program is an extension, let it
19439 		 * return void - attaching will succeed only if the
19440 		 * program being replaced also returns void, and since
19441 		 * it has passed verification its actual type doesn't matter.
19442 		 */
19443 		if (subprog_returns_void(env, 0))
19444 			return true;
19445 		break;
19446 	default:
19447 		break;
19448 	}
19449 	return false;
19450 }
19451 
19452 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
19453 {
19454 	const char *exit_ctx = "At program exit";
19455 	struct tnum enforce_attach_type_range = tnum_unknown;
19456 	const struct bpf_prog *prog = env->prog;
19457 	struct bpf_reg_state *reg = reg_state(env, regno);
19458 	struct bpf_retval_range range = retval_range(0, 1);
19459 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
19460 	struct bpf_func_state *frame = env->cur_state->frame[0];
19461 	const struct btf_type *reg_type, *ret_type = NULL;
19462 	int err;
19463 
19464 	/* LSM and struct_ops func-ptr's return type could be "void" */
19465 	if (!frame->in_async_callback_fn && program_returns_void(env))
19466 		return 0;
19467 
19468 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
19469 		/* Allow a struct_ops program to return a referenced kptr if it
19470 		 * matches the operator's return type and is in its unmodified
19471 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
19472 		 */
19473 		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
19474 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
19475 						prog->aux->attach_func_proto->type,
19476 						NULL);
19477 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
19478 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
19479 	}
19480 
19481 	/* eBPF calling convention is such that R0 is used
19482 	 * to return the value from eBPF program.
19483 	 * Make sure that it's readable at this time
19484 	 * of bpf_exit, which means that program wrote
19485 	 * something into it earlier
19486 	 */
19487 	err = check_reg_arg(env, regno, SRC_OP);
19488 	if (err)
19489 		return err;
19490 
19491 	if (is_pointer_value(env, regno)) {
19492 		verbose(env, "R%d leaks addr as return value\n", regno);
19493 		return -EACCES;
19494 	}
19495 
19496 	if (frame->in_async_callback_fn) {
19497 		exit_ctx = "At async callback return";
19498 		range = frame->callback_ret_range;
19499 		goto enforce_retval;
19500 	}
19501 
19502 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
19503 		return 0;
19504 
19505 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
19506 		enforce_attach_type_range = tnum_range(2, 3);
19507 
19508 	if (!return_retval_range(env, &range))
19509 		return 0;
19510 
19511 enforce_retval:
19512 	if (reg->type != SCALAR_VALUE) {
19513 		verbose(env, "%s the register R%d is not a known value (%s)\n",
19514 			exit_ctx, regno, reg_type_str(env, reg->type));
19515 		return -EINVAL;
19516 	}
19517 
19518 	err = mark_chain_precision(env, regno);
19519 	if (err)
19520 		return err;
19521 
19522 	if (!retval_range_within(range, reg)) {
19523 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
19524 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
19525 		    prog_type == BPF_PROG_TYPE_LSM &&
19526 		    !prog->aux->attach_func_proto->type)
19527 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
19528 		return -EINVAL;
19529 	}
19530 
19531 	if (!tnum_is_unknown(enforce_attach_type_range) &&
19532 	    tnum_in(enforce_attach_type_range, reg->var_off))
19533 		env->prog->enforce_expected_attach_type = 1;
19534 	return 0;
19535 }
19536 
19537 static int check_global_ret_scalar_reg(struct bpf_verifier_env *env, u32 regno)
19538 {
19539 	struct bpf_reg_state *reg;
19540 	int err;
19541 
19542 	err = check_reg_arg(env, regno, SRC_OP);
19543 	if (err)
19544 		return err;
19545 
19546 	/* Pointers to arena are safe to pass between subprograms. */
19547 	if (is_arena_reg(env, regno))
19548 		return 0;
19549 
19550 	if (is_pointer_value(env, regno)) {
19551 		verbose(env, "R%d leaks addr as return value\n", regno);
19552 		return -EACCES;
19553 	}
19554 
19555 	reg = reg_state(env, regno);
19556 	if (reg->type != SCALAR_VALUE) {
19557 		verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
19558 			regno, reg_type_str(env, reg->type));
19559 		return -EINVAL;
19560 	}
19561 
19562 	return 0;
19563 }
19564 
19565 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
19566 {
19567 	struct bpf_func_state *cur_frame = cur_func(env);
19568 	u32 subprog = cur_frame->subprogno;
19569 	u32 i, nregs;
19570 	int err;
19571 
19572 	if (subprog_returns_void(env, subprog))
19573 		return 0;
19574 
19575 	nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
19576 	for (i = 0; i < nregs; i++) {
19577 		err = check_global_ret_scalar_reg(env, ret_regs[i]);
19578 		if (err)
19579 			return err;
19580 	}
19581 
19582 	return 0;
19583 }
19584 
19585 /* Bitmask with 1s for all caller saved registers */
19586 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
19587 
19588 /* True if do_misc_fixups() replaces calls to helper number 'imm',
19589  * replacement patch is presumed to follow bpf_fastcall contract
19590  * (see mark_fastcall_pattern_for_call() below).
19591  */
19592 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
19593 {
19594 	switch (imm) {
19595 #ifdef CONFIG_X86_64
19596 	case BPF_FUNC_get_smp_processor_id:
19597 #ifdef CONFIG_SMP
19598 	case BPF_FUNC_get_current_task_btf:
19599 	case BPF_FUNC_get_current_task:
19600 #endif
19601 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
19602 #endif
19603 	default:
19604 		return false;
19605 	}
19606 }
19607 
19608 /* If @call is a kfunc or helper call, fills @cs and returns true,
19609  * otherwise returns false.
19610  */
19611 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
19612 			  struct bpf_call_summary *cs)
19613 {
19614 	struct bpf_call_arg_meta meta;
19615 	const struct bpf_func_proto *fn;
19616 	int i;
19617 
19618 	if (bpf_helper_call(call)) {
19619 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
19620 			/* error would be reported later */
19621 			return false;
19622 		cs->fastcall = fn->allow_fastcall &&
19623 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
19624 				bpf_jit_inlines_helper_call(call->imm));
19625 		cs->is_void = fn->ret_type == RET_VOID;
19626 		cs->arg_slot_cnt = 0;
19627 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
19628 			if (fn->arg_type[i] == ARG_UNUSED)
19629 				break;
19630 			cs->arg_slot_cnt++;
19631 		}
19632 		return true;
19633 	}
19634 
19635 	if (bpf_pseudo_kfunc_call(call)) {
19636 		int err;
19637 
19638 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
19639 		if (err < 0)
19640 			/* error would be reported later */
19641 			return false;
19642 		cs->arg_slot_cnt = btf_proto_slots(meta.btf, meta.func_proto);
19643 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
19644 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
19645 		return true;
19646 	}
19647 
19648 	return false;
19649 }
19650 
19651 /* LLVM define a bpf_fastcall function attribute.
19652  * This attribute means that function scratches only some of
19653  * the caller saved registers defined by ABI.
19654  * For BPF the set of such registers could be defined as follows:
19655  * - R0 is scratched only if function is non-void;
19656  * - R1-R5 are scratched only if corresponding parameter type is defined
19657  *   in the function prototype.
19658  *
19659  * The contract between kernel and clang allows to simultaneously use
19660  * such functions and maintain backwards compatibility with old
19661  * kernels that don't understand bpf_fastcall calls:
19662  *
19663  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
19664  *   registers are not scratched by the call;
19665  *
19666  * - as a post-processing step, clang visits each bpf_fastcall call and adds
19667  *   spill/fill for every live r0-r5;
19668  *
19669  * - stack offsets used for the spill/fill are allocated as lowest
19670  *   stack offsets in whole function and are not used for any other
19671  *   purposes;
19672  *
19673  * - when kernel loads a program, it looks for such patterns
19674  *   (bpf_fastcall function surrounded by spills/fills) and checks if
19675  *   spill/fill stack offsets are used exclusively in fastcall patterns;
19676  *
19677  * - if so, and if verifier or current JIT inlines the call to the
19678  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
19679  *   spill/fill pairs;
19680  *
19681  * - when old kernel loads a program, presence of spill/fill pairs
19682  *   keeps BPF program valid, albeit slightly less efficient.
19683  *
19684  * For example:
19685  *
19686  *   r1 = 1;
19687  *   r2 = 2;
19688  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19689  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
19690  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19691  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
19692  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
19693  *   r0 = r1;                            exit;
19694  *   r0 += r2;
19695  *   exit;
19696  *
19697  * The purpose of mark_fastcall_pattern_for_call is to:
19698  * - look for such patterns;
19699  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
19700  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
19701  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
19702  *   at which bpf_fastcall spill/fill stack slots start;
19703  * - update env->subprog_info[*]->keep_fastcall_stack.
19704  *
19705  * The .fastcall_pattern and .fastcall_stack_off are used by
19706  * check_fastcall_stack_contract() to check if every stack access to
19707  * fastcall spill/fill stack slot originates from spill/fill
19708  * instructions, members of fastcall patterns.
19709  *
19710  * If such condition holds true for a subprogram, fastcall patterns could
19711  * be rewritten by remove_fastcall_spills_fills().
19712  * Otherwise bpf_fastcall patterns are not changed in the subprogram
19713  * (code, presumably, generated by an older clang version).
19714  *
19715  * For example, it is *not* safe to remove spill/fill below:
19716  *
19717  *   r1 = 1;
19718  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
19719  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
19720  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
19721  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
19722  *   r0 += r1;                           exit;
19723  *   exit;
19724  *
19725  * Both uses of the marks assume that a pattern is entered at its first
19726  * spill and thus executes as a unit, hence a pattern is not grown past
19727  * an instruction targeted by a jump.
19728  */
19729 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
19730 					   struct bpf_subprog_info *subprog,
19731 					   int insn_idx, s16 lowest_off)
19732 {
19733 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
19734 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
19735 	u32 clobbered_regs_mask;
19736 	struct bpf_call_summary cs;
19737 	u32 expected_regs_mask;
19738 	s16 off;
19739 	int i;
19740 
19741 	if (!bpf_get_call_summary(env, call, &cs))
19742 		return;
19743 
19744 	/* A bitmask specifying which caller saved registers are clobbered
19745 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
19746 	 * bpf_fastcall contract:
19747 	 * - includes R0 if function is non-void;
19748 	 * - includes R1-R5 if corresponding parameter has is described
19749 	 *   in the function prototype.
19750 	 */
19751 	clobbered_regs_mask = GENMASK(cs.arg_slot_cnt, cs.is_void ? 1 : 0);
19752 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
19753 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
19754 
19755 	/* match pairs of form:
19756 	 *
19757 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
19758 	 * ...
19759 	 * call %[to_be_inlined]
19760 	 * ...
19761 	 * rX = *(u64 *)(r10 - Y)
19762 	 */
19763 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
19764 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
19765 			break;
19766 		/* stx/ldx/call must not be a jump targets, a jump to the first stx is fine */
19767 		if (bpf_is_jump_target(env, insn_idx - i + 1) ||
19768 		    bpf_is_jump_target(env, insn_idx + i))
19769 			break;
19770 		stx = &insns[insn_idx - i];
19771 		ldx = &insns[insn_idx + i];
19772 		/* must be a stack spill/fill pair */
19773 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19774 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
19775 		    stx->dst_reg != BPF_REG_10 ||
19776 		    ldx->src_reg != BPF_REG_10)
19777 			break;
19778 		/* must be a spill/fill for the same reg */
19779 		if (stx->src_reg != ldx->dst_reg)
19780 			break;
19781 		/* must be one of the previously unseen registers */
19782 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
19783 			break;
19784 		/* must be a spill/fill for the same expected offset,
19785 		 * no need to check offset alignment, BPF_DW stack access
19786 		 * is always 8-byte aligned.
19787 		 */
19788 		if (stx->off != off || ldx->off != off)
19789 			break;
19790 		expected_regs_mask &= ~BIT(stx->src_reg);
19791 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
19792 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
19793 	}
19794 	if (i == 1)
19795 		return;
19796 
19797 	/* Conditionally set 'fastcall_spills_num' to allow forward
19798 	 * compatibility when more helper functions are marked as
19799 	 * bpf_fastcall at compile time than current kernel supports, e.g:
19800 	 *
19801 	 *   1: *(u64 *)(r10 - 8) = r1
19802 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
19803 	 *   3: r1 = *(u64 *)(r10 - 8)
19804 	 *   4: *(u64 *)(r10 - 8) = r1
19805 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
19806 	 *   6: r1 = *(u64 *)(r10 - 8)
19807 	 *
19808 	 * There is no need to block bpf_fastcall rewrite for such program.
19809 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
19810 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
19811 	 * does not remove spill/fill pair {4,6}.
19812 	 */
19813 	if (cs.fastcall)
19814 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
19815 	else
19816 		subprog->keep_fastcall_stack = 1;
19817 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
19818 }
19819 
19820 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
19821 {
19822 	struct bpf_subprog_info *subprog = env->subprog_info;
19823 	struct bpf_insn *insn;
19824 	s16 lowest_off;
19825 	int s, i;
19826 
19827 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
19828 		/* find lowest stack spill offset used in this subprog */
19829 		lowest_off = 0;
19830 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19831 			insn = env->prog->insnsi + i;
19832 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
19833 			    insn->dst_reg != BPF_REG_10)
19834 				continue;
19835 			lowest_off = min(lowest_off, insn->off);
19836 		}
19837 		/* use this offset to find fastcall patterns */
19838 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
19839 			insn = env->prog->insnsi + i;
19840 			if (insn->code != (BPF_JMP | BPF_CALL))
19841 				continue;
19842 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
19843 		}
19844 	}
19845 	return 0;
19846 }
19847 
19848 static void adjust_btf_func(struct bpf_verifier_env *env)
19849 {
19850 	struct bpf_prog_aux *aux = env->prog->aux;
19851 	int i;
19852 
19853 	if (!aux->func_info)
19854 		return;
19855 
19856 	/* func_info is not available for hidden subprogs */
19857 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
19858 		aux->func_info[i].insn_off = env->subprog_info[i].start;
19859 }
19860 
19861 /* Find id in idset and increment its count, or add new entry */
19862 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
19863 {
19864 	u32 i;
19865 
19866 	for (i = 0; i < idset->num_ids; i++) {
19867 		if (idset->entries[i].id == id) {
19868 			idset->entries[i].cnt++;
19869 			return;
19870 		}
19871 	}
19872 	/* New id */
19873 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
19874 		idset->entries[idset->num_ids].id = id;
19875 		idset->entries[idset->num_ids].cnt = 1;
19876 		idset->num_ids++;
19877 	}
19878 }
19879 
19880 /* Find id in idset and return its count, or 0 if not found */
19881 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
19882 {
19883 	u32 i;
19884 
19885 	for (i = 0; i < idset->num_ids; i++) {
19886 		if (idset->entries[i].id == id)
19887 			return idset->entries[i].cnt;
19888 	}
19889 	return 0;
19890 }
19891 
19892 /*
19893  * Clear singular scalar ids in a state.
19894  * A register with a non-zero id is called singular if no other register shares
19895  * the same base id. Such registers can be treated as independent (id=0).
19896  */
19897 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
19898 			    struct bpf_verifier_state *st)
19899 {
19900 	struct bpf_idset *idset = &env->idset_scratch;
19901 	struct bpf_func_state *func;
19902 	struct bpf_reg_state *reg;
19903 
19904 	idset->num_ids = 0;
19905 
19906 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19907 		if (reg->type != SCALAR_VALUE)
19908 			continue;
19909 		if (!reg->id)
19910 			continue;
19911 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
19912 	}));
19913 
19914 	bpf_for_each_reg_in_vstate(st, func, reg, ({
19915 		if (reg->type != SCALAR_VALUE)
19916 			continue;
19917 		if (!reg->id)
19918 			continue;
19919 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
19920 			clear_scalar_id(reg);
19921 	}));
19922 }
19923 
19924 /* Return true if it's OK to have the same insn return a different type. */
19925 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19926 {
19927 	switch (base_type(type)) {
19928 	case PTR_TO_CTX:
19929 	case PTR_TO_SOCKET:
19930 	case PTR_TO_SOCK_COMMON:
19931 	case PTR_TO_TCP_SOCK:
19932 	case PTR_TO_XDP_SOCK:
19933 	case PTR_TO_BTF_ID:
19934 	case PTR_TO_ARENA:
19935 		return false;
19936 	case PTR_TO_MEM:
19937 		return !bpf_may_fault_on_deref(type);
19938 	default:
19939 		return true;
19940 	}
19941 }
19942 
19943 /* If an instruction was previously used with particular pointer types, then we
19944  * need to be careful to avoid cases such as the below, where it may be ok
19945  * for one branch accessing the pointer, but not ok for the other branch:
19946  *
19947  * R1 = sock_ptr
19948  * goto X;
19949  * ...
19950  * R1 = some_other_valid_ptr;
19951  * goto X;
19952  * ...
19953  * R2 = *(u32 *)(R1 + 0);
19954  */
19955 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19956 {
19957 	return src != prev && (!reg_type_mismatch_ok(src) ||
19958 			       !reg_type_mismatch_ok(prev));
19959 }
19960 
19961 static bool is_ptr_to_mem(enum bpf_reg_type type)
19962 {
19963 	return base_type(type) == PTR_TO_MEM;
19964 }
19965 
19966 static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a,
19967 					 enum bpf_reg_type type_b)
19968 {
19969 	bool to_mem = is_ptr_to_mem(type_a) || is_ptr_to_mem(type_b);
19970 	enum bpf_reg_type type_merged = to_mem ? PTR_TO_MEM : PTR_TO_BTF_ID;
19971 
19972 	if (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b))
19973 		type_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED :
19974 					PTR_UNTRUSTED;
19975 	else
19976 		type_merged |= ((type_a | type_b) & MEM_RDONLY);
19977 	return type_merged;
19978 }
19979 
19980 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19981 			     bool allow_trust_mismatch)
19982 {
19983 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19984 
19985 	if (*prev_type == NOT_INIT) {
19986 		/* Saw a valid insn
19987 		 * dst_reg = *(u32 *)(src_reg + off)
19988 		 * save type to validate intersecting paths
19989 		 */
19990 		*prev_type = type;
19991 	} else if (reg_type_mismatch(type, *prev_type)) {
19992 		/* Abuser program is trying to use the same insn
19993 		 * dst_reg = *(u32*) (src_reg + off)
19994 		 * with different pointer types:
19995 		 * src_reg == ctx in one branch and
19996 		 * src_reg == stack|map in some other branch.
19997 		 * Reject it.
19998 		 */
19999 		if (allow_trust_mismatch &&
20000 		    bpf_is_ptr_to_mem_or_btf_id(type) &&
20001 		    bpf_is_ptr_to_mem_or_btf_id(*prev_type)) {
20002 			/*
20003 			 * Have to support a use case when one path through
20004 			 * the program yields a TRUSTED pointer while another
20005 			 * is UNTRUSTED. Merge them into a type which keeps
20006 			 * the BPF_PROBE_MEM/BPF_PROBE_MEMSX rewrite when
20007 			 * either side needs it.
20008 			 */
20009 			*prev_type = merge_ptr_types(type, *prev_type);
20010 		} else {
20011 			verbose(env, "same insn cannot be used with different pointers\n");
20012 			return -EINVAL;
20013 		}
20014 	}
20015 
20016 	return 0;
20017 }
20018 
20019 enum {
20020 	PROCESS_BPF_EXIT = 1,
20021 	INSN_IDX_UPDATED = 2,
20022 };
20023 
20024 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20025 				 bool *do_print_state,
20026 				 bool exception_exit)
20027 {
20028 	struct bpf_func_state *cur_frame = cur_func(env);
20029 
20030 	/* We must do check_reference_leak here before
20031 	 * prepare_func_exit to handle the case when
20032 	 * state->curframe > 0, it may be a callback function,
20033 	 * for which reference_state must match caller reference
20034 	 * state when it exits.
20035 	 */
20036 	int err = check_resource_leak(env, exception_exit,
20037 				      exception_exit || !env->cur_state->curframe,
20038 				      exception_exit ? "bpf_throw" :
20039 				      "BPF_EXIT instruction in main prog");
20040 	if (err)
20041 		return err;
20042 
20043 	/* The side effect of the prepare_func_exit which is
20044 	 * being skipped is that it frees bpf_func_state.
20045 	 * Typically, process_bpf_exit will only be hit with
20046 	 * outermost exit. copy_verifier_state in pop_stack will
20047 	 * handle freeing of any extra bpf_func_state left over
20048 	 * from not processing all nested function exits. We
20049 	 * also skip return code checks as they are not needed
20050 	 * for exceptional exits.
20051 	 */
20052 	if (exception_exit)
20053 		return PROCESS_BPF_EXIT;
20054 
20055 	if (env->cur_state->curframe) {
20056 		/* exit from nested function */
20057 		err = prepare_func_exit(env, &env->insn_idx);
20058 		if (err)
20059 			return err;
20060 		*do_print_state = true;
20061 		return INSN_IDX_UPDATED;
20062 	}
20063 
20064 	/*
20065 	 * Return from a regular global subprogram differs from return
20066 	 * from the main program or async/exception callback.
20067 	 * Main program exit implies return code restrictions
20068 	 * that depend on program type.
20069 	 * Exit from exception callback is equivalent to main program exit.
20070 	 * Exit from async callback implies return code restrictions
20071 	 * that depend on async scheduling mechanism.
20072 	 */
20073 	if (cur_frame->subprogno &&
20074 	    !cur_frame->in_async_callback_fn &&
20075 	    !cur_frame->in_exception_callback_fn)
20076 		err = check_global_subprog_return_code(env);
20077 	else
20078 		err = check_return_code(env, BPF_REG_0, "R0");
20079 	if (err)
20080 		return err;
20081 	return PROCESS_BPF_EXIT;
20082 }
20083 
20084 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20085 				       int regno,
20086 				       struct bpf_map *map,
20087 				       u32 *pmin_index, u32 *pmax_index)
20088 {
20089 	struct bpf_reg_state *reg = reg_state(env, regno);
20090 	u64 min_index = reg_umin(reg);
20091 	u64 max_index = reg_umax(reg);
20092 	const u32 size = 8;
20093 
20094 	if (min_index > (u64) U32_MAX * size) {
20095 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
20096 		return -ERANGE;
20097 	}
20098 	if (max_index > (u64) U32_MAX * size) {
20099 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
20100 		return -ERANGE;
20101 	}
20102 
20103 	min_index /= size;
20104 	max_index /= size;
20105 
20106 	if (max_index >= map->max_entries) {
20107 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20108 			     regno, min_index, max_index, map->max_entries);
20109 		return -EINVAL;
20110 	}
20111 
20112 	*pmin_index = min_index;
20113 	*pmax_index = max_index;
20114 	return 0;
20115 }
20116 
20117 static int reject_gotox_out_of_subprog(struct bpf_verifier_env *env, u32 target,
20118 				       u32 subprog_start, u32 subprog_end)
20119 {
20120 	verbose(env, "indirect jump from insn %d to %u leaves the subprog [%u,%u)\n",
20121 		env->insn_idx, target, subprog_start, subprog_end);
20122 	bpf_diag_program_structure(
20123 		env, env->insn_idx, "indirect jump leaves subprogram",
20124 		"Keep every reachable jump-table target inside the subprogram of the indirect jump.",
20125 		"Instruction %d can jump indirectly to instruction %u, which is outside its own subprogram [%u,%u).",
20126 		env->insn_idx, target, subprog_start, subprog_end);
20127 	return -EINVAL;
20128 }
20129 
20130 /* gotox *dst_reg */
20131 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20132 {
20133 	struct bpf_verifier_state *other_branch;
20134 	struct bpf_subprog_info *subprog;
20135 	u32 subprog_start, subprog_end;
20136 	struct bpf_reg_state *dst_reg;
20137 	struct bpf_map *map;
20138 	u32 min_index, max_index;
20139 	int err = 0;
20140 	int n;
20141 	int i;
20142 
20143 	dst_reg = reg_state(env, insn->dst_reg);
20144 	if (dst_reg->type != PTR_TO_INSN) {
20145 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20146 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
20147 		return -EINVAL;
20148 	}
20149 
20150 	map = dst_reg->map_ptr;
20151 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20152 		return -EFAULT;
20153 
20154 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20155 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20156 		return -EFAULT;
20157 
20158 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20159 	if (err)
20160 		return err;
20161 
20162 	/* Ensure that the buffer is large enough */
20163 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20164 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
20165 						        max_index - min_index + 1);
20166 		if (!env->gotox_tmp_buf)
20167 			return -ENOMEM;
20168 	}
20169 
20170 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20171 	if (n < 0)
20172 		return n;
20173 	if (n == 0) {
20174 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20175 			     insn->dst_reg, map->id);
20176 		return -EINVAL;
20177 	}
20178 
20179 	subprog = bpf_find_containing_subprog(env, env->insn_idx);
20180 	if (verifier_bug_if(!subprog, env, "no subprog contains insn %d", env->insn_idx))
20181 		return -EFAULT;
20182 	subprog_start = subprog->start;
20183 	subprog_end = (subprog + 1)->start;
20184 
20185 	/*
20186 	 * Maps are confined to a subprog, see compute_subprog_jts(), and the
20187 	 * targets are sorted and free of duplicates, see sort_insn_array_uniq(),
20188 	 * so either all of them belong to this subprog or none of them does.
20189 	 */
20190 	if (env->gotox_tmp_buf->items[0] < subprog_start)
20191 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[0],
20192 						   subprog_start, subprog_end);
20193 	if (env->gotox_tmp_buf->items[n - 1] >= subprog_end)
20194 		return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[n - 1],
20195 						   subprog_start, subprog_end);
20196 
20197 	for (i = 0; i < n - 1; i++) {
20198 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
20199 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20200 					  env->insn_idx, env->cur_state->speculative);
20201 		if (IS_ERR(other_branch))
20202 			return PTR_ERR(other_branch);
20203 	}
20204 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
20205 	mark_indirect_target(env, env->insn_idx);
20206 	return INSN_IDX_UPDATED;
20207 }
20208 
20209 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20210 {
20211 	int err;
20212 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20213 	u8 class = BPF_CLASS(insn->code);
20214 
20215 	switch (class) {
20216 	case BPF_ALU:
20217 	case BPF_ALU64:
20218 		return check_alu_op(env, insn);
20219 
20220 	case BPF_LDX:
20221 		return check_load_mem(env, insn, false,
20222 				      BPF_MODE(insn->code) == BPF_MEMSX,
20223 				      true, "ldx");
20224 
20225 	case BPF_STX:
20226 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
20227 			return check_atomic(env, insn);
20228 		return check_store_reg(env, insn, false);
20229 
20230 	case BPF_ST: {
20231 		/* Handle stack arg write (store immediate) */
20232 		if (is_stack_arg_st(insn)) {
20233 			struct bpf_verifier_state *vstate = env->cur_state;
20234 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
20235 
20236 			return check_stack_arg_write(env, state, insn->off, NULL);
20237 		}
20238 
20239 		struct bpf_reg_state arena, *dst_reg;
20240 		enum bpf_reg_type dst_reg_type;
20241 
20242 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20243 		if (err)
20244 			return err;
20245 
20246 		dst_reg = mem_access_reg(env, insn->dst_reg, &arena);
20247 		dst_reg_type = dst_reg->type;
20248 
20249 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
20250 				       insn->off, BPF_SIZE(insn->code),
20251 				       BPF_WRITE, -1, false, false);
20252 		if (err)
20253 			return err;
20254 
20255 		return save_aux_ptr_type(env, dst_reg_type, false);
20256 	}
20257 	case BPF_JMP:
20258 	case BPF_JMP32: {
20259 		u8 opcode = BPF_OP(insn->code);
20260 
20261 		env->jmps_processed++;
20262 		if (opcode == BPF_CALL) {
20263 			if (env->cur_state->active_locks) {
20264 				/* similar to static subprog calls callx is allowed under a lock */
20265 				if (!bpf_is_callx(insn) &&
20266 				    ((insn->src_reg == BPF_REG_0 &&
20267 				      insn->imm != BPF_FUNC_spin_unlock &&
20268 				      insn->imm != BPF_FUNC_kptr_xchg) ||
20269 				     (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20270 				      !kfunc_spin_allowed(env, insn->imm, insn->off)))) {
20271 					verbose(env,
20272 						"function calls are not allowed while holding a lock\n");
20273 					bpf_diag_ctx_active(
20274 						env, env->insn_idx,
20275 						"function call", BPF_DIAG_CONTEXT_LOCK,
20276 						"Release the BPF spin lock before making this call, or move the call outside the locked region.");
20277 					return -EINVAL;
20278 				}
20279 			}
20280 			mark_reg_scratched(env, BPF_REG_0);
20281 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
20282 				cur_func(env)->no_stack_arg_load = true;
20283 			if (bpf_is_callx(insn))
20284 				return check_func_callx(env, insn, &env->insn_idx);
20285 			if (insn->src_reg == BPF_PSEUDO_CALL)
20286 				return check_func_call(env, insn, &env->insn_idx);
20287 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
20288 				return check_kfunc_call(env, insn, &env->insn_idx);
20289 			return check_helper_call(env, insn, &env->insn_idx);
20290 		} else if (opcode == BPF_JA) {
20291 			if (BPF_SRC(insn->code) == BPF_X)
20292 				return check_indirect_jump(env, insn);
20293 
20294 			if (class == BPF_JMP)
20295 				env->insn_idx += insn->off + 1;
20296 			else
20297 				env->insn_idx += insn->imm + 1;
20298 			return INSN_IDX_UPDATED;
20299 		} else if (opcode == BPF_EXIT) {
20300 			return process_bpf_exit_full(env, do_print_state, false);
20301 		}
20302 		return check_cond_jmp_op(env, insn, &env->insn_idx);
20303 	}
20304 	case BPF_LD: {
20305 		u8 mode = BPF_MODE(insn->code);
20306 
20307 		if (mode == BPF_ABS || mode == BPF_IND)
20308 			return check_ld_abs(env, insn);
20309 
20310 		if (mode == BPF_IMM) {
20311 			err = check_ld_imm(env, insn);
20312 			if (err)
20313 				return err;
20314 
20315 			env->insn_idx++;
20316 			sanitize_mark_insn_seen(env);
20317 		}
20318 		return 0;
20319 	}
20320 	}
20321 	/* all class values are handled above. silence compiler warning */
20322 	return -EFAULT;
20323 }
20324 
20325 /*
20326  * Push the loop entered at insn_idx onto the stack. Usually this adds a single
20327  * entry on top of its enclosing loop. However, an edge may enter an inner loop
20328  * directly, bypassing the header(s) of its enclosing loop(s), e.g.:
20329  *
20330  *   1: for (...):       // enclosing loop, header at 1
20331  *   2:   for (...):     // inner loop, header at 2
20332  *        ...
20333  *   3: if ...:
20334  *        goto 2b;       // enters loop 2 without going through header 1
20335  *
20336  * Such a bypass makes the enclosing loop irreducible, so its header is missing
20337  * from the stack and both headers (1) and (2) need to be pushed onto stack.
20338  * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
20339  * the bypassed ancestors are irreducible and pushed as non-terminating.
20340  *
20341  * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
20342  * of the bpf_loop_at_index(env->insn_idx) and whatever was at the top of the loop stack.
20343  */
20344 static int loop_stack_push(struct bpf_verifier_env *env, bool *pushed)
20345 {
20346 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20347 	struct bpf_func_state *frame = cur_func(env);
20348 	struct loop_stack_entry *loop_stack = frame->loop_stack;
20349 	u32 missing_headers[LOOP_STACK_SIZE];
20350 	u32 cnt = frame->loop_stack_cnt;
20351 	u32 num_missing = 0;
20352 	int h;
20353 
20354 	*pushed = false;
20355 
20356 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
20357 		if (cnt && loop_stack[cnt - 1].loop_id == h)
20358 			break;
20359 		if (num_missing == LOOP_STACK_SIZE)
20360 			goto e2big;
20361 		missing_headers[num_missing] = h;
20362 	}
20363 
20364 	if (num_missing == 0)
20365 		return 0;
20366 	if (cnt + num_missing > LOOP_STACK_SIZE)
20367 		goto e2big;
20368 	frame->loop_stack = realloc_array(frame->loop_stack, cnt, cnt + num_missing,
20369 					 sizeof(*frame->loop_stack));
20370 	if (!frame->loop_stack)
20371 		return -ENOMEM;
20372 	loop_stack = frame->loop_stack;
20373 
20374 	for (; num_missing; num_missing--, cnt++) {
20375 		h = missing_headers[num_missing - 1];
20376 		loop_stack[cnt] = (struct loop_stack_entry){ .loop_id = h };
20377 		if (env->log.level & BPF_LOG_LEVEL2)
20378 			verbose(env, "entering loop %d\n", h);
20379 		*pushed = true;
20380 	}
20381 	frame->loop_stack_cnt = cnt;
20382 	return 0;
20383 
20384 e2big:
20385 	verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
20386 	return -E2BIG;
20387 }
20388 
20389 /*
20390  * An exit from a loop can cross several nested loops, e.g.:
20391  *
20392  *   1: for (...):
20393  *   2:   for (...):
20394  *   3:     for (...):
20395  *            if ...:    // before goto the loop stack is [1, 2, 3 <top>]
20396  *              goto 1b; // after goto it should become [1]
20397  */
20398 static int loop_stack_pop(struct bpf_verifier_env *env)
20399 {
20400 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
20401 	struct bpf_func_state *frame = cur_func(env);
20402 	int new_cnt = 0;
20403 	int h, i;
20404 
20405 	/*
20406 	 * Walk the loop nest of insn_idx outwards (innermost first) and stop at
20407 	 * the first loop that is present on the stack - that loop is the common
20408 	 * ancestor and becomes the new top. If no enclosing loop is on the
20409 	 * stack, drop all loops.
20410 	 */
20411 	for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
20412 		for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
20413 			if (frame->loop_stack[i].loop_id == h) {
20414 				new_cnt = i + 1;
20415 				goto pop;
20416 			}
20417 		}
20418 	}
20419 
20420 pop:
20421 	if (env->log.level & BPF_LOG_LEVEL2)
20422 		for (i = frame->loop_stack_cnt - 1; i >= new_cnt; i--)
20423 			verbose(env, "exiting loop %d\n", frame->loop_stack[i].loop_id);
20424 	frame->loop_stack_cnt = new_cnt;
20425 	return 0;
20426 }
20427 
20428 static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
20429 {
20430 	struct bpf_func_state *frame = cur_func(env);
20431 	struct loop_stack_entry *entry;
20432 
20433 	if (frame->loop_stack_cnt == 0) {
20434 		verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
20435 		return -EFAULT;
20436 	}
20437 
20438 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20439 	if (!entry->terminates)
20440 		return 0;
20441 
20442 	return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state,
20443 				   entry->max_header_count);
20444 }
20445 
20446 static int handle_loop_entry_exit(struct bpf_verifier_env *env)
20447 {
20448 	struct bpf_verifier_state *cur = env->cur_state;
20449 	struct bpf_func_state *frame = cur_func(env);
20450 	struct loop_stack_entry *entry;
20451 	struct bpf_loop_iters iters;
20452 	bool pushed, terminates;
20453 	int err;
20454 
20455 	err = loop_stack_pop(env);
20456 	if (err)
20457 		return err;
20458 
20459 	err = loop_stack_push(env, &pushed);
20460 	if (err)
20461 		return err;
20462 
20463 	if (frame->loop_stack_cnt == 0)
20464 		return 0;
20465 
20466 	entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
20467 	if (env->insn_idx != entry->loop_id)
20468 		return 0;
20469 
20470 	/* If nothing was pushed and env->insn_idx is a loop header, we've taken a backedge. */
20471 	if (!pushed)
20472 		return maybe_clamp_scev_regs(env);
20473 
20474 	err = bpf_compute_loop_iters(env, env->cur_state, &iters);
20475 	if (err < 0)
20476 		return err;
20477 
20478 	terminates = err == 1;
20479 	if (!terminates)
20480 		return 0;
20481 
20482 	/* Create a loop_entry checkpoint before widening */
20483 	err = bpf_split_cur_state(env);
20484 	if (err)
20485 		return err;
20486 
20487 	entry->min_header_count = iters.min_header_count;
20488 	entry->max_header_count = iters.max_header_count;
20489 	entry->entry_state = cur->parent;
20490 	entry->terminates = true;
20491 	err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
20492 	if (err < 0)
20493 		return err;
20494 	return 0;
20495 }
20496 
20497 static int do_check(struct bpf_verifier_env *env)
20498 {
20499 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20500 	struct bpf_verifier_state *state = env->cur_state;
20501 	struct bpf_insn *insns = env->prog->insnsi;
20502 	int insn_cnt = env->prog->len;
20503 	bool do_print_state = false;
20504 	int prev_insn_idx = -1;
20505 
20506 	for (;;) {
20507 		struct bpf_insn *insn;
20508 		struct bpf_insn_aux_data *insn_aux;
20509 		int err;
20510 
20511 		if (signal_pending(current))
20512 			return -EAGAIN;
20513 
20514 		if (need_resched())
20515 			cond_resched();
20516 
20517 		/* reset current history entry on each new instruction */
20518 		env->cur_hist_ent = NULL;
20519 
20520 		env->prev_insn_idx = prev_insn_idx;
20521 		if (env->insn_idx >= insn_cnt) {
20522 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20523 				env->insn_idx, insn_cnt);
20524 			return -EFAULT;
20525 		}
20526 
20527 		insn = &insns[env->insn_idx];
20528 		insn_aux = &env->insn_aux_data[env->insn_idx];
20529 
20530 		account_processed_insn(env);
20531 
20532 		if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20533 			verbose(env,
20534 				"BPF program is too large. Processed %d insn\n",
20535 				env->insn_processed);
20536 			return -E2BIG;
20537 		}
20538 
20539 		state->last_insn_idx = env->prev_insn_idx;
20540 		state->insn_idx = env->insn_idx;
20541 		/*
20542 		 * Record the incoming edge so active and queued paths use the same
20543 		 * branch-recording path. A zero-offset conditional has identical
20544 		 * successors, so its outcome cannot be reconstructed from the edge.
20545 		 */
20546 		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
20547 			struct bpf_insn *prev_insn = &insns[prev_insn_idx];
20548 			int fallthrough_idx = prev_insn_idx + 1;
20549 			int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1;
20550 			u8 class = BPF_CLASS(prev_insn->code);
20551 			u8 opcode = BPF_OP(prev_insn->code);
20552 
20553 			if ((class == BPF_JMP || class == BPF_JMP32) &&
20554 			    opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT &&
20555 			    opcode <= BPF_JCOND && branch_idx != fallthrough_idx) {
20556 				if (env->insn_idx == branch_idx)
20557 					bpf_diag_record_branch(env, prev_insn_idx, true);
20558 				else if (env->insn_idx == fallthrough_idx)
20559 					bpf_diag_record_branch(env, prev_insn_idx, false);
20560 			}
20561 		}
20562 
20563 		/*
20564 		 * Possibly widen the registers before creating a checkpoint
20565 		 * in bpf_is_state_visited(). The next loop iteration will
20566 		 * have a chance to hit this checkpoint and converge.
20567 		 */
20568 		err = handle_loop_entry_exit(env);
20569 		if (err)
20570 			return err;
20571 
20572 		if (bpf_is_prune_point(env, env->insn_idx)) {
20573 			err = bpf_is_state_visited(env, env->insn_idx);
20574 			if (err < 0)
20575 				return err;
20576 			if (err == 1) {
20577 				/* found equivalent state, can prune the search */
20578 				if (env->log.level & BPF_LOG_LEVEL) {
20579 					if (do_print_state)
20580 						verbose(env, "\nfrom %d to %d%s: safe\n",
20581 							env->prev_insn_idx, env->insn_idx,
20582 							env->cur_state->speculative ?
20583 							" (speculative execution)" : "");
20584 					else
20585 						verbose(env, "%d: safe\n", env->insn_idx);
20586 				}
20587 				goto process_bpf_exit;
20588 			}
20589 		}
20590 
20591 		if (bpf_is_jmp_point(env, env->insn_idx)) {
20592 			err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0);
20593 			if (err)
20594 				return err;
20595 		}
20596 
20597 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20598 			verbose(env, "\nfrom %d to %d%s:",
20599 				env->prev_insn_idx, env->insn_idx,
20600 				env->cur_state->speculative ?
20601 				" (speculative execution)" : "");
20602 			print_verifier_state(env, state, state->curframe, true);
20603 			do_print_state = false;
20604 		}
20605 
20606 		if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
20607 		    cur_func(env)->loop_stack_cnt == 0) {
20608 			verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
20609 				     env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
20610 			return -EFAULT;
20611 		}
20612 
20613 		if (env->log.level & BPF_LOG_LEVEL) {
20614 			if (verifier_state_scratched(env))
20615 				print_insn_state(env, state, state->curframe);
20616 
20617 			verbose_linfo(env, env->insn_idx, "; ");
20618 			env->prev_log_pos = env->log.end_pos;
20619 			verbose(env, "%d: ", env->insn_idx);
20620 			bpf_verbose_insn(env, insn);
20621 			verbose(env, "\n");
20622 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20623 			env->prev_log_pos = env->log.end_pos;
20624 		}
20625 
20626 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20627 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20628 							   env->prev_insn_idx);
20629 			if (err)
20630 				return err;
20631 		}
20632 
20633 		sanitize_mark_insn_seen(env);
20634 		prev_insn_idx = env->insn_idx;
20635 
20636 		/* Sanity check: precomputed constants must match verifier state */
20637 		if (!state->speculative && insn_aux->const_reg_mask) {
20638 			struct bpf_reg_state *regs = cur_regs(env);
20639 			u16 mask = insn_aux->const_reg_mask;
20640 
20641 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
20642 				u32 cval = insn_aux->const_reg_vals[r];
20643 
20644 				if (!(mask & BIT(r)))
20645 					continue;
20646 				if (regs[r].type != SCALAR_VALUE)
20647 					continue;
20648 				if (!tnum_is_const(regs[r].var_off))
20649 					continue;
20650 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
20651 						    env, "const R%d: %u != %llu",
20652 						    r, cval, regs[r].var_off.value))
20653 					return -EFAULT;
20654 			}
20655 		}
20656 
20657 		/* Reduce verification complexity by stopping speculative path
20658 		 * verification when a nospec is encountered.
20659 		 */
20660 		if (state->speculative && insn_aux->nospec)
20661 			goto process_bpf_exit;
20662 
20663 		err = do_check_insn(env, &do_print_state);
20664 		if (error_recoverable_with_nospec(err) && state->speculative) {
20665 			/* Prevent this speculative path from ever reaching the
20666 			 * insn that would have been unsafe to execute.
20667 			 */
20668 			insn_aux->nospec = true;
20669 			/* If it was an ADD/SUB insn, potentially remove any
20670 			 * markings for alu sanitization.
20671 			 */
20672 			insn_aux->alu_state = 0;
20673 			goto process_bpf_exit;
20674 		} else if (err < 0) {
20675 			return err;
20676 		} else if (err == PROCESS_BPF_EXIT) {
20677 			goto process_bpf_exit;
20678 		} else if (err == INSN_IDX_UPDATED) {
20679 		} else if (err == 0) {
20680 			env->insn_idx++;
20681 		}
20682 
20683 		if (state->speculative && insn_aux->nospec_result) {
20684 			/* If we are on a path that performed a jump-op, this
20685 			 * may skip a nospec patched-in after the jump. This can
20686 			 * currently never happen because nospec_result is only
20687 			 * used for the write-ops
20688 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
20689 			 * calls. These must never skip the following insn
20690 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
20691 			 * is false). Still, add a warning to document this in
20692 			 * case nospec_result is used elsewhere in the future.
20693 			 *
20694 			 * All non-branch instructions have a single
20695 			 * fall-through edge. For these, nospec_result should
20696 			 * already work.
20697 			 */
20698 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
20699 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
20700 					    BPF_OP(insn->code) != BPF_CALL, env,
20701 					    "speculation barrier after jump instruction may not have the desired effect"))
20702 				return -EFAULT;
20703 process_bpf_exit:
20704 			account_current_path(env);
20705 			mark_verifier_state_scratched(env);
20706 			err = bpf_update_branch_counts(env, env->cur_state);
20707 			if (err)
20708 				return err;
20709 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20710 					pop_log);
20711 			if (err < 0) {
20712 				if (err != -ENOENT)
20713 					return err;
20714 				break;
20715 			} else {
20716 				do_print_state = true;
20717 				continue;
20718 			}
20719 		}
20720 	}
20721 
20722 	return 0;
20723 }
20724 
20725 static int find_btf_percpu_datasec(struct btf *btf)
20726 {
20727 	const struct btf_type *t;
20728 	const char *tname;
20729 	int i, n;
20730 
20731 	/*
20732 	 * Both vmlinux and module each have their own ".data..percpu"
20733 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20734 	 * types to look at only module's own BTF types.
20735 	 */
20736 	n = btf_nr_types(btf);
20737 	for (i = btf_named_start_id(btf, true); i < n; i++) {
20738 		t = btf_type_by_id(btf, i);
20739 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20740 			continue;
20741 
20742 		tname = btf_name_by_offset(btf, t->name_off);
20743 		if (!strcmp(tname, ".data..percpu"))
20744 			return i;
20745 	}
20746 
20747 	return -ENOENT;
20748 }
20749 
20750 /*
20751  * Add btf to the env->used_btfs array. If needed, refcount the
20752  * corresponding kernel module. To simplify caller's logic
20753  * in case of error or if btf was added before the function
20754  * decreases the btf refcount.
20755  */
20756 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20757 {
20758 	struct btf_mod_pair *btf_mod;
20759 	int ret = 0;
20760 	int i;
20761 
20762 	/* check whether we recorded this BTF (and maybe module) already */
20763 	for (i = 0; i < env->used_btf_cnt; i++)
20764 		if (env->used_btfs[i].btf == btf)
20765 			goto ret_put;
20766 
20767 	if (env->signature) {
20768 		verbose(env, "signed program cannot bind any BTF\n");
20769 		ret = -EACCES;
20770 		goto ret_put;
20771 	}
20772 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20773 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20774 			MAX_USED_BTFS);
20775 		ret = -E2BIG;
20776 		goto ret_put;
20777 	}
20778 
20779 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20780 	btf_mod->btf = btf;
20781 	btf_mod->module = NULL;
20782 
20783 	/* if we reference variables from kernel module, bump its refcount */
20784 	if (btf_is_module(btf)) {
20785 		btf_mod->module = btf_try_get_module(btf);
20786 		if (!btf_mod->module) {
20787 			ret = -ENXIO;
20788 			goto ret_put;
20789 		}
20790 	}
20791 
20792 	env->used_btf_cnt++;
20793 	return 0;
20794 
20795 ret_put:
20796 	/* Either error or this BTF was already added */
20797 	btf_put(btf);
20798 	return ret;
20799 }
20800 
20801 /* replace pseudo btf_id with kernel symbol address */
20802 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20803 				 struct bpf_insn *insn,
20804 				 struct bpf_insn_aux_data *aux,
20805 				 struct btf *btf)
20806 {
20807 	const struct btf_var_secinfo *vsi;
20808 	const struct btf_type *datasec;
20809 	const struct btf_type *t;
20810 	const char *sym_name;
20811 	bool percpu = false;
20812 	u32 type, id = insn->imm;
20813 	s32 datasec_id;
20814 	u64 addr;
20815 	int i;
20816 
20817 	t = btf_type_by_id(btf, id);
20818 	if (!t) {
20819 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20820 		return -ENOENT;
20821 	}
20822 
20823 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20824 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20825 		return -EINVAL;
20826 	}
20827 
20828 	sym_name = btf_name_by_offset(btf, t->name_off);
20829 	addr = kallsyms_lookup_name(sym_name);
20830 	if (!addr) {
20831 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20832 			sym_name);
20833 		return -ENOENT;
20834 	}
20835 	insn[0].imm = (u32)addr;
20836 	insn[1].imm = addr >> 32;
20837 
20838 	if (btf_type_is_func(t)) {
20839 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20840 		aux->btf_var.mem_size = 0;
20841 		return 0;
20842 	}
20843 
20844 	datasec_id = find_btf_percpu_datasec(btf);
20845 	if (datasec_id > 0) {
20846 		datasec = btf_type_by_id(btf, datasec_id);
20847 		for_each_vsi(i, datasec, vsi) {
20848 			if (vsi->type == id) {
20849 				percpu = true;
20850 				break;
20851 			}
20852 		}
20853 	}
20854 
20855 	type = t->type;
20856 	t = btf_type_skip_modifiers(btf, type, NULL);
20857 	if (percpu) {
20858 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20859 		aux->btf_var.btf = btf;
20860 		aux->btf_var.btf_id = type;
20861 	} else if (!btf_type_is_struct(t)) {
20862 		const struct btf_type *ret;
20863 		const char *tname;
20864 		u32 tsize;
20865 
20866 		/* resolve the type size of ksym. */
20867 		ret = btf_resolve_size(btf, t, &tsize);
20868 		if (IS_ERR(ret)) {
20869 			tname = btf_name_by_offset(btf, t->name_off);
20870 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20871 				tname, PTR_ERR(ret));
20872 			return -EINVAL;
20873 		}
20874 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20875 		aux->btf_var.mem_size = tsize;
20876 	} else {
20877 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20878 		aux->btf_var.btf = btf;
20879 		aux->btf_var.btf_id = type;
20880 	}
20881 
20882 	return 0;
20883 }
20884 
20885 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20886 			       struct bpf_insn *insn,
20887 			       struct bpf_insn_aux_data *aux)
20888 {
20889 	struct btf *btf;
20890 	int btf_fd;
20891 	int err;
20892 
20893 	btf_fd = insn[1].imm;
20894 	if (btf_fd) {
20895 		btf = btf_get_by_fd(btf_fd);
20896 		if (IS_ERR(btf)) {
20897 			verbose(env, "invalid module BTF object FD specified.\n");
20898 			return -EINVAL;
20899 		}
20900 	} else {
20901 		if (!btf_vmlinux) {
20902 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20903 			return -EINVAL;
20904 		}
20905 		btf_get(btf_vmlinux);
20906 		btf = btf_vmlinux;
20907 	}
20908 
20909 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20910 	if (err) {
20911 		btf_put(btf);
20912 		return err;
20913 	}
20914 
20915 	return __add_used_btf(env, btf);
20916 }
20917 
20918 static bool is_tracing_prog_type(enum bpf_prog_type type)
20919 {
20920 	switch (type) {
20921 	case BPF_PROG_TYPE_KPROBE:
20922 	case BPF_PROG_TYPE_TRACEPOINT:
20923 	case BPF_PROG_TYPE_PERF_EVENT:
20924 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20925 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20926 		return true;
20927 	default:
20928 		return false;
20929 	}
20930 }
20931 
20932 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20933 {
20934 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20935 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20936 }
20937 
20938 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20939 					struct bpf_map *map,
20940 					struct bpf_prog *prog)
20941 
20942 {
20943 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20944 
20945 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20946 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20947 		if (is_tracing_prog_type(prog_type)) {
20948 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20949 			return -EINVAL;
20950 		}
20951 	}
20952 
20953 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20954 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20955 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20956 			return -EINVAL;
20957 		}
20958 	}
20959 
20960 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
20961 		if (is_tracing_prog_type(prog_type)) {
20962 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20963 			return -EINVAL;
20964 		}
20965 	}
20966 
20967 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20968 	    !bpf_offload_prog_map_match(prog, map)) {
20969 		verbose(env, "offload device mismatch between prog and map\n");
20970 		return -EINVAL;
20971 	}
20972 
20973 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20974 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20975 		return -EINVAL;
20976 	}
20977 
20978 	if (prog->sleepable && !map_needs_no_rcu(map)) {
20979 		verbose(env,
20980 			"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20981 		return -EINVAL;
20982 	}
20983 
20984 	if (bpf_map_is_cgroup_storage(map) &&
20985 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20986 		verbose(env, "only one cgroup storage of each type is allowed\n");
20987 		return -EBUSY;
20988 	}
20989 
20990 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20991 		if (env->prog->aux->arena) {
20992 			verbose(env, "Only one arena per program\n");
20993 			return -EBUSY;
20994 		}
20995 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20996 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20997 			return -EPERM;
20998 		}
20999 		if (!env->prog->jit_requested) {
21000 			verbose(env, "JIT is required to use arena\n");
21001 			return -EOPNOTSUPP;
21002 		}
21003 		if (!bpf_jit_supports_arena()) {
21004 			verbose(env, "JIT doesn't support arena\n");
21005 			return -EOPNOTSUPP;
21006 		}
21007 		env->prog->aux->arena = (void *)map;
21008 		env->prog->jit_required = true;
21009 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
21010 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
21011 			return -EINVAL;
21012 		}
21013 	}
21014 
21015 	return 0;
21016 }
21017 
21018 /*
21019  * Keep track of whether the map is used by one program only. Such program may
21020  * store the addresses of its functions into the map when it's frozen, see
21021  * resolve_func_ptrs(), since nothing else relies on what the map has. After
21022  * that the map is not available to other programs.
21023  */
21024 static int bpf_map_claim(struct bpf_verifier_env *env, struct bpf_map *map)
21025 {
21026 	unsigned long me = (unsigned long)env->prog->aux, old;
21027 
21028 	for (;;) {
21029 		old = READ_ONCE(map->user);
21030 		if (old == me || old == BPF_MAP_USER_MANY)
21031 			return 0;
21032 		if (old & BPF_MAP_USER_PATCHED) {
21033 			verbose(env, "map '%s' has addresses of functions of another program\n",
21034 				map->name);
21035 			return -EBUSY;
21036 		}
21037 		if (cmpxchg(&map->user, old, old ? BPF_MAP_USER_MANY : me) == old)
21038 			return 0;
21039 	}
21040 }
21041 
21042 /*
21043  * An exclusive map is bound to the digest of its program. The digest covers
21044  * the insns as they are verified, after the CO-RE relocations the kernel
21045  * applies, so it exists only once check_and_resolve_insns() has computed it,
21046  * and the maps are checked against it there, whether an insn referred to
21047  * them or a continuous fd_array bound them before.
21048  */
21049 static int check_excl_maps(struct bpf_verifier_env *env)
21050 {
21051 	int i;
21052 
21053 	for (i = 0; i < env->used_map_cnt; i++) {
21054 		struct bpf_map *map = env->used_maps[i];
21055 
21056 		if (map->excl_prog_sha &&
21057 		    memcmp(map->excl_prog_sha, env->prog->digest, SHA256_DIGEST_SIZE)) {
21058 			verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
21059 			return -EACCES;
21060 		}
21061 	}
21062 	return 0;
21063 }
21064 
21065 /*
21066  * The program may use every map it referred to, see check_excl_maps(). Only now
21067  * does it leave a trace on them: it claims each as its user, see
21068  * bpf_map_claim(), and takes over its insn arrays. A program rejected before
21069  * this point, one that is not the owner of an exclusive map in particular,
21070  * leaves the maps as it found them. Nothing consults a claim before
21071  * resolve_func_ptrs() and the fixup passes, which run later.
21072  */
21073 static int claim_used_maps(struct bpf_verifier_env *env)
21074 {
21075 	int i, err;
21076 
21077 	for (i = 0; i < env->used_map_cnt; i++) {
21078 		struct bpf_map *map = env->used_maps[i];
21079 
21080 		err = bpf_map_claim(env, map);
21081 		if (err)
21082 			return err;
21083 
21084 		if (map->map_type != BPF_MAP_TYPE_INSN_ARRAY)
21085 			continue;
21086 		err = bpf_insn_array_init(map, env->prog);
21087 		if (err) {
21088 			verbose(env, "Failed to properly initialize insn array\n");
21089 			return err;
21090 		}
21091 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
21092 		env->prog->jit_required = true;
21093 	}
21094 	return 0;
21095 }
21096 
21097 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
21098 {
21099 	int i, err;
21100 
21101 	/* check whether we recorded this map already */
21102 	for (i = 0; i < env->used_map_cnt; i++)
21103 		if (env->used_maps[i] == map)
21104 			return i;
21105 
21106 	if (env->signature &&
21107 	    env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) {
21108 		verbose(env, "signed program cannot bind map '%s' not covered by the signature\n",
21109 			map->name);
21110 		return -EACCES;
21111 	}
21112 	if (env->used_map_cnt >= MAX_USED_MAPS) {
21113 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
21114 			MAX_USED_MAPS);
21115 		return -E2BIG;
21116 	}
21117 
21118 	err = check_map_prog_compatibility(env, map, env->prog);
21119 	if (err)
21120 		return err;
21121 
21122 	if (bpf_prog_runs_sleepable(env->prog))
21123 		atomic64_inc(&map->sleepable_refcnt);
21124 
21125 	/* hold the map. If the program is rejected by verifier,
21126 	 * the map will be released by release_maps() or it
21127 	 * will be used by the valid program until it's unloaded
21128 	 * and all maps are released in bpf_free_used_maps()
21129 	 */
21130 	bpf_map_inc(map);
21131 
21132 	env->used_maps[env->used_map_cnt++] = map;
21133 
21134 	return env->used_map_cnt - 1;
21135 }
21136 
21137 /* Add map behind fd to used maps list, if it's not already there, and return
21138  * its index.
21139  * Returns <0 on error, or >= 0 index, on success.
21140  */
21141 static int add_used_map(struct bpf_verifier_env *env, int fd)
21142 {
21143 	struct bpf_map *map;
21144 	CLASS(fd, f)(fd);
21145 
21146 	map = __bpf_map_get(f);
21147 	if (IS_ERR(map)) {
21148 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21149 		return PTR_ERR(map);
21150 	}
21151 
21152 	return __add_used_map(env, map);
21153 }
21154 
21155 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx)
21156 {
21157 	struct bpf_map *map;
21158 
21159 	if (idx >= env->fd_array_cnt) {
21160 		verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n",
21161 			idx, env->fd_array_cnt);
21162 		return -EINVAL;
21163 	}
21164 	map = fd_slot_map(env->fd_array[idx]);
21165 	if (!map) {
21166 		verbose(env, "fd_idx %u is not a map\n", idx);
21167 		return -EINVAL;
21168 	}
21169 	return __add_used_map(env, map);
21170 }
21171 
21172 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx)
21173 {
21174 	int fd;
21175 
21176 	if (copy_from_bpfptr_offset(&fd, env->fd_array_raw,
21177 				    (size_t)idx * sizeof(fd), sizeof(fd)))
21178 		return -EFAULT;
21179 	return add_used_map(env, fd);
21180 }
21181 
21182 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx)
21183 {
21184 	if (env->fd_array)
21185 		return fd_array_get_map_idx_continuous(env, idx);
21186 	if (env->signature) {
21187 		verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n");
21188 		return -EACCES;
21189 	}
21190 	if (!bpfptr_is_null(env->fd_array_raw))
21191 		return fd_array_get_map_idx_sparse(env, idx);
21192 
21193 	verbose(env, "fd_idx without fd_array is invalid\n");
21194 	return -EPROTO;
21195 }
21196 
21197 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21198 {
21199 	u8 class = BPF_CLASS(insn->code);
21200 	u8 opcode = BPF_OP(insn->code);
21201 
21202 	switch (opcode) {
21203 	case BPF_NEG:
21204 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
21205 		    insn->off != 0 || insn->imm != 0) {
21206 			verbose(env, "BPF_NEG uses reserved fields\n");
21207 			return -EINVAL;
21208 		}
21209 		return 0;
21210 	case BPF_END:
21211 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
21212 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
21213 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
21214 			verbose(env, "BPF_END uses reserved fields\n");
21215 			return -EINVAL;
21216 		}
21217 		return 0;
21218 	case BPF_MOV:
21219 		if (BPF_SRC(insn->code) == BPF_X) {
21220 			if (class == BPF_ALU) {
21221 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
21222 				    insn->imm) {
21223 					verbose(env, "BPF_MOV uses reserved fields\n");
21224 					return -EINVAL;
21225 				}
21226 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
21227 				if (insn->imm != 1 && insn->imm != 1u << 16) {
21228 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
21229 					return -EINVAL;
21230 				}
21231 			} else if ((insn->off != 0 && insn->off != 8 &&
21232 				    insn->off != 16 && insn->off != 32) || insn->imm) {
21233 				verbose(env, "BPF_MOV uses reserved fields\n");
21234 				return -EINVAL;
21235 			}
21236 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
21237 			verbose(env, "BPF_MOV uses reserved fields\n");
21238 			return -EINVAL;
21239 		}
21240 		return 0;
21241 	case BPF_ADD:
21242 	case BPF_SUB:
21243 	case BPF_AND:
21244 	case BPF_OR:
21245 	case BPF_XOR:
21246 	case BPF_LSH:
21247 	case BPF_RSH:
21248 	case BPF_ARSH:
21249 	case BPF_MUL:
21250 	case BPF_DIV:
21251 	case BPF_MOD:
21252 		if (BPF_SRC(insn->code) == BPF_X) {
21253 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
21254 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
21255 				verbose(env, "BPF_ALU uses reserved fields\n");
21256 				return -EINVAL;
21257 			}
21258 		} else if (insn->src_reg != BPF_REG_0 ||
21259 			   (insn->off != 0 && insn->off != 1) ||
21260 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
21261 			verbose(env, "BPF_ALU uses reserved fields\n");
21262 			return -EINVAL;
21263 		}
21264 		return 0;
21265 	default:
21266 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
21267 		return -EINVAL;
21268 	}
21269 }
21270 
21271 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21272 {
21273 	u8 class = BPF_CLASS(insn->code);
21274 	u8 opcode = BPF_OP(insn->code);
21275 
21276 	switch (opcode) {
21277 	case BPF_CALL:
21278 		if (bpf_is_callx(insn)) {
21279 			/* callx dst_reg */
21280 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
21281 				verbose(env, "BPF_CALL|BPF_X uses reserved fields\n");
21282 				return -EINVAL;
21283 			}
21284 			return 0;
21285 		}
21286 		if (BPF_SRC(insn->code) != BPF_K ||
21287 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
21288 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
21289 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
21290 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
21291 			verbose(env, "BPF_CALL uses reserved fields\n");
21292 			return -EINVAL;
21293 		}
21294 		return 0;
21295 	case BPF_JA:
21296 		if (BPF_SRC(insn->code) == BPF_X) {
21297 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
21298 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
21299 				return -EINVAL;
21300 			}
21301 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
21302 			   (class == BPF_JMP && insn->imm != 0) ||
21303 			   (class == BPF_JMP32 && insn->off != 0)) {
21304 			verbose(env, "BPF_JA uses reserved fields\n");
21305 			return -EINVAL;
21306 		}
21307 		return 0;
21308 	case BPF_EXIT:
21309 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
21310 		    insn->src_reg > BPF_UNWIND_EXIT || insn->dst_reg != BPF_REG_0 ||
21311 		    class == BPF_JMP32) {
21312 			verbose(env, "BPF_EXIT uses reserved fields\n");
21313 			return -EINVAL;
21314 		}
21315 		return 0;
21316 	case BPF_JCOND:
21317 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg > BPF_UNWIND_GOTO ||
21318 		    insn->dst_reg || insn->imm) {
21319 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
21320 			return -EINVAL;
21321 		}
21322 		return 0;
21323 	default:
21324 		if (BPF_SRC(insn->code) == BPF_X) {
21325 			if (insn->imm != 0) {
21326 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
21327 				return -EINVAL;
21328 			}
21329 		} else if (insn->src_reg != BPF_REG_0) {
21330 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
21331 			return -EINVAL;
21332 		}
21333 		return 0;
21334 	}
21335 }
21336 
21337 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
21338 {
21339 	switch (BPF_CLASS(insn->code)) {
21340 	case BPF_ALU:
21341 	case BPF_ALU64:
21342 		return check_alu_fields(env, insn);
21343 	case BPF_LDX:
21344 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21345 		    insn->imm != 0) {
21346 			verbose(env, "BPF_LDX uses reserved fields\n");
21347 			return -EINVAL;
21348 		}
21349 		return 0;
21350 	case BPF_STX:
21351 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
21352 			return 0;
21353 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
21354 			verbose(env, "BPF_STX uses reserved fields\n");
21355 			return -EINVAL;
21356 		}
21357 		return 0;
21358 	case BPF_ST:
21359 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
21360 			verbose(env, "BPF_ST uses reserved fields\n");
21361 			return -EINVAL;
21362 		}
21363 		return 0;
21364 	case BPF_JMP:
21365 	case BPF_JMP32:
21366 		return check_jmp_fields(env, insn);
21367 	case BPF_LD: {
21368 		u8 mode = BPF_MODE(insn->code);
21369 
21370 		if (mode == BPF_ABS || mode == BPF_IND) {
21371 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
21372 			    BPF_SIZE(insn->code) == BPF_DW ||
21373 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
21374 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
21375 				return -EINVAL;
21376 			}
21377 		} else if (mode != BPF_IMM) {
21378 			verbose(env, "invalid BPF_LD mode\n");
21379 			return -EINVAL;
21380 		}
21381 		return 0;
21382 	}
21383 	default:
21384 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
21385 		return -EINVAL;
21386 	}
21387 }
21388 
21389 /*
21390  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
21391  *
21392  * 1. if it accesses map FD, replace it with actual map pointer.
21393  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21394  *
21395  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21396  */
21397 static int check_and_resolve_insns(struct bpf_verifier_env *env)
21398 {
21399 	struct bpf_insn *insn = env->prog->insnsi;
21400 	int insn_cnt = env->prog->len;
21401 	int i, err;
21402 
21403 	err = bpf_prog_calc_tag(env->prog);
21404 	if (err)
21405 		return err;
21406 
21407 	for (i = 0; i < insn_cnt; i++, insn++) {
21408 		if (insn->dst_reg >= MAX_BPF_REG &&
21409 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
21410 			verbose(env, "R%d is invalid\n", insn->dst_reg);
21411 			return -EINVAL;
21412 		}
21413 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
21414 			verbose(env, "R%d is invalid\n", insn->src_reg);
21415 			return -EINVAL;
21416 		}
21417 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21418 			struct bpf_insn_aux_data *aux;
21419 			struct bpf_map *map;
21420 			int map_idx;
21421 			u64 addr;
21422 
21423 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
21424 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21425 			    insn[1].off != 0) {
21426 				verbose(env, "invalid bpf_ld_imm64 insn\n");
21427 				return -EINVAL;
21428 			}
21429 
21430 			if (insn[0].off != 0) {
21431 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
21432 				return -EINVAL;
21433 			}
21434 
21435 			if (insn[0].src_reg == 0)
21436 				/* valid generic load 64-bit imm */
21437 				goto next_insn;
21438 
21439 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21440 				aux = &env->insn_aux_data[i];
21441 				err = check_pseudo_btf_id(env, insn, aux);
21442 				if (err)
21443 					return err;
21444 				goto next_insn;
21445 			}
21446 
21447 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21448 				aux = &env->insn_aux_data[i];
21449 				aux->ptr_type = PTR_TO_FUNC;
21450 				goto next_insn;
21451 			}
21452 
21453 			/* In final convert_pseudo_ld_imm64() step, this is
21454 			 * converted into regular 64-bit imm load insn.
21455 			 */
21456 			switch (insn[0].src_reg) {
21457 			case BPF_PSEUDO_MAP_VALUE:
21458 			case BPF_PSEUDO_MAP_IDX_VALUE:
21459 				break;
21460 			case BPF_PSEUDO_MAP_FD:
21461 			case BPF_PSEUDO_MAP_IDX:
21462 				if (insn[1].imm == 0)
21463 					break;
21464 				fallthrough;
21465 			default:
21466 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21467 				return -EINVAL;
21468 			}
21469 
21470 			switch (insn[0].src_reg) {
21471 			case BPF_PSEUDO_MAP_IDX_VALUE:
21472 			case BPF_PSEUDO_MAP_IDX:
21473 				map_idx = fd_array_get_map_idx(env, insn[0].imm);
21474 				break;
21475 			default:
21476 				if (env->signature) {
21477 					verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n");
21478 					return -EINVAL;
21479 				}
21480 				map_idx = add_used_map(env, insn[0].imm);
21481 				break;
21482 			}
21483 
21484 			if (map_idx < 0)
21485 				return map_idx;
21486 			map = env->used_maps[map_idx];
21487 
21488 			aux = &env->insn_aux_data[i];
21489 			aux->map_index = map_idx;
21490 
21491 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21492 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21493 				addr = (unsigned long)map;
21494 			} else {
21495 				u32 off = insn[1].imm;
21496 
21497 				if (!map->ops->map_direct_value_addr) {
21498 					verbose(env, "no direct value access support for this map type\n");
21499 					return -EINVAL;
21500 				}
21501 
21502 				err = map->ops->map_direct_value_addr(map, &addr, off);
21503 				if (err) {
21504 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21505 						map->value_size, off);
21506 					return err;
21507 				}
21508 
21509 				aux->map_off = off;
21510 				addr += off;
21511 			}
21512 
21513 			insn[0].imm = (u32)addr;
21514 			insn[1].imm = addr >> 32;
21515 
21516 next_insn:
21517 			insn++;
21518 			i++;
21519 			continue;
21520 		}
21521 
21522 		/* Basic sanity check before we invest more work here. */
21523 		if (!bpf_opcode_in_insntable(insn->code)) {
21524 			verbose(env, "unknown opcode %02x\n", insn->code);
21525 			return -EINVAL;
21526 		}
21527 
21528 		err = check_insn_fields(env, insn);
21529 		if (err)
21530 			return err;
21531 	}
21532 
21533 	/* now all pseudo BPF_LD_IMM64 instructions load valid
21534 	 * 'struct bpf_map *' into a register instead of user map_fd.
21535 	 * These pointers will be used later by verifier to validate map access.
21536 	 */
21537 	err = check_excl_maps(env);
21538 	if (err)
21539 		return err;
21540 	return claim_used_maps(env);
21541 }
21542 
21543 /* that many pointers to functions are recognized in the maps of a program at most */
21544 #define BPF_MAX_FUNC_PTRS (1 << 20)
21545 
21546 static int add_func_ptr(struct bpf_verifier_env *env, struct bpf_map *map, u32 map_off,
21547 			u32 xlated_off)
21548 {
21549 	struct bpf_func_ptr *ptrs;
21550 
21551 	if (env->func_ptr_cnt == BPF_MAX_FUNC_PTRS) {
21552 		verbose(env, "too many pointers to functions in maps, the limit is %d\n",
21553 			BPF_MAX_FUNC_PTRS);
21554 		return -E2BIG;
21555 	}
21556 
21557 	/* grow by doubling, the array is sorted and searched later */
21558 	if (!(env->func_ptr_cnt & (env->func_ptr_cnt - 1))) {
21559 		ptrs = kvrealloc(env->func_ptrs,
21560 				 array_size(max(2 * env->func_ptr_cnt, 16U), sizeof(*ptrs)),
21561 				 GFP_KERNEL_ACCOUNT);
21562 		if (!ptrs)
21563 			return -ENOMEM;
21564 		env->func_ptrs = ptrs;
21565 	}
21566 	env->func_ptrs[env->func_ptr_cnt++] = (struct bpf_func_ptr){
21567 		.map = map,
21568 		.map_off = map_off,
21569 		.orig_off = xlated_off,
21570 		.xlated_off = xlated_off,
21571 	};
21572 	return 0;
21573 }
21574 
21575 /*
21576  * Compilers put pointers to functions into read-only data: tables of functions,
21577  * structures of operations, vtables, where they are mixed with other data.
21578  * The loader stores such data in a frozen read-only array map and resolves
21579  * a pointer to a static function to the offset in bytes of its first
21580  * instruction in the program: the address of the function in the program.
21581  *
21582  * Find 64-bit values that look like that in the maps of a program that uses
21583  * callx. It's a guess. When the value is not a pointer, the program either
21584  * fails to load, because it does with a pointer what can be done with
21585  * a number only, or it sees the address of a function instead of the number.
21586  * It's known before the control flow graph of the program is built and the main
21587  * verification pass begins which functions may be called via callx.
21588  *
21589  * When the program is jitted the offsets are replaced with the addresses of
21590  * the functions in the map itself, see jit_subprogs(). Hence the program has to
21591  * be the only user of the map, see bpf_map_claim(): nothing else may rely on
21592  * what the map had.
21593  *
21594  * The program reads the addresses of its functions from there like any other
21595  * data, so it has to be allowed to leak pointers.
21596  */
21597 static int resolve_func_ptrs(struct bpf_verifier_env *env)
21598 {
21599 	int insn_cnt = env->prog->len;
21600 	int i, err, subprog;
21601 	struct bpf_map *map;
21602 	u64 addr, val;
21603 	u32 off;
21604 
21605 	if (!env->has_callx || !env->allow_ptr_leaks)
21606 		return 0;
21607 
21608 	for (i = 0; i < env->used_map_cnt; i++) {
21609 		map = env->used_maps[i];
21610 		/* coincidences in maps that are shared with other programs don't matter */
21611 		if (READ_ONCE(map->user) != (unsigned long)env->prog->aux)
21612 			continue;
21613 		if (map->map_type != BPF_MAP_TYPE_ARRAY || map->max_entries != 1 ||
21614 		    !bpf_map_is_rdonly(map) || !map->ops->map_direct_value_addr ||
21615 		    !IS_ERR_OR_NULL(map->record))
21616 			continue;
21617 		if (map->ops->map_direct_value_addr(map, &addr, 0))
21618 			continue;
21619 
21620 		for (off = 0; off + sizeof(u64) <= map->value_size; off += sizeof(u64)) {
21621 			if (!(off % SZ_64K))
21622 				cond_resched();
21623 			val = *(u64 *)(unsigned long)(addr + off);
21624 			if (!val || val % sizeof(struct bpf_insn) ||
21625 			    val / sizeof(struct bpf_insn) >= insn_cnt)
21626 				continue;
21627 			subprog = bpf_find_subprog(env, val / sizeof(struct bpf_insn));
21628 			if (subprog <= 0 || bpf_subprog_is_global(env, subprog))
21629 				continue;
21630 			err = add_func_ptr(env, map, off, val / sizeof(struct bpf_insn));
21631 			if (err)
21632 				return err;
21633 		}
21634 	}
21635 	if (env->func_ptr_cnt)
21636 		sort(env->func_ptrs, env->func_ptr_cnt, sizeof(*env->func_ptrs),
21637 		     cmp_func_ptrs, NULL);
21638 	return 0;
21639 }
21640 
21641 /* drop refcnt of maps used by the rejected program */
21642 static void release_maps(struct bpf_verifier_env *env)
21643 {
21644 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
21645 			     env->used_map_cnt);
21646 }
21647 
21648 /* drop refcnt of maps used by the rejected program */
21649 static void release_btfs(struct bpf_verifier_env *env)
21650 {
21651 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21652 }
21653 
21654 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
21655 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21656 {
21657 	struct bpf_insn *insn = env->prog->insnsi;
21658 	int insn_cnt = env->prog->len;
21659 	int i;
21660 
21661 	for (i = 0; i < insn_cnt; i++, insn++) {
21662 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21663 			continue;
21664 		if (insn->src_reg == BPF_PSEUDO_FUNC)
21665 			continue;
21666 		insn->src_reg = 0;
21667 	}
21668 }
21669 
21670 static void release_insn_arrays(struct bpf_verifier_env *env)
21671 {
21672 	int i;
21673 
21674 	for (i = 0; i < env->insn_array_map_cnt; i++)
21675 		bpf_insn_array_release(env->insn_array_maps[i]);
21676 }
21677 
21678 /* The verifier does more data flow analysis than llvm and will not
21679  * explore branches that are dead at run time. Malicious programs can
21680  * have dead code too. Therefore replace all dead at-run-time code
21681  * with 'ja -1'.
21682  *
21683  * Just nops are not optimal, e.g. if they would sit at the end of the
21684  * program and through another bug we would manage to jump there, then
21685  * we'd execute beyond program memory otherwise. Returning exception
21686  * code also wouldn't work since we can have subprogs where the dead
21687  * code could be located.
21688  */
21689 static void sanitize_dead_code(struct bpf_verifier_env *env)
21690 {
21691 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21692 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21693 	struct bpf_insn *insn = env->prog->insnsi;
21694 	const int insn_cnt = env->prog->len;
21695 	int i;
21696 
21697 	for (i = 0; i < insn_cnt; i++) {
21698 		if (aux_data[i].seen)
21699 			continue;
21700 		memcpy(insn + i, &trap, sizeof(trap));
21701 		aux_data[i].zext_dst = false;
21702 	}
21703 }
21704 
21705 static void free_states(struct bpf_verifier_env *env)
21706 {
21707 	struct bpf_verifier_state_list *sl;
21708 	struct list_head *head, *pos, *tmp;
21709 	struct bpf_scc_info *info;
21710 	int i, j;
21711 
21712 	bpf_free_verifier_state(env->cur_state, true);
21713 	env->cur_state = NULL;
21714 	while (!pop_stack(env, NULL, NULL, false));
21715 
21716 	list_for_each_safe(pos, tmp, &env->free_list) {
21717 		sl = container_of(pos, struct bpf_verifier_state_list, node);
21718 		bpf_free_verifier_state(&sl->state, false);
21719 		kfree(sl);
21720 	}
21721 	INIT_LIST_HEAD(&env->free_list);
21722 
21723 	for (i = 0; i < env->scc_cnt; ++i) {
21724 		info = env->scc_info[i];
21725 		if (!info)
21726 			continue;
21727 		for (j = 0; j < info->num_visits; j++)
21728 			bpf_free_backedges(&info->visits[j]);
21729 		kvfree(info);
21730 		env->scc_info[i] = NULL;
21731 	}
21732 
21733 	if (!env->explored_states)
21734 		return;
21735 
21736 	for (i = 0; i < state_htab_size(env); i++) {
21737 		head = &env->explored_states[i];
21738 
21739 		list_for_each_safe(pos, tmp, head) {
21740 			sl = container_of(pos, struct bpf_verifier_state_list, node);
21741 			bpf_free_verifier_state(&sl->state, false);
21742 			kfree(sl);
21743 		}
21744 		INIT_LIST_HEAD(&env->explored_states[i]);
21745 	}
21746 }
21747 
21748 static int do_check_common(struct bpf_verifier_env *env, int subprog,
21749 			   enum bpf_func_context context)
21750 {
21751 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21752 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
21753 	struct bpf_prog_aux *aux = env->prog->aux;
21754 	struct bpf_verifier_state *state;
21755 	struct bpf_reg_state *regs;
21756 	u32 old_insns_total = sub->insns_total;
21757 	u32 insn_processed = env->insn_processed;
21758 	int ret, i;
21759 
21760 	env->prev_linfo = NULL;
21761 	env->pass_cnt++;
21762 
21763 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
21764 	if (!state)
21765 		return -ENOMEM;
21766 	state->curframe = 0;
21767 	state->speculative = false;
21768 	state->branches = 1;
21769 	state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE;
21770 	env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK;
21771 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
21772 	if (!state->frame[0]) {
21773 		kfree(state);
21774 		return -ENOMEM;
21775 	}
21776 	env->cur_state = state;
21777 	init_func_state(env, state->frame[0],
21778 			BPF_MAIN_FUNC /* callsite */,
21779 			0 /* frameno */,
21780 			subprog);
21781 	state->first_insn_idx = env->subprog_info[subprog].start;
21782 	state->last_insn_idx = -1;
21783 
21784 	regs = state->frame[state->curframe]->regs;
21785 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21786 		const char *sub_name = bpf_subprog_name(env, subprog);
21787 		struct bpf_subprog_arg_info *arg;
21788 		struct bpf_reg_state *reg;
21789 
21790 		if (env->log.level & BPF_LOG_LEVEL)
21791 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21792 		ret = btf_prepare_func_args(env, subprog);
21793 		if (ret)
21794 			goto out;
21795 
21796 		if (subprog_is_exc_cb(env, subprog)) {
21797 			state->frame[0]->in_exception_callback_fn = true;
21798 
21799 			/*
21800 			 * Global functions are scalar or void, make sure
21801 			 * we return a scalar.
21802 			 */
21803 			if (subprog_returns_void(env, subprog)) {
21804 				verbose(env, "exception cb cannot return void\n");
21805 				ret = -EINVAL;
21806 				goto out;
21807 			}
21808 
21809 			/* Also ensure the callback only has a single scalar argument. */
21810 			if (sub->arg_slot_cnt != 1 || sub->args[0].arg_type != ARG_SCALAR) {
21811 				verbose(env, "exception cb only supports single integer argument\n");
21812 				ret = -EINVAL;
21813 				goto out;
21814 			}
21815 		}
21816 		for (i = BPF_REG_1;
21817 		     i <= min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
21818 			arg = &sub->args[i - BPF_REG_1];
21819 			reg = &regs[i];
21820 
21821 			if (arg->arg_type == ARG_PTR_TO_CTX) {
21822 				reg->type = PTR_TO_CTX;
21823 				mark_reg_known_zero(env, regs, i);
21824 			} else if (arg->arg_type == ARG_SCALAR) {
21825 				reg->type = SCALAR_VALUE;
21826 				mark_reg_unknown(env, regs, i);
21827 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
21828 				/*
21829 				 * The callers may hand in a dynptr of any type.
21830 				 * Take it for that of an skb, so that a write
21831 				 * through it and its slices are treated with care.
21832 				 */
21833 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen, 0);
21834 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
21835 				reg->type = PTR_TO_MEM;
21836 				reg->type |= arg->arg_type &
21837 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
21838 				mark_reg_known_zero(env, regs, i);
21839 				reg->mem_size = arg->mem_size;
21840 				if (arg->arg_type & PTR_MAYBE_NULL)
21841 					reg->id = ++env->id_gen;
21842 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
21843 				reg->type = PTR_TO_BTF_ID;
21844 				if (arg->arg_type & PTR_MAYBE_NULL)
21845 					reg->type |= PTR_MAYBE_NULL;
21846 				if (arg->arg_type & PTR_UNTRUSTED)
21847 					reg->type |= PTR_UNTRUSTED;
21848 				if (arg->arg_type & PTR_TRUSTED)
21849 					reg->type |= PTR_TRUSTED;
21850 				mark_reg_known_zero(env, regs, i);
21851 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
21852 				reg->btf_id = arg->btf_id;
21853 				reg->id = ++env->id_gen;
21854 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
21855 				/* caller can pass either PTR_TO_ARENA or SCALAR */
21856 				mark_reg_unknown(env, regs, i);
21857 			} else {
21858 				verifier_bug(env, "unhandled arg#%d type %d",
21859 					     i - BPF_REG_1 + 1, arg->arg_type);
21860 				ret = -EFAULT;
21861 				goto out;
21862 			}
21863 		}
21864 		if (env->prog->type == BPF_PROG_TYPE_EXT &&
21865 		    sub->arg_slot_cnt > MAX_BPF_FUNC_REG_ARGS) {
21866 			verbose(env, "freplace programs with >%d args not supported yet\n",
21867 				MAX_BPF_FUNC_REG_ARGS);
21868 			ret = -EINVAL;
21869 			goto out;
21870 		}
21871 	} else {
21872 		/* if main BPF program has associated BTF info, validate that
21873 		 * it's matching expected signature, and otherwise mark BTF
21874 		 * info for main program as unreliable
21875 		 */
21876 		if (env->prog->aux->func_info_aux) {
21877 			ret = btf_prepare_func_args(env, 0);
21878 			if (ret || sub->arg_slot_cnt != 1 ||
21879 			    sub->args[0].arg_type != ARG_PTR_TO_CTX) {
21880 				env->prog->aux->func_info_aux[0].unreliable = true;
21881 				sub->arg_slot_cnt = 1;
21882 				sub->stack_arg_cnt = 0;
21883 			}
21884 		}
21885 
21886 		/* 1st arg to a function */
21887 		regs[BPF_REG_1].type = PTR_TO_CTX;
21888 		mark_reg_known_zero(env, regs, BPF_REG_1);
21889 	}
21890 
21891 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
21892 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
21893 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
21894 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
21895 			if (ret < 0)
21896 				goto out;
21897 
21898 			aux->ctx_arg_info[i].ref_id = ret;
21899 		}
21900 	}
21901 
21902 	ret = do_check(env);
21903 out:
21904 	account_current_path(env);
21905 	if (!ret) {
21906 		if (pop_log)
21907 			bpf_vlog_reset(&env->log, 0);
21908 		bpf_diag_event_log_restore(env, 0);
21909 	}
21910 	free_states(env);
21911 
21912 	/*
21913 	 * The override is needed to account for async subprograms, which
21914 	 * are verified with their own set of stack frames and thus are
21915 	 * not accounted as callees by account_current_path().
21916 	 * Accumulate their total counts as total counts of the main or
21917 	 * global subprog hosting the async call.
21918 	 * Start from the saved total of earlier contexts: adding to the current
21919 	 * total would count this pass's synchronous paths twice.
21920 	 */
21921 	sub->insns_total = old_insns_total + (env->insn_processed - insn_processed);
21922 	return ret;
21923 }
21924 
21925 /* Lazily verify all global functions based on their BTF, if they are called
21926  * from main BPF program or any of subprograms transitively.
21927  * BPF global subprogs called from dead code are not validated.
21928  * All callable global functions must pass verification.
21929  * Otherwise the whole program is rejected.
21930  * Consider:
21931  * int bar(int);
21932  * int foo(int f)
21933  * {
21934  *    return bar(f);
21935  * }
21936  * int bar(int b)
21937  * {
21938  *    ...
21939  * }
21940  * foo() will be verified first for R1=any_scalar_value. During verification it
21941  * will be assumed that bar() already verified successfully and call to bar()
21942  * from foo() will be checked for type match only. Later bar() will be verified
21943  * independently to check that it's safe for R1=any_scalar_value.
21944  */
21945 static int do_check_subprogs(struct bpf_verifier_env *env)
21946 {
21947 	struct bpf_prog_aux *aux = env->prog->aux;
21948 	struct bpf_func_info_aux *sub_aux;
21949 	int context, i, ret, new_cnt;
21950 
21951 	if (!aux->func_info)
21952 		return 0;
21953 
21954 	/*
21955 	 * Callbacks cannot throw, so the exception callback always runs in the
21956 	 * main program's context. It is presumed to be always called.
21957 	 */
21958 	if (env->exception_callback_subprog) {
21959 		sub_aux = subprog_aux(env, env->exception_callback_subprog);
21960 		sub_aux->called[env->prog->sleepable] = true;
21961 	}
21962 
21963 again:
21964 	new_cnt = 0;
21965 	for (i = 1; i < env->subprog_cnt; i++) {
21966 		if (!bpf_subprog_is_global(env, i))
21967 			continue;
21968 
21969 		sub_aux = subprog_aux(env, i);
21970 		for (context = 0; context < ARRAY_SIZE(sub_aux->called); context++) {
21971 			if (!sub_aux->called[context] || sub_aux->verified[context])
21972 				continue;
21973 
21974 			env->insn_idx = env->subprog_info[i].start;
21975 			WARN_ON_ONCE(env->insn_idx == 0);
21976 			ret = do_check_common(env, i, context);
21977 			if (ret)
21978 				return ret;
21979 			if (env->log.level & BPF_LOG_LEVEL)
21980 				verbose(env, "Func#%d ('%s') is safe for any args "
21981 					"that match its prototype\n",
21982 					i, bpf_subprog_name(env, i));
21983 
21984 			sub_aux->verified[context] = true;
21985 			new_cnt++;
21986 		}
21987 	}
21988 
21989 	/*
21990 	 * We can't loop forever as each pass verifies at least one new context,
21991 	 * and there are only three contexts per global subprog.
21992 	 */
21993 	if (new_cnt)
21994 		goto again;
21995 
21996 	return 0;
21997 }
21998 
21999 static int do_check_main(struct bpf_verifier_env *env)
22000 {
22001 	int ret;
22002 
22003 	env->insn_idx = 0;
22004 	ret = do_check_common(env, 0, env->prog->sleepable);
22005 	if (!ret)
22006 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
22007 	return ret;
22008 }
22009 
22010 static void print_verification_stats(struct bpf_verifier_env *env)
22011 {
22012 	/* Skip over hidden subprogs which are not verified. */
22013 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22014 
22015 	if (env->log.level & BPF_LOG_STATS) {
22016 		verbose(env, "verification time %lld usec\n",
22017 			div_u64(env->verification_time, 1000));
22018 		verbose(env, "stack depth max %d\n", env->max_stack_depth);
22019 		for (i = 0; i < subprog_cnt; i++) {
22020 			const char *name = env->subprog_info[i].name;
22021 			const char *kind;
22022 
22023 			if (!name || !name[0])
22024 				name = "<unknown>";
22025 			kind = i == 0 ? "main" :
22026 			       bpf_subprog_is_global(env, i) ? "global" : "static";
22027 			verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n",
22028 				i, name, kind, env->subprog_info[i].insns_self,
22029 				env->subprog_info[i].insns_total,
22030 				env->subprog_info[i].stack_depth);
22031 		}
22032 	}
22033 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
22034 		"total_states %d peak_states %d mark_read %d\n",
22035 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
22036 		env->max_states_per_insn, env->total_states,
22037 		env->peak_states, env->longest_mark_read_walk);
22038 }
22039 
22040 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
22041 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
22042 {
22043 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
22044 	prog->aux->ctx_arg_info_size = cnt;
22045 
22046 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
22047 }
22048 
22049 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
22050 {
22051 	const struct btf_type *t, *func_proto;
22052 	const struct bpf_struct_ops_desc *st_ops_desc;
22053 	const struct bpf_struct_ops_arg_info *arg_info;
22054 	const struct bpf_struct_ops *st_ops;
22055 	const struct btf_member *member;
22056 	struct bpf_prog *prog = env->prog;
22057 	bool has_refcounted_arg = false;
22058 	u32 btf_id, member_idx, member_off;
22059 	struct btf *btf;
22060 	const char *mname;
22061 	int i, err;
22062 
22063 	if (!prog->gpl_compatible) {
22064 		verbose(env, "struct ops programs must have a GPL compatible license\n");
22065 		return -EINVAL;
22066 	}
22067 
22068 	if (!prog->aux->attach_btf_id)
22069 		return -ENOTSUPP;
22070 
22071 	btf = prog->aux->attach_btf;
22072 	if (btf_is_module(btf)) {
22073 		/* Make sure st_ops is valid through the lifetime of env */
22074 		env->attach_btf_mod = btf_try_get_module(btf);
22075 		if (!env->attach_btf_mod) {
22076 			verbose(env, "struct_ops module %s is not found\n",
22077 				btf_get_name(btf));
22078 			return -ENOTSUPP;
22079 		}
22080 	}
22081 
22082 	btf_id = prog->aux->attach_btf_id;
22083 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
22084 	if (!st_ops_desc) {
22085 		verbose(env, "attach_btf_id %u is not a supported struct\n",
22086 			btf_id);
22087 		return -ENOTSUPP;
22088 	}
22089 	st_ops = st_ops_desc->st_ops;
22090 
22091 	t = st_ops_desc->type;
22092 	member_idx = prog->expected_attach_type;
22093 	if (member_idx >= btf_type_vlen(t)) {
22094 		verbose(env, "attach to invalid member idx %u of struct %s\n",
22095 			member_idx, st_ops->name);
22096 		return -EINVAL;
22097 	}
22098 
22099 	member = &btf_type_member(t)[member_idx];
22100 	mname = btf_name_by_offset(btf, member->name_off);
22101 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
22102 					       NULL);
22103 	if (!func_proto) {
22104 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
22105 			mname, member_idx, st_ops->name);
22106 		return -EINVAL;
22107 	}
22108 
22109 	member_off = __btf_member_bit_offset(t, member) / 8;
22110 	err = bpf_struct_ops_supported(st_ops, member_off);
22111 	if (err) {
22112 		verbose(env, "attach to unsupported member %s of struct %s\n",
22113 			mname, st_ops->name);
22114 		return err;
22115 	}
22116 
22117 	if (st_ops->check_member) {
22118 		err = st_ops->check_member(t, member, prog);
22119 
22120 		if (err) {
22121 			verbose(env, "attach to unsupported member %s of struct %s\n",
22122 				mname, st_ops->name);
22123 			return err;
22124 		}
22125 	}
22126 
22127 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
22128 		verbose(env, "Private stack not supported by jit\n");
22129 		return -EACCES;
22130 	}
22131 
22132 	arg_info = &st_ops_desc->arg_info[member_idx];
22133 	for (i = 0; i < arg_info->cnt; i++) {
22134 		const struct bpf_ctx_arg_aux *info = &arg_info->info[i];
22135 
22136 		if (info->refcounted)
22137 			has_refcounted_arg = true;
22138 		if (base_type(info->reg_type) == PTR_TO_ARENA) {
22139 			if (!bpf_jit_supports_arena_args()) {
22140 				verbose(env, "JIT does not support arena arguments\n");
22141 				return -ENOTSUPP;
22142 			}
22143 			if (!prog->aux->arena) {
22144 				verbose(env,
22145 					"arena argument of %s requires a program with an associated arena\n",
22146 					mname);
22147 				return -EINVAL;
22148 			}
22149 		}
22150 	}
22151 
22152 	/* Tail call is not allowed for programs with refcounted arguments since we
22153 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
22154 	 */
22155 	for (i = 0; i < env->subprog_cnt; i++) {
22156 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
22157 			verbose(env, "program with __ref argument cannot tail call\n");
22158 			return -EINVAL;
22159 		}
22160 	}
22161 
22162 	prog->aux->st_ops = st_ops;
22163 	prog->aux->attach_st_ops_member_off = member_off;
22164 
22165 	prog->aux->attach_func_proto = func_proto;
22166 	prog->aux->attach_func_name = mname;
22167 	env->ops = st_ops->verifier_ops;
22168 
22169 	return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt);
22170 }
22171 #define SECURITY_PREFIX "security_"
22172 
22173 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
22174 
22175 /* list of non-sleepable functions that are otherwise on
22176  * ALLOW_ERROR_INJECTION list
22177  */
22178 BTF_SET_START(btf_non_sleepable_error_inject)
22179 /* Three functions below can be called from sleepable and non-sleepable context.
22180  * Assume non-sleepable from bpf safety point of view.
22181  */
22182 BTF_ID(func, __filemap_add_folio)
22183 #ifdef CONFIG_FAIL_PAGE_ALLOC
22184 BTF_ID(func, should_fail_alloc_page)
22185 #endif
22186 #ifdef CONFIG_FAILSLAB
22187 BTF_ID(func, should_failslab)
22188 #endif
22189 BTF_SET_END(btf_non_sleepable_error_inject)
22190 
22191 static int check_non_sleepable_error_inject(u32 btf_id)
22192 {
22193 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
22194 }
22195 
22196 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
22197 {
22198 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
22199 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22200 	 */
22201 	if (!check_non_sleepable_error_inject(btf_id) &&
22202 	    within_error_injection_list(addr))
22203 		return 0;
22204 
22205 	return -EINVAL;
22206 }
22207 
22208 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22209 {
22210 	if (within_error_injection_list(addr) ||
22211 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22212 		return 0;
22213 
22214 	return -EINVAL;
22215 }
22216 
22217 #else
22218 
22219 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
22220  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
22221  * but that just compares two concrete function names.
22222  */
22223 static bool has_arch_syscall_prefix(const char *func_name)
22224 {
22225 #if defined(__x86_64__)
22226 	return !strncmp(func_name, "__x64_", 6);
22227 #elif defined(__i386__)
22228 	return !strncmp(func_name, "__ia32_", 7);
22229 #elif defined(__s390x__)
22230 	return !strncmp(func_name, "__s390x_", 8);
22231 #elif defined(__aarch64__)
22232 	return !strncmp(func_name, "__arm64_", 8);
22233 #elif defined(__riscv)
22234 	return !strncmp(func_name, "__riscv_", 8);
22235 #elif defined(__powerpc__) || defined(__powerpc64__)
22236 	return !strncmp(func_name, "sys_", 4);
22237 #elif defined(__loongarch__)
22238 	return !strncmp(func_name, "sys_", 4);
22239 #else
22240 	return false;
22241 #endif
22242 }
22243 
22244 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
22245 
22246 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
22247 {
22248 	if (has_arch_syscall_prefix(func_name))
22249 		return 0;
22250 
22251 	return -EINVAL;
22252 }
22253 
22254 static int check_attach_modify_return(unsigned long addr, const char *func_name)
22255 {
22256 	if (has_arch_syscall_prefix(func_name) ||
22257 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
22258 		return 0;
22259 
22260 	return -EINVAL;
22261 }
22262 
22263 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
22264 
22265 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
22266 {
22267 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
22268 }
22269 
22270 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
22271 				  const struct btf *btf)
22272 {
22273 	const struct btf_type *t;
22274 	const char *tname;
22275 
22276 	if (!btf_is_kernel(btf))
22277 		return -EINVAL;
22278 
22279 	switch (prog->type) {
22280 	case BPF_PROG_TYPE_TRACING:
22281 		t = btf_type_by_id(btf, btf_id);
22282 		if (!t)
22283 			return -EINVAL;
22284 		tname = btf_name_by_offset(btf, t->name_off);
22285 		if (!tname)
22286 			return -EINVAL;
22287 
22288 		/*
22289 		 * *.multi sleepable programs will pass initial sleepable check,
22290 		 * the actual attached btf ids are checked later during the link
22291 		 * attachment.
22292 		 */
22293 		if (is_tracing_multi_id(prog, btf_id))
22294 			return 0;
22295 		if (!check_attach_sleepable(btf_id, addr, tname))
22296 			return 0;
22297 		/*
22298 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
22299 		 * in the fmodret id set with the KF_SLEEPABLE flag.
22300 		 */
22301 		else {
22302 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
22303 
22304 			if (flags && (*flags & KF_SLEEPABLE))
22305 				return 0;
22306 		}
22307 		break;
22308 	case BPF_PROG_TYPE_LSM:
22309 		/*
22310 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
22311 		 * Only some of them are sleepable.
22312 		 */
22313 		if (bpf_lsm_is_sleepable_hook(btf_id))
22314 			return 0;
22315 		break;
22316 	default:
22317 		break;
22318 	}
22319 	return -EINVAL;
22320 }
22321 
22322 /*
22323  * Resolve the prototype describing a trace target's real ABI. A
22324  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
22325  * prototype, so use the _impl prototype; other targets use their own.
22326  */
22327 static const struct btf_type *
22328 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
22329 {
22330 	const struct btf_type *func;
22331 	struct module *mod = NULL;
22332 	const char *name;
22333 	int implicit;
22334 
22335 	func = btf_type_by_id(btf, func_id);
22336 	if (!func || !btf_type_is_func(func))
22337 		return NULL;
22338 	name = btf_name_by_offset(btf, func->name_off);
22339 
22340 	/*
22341 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
22342 	 * stable only once it is live; hold a module ref across the read to
22343 	 * exclude a concurrent module load.
22344 	 */
22345 	if (btf_is_module(btf)) {
22346 		mod = btf_try_get_module(btf);
22347 		if (!mod)
22348 			return NULL;
22349 	}
22350 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
22351 	module_put(mod);
22352 
22353 	if (implicit == -EINVAL) {
22354 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
22355 		return NULL;
22356 	}
22357 	if (implicit > 0)
22358 		return find_kfunc_impl_proto(log, btf, name);
22359 
22360 	return btf_type_by_id(btf, func->type);
22361 }
22362 
22363 static bool attach_uses_trampoline_retval(enum bpf_attach_type type)
22364 {
22365 	switch (type) {
22366 	case BPF_MODIFY_RETURN:
22367 	case BPF_TRACE_FEXIT:
22368 	case BPF_TRACE_FEXIT_MULTI:
22369 	case BPF_TRACE_FSESSION:
22370 	case BPF_TRACE_FSESSION_MULTI:
22371 		return true;
22372 	default:
22373 		return false;
22374 	}
22375 }
22376 
22377 /*
22378  * BPF code passes argument slot N where the kernel convention passes its Nth
22379  * u64 argument, so describe a BPF function to its trampoline as one u64 per
22380  * slot, and every arch places its arguments right.
22381  */
22382 static int flatten_bpf_func_model(struct bpf_verifier_log *log, const char *tname,
22383 				  struct btf_func_model *m)
22384 {
22385 	u32 i, nslots = 0;
22386 
22387 	for (i = 0; i < m->nr_args; i++)
22388 		nslots += btf_func_model_arg_slots(m, i);
22389 	if (nslots > MAX_BPF_FUNC_ARGS) {
22390 		bpf_log(log, "The function %s has %u argument slots. Too many.\n",
22391 			tname, nslots);
22392 		return -EINVAL;
22393 	}
22394 
22395 	for (i = 0; i < nslots; i++) {
22396 		m->arg_size[i] = sizeof(u64);
22397 		m->arg_flags[i] = 0;
22398 	}
22399 	m->nr_args = nslots;
22400 	return 0;
22401 }
22402 
22403 /*
22404  * The verifier lets a static function use stack arguments counted from its
22405  * BTF, even if that BTF turns out unreliable. A trampoline on the function is
22406  * then given only MAX_BPF_FUNC_REG_ARGS u64 arguments and would lose the
22407  * stack arguments, so such a function cannot be attached to.
22408  */
22409 static int check_unreliable_func_args(struct bpf_verifier_log *log, struct btf *btf,
22410 				      const struct btf_type *func_proto, const char *tname)
22411 {
22412 	struct btf_func_model m;
22413 	u32 i, nslots = 0;
22414 
22415 	if (btf_distill_func_proto(NULL, btf, func_proto, tname, &m)) {
22416 		/* at least a slot for each argument */
22417 		nslots = btf_type_vlen(func_proto);
22418 	} else {
22419 		for (i = 0; i < m.nr_args; i++)
22420 			nslots += btf_func_model_arg_slots(&m, i);
22421 	}
22422 	if (nslots <= MAX_BPF_FUNC_REG_ARGS)
22423 		return 0;
22424 
22425 	bpf_log(log, "Cannot attach to static function %s: unreliable BTF and stack arguments\n",
22426 		tname);
22427 	return -EINVAL;
22428 }
22429 
22430 /* Functions may share a type id. The first of them is attached to. */
22431 static int find_tgt_subprog(const struct bpf_prog *tgt_prog, u32 btf_id)
22432 {
22433 	const struct bpf_prog_aux *aux = tgt_prog->aux;
22434 	int i;
22435 
22436 	for (i = 0; i < aux->func_info_cnt; i++)
22437 		if (aux->func_info[i].type_id == btf_id)
22438 			return i;
22439 
22440 	return -1;
22441 }
22442 
22443 /*
22444  * The prologue of an extension gives a cloned skb a new head, unless the
22445  * prologue of the target program has done that. The callers of the function
22446  * that it replaces must not hold on to the old head.
22447  */
22448 int bpf_check_ext_prologue(struct bpf_verifier_log *log,
22449 			   const struct bpf_prog *tgt_prog, u32 btf_id)
22450 {
22451 	const struct bpf_prog_aux *aux = tgt_prog->aux;
22452 	int subprog = find_tgt_subprog(tgt_prog, btf_id);
22453 
22454 	if (aux->has_prologue)
22455 		return 0;
22456 
22457 	if (subprog >= 0 && !aux->func_info_aux[subprog].called_with_pkt_ptrs)
22458 		return 0;
22459 
22460 	bpf_log(log,
22461 		"Extension writing packet data cannot replace a function whose callers keep packet pointers\n");
22462 	return -EINVAL;
22463 }
22464 
22465 /*
22466  * An extension is verified as a program that runs under the RCU read lock. Does
22467  * the function that it is to replace?
22468  */
22469 static bool func_has_rcu_read_lock(const struct bpf_prog *prog, int subprog)
22470 {
22471 	const struct bpf_func_info_aux *sub_aux = &prog->aux->func_info_aux[subprog];
22472 
22473 	if (!subprog)
22474 		return !prog->sleepable;
22475 
22476 	return !sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] &&
22477 	       !sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK];
22478 }
22479 
22480 int bpf_check_attach_target(struct bpf_verifier_log *log,
22481 			    const struct bpf_prog *prog,
22482 			    const struct bpf_prog *tgt_prog,
22483 			    u32 btf_id,
22484 			    struct bpf_attach_target_info *tgt_info)
22485 {
22486 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
22487 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
22488 	char trace_symbol[KSYM_SYMBOL_LEN];
22489 	const char prefix[] = "btf_trace_";
22490 	struct bpf_raw_event_map *btp;
22491 	int ret = 0, subprog = -1;
22492 	const struct btf_type *t;
22493 	bool conservative = true;
22494 	const char *tname, *fname;
22495 	struct btf *btf;
22496 	long addr = 0;
22497 	struct module *mod = NULL;
22498 
22499 	if (!btf_id) {
22500 		bpf_log(log, "Tracing programs must provide btf_id\n");
22501 		return -EINVAL;
22502 	}
22503 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
22504 	if (!btf) {
22505 		bpf_log(log,
22506 			"Tracing program can only be attached to another program annotated with BTF\n");
22507 		return -EINVAL;
22508 	}
22509 	t = btf_type_by_id(btf, btf_id);
22510 	if (!t) {
22511 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
22512 		return -EINVAL;
22513 	}
22514 	tname = btf_name_by_offset(btf, t->name_off);
22515 	if (!tname) {
22516 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
22517 		return -EINVAL;
22518 	}
22519 	if (tgt_prog) {
22520 		struct bpf_prog_aux *aux = tgt_prog->aux;
22521 		bool tgt_changes_pkt_data;
22522 		bool tgt_might_sleep;
22523 		bool tgt_can_unwind;
22524 
22525 		if (bpf_prog_is_dev_bound(prog->aux) &&
22526 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
22527 			bpf_log(log, "Target program bound device mismatch");
22528 			return -EINVAL;
22529 		}
22530 
22531 		subprog = find_tgt_subprog(tgt_prog, btf_id);
22532 		if (subprog == -1) {
22533 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
22534 			return -EINVAL;
22535 		}
22536 		/*
22537 		 * A struct_ops indirect trampoline converts arena arguments
22538 		 * before invoking its program. A tracing or extension program
22539 		 * attached to the main program would see the converted offset as a
22540 		 * regular BTF pointer.
22541 		 */
22542 		if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) {
22543 			bpf_log(log, "Cannot attach to a target with arena context arguments\n");
22544 			return -EOPNOTSUPP;
22545 		}
22546 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
22547 			bpf_log(log,
22548 				"%s programs cannot attach to exception callback\n",
22549 				prog_extension ? "Extension" : "Tracing");
22550 			return -EINVAL;
22551 		}
22552 		/* unwind_exit of the main prog is exit, unless it's an extension */
22553 		tgt_can_unwind = (subprog || tgt_prog->type == BPF_PROG_TYPE_EXT) &&
22554 				 (aux->func ? aux->func[subprog]->aux->can_unwind
22555 					    : aux->can_unwind);
22556 		/* unwind_exit would return to the trampoline that called the target */
22557 		if (tgt_can_unwind && !prog_extension &&
22558 		    prog->expected_attach_type != BPF_TRACE_FENTRY) {
22559 			bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);
22560 			return -EINVAL;
22561 		}
22562 		conservative = aux->func_info_aux[subprog].unreliable;
22563 		if (prog_extension) {
22564 			if (aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL ||
22565 			    conservative) {
22566 				bpf_log(log,
22567 					"Cannot replace static functions\n");
22568 				return -EINVAL;
22569 			}
22570 			if (!prog->jit_requested) {
22571 				bpf_log(log,
22572 					"Extension programs should be JITed\n");
22573 				return -EINVAL;
22574 			}
22575 			/*
22576 			 * How much of the buffer of the tracepoint is used
22577 			 * is checked for the program that is attached to it.
22578 			 */
22579 			if (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) {
22580 				bpf_log(log,
22581 					"Cannot extend a writable raw tracepoint program\n");
22582 				return -EINVAL;
22583 			}
22584 			if (!func_has_rcu_read_lock(tgt_prog, subprog)) {
22585 				bpf_log(log,
22586 					"Cannot extend a function that runs without RCU read lock\n");
22587 				return -EINVAL;
22588 			}
22589 			tgt_changes_pkt_data = aux->func
22590 					       ? aux->func[subprog]->aux->changes_pkt_data
22591 					       : aux->changes_pkt_data;
22592 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
22593 				bpf_log(log,
22594 					"Extension program changes packet data, while original does not\n");
22595 				return -EINVAL;
22596 			}
22597 			if (prog->aux->has_prologue &&
22598 			    bpf_check_ext_prologue(log, tgt_prog, btf_id))
22599 				return -EINVAL;
22600 
22601 			tgt_might_sleep = aux->func
22602 					  ? aux->func[subprog]->aux->might_sleep
22603 					  : aux->might_sleep;
22604 			if (prog->aux->might_sleep && !tgt_might_sleep) {
22605 				bpf_log(log,
22606 					"Extension program may sleep, while original does not\n");
22607 				return -EINVAL;
22608 			}
22609 			/* There is no unwind_goto after the calls of the original */
22610 			if (prog->aux->can_unwind && !tgt_can_unwind) {
22611 				bpf_log(log,
22612 					"Extension program can unwind, while original does not\n");
22613 				return -EINVAL;
22614 			}
22615 		}
22616 		if (!tgt_prog->jited) {
22617 			bpf_log(log, "Can attach to only JITed progs\n");
22618 			return -EINVAL;
22619 		}
22620 		if (prog_tracing) {
22621 			if (aux->attach_tracing_prog) {
22622 				/*
22623 				 * Target program is an fentry/fexit which is already attached
22624 				 * to another tracing program. More levels of nesting
22625 				 * attachment are not allowed.
22626 				 */
22627 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
22628 				return -EINVAL;
22629 			}
22630 		} else if (tgt_prog->type == prog->type) {
22631 			/*
22632 			 * To avoid potential call chain cycles, prevent attaching of a
22633 			 * program extension to another extension. It's ok to attach
22634 			 * fentry/fexit to extension program.
22635 			 */
22636 			bpf_log(log, "Cannot recursively attach\n");
22637 			return -EINVAL;
22638 		}
22639 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
22640 		    prog_extension &&
22641 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
22642 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
22643 		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
22644 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
22645 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
22646 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
22647 			/* Program extensions can extend all program types
22648 			 * except fentry/fexit. The reason is the following.
22649 			 * The fentry/fexit programs are used for performance
22650 			 * analysis, stats and can be attached to any program
22651 			 * type. When extension program is replacing XDP function
22652 			 * it is necessary to allow performance analysis of all
22653 			 * functions. Both original XDP program and its program
22654 			 * extension. Hence attaching fentry/fexit to
22655 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
22656 			 * fentry/fexit was allowed it would be possible to create
22657 			 * long call chain fentry->extension->fentry->extension
22658 			 * beyond reasonable stack size. Hence extending fentry
22659 			 * is not allowed.
22660 			 */
22661 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
22662 			return -EINVAL;
22663 		}
22664 	} else {
22665 		if (prog_extension) {
22666 			bpf_log(log, "Cannot replace kernel functions\n");
22667 			return -EINVAL;
22668 		}
22669 	}
22670 
22671 	switch (prog->expected_attach_type) {
22672 	case BPF_TRACE_RAW_TP:
22673 		if (tgt_prog) {
22674 			bpf_log(log,
22675 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
22676 			return -EINVAL;
22677 		}
22678 		if (!btf_type_is_typedef(t)) {
22679 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
22680 				btf_id);
22681 			return -EINVAL;
22682 		}
22683 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
22684 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22685 				btf_id, tname);
22686 			return -EINVAL;
22687 		}
22688 		tname += sizeof(prefix) - 1;
22689 
22690 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22691 		 * names. Thus using bpf_raw_event_map to get argument names.
22692 		 */
22693 		btp = bpf_get_raw_tracepoint(tname);
22694 		if (!btp)
22695 			return -EINVAL;
22696 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
22697 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
22698 				tname);
22699 			bpf_put_raw_tracepoint(btp);
22700 			return -EINVAL;
22701 		}
22702 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22703 					trace_symbol);
22704 		bpf_put_raw_tracepoint(btp);
22705 
22706 		if (fname)
22707 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22708 
22709 		if (!fname || ret < 0) {
22710 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22711 				prefix, tname);
22712 			t = btf_type_by_id(btf, t->type);
22713 			if (!btf_type_is_ptr(t))
22714 				/* should never happen in valid vmlinux build */
22715 				return -EINVAL;
22716 		} else {
22717 			t = btf_type_by_id(btf, ret);
22718 			if (!btf_type_is_func(t))
22719 				/* should never happen in valid vmlinux build */
22720 				return -EINVAL;
22721 		}
22722 
22723 		t = btf_type_by_id(btf, t->type);
22724 		if (!btf_type_is_func_proto(t))
22725 			/* should never happen in valid vmlinux build */
22726 			return -EINVAL;
22727 
22728 		break;
22729 	case BPF_TRACE_ITER:
22730 		if (!btf_type_is_func(t)) {
22731 			bpf_log(log, "attach_btf_id %u is not a function\n",
22732 				btf_id);
22733 			return -EINVAL;
22734 		}
22735 		t = btf_type_by_id(btf, t->type);
22736 		if (!btf_type_is_func_proto(t))
22737 			return -EINVAL;
22738 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22739 		if (ret)
22740 			return ret;
22741 		break;
22742 	default:
22743 		if (!prog_extension)
22744 			return -EINVAL;
22745 		fallthrough;
22746 	case BPF_MODIFY_RETURN:
22747 	case BPF_LSM_MAC:
22748 	case BPF_LSM_CGROUP:
22749 	case BPF_TRACE_FENTRY:
22750 	case BPF_TRACE_FEXIT:
22751 	case BPF_TRACE_FSESSION:
22752 	case BPF_TRACE_FSESSION_MULTI:
22753 	case BPF_TRACE_FENTRY_MULTI:
22754 	case BPF_TRACE_FEXIT_MULTI:
22755 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
22756 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
22757 		    !bpf_jit_supports_fsession()) {
22758 			bpf_log(log, "JIT does not support fsession\n");
22759 			return -EOPNOTSUPP;
22760 		}
22761 		if (!btf_type_is_func(t)) {
22762 			bpf_log(log, "attach_btf_id %u is not a function\n",
22763 				btf_id);
22764 			return -EINVAL;
22765 		}
22766 		if (prog_extension &&
22767 		    btf_check_type_match(log, prog, btf, t))
22768 			return -EINVAL;
22769 		t = btf_attach_func_proto(log, btf, btf_id);
22770 		if (!t || !btf_type_is_func_proto(t))
22771 			return -EINVAL;
22772 
22773 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22774 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22775 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22776 			return -EINVAL;
22777 
22778 		if (tgt_prog && conservative) {
22779 			if (subprog > 0) {
22780 				ret = check_unreliable_func_args(log, btf, t, tname);
22781 				if (ret)
22782 					return ret;
22783 			}
22784 			t = NULL;
22785 		}
22786 
22787 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22788 		if (ret < 0)
22789 			return ret;
22790 		if (tgt_prog) {
22791 			ret = flatten_bpf_func_model(log, tname, &tgt_info->fmodel);
22792 			if (ret < 0)
22793 				return ret;
22794 		}
22795 
22796 		if (tgt_info->fmodel.ret_size > 8 &&
22797 		    attach_uses_trampoline_retval(prog->expected_attach_type)) {
22798 			bpf_log(log,
22799 				"Attach to function %s with a >8 byte return value is not supported for this attach type\n",
22800 				tname);
22801 			return -EOPNOTSUPP;
22802 		}
22803 
22804 		/*
22805 		 * *.multi programs don't need an address during program
22806 		 * verification, we just take the module ref if needed.
22807 		 */
22808 		if (is_tracing_multi_id(prog, btf_id)) {
22809 			if (btf_is_module(btf)) {
22810 				mod = btf_try_get_module(btf);
22811 				if (!mod)
22812 					return -ENOENT;
22813 			}
22814 			addr = 0;
22815 		} else if (tgt_prog) {
22816 			if (subprog == 0)
22817 				addr = (long) tgt_prog->bpf_func;
22818 			else
22819 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22820 		} else {
22821 			if (btf_is_module(btf)) {
22822 				mod = btf_try_get_module(btf);
22823 				if (mod)
22824 					addr = find_kallsyms_symbol_value(mod, tname);
22825 				else
22826 					addr = 0;
22827 			} else {
22828 				addr = kallsyms_lookup_name(tname);
22829 			}
22830 			if (!addr) {
22831 				module_put(mod);
22832 				bpf_log(log,
22833 					"The address of function %s cannot be found\n",
22834 					tname);
22835 				return -ENOENT;
22836 			}
22837 		}
22838 
22839 		if (prog->sleepable) {
22840 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
22841 			if (ret) {
22842 				module_put(mod);
22843 				bpf_log(log, "%s is not sleepable\n", tname);
22844 				return ret;
22845 			}
22846 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22847 			if (tgt_prog) {
22848 				module_put(mod);
22849 				bpf_log(log, "can't modify return codes of BPF programs\n");
22850 				return -EINVAL;
22851 			}
22852 			ret = -EINVAL;
22853 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22854 			    !check_attach_modify_return(addr, tname))
22855 				ret = 0;
22856 			if (ret) {
22857 				module_put(mod);
22858 				bpf_log(log, "%s() is not modifiable\n", tname);
22859 				return ret;
22860 			}
22861 		}
22862 
22863 		break;
22864 	}
22865 	tgt_info->tgt_addr = addr;
22866 	tgt_info->tgt_name = tname;
22867 	tgt_info->tgt_type = t;
22868 	tgt_info->tgt_mod = mod;
22869 	return 0;
22870 }
22871 
22872 BTF_SET_START(btf_id_deny)
22873 BTF_ID_UNUSED
22874 #ifdef CONFIG_SMP
22875 BTF_ID(func, ___migrate_enable)
22876 BTF_ID(func, migrate_disable)
22877 BTF_ID(func, migrate_enable)
22878 #endif
22879 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22880 BTF_ID(func, rcu_read_unlock_strict)
22881 #endif
22882 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22883 BTF_ID(func, preempt_count_add)
22884 BTF_ID(func, preempt_count_sub)
22885 #endif
22886 #ifdef CONFIG_PREEMPT_RCU
22887 BTF_ID(func, __rcu_read_lock)
22888 BTF_ID(func, __rcu_read_unlock)
22889 #endif
22890 BTF_SET_END(btf_id_deny)
22891 
22892 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
22893  * Currently, we must manually list all __noreturn functions here. Once a more
22894  * robust solution is implemented, this workaround can be removed.
22895  */
22896 BTF_SET_START(noreturn_deny)
22897 #ifdef CONFIG_IA32_EMULATION
22898 BTF_ID(func, __ia32_sys_exit)
22899 BTF_ID(func, __ia32_sys_exit_group)
22900 #endif
22901 #ifdef CONFIG_KUNIT
22902 BTF_ID(func, __kunit_abort)
22903 BTF_ID(func, kunit_try_catch_throw)
22904 #endif
22905 #ifdef CONFIG_MODULES
22906 BTF_ID(func, __module_put_and_kthread_exit)
22907 #endif
22908 #ifdef CONFIG_X86_64
22909 BTF_ID(func, __x64_sys_exit)
22910 BTF_ID(func, __x64_sys_exit_group)
22911 #endif
22912 BTF_ID(func, do_exit)
22913 BTF_ID(func, do_group_exit)
22914 BTF_ID(func, kthread_complete_and_exit)
22915 BTF_ID(func, make_task_dead)
22916 BTF_SET_END(noreturn_deny)
22917 
22918 static bool can_be_sleepable(struct bpf_prog *prog)
22919 {
22920 	if (prog->type == BPF_PROG_TYPE_TRACING) {
22921 		switch (prog->expected_attach_type) {
22922 		case BPF_TRACE_FENTRY:
22923 		case BPF_TRACE_FEXIT:
22924 		case BPF_MODIFY_RETURN:
22925 		case BPF_TRACE_ITER:
22926 		case BPF_TRACE_FSESSION:
22927 		case BPF_TRACE_RAW_TP:
22928 		case BPF_TRACE_FENTRY_MULTI:
22929 		case BPF_TRACE_FEXIT_MULTI:
22930 		case BPF_TRACE_FSESSION_MULTI:
22931 			return true;
22932 		default:
22933 			return false;
22934 		}
22935 	}
22936 	if (prog->type == BPF_PROG_TYPE_LSM)
22937 		return prog->expected_attach_type != BPF_LSM_CGROUP;
22938 
22939 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22940 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
22941 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
22942 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
22943 }
22944 
22945 static int check_attach_btf_id(struct bpf_verifier_env *env)
22946 {
22947 	struct bpf_prog *prog = env->prog;
22948 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22949 	struct bpf_attach_target_info tgt_info = {};
22950 	u32 btf_id = prog->aux->attach_btf_id;
22951 	struct bpf_trampoline *tr;
22952 	int ret;
22953 	u64 key;
22954 
22955 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22956 		if (prog->sleepable)
22957 			/* attach_btf_id checked to be zero already */
22958 			return 0;
22959 		verbose(env, "Syscall programs can only be sleepable\n");
22960 		return -EINVAL;
22961 	}
22962 
22963 	if (prog->sleepable && !can_be_sleepable(prog)) {
22964 		verbose(env, "Program of this type cannot be sleepable\n");
22965 		return -EINVAL;
22966 	}
22967 
22968 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22969 		return check_struct_ops_btf_id(env);
22970 
22971 	if (prog->type != BPF_PROG_TYPE_TRACING &&
22972 	    prog->type != BPF_PROG_TYPE_LSM &&
22973 	    prog->type != BPF_PROG_TYPE_EXT)
22974 		return 0;
22975 
22976 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22977 	if (ret)
22978 		return ret;
22979 
22980 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22981 		/* to make freplace equivalent to their targets, they need to
22982 		 * inherit env->ops and expected_attach_type for the rest of the
22983 		 * verification
22984 		 */
22985 		env->ops = bpf_verifier_ops[tgt_prog->type];
22986 		prog->expected_attach_type = tgt_prog->expected_attach_type;
22987 	}
22988 
22989 	/* store info about the attachment target that will be used later */
22990 	prog->aux->attach_func_proto = tgt_info.tgt_type;
22991 	prog->aux->attach_func_name = tgt_info.tgt_name;
22992 	prog->aux->mod = tgt_info.tgt_mod;
22993 
22994 	if (tgt_prog) {
22995 		prog->aux->saved_dst_prog_type = tgt_prog->type;
22996 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22997 	}
22998 
22999 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23000 		prog->aux->attach_btf_trace = true;
23001 		return 0;
23002 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23003 		return bpf_iter_prog_supported(prog);
23004 	}
23005 
23006 	if (prog->type == BPF_PROG_TYPE_LSM) {
23007 		ret = bpf_lsm_verify_prog(&env->log, prog);
23008 		if (ret < 0)
23009 			return ret;
23010 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23011 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23012 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23013 			tgt_info.tgt_name);
23014 		return -EINVAL;
23015 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23016 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
23017 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
23018 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23019 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23020 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
23021 			tgt_info.tgt_name);
23022 		return -EINVAL;
23023 	}
23024 
23025 	/*
23026 	 * We don't get trampoline for tracing_multi programs at this point,
23027 	 * it's done when tracing_multi link is created.
23028 	 */
23029 	if (prog->type == BPF_PROG_TYPE_TRACING &&
23030 	    is_tracing_multi(prog->expected_attach_type))
23031 		return 0;
23032 
23033 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23034 	tr = bpf_trampoline_get(key, &tgt_info);
23035 	if (!tr)
23036 		return -ENOMEM;
23037 
23038 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
23039 		bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX);
23040 
23041 	prog->aux->dst_trampoline = tr;
23042 	return 0;
23043 }
23044 
23045 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
23046 				  struct bpf_attach_target_info *tgt_info)
23047 {
23048 	const struct btf_type *t;
23049 	unsigned long addr;
23050 	const char *tname;
23051 	int err;
23052 
23053 	if (!btf_id || !btf)
23054 		return -EINVAL;
23055 
23056 	/* Check noreturn attachment. */
23057 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
23058 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
23059 	     btf_id_set_contains(&noreturn_deny, btf_id))
23060 		return -EINVAL;
23061 	/* Check denied attachment. */
23062 	if (btf_id_set_contains(&btf_id_deny, btf_id))
23063 		return -EINVAL;
23064 
23065 	/* Check and get function target data. */
23066 	t = btf_type_by_id(btf, btf_id);
23067 	if (!t)
23068 		return -EINVAL;
23069 	tname = btf_name_by_offset(btf, t->name_off);
23070 	if (!tname)
23071 		return -EINVAL;
23072 	t = btf_attach_func_proto(NULL, btf, btf_id);
23073 	if (!t || !btf_type_is_func_proto(t))
23074 		return -EINVAL;
23075 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
23076 	if (err < 0)
23077 		return err;
23078 	if (tgt_info->fmodel.ret_size > 8 &&
23079 	    attach_uses_trampoline_retval(prog->expected_attach_type))
23080 		return -EOPNOTSUPP;
23081 	if (btf_is_module(btf)) {
23082 		/* The bpf program already holds reference to module. */
23083 		if (WARN_ON_ONCE(!prog->aux->mod))
23084 			return -EINVAL;
23085 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
23086 	} else {
23087 		addr = kallsyms_lookup_name(tname);
23088 	}
23089 	if (!addr || !ftrace_location(addr))
23090 		return -ENOENT;
23091 
23092 	/* Check sleepable program attachment. */
23093 	if (prog->sleepable) {
23094 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
23095 		if (err)
23096 			return err;
23097 	}
23098 	tgt_info->tgt_addr = addr;
23099 	return 0;
23100 }
23101 
23102 struct btf *bpf_get_btf_vmlinux(void)
23103 {
23104 	/* Pairs with the smp_store_release() on the parse path below. */
23105 	struct btf *btf = smp_load_acquire(&btf_vmlinux);
23106 
23107 	if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
23108 		mutex_lock(&btf_vmlinux_lock);
23109 		btf = btf_vmlinux;
23110 		if (!btf) {
23111 			btf = btf_parse_vmlinux();
23112 			/*
23113 			 * Order the parsed BTF contents and the globals the
23114 			 * parse populated (e.g. bpf_ctx_convert.t) before
23115 			 * the pointer publication. Pairs with the acquire
23116 			 * on the lockless fast path above.
23117 			 */
23118 			smp_store_release(&btf_vmlinux, btf);
23119 		}
23120 		mutex_unlock(&btf_vmlinux_lock);
23121 	}
23122 	return btf;
23123 }
23124 
23125 /*
23126  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
23127  * this case expect that every file descriptor in the array is either a map or
23128  * a BTF. Everything else is considered to be trash.
23129  */
23130 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd)
23131 {
23132 	struct bpf_map *map;
23133 	struct btf *btf;
23134 	CLASS(fd, f)(fd);
23135 	int err;
23136 
23137 	map = __bpf_map_get(f);
23138 	if (!IS_ERR(map)) {
23139 		err = __add_used_map(env, map);
23140 		if (err < 0)
23141 			return err;
23142 		fd_slot_set_map(&env->fd_array[idx], map);
23143 		return 0;
23144 	}
23145 
23146 	btf = __btf_get_by_fd(f);
23147 	if (!IS_ERR(btf)) {
23148 		btf_get(btf);
23149 		err = __add_used_btf(env, btf);
23150 		if (err < 0)
23151 			return err;
23152 		fd_slot_set_btf(&env->fd_array[idx], btf);
23153 		return 0;
23154 	}
23155 
23156 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
23157 	return PTR_ERR(map);
23158 }
23159 
23160 /*
23161  * A continuous fd_array is resolved into an in-memory cache with one slot
23162  * per entry. The bound here is deliberately generous and not derived from
23163  * the per-program object limits: Duplicate entries /are/ permitted, and
23164  * the number of distinct maps and BTFs a program can bind is enforced when
23165  * each entry is resolved by __add_used_map() and __add_used_btf().
23166  */
23167 #define MAX_FD_ARRAY_CNT 4096
23168 
23169 static int process_fd_array_continuous(struct bpf_verifier_env *env,
23170 				       bpfptr_t fd_array, u32 cnt)
23171 {
23172 	int fd, ret;
23173 	u32 i;
23174 
23175 	if (cnt > MAX_FD_ARRAY_CNT) {
23176 		verbose(env, "fd_array has too many entries (%u, max %u)\n",
23177 			cnt, MAX_FD_ARRAY_CNT);
23178 		return -E2BIG;
23179 	}
23180 
23181 	env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT);
23182 	if (!env->fd_array)
23183 		return -ENOMEM;
23184 	env->fd_array_cnt = cnt;
23185 	for (i = 0; i < cnt; i++) {
23186 		if (copy_from_bpfptr_offset(&fd, fd_array,
23187 					    (size_t)i * sizeof(fd), sizeof(fd)))
23188 			return -EFAULT;
23189 		ret = add_fd_from_fd_array(env, i, fd);
23190 		if (ret)
23191 			return ret;
23192 	}
23193 	return 0;
23194 }
23195 
23196 static int process_fd_array(struct bpf_verifier_env *env,
23197 			    union bpf_attr *attr, bpfptr_t uattr)
23198 {
23199 	bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
23200 
23201 	if (bpfptr_is_null(fd_array)) {
23202 		if (attr->fd_array_cnt) {
23203 			verbose(env, "fd_array_cnt %u without fd_array is invalid\n",
23204 				attr->fd_array_cnt);
23205 			return -EINVAL;
23206 		}
23207 		return 0;
23208 	}
23209 	/*
23210 	 * New API: the caller passes fd_array_cnt and a continuous array that
23211 	 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep
23212 	 * the caller's array and resolve entries on the spot at each reference.
23213 	 */
23214 	if (attr->fd_array_cnt)
23215 		return process_fd_array_continuous(env, fd_array,
23216 						   attr->fd_array_cnt);
23217 	env->fd_array_raw = fd_array;
23218 	return 0;
23219 }
23220 
23221 /* replace a generic kfunc with a specialized version if necessary */
23222 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
23223 {
23224 	struct bpf_prog *prog = env->prog;
23225 	bool seen_direct_write;
23226 	void *xdp_kfunc;
23227 	bool is_rdonly;
23228 	u32 func_id = desc->func_id;
23229 	u16 offset = desc->offset;
23230 	unsigned long addr = desc->addr;
23231 
23232 	if (offset) /* return if module BTF is used */
23233 		return 0;
23234 
23235 	if (bpf_dev_bound_kfunc_id(func_id)) {
23236 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
23237 		if (xdp_kfunc)
23238 			addr = (unsigned long)xdp_kfunc;
23239 		/* fallback to default kfunc when not supported by netdev */
23240 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
23241 		seen_direct_write = env->seen_direct_write;
23242 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
23243 
23244 		if (is_rdonly)
23245 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
23246 
23247 		/* restore env->seen_direct_write to its original value, since
23248 		 * may_access_direct_pkt_data mutates it
23249 		 */
23250 		env->seen_direct_write = seen_direct_write;
23251 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
23252 		if (bpf_lsm_has_d_inode_locked(prog))
23253 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
23254 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
23255 		if (bpf_lsm_has_d_inode_locked(prog))
23256 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
23257 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
23258 		if (!env->insn_aux_data[insn_idx].non_sleepable)
23259 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
23260 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
23261 		if (env->insn_aux_data[insn_idx].non_sleepable)
23262 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
23263 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
23264 		if (env->insn_aux_data[insn_idx].non_sleepable)
23265 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
23266 	}
23267 	desc->addr = addr;
23268 	return 0;
23269 }
23270 
23271 static int add_kfunc_desc_target(struct bpf_verifier_env *env,
23272 				 const struct bpf_kfunc_desc *target_desc,
23273 				 u16 base_desc_idx, u16 *desc_idx)
23274 {
23275 	struct bpf_kfunc_desc desc = *target_desc;
23276 	struct bpf_kfunc_desc_tab *new_tab;
23277 	struct bpf_kfunc_desc_tab *tab;
23278 	struct bpf_prog_aux *prog_aux;
23279 	u32 i;
23280 
23281 	prog_aux = env->prog->aux;
23282 	tab = prog_aux->kfunc_tab;
23283 
23284 	if (base_desc_idx >= tab->nr_base_descs) {
23285 		verifier_bug(env, "kfunc desc_idx %d out of bounds (%d descriptors)",
23286 				base_desc_idx, tab->nr_base_descs);
23287 		return -EFAULT;
23288 	}
23289 	if (tab->descs[base_desc_idx].func_id != desc.func_id) {
23290 		verifier_bug(env, "kfunc desc %d has invalid id (expected %d, got %d)",
23291 				base_desc_idx, tab->descs[base_desc_idx].func_id, desc.func_id);
23292 		return -EFAULT;
23293 	}
23294 	if (tab->descs[base_desc_idx].offset != desc.offset) {
23295 		verifier_bug(env, "kfunc desc %d has invalid offset (expected %d, got %d)",
23296 				base_desc_idx, tab->descs[base_desc_idx].offset, desc.offset);
23297 		return -EFAULT;
23298 	}
23299 
23300 	if (tab->descs[base_desc_idx].addr == desc.addr) {
23301 		*desc_idx = base_desc_idx;
23302 		return 0;
23303 	}
23304 
23305 	for (i = tab->nr_base_descs; i < tab->nr_descs; i++) {
23306 		if (tab->descs[i].func_id == desc.func_id &&
23307 		    tab->descs[i].offset == desc.offset &&
23308 		    tab->descs[i].addr == desc.addr) {
23309 			*desc_idx = i;
23310 			return 0;
23311 		}
23312 	}
23313 
23314 	if (tab->nr_descs == MAX_KFUNC_CALL_DESCS) {
23315 		verbose(env, "too many different kernel function call targets\n");
23316 		return -E2BIG;
23317 	}
23318 
23319 	new_tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1),
23320 			   GFP_KERNEL_ACCOUNT);
23321 	if (!new_tab)
23322 		return -ENOMEM;
23323 	tab = new_tab;
23324 	prog_aux->kfunc_tab = tab;
23325 
23326 	*desc_idx = tab->nr_descs;
23327 	tab->descs[tab->nr_descs++] = desc;
23328 	return 0;
23329 }
23330 
23331 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
23332 					    u16 struct_meta_reg,
23333 					    u16 node_offset_reg,
23334 					    struct bpf_insn *insn,
23335 					    struct bpf_insn *insn_buf,
23336 					    int *cnt)
23337 {
23338 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
23339 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
23340 
23341 	insn_buf[0] = addr[0];
23342 	insn_buf[1] = addr[1];
23343 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
23344 	insn_buf[3] = *insn;
23345 	*cnt = 4;
23346 }
23347 
23348 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
23349 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
23350 {
23351 	struct bpf_kfunc_desc desc_copy;
23352 	struct bpf_kfunc_desc *desc;
23353 	unsigned long call_imm;
23354 	u16 base_desc_idx, desc_idx;
23355 	bool near_call;
23356 	int err;
23357 
23358 	if (!insn->imm) {
23359 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
23360 		return -EINVAL;
23361 	}
23362 
23363 	*cnt = 0;
23364 
23365 	/* insn->imm has the btf func_id. Replace it with an offset relative to
23366 	 * __bpf_call_base, unless the JIT needs to call functions that are
23367 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
23368 	 */
23369 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
23370 	if (!desc) {
23371 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
23372 			     insn->imm);
23373 		return -EFAULT;
23374 	}
23375 	base_desc_idx = desc - env->prog->aux->kfunc_tab->descs;
23376 
23377 	near_call = !bpf_jit_supports_far_kfunc_call();
23378 	desc_copy = *desc;
23379 	desc = &desc_copy;
23380 
23381 	err = specialize_kfunc(env, desc, insn_idx);
23382 	if (err)
23383 		return err;
23384 
23385 	if (near_call) {
23386 		call_imm = BPF_CALL_IMM(desc->addr);
23387 		if ((unsigned long)(s32)call_imm != call_imm) {
23388 			verbose(env, "address of kernel func_id %u is out of range\n",
23389 				desc->func_id);
23390 			return -EINVAL;
23391 		}
23392 		insn->imm = call_imm;
23393 	}
23394 
23395 	err = add_kfunc_desc_target(env, desc, base_desc_idx, &desc_idx);
23396 	if (err)
23397 		return err;
23398 	insn->off = desc_idx;
23399 
23400 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
23401 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23402 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23403 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
23404 
23405 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
23406 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23407 				     insn_idx);
23408 			return -EFAULT;
23409 		}
23410 
23411 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
23412 		insn_buf[1] = addr[0];
23413 		insn_buf[2] = addr[1];
23414 		insn_buf[3] = *insn;
23415 		*cnt = 4;
23416 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
23417 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
23418 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
23419 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23420 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
23421 
23422 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
23423 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
23424 				     insn_idx);
23425 			return -EFAULT;
23426 		}
23427 
23428 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
23429 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23430 				     insn_idx);
23431 			return -EFAULT;
23432 		}
23433 
23434 		insn_buf[0] = addr[0];
23435 		insn_buf[1] = addr[1];
23436 		insn_buf[2] = *insn;
23437 		*cnt = 3;
23438 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
23439 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
23440 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
23441 		int struct_meta_reg = BPF_REG_3;
23442 		int node_offset_reg = BPF_REG_4;
23443 
23444 		/* list_add/rbtree_add have an extra arg (prev/less),
23445 		 * so args-to-fixup are in diff regs.
23446 		 */
23447 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
23448 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
23449 			struct_meta_reg = BPF_REG_4;
23450 			node_offset_reg = BPF_REG_5;
23451 		}
23452 
23453 		if (!kptr_struct_meta) {
23454 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
23455 				     insn_idx);
23456 			return -EFAULT;
23457 		}
23458 
23459 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
23460 						node_offset_reg, insn, insn_buf, cnt);
23461 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
23462 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
23463 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23464 		*cnt = 1;
23465 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
23466 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
23467 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
23468 
23469 		/*
23470 		 * inline the bpf_session_is_return() for fsession:
23471 		 *   bool bpf_session_is_return(void *ctx)
23472 		 *   {
23473 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
23474 		 *   }
23475 		 */
23476 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23477 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
23478 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
23479 		*cnt = 3;
23480 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
23481 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
23482 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
23483 		/*
23484 		 * inline bpf_session_cookie() for fsession:
23485 		 *   __u64 *bpf_session_cookie(void *ctx)
23486 		 *   {
23487 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
23488 		 *       return &((u64 *)ctx)[-off];
23489 		 *   }
23490 		 */
23491 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23492 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
23493 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
23494 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23495 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
23496 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
23497 		*cnt = 6;
23498 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) {
23499 		/* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */
23500 		int i = 0;
23501 
23502 		/* if (start > end) goto einval; */
23503 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8);
23504 		/* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */
23505 		insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3);
23506 		insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2);
23507 		insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8);
23508 		/* s->cur = start - 1; s->end = end; return 0; */
23509 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1);
23510 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0);
23511 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4);
23512 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23513 		insn_buf[i++] = BPF_JMP_A(5);
23514 		/* einval: s->cur = s->end = 0; return -EINVAL; */
23515 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23516 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23517 		insn_buf[i++] = BPF_JMP_A(2);
23518 		/* e2big: s->cur = s->end = 0; return -E2BIG; */
23519 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23520 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
23521 		*cnt = i;
23522 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) {
23523 		/* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */
23524 		int i = 0;
23525 
23526 		/* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */
23527 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0);
23528 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1);
23529 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4);
23530 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3);
23531 		/* s->cur = r0; return &s->cur; */
23532 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0);
23533 		insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
23534 		insn_buf[i++] = BPF_JMP_A(2);
23535 		/* done: s->cur = s->end = 0; return NULL; */
23536 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
23537 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
23538 		*cnt = i;
23539 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) {
23540 		/* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */
23541 		insn_buf[0] = BPF_JMP_A(0);
23542 		*cnt = 1;
23543 	}
23544 
23545 	if (env->insn_aux_data[insn_idx].arg_prog) {
23546 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
23547 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
23548 		int idx = *cnt;
23549 
23550 		insn_buf[idx++] = ld_addrs[0];
23551 		insn_buf[idx++] = ld_addrs[1];
23552 		insn_buf[idx++] = *insn;
23553 		*cnt = idx;
23554 	}
23555 	return 0;
23556 }
23557 
23558 /*
23559  * Upper bound on the PKCS#7 signature blob passed with a program. Comfortably
23560  * above the largest signature the kernel can verify, and far below anything
23561  * that would make rejecting a load expensive. Deliberately a fixed number so
23562  * that what the syscall accepts does not depend on PAGE_SIZE.
23563  */
23564 #define BPF_PROG_MAX_SIGNATURE_SIZE	(64 * 1024)
23565 
23566 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id)
23567 {
23568 	switch (keyring_id) {
23569 	case 0:
23570 		return BPF_SIG_KEYRING_BUILTIN;
23571 	case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING:
23572 		return BPF_SIG_KEYRING_SECONDARY;
23573 	case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING:
23574 		return BPF_SIG_KEYRING_PLATFORM;
23575 	case KEY_SPEC_BPF_KEYRING:
23576 		return BPF_SIG_KEYRING_BPF;
23577 	default:
23578 		return BPF_SIG_KEYRING_USER;
23579 	}
23580 }
23581 
23582 /*
23583  * Verify the PKCS#7 signature of a loaded program. Called from bpf_check()
23584  * once the program's metadata maps have been resolved into used_maps, so
23585  * the exact maps folded into the signature are the ones the program binds.
23586  *
23587  * The signature covers the instructions followed by the frozen contents of
23588  * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the
23589  * verdict and keyring info are recorded on prog->aux.
23590  */
23591 static int bpf_prog_verify_signature(struct bpf_verifier_env *env,
23592 				     union bpf_attr *attr, bool is_kernel)
23593 {
23594 	bpfptr_t usig = make_bpfptr(attr->signature, is_kernel);
23595 	struct bpf_dynptr_kern sig_ptr, data_ptr;
23596 	struct bpf_prog *prog = env->prog;
23597 	struct bpf_map **maps = env->used_maps;
23598 	struct bpf_key *key = NULL;
23599 	void *sig, *data = NULL;
23600 	u32 map_cnt = env->used_map_cnt;
23601 	u32 i, off, insns_sz;
23602 	u64 data_sz;
23603 	int err = 0;
23604 
23605 	/*
23606 	 * The signature covers the insns as submitted. CO-RE relocations would
23607 	 * have the kernel rewrite them afterwards, with values the loader picks
23608 	 * through the BTF it supplies, see bpf_check_core_relo().
23609 	 */
23610 	if (attr->core_relo_cnt) {
23611 		verbose(env, "signed program cannot carry CO-RE relocations\n");
23612 		return -EACCES;
23613 	}
23614 	if (!attr->signature_size ||
23615 	    attr->signature_size > BPF_PROG_MAX_SIGNATURE_SIZE)
23616 		return -EINVAL;
23617 
23618 	if (system_keyring_id_check(attr->keyring_id) == 0) {
23619 		key = bpf_lookup_system_key(attr->keyring_id);
23620 	} else if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23621 		key = bpf_lookup_keyring();
23622 	} else if (bpf_keyring_enforced()) {
23623 		verbose(env, "caller-supplied keyring refused, use bpf keyring\n");
23624 		return -EPERM;
23625 	} else {
23626 		key = bpf_lookup_user_key(attr->keyring_id, 0);
23627 	}
23628 	if (!key) {
23629 		if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) {
23630 			verbose(env, "the bpf keyring is empty or has not been restricted\n");
23631 			return -ENOKEY;
23632 		}
23633 		verbose(env, "cannot resolve signing keyring with keyring_id %d\n",
23634 			attr->keyring_id);
23635 		return -EINVAL;
23636 	}
23637 
23638 	sig = kvmemdup_bpfptr(usig, attr->signature_size);
23639 	if (IS_ERR(sig)) {
23640 		bpf_key_put(key);
23641 		return PTR_ERR(sig);
23642 	}
23643 
23644 	insns_sz = prog->len * sizeof(struct bpf_insn);
23645 	data_sz = insns_sz;
23646 	for (i = 0; i < map_cnt; i++) {
23647 		struct bpf_map *map = maps[i];
23648 
23649 		if (map->map_type != BPF_MAP_TYPE_ARRAY ||
23650 		    !map->ops->map_direct_value_addr) {
23651 			verbose(env, "signed program metadata map '%s' must be an array\n",
23652 				map->name);
23653 			err = -EINVAL;
23654 			goto out;
23655 		}
23656 		if (!READ_ONCE(map->frozen)) {
23657 			verbose(env, "signed program metadata map '%s' must be frozen\n",
23658 				map->name);
23659 			err = -EPERM;
23660 			goto out;
23661 		}
23662 		if (bpf_map_write_active(map)) {
23663 			verbose(env, "signed program metadata map '%s' has active writers\n",
23664 				map->name);
23665 			err = -EBUSY;
23666 			goto out;
23667 		}
23668 		if (!map->excl_prog_sha) {
23669 			verbose(env, "signed program metadata map '%s' must be exclusive\n",
23670 				map->name);
23671 			err = -EPERM;
23672 			goto out;
23673 		}
23674 		data_sz += map->value_size;
23675 	}
23676 	if (bpf_dynptr_check_size(data_sz)) {
23677 		verbose(env, "signed payload too large: %llu bytes\n", data_sz);
23678 		err = -E2BIG;
23679 		goto out;
23680 	}
23681 	data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
23682 	if (!data) {
23683 		err = -ENOMEM;
23684 		goto out;
23685 	}
23686 	memcpy(data, prog->insnsi, insns_sz);
23687 	off = insns_sz;
23688 	for (i = 0; i < map_cnt; i++) {
23689 		struct bpf_map *map = maps[i];
23690 		u64 addr;
23691 
23692 		err = map->ops->map_direct_value_addr(map, &addr, 0);
23693 		if (err) {
23694 			verbose(env, "failed to read signed metadata map '%s': %d\n",
23695 				map->name, err);
23696 			goto out;
23697 		}
23698 		memcpy(data + off, (void *)(unsigned long)addr,
23699 		       map->value_size);
23700 		off += map->value_size;
23701 	}
23702 
23703 	bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz);
23704 	bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0,
23705 			attr->signature_size);
23706 
23707 	err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr,
23708 					 (struct bpf_dynptr *)&sig_ptr, key);
23709 	if (err) {
23710 		verbose(env, "signature verification failed: %d\n", err);
23711 	} else {
23712 		verbose(env, "signature verification passed\n");
23713 		prog->aux->sig.keyring_serial = bpf_key_serial(key);
23714 		prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id);
23715 		prog->aux->sig.verdict = BPF_SIG_VERIFIED;
23716 	}
23717 out:
23718 	kvfree(data);
23719 	bpf_key_put(key);
23720 	kvfree(sig);
23721 	return err;
23722 }
23723 
23724 /*
23725  * bpf_clone_redirect() transmits from inside the program, so a tc egress or
23726  * lwt_xmit program that redirects to its own device runs again on top of its
23727  * own frame, and again from there, until the datapath's recursion limit drops
23728  * the packet: ten frames deep. Ten MAX_BPF_STACK frames fit the kernel stack
23729  * as they always did; ten MAX_BPF_STACK_JIT frames would not, so a program
23730  * calling it keeps the smaller budget. The redirect helpers that transmit
23731  * after the program has returned leave no frame behind.
23732  */
23733 static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)
23734 {
23735 	const struct bpf_insn *insn = prog->insnsi;
23736 	int i;
23737 
23738 	for (i = 0; i < prog->len; i++, insn++)
23739 		if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_clone_redirect)
23740 			return true;
23741 	return false;
23742 }
23743 
23744 /* Various log level 2 information about the program */
23745 static void log_program(struct bpf_verifier_env *env)
23746 {
23747 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
23748 	struct bpf_insn *insns = env->prog->insnsi;
23749 	u32 insn_cnt = env->prog->len;
23750 	u64 pos, insn_pos;
23751 	u32 i, j;
23752 
23753 	verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
23754 	for (i = 0; i < insn_cnt; ++i) {
23755 		verbose_linfo(env, i, "    ; ");
23756 		if (env->insn_aux_data[i].scc)
23757 			verbose(env, "%3d ", env->insn_aux_data[i].scc);
23758 		else
23759 			verbose(env, "    ");
23760 		if (env->insn_aux_data[i].loop_header >= 0)
23761 			verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
23762 		else
23763 			verbose(env, "    ");
23764 		verbose(env, "%3d ", env->idoms[i]);
23765 		verbose(env, "%3d: ", i);
23766 		for (j = BPF_REG_0; j < BPF_REG_10; ++j)
23767 			if (insn_aux[i].live_regs_before & BIT(j))
23768 				verbose(env, "%d", j);
23769 			else
23770 				verbose(env, ".");
23771 		verbose(env, " ");
23772 		pos = env->log.end_pos;
23773 		bpf_verbose_insn(env, &insns[i]);
23774 		insn_pos = env->log.end_pos;
23775 		if (insn_aux[i].zext_dst)
23776 			verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
23777 		verbose(env, "\n");
23778 		if (bpf_is_ldimm64(&insns[i]))
23779 			i++;
23780 	}
23781 }
23782 
23783 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
23784 	      struct bpf_log_attr *attr_log)
23785 {
23786 	u64 start_time = ktime_get_ns();
23787 	struct bpf_verifier_env *env;
23788 	int i, len, ret = -EINVAL, err;
23789 	bool is_priv;
23790 
23791 	BTF_TYPE_EMIT(enum bpf_features);
23792 
23793 	/* no program is valid */
23794 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
23795 		return -EINVAL;
23796 
23797 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
23798 	 * allocate/free it every time bpf_check() is called
23799 	 */
23800 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
23801 	if (!env)
23802 		return -ENOMEM;
23803 
23804 	env->bt.env = env;
23805 	env->prog = *prog;
23806 	env->ops = bpf_verifier_ops[env->prog->type];
23807 	env->stack_limit = bpf_prog_stack_limit(env->prog);
23808 	if (bpf_prog_reenters_datapath(env->prog))
23809 		env->stack_limit = MAX_BPF_STACK;
23810 
23811 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
23812 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
23813 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
23814 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
23815 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
23816 	env->signature = attr->signature;
23817 
23818 	/* user could have requested verbose verifier output
23819 	 * and supplied buffer to store the verification trace
23820 	 */
23821 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
23822 	if (ret)
23823 		goto err_free_env;
23824 	ret = bpf_diag_init(env);
23825 	if (ret)
23826 		goto err_prep;
23827 	if (env->prog->insnsi[env->prog->len - 1].code == (BPF_LD | BPF_IMM | BPF_DW)) {
23828 		verbose(env, "invalid bpf_ld_imm64 insn\n");
23829 		ret = -EINVAL;
23830 		goto err_prep;
23831 	}
23832 
23833 	ret = process_fd_array(env, attr, uattr);
23834 	if (ret)
23835 		goto err_prep;
23836 
23837 	if (env->signature) {
23838 		ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel);
23839 		if (ret)
23840 			goto err_prep;
23841 	}
23842 
23843 	ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token,
23844 				     uattr.is_kernel);
23845 	if (ret)
23846 		goto err_prep;
23847 
23848 	bpf_get_btf_vmlinux();
23849 
23850 	/* Serialize verification of unprivileged programs. */
23851 	if (!is_priv)
23852 		mutex_lock(&bpf_verifier_lock);
23853 
23854 	len = env->insn_aux_data_len = env->prog->len;
23855 	env->insn_aux_data =
23856 		__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),
23857 			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
23858 	ret = -ENOMEM;
23859 	if (!env->insn_aux_data)
23860 		goto skip_full_check;
23861 	for (i = 0; i < len; i++)
23862 		env->insn_aux_data[i].orig_idx = i;
23863 	env->succ = bpf_iarray_realloc(NULL, 2);
23864 	if (!env->succ)
23865 		goto skip_full_check;
23866 
23867 	mark_verifier_state_clean(env);
23868 
23869 	if (IS_ERR(btf_vmlinux)) {
23870 		/* Either gcc or pahole or kernel are broken. */
23871 		verbose(env, "in-kernel BTF is malformed\n");
23872 		ret = PTR_ERR(btf_vmlinux);
23873 		goto skip_full_check;
23874 	}
23875 
23876 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
23877 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
23878 		env->strict_alignment = true;
23879 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
23880 		env->strict_alignment = false;
23881 
23882 	if (is_priv)
23883 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
23884 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
23885 	env->arena_scalar = attr->prog_flags & BPF_F_ARENA_SCALAR;
23886 
23887 	env->explored_states = kvzalloc_objs(struct list_head,
23888 					     state_htab_size(env),
23889 					     GFP_KERNEL_ACCOUNT);
23890 	ret = -ENOMEM;
23891 	if (!env->explored_states)
23892 		goto skip_full_check;
23893 
23894 	for (i = 0; i < state_htab_size(env); i++)
23895 		INIT_LIST_HEAD(&env->explored_states[i]);
23896 	INIT_LIST_HEAD(&env->free_list);
23897 
23898 	/* Prepare BTF and func_info needed to discover all subprograms. */
23899 	ret = bpf_prepare_btf_info(env, attr, uattr);
23900 	if (ret < 0)
23901 		goto skip_full_check;
23902 
23903 	/* Apply CO-RE before validating the program's instruction layout. */
23904 	ret = bpf_check_core_relo(env, attr, uattr);
23905 	if (ret < 0)
23906 		goto skip_full_check;
23907 
23908 	/* Discover all subprograms and collect the properties needed by BTF validation. */
23909 	ret = add_subprogs(env);
23910 	if (ret < 0)
23911 		goto skip_full_check;
23912 
23913 	find_subprog_properties(env);
23914 
23915 	/* Validate BTF before reporting subprogram layout errors. */
23916 	ret = bpf_check_btf_info(env, attr, uattr);
23917 	if (ret < 0)
23918 		goto skip_full_check;
23919 
23920 	ret = check_subprogs(env);
23921 	if (ret < 0)
23922 		goto skip_full_check;
23923 
23924 	/* Validate instructions and resolve the program's referenced resources. */
23925 	ret = check_and_resolve_insns(env);
23926 	if (ret < 0)
23927 		goto skip_full_check;
23928 
23929 	/* Find pointers to functions in the read-only maps of the program. */
23930 	ret = resolve_func_ptrs(env);
23931 	if (ret < 0)
23932 		goto skip_full_check;
23933 
23934 	/* Build kfunc prototypes after resolving program resources. */
23935 	ret = add_kfuncs(env);
23936 	if (ret < 0)
23937 		goto skip_full_check;
23938 
23939 	if (bpf_prog_is_offloaded(env->prog->aux)) {
23940 		ret = bpf_prog_offload_verifier_prep(env->prog);
23941 		if (ret)
23942 			goto skip_full_check;
23943 	}
23944 
23945 	ret = bpf_check_cfg(env);
23946 	if (ret < 0)
23947 		goto skip_full_check;
23948 
23949 	ret = check_unwind_insns(env);
23950 	if (ret < 0)
23951 		goto skip_full_check;
23952 
23953 	ret = bpf_compute_postorder(env);
23954 	if (ret < 0)
23955 		goto skip_full_check;
23956 
23957 	ret = bpf_stack_liveness_init(env);
23958 	if (ret)
23959 		goto skip_full_check;
23960 
23961 	ret = check_attach_btf_id(env);
23962 	if (ret)
23963 		goto skip_full_check;
23964 
23965 	ret = bpf_compute_const_regs(env);
23966 	if (ret < 0)
23967 		goto skip_full_check;
23968 
23969 	ret = bpf_prune_dead_branches(env);
23970 	if (ret < 0)
23971 		goto skip_full_check;
23972 
23973 	ret = sort_subprogs_topo(env);
23974 	if (ret < 0)
23975 		goto skip_full_check;
23976 
23977 	ret = bpf_compute_scc(env);
23978 	if (ret < 0)
23979 		goto skip_full_check;
23980 
23981 	/* must precede the first bpf_ret_reg_pair() user below */
23982 	ret = bpf_compute_subprog_ret_regs(env);
23983 	if (ret < 0)
23984 		goto skip_full_check;
23985 
23986 	prepare_subprog_args(env);
23987 
23988 	ret = bpf_compute_idoms(env);
23989 	if (ret < 0)
23990 		goto skip_full_check;
23991 
23992 	ret = bpf_compute_loops(env);
23993 	if (ret < 0)
23994 		goto skip_full_check;
23995 
23996 	ret = bpf_compute_live_registers(env);
23997 	if (ret < 0)
23998 		goto skip_full_check;
23999 
24000 	if (env->log.level & BPF_LOG_LEVEL2)
24001 		log_program(env);
24002 
24003 	ret = bpf_init_scev(env);
24004 	if (ret < 0)
24005 		goto skip_full_check;
24006 
24007 	ret = bpf_compute_scev(env);
24008 	if (ret < 0)
24009 		goto skip_full_check;
24010 
24011 	bpf_free_subprog_jts(env);
24012 
24013 	ret = mark_fastcall_patterns(env);
24014 	if (ret < 0)
24015 		goto skip_full_check;
24016 
24017 	ret = do_check_main(env);
24018 	ret = ret ?: do_check_subprogs(env);
24019 
24020 	/* reject recursion through the callx edges found by the main pass */
24021 	if (ret == 0 && env->callx_edges)
24022 		ret = sort_subprogs_topo(env);
24023 
24024 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24025 		ret = bpf_prog_offload_finalize(env);
24026 
24027 skip_full_check:
24028 	kvfree(env->explored_states);
24029 
24030 	/* might decrease stack depth, keep it before passes that
24031 	 * allocate additional slots.
24032 	 */
24033 	if (ret == 0)
24034 		ret = bpf_remove_fastcall_spills_fills(env);
24035 
24036 	if (ret == 0)
24037 		ret = check_max_stack_depth(env);
24038 
24039 	/* instruction rewrites happen after this point */
24040 	if (ret == 0)
24041 		ret = bpf_optimize_bpf_loop(env);
24042 
24043 	if (is_priv) {
24044 		if (ret == 0)
24045 			bpf_opt_hard_wire_dead_code_branches(env);
24046 		if (ret == 0)
24047 			ret = bpf_opt_remove_dead_code(env);
24048 		if (ret == 0)
24049 			ret = bpf_opt_remove_nops(env);
24050 	} else {
24051 		if (ret == 0)
24052 			sanitize_dead_code(env);
24053 	}
24054 
24055 	if (ret == 0)
24056 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24057 		ret = bpf_convert_ctx_accesses(env);
24058 
24059 	if (ret == 0)
24060 		ret = bpf_do_misc_fixups(env);
24061 
24062 	/* do 32-bit optimization after insn patching has done so those patched
24063 	 * insns could be handled correctly.
24064 	 */
24065 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24066 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
24067 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24068 								     : false;
24069 	}
24070 
24071 	if (ret == 0)
24072 		ret = bpf_fixup_call_args(env);
24073 
24074 	env->verification_time = ktime_get_ns() - start_time;
24075 	print_verification_stats(env);
24076 	env->prog->aux->verified_insns = env->insn_processed;
24077 
24078 	/* preserve original error even if log finalization is successful */
24079 	err = bpf_log_attr_finalize(attr_log, &env->log);
24080 	if (err)
24081 		ret = err;
24082 
24083 	if (ret)
24084 		goto err_release_maps;
24085 
24086 	if (env->used_map_cnt) {
24087 		/* if program passed verifier, update used_maps in bpf_prog_info */
24088 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
24089 							 env->used_map_cnt,
24090 							 GFP_KERNEL_ACCOUNT);
24091 
24092 		if (!env->prog->aux->used_maps) {
24093 			ret = -ENOMEM;
24094 			goto err_release_maps;
24095 		}
24096 
24097 		memcpy(env->prog->aux->used_maps, env->used_maps,
24098 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24099 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24100 	}
24101 	if (env->used_btf_cnt) {
24102 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24103 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
24104 							 env->used_btf_cnt,
24105 							 GFP_KERNEL_ACCOUNT);
24106 		if (!env->prog->aux->used_btfs) {
24107 			ret = -ENOMEM;
24108 			goto err_release_maps;
24109 		}
24110 
24111 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24112 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24113 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24114 	}
24115 	if (env->used_map_cnt || env->used_btf_cnt) {
24116 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24117 		 * bpf_ld_imm64 instructions
24118 		 */
24119 		convert_pseudo_ld_imm64(env);
24120 	}
24121 
24122 	adjust_btf_func(env);
24123 
24124 	/* extension progs temporarily inherit the attach_type of their targets
24125 	   for verification purposes, so set it back to zero before returning
24126 	 */
24127 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24128 		env->prog->expected_attach_type = 0;
24129 
24130 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
24131 
24132 err_release_maps:
24133 	if (ret)
24134 		release_insn_arrays(env);
24135 	if (!env->prog->aux->used_maps)
24136 		/* if we didn't copy map pointers into bpf_prog_info, release
24137 		 * them now. Otherwise free_used_maps() will release them.
24138 		 */
24139 		release_maps(env);
24140 	if (!env->prog->aux->used_btfs)
24141 		release_btfs(env);
24142 
24143 	*prog = env->prog;
24144 
24145 	module_put(env->attach_btf_mod);
24146 	if (!is_priv)
24147 		mutex_unlock(&bpf_verifier_lock);
24148 	goto err_free_env;
24149 err_prep:
24150 	err = bpf_log_attr_finalize(attr_log, &env->log);
24151 	if (err)
24152 		ret = err;
24153 	release_insn_arrays(env);
24154 	release_maps(env);
24155 	release_btfs(env);
24156 err_free_env:
24157 	bpf_free_subprog_jts(env);
24158 	if (env->insn_aux_data)
24159 		bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
24160 	vfree(env->insn_aux_data);
24161 	kvfree(env->fd_array);
24162 	bpf_free_scev(env);
24163 	bpf_stack_liveness_free(env);
24164 	kvfree(env->cfg.postorder_nums);
24165 	kvfree(env->cfg.insn_postorder);
24166 	kvfree(env->scc_info);
24167 	kvfree(env->succ);
24168 	kvfree(env->gotox_tmp_buf);
24169 	kvfree(env->callx_edges);
24170 	kvfree(env->func_ptrs);
24171 	bpf_diag_free(env);
24172 	kvfree(env->idoms);
24173 	kvfree(env);
24174 	return ret;
24175 }
24176