xref: /linux/kernel/bpf/verifier.c (revision 490599ab23134962a6d18a024e84541d77bdb999)
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/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/security.h>
26 #include <linux/verification.h>
27 #include <linux/btf_ids.h>
28 #include <linux/poison.h>
29 #include <linux/module.h>
30 #include <linux/cpumask.h>
31 #include <linux/cnum.h>
32 #include <linux/bpf_mem_alloc.h>
33 #include <net/xdp.h>
34 #include <linux/trace_events.h>
35 #include <linux/kallsyms.h>
36 
37 #include "diagnostics.h"
38 #include "disasm.h"
39 
40 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
41 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
42 	[_id] = & _name ## _verifier_ops,
43 #define BPF_MAP_TYPE(_id, _ops)
44 #define BPF_LINK_TYPE(_id, _name)
45 #include <linux/bpf_types.h>
46 #undef BPF_PROG_TYPE
47 #undef BPF_MAP_TYPE
48 #undef BPF_LINK_TYPE
49 };
50 
51 enum bpf_features {
52 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
53 	BPF_FEAT_STREAMS	     = 1,
54 	__MAX_BPF_FEAT,
55 };
56 
57 struct bpf_mem_alloc bpf_global_percpu_ma;
58 static bool bpf_global_percpu_ma_set;
59 
60 /* bpf_check() is a static code analyzer that walks eBPF program
61  * instruction by instruction and updates register/stack state.
62  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
63  *
64  * The first pass is depth-first-search to check that the program is a DAG.
65  * It rejects the following programs:
66  * - larger than BPF_MAXINSNS insns
67  * - if loop is present (detected via back-edge)
68  * - unreachable insns exist (shouldn't be a forest. program = one function)
69  * - out of bounds or malformed jumps
70  * The second pass is all possible path descent from the 1st insn.
71  * Since it's analyzing all paths through the program, the length of the
72  * analysis is limited to 64k insn, which may be hit even if total number of
73  * insn is less then 4K, but there are too many branches that change stack/regs.
74  * Number of 'branches to be analyzed' is limited to 1k
75  *
76  * On entry to each instruction, each register has a type, and the instruction
77  * changes the types of the registers depending on instruction semantics.
78  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
79  * copied to R1.
80  *
81  * All registers are 64-bit.
82  * R0 - return register
83  * R1-R5 argument passing registers
84  * R6-R9 callee saved registers
85  * R10 - frame pointer read-only
86  *
87  * At the start of BPF program the register R1 contains a pointer to bpf_context
88  * and has type PTR_TO_CTX.
89  *
90  * Verifier tracks arithmetic operations on pointers in case:
91  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
92  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
93  * 1st insn copies R10 (which has FRAME_PTR) type into R1
94  * and 2nd arithmetic instruction is pattern matched to recognize
95  * that it wants to construct a pointer to some element within stack.
96  * So after 2nd insn, the register R1 has type PTR_TO_STACK
97  * (and -20 constant is saved for further stack bounds checking).
98  * Meaning that this reg is a pointer to stack plus known immediate constant.
99  *
100  * Most of the time the registers have SCALAR_VALUE type, which
101  * means the register has some value, but it's not a valid pointer.
102  * (like pointer plus pointer becomes SCALAR_VALUE type)
103  *
104  * When verifier sees load or store instructions the type of base register
105  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
106  * four pointer types recognized by check_mem_access() function.
107  *
108  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
109  * and the range of [ptr, ptr + map's value_size) is accessible.
110  *
111  * registers used to pass values to function calls are checked against
112  * function argument constraints.
113  *
114  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
115  * It means that the register type passed to this function must be
116  * PTR_TO_STACK and it will be used inside the function as
117  * 'pointer to map element key'
118  *
119  * For example the argument constraints for bpf_map_lookup_elem():
120  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
121  *   .arg1_type = ARG_CONST_MAP_PTR,
122  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
123  *
124  * ret_type says that this function returns 'pointer to map elem value or null'
125  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
126  * 2nd argument should be a pointer to stack, which will be used inside
127  * the helper function as a pointer to map element key.
128  *
129  * On the kernel side the helper function looks like:
130  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
131  * {
132  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
133  *    void *key = (void *) (unsigned long) r2;
134  *    void *value;
135  *
136  *    here kernel can access 'key' and 'map' pointers safely, knowing that
137  *    [key, key + map->key_size) bytes are valid and were initialized on
138  *    the stack of eBPF program.
139  * }
140  *
141  * Corresponding eBPF program may look like:
142  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
143  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
144  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
145  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
146  * here verifier looks at prototype of map_lookup_elem() and sees:
147  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
148  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
149  *
150  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
151  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
152  * and were initialized prior to this call.
153  * If it's ok, then verifier allows this BPF_CALL insn and looks at
154  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
155  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
156  * returns either pointer to map value or NULL.
157  *
158  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
159  * insn, the register holding that pointer in the true branch changes state to
160  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
161  * branch. See check_cond_jmp_op().
162  *
163  * After the call R0 is set to return type of the function and registers R1-R5
164  * are set to NOT_INIT to indicate that they are no longer readable.
165  *
166  * The following reference types represent a potential reference to a kernel
167  * resource which, after first being allocated, must be checked and freed by
168  * the BPF program:
169  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
170  *
171  * When the verifier sees a helper call return a reference type, it allocates a
172  * pointer id for the reference and stores it in the current function state.
173  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
174  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
175  * passes through a NULL-check conditional. For the branch wherein the state is
176  * changed to CONST_IMM, the verifier releases the reference.
177  *
178  * For each helper function that allocates a reference, such as
179  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
180  * bpf_sk_release(). When a reference type passes into the release function,
181  * the verifier also releases the reference. If any unchecked or unreleased
182  * reference remains at the end of the program, the verifier rejects it.
183  */
184 
185 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
186 struct bpf_verifier_stack_elem {
187 	/* verifier state is 'st'
188 	 * before processing instruction 'insn_idx'
189 	 * and after processing instruction 'prev_insn_idx'
190 	 */
191 	struct bpf_verifier_state st;
192 	int insn_idx;
193 	int prev_insn_idx;
194 	struct bpf_verifier_stack_elem *next;
195 	/* length of verifier log at the time this state was pushed on stack */
196 	u32 log_pos;
197 	u64 diag_log_pos;
198 };
199 
200 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
201 #define BPF_COMPLEXITY_LIMIT_STATES	64
202 
203 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
204 
205 #define BPF_PRIV_STACK_MIN_SIZE		64
206 
207 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
208 static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
209 static int release_reference_nomark(struct bpf_verifier_env *env, int id);
210 static int release_reference(struct bpf_verifier_env *env, int id);
211 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
212 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env);
213 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
214 static bool is_tracing_prog_type(enum bpf_prog_type type);
215 static int ref_set_non_owning(struct bpf_verifier_env *env,
216 			      struct bpf_reg_state *reg);
217 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
218 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
219 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
220 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
221 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
222 
223 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
224 			      struct bpf_map *map,
225 			      bool unpriv, bool poison)
226 {
227 	unpriv |= bpf_map_ptr_unpriv(aux);
228 	aux->map_ptr_state.unpriv = unpriv;
229 	aux->map_ptr_state.poison = poison;
230 	aux->map_ptr_state.map_ptr = map;
231 }
232 
233 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
234 {
235 	bool poisoned = bpf_map_key_poisoned(aux);
236 
237 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
238 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
239 }
240 
241 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
242 {
243 	ref_obj->id = reg->id;
244 	ref_obj->parent_id = reg->parent_id;
245 	ref_obj->cnt++;
246 }
247 
248 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
249 {
250 	if (ref_obj->cnt > 1) {
251 		verifier_bug(env, "function expects only one referenced object but got %d\n",
252 			     ref_obj->cnt);
253 		return -EFAULT;
254 	}
255 
256 	return 0;
257 }
258 
259 struct bpf_kfunc_meta {
260 	struct btf *btf;
261 	const struct btf_type *proto;
262 	const char *name;
263 	const u32 *flags;
264 	s32 id;
265 };
266 
267 struct btf *btf_vmlinux;
268 
269 typedef struct argno {
270 	int argno;
271 } argno_t;
272 
273 static argno_t argno_from_reg(u32 regno)
274 {
275 	return (argno_t){ .argno = regno };
276 }
277 
278 static argno_t argno_from_arg(u32 arg)
279 {
280 	return (argno_t){ .argno = -arg };
281 }
282 
283 static int reg_from_argno(argno_t a)
284 {
285 	if (a.argno >= 0)
286 		return a.argno;
287 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
288 		return -a.argno;
289 	return -1;
290 }
291 
292 static int arg_from_argno(argno_t a)
293 {
294 	if (a.argno < 0)
295 		return -a.argno;
296 	return -1;
297 }
298 
299 static int arg_idx_from_argno(argno_t a)
300 {
301 	return arg_from_argno(a) - 1;
302 }
303 
304 static const char *btf_type_name(const struct btf *btf, u32 id)
305 {
306 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
307 }
308 
309 static DEFINE_MUTEX(bpf_verifier_lock);
310 static DEFINE_MUTEX(btf_vmlinux_lock);
311 static DEFINE_MUTEX(bpf_percpu_ma_lock);
312 
313 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
314 {
315 	struct bpf_verifier_env *env = private_data;
316 	va_list args;
317 
318 	if (!bpf_verifier_log_needed(&env->log))
319 		return;
320 
321 	va_start(args, fmt);
322 	bpf_verifier_vlog(&env->log, fmt, args);
323 	va_end(args);
324 }
325 
326 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
327 				   struct bpf_reg_state *reg,
328 				   struct bpf_retval_range range, const char *ctx,
329 				   const char *reg_name)
330 {
331 	bool unknown = true;
332 
333 	verbose(env, "%s the register %s has", ctx, reg_name);
334 	if (reg_smin(reg) > S64_MIN) {
335 		verbose(env, " smin=%lld", reg_smin(reg));
336 		unknown = false;
337 	}
338 	if (reg_smax(reg) < S64_MAX) {
339 		verbose(env, " smax=%lld", reg_smax(reg));
340 		unknown = false;
341 	}
342 	if (unknown)
343 		verbose(env, " unknown scalar value");
344 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
345 }
346 
347 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
348 {
349 	enum bpf_reg_type type;
350 
351 	type = reg->type;
352 	if (type_may_be_null(type))
353 		return false;
354 
355 	/*
356 	 * The types below guarantee a non-NULL base, an unbounded offset can
357 	 * still wrap base + offset to zero.
358 	 */
359 	if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF)
360 		return false;
361 
362 	type = base_type(type);
363 	return type == PTR_TO_SOCKET ||
364 		type == PTR_TO_TCP_SOCK ||
365 		type == PTR_TO_XDP_SOCK ||
366 		type == PTR_TO_BUF ||
367 		type == PTR_TO_MAP_VALUE ||
368 		type == PTR_TO_MAP_KEY ||
369 		type == PTR_TO_SOCK_COMMON ||
370 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
371 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
372 		type == CONST_PTR_TO_MAP;
373 }
374 
375 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
376 {
377 	struct btf_record *rec = NULL;
378 	struct btf_struct_meta *meta;
379 
380 	if (reg->type == PTR_TO_MAP_VALUE) {
381 		rec = reg->map_ptr->record;
382 	} else if (type_is_ptr_alloc_obj(reg->type)) {
383 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
384 		if (meta)
385 			rec = meta->record;
386 	}
387 	return rec;
388 }
389 
390 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
391 {
392 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
393 
394 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
395 }
396 
397 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
398 {
399 	const struct btf_type *type, *func, *func_proto;
400 	const struct btf *btf = env->prog->aux->btf;
401 	u32 btf_id;
402 
403 	btf_id = env->prog->aux->func_info[subprog].type_id;
404 
405 	func = btf_type_by_id(btf, btf_id);
406 	if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id))
407 		return false;
408 
409 	func_proto = btf_type_by_id(btf, func->type);
410 	if (!func_proto)
411 		return false;
412 
413 	type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
414 	if (!type)
415 		return false;
416 
417 	return btf_type_is_void(type);
418 }
419 
420 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)
421 {
422 	struct bpf_func_info *info;
423 
424 	if (!env->prog->aux->func_info)
425 		return "";
426 
427 	info = &env->prog->aux->func_info[subprog];
428 	return btf_type_name(env->prog->aux->btf, info->type_id);
429 }
430 
431 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_subprog_info *info = subprog_info(env, subprog);
434 
435 	info->is_cb = true;
436 	info->is_async_cb = true;
437 	info->is_exception_cb = true;
438 }
439 
440 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
441 {
442 	return subprog_info(env, subprog)->is_exception_cb;
443 }
444 
445 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
446 {
447 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
448 }
449 
450 static bool type_is_rdonly_mem(u32 type)
451 {
452 	return type & MEM_RDONLY;
453 }
454 
455 static bool is_acquire_function(enum bpf_func_id func_id,
456 				const struct bpf_map *map)
457 {
458 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
459 
460 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
461 	    func_id == BPF_FUNC_sk_lookup_udp ||
462 	    func_id == BPF_FUNC_skc_lookup_tcp ||
463 	    func_id == BPF_FUNC_ringbuf_reserve ||
464 	    func_id == BPF_FUNC_kptr_xchg)
465 		return true;
466 
467 	if (func_id == BPF_FUNC_map_lookup_elem &&
468 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
469 	     map_type == BPF_MAP_TYPE_SOCKHASH))
470 		return true;
471 
472 	return false;
473 }
474 
475 static bool is_ptr_cast_function(enum bpf_func_id func_id)
476 {
477 	return func_id == BPF_FUNC_tcp_sock ||
478 		func_id == BPF_FUNC_sk_fullsock ||
479 		func_id == BPF_FUNC_skc_to_tcp_sock ||
480 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
481 		func_id == BPF_FUNC_skc_to_udp6_sock ||
482 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
483 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
484 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
485 }
486 
487 static bool is_sync_callback_calling_kfunc(u32 btf_id);
488 static bool is_async_callback_calling_kfunc(u32 btf_id);
489 static bool is_callback_calling_kfunc(u32 btf_id);
490 
491 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
492 static bool is_task_work_add_kfunc(u32 func_id);
493 
494 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
495 {
496 	return func_id == BPF_FUNC_for_each_map_elem ||
497 	       func_id == BPF_FUNC_find_vma ||
498 	       func_id == BPF_FUNC_loop ||
499 	       func_id == BPF_FUNC_user_ringbuf_drain;
500 }
501 
502 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
503 {
504 	return func_id == BPF_FUNC_timer_set_callback;
505 }
506 
507 static bool is_callback_calling_function(enum bpf_func_id func_id)
508 {
509 	return is_sync_callback_calling_function(func_id) ||
510 	       is_async_callback_calling_function(func_id);
511 }
512 
513 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
514 {
515 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
516 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
517 }
518 
519 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
520 {
521 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
522 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
523 }
524 
525 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
526 {
527 	/* bpf_timer callbacks are never sleepable. */
528 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
529 		return false;
530 
531 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
532 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
533 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
534 		return true;
535 
536 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
537 	return false;
538 }
539 
540 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
541 {
542 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
543 }
544 
545 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
546 {
547        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
548 
549        /* We need to check that slots between [spi - nr_slots + 1, spi] are
550 	* within [0, allocated_stack).
551 	*
552 	* Please note that the spi grows downwards. For example, a dynptr
553 	* takes the size of two stack slots; the first slot will be at
554 	* spi and the second slot will be at spi - 1.
555 	*/
556        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
557 }
558 
559 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
560 			          const char *obj_kind, int nr_slots)
561 {
562 	int off, spi;
563 
564 	if (!tnum_is_const(reg->var_off)) {
565 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
566 		return -EINVAL;
567 	}
568 
569 	off = reg->var_off.value;
570 	if (off % BPF_REG_SIZE) {
571 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
572 		return -EINVAL;
573 	}
574 
575 	spi = bpf_get_spi(off);
576 	if (spi + 1 < nr_slots) {
577 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
578 		return -EINVAL;
579 	}
580 
581 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
582 		return -ERANGE;
583 	return spi;
584 }
585 
586 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
587 {
588 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
589 }
590 
591 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
592 {
593 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
594 }
595 
596 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
597 {
598 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
599 }
600 
601 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
602 {
603 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
604 	case DYNPTR_TYPE_LOCAL:
605 		return BPF_DYNPTR_TYPE_LOCAL;
606 	case DYNPTR_TYPE_RINGBUF:
607 		return BPF_DYNPTR_TYPE_RINGBUF;
608 	case DYNPTR_TYPE_SKB:
609 		return BPF_DYNPTR_TYPE_SKB;
610 	case DYNPTR_TYPE_XDP:
611 		return BPF_DYNPTR_TYPE_XDP;
612 	case DYNPTR_TYPE_SKB_META:
613 		return BPF_DYNPTR_TYPE_SKB_META;
614 	case DYNPTR_TYPE_FILE:
615 		return BPF_DYNPTR_TYPE_FILE;
616 	default:
617 		return BPF_DYNPTR_TYPE_INVALID;
618 	}
619 }
620 
621 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
622 {
623 	switch (type) {
624 	case BPF_DYNPTR_TYPE_LOCAL:
625 		return DYNPTR_TYPE_LOCAL;
626 	case BPF_DYNPTR_TYPE_RINGBUF:
627 		return DYNPTR_TYPE_RINGBUF;
628 	case BPF_DYNPTR_TYPE_SKB:
629 		return DYNPTR_TYPE_SKB;
630 	case BPF_DYNPTR_TYPE_XDP:
631 		return DYNPTR_TYPE_XDP;
632 	case BPF_DYNPTR_TYPE_SKB_META:
633 		return DYNPTR_TYPE_SKB_META;
634 	case BPF_DYNPTR_TYPE_FILE:
635 		return DYNPTR_TYPE_FILE;
636 	default:
637 		return 0;
638 	}
639 }
640 
641 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
642 {
643 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
644 }
645 
646 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
647 			      enum bpf_dynptr_type type,
648 			      bool first_slot, int id, int parent_id);
649 
650 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
651 				   struct bpf_reg_state *sreg1,
652 				   struct bpf_reg_state *sreg2,
653 				   enum bpf_dynptr_type type, int parent_id)
654 {
655 	int id = ++env->id_gen;
656 
657 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
658 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
659 }
660 
661 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
662 			       struct bpf_reg_state *reg,
663 			       enum bpf_dynptr_type type)
664 {
665 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
666 }
667 
668 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
669 				        struct bpf_func_state *state, int spi);
670 
671 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
672 				   enum bpf_arg_type arg_type, int insn_idx,
673 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
674 {
675 	struct bpf_func_state *state = bpf_func(env, reg);
676 	int spi, i, err, parent_id = 0;
677 	enum bpf_dynptr_type type;
678 
679 	spi = dynptr_get_spi(env, reg);
680 	if (spi < 0)
681 		return spi;
682 
683 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
684 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
685 	 * to ensure that for the following example:
686 	 *	[d1][d1][d2][d2]
687 	 * spi    3   2   1   0
688 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
689 	 * case they do belong to same dynptr, second call won't see slot_type
690 	 * as STACK_DYNPTR and will simply skip destruction.
691 	 */
692 	err = destroy_if_dynptr_stack_slot(env, state, spi);
693 	if (err)
694 		return err;
695 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
696 	if (err)
697 		return err;
698 
699 	for (i = 0; i < BPF_REG_SIZE; i++) {
700 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
701 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
702 	}
703 
704 	type = arg_to_dynptr_type(arg_type);
705 	if (type == BPF_DYNPTR_TYPE_INVALID)
706 		return -EINVAL;
707 
708 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
709 		err = validate_ref_obj(env, ref_obj);
710 		if (err)
711 			return err;
712 
713 		/* Track parent's id if the parent is a referenced object */
714 		parent_id = ref_obj->id;
715 
716 		if (dynptr_type_referenced(type)) {
717 			int id;
718 
719 			/*
720 			 * Create an intermediate reference that tracks the referenced
721 			 * object for the referenced dynptr. Freeing a referenced dynptr
722 			 * through helpers/kfuncs will invalidate all clones.
723 			 */
724 			id = acquire_reference(env, insn_idx, parent_id);
725 			if (id < 0)
726 				return id;
727 
728 			parent_id = id;
729 		}
730 	} else { /* bpf_dynptr_clone() */
731 		parent_id = dynptr->parent_id;
732 	}
733 
734 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
735 			       &state->stack[spi - 1].spilled_ptr, type, parent_id);
736 
737 	return 0;
738 }
739 
740 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
741 {
742 	int i;
743 
744 	for (i = 0; i < BPF_REG_SIZE; i++) {
745 		stack[0].slot_type[i] = STACK_INVALID;
746 		stack[1].slot_type[i] = STACK_INVALID;
747 	}
748 
749 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
750 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
751 }
752 
753 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
754 {
755 	struct bpf_func_state *state = bpf_func(env, reg);
756 	int spi;
757 
758 	spi = dynptr_get_spi(env, reg);
759 	if (spi < 0)
760 		return spi;
761 
762 	/*
763 	 * For referenced dynptr, release the parent ref which cascades to
764 	 * all clones and derived slices. For non-referenced dynptr, only
765 	 * the dynptr and slices derived from it will be invalidated.
766 	 */
767 	reg = &state->stack[spi].spilled_ptr;
768 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
769 				      ? reg->parent_id
770 				      : reg->id);
771 }
772 
773 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
774 			       struct bpf_reg_state *reg);
775 
776 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
777 {
778 	if (!env->allow_ptr_leaks)
779 		bpf_mark_reg_not_init(env, reg);
780 	else
781 		__mark_reg_unknown(env, reg);
782 }
783 
784 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
785 {
786 	struct bpf_stack_state *stack;
787 	struct bpf_func_state *state;
788 	struct bpf_reg_state *reg;
789 	int ref_cnt = 0;
790 
791 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
792 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
793 			continue;
794 		if (!stack->spilled_ptr.dynptr.first_slot)
795 			continue;
796 		if (stack->spilled_ptr.parent_id == v_parent_id)
797 			ref_cnt++;
798 	}));
799 
800 	return ref_cnt;
801 }
802 
803 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
804 				        struct bpf_func_state *state, int spi)
805 {
806 	int err = 0;
807 
808 	/* We always ensure that STACK_DYNPTR is never set partially,
809 	 * hence just checking for slot_type[0] is enough. This is
810 	 * different for STACK_SPILL, where it may be only set for
811 	 * 1 byte, so code has to use is_spilled_reg.
812 	 */
813 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
814 		return 0;
815 
816 	/* Reposition spi to first slot */
817 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
818 		spi = spi + 1;
819 
820 	/*
821 	 * A referenced dynptr can be overwritten only if there is at
822 	 * least one other dynptr sharing the same virtual ref parent,
823 	 * ensuring the reference can still be properly released.
824 	 */
825 	if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) &&
826 	    dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) {
827 		verbose(env, "cannot overwrite referenced dynptr\n");
828 		bpf_diag_res(
829 			env, env->insn_idx, "referenced dynptr overwrite",
830 			"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.",
831 			"Release or clone the dynptr so another live dynptr still tracks the referenced resource before overwriting this stack slot.");
832 		return -EINVAL;
833 	}
834 
835 	/* Invalidate the dynptr and any derived slices */
836 	err = release_reference(env, state->stack[spi].spilled_ptr.id);
837 	if (!err) {
838 		mark_stack_slot_scratched(env, spi);
839 		mark_stack_slot_scratched(env, spi - 1);
840 	}
841 
842 	return err;
843 }
844 
845 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
846 {
847 	int spi;
848 
849 	if (reg->type == CONST_PTR_TO_DYNPTR)
850 		return false;
851 
852 	spi = dynptr_get_spi(env, reg);
853 
854 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
855 	 * error because this just means the stack state hasn't been updated yet.
856 	 * We will do check_mem_access to check and update stack bounds later.
857 	 */
858 	if (spi < 0 && spi != -ERANGE)
859 		return false;
860 
861 	/* We don't need to check if the stack slots are marked by previous
862 	 * dynptr initializations because we allow overwriting existing unreferenced
863 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
864 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
865 	 * touching are completely destructed before we reinitialize them for a new
866 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
867 	 * instead of delaying it until the end where the user will get "Unreleased
868 	 * reference" error.
869 	 */
870 	return true;
871 }
872 
873 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
874 {
875 	struct bpf_func_state *state = bpf_func(env, reg);
876 	int i, spi;
877 
878 	/* This already represents first slot of initialized bpf_dynptr.
879 	 *
880 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
881 	 * check_func_arg_reg_off's logic, so we don't need to check its
882 	 * offset and alignment.
883 	 */
884 	if (reg->type == CONST_PTR_TO_DYNPTR)
885 		return true;
886 
887 	spi = dynptr_get_spi(env, reg);
888 	if (spi < 0)
889 		return false;
890 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
891 		return false;
892 
893 	for (i = 0; i < BPF_REG_SIZE; i++) {
894 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
895 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
896 			return false;
897 	}
898 
899 	return true;
900 }
901 
902 static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
903 {
904 	struct bpf_func_state *state;
905 	int spi;
906 
907 	if (reg->type == CONST_PTR_TO_DYNPTR)
908 		return reg->dynptr.type;
909 
910 	spi = dynptr_get_spi(env, reg);
911 	if (spi < 0)
912 		return BPF_DYNPTR_TYPE_INVALID;
913 	state = bpf_func(env, reg);
914 	return state->stack[spi].spilled_ptr.dynptr.type;
915 }
916 
917 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
918 				    enum bpf_arg_type arg_type)
919 {
920 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
921 	if (arg_type == ARG_PTR_TO_DYNPTR)
922 		return true;
923 
924 	return dynptr_reg_type(env, reg) == arg_to_dynptr_type(arg_type);
925 }
926 
927 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
928 
929 static bool in_rcu_cs(struct bpf_verifier_env *env);
930 
931 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta);
932 
933 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
934 				 struct bpf_call_arg_meta *meta,
935 				 struct bpf_reg_state *reg, int insn_idx,
936 				 struct btf *btf, u32 btf_id, int nr_slots)
937 {
938 	struct bpf_func_state *state = bpf_func(env, reg);
939 	int spi, i, j, id;
940 
941 	spi = iter_get_spi(env, reg, nr_slots);
942 	if (spi < 0)
943 		return spi;
944 
945 	id = acquire_reference(env, insn_idx, 0);
946 	if (id < 0)
947 		return id;
948 
949 	for (i = 0; i < nr_slots; i++) {
950 		struct bpf_stack_state *slot = &state->stack[spi - i];
951 		struct bpf_reg_state *st = &slot->spilled_ptr;
952 
953 		__mark_reg_known_zero(st);
954 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
955 		if (is_kfunc_rcu_protected(meta)) {
956 			if (in_rcu_cs(env))
957 				st->type |= MEM_RCU;
958 			else
959 				st->type |= PTR_UNTRUSTED;
960 		}
961 		st->id = i == 0 ? id : 0;
962 		st->iter.btf = btf;
963 		st->iter.btf_id = btf_id;
964 		st->iter.state = BPF_ITER_STATE_ACTIVE;
965 		st->iter.depth = 0;
966 
967 		for (j = 0; j < BPF_REG_SIZE; j++)
968 			slot->slot_type[j] = STACK_ITER;
969 
970 		mark_stack_slot_scratched(env, spi - i);
971 	}
972 
973 	return 0;
974 }
975 
976 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
977 				   struct bpf_reg_state *reg, int nr_slots)
978 {
979 	struct bpf_func_state *state = bpf_func(env, reg);
980 	int spi, i, j;
981 
982 	spi = iter_get_spi(env, reg, nr_slots);
983 	if (spi < 0)
984 		return spi;
985 
986 	for (i = 0; i < nr_slots; i++) {
987 		struct bpf_stack_state *slot = &state->stack[spi - i];
988 		struct bpf_reg_state *st = &slot->spilled_ptr;
989 
990 		if (i == 0)
991 			WARN_ON_ONCE(release_reference(env, st->id));
992 
993 		bpf_mark_reg_not_init(env, st);
994 
995 		for (j = 0; j < BPF_REG_SIZE; j++)
996 			slot->slot_type[j] = STACK_INVALID;
997 
998 		mark_stack_slot_scratched(env, spi - i);
999 	}
1000 
1001 	return 0;
1002 }
1003 
1004 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1005 				     struct bpf_reg_state *reg, int nr_slots)
1006 {
1007 	struct bpf_func_state *state = bpf_func(env, reg);
1008 	int spi, i, j;
1009 
1010 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1011 	 * will do check_mem_access to check and update stack bounds later, so
1012 	 * return true for that case.
1013 	 */
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi == -ERANGE)
1016 		return true;
1017 	if (spi < 0)
1018 		return false;
1019 
1020 	for (i = 0; i < nr_slots; i++) {
1021 		struct bpf_stack_state *slot = &state->stack[spi - i];
1022 
1023 		for (j = 0; j < BPF_REG_SIZE; j++)
1024 			if (slot->slot_type[j] == STACK_ITER)
1025 				return false;
1026 	}
1027 
1028 	return true;
1029 }
1030 
1031 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1032 				   struct btf *btf, u32 btf_id, int nr_slots)
1033 {
1034 	struct bpf_func_state *state = bpf_func(env, reg);
1035 	int spi, i, j;
1036 
1037 	spi = iter_get_spi(env, reg, nr_slots);
1038 	if (spi < 0)
1039 		return -EINVAL;
1040 
1041 	for (i = 0; i < nr_slots; i++) {
1042 		struct bpf_stack_state *slot = &state->stack[spi - i];
1043 		struct bpf_reg_state *st = &slot->spilled_ptr;
1044 
1045 		if (st->type & PTR_UNTRUSTED)
1046 			return -EPROTO;
1047 		/* only main (first) slot has id set */
1048 		if (i == 0 && !st->id)
1049 			return -EINVAL;
1050 		if (i != 0 && st->id)
1051 			return -EINVAL;
1052 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1053 			return -EINVAL;
1054 
1055 		for (j = 0; j < BPF_REG_SIZE; j++)
1056 			if (slot->slot_type[j] != STACK_ITER)
1057 				return -EINVAL;
1058 	}
1059 
1060 	return 0;
1061 }
1062 
1063 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1064 static int release_irq_state(struct bpf_verifier_env *env, int id);
1065 
1066 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1067 				     struct bpf_call_arg_meta *meta,
1068 				     struct bpf_reg_state *reg, int insn_idx,
1069 				     int kfunc_class)
1070 {
1071 	struct bpf_func_state *state = bpf_func(env, reg);
1072 	struct bpf_stack_state *slot;
1073 	struct bpf_reg_state *st;
1074 	int spi, i, id;
1075 
1076 	spi = irq_flag_get_spi(env, reg);
1077 	if (spi < 0)
1078 		return spi;
1079 
1080 	id = acquire_irq_state(env, insn_idx);
1081 	if (id < 0)
1082 		return id;
1083 
1084 	slot = &state->stack[spi];
1085 	st = &slot->spilled_ptr;
1086 
1087 	__mark_reg_known_zero(st);
1088 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1089 	st->id = id;
1090 	st->irq.kfunc_class = kfunc_class;
1091 
1092 	for (i = 0; i < BPF_REG_SIZE; i++)
1093 		slot->slot_type[i] = STACK_IRQ_FLAG;
1094 
1095 	mark_stack_slot_scratched(env, spi);
1096 	return 0;
1097 }
1098 
1099 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1100 				      int kfunc_class)
1101 {
1102 	struct bpf_func_state *state = bpf_func(env, reg);
1103 	struct bpf_stack_state *slot;
1104 	struct bpf_reg_state *st;
1105 	int spi, i, err;
1106 
1107 	spi = irq_flag_get_spi(env, reg);
1108 	if (spi < 0)
1109 		return spi;
1110 
1111 	slot = &state->stack[spi];
1112 	st = &slot->spilled_ptr;
1113 
1114 	if (st->irq.kfunc_class != kfunc_class) {
1115 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1116 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1117 		const char *reason;
1118 
1119 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1120 			flag_kfunc, used_kfunc);
1121 		reason = bpf_diag_fmt(env,
1122 				      "This IRQ flag was saved by %s IRQ kfuncs, but the restore call "
1123 			"belongs to the %s IRQ kfunc family. Save and restore operations "
1124 			"must use the same family.",
1125 			flag_kfunc, used_kfunc);
1126 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore mismatch", reason,
1127 			     "Restore the flag with the matching IRQ restore kfunc for the save "
1128 			     "operation that created it.",
1129 			     bpf_diag_irq_depth(env->cur_state));
1130 		return -EINVAL;
1131 	}
1132 
1133 	err = release_irq_state(env, st->id);
1134 	WARN_ON_ONCE(err && err != -EACCES);
1135 	if (err) {
1136 		int insn_idx = 0;
1137 
1138 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1139 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1140 				insn_idx = env->cur_state->refs[i].insn_idx;
1141 				break;
1142 			}
1143 		}
1144 
1145 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1146 			env->cur_state->active_irq_id, insn_idx);
1147 		bpf_diag_irq(env, env->insn_idx, "IRQ flag restore out of order",
1148 			     "IRQ-disabled regions must be restored in last-in, first-out order, "
1149 			     "but this restore does not match the currently active IRQ flag.",
1150 			     "Restore nested IRQ flags in the reverse order they were saved.",
1151 			     bpf_diag_irq_depth(env->cur_state));
1152 		return err;
1153 	}
1154 
1155 	bpf_mark_reg_not_init(env, st);
1156 
1157 	for (i = 0; i < BPF_REG_SIZE; i++)
1158 		slot->slot_type[i] = STACK_INVALID;
1159 
1160 	mark_stack_slot_scratched(env, spi);
1161 	return 0;
1162 }
1163 
1164 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1165 {
1166 	struct bpf_func_state *state = bpf_func(env, reg);
1167 	struct bpf_stack_state *slot;
1168 	int spi, i;
1169 
1170 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1171 	 * will do check_mem_access to check and update stack bounds later, so
1172 	 * return true for that case.
1173 	 */
1174 	spi = irq_flag_get_spi(env, reg);
1175 	if (spi == -ERANGE)
1176 		return true;
1177 	if (spi < 0)
1178 		return false;
1179 
1180 	slot = &state->stack[spi];
1181 
1182 	for (i = 0; i < BPF_REG_SIZE; i++)
1183 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1184 			return false;
1185 	return true;
1186 }
1187 
1188 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1189 {
1190 	struct bpf_func_state *state = bpf_func(env, reg);
1191 	struct bpf_stack_state *slot;
1192 	struct bpf_reg_state *st;
1193 	int spi, i;
1194 
1195 	spi = irq_flag_get_spi(env, reg);
1196 	if (spi < 0)
1197 		return -EINVAL;
1198 
1199 	slot = &state->stack[spi];
1200 	st = &slot->spilled_ptr;
1201 
1202 	if (!st->id)
1203 		return -EINVAL;
1204 
1205 	for (i = 0; i < BPF_REG_SIZE; i++)
1206 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1207 			return -EINVAL;
1208 	return 0;
1209 }
1210 
1211 /* Check if given stack slot is "special":
1212  *   - spilled register state (STACK_SPILL);
1213  *   - dynptr state (STACK_DYNPTR);
1214  *   - iter state (STACK_ITER).
1215  *   - irq flag state (STACK_IRQ_FLAG)
1216  */
1217 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1218 {
1219 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1220 
1221 	switch (type) {
1222 	case STACK_SPILL:
1223 	case STACK_DYNPTR:
1224 	case STACK_ITER:
1225 	case STACK_IRQ_FLAG:
1226 		return true;
1227 	case STACK_INVALID:
1228 	case STACK_POISON:
1229 	case STACK_MISC:
1230 	case STACK_ZERO:
1231 		return false;
1232 	default:
1233 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1234 		return true;
1235 	}
1236 }
1237 
1238 /* The reg state of a pointer or a bounded scalar was saved when
1239  * it was spilled to the stack.
1240  */
1241 
1242 /*
1243  * Mark stack slot as STACK_MISC, unless it is already:
1244  * - STACK_INVALID, in which case they are equivalent.
1245  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1246  * - STACK_POISON, which truly forbids access to the slot.
1247  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1248  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1249  * unnecessary as both are considered equivalent when loading data and pruning,
1250  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1251  * slots.
1252  */
1253 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1254 {
1255 	if (*stype == STACK_ZERO)
1256 		return;
1257 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1258 		return;
1259 	*stype = STACK_MISC;
1260 }
1261 
1262 static void scrub_spilled_slot(u8 *stype)
1263 {
1264 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1265 		*stype = STACK_MISC;
1266 }
1267 
1268 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1269  * small to hold src. This is different from krealloc since we don't want to preserve
1270  * the contents of dst.
1271  *
1272  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1273  * not be allocated.
1274  */
1275 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1276 {
1277 	size_t alloc_bytes;
1278 	void *orig = dst;
1279 	size_t bytes;
1280 
1281 	if (ZERO_OR_NULL_PTR(src))
1282 		goto out;
1283 
1284 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1285 		return NULL;
1286 
1287 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1288 	dst = krealloc(orig, alloc_bytes, flags);
1289 	if (!dst) {
1290 		kfree(orig);
1291 		return NULL;
1292 	}
1293 
1294 	memcpy(dst, src, bytes);
1295 out:
1296 	return dst ? dst : ZERO_SIZE_PTR;
1297 }
1298 
1299 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1300  * small to hold new_n items. new items are zeroed out if the array grows.
1301  *
1302  * Contrary to krealloc_array, does not free arr if new_n is zero.
1303  */
1304 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1305 {
1306 	size_t alloc_size;
1307 	void *new_arr;
1308 
1309 	if (!new_n || old_n == new_n)
1310 		goto out;
1311 
1312 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1313 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1314 	if (!new_arr) {
1315 		kfree(arr);
1316 		return NULL;
1317 	}
1318 	arr = new_arr;
1319 
1320 	if (new_n > old_n)
1321 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1322 
1323 out:
1324 	return arr ? arr : ZERO_SIZE_PTR;
1325 }
1326 
1327 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1328 {
1329 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1330 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1331 	if (!dst->refs)
1332 		return -ENOMEM;
1333 
1334 	dst->acquired_refs = src->acquired_refs;
1335 	dst->active_locks = src->active_locks;
1336 	dst->active_preempt_locks = src->active_preempt_locks;
1337 	dst->active_rcu_locks = src->active_rcu_locks;
1338 	dst->active_irq_id = src->active_irq_id;
1339 	dst->active_lock_id = src->active_lock_id;
1340 	dst->active_lock_ptr = src->active_lock_ptr;
1341 	return 0;
1342 }
1343 
1344 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1345 {
1346 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1347 
1348 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1349 				GFP_KERNEL_ACCOUNT);
1350 	if (!dst->stack)
1351 		return -ENOMEM;
1352 
1353 	dst->allocated_stack = src->allocated_stack;
1354 
1355 	/* copy stack args state */
1356 	n = src->out_stack_arg_cnt;
1357 	if (n) {
1358 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1359 						 sizeof(struct bpf_reg_state),
1360 						 GFP_KERNEL_ACCOUNT);
1361 		if (!dst->stack_arg_regs)
1362 			return -ENOMEM;
1363 	}
1364 
1365 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1366 	return 0;
1367 }
1368 
1369 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1370 {
1371 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1372 				    sizeof(struct bpf_reference_state));
1373 	if (!state->refs)
1374 		return -ENOMEM;
1375 
1376 	state->acquired_refs = n;
1377 	return 0;
1378 }
1379 
1380 /* Possibly update state->allocated_stack to be at least size bytes. Also
1381  * possibly update the function's high-water mark in its bpf_subprog_info.
1382  */
1383 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1384 {
1385 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1386 
1387 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1388 	size = round_up(size, BPF_REG_SIZE);
1389 	n = size / BPF_REG_SIZE;
1390 
1391 	if (old_n >= n)
1392 		return 0;
1393 
1394 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1395 	if (!state->stack)
1396 		return -ENOMEM;
1397 
1398 	state->allocated_stack = size;
1399 
1400 	/* update known max for given subprogram */
1401 	if (env->subprog_info[state->subprogno].stack_depth < size)
1402 		env->subprog_info[state->subprogno].stack_depth = size;
1403 
1404 	return 0;
1405 }
1406 
1407 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1408 				struct bpf_func_state *state, int cnt)
1409 {
1410 	size_t old_n = state->out_stack_arg_cnt;
1411 
1412 	if (old_n >= cnt)
1413 		return 0;
1414 
1415 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1416 					      sizeof(struct bpf_reg_state));
1417 	if (!state->stack_arg_regs)
1418 		return -ENOMEM;
1419 
1420 	state->out_stack_arg_cnt = cnt;
1421 	return 0;
1422 }
1423 
1424 /* Acquire a pointer id from the env and update the state->refs to include
1425  * this new pointer reference.
1426  * On success, returns a valid pointer id to associate with the register
1427  * On failure, returns a negative errno.
1428  */
1429 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1430 {
1431 	struct bpf_verifier_state *state = env->cur_state;
1432 	int new_ofs = state->acquired_refs;
1433 	int err;
1434 
1435 	err = resize_reference_state(state, state->acquired_refs + 1);
1436 	if (err)
1437 		return NULL;
1438 	state->refs[new_ofs].insn_idx = insn_idx;
1439 
1440 	return &state->refs[new_ofs];
1441 }
1442 
1443 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1444 {
1445 	struct bpf_reference_state *s;
1446 
1447 	s = acquire_reference_state(env, insn_idx);
1448 	if (!s)
1449 		return -ENOMEM;
1450 	s->type = REF_TYPE_PTR;
1451 	s->id = ++env->id_gen;
1452 	s->parent_id = parent_id;
1453 	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
1454 	return s->id;
1455 }
1456 
1457 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1458 			      int id, void *ptr)
1459 {
1460 	struct bpf_verifier_state *state = env->cur_state;
1461 	struct bpf_reference_state *s;
1462 
1463 	s = acquire_reference_state(env, insn_idx);
1464 	if (!s)
1465 		return -ENOMEM;
1466 	s->type = type;
1467 	s->id = id;
1468 	s->ptr = ptr;
1469 
1470 	state->active_locks++;
1471 	state->active_lock_id = id;
1472 	state->active_lock_ptr = ptr;
1473 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_LOCK, true,
1474 				state->active_locks);
1475 	return 0;
1476 }
1477 
1478 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1479 {
1480 	struct bpf_verifier_state *state = env->cur_state;
1481 	struct bpf_reference_state *s;
1482 
1483 	s = acquire_reference_state(env, insn_idx);
1484 	if (!s)
1485 		return -ENOMEM;
1486 	s->type = REF_TYPE_IRQ;
1487 	s->id = ++env->id_gen;
1488 
1489 	state->active_irq_id = s->id;
1490 	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true,
1491 				bpf_diag_irq_depth(state));
1492 	return s->id;
1493 }
1494 
1495 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1496 {
1497 	int last_idx;
1498 	size_t rem;
1499 
1500 	/* IRQ state requires the relative ordering of elements remaining the
1501 	 * same, since it relies on the refs array to behave as a stack, so that
1502 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1503 	 * the array instead of swapping the final element into the deleted idx.
1504 	 */
1505 	last_idx = state->acquired_refs - 1;
1506 	rem = state->acquired_refs - idx - 1;
1507 	if (last_idx && idx != last_idx)
1508 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1509 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1510 	state->acquired_refs--;
1511 	return;
1512 }
1513 
1514 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1515 {
1516 	int i;
1517 
1518 	for (i = 0; i < state->acquired_refs; i++) {
1519 		if (state->refs[i].type != REF_TYPE_PTR)
1520 			continue;
1521 		if (state->refs[i].id == id)
1522 			return true;
1523 	}
1524 
1525 	return false;
1526 }
1527 
1528 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1529 {
1530 	return find_reference_state(env->cur_state, reg->id);
1531 }
1532 
1533 static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr)
1534 {
1535 	struct bpf_verifier_state *state = env->cur_state;
1536 	void *prev_ptr = NULL;
1537 	u32 prev_id = 0;
1538 	int i;
1539 
1540 	for (i = 0; i < state->acquired_refs; i++) {
1541 		if (state->refs[i].type == type && state->refs[i].id == id &&
1542 		    state->refs[i].ptr == ptr) {
1543 			release_reference_state(state, i);
1544 			state->active_locks--;
1545 			/* Reassign active lock (id, ptr). */
1546 			state->active_lock_id = prev_id;
1547 			state->active_lock_ptr = prev_ptr;
1548 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_LOCK,
1549 						false, state->active_locks);
1550 			return 0;
1551 		}
1552 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1553 			prev_id = state->refs[i].id;
1554 			prev_ptr = state->refs[i].ptr;
1555 		}
1556 	}
1557 	return -EINVAL;
1558 }
1559 
1560 static int release_irq_state(struct bpf_verifier_env *env, int id)
1561 {
1562 	struct bpf_verifier_state *state = env->cur_state;
1563 	u32 prev_id = 0;
1564 	int i;
1565 
1566 	if (id != state->active_irq_id)
1567 		return -EACCES;
1568 
1569 	for (i = 0; i < state->acquired_refs; i++) {
1570 		if (state->refs[i].type != REF_TYPE_IRQ)
1571 			continue;
1572 		if (state->refs[i].id == id) {
1573 			release_reference_state(state, i);
1574 			state->active_irq_id = prev_id;
1575 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ,
1576 						false, bpf_diag_irq_depth(state));
1577 			return 0;
1578 		} else {
1579 			prev_id = state->refs[i].id;
1580 		}
1581 	}
1582 	return -EINVAL;
1583 }
1584 
1585 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1586 						   int id, void *ptr)
1587 {
1588 	int i;
1589 
1590 	for (i = 0; i < state->acquired_refs; i++) {
1591 		struct bpf_reference_state *s = &state->refs[i];
1592 
1593 		if (!(s->type & type))
1594 			continue;
1595 
1596 		if (s->id == id && s->ptr == ptr)
1597 			return s;
1598 	}
1599 	return NULL;
1600 }
1601 
1602 static void free_func_state(struct bpf_func_state *state)
1603 {
1604 	if (!state)
1605 		return;
1606 	kfree(state->stack_arg_regs);
1607 	kfree(state->stack);
1608 	kfree(state);
1609 }
1610 
1611 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1612 {
1613 	kfree(state->jmp_history);
1614 	state->jmp_history = NULL;
1615 	state->jmp_history_cnt = 0;
1616 }
1617 
1618 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1619 			    bool free_self)
1620 {
1621 	int i;
1622 
1623 	for (i = 0; i <= state->curframe; i++) {
1624 		free_func_state(state->frame[i]);
1625 		state->frame[i] = NULL;
1626 	}
1627 	kfree(state->refs);
1628 	bpf_clear_jmp_history(state);
1629 	if (free_self)
1630 		kfree(state);
1631 }
1632 
1633 /* copy verifier state from src to dst growing dst stack space
1634  * when necessary to accommodate larger src stack
1635  */
1636 static int copy_func_state(struct bpf_func_state *dst,
1637 			   const struct bpf_func_state *src)
1638 {
1639 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1640 	/* Instruction accounting is path-local, not part of verifier state. */
1641 	dst->insns_subtotal = 0;
1642 	return copy_stack_state(dst, src);
1643 }
1644 
1645 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1646 			   const struct bpf_verifier_state *src)
1647 {
1648 	struct bpf_func_state *dst;
1649 	int i, err;
1650 
1651 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1652 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1653 					  GFP_KERNEL_ACCOUNT);
1654 	if (!dst_state->jmp_history)
1655 		return -ENOMEM;
1656 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1657 
1658 	/* if dst has more stack frames then src frame, free them, this is also
1659 	 * necessary in case of exceptional exits using bpf_throw.
1660 	 */
1661 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1662 		free_func_state(dst_state->frame[i]);
1663 		dst_state->frame[i] = NULL;
1664 	}
1665 	err = copy_reference_state(dst_state, src);
1666 	if (err)
1667 		return err;
1668 	dst_state->speculative = src->speculative;
1669 	dst_state->in_sleepable = src->in_sleepable;
1670 	dst_state->curframe = src->curframe;
1671 	dst_state->branches = src->branches;
1672 	dst_state->parent = src->parent;
1673 	dst_state->first_insn_idx = src->first_insn_idx;
1674 	dst_state->last_insn_idx = src->last_insn_idx;
1675 	dst_state->dfs_depth = src->dfs_depth;
1676 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1677 	dst_state->may_goto_depth = src->may_goto_depth;
1678 	dst_state->equal_state = src->equal_state;
1679 	for (i = 0; i <= src->curframe; i++) {
1680 		dst = dst_state->frame[i];
1681 		if (!dst) {
1682 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1683 			if (!dst)
1684 				return -ENOMEM;
1685 			dst_state->frame[i] = dst;
1686 		}
1687 		err = copy_func_state(dst, src->frame[i]);
1688 		if (err)
1689 			return err;
1690 	}
1691 	return 0;
1692 }
1693 
1694 static u32 state_htab_size(struct bpf_verifier_env *env)
1695 {
1696 	return env->prog->len;
1697 }
1698 
1699 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1700 {
1701 	struct bpf_verifier_state *cur = env->cur_state;
1702 	struct bpf_func_state *state = cur->frame[cur->curframe];
1703 
1704 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1705 }
1706 
1707 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1708 {
1709 	int fr;
1710 
1711 	if (a->curframe != b->curframe)
1712 		return false;
1713 
1714 	for (fr = a->curframe; fr >= 0; fr--)
1715 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1716 			return false;
1717 
1718 	return true;
1719 }
1720 
1721 void bpf_free_backedges(struct bpf_scc_visit *visit)
1722 {
1723 	struct bpf_scc_backedge *backedge, *next;
1724 
1725 	for (backedge = visit->backedges; backedge; backedge = next) {
1726 		bpf_free_verifier_state(&backedge->state, false);
1727 		next = backedge->next;
1728 		kfree(backedge);
1729 	}
1730 	visit->backedges = NULL;
1731 }
1732 
1733 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1734 		     int *insn_idx, bool pop_log)
1735 {
1736 	struct bpf_verifier_state *cur = env->cur_state;
1737 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1738 	int err;
1739 
1740 	if (env->head == NULL)
1741 		return -ENOENT;
1742 
1743 	if (cur) {
1744 		err = bpf_copy_verifier_state(cur, &head->st);
1745 		if (err)
1746 			return err;
1747 		bpf_diag_event_log_restore(env, head->diag_log_pos);
1748 	}
1749 	if (pop_log)
1750 		bpf_vlog_reset(&env->log, head->log_pos);
1751 	if (insn_idx)
1752 		*insn_idx = head->insn_idx;
1753 	if (prev_insn_idx)
1754 		*prev_insn_idx = head->prev_insn_idx;
1755 	elem = head->next;
1756 	bpf_free_verifier_state(&head->st, false);
1757 	kfree(head);
1758 	env->head = elem;
1759 	env->stack_size--;
1760 	return 0;
1761 }
1762 
1763 static bool error_recoverable_with_nospec(int err)
1764 {
1765 	/* Should only return true for non-fatal errors that are allowed to
1766 	 * occur during speculative verification. For these we can insert a
1767 	 * nospec and the program might still be accepted. Do not include
1768 	 * something like ENOMEM because it is likely to re-occur for the next
1769 	 * architectural path once it has been recovered-from in all speculative
1770 	 * paths.
1771 	 */
1772 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1773 }
1774 
1775 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1776 					     int insn_idx, int prev_insn_idx,
1777 					     bool speculative)
1778 {
1779 	struct bpf_verifier_state *cur = env->cur_state;
1780 	struct bpf_verifier_stack_elem *elem;
1781 	int err;
1782 
1783 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1784 	if (!elem)
1785 		return ERR_PTR(-ENOMEM);
1786 
1787 	elem->insn_idx = insn_idx;
1788 	elem->prev_insn_idx = prev_insn_idx;
1789 	elem->next = env->head;
1790 	elem->log_pos = env->log.end_pos;
1791 	elem->diag_log_pos = bpf_diag_event_log_save(env);
1792 	env->head = elem;
1793 	env->stack_size++;
1794 	err = bpf_copy_verifier_state(&elem->st, cur);
1795 	if (err)
1796 		return ERR_PTR(-ENOMEM);
1797 	elem->st.speculative |= speculative;
1798 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1799 		verbose(env, "The sequence of %d jumps is too complex.\n",
1800 			env->stack_size);
1801 		return ERR_PTR(-E2BIG);
1802 	}
1803 	if (elem->st.parent) {
1804 		++elem->st.parent->branches;
1805 		/* WARN_ON(branches > 2) technically makes sense here,
1806 		 * but
1807 		 * 1. speculative states will bump 'branches' for non-branch
1808 		 * instructions
1809 		 * 2. is_state_visited() heuristics may decide not to create
1810 		 * a new state for a sequence of branches and all such current
1811 		 * and cloned states will be pointing to a single parent state
1812 		 * which might have large 'branches' count.
1813 		 */
1814 	}
1815 	return &elem->st;
1816 }
1817 
1818 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1819 {
1820 	char *buf = env->tmp_arg_name;
1821 	int len = sizeof(env->tmp_arg_name);
1822 	int arg, regno = reg_from_argno(argno);
1823 
1824 	if (regno >= 0) {
1825 		snprintf(buf, len, "R%d", regno);
1826 	} else {
1827 		arg = arg_from_argno(argno);
1828 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1829 	}
1830 
1831 	return buf;
1832 }
1833 
1834 static const int caller_saved[CALLER_SAVED_REGS] = {
1835 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1836 };
1837 
1838 static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
1839 					 struct bpf_reg_state *regs)
1840 {
1841 	int i;
1842 
1843 	for (i = 1; i < CALLER_SAVED_REGS; i++) {
1844 		bpf_diag_record_scrub(env, &regs[caller_saved[i]],
1845 				      BPF_DIAG_MOD_CALLER_SAVED);
1846 	}
1847 }
1848 
1849 /* This helper doesn't clear reg->id */
1850 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1851 {
1852 	reg->var_off = tnum_const(imm);
1853 	reg->r64 = cnum64_from_urange(imm, imm);
1854 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1855 }
1856 
1857 /* Mark the unknown part of a register (variable offset or scalar value) as
1858  * known to have the value @imm.
1859  */
1860 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1861 {
1862 	/* Clear off and union(map_ptr, range) */
1863 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1864 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1865 	reg->id = 0;
1866 	reg->parent_id = 0;
1867 	___mark_reg_known(reg, imm);
1868 }
1869 
1870 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1871 {
1872 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1873 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1874 }
1875 
1876 /* Mark the 'variable offset' part of a register as zero.  This should be
1877  * used only on registers holding a pointer type.
1878  */
1879 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1880 {
1881 	__mark_reg_known(reg, 0);
1882 }
1883 
1884 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1885 {
1886 	__mark_reg_known(reg, 0);
1887 	reg->type = SCALAR_VALUE;
1888 	/* all scalars are assumed imprecise initially (unless unprivileged,
1889 	 * in which case everything is forced to be precise)
1890 	 */
1891 	reg->precise = !env->bpf_capable;
1892 }
1893 
1894 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1895 				struct bpf_reg_state *regs, u32 regno)
1896 {
1897 	__mark_reg_known_zero(regs + regno);
1898 }
1899 
1900 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1901 			      bool first_slot, int id, int parent_id)
1902 {
1903 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1904 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1905 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1906 	 */
1907 	__mark_reg_known_zero(reg);
1908 	reg->type = CONST_PTR_TO_DYNPTR;
1909 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1910 	reg->id = id;
1911 	reg->parent_id = parent_id;
1912 	reg->dynptr.type = type;
1913 	reg->dynptr.first_slot = first_slot;
1914 }
1915 
1916 /*
1917  * Refine the return type of the bpf_map_lookup_elem() for special map types:
1918  * map-in-map, xskmap, sockmap and sockhash.
1919  */
1920 static void refine_map_lookup_value(struct bpf_reg_state *reg)
1921 {
1922 	enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL;
1923 	const struct bpf_map *map = reg->map_ptr;
1924 
1925 	if (map->inner_map_meta) {
1926 		reg->type = CONST_PTR_TO_MAP | maybe_null;
1927 		reg->map_ptr = map->inner_map_meta;
1928 		/* transfer reg's id which is unique for every map_lookup_elem
1929 		 * as UID of the inner map.
1930 		 */
1931 		if (btf_record_has_field(map->inner_map_meta->record,
1932 					 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK))
1933 			reg->map_uid = reg->id;
1934 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1935 		reg->type = PTR_TO_XDP_SOCK | maybe_null;
1936 	} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1937 		   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1938 		reg->type = PTR_TO_SOCKET | maybe_null;
1939 	}
1940 }
1941 
1942 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1943 {
1944 	reg->type &= ~PTR_MAYBE_NULL;
1945 }
1946 
1947 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1948 				struct btf_field_graph_root *ds_head)
1949 {
1950 	__mark_reg_known(&regs[regno], ds_head->node_offset);
1951 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1952 	regs[regno].btf = ds_head->btf;
1953 	regs[regno].btf_id = ds_head->value_btf_id;
1954 }
1955 
1956 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1957 {
1958 	return type_is_pkt_pointer(reg->type);
1959 }
1960 
1961 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1962 {
1963 	return reg_is_pkt_pointer(reg) ||
1964 	       reg->type == PTR_TO_PACKET_END;
1965 }
1966 
1967 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1968 {
1969 	return base_type(reg->type) == PTR_TO_MEM &&
1970 	       (reg->type &
1971 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
1972 }
1973 
1974 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1975 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1976 				    enum bpf_reg_type which)
1977 {
1978 	/* The register can already have a range from prior markings.
1979 	 * This is fine as long as it hasn't been advanced from its
1980 	 * origin.
1981 	 */
1982 	return reg->type == which &&
1983 	       reg->id == 0 &&
1984 	       tnum_equals_const(reg->var_off, 0);
1985 }
1986 
1987 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1988 {
1989 	reg->r32 = CNUM32_UNBOUNDED;
1990 }
1991 
1992 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1993 {
1994 	reg->r64 = CNUM64_UNBOUNDED;
1995 }
1996 
1997 /* Reset the min/max bounds of a register */
1998 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1999 {
2000 	__mark_reg64_unbounded(reg);
2001 	__mark_reg32_unbounded(reg);
2002 }
2003 
2004 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
2005 {
2006 	__mark_reg64_unbounded(reg);
2007 	reg->var_off = tnum_unknown;
2008 }
2009 
2010 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
2011 {
2012 	__mark_reg32_unbounded(reg);
2013 	reg->var_off = tnum_unknown;
2014 }
2015 
2016 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
2017 {
2018 	tnum = tnum_subreg(tnum);
2019 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
2020 		/* min signed is max(sign bit) | min(other bits) */
2021 		/* max signed is min(sign bit) | max(other bits) */
2022 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
2023 					  tnum.value | (tnum.mask & S32_MAX));
2024 	else
2025 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
2026 }
2027 
2028 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
2029 {
2030 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
2031 		/* min signed is max(sign bit) | min(other bits) */
2032 		/* max signed is min(sign bit) | max(other bits) */
2033 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
2034 					  tnum.value | (tnum.mask & S64_MAX));
2035 	else
2036 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
2037 }
2038 
2039 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2040 {
2041 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
2042 }
2043 
2044 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2045 {
2046 	u64 tnum_next, tmax;
2047 	bool umin_in_tnum;
2048 
2049 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2050 
2051 	/* Check if u64 and tnum overlap in a single value */
2052 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2053 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2054 	tmax = reg->var_off.value | reg->var_off.mask;
2055 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2056 		/* The u64 range and the tnum only overlap in umin.
2057 		 * u64:  ---[xxxxxx]-----
2058 		 * tnum: --xx----------x-
2059 		 */
2060 		___mark_reg_known(reg, reg_umin(reg));
2061 	} else if (!umin_in_tnum && tnum_next == tmax) {
2062 		/* The u64 range and the tnum only overlap in the maximum value
2063 		 * represented by the tnum, called tmax.
2064 		 * u64:  ---[xxxxxx]-----
2065 		 * tnum: xx-----x--------
2066 		 */
2067 		___mark_reg_known(reg, tmax);
2068 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2069 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2070 		/* The u64 range and the tnum only overlap in between umin
2071 		 * (excluded) and umax.
2072 		 * u64:  ---[xxxxxx]-----
2073 		 * tnum: xx----x-------x-
2074 		 */
2075 		___mark_reg_known(reg, tnum_next);
2076 	}
2077 }
2078 
2079 static void __update_reg_bounds(struct bpf_reg_state *reg)
2080 {
2081 	__update_reg32_bounds(reg);
2082 	__update_reg64_bounds(reg);
2083 }
2084 
2085 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2086 {
2087 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2088 }
2089 
2090 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2091 {
2092 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2093 }
2094 
2095 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2096 {
2097 	deduce_bounds_32_from_64(reg);
2098 	deduce_bounds_64_from_32(reg);
2099 }
2100 
2101 /* Attempts to improve var_off based on unsigned min/max information */
2102 static void __reg_bound_offset(struct bpf_reg_state *reg)
2103 {
2104 	struct tnum var64_off = tnum_intersect(reg->var_off,
2105 					       tnum_range(reg_umin(reg),
2106 							  reg_umax(reg)));
2107 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2108 					       tnum_range(reg_u32_min(reg),
2109 							  reg_u32_max(reg)));
2110 
2111 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2112 }
2113 
2114 static bool range_bounds_violation(struct bpf_reg_state *reg);
2115 
2116 static void reg_bounds_sync(struct bpf_reg_state *reg)
2117 {
2118 	/* If the input reg_state is invalid, we can exit early */
2119 	if (range_bounds_violation(reg))
2120 		return;
2121 	/* We might have learned new bounds from the var_off. */
2122 	__update_reg_bounds(reg);
2123 	/* We might have learned something about the sign bit. */
2124 	__reg_deduce_bounds(reg);
2125 	__reg_deduce_bounds(reg);
2126 	/* We might have learned some bits from the bounds. */
2127 	__reg_bound_offset(reg);
2128 	/* Intersecting with the old var_off might have improved our bounds
2129 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2130 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2131 	 */
2132 	__update_reg_bounds(reg);
2133 }
2134 
2135 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2136 {
2137 	if (!tnum_is_const(reg->var_off))
2138 		return false;
2139 
2140 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2141 }
2142 
2143 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2144 {
2145 	if (!tnum_subreg_is_const(reg->var_off))
2146 		return false;
2147 
2148 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2149 }
2150 
2151 static bool range_bounds_violation(struct bpf_reg_state *reg)
2152 {
2153 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2154 }
2155 
2156 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2157 				   struct bpf_reg_state *reg, const char *ctx)
2158 {
2159 	const char *msg;
2160 
2161 	if (range_bounds_violation(reg)) {
2162 		msg = "range bounds violation";
2163 		goto out;
2164 	}
2165 
2166 	if (const_tnum_range_mismatch(reg)) {
2167 		msg = "const tnum out of sync with range bounds";
2168 		goto out;
2169 	}
2170 
2171 	if (const_tnum_range_mismatch_32(reg)) {
2172 		msg = "const subreg tnum out of sync with range bounds";
2173 		goto out;
2174 	}
2175 
2176 	return 0;
2177 out:
2178 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2179 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)",
2180 		     ctx, msg,
2181 		     reg->r64.base, reg->r64.size,
2182 		     reg->r32.base, reg->r32.size,
2183 		     reg->var_off.value, reg->var_off.mask);
2184 	if (env->test_reg_invariants)
2185 		return -EFAULT;
2186 	__mark_reg_unbounded(reg);
2187 	return 0;
2188 }
2189 
2190 /* Mark a register as having a completely unknown (scalar) value. */
2191 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2192 {
2193 	memset(reg, 0, sizeof(*reg));
2194 	reg->type = SCALAR_VALUE;
2195 	reg->var_off = tnum_unknown;
2196 	__mark_reg_unbounded(reg);
2197 }
2198 
2199 /* Mark a register as having a completely unknown (scalar) value,
2200  * initialize .precise as true when not bpf capable.
2201  */
2202 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2203 			       struct bpf_reg_state *reg)
2204 {
2205 	bpf_mark_reg_unknown_imprecise(reg);
2206 	reg->precise = !env->bpf_capable;
2207 }
2208 
2209 static void mark_reg_unknown(struct bpf_verifier_env *env,
2210 			     struct bpf_reg_state *regs, u32 regno)
2211 {
2212 	__mark_reg_unknown(env, regs + regno);
2213 }
2214 
2215 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2216 				struct bpf_reg_state *regs,
2217 				u32 regno,
2218 				s32 s32_min,
2219 				s32 s32_max)
2220 {
2221 	struct bpf_reg_state *reg = regs + regno;
2222 
2223 	reg_set_srange32(reg,
2224 			 max_t(s32, reg_s32_min(reg), s32_min),
2225 			 min_t(s32, reg_s32_max(reg), s32_max));
2226 	reg_set_srange64(reg,
2227 			 max_t(s64, reg_smin(reg), s32_min),
2228 			 min_t(s64, reg_smax(reg), s32_max));
2229 
2230 	reg_bounds_sync(reg);
2231 
2232 	return reg_bounds_sanity_check(env, reg, "s32_range");
2233 }
2234 
2235 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2236 			   struct bpf_reg_state *reg)
2237 {
2238 	__mark_reg_unknown(env, reg);
2239 	reg->type = NOT_INIT;
2240 }
2241 
2242 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2243 			   struct bpf_reg_state *regs, u32 regno,
2244 			   enum bpf_reg_type reg_type,
2245 			   struct btf *btf, u32 btf_id,
2246 			   enum bpf_type_flag flag)
2247 {
2248 	switch (reg_type) {
2249 	case SCALAR_VALUE:
2250 		mark_reg_unknown(env, regs, regno);
2251 		return 0;
2252 	case PTR_TO_BTF_ID:
2253 		mark_reg_known_zero(env, regs, regno);
2254 		regs[regno].type = PTR_TO_BTF_ID | flag;
2255 		regs[regno].btf = btf;
2256 		regs[regno].btf_id = btf_id;
2257 		if (type_may_be_null(flag))
2258 			regs[regno].id = ++env->id_gen;
2259 		return 0;
2260 	case PTR_TO_MEM:
2261 		mark_reg_known_zero(env, regs, regno);
2262 		regs[regno].type = PTR_TO_MEM | flag;
2263 		regs[regno].mem_size = 0;
2264 		return 0;
2265 	default:
2266 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2267 		return -EFAULT;
2268 	}
2269 }
2270 
2271 static void init_reg_state(struct bpf_verifier_env *env,
2272 			   struct bpf_func_state *state)
2273 {
2274 	struct bpf_reg_state *regs = state->regs;
2275 	int i;
2276 
2277 	for (i = 0; i < MAX_BPF_REG; i++) {
2278 		bpf_mark_reg_not_init(env, &regs[i]);
2279 	}
2280 
2281 	/* frame pointer */
2282 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2283 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2284 	regs[BPF_REG_FP].frameno = state->frameno;
2285 }
2286 
2287 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2288 {
2289 	/*
2290 	 * return_32bit is set to false by default and set explicitly
2291 	 * by the caller when necessary.
2292 	 */
2293 	return (struct bpf_retval_range){ minval, maxval, false };
2294 }
2295 
2296 static void init_func_state(struct bpf_verifier_env *env,
2297 			    struct bpf_func_state *state,
2298 			    int callsite, int frameno, int subprogno)
2299 {
2300 	state->callsite = callsite;
2301 	state->frameno = frameno;
2302 	bpf_diag_init_frame(env, state);
2303 	state->subprogno = subprogno;
2304 	state->callback_ret_range = retval_range(0, 0);
2305 	init_reg_state(env, state);
2306 	mark_verifier_state_scratched(env);
2307 }
2308 
2309 /* Similar to push_stack(), but for async callbacks */
2310 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2311 						int insn_idx, int prev_insn_idx,
2312 						int subprog, bool is_sleepable)
2313 {
2314 	struct bpf_verifier_stack_elem *elem;
2315 	struct bpf_func_state *frame;
2316 
2317 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2318 	if (!elem)
2319 		return ERR_PTR(-ENOMEM);
2320 
2321 	elem->insn_idx = insn_idx;
2322 	elem->prev_insn_idx = prev_insn_idx;
2323 	elem->next = env->head;
2324 	elem->log_pos = env->log.end_pos;
2325 	elem->diag_log_pos = bpf_diag_event_log_save(env);
2326 	env->head = elem;
2327 	env->stack_size++;
2328 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2329 		verbose(env,
2330 			"The sequence of %d jumps is too complex for async cb.\n",
2331 			env->stack_size);
2332 		return ERR_PTR(-E2BIG);
2333 	}
2334 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2335 	 * The caller state doesn't matter.
2336 	 * This is async callback. It starts in a fresh stack.
2337 	 * Initialize it similar to do_check_common().
2338 	 */
2339 	elem->st.branches = 1;
2340 	elem->st.in_sleepable = is_sleepable;
2341 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2342 	if (!frame)
2343 		return ERR_PTR(-ENOMEM);
2344 	init_func_state(env, frame,
2345 			BPF_MAIN_FUNC /* callsite */,
2346 			0 /* frameno within this callchain */,
2347 			subprog /* subprog number within this prog */);
2348 	elem->st.frame[0] = frame;
2349 	return &elem->st;
2350 }
2351 
2352 static int cmp_subprogs(const void *a, const void *b)
2353 {
2354 	return ((struct bpf_subprog_info *)a)->start -
2355 	       ((struct bpf_subprog_info *)b)->start;
2356 }
2357 
2358 /* Find subprogram that contains instruction at 'off' */
2359 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2360 {
2361 	struct bpf_subprog_info *vals = env->subprog_info;
2362 	int l, r, m;
2363 
2364 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2365 		return NULL;
2366 
2367 	l = 0;
2368 	r = env->subprog_cnt - 1;
2369 	while (l < r) {
2370 		m = l + (r - l + 1) / 2;
2371 		if (vals[m].start <= off)
2372 			l = m;
2373 		else
2374 			r = m - 1;
2375 	}
2376 	return &vals[l];
2377 }
2378 
2379 /* Find subprogram that starts exactly at 'off' */
2380 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2381 {
2382 	struct bpf_subprog_info *p;
2383 
2384 	p = bpf_find_containing_subprog(env, off);
2385 	if (!p || p->start != off)
2386 		return -ENOENT;
2387 	return p - env->subprog_info;
2388 }
2389 
2390 static int add_subprog(struct bpf_verifier_env *env, int off)
2391 {
2392 	int insn_cnt = env->prog->len;
2393 	int ret;
2394 
2395 	if (off >= insn_cnt || off < 0) {
2396 		verbose(env, "call to invalid destination\n");
2397 		return -EINVAL;
2398 	}
2399 	ret = bpf_find_subprog(env, off);
2400 	if (ret >= 0)
2401 		return ret;
2402 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2403 		verbose(env, "too many subprograms\n");
2404 		return -E2BIG;
2405 	}
2406 	/* determine subprog starts. The end is one before the next starts */
2407 	env->subprog_info[env->subprog_cnt++].start = off;
2408 	sort(env->subprog_info, env->subprog_cnt,
2409 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2410 	return env->subprog_cnt - 1;
2411 }
2412 
2413 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2414 {
2415 	struct bpf_prog_aux *aux = env->prog->aux;
2416 	struct btf *btf = aux->btf;
2417 	const struct btf_type *t;
2418 	u32 main_btf_id, id;
2419 	const char *name;
2420 	int ret, i;
2421 
2422 	/* Non-zero func_info_cnt implies valid btf */
2423 	if (!aux->func_info_cnt)
2424 		return 0;
2425 	main_btf_id = aux->func_info[0].type_id;
2426 
2427 	t = btf_type_by_id(btf, main_btf_id);
2428 	if (!t) {
2429 		verbose(env, "invalid btf id for main subprog in func_info\n");
2430 		return -EINVAL;
2431 	}
2432 
2433 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2434 	if (IS_ERR(name)) {
2435 		ret = PTR_ERR(name);
2436 		/* If there is no tag present, there is no exception callback */
2437 		if (ret == -ENOENT)
2438 			ret = 0;
2439 		else if (ret == -EEXIST)
2440 			verbose(env, "multiple exception callback tags for main subprog\n");
2441 		return ret;
2442 	}
2443 
2444 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2445 	if (ret < 0) {
2446 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2447 		return ret;
2448 	}
2449 	id = ret;
2450 	t = btf_type_by_id(btf, id);
2451 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2452 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2453 		return -EINVAL;
2454 	}
2455 	ret = 0;
2456 	for (i = 0; i < aux->func_info_cnt; i++) {
2457 		if (aux->func_info[i].type_id != id)
2458 			continue;
2459 		ret = aux->func_info[i].insn_off;
2460 		/* Further func_info and subprog checks will also happen
2461 		 * later, so assume this is the right insn_off for now.
2462 		 */
2463 		if (!ret) {
2464 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2465 			ret = -EINVAL;
2466 		}
2467 	}
2468 	if (!ret) {
2469 		verbose(env, "exception callback type id not found in func_info\n");
2470 		ret = -EINVAL;
2471 	}
2472 	return ret;
2473 }
2474 
2475 #define MAX_KFUNC_BTFS	256
2476 
2477 struct bpf_kfunc_btf {
2478 	struct btf *btf;
2479 	struct module *module;
2480 	u16 offset;
2481 };
2482 
2483 struct bpf_kfunc_btf_tab {
2484 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2485 	u32 nr_descs;
2486 };
2487 
2488 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2489 {
2490 	const struct bpf_kfunc_desc *d0 = a;
2491 	const struct bpf_kfunc_desc *d1 = b;
2492 
2493 	/* func_id is not greater than BTF_MAX_TYPE */
2494 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2495 }
2496 
2497 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498 {
2499 	const struct bpf_kfunc_btf *d0 = a;
2500 	const struct bpf_kfunc_btf *d1 = b;
2501 
2502 	return d0->offset - d1->offset;
2503 }
2504 
2505 static struct bpf_kfunc_desc *
2506 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2507 {
2508 	struct bpf_kfunc_desc desc = {
2509 		.func_id = func_id,
2510 		.offset = offset,
2511 	};
2512 	struct bpf_kfunc_desc_tab *tab;
2513 
2514 	tab = prog->aux->kfunc_tab;
2515 	return bsearch(&desc, tab->descs, tab->nr_descs,
2516 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2517 }
2518 
2519 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520 		       u16 btf_fd_idx, u8 **func_addr)
2521 {
2522 	const struct bpf_kfunc_desc *desc;
2523 
2524 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2525 	if (!desc)
2526 		return -EFAULT;
2527 
2528 	*func_addr = (u8 *)desc->addr;
2529 	return 0;
2530 }
2531 
2532 #define BPF_FD_SLOT_BTF	1UL
2533 
2534 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map)
2535 {
2536 	slot->val = (unsigned long)map;
2537 }
2538 
2539 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf)
2540 {
2541 	slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF;
2542 }
2543 
2544 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot)
2545 {
2546 	if (slot.val & BPF_FD_SLOT_BTF)
2547 		return NULL;
2548 	return (struct bpf_map *)slot.val;
2549 }
2550 
2551 static struct btf *fd_slot_btf(struct bpf_fd_array slot)
2552 {
2553 	if (!(slot.val & BPF_FD_SLOT_BTF))
2554 		return NULL;
2555 	return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF);
2556 }
2557 
2558 static struct btf *
2559 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx)
2560 {
2561 	struct btf *btf;
2562 
2563 	if (idx >= env->fd_array_cnt) {
2564 		verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n",
2565 			idx, env->fd_array_cnt);
2566 		return ERR_PTR(-EINVAL);
2567 	}
2568 	btf = fd_slot_btf(env->fd_array[idx]);
2569 	if (!btf) {
2570 		verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx);
2571 		return ERR_PTR(-EINVAL);
2572 	}
2573 	btf_get(btf);
2574 	return btf;
2575 }
2576 
2577 static struct btf *
2578 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx)
2579 {
2580 	struct btf *btf;
2581 	int btf_fd;
2582 
2583 	if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw,
2584 				    (size_t)idx * sizeof(btf_fd), sizeof(btf_fd)))
2585 		return ERR_PTR(-EFAULT);
2586 	btf = btf_get_by_fd(btf_fd);
2587 	if (IS_ERR(btf)) {
2588 		verbose(env, "invalid module BTF fd specified\n");
2589 		return btf;
2590 	}
2591 	return btf;
2592 }
2593 
2594 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx)
2595 {
2596 	if (env->signature) {
2597 		verbose(env, "signed program cannot bind any BTF\n");
2598 		return ERR_PTR(-EACCES);
2599 	}
2600 	if (env->fd_array)
2601 		return fd_array_get_btf_continuous(env, idx);
2602 	if (!bpfptr_is_null(env->fd_array_raw))
2603 		return fd_array_get_btf_sparse(env, idx);
2604 
2605 	verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2606 	return ERR_PTR(-EPROTO);
2607 }
2608 
2609 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2610 					 s16 offset)
2611 {
2612 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2613 	struct bpf_kfunc_btf_tab *tab;
2614 	struct bpf_kfunc_btf *b;
2615 	struct module *mod;
2616 	struct btf *btf;
2617 
2618 	tab = env->prog->aux->kfunc_btf_tab;
2619 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2620 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2621 	if (!b) {
2622 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2623 			verbose(env, "too many different module BTFs\n");
2624 			return ERR_PTR(-E2BIG);
2625 		}
2626 
2627 		btf = fd_array_get_btf(env, offset);
2628 		if (IS_ERR(btf))
2629 			return btf;
2630 		if (!btf_is_module(btf)) {
2631 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2632 			btf_put(btf);
2633 			return ERR_PTR(-EINVAL);
2634 		}
2635 
2636 		mod = btf_try_get_module(btf);
2637 		if (!mod) {
2638 			btf_put(btf);
2639 			return ERR_PTR(-ENXIO);
2640 		}
2641 
2642 		b = &tab->descs[tab->nr_descs++];
2643 		b->btf = btf;
2644 		b->module = mod;
2645 		b->offset = offset;
2646 
2647 		/* sort() reorders entries by value, so b may no longer point
2648 		 * to the right entry after this
2649 		 */
2650 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2651 		     kfunc_btf_cmp_by_off, NULL);
2652 	} else {
2653 		btf = b->btf;
2654 	}
2655 
2656 	return btf;
2657 }
2658 
2659 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2660 {
2661 	if (!tab)
2662 		return;
2663 
2664 	while (tab->nr_descs--) {
2665 		module_put(tab->descs[tab->nr_descs].module);
2666 		btf_put(tab->descs[tab->nr_descs].btf);
2667 	}
2668 	kfree(tab);
2669 }
2670 
2671 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2672 {
2673 	if (offset) {
2674 		if (offset < 0) {
2675 			/* In the future, this can be allowed to increase limit
2676 			 * of fd index into fd_array, interpreted as u16.
2677 			 */
2678 			verbose(env, "negative offset disallowed for kernel module function call\n");
2679 			return ERR_PTR(-EINVAL);
2680 		}
2681 
2682 		return __find_kfunc_desc_btf(env, offset);
2683 	}
2684 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2685 }
2686 
2687 static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset)
2688 {
2689 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2690 	struct bpf_kfunc_btf_tab *tab;
2691 	struct bpf_kfunc_btf *b;
2692 
2693 	if (!offset)
2694 		return btf_vmlinux ?: ERR_PTR(-ENOENT);
2695 	if (offset < 0)
2696 		return ERR_PTR(-EINVAL);
2697 
2698 	tab = env->prog->aux->kfunc_btf_tab;
2699 	if (!tab)
2700 		return ERR_PTR(-ENOENT);
2701 
2702 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2703 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2704 	return b ? b->btf : ERR_PTR(-ENOENT);
2705 }
2706 
2707 #define KF_IMPL_SUFFIX "_impl"
2708 
2709 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2710 						    struct btf *btf,
2711 						    const char *func_name)
2712 {
2713 	const struct btf_type *func;
2714 	char buf[KSYM_NAME_LEN];
2715 	s32 impl_id;
2716 	int len;
2717 
2718 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2719 	if (len < 0 || len >= sizeof(buf)) {
2720 		bpf_log(log, "function name %s%s is too long\n",
2721 			func_name, KF_IMPL_SUFFIX);
2722 		return NULL;
2723 	}
2724 
2725 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
2726 	if (impl_id <= 0) {
2727 		bpf_log(log, "cannot find function %s in BTF\n", buf);
2728 		return NULL;
2729 	}
2730 
2731 	func = btf_type_by_id(btf, impl_id);
2732 
2733 	return btf_type_by_id(btf, func->type);
2734 }
2735 
2736 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
2737 			    s32 func_id,
2738 			    s16 offset,
2739 			    struct bpf_kfunc_meta *kfunc)
2740 {
2741 	const struct btf_type *func, *func_proto;
2742 	const char *func_name;
2743 	u32 *kfunc_flags;
2744 	struct btf *btf;
2745 
2746 	if (func_id <= 0) {
2747 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
2748 		return -EINVAL;
2749 	}
2750 
2751 	btf = find_kfunc_desc_btf(env, offset);
2752 	if (IS_ERR(btf)) {
2753 		verbose(env, "failed to find BTF for kernel function\n");
2754 		return PTR_ERR(btf);
2755 	}
2756 
2757 	/*
2758 	 * Note that kfunc_flags may be NULL at this point, which
2759 	 * means that we couldn't find func_id in any relevant
2760 	 * kfunc_id_set. This most likely indicates an invalid kfunc
2761 	 * call.  However we don't fail with an error here,
2762 	 * and let the caller decide what to do with NULL kfunc->flags.
2763 	 */
2764 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
2765 
2766 	func = btf_type_by_id(btf, func_id);
2767 	if (!func || !btf_type_is_func(func)) {
2768 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
2769 		return -EINVAL;
2770 	}
2771 
2772 	func_name = btf_name_by_offset(btf, func->name_off);
2773 
2774 	/*
2775 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
2776 	 * can be found through the counterpart _impl kfunc.
2777 	 */
2778 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
2779 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
2780 	else
2781 		func_proto = btf_type_by_id(btf, func->type);
2782 
2783 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2784 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
2785 			func_id);
2786 		return -EINVAL;
2787 	}
2788 
2789 	memset(kfunc, 0, sizeof(*kfunc));
2790 	kfunc->btf = btf;
2791 	kfunc->id = func_id;
2792 	kfunc->name = func_name;
2793 	kfunc->proto = func_proto;
2794 	kfunc->flags = kfunc_flags;
2795 
2796 	return 0;
2797 }
2798 
2799 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2800 			       struct bpf_func_proto *proto);
2801 
2802 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
2803 {
2804 	struct bpf_call_arg_meta meta;
2805 	struct bpf_kfunc_btf_tab *btf_tab;
2806 	struct btf_func_model func_model;
2807 	struct bpf_kfunc_desc_tab *tab;
2808 	struct bpf_prog_aux *prog_aux;
2809 	struct bpf_kfunc_meta kfunc;
2810 	struct bpf_kfunc_desc *desc;
2811 	unsigned long addr;
2812 	int err;
2813 
2814 	prog_aux = env->prog->aux;
2815 	tab = prog_aux->kfunc_tab;
2816 	btf_tab = prog_aux->kfunc_btf_tab;
2817 	if (!tab) {
2818 		if (!btf_vmlinux) {
2819 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2820 			return -ENOTSUPP;
2821 		}
2822 
2823 		if (!env->prog->jit_requested) {
2824 			verbose(env, "JIT is required for calling kernel function\n");
2825 			return -ENOTSUPP;
2826 		}
2827 
2828 		if (!bpf_jit_supports_kfunc_call()) {
2829 			verbose(env, "JIT does not support calling kernel function\n");
2830 			return -ENOTSUPP;
2831 		}
2832 
2833 		if (!env->prog->gpl_compatible) {
2834 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2835 			return -EINVAL;
2836 		}
2837 
2838 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
2839 		if (!tab)
2840 			return -ENOMEM;
2841 		prog_aux->kfunc_tab = tab;
2842 	}
2843 
2844 	env->prog->jit_required = 1;
2845 
2846 	/* func_id == 0 is always invalid, but instead of returning an error, be
2847 	 * conservative and wait until the code elimination pass before returning
2848 	 * error, so that invalid calls that get pruned out can be in BPF programs
2849 	 * loaded from userspace.  It is also required that offset be untouched
2850 	 * for such calls.
2851 	 */
2852 	if (!func_id && !offset)
2853 		return 0;
2854 
2855 	if (!btf_tab && offset) {
2856 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
2857 		if (!btf_tab)
2858 			return -ENOMEM;
2859 		prog_aux->kfunc_btf_tab = btf_tab;
2860 	}
2861 
2862 	if (find_kfunc_desc(env->prog, func_id, offset))
2863 		return 0;
2864 
2865 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2866 		verbose(env, "too many different kernel function calls\n");
2867 		return -E2BIG;
2868 	}
2869 
2870 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
2871 	if (err)
2872 		return err;
2873 
2874 	addr = kallsyms_lookup_name(kfunc.name);
2875 	if (!addr) {
2876 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
2877 		return -EINVAL;
2878 	}
2879 
2880 	if (bpf_dev_bound_kfunc_id(func_id)) {
2881 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2882 		if (err)
2883 			return err;
2884 	}
2885 
2886 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
2887 	if (err)
2888 		return err;
2889 
2890 	memset(&meta, 0, sizeof(meta));
2891 	meta.btf = kfunc.btf;
2892 	meta.func_id = kfunc.id;
2893 	meta.func_proto = kfunc.proto;
2894 	meta.func_name = kfunc.name;
2895 	meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0;
2896 
2897 	tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT);
2898 	if (!tab)
2899 		return -ENOMEM;
2900 	prog_aux->kfunc_tab = tab;
2901 
2902 	desc = &tab->descs[tab->nr_descs];
2903 	memset(desc, 0, sizeof(*desc));
2904 
2905 	err = gen_kfunc_arg_proto(env, &meta, &desc->proto);
2906 	if (err)
2907 		return err;
2908 
2909 	desc->func_id = func_id;
2910 	desc->offset = offset;
2911 	desc->addr = addr;
2912 	desc->func_model = func_model;
2913 	tab->nr_descs++;
2914 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2915 	     kfunc_desc_cmp_by_id_off, NULL);
2916 	return 0;
2917 }
2918 
2919 static int add_subprogs(struct bpf_verifier_env *env)
2920 {
2921 	struct bpf_subprog_info *subprog = env->subprog_info;
2922 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2923 	struct bpf_insn *insn = env->prog->insnsi;
2924 	const char *operation, *suggestion;
2925 
2926 	/* Add entry function. */
2927 	ret = add_subprog(env, 0);
2928 	if (ret)
2929 		return ret;
2930 
2931 	for (i = 0; i < insn_cnt; i++, insn++) {
2932 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
2933 			continue;
2934 
2935 		if (!env->bpf_capable) {
2936 			if (bpf_pseudo_func(insn)) {
2937 				operation = "BPF function reference";
2938 				suggestion = "Load this program with the required capability, or avoid BPF function references in unprivileged programs.";
2939 			} else {
2940 				operation = "BPF-to-BPF function call";
2941 				suggestion = "Load this program with the required capability, or avoid BPF-to-BPF function calls in unprivileged programs.";
2942 			}
2943 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2944 			bpf_diag_policy(
2945 				env, i, operation,
2946 				"loading or calling other BPF functions requires CAP_BPF or CAP_SYS_ADMIN",
2947 				suggestion);
2948 			return -EPERM;
2949 		}
2950 
2951 		ret = add_subprog(env, i + insn->imm + 1);
2952 		if (ret < 0)
2953 			return ret;
2954 	}
2955 
2956 	ret = bpf_find_exception_callback_insn_off(env);
2957 	if (ret < 0)
2958 		return ret;
2959 	ex_cb_insn = ret;
2960 
2961 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2962 	 * marked using BTF decl tag to serve as the exception callback.
2963 	 */
2964 	if (ex_cb_insn) {
2965 		ret = add_subprog(env, ex_cb_insn);
2966 		if (ret < 0)
2967 			return ret;
2968 		for (i = 1; i < env->subprog_cnt; i++) {
2969 			if (env->subprog_info[i].start != ex_cb_insn)
2970 				continue;
2971 			env->exception_callback_subprog = i;
2972 			bpf_mark_subprog_exc_cb(env, i);
2973 			break;
2974 		}
2975 	}
2976 
2977 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2978 	 * logic. 'subprog_cnt' should not be increased.
2979 	 */
2980 	subprog[env->subprog_cnt].start = insn_cnt;
2981 
2982 	if (env->log.level & BPF_LOG_LEVEL2)
2983 		for (i = 0; i < env->subprog_cnt; i++)
2984 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2985 
2986 	return 0;
2987 }
2988 
2989 static int add_kfuncs(struct bpf_verifier_env *env)
2990 {
2991 	struct bpf_insn *insn = env->prog->insnsi;
2992 	int i, ret, insn_cnt = env->prog->len;
2993 
2994 	for (i = 0; i < insn_cnt; i++, insn++) {
2995 		if (!bpf_pseudo_kfunc_call(insn))
2996 			continue;
2997 
2998 		if (!env->bpf_capable) {
2999 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3000 			bpf_diag_policy(
3001 				env, i, "kernel function call",
3002 				"calling kernel functions requires CAP_BPF or CAP_SYS_ADMIN",
3003 				"Load this program with the required capability, or avoid kernel function calls in unprivileged programs.");
3004 			return -EPERM;
3005 		}
3006 
3007 		ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
3008 		if (ret < 0)
3009 			return ret;
3010 	}
3011 
3012 	return 0;
3013 }
3014 
3015 static int check_subprogs(struct bpf_verifier_env *env)
3016 {
3017 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3018 	struct bpf_subprog_info *subprog = env->subprog_info;
3019 	struct bpf_insn *insn = env->prog->insnsi;
3020 	int insn_cnt = env->prog->len;
3021 
3022 	/* now check that all jumps are within the same subprog */
3023 	subprog_start = subprog[cur_subprog].start;
3024 	subprog_end = subprog[cur_subprog + 1].start;
3025 	for (i = 0; i < insn_cnt; i++) {
3026 		u8 code = insn[i].code;
3027 
3028 		if (code == (BPF_JMP | BPF_CALL) &&
3029 		    insn[i].src_reg == 0 &&
3030 		    insn[i].imm == BPF_FUNC_tail_call) {
3031 			subprog[cur_subprog].has_tail_call = true;
3032 			subprog[cur_subprog].tail_call_reachable = true;
3033 		}
3034 		if (BPF_CLASS(code) == BPF_LD &&
3035 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3036 			subprog[cur_subprog].has_ld_abs = true;
3037 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3038 			goto next;
3039 		if (BPF_OP(code) == BPF_CALL)
3040 			goto next;
3041 		if (BPF_OP(code) == BPF_EXIT) {
3042 			subprog[cur_subprog].exit_idx = i;
3043 			goto next;
3044 		}
3045 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3046 		if (off < subprog_start || off >= subprog_end) {
3047 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3048 			bpf_diag_program_structure(
3049 				env, i, "jump out of range",
3050 				"Keep branch targets within the same subprogram, or use an explicit subprogram call.",
3051 				"Instruction %d jumps to instruction %d, but subprogram %d only contains instructions %d through %d. "
3052 				"A branch target must stay inside the same subprogram.",
3053 				i, off, cur_subprog, subprog_start, subprog_end - 1);
3054 			return -EINVAL;
3055 		}
3056 next:
3057 		if (i == subprog_end - 1) {
3058 			/* to avoid fall-through from one subprog into another
3059 			 * the last insn of the subprog should be either exit
3060 			 * or unconditional jump back or bpf_throw call
3061 			 */
3062 			if (code != (BPF_JMP | BPF_EXIT) &&
3063 			    code != (BPF_JMP32 | BPF_JA) &&
3064 			    code != (BPF_JMP | BPF_JA)) {
3065 				verbose(env, "last insn is not an exit or jmp\n");
3066 				bpf_diag_program_structure(
3067 					env, i, "subprogram can fall through",
3068 					"End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.",
3069 					"Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.",
3070 					cur_subprog, i);
3071 				return -EINVAL;
3072 			}
3073 			subprog_start = subprog_end;
3074 			cur_subprog++;
3075 			if (cur_subprog < env->subprog_cnt)
3076 				subprog_end = subprog[cur_subprog + 1].start;
3077 		}
3078 	}
3079 	return 0;
3080 }
3081 
3082 /*
3083  * Sort subprogs in topological order so that leaf subprogs come first and
3084  * their callers come later. This is a DFS post-order traversal of the call
3085  * graph. Scan only reachable instructions (those in the computed postorder) of
3086  * the current subprog to discover callees (direct subprogs and sync
3087  * callbacks).
3088  */
3089 static int sort_subprogs_topo(struct bpf_verifier_env *env)
3090 {
3091 	struct bpf_subprog_info *si = env->subprog_info;
3092 	int *insn_postorder = env->cfg.insn_postorder;
3093 	struct bpf_insn *insn = env->prog->insnsi;
3094 	int cnt = env->subprog_cnt;
3095 	int *dfs_stack = NULL;
3096 	int top = 0, order = 0;
3097 	int i, ret = 0;
3098 	u8 *color = NULL;
3099 
3100 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
3101 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
3102 	if (!color || !dfs_stack) {
3103 		ret = -ENOMEM;
3104 		goto out;
3105 	}
3106 
3107 	/*
3108 	 * DFS post-order traversal.
3109 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
3110 	 */
3111 	for (i = 0; i < cnt; i++) {
3112 		if (color[i])
3113 			continue;
3114 		color[i] = 1;
3115 		dfs_stack[top++] = i;
3116 
3117 		while (top > 0) {
3118 			int cur = dfs_stack[top - 1];
3119 			int po_start = si[cur].postorder_start;
3120 			int po_end = si[cur + 1].postorder_start;
3121 			bool pushed = false;
3122 			int j;
3123 
3124 			for (j = po_start; j < po_end; j++) {
3125 				int idx = insn_postorder[j];
3126 				int callee;
3127 
3128 				if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx]))
3129 					continue;
3130 				callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
3131 				if (callee < 0) {
3132 					ret = -EFAULT;
3133 					goto out;
3134 				}
3135 				if (color[callee] == 2)
3136 					continue;
3137 				if (color[callee] == 1) {
3138 					if (bpf_pseudo_func(&insn[idx]))
3139 						continue;
3140 					verbose(env, "recursive call from %s() to %s()\n",
3141 						bpf_subprog_name(env, cur),
3142 						bpf_subprog_name(env, callee));
3143 					bpf_diag_program_structure(
3144 						env, idx, "recursive subprogram call",
3145 						"Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.",
3146 						"This bpf2bpf call would make the subprogram call graph recursive. "
3147 						"The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis.");
3148 					ret = -EINVAL;
3149 					goto out;
3150 				}
3151 				color[callee] = 1;
3152 				dfs_stack[top++] = callee;
3153 				pushed = true;
3154 				break;
3155 			}
3156 
3157 			if (!pushed) {
3158 				color[cur] = 2;
3159 				env->subprog_topo_order[order++] = cur;
3160 				top--;
3161 			}
3162 		}
3163 	}
3164 
3165 	if (env->log.level & BPF_LOG_LEVEL2)
3166 		for (i = 0; i < cnt; i++)
3167 			verbose(env, "topo_order[%d] = %s\n",
3168 				i, bpf_subprog_name(env, env->subprog_topo_order[i]));
3169 out:
3170 	kvfree(dfs_stack);
3171 	kvfree(color);
3172 	return ret;
3173 }
3174 
3175 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
3176 				       int spi, int nr_slots)
3177 {
3178 	int i;
3179 
3180 	for (i = 0; i < nr_slots; i++)
3181 		mark_stack_slot_scratched(env, spi - i);
3182 }
3183 
3184 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3185 			   enum bpf_reg_arg_type t)
3186 {
3187 	struct bpf_reg_state *reg;
3188 
3189 	mark_reg_scratched(env, regno);
3190 
3191 	reg = &regs[regno];
3192 	if (t == SRC_OP) {
3193 		/* check whether register used as source operand can be read */
3194 		if (reg->type == NOT_INIT) {
3195 			verbose(env, "R%d !read_ok\n", regno);
3196 			bpf_diag_unreadable_reg(env, env->insn_idx, regno);
3197 			return -EACCES;
3198 		}
3199 		/* We don't need to worry about FP liveness because it's read-only */
3200 		if (regno == BPF_REG_FP)
3201 			return 0;
3202 
3203 		return 0;
3204 	} else {
3205 		/* check whether register used as dest operand can be written to */
3206 		if (regno == BPF_REG_FP) {
3207 			verbose(env, "frame pointer is read only\n");
3208 			return -EACCES;
3209 		}
3210 		if (t == DST_OP)
3211 			mark_reg_unknown(env, regs, regno);
3212 	}
3213 	return 0;
3214 }
3215 
3216 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3217 			 enum bpf_reg_arg_type t)
3218 {
3219 	struct bpf_verifier_state *vstate = env->cur_state;
3220 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3221 
3222 	return __check_reg_arg(env, state->regs, regno, t);
3223 }
3224 
3225 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3226 {
3227 	env->insn_aux_data[idx].indirect_target = true;
3228 }
3229 
3230 #define LR_FRAMENO_BITS	4
3231 #define LR_SPI_BITS	6
3232 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3233 #define LR_SIZE_BITS	4
3234 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3235 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3236 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3237 #define LR_SPI_OFF	LR_FRAMENO_BITS
3238 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3239 #define LINKED_REGS_MAX	5
3240 
3241 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3242 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS));
3243 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64);
3244 
3245 struct linked_reg {
3246 	u8 frameno;
3247 	union {
3248 		u8 spi;
3249 		u8 regno;
3250 	};
3251 	bool is_reg;
3252 };
3253 
3254 struct linked_regs {
3255 	int cnt;
3256 	struct linked_reg entries[LINKED_REGS_MAX];
3257 };
3258 
3259 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3260 {
3261 	if (s->cnt < LINKED_REGS_MAX)
3262 		return &s->entries[s->cnt++];
3263 
3264 	return NULL;
3265 }
3266 
3267 /*
3268  * Use u64 as a vector of 5 11-bit values, use first 4-bits to track
3269  * number of elements currently in stack.
3270  * Pack one history entry for linked registers as 11 bits in the following format:
3271  * - 4-bits frameno
3272  * - 6-bits spi_or_reg
3273  * - 1-bit  is_reg
3274  */
3275 static u64 linked_regs_pack(struct linked_regs *s)
3276 {
3277 	u64 val = 0;
3278 	int i;
3279 
3280 	for (i = 0; i < s->cnt; ++i) {
3281 		struct linked_reg *e = &s->entries[i];
3282 		u64 tmp = 0;
3283 
3284 		tmp |= e->frameno;
3285 		tmp |= e->spi << LR_SPI_OFF;
3286 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3287 
3288 		val <<= LR_ENTRY_BITS;
3289 		val |= tmp;
3290 	}
3291 	val <<= LR_SIZE_BITS;
3292 	val |= s->cnt;
3293 	return val;
3294 }
3295 
3296 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3297 {
3298 	int i;
3299 
3300 	s->cnt = val & LR_SIZE_MASK;
3301 	val >>= LR_SIZE_BITS;
3302 
3303 	for (i = 0; i < s->cnt; ++i) {
3304 		struct linked_reg *e = &s->entries[i];
3305 
3306 		e->frameno =  val & LR_FRAMENO_MASK;
3307 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3308 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3309 		val >>= LR_ENTRY_BITS;
3310 	}
3311 }
3312 
3313 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3314 {
3315 	const struct btf_type *func;
3316 	struct btf *desc_btf;
3317 
3318 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3319 		return NULL;
3320 
3321 	desc_btf = find_kfunc_desc_btf_cached(data, insn->off);
3322 	if (IS_ERR(desc_btf))
3323 		return "<error>";
3324 
3325 	func = btf_type_by_id(desc_btf, insn->imm);
3326 	if (!func || !btf_type_is_func(func))
3327 		return "<error>";
3328 	return btf_name_by_offset(desc_btf, func->name_off);
3329 }
3330 
3331 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3332 {
3333 	const struct bpf_insn_cbs cbs = {
3334 		.cb_call	= bpf_disasm_kfunc_name,
3335 		.cb_print	= verbose,
3336 		.private_data	= env,
3337 	};
3338 
3339 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3340 }
3341 
3342 /* If any register R in hist->linked_regs is marked as precise in bt,
3343  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3344  */
3345 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3346 {
3347 	struct linked_regs linked_regs;
3348 	bool some_precise = false;
3349 	int i;
3350 
3351 	if (!hist || hist->linked_regs == 0)
3352 		return;
3353 
3354 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3355 	for (i = 0; i < linked_regs.cnt; ++i) {
3356 		struct linked_reg *e = &linked_regs.entries[i];
3357 
3358 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3359 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3360 			some_precise = true;
3361 			break;
3362 		}
3363 	}
3364 
3365 	if (!some_precise)
3366 		return;
3367 
3368 	for (i = 0; i < linked_regs.cnt; ++i) {
3369 		struct linked_reg *e = &linked_regs.entries[i];
3370 
3371 		if (e->is_reg)
3372 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3373 		else
3374 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3375 	}
3376 }
3377 
3378 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3379 {
3380 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3381 }
3382 
3383 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3384  * desired reg and stack masks across all relevant frames
3385  */
3386 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3387 				      struct bpf_verifier_state *starting_state)
3388 {
3389 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3390 }
3391 
3392 /* check if register is a constant scalar value */
3393 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3394 {
3395 	return reg->type == SCALAR_VALUE &&
3396 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3397 }
3398 
3399 /* assuming is_reg_const() is true, return constant value of a register */
3400 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3401 {
3402 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3403 }
3404 
3405 static bool is_pointer_regtype(enum bpf_reg_type type)
3406 {
3407 	return type != SCALAR_VALUE && type != NOT_INIT;
3408 }
3409 
3410 static bool __is_pointer_value(bool allow_ptr_leaks,
3411 			       const struct bpf_reg_state *reg)
3412 {
3413 	if (allow_ptr_leaks)
3414 		return false;
3415 
3416 	return is_pointer_regtype(reg->type);
3417 }
3418 
3419 static void clear_scalar_id(struct bpf_reg_state *reg)
3420 {
3421 	reg->id = 0;
3422 	reg->delta = 0;
3423 }
3424 
3425 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3426 					struct bpf_reg_state *src_reg)
3427 {
3428 	if (src_reg->type != SCALAR_VALUE)
3429 		return;
3430 	/*
3431 	 * The verifier is processing rX = rY insn and
3432 	 * rY->id has special linked register already.
3433 	 * Cleared it, since multiple rX += const are not supported.
3434 	 */
3435 	if (src_reg->id & BPF_ADD_CONST)
3436 		clear_scalar_id(src_reg);
3437 	/*
3438 	 * Ensure that src_reg has a valid ID that will be copied to
3439 	 * dst_reg and then will be used by sync_linked_regs() to
3440 	 * propagate min/max range.
3441 	 */
3442 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3443 		src_reg->id = ++env->id_gen;
3444 }
3445 
3446 static void save_register_state(struct bpf_verifier_env *env,
3447 				struct bpf_func_state *state,
3448 				int spi, struct bpf_reg_state *reg,
3449 				int size)
3450 {
3451 	int i;
3452 
3453 	bpf_diag_mod_begin(env, &state->stack[spi].spilled_ptr, reg, BPF_DIAG_MOD_SPILL);
3454 	state->stack[spi].spilled_ptr = *reg;
3455 
3456 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3457 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3458 
3459 	/* size < 8 bytes spill */
3460 	for (; i; i--)
3461 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
3462 
3463 	bpf_diag_mod_end(env);
3464 }
3465 
3466 static bool is_bpf_st_mem(struct bpf_insn *insn)
3467 {
3468 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3469 }
3470 
3471 static int get_reg_width(struct bpf_reg_state *reg)
3472 {
3473 	return fls64(reg_umax(reg));
3474 }
3475 
3476 /* See comment for mark_fastcall_pattern_for_call() */
3477 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3478 					  struct bpf_func_state *state, int insn_idx, int off)
3479 {
3480 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3481 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3482 	int i;
3483 
3484 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3485 		return;
3486 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3487 	 * from something that is not a part of the fastcall pattern,
3488 	 * disable fastcall rewrites for current subprogram by setting
3489 	 * fastcall_stack_off to a value smaller than any possible offset.
3490 	 */
3491 	subprog->fastcall_stack_off = S16_MIN;
3492 	/* reset fastcall aux flags within subprogram,
3493 	 * happens at most once per subprogram
3494 	 */
3495 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3496 		aux[i].fastcall_spills_num = 0;
3497 		aux[i].fastcall_pattern = 0;
3498 	}
3499 }
3500 
3501 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3502 {
3503 	int i;
3504 
3505 	/* regular write of data into stack destroys any spilled ptr */
3506 	state->stack[spi].spilled_ptr.type = NOT_INIT;
3507 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3508 	if (is_stack_slot_special(&state->stack[spi]))
3509 		for (i = 0; i < BPF_REG_SIZE; i++)
3510 			scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3511 }
3512 
3513 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3514  * stack boundary and alignment are checked in check_mem_access()
3515  */
3516 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3517 				       /* stack frame we're writing to */
3518 				       struct bpf_func_state *state,
3519 				       int off, int size, int value_regno,
3520 				       int insn_idx)
3521 {
3522 	struct bpf_func_state *cur; /* state of the current function */
3523 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3524 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3525 	struct bpf_reg_state *reg = NULL;
3526 	int insn_flags = INSN_F_STACK_ACCESS;
3527 	int hist_spi = spi, hist_frame = state->frameno;
3528 
3529 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3530 	 * so it's aligned access and [off, off + size) are within stack limits
3531 	 */
3532 	if (!env->allow_ptr_leaks &&
3533 	    bpf_is_spilled_reg(&state->stack[spi]) &&
3534 	    !bpf_is_spilled_scalar_reg(&state->stack[spi]) &&
3535 	    size != BPF_REG_SIZE) {
3536 		const char *reason;
3537 
3538 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3539 		reason = bpf_diag_fmt(env,
3540 				      "This store writes %d bytes at stack offset %d into a stack slot that currently holds a spilled pointer. "
3541 			"Partial writes to spilled pointers are rejected because they can corrupt pointer metadata and leak kernel pointers.",
3542 			size, off);
3543 		bpf_diag_memory(
3544 			env, insn_idx, "stack spill corruption", reason,
3545 			"Write the full 8-byte spilled pointer slot, or use a separate stack slot for scalar data before overwriting only part of it.");
3546 		return -EACCES;
3547 	}
3548 
3549 	cur = env->cur_state->frame[env->cur_state->curframe];
3550 	if (value_regno >= 0)
3551 		reg = &cur->regs[value_regno];
3552 	if (!env->bypass_spec_v4) {
3553 		bool sanitize = reg && is_pointer_regtype(reg->type);
3554 
3555 		for (i = 0; i < size; i++) {
3556 			u8 type = state->stack[spi].slot_type[(slot - i) %
3557 							      BPF_REG_SIZE];
3558 
3559 			if (type != STACK_MISC && type != STACK_ZERO) {
3560 				sanitize = true;
3561 				break;
3562 			}
3563 		}
3564 
3565 		if (sanitize)
3566 			env->insn_aux_data[insn_idx].nospec_result = true;
3567 	}
3568 
3569 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3570 	if (err)
3571 		return err;
3572 
3573 	check_fastcall_stack_contract(env, state, insn_idx, off);
3574 	mark_stack_slot_scratched(env, spi);
3575 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3576 		bool reg_value_fits;
3577 
3578 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3579 		/* Make sure that reg had an ID to build a relation on spill. */
3580 		if (reg_value_fits)
3581 			assign_scalar_id_before_mov(env, reg);
3582 		save_register_state(env, state, spi, reg, size);
3583 		/* Break the relation on a narrowing spill. */
3584 		if (!reg_value_fits)
3585 			state->stack[spi].spilled_ptr.id = 0;
3586 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3587 		   env->bpf_capable) {
3588 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3589 
3590 		memset(tmp_reg, 0, sizeof(*tmp_reg));
3591 		__mark_reg_known(tmp_reg, insn->imm);
3592 		tmp_reg->type = SCALAR_VALUE;
3593 		save_register_state(env, state, spi, tmp_reg, size);
3594 	} else if (reg && is_pointer_regtype(reg->type)) {
3595 		/* register containing pointer is being spilled into stack */
3596 		if (size != BPF_REG_SIZE) {
3597 			verbose_linfo(env, insn_idx, "; ");
3598 			verbose(env, "invalid size of register spill\n");
3599 			return -EACCES;
3600 		}
3601 		if (state != cur && reg->type == PTR_TO_STACK) {
3602 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3603 			return -EINVAL;
3604 		}
3605 		save_register_state(env, state, spi, reg, size);
3606 	} else {
3607 		u8 type = STACK_MISC;
3608 
3609 		if (bpf_is_spilled_reg(&state->stack[spi]))
3610 			bpf_diag_record_scrub(env, &state->stack[spi].spilled_ptr,
3611 					      BPF_DIAG_MOD_WRITE);
3612 		scrub_special_slot(state, spi);
3613 
3614 		/* when we zero initialize stack slots mark them as such */
3615 		if ((reg && bpf_register_is_null(reg)) ||
3616 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3617 			/* STACK_ZERO case happened because register spill
3618 			 * wasn't properly aligned at the stack slot boundary,
3619 			 * so it's not a register spill anymore; force
3620 			 * originating register to be precise to make
3621 			 * STACK_ZERO correct for subsequent states
3622 			 */
3623 			err = mark_chain_precision(env, value_regno);
3624 			if (err)
3625 				return err;
3626 			type = STACK_ZERO;
3627 		}
3628 
3629 		/* Mark slots affected by this stack write. */
3630 		for (i = 0; i < size; i++)
3631 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
3632 		insn_flags = 0; /* not a register spill */
3633 	}
3634 
3635 	if (insn_flags)
3636 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3637 					    hist_spi, hist_frame, 0);
3638 	return 0;
3639 }
3640 
3641 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
3642  * known to contain a variable offset.
3643  * This function checks whether the write is permitted and conservatively
3644  * tracks the effects of the write, considering that each stack slot in the
3645  * dynamic range is potentially written to.
3646  *
3647  * 'value_regno' can be -1, meaning that an unknown value is being written to
3648  * the stack.
3649  *
3650  * Spilled pointers in range are not marked as written because we don't know
3651  * what's going to be actually written. This means that read propagation for
3652  * future reads cannot be terminated by this write.
3653  *
3654  * For privileged programs, uninitialized stack slots are considered
3655  * initialized by this write (even though we don't know exactly what offsets
3656  * are going to be written to). The idea is that we don't want the verifier to
3657  * reject future reads that access slots written to through variable offsets.
3658  */
3659 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3660 				     /* func where register points to */
3661 				     struct bpf_func_state *state,
3662 				     struct bpf_reg_state *ptr_reg, int off, int size,
3663 				     int value_regno, int insn_idx)
3664 {
3665 	struct bpf_func_state *cur; /* state of the current function */
3666 	int min_off, max_off;
3667 	int i, err;
3668 	struct bpf_reg_state *value_reg = NULL;
3669 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3670 	bool writing_zero = false;
3671 	/* set if the fact that we're writing a zero is used to let any
3672 	 * stack slots remain STACK_ZERO
3673 	 */
3674 	bool zero_used = false;
3675 
3676 	cur = env->cur_state->frame[env->cur_state->curframe];
3677 	min_off = reg_smin(ptr_reg) + off;
3678 	max_off = reg_smax(ptr_reg) + off + size;
3679 	if (value_regno >= 0)
3680 		value_reg = &cur->regs[value_regno];
3681 	if ((value_reg && bpf_register_is_null(value_reg)) ||
3682 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3683 		writing_zero = true;
3684 
3685 	for (i = min_off; i < max_off; i++) {
3686 		int spi;
3687 
3688 		spi = bpf_get_spi(i);
3689 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3690 		if (err)
3691 			return err;
3692 	}
3693 
3694 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
3695 	/* Variable offset writes destroy any spilled pointers in range. */
3696 	for (i = min_off; i < max_off; i++) {
3697 		u8 new_type, *stype;
3698 		int slot, spi;
3699 
3700 		slot = -i - 1;
3701 		spi = slot / BPF_REG_SIZE;
3702 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3703 		mark_stack_slot_scratched(env, spi);
3704 
3705 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3706 			/* Reject the write if range we may write to has not
3707 			 * been initialized beforehand. If we didn't reject
3708 			 * here, the ptr status would be erased below (even
3709 			 * though not all slots are actually overwritten),
3710 			 * possibly opening the door to leaks.
3711 			 *
3712 			 * We do however catch STACK_INVALID case below, and
3713 			 * only allow reading possibly uninitialized memory
3714 			 * later for CAP_PERFMON, as the write may not happen to
3715 			 * that slot.
3716 			 */
3717 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3718 				insn_idx, i);
3719 			return -EINVAL;
3720 		}
3721 
3722 		/* If writing_zero and the spi slot contains a spill of value 0,
3723 		 * maintain the spill type.
3724 		 */
3725 		if (writing_zero && *stype == STACK_SPILL &&
3726 		    bpf_is_spilled_scalar_reg(&state->stack[spi])) {
3727 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
3728 
3729 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
3730 				zero_used = true;
3731 				continue;
3732 			}
3733 		}
3734 
3735 		/*
3736 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
3737 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
3738 		 * and valid program is rejected by check_stack_read_fixed_off()
3739 		 * with obscure "invalid size of register fill" message.
3740 		 */
3741 		scrub_special_slot(state, spi);
3742 
3743 		/* Update the slot type. */
3744 		new_type = STACK_MISC;
3745 		if (writing_zero && *stype == STACK_ZERO) {
3746 			new_type = STACK_ZERO;
3747 			zero_used = true;
3748 		}
3749 		/* If the slot is STACK_INVALID, we check whether it's OK to
3750 		 * pretend that it will be initialized by this write. The slot
3751 		 * might not actually be written to, and so if we mark it as
3752 		 * initialized future reads might leak uninitialized memory.
3753 		 * For privileged programs, we will accept such reads to slots
3754 		 * that may or may not be written because, if we're reject
3755 		 * them, the error would be too confusing.
3756 		 * Conservatively, treat STACK_POISON in a similar way.
3757 		 */
3758 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
3759 		    !env->allow_uninit_stack) {
3760 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3761 					insn_idx, i);
3762 			return -EINVAL;
3763 		}
3764 		*stype = new_type;
3765 	}
3766 	if (zero_used) {
3767 		/* backtracking doesn't work for STACK_ZERO yet. */
3768 		err = mark_chain_precision(env, value_regno);
3769 		if (err)
3770 			return err;
3771 	}
3772 	bpf_diag_record_scrub_stack(env, state, min_off, max_off,
3773 				    BPF_DIAG_MOD_VAR_WRITE);
3774 	return 0;
3775 }
3776 
3777 /* When register 'dst_regno' is assigned some values from stack[min_off,
3778  * max_off), we set the register's type according to the types of the
3779  * respective stack slots. If all the stack values are known to be zeros, then
3780  * so is the destination reg. Otherwise, the register is considered to be
3781  * SCALAR. This function does not deal with register filling; the caller must
3782  * ensure that all spilled registers in the stack range have been marked as
3783  * read.
3784  *
3785  * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered
3786  * zero bytes. In that case, mark the contributing stack slots precise so
3787  * pruning cannot reuse a zero-spill state for a later non-zero spill state.
3788  *
3789  * Returns an error if precision backtracking fails.
3790  */
3791 static int mark_reg_stack_read(struct bpf_verifier_env *env,
3792 			       /* func where src register points to */
3793 			       struct bpf_func_state *ptr_state,
3794 			       int min_off, int max_off, int dst_regno)
3795 {
3796 	struct bpf_verifier_state *vstate = env->cur_state;
3797 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3798 	u64 zero_spill_mask = 0;
3799 	int i, slot, spi;
3800 	u8 *stype;
3801 	int zeros = 0;
3802 
3803 	for (i = min_off; i < max_off; i++) {
3804 		slot = -i - 1;
3805 		spi = slot / BPF_REG_SIZE;
3806 		mark_stack_slot_scratched(env, spi);
3807 		stype = ptr_state->stack[spi].slot_type;
3808 		if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) {
3809 			zeros++;
3810 			continue;
3811 		}
3812 		if (stype[slot % BPF_REG_SIZE] == STACK_SPILL &&
3813 		    bpf_register_is_null(&ptr_state->stack[spi].spilled_ptr)) {
3814 			zero_spill_mask |= 1ull << spi;
3815 			zeros++;
3816 			continue;
3817 		}
3818 		break;
3819 	}
3820 	if (zeros == max_off - min_off) {
3821 		/* Any access_size read into register is zero extended,
3822 		 * so the whole register == const_zero.
3823 		 */
3824 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
3825 		if (zero_spill_mask) {
3826 			bpf_bt_set_frame_slot_mask(&env->bt, ptr_state->frameno, zero_spill_mask);
3827 			return mark_chain_precision_batch(env, env->cur_state);
3828 		}
3829 	} else {
3830 		/* have read misc data from the stack */
3831 		mark_reg_unknown(env, state->regs, dst_regno);
3832 	}
3833 
3834 	return 0;
3835 }
3836 
3837 static void bpf_diag_stack_read_uninit(struct bpf_verifier_env *env, int off, int i,
3838 				       int size)
3839 {
3840 	const char *reason;
3841 
3842 	reason = bpf_diag_fmt(env,
3843 			      "This rejected read uses %d bytes at stack offset %d, but byte %d in that range is uninitialized on this path. "
3844 		"Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.",
3845 		size, off, i);
3846 	bpf_diag_memory(
3847 		env, env->insn_idx, "uninitialized stack read", reason,
3848 		"Initialize every byte in the stack range before reading it, adjust the offset and size so the read covers only initialized bytes, "
3849 		"or load with CAP_PERFMON if uninitialized stack reads are intended.");
3850 }
3851 
3852 /* Read the stack at 'off' and put the results into the register indicated by
3853  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3854  * spilled reg.
3855  *
3856  * 'dst_regno' can be -1, meaning that the read value is not going to a
3857  * register.
3858  *
3859  * The access is assumed to be within the current stack bounds.
3860  */
3861 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3862 				      /* func where src register points to */
3863 				      struct bpf_func_state *reg_state,
3864 				      int off, int size, int dst_regno)
3865 {
3866 	struct bpf_verifier_state *vstate = env->cur_state;
3867 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3868 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3869 	struct bpf_reg_state *reg;
3870 	u8 *stype, type;
3871 	int err;
3872 	int insn_flags = INSN_F_STACK_ACCESS;
3873 	int hist_spi = spi, hist_frame = reg_state->frameno;
3874 
3875 	stype = reg_state->stack[spi].slot_type;
3876 	reg = &reg_state->stack[spi].spilled_ptr;
3877 
3878 	mark_stack_slot_scratched(env, spi);
3879 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
3880 
3881 	/*
3882 	 * Refine the in-progress load record's origin to the source stack slot.
3883 	 */
3884 	if (dst_regno >= 0)
3885 		bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE);
3886 
3887 	if (bpf_is_spilled_reg(&reg_state->stack[spi])) {
3888 		u8 spill_size = 1;
3889 
3890 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3891 			spill_size++;
3892 
3893 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3894 			if (reg->type != SCALAR_VALUE) {
3895 				verbose_linfo(env, env->insn_idx, "; ");
3896 				verbose(env, "invalid size of register fill\n");
3897 				return -EACCES;
3898 			}
3899 
3900 			if (dst_regno < 0)
3901 				return 0;
3902 
3903 			if (size <= spill_size &&
3904 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
3905 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
3906 				    get_reg_width(reg) <= 32)
3907 					/* Ensure stack slot has an ID to build a relation
3908 					 * with the destination register on fill.
3909 					 */
3910 					assign_scalar_id_before_mov(env, reg);
3911 				state->regs[dst_regno] = *reg;
3912 
3913 				/* Break the relation on a narrowing fill.
3914 				 * coerce_reg_to_size will adjust the boundaries.
3915 				 */
3916 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
3917 					clear_scalar_id(&state->regs[dst_regno]);
3918 			} else {
3919 				int spill_cnt = 0, zero_cnt = 0;
3920 
3921 				for (i = 0; i < size; i++) {
3922 					type = stype[(slot - i) % BPF_REG_SIZE];
3923 					if (type == STACK_SPILL) {
3924 						spill_cnt++;
3925 						continue;
3926 					}
3927 					if (type == STACK_MISC)
3928 						continue;
3929 					if (type == STACK_ZERO) {
3930 						zero_cnt++;
3931 						continue;
3932 					}
3933 					if (type == STACK_INVALID && env->allow_uninit_stack)
3934 						continue;
3935 					if (type == STACK_POISON) {
3936 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3937 							off, i, size);
3938 					} else {
3939 						verbose(env, "invalid read from stack off %d+%d size %d\n",
3940 							off, i, size);
3941 						bpf_diag_stack_read_uninit(env, off, i, size);
3942 					}
3943 					return -EACCES;
3944 				}
3945 
3946 				if (spill_cnt == size &&
3947 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
3948 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3949 					/* this IS register fill, so keep insn_flags */
3950 				} else if (zero_cnt == size) {
3951 					/* similarly to mark_reg_stack_read(), preserve zeroes */
3952 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3953 					insn_flags = 0; /* not restoring original register state */
3954 				} else {
3955 					err = mark_reg_stack_read(env, reg_state, off, off + size,
3956 								  dst_regno);
3957 					if (err)
3958 						return err;
3959 					insn_flags = 0; /* not restoring original register state */
3960 				}
3961 			}
3962 		} else if (dst_regno >= 0) {
3963 			/* restore register state from stack */
3964 			if (env->bpf_capable)
3965 				/* Ensure stack slot has an ID to build a relation
3966 				 * with the destination register on fill.
3967 				 */
3968 				assign_scalar_id_before_mov(env, reg);
3969 			state->regs[dst_regno] = *reg;
3970 			/* mark reg as written since spilled pointer state likely
3971 			 * has its liveness marks cleared by is_state_visited()
3972 			 * which resets stack/reg liveness for state transitions
3973 			 */
3974 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3975 			/* If dst_regno==-1, the caller is asking us whether
3976 			 * it is acceptable to use this value as a SCALAR_VALUE
3977 			 * (e.g. for XADD).
3978 			 * We must not allow unprivileged callers to do that
3979 			 * with spilled pointers.
3980 			 */
3981 			verbose(env, "leaking pointer from stack off %d\n",
3982 				off);
3983 			return -EACCES;
3984 		}
3985 	} else {
3986 		for (i = 0; i < size; i++) {
3987 			type = stype[(slot - i) % BPF_REG_SIZE];
3988 			if (type == STACK_MISC)
3989 				continue;
3990 			if (type == STACK_ZERO)
3991 				continue;
3992 			if (type == STACK_INVALID && env->allow_uninit_stack)
3993 				continue;
3994 			if (type == STACK_POISON) {
3995 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3996 					off, i, size);
3997 			} else {
3998 				verbose(env, "invalid read from stack off %d+%d size %d\n",
3999 					off, i, size);
4000 				bpf_diag_stack_read_uninit(env, off, i, size);
4001 			}
4002 			return -EACCES;
4003 		}
4004 		if (dst_regno >= 0) {
4005 			err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4006 			if (err)
4007 				return err;
4008 		}
4009 		insn_flags = 0; /* we are not restoring spilled register */
4010 	}
4011 	if (insn_flags)
4012 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
4013 					    hist_spi, hist_frame, 0);
4014 	return 0;
4015 }
4016 
4017 enum bpf_access_src {
4018 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4019 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4020 };
4021 
4022 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4023 					 argno_t argno, int off, int access_size,
4024 					 bool zero_size_allowed,
4025 					 enum bpf_access_type type,
4026 					 struct bpf_call_arg_meta *meta);
4027 
4028 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4029 {
4030 	return cur_regs(env) + regno;
4031 }
4032 
4033 /* Read the stack at 'reg + off' and put the result into the register
4034  * 'dst_regno'.
4035  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
4036  * but not its variable offset.
4037  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4038  *
4039  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4040  * filling registers (i.e. reads of spilled register cannot be detected when
4041  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4042  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
4043  * offset; for a fixed offset check_stack_read_fixed_off should be used
4044  * instead.
4045  */
4046 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4047 				    argno_t ptr_argno, int off, int size, int dst_regno)
4048 {
4049 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
4050 	int err;
4051 	int min_off, max_off;
4052 
4053 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4054 	 */
4055 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
4056 					    false, BPF_READ, NULL);
4057 	if (err)
4058 		return err;
4059 
4060 	min_off = reg_smin(reg) + off;
4061 	max_off = reg_smax(reg) + off;
4062 	err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size,
4063 				  dst_regno);
4064 	if (err)
4065 		return err;
4066 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
4067 	return 0;
4068 }
4069 
4070 /* check_stack_read dispatches to check_stack_read_fixed_off or
4071  * check_stack_read_var_off.
4072  *
4073  * The caller must ensure that the offset falls within the allocated stack
4074  * bounds.
4075  *
4076  * 'dst_regno' is a register which will receive the value from the stack. It
4077  * can be -1, meaning that the read value is not going to a register.
4078  */
4079 static int check_stack_read(struct bpf_verifier_env *env,
4080 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
4081 			    int dst_regno)
4082 {
4083 	struct bpf_func_state *state = bpf_func(env, reg);
4084 	int err;
4085 	/* Some accesses are only permitted with a static offset. */
4086 	bool var_off = !tnum_is_const(reg->var_off);
4087 
4088 	/* The offset is required to be static when reads don't go to a
4089 	 * register, in order to not leak pointers (see
4090 	 * check_stack_read_fixed_off).
4091 	 */
4092 	if (dst_regno < 0 && var_off) {
4093 		const char *reason;
4094 		char tn_buf[48];
4095 
4096 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4097 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4098 			tn_buf, off, size);
4099 		reason = bpf_diag_fmt(env,
4100 				      "The helper would access the stack through variable offset %s plus fixed offset %d and size %d. "
4101 			"Helper stack memory arguments require a constant stack offset and a precise initialized range.",
4102 			tn_buf, off, size);
4103 		bpf_diag_memory(
4104 			env, env->insn_idx, "variable stack access", reason,
4105 			"Use a fixed stack offset for helper memory arguments, or copy the needed bytes into a fixed stack slot first.");
4106 		return -EACCES;
4107 	}
4108 	/* Variable offset is prohibited for unprivileged mode for simplicity
4109 	 * since it requires corresponding support in Spectre masking for stack
4110 	 * ALU. See also retrieve_ptr_limit(). The check in
4111 	 * check_stack_access_for_ptr_arithmetic() called by
4112 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4113 	 * with variable offsets, therefore no check is required here. Further,
4114 	 * just checking it here would be insufficient as speculative stack
4115 	 * writes could still lead to unsafe speculative behaviour.
4116 	 */
4117 	if (!var_off) {
4118 		off += reg->var_off.value;
4119 		err = check_stack_read_fixed_off(env, state, off, size,
4120 						 dst_regno);
4121 	} else {
4122 		/* Variable offset stack reads need more conservative handling
4123 		 * than fixed offset ones. Note that dst_regno >= 0 on this
4124 		 * branch.
4125 		 */
4126 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
4127 					       dst_regno);
4128 	}
4129 	return err;
4130 }
4131 
4132 /* check_stack_write dispatches to check_stack_write_fixed_off or
4133  * check_stack_write_var_off.
4134  *
4135  * 'reg' is the register used as a pointer into the stack.
4136  * 'value_regno' is the register whose value we're writing to the stack. It can
4137  * be -1, meaning that we're not writing from a register.
4138  *
4139  * The caller must ensure that the offset falls within the maximum stack size.
4140  */
4141 static int check_stack_write(struct bpf_verifier_env *env,
4142 			     struct bpf_reg_state *reg, int off, int size,
4143 			     int value_regno, int insn_idx)
4144 {
4145 	struct bpf_func_state *state = bpf_func(env, reg);
4146 	int err;
4147 
4148 	if (tnum_is_const(reg->var_off)) {
4149 		off += reg->var_off.value;
4150 		err = check_stack_write_fixed_off(env, state, off, size,
4151 						  value_regno, insn_idx);
4152 	} else {
4153 		/* Variable offset stack reads need more conservative handling
4154 		 * than fixed offset ones.
4155 		 */
4156 		err = check_stack_write_var_off(env, state,
4157 						reg, off, size,
4158 						value_regno, insn_idx);
4159 	}
4160 	return err;
4161 }
4162 
4163 /*
4164  * Write a value to the outgoing stack arg area.
4165  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4166  */
4167 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4168 				 int off, struct bpf_reg_state *value_reg)
4169 {
4170 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4171 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4172 	int spi = -off / BPF_REG_SIZE - 1;
4173 	struct bpf_reg_state *arg;
4174 	int err;
4175 
4176 	if (spi >= max_stack_arg_regs) {
4177 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4178 			off, max_stack_arg_regs);
4179 		return -EINVAL;
4180 	}
4181 
4182 	err = grow_stack_arg_slots(env, state, spi + 1);
4183 	if (err)
4184 		return err;
4185 
4186 	/* Track the max outgoing stack arg slot count. */
4187 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4188 		subprog->max_out_stack_arg_cnt = spi + 1;
4189 
4190 	arg = &state->stack_arg_regs[spi];
4191 	bpf_diag_mod_begin(env, arg, value_reg, BPF_DIAG_MOD_WRITE);
4192 
4193 	if (value_reg) {
4194 		state->stack_arg_regs[spi] = *value_reg;
4195 	} else {
4196 		/* BPF_ST: store immediate, treat as scalar */
4197 		arg->type = SCALAR_VALUE;
4198 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4199 	}
4200 	bpf_diag_mod_end(env);
4201 	state->no_stack_arg_load = true;
4202 	return bpf_push_jmp_history(env, env->cur_state,
4203 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4204 }
4205 
4206 /*
4207  * Read a value from the incoming stack arg area.
4208  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4209  */
4210 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4211 				int off, int dst_regno)
4212 {
4213 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4214 	struct bpf_verifier_state *vstate = env->cur_state;
4215 	int spi = off / BPF_REG_SIZE - 1;
4216 	struct bpf_func_state *caller, *cur;
4217 	struct bpf_reg_state *arg;
4218 
4219 	if (state->no_stack_arg_load) {
4220 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4221 		return -EINVAL;
4222 	}
4223 
4224 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4225 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4226 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4227 		return -EACCES;
4228 	}
4229 
4230 	caller = vstate->frame[vstate->curframe - 1];
4231 	arg = &caller->stack_arg_regs[spi];
4232 	cur = vstate->frame[vstate->curframe];
4233 	bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE);
4234 	cur->regs[dst_regno] = *arg;
4235 	bpf_diag_mod_end(env);
4236 	return bpf_push_jmp_history(env, env->cur_state,
4237 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4238 }
4239 
4240 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4241 {
4242 	struct bpf_func_state *caller = cur_func(env);
4243 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4244 
4245 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4246 	return mark_chain_precision_batch(env, env->cur_state);
4247 }
4248 
4249 static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)
4250 {
4251 	int regno = reg_from_argno(argno);
4252 
4253 	if (regno >= 0)
4254 		return mark_chain_precision(env, regno);
4255 	return mark_stack_arg_precision(env, arg_idx_from_argno(argno));
4256 }
4257 
4258 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4259 				     int nargs, const char *callee_name, const struct btf *btf,
4260 				     const struct btf_param *args)
4261 {
4262 	int i, spi;
4263 
4264 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4265 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4266 		if (spi >= caller->out_stack_arg_cnt ||
4267 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4268 			const char *arg_name = NULL;
4269 
4270 			if (args && args[i].name_off)
4271 				arg_name = btf_name_by_offset(btf, args[i].name_off);
4272 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4273 				nargs, spi + 1);
4274 			bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi,
4275 						  callee_name, arg_name);
4276 			return -EFAULT;
4277 		}
4278 	}
4279 
4280 	return 0;
4281 }
4282 
4283 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4284 					      struct bpf_reg_state *regs, int arg)
4285 {
4286 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4287 		return &regs[arg + 1];
4288 
4289 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4290 }
4291 
4292 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4293 				 int off, int size, enum bpf_access_type type)
4294 {
4295 	struct bpf_map *map = reg->map_ptr;
4296 	u32 cap = bpf_map_flags_to_cap(map);
4297 
4298 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4299 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4300 			map->value_size, reg_smin(reg) + off, size);
4301 		return -EACCES;
4302 	}
4303 
4304 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4305 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4306 			map->value_size, reg_smin(reg) + off, size);
4307 		return -EACCES;
4308 	}
4309 
4310 	return 0;
4311 }
4312 
4313 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4314 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4315 			      int off, int size, u32 mem_size,
4316 			      bool zero_size_allowed)
4317 {
4318 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4319 
4320 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4321 		return 0;
4322 
4323 	switch (reg->type) {
4324 	case PTR_TO_MAP_KEY:
4325 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4326 			mem_size, off, size);
4327 		break;
4328 	case PTR_TO_MAP_VALUE:
4329 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4330 			mem_size, off, size);
4331 		break;
4332 	case PTR_TO_PACKET:
4333 	case PTR_TO_PACKET_META:
4334 	case PTR_TO_PACKET_END:
4335 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4336 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4337 		break;
4338 	case PTR_TO_CTX:
4339 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4340 			mem_size, off, size);
4341 		break;
4342 	case PTR_TO_MEM:
4343 	default:
4344 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4345 			mem_size, off, size);
4346 	}
4347 
4348 	return -EACCES;
4349 }
4350 
4351 /* check read/write into a memory region with possible variable offset */
4352 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4353 				   int off, int size, u32 mem_size,
4354 				   bool zero_size_allowed)
4355 {
4356 	const char *proof = "";
4357 	const char *start;
4358 	s64 max_start, max_end;
4359 	int err;
4360 
4361 	/* We may have adjusted the register pointing to memory region, so we
4362 	 * need to try adding each of min_value and max_value to off
4363 	 * to make sure our theoretical access will be safe.
4364 	 *
4365 	 * The minimum value is only important with signed
4366 	 * comparisons where we can't assume the floor of a
4367 	 * value is 0.  If we are using signed variables for our
4368 	 * index'es we need to make sure that whatever we use
4369 	 * will have a set floor within our range.
4370 	 */
4371 	if (reg_smin(reg) < 0 &&
4372 	    (reg_smin(reg) == S64_MIN ||
4373 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4374 	      reg_smin(reg) + off < 0)) {
4375 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4376 			reg_arg_name(env, argno));
4377 		err = -EACCES;
4378 		if (bpf_diag_enabled(env)) {
4379 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4380 			proof = bpf_diag_fmt(
4381 				env, "the minimal bound for a memory access is a negative value: %s",
4382 				start);
4383 		}
4384 		goto report_error;
4385 	}
4386 
4387 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4388 				 mem_size, zero_size_allowed);
4389 	if (err) {
4390 		verbose(env, "%s min value is outside of the allowed memory range\n",
4391 			reg_arg_name(env, argno));
4392 		if (bpf_diag_enabled(env)) {
4393 			start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off);
4394 			proof = bpf_diag_fmt(
4395 				env, "the minimal bound for a memory access is %s and is outside of the object of size %u",
4396 				start, mem_size);
4397 		}
4398 		goto report_error;
4399 	}
4400 
4401 	/* If we haven't set a max value then we need to bail since we can't be
4402 	 * sure we won't do bad things.
4403 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4404 	 */
4405 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4406 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4407 			reg_arg_name(env, argno));
4408 		err = -EACCES;
4409 		if (bpf_diag_enabled(env))
4410 			proof = bpf_diag_fmt(
4411 				env, "the maximal bound for a memory access is %llu and exceeds maximum allowed offset of %u",
4412 				reg_umax(reg), BPF_MAX_VAR_OFF);
4413 		goto report_error;
4414 	}
4415 
4416 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4417 				 mem_size, zero_size_allowed);
4418 	if (err) {
4419 		verbose(env, "%s max value is outside of the allowed memory range\n",
4420 			reg_arg_name(env, argno));
4421 		if (bpf_diag_enabled(env)) {
4422 			max_start = (s64)reg_umax(reg) + off;
4423 			max_end = max_start + size;
4424 			proof = bpf_diag_fmt(
4425 				env, "the maximal bound for a memory access is %lld: start %lld + access_size %d, beyond object_size %u",
4426 				max_end, max_start, size, mem_size);
4427 		}
4428 		goto report_error;
4429 	}
4430 
4431 	return 0;
4432 
4433 report_error:
4434 	bpf_diag_mem_bounds(env, env->insn_idx, reg_from_argno(argno),
4435 			    reg_arg_name(env, argno), reg_type_str(env, reg->type), proof,
4436 			    off, size, mem_size, reg);
4437 	return err;
4438 }
4439 
4440 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4441 			       const struct bpf_reg_state *reg, argno_t argno,
4442 			       bool fixed_off_ok)
4443 {
4444 	/* Access to this pointer-typed register or passing it to a helper
4445 	 * is only allowed in its original, unmodified form.
4446 	 */
4447 
4448 	if (!tnum_is_const(reg->var_off)) {
4449 		char tn_buf[48];
4450 
4451 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4452 		verbose(env, "variable %s access var_off=%s disallowed\n",
4453 			reg_type_str(env, reg->type), tn_buf);
4454 		return -EACCES;
4455 	}
4456 
4457 	if (reg_smin(reg) < 0) {
4458 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4459 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4460 		return -EACCES;
4461 	}
4462 
4463 	if (!fixed_off_ok && reg->var_off.value != 0) {
4464 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4465 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4466 		bpf_diag_invalid_deref(env, env->insn_idx, reg_from_argno(argno),
4467 				       reg_arg_name(env, argno), reg,
4468 					      BPF_DIAG_DEREF_MODIFIED_PTR, reg->var_off.value);
4469 		return -EACCES;
4470 	}
4471 
4472 	return 0;
4473 }
4474 
4475 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4476 		             const struct bpf_reg_state *reg, int regno)
4477 {
4478 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4479 }
4480 
4481 static int map_kptr_match_type(struct bpf_verifier_env *env,
4482 			       struct btf_field *kptr_field,
4483 			       struct bpf_reg_state *reg, u32 regno)
4484 {
4485 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4486 	int perm_flags;
4487 	const char *reg_name = "";
4488 
4489 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4490 		goto bad_type;
4491 
4492 	if (btf_is_kernel(reg->btf)) {
4493 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4494 
4495 		/* Only unreferenced case accepts untrusted pointers */
4496 		if (kptr_field->type == BPF_KPTR_UNREF)
4497 			perm_flags |= PTR_UNTRUSTED;
4498 	} else {
4499 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4500 		if (kptr_field->type == BPF_KPTR_PERCPU)
4501 			perm_flags |= MEM_PERCPU;
4502 	}
4503 
4504 	if (type_flag(reg->type) & ~perm_flags)
4505 		goto bad_type;
4506 
4507 	/*
4508 	 * A BPF_KPTR_PERCPU field is read back as MEM_PERCPU, so the value
4509 	 * stored in it must carry the same flag.
4510 	 */
4511 	if ((kptr_field->type == BPF_KPTR_PERCPU) != !!(reg->type & MEM_PERCPU))
4512 		goto bad_type;
4513 
4514 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4515 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4516 
4517 	/* For ref_ptr case, release function check should ensure we get one
4518 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4519 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4520 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4521 	 * reg->id is not needed here.
4522 	 */
4523 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4524 		return -EACCES;
4525 
4526 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4527 	 * we also need to take into account the reg->var_off.
4528 	 *
4529 	 * We want to support cases like:
4530 	 *
4531 	 * struct foo {
4532 	 *         struct bar br;
4533 	 *         struct baz bz;
4534 	 * };
4535 	 *
4536 	 * struct foo *v;
4537 	 * v = func();	      // PTR_TO_BTF_ID
4538 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
4539 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
4540 	 *                    // first member type of struct after comparison fails
4541 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
4542 	 *                    // to match type
4543 	 *
4544 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
4545 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4546 	 * the struct to match type against first member of struct, i.e. reject
4547 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4548 	 * strict mode to true for type match.
4549 	 */
4550 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
4551 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4552 				  kptr_field->type != BPF_KPTR_UNREF,
4553 				  !type_is_alloc(reg->type)))
4554 		goto bad_type;
4555 	return 0;
4556 bad_type:
4557 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4558 		reg_type_str(env, reg->type), reg_name);
4559 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4560 	if (kptr_field->type == BPF_KPTR_UNREF)
4561 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4562 			targ_name);
4563 	else
4564 		verbose(env, "\n");
4565 	return -EINVAL;
4566 }
4567 
4568 static bool in_sleepable(struct bpf_verifier_env *env)
4569 {
4570 	return env->cur_state->in_sleepable;
4571 }
4572 
4573 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4574  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4575  */
4576 static bool in_rcu_cs(struct bpf_verifier_env *env)
4577 {
4578 	return env->cur_state->active_rcu_locks ||
4579 	       env->cur_state->active_preempt_locks ||
4580 	       env->cur_state->active_locks ||
4581 	       env->cur_state->active_irq_id ||
4582 	       !in_sleepable(env);
4583 }
4584 
4585 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4586 BTF_SET_START(rcu_protected_types)
4587 #ifdef CONFIG_NET
4588 BTF_ID(struct, prog_test_ref_kfunc)
4589 #endif
4590 #ifdef CONFIG_CGROUPS
4591 BTF_ID(struct, cgroup)
4592 #endif
4593 #ifdef CONFIG_BPF_JIT
4594 BTF_ID(struct, bpf_cpumask)
4595 #endif
4596 BTF_ID(struct, task_struct)
4597 #ifdef CONFIG_CRYPTO
4598 BTF_ID(struct, bpf_crypto_ctx)
4599 #endif
4600 #ifdef CONFIG_INET
4601 BTF_ID(struct, bpf_ksock)
4602 #endif
4603 BTF_SET_END(rcu_protected_types)
4604 
4605 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4606 {
4607 	if (!btf_is_kernel(btf))
4608 		return true;
4609 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4610 }
4611 
4612 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
4613 {
4614 	struct btf_struct_meta *meta;
4615 
4616 	if (btf_is_kernel(kptr_field->kptr.btf))
4617 		return NULL;
4618 
4619 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
4620 				    kptr_field->kptr.btf_id);
4621 
4622 	return meta ? meta->record : NULL;
4623 }
4624 
4625 static bool rcu_safe_kptr(const struct btf_field *field)
4626 {
4627 	const struct btf_field_kptr *kptr = &field->kptr;
4628 
4629 	return field->type == BPF_KPTR_PERCPU ||
4630 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
4631 }
4632 
4633 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
4634 {
4635 	struct btf_record *rec;
4636 	u32 ret;
4637 
4638 	ret = PTR_MAYBE_NULL;
4639 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
4640 		ret |= MEM_RCU;
4641 		if (kptr_field->type == BPF_KPTR_PERCPU)
4642 			ret |= MEM_PERCPU;
4643 		else if (!btf_is_kernel(kptr_field->kptr.btf))
4644 			ret |= MEM_ALLOC;
4645 
4646 		rec = kptr_pointee_btf_record(kptr_field);
4647 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
4648 			ret |= NON_OWN_REF;
4649 	} else {
4650 		ret |= PTR_UNTRUSTED;
4651 	}
4652 
4653 	return ret;
4654 }
4655 
4656 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
4657 			    struct btf_field *field)
4658 {
4659 	struct bpf_reg_state *reg;
4660 	const struct btf_type *t;
4661 
4662 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
4663 	mark_reg_known_zero(env, cur_regs(env), regno);
4664 	reg = reg_state(env, regno);
4665 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
4666 	reg->mem_size = t->size;
4667 	reg->id = ++env->id_gen;
4668 
4669 	return 0;
4670 }
4671 
4672 static int check_map_kptr_access(struct bpf_verifier_env *env,
4673 				 int value_regno, int insn_idx,
4674 				 struct btf_field *kptr_field)
4675 {
4676 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4677 	int class = BPF_CLASS(insn->code);
4678 	struct bpf_reg_state *val_reg;
4679 	int ret;
4680 
4681 	/* Things we already checked for in check_map_access and caller:
4682 	 *  - Reject cases where variable offset may touch kptr
4683 	 *  - size of access (must be BPF_DW)
4684 	 *  - tnum_is_const(reg->var_off)
4685 	 *  - kptr_field->offset == off + reg->var_off.value
4686 	 */
4687 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4688 	if (BPF_MODE(insn->code) != BPF_MEM) {
4689 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4690 		return -EACCES;
4691 	}
4692 
4693 	/* We only allow loading referenced kptr, since it will be marked as
4694 	 * untrusted, similar to unreferenced kptr.
4695 	 */
4696 	if (class != BPF_LDX &&
4697 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
4698 		verbose(env, "store to referenced kptr disallowed\n");
4699 		return -EACCES;
4700 	}
4701 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
4702 		verbose(env, "store to uptr disallowed\n");
4703 		return -EACCES;
4704 	}
4705 
4706 	if (class == BPF_LDX) {
4707 		if (kptr_field->type == BPF_UPTR)
4708 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
4709 
4710 		/* We can simply mark the value_regno receiving the pointer
4711 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4712 		 */
4713 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
4714 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4715 				      btf_ld_kptr_type(env, kptr_field));
4716 		if (ret < 0)
4717 			return ret;
4718 	} else if (class == BPF_STX) {
4719 		val_reg = reg_state(env, value_regno);
4720 		if (bpf_register_is_null(val_reg)) {
4721 			/*
4722 			 * This store is valid only because the scalar is known to be
4723 			 * zero. Mark it precise so another scalar cannot be pruned
4724 			 * against this state.
4725 			 */
4726 			return mark_chain_precision(env, value_regno);
4727 		}
4728 		if (map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4729 			return -EACCES;
4730 	} else if (class == BPF_ST) {
4731 		if (insn->imm) {
4732 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4733 				kptr_field->offset);
4734 			return -EACCES;
4735 		}
4736 	} else {
4737 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4738 		return -EACCES;
4739 	}
4740 	return 0;
4741 }
4742 
4743 /*
4744  * Return the size of the memory region accessible from a pointer to map value.
4745  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
4746  */
4747 static u32 map_mem_size(const struct bpf_map *map)
4748 {
4749 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
4750 		return map->max_entries * sizeof(long);
4751 
4752 	return map->value_size;
4753 }
4754 
4755 /* check read/write into a map element with possible variable offset */
4756 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4757 			    int off, int size, bool zero_size_allowed,
4758 			    enum bpf_access_src src)
4759 {
4760 	struct bpf_map *map = reg->map_ptr;
4761 	u32 mem_size = map_mem_size(map);
4762 	struct btf_record *rec;
4763 	int err, i;
4764 
4765 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
4766 	if (err)
4767 		return err;
4768 
4769 	if (IS_ERR_OR_NULL(map->record))
4770 		return 0;
4771 	rec = map->record;
4772 	for (i = 0; i < rec->cnt; i++) {
4773 		struct btf_field *field = &rec->fields[i];
4774 		u32 p = field->offset;
4775 
4776 		/* If any part of a field  can be touched by load/store, reject
4777 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4778 		 * it is sufficient to check x1 < y2 && y1 < x2.
4779 		 */
4780 		if (reg_smin(reg) + off < p + field->size &&
4781 		    p < reg_umax(reg) + off + size) {
4782 			switch (field->type) {
4783 			case BPF_KPTR_UNREF:
4784 			case BPF_KPTR_REF:
4785 			case BPF_KPTR_PERCPU:
4786 			case BPF_UPTR:
4787 				if (src != ACCESS_DIRECT) {
4788 					verbose(env, "%s cannot be accessed indirectly by helper\n",
4789 						btf_field_type_name(field->type));
4790 					return -EACCES;
4791 				}
4792 				if (!tnum_is_const(reg->var_off)) {
4793 					verbose(env, "%s access cannot have variable offset\n",
4794 						btf_field_type_name(field->type));
4795 					return -EACCES;
4796 				}
4797 				if (p != off + reg->var_off.value) {
4798 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
4799 						btf_field_type_name(field->type),
4800 						p, off + reg->var_off.value);
4801 					return -EACCES;
4802 				}
4803 				if (size != bpf_size_to_bytes(BPF_DW)) {
4804 					verbose(env, "%s access size must be BPF_DW\n",
4805 						btf_field_type_name(field->type));
4806 					return -EACCES;
4807 				}
4808 				break;
4809 			default:
4810 				verbose(env, "%s cannot be accessed directly by load/store\n",
4811 					btf_field_type_name(field->type));
4812 				return -EACCES;
4813 			}
4814 		}
4815 	}
4816 	return 0;
4817 }
4818 
4819 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4820 			       const struct bpf_func_proto *fn,
4821 			       enum bpf_access_type t)
4822 {
4823 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4824 
4825 	switch (prog_type) {
4826 	/* Program types only with direct read access go here! */
4827 	case BPF_PROG_TYPE_LWT_IN:
4828 	case BPF_PROG_TYPE_LWT_OUT:
4829 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4830 	case BPF_PROG_TYPE_SK_REUSEPORT:
4831 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4832 	case BPF_PROG_TYPE_CGROUP_SKB:
4833 		if (t == BPF_WRITE)
4834 			return false;
4835 		fallthrough;
4836 
4837 	/* Program types with direct read + write access go here! */
4838 	case BPF_PROG_TYPE_SCHED_CLS:
4839 	case BPF_PROG_TYPE_SCHED_ACT:
4840 	case BPF_PROG_TYPE_XDP:
4841 	case BPF_PROG_TYPE_LWT_XMIT:
4842 	case BPF_PROG_TYPE_SK_SKB:
4843 	case BPF_PROG_TYPE_SK_MSG:
4844 		if (fn)
4845 			return fn->pkt_access;
4846 
4847 		env->seen_direct_write = true;
4848 		return true;
4849 
4850 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4851 		if (t == BPF_WRITE)
4852 			env->seen_direct_write = true;
4853 
4854 		return true;
4855 
4856 	default:
4857 		return false;
4858 	}
4859 }
4860 
4861 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
4862 			       int size, bool zero_size_allowed)
4863 {
4864 	int err;
4865 
4866 	if (reg->range < 0) {
4867 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
4868 		return -EINVAL;
4869 	}
4870 
4871 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
4872 	if (err)
4873 		return err;
4874 
4875 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4876 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
4877 	 * otherwise find_good_pkt_pointers would have refused to set range info
4878 	 * that __check_mem_access would have rejected this pkt access.
4879 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
4880 	 */
4881 	env->prog->aux->max_pkt_offset =
4882 		max_t(u32, env->prog->aux->max_pkt_offset,
4883 		      off + reg_umax(reg) + size - 1);
4884 
4885 	return 0;
4886 }
4887 
4888 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
4889 {
4890 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
4891 }
4892 
4893 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4894 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4895 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
4896 {
4897 	if (env->ops->is_valid_access &&
4898 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
4899 		/* A non zero info.ctx_field_size indicates that this field is a
4900 		 * candidate for later verifier transformation to load the whole
4901 		 * field and then apply a mask when accessed with a narrower
4902 		 * access than actual ctx access size. A zero info.ctx_field_size
4903 		 * will only allow for whole field access and rejects any other
4904 		 * type of narrower access.
4905 		 */
4906 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
4907 			if (info->ref_id &&
4908 			    !find_reference_state(env->cur_state, info->ref_id)) {
4909 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
4910 					off);
4911 				return -EACCES;
4912 			}
4913 		} else {
4914 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
4915 		}
4916 		/* remember the offset of last byte accessed in ctx */
4917 		if (env->prog->aux->max_ctx_offset < off + size)
4918 			env->prog->aux->max_ctx_offset = off + size;
4919 		return 0;
4920 	}
4921 
4922 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4923 	return -EACCES;
4924 }
4925 
4926 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
4927 			    int off, int access_size, enum bpf_access_type t,
4928 			    struct bpf_insn_access_aux *info)
4929 {
4930 	/*
4931 	 * Program types that don't rewrite ctx accesses can safely
4932 	 * dereference ctx pointers with fixed offsets.
4933 	 */
4934 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
4935 	bool fixed_off_ok = !env->ops->convert_ctx_access;
4936 	int err;
4937 
4938 	if (var_off_ok)
4939 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
4940 	else
4941 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
4942 	if (err)
4943 		return err;
4944 	off += reg_umax(reg);
4945 
4946 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
4947 	if (err)
4948 		verbose_linfo(env, insn_idx, "; ");
4949 	return err;
4950 }
4951 
4952 static int check_flow_keys_access(struct bpf_verifier_env *env,
4953 				  struct bpf_reg_state *reg, argno_t argno,
4954 				  int off, int size)
4955 {
4956 	/* Only a constant offset is allowed here; fold it into off. */
4957 	if (!tnum_is_const(reg->var_off)) {
4958 		char tn_buf[48];
4959 
4960 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4961 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
4962 			reg_arg_name(env, argno), off, tn_buf);
4963 		return -EACCES;
4964 	}
4965 	off += reg->var_off.value;
4966 
4967 	if (size < 0 || off < 0 ||
4968 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4969 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4970 			off, size);
4971 		return -EACCES;
4972 	}
4973 	return 0;
4974 }
4975 
4976 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4977 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
4978 			     enum bpf_access_type t)
4979 {
4980 	struct bpf_insn_access_aux info = {};
4981 	bool valid;
4982 
4983 	if (reg_smin(reg) < 0) {
4984 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4985 			reg_arg_name(env, argno));
4986 		return -EACCES;
4987 	}
4988 
4989 	switch (reg->type) {
4990 	case PTR_TO_SOCK_COMMON:
4991 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4992 		break;
4993 	case PTR_TO_SOCKET:
4994 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4995 		break;
4996 	case PTR_TO_TCP_SOCK:
4997 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4998 		break;
4999 	case PTR_TO_XDP_SOCK:
5000 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5001 		break;
5002 	default:
5003 		valid = false;
5004 	}
5005 
5006 	if (valid) {
5007 		env->insn_aux_data[insn_idx].ctx_field_size =
5008 			info.ctx_field_size;
5009 		return 0;
5010 	}
5011 
5012 	verbose(env, "%s invalid %s access off=%d size=%d\n",
5013 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
5014 
5015 	return -EACCES;
5016 }
5017 
5018 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5019 {
5020 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5021 }
5022 
5023 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5024 {
5025 	const struct bpf_reg_state *reg = reg_state(env, regno);
5026 
5027 	return reg->type == PTR_TO_CTX;
5028 }
5029 
5030 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5031 {
5032 	const struct bpf_reg_state *reg = reg_state(env, regno);
5033 
5034 	return type_is_sk_pointer(reg->type);
5035 }
5036 
5037 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5038 {
5039 	const struct bpf_reg_state *reg = reg_state(env, regno);
5040 
5041 	return type_is_pkt_pointer(reg->type);
5042 }
5043 
5044 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5045 {
5046 	const struct bpf_reg_state *reg = reg_state(env, regno);
5047 
5048 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5049 	return reg->type == PTR_TO_FLOW_KEYS;
5050 }
5051 
5052 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5053 {
5054 	const struct bpf_reg_state *reg = reg_state(env, regno);
5055 
5056 	return reg->type == PTR_TO_ARENA;
5057 }
5058 
5059 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno,
5060 			       struct bpf_insn *insn)
5061 {
5062 	const struct bpf_reg_state *reg = reg_state(env, regno);
5063 
5064 	/*
5065 	 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the
5066 	 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load
5067 	 * with no exception table entry, so a fault (e.g. NULL deref) crashes
5068 	 * the kernel instead of being handled. Reject the source pointer types
5069 	 * that would have needed that protection, the remaining ones stay
5070 	 * allowed.
5071 	 */
5072 	return insn->imm == BPF_LOAD_ACQ && bpf_may_fault_on_deref(reg->type);
5073 }
5074 
5075 /* Return false if @regno contains a pointer whose type isn't supported for
5076  * atomic instruction @insn.
5077  */
5078 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
5079 			       struct bpf_insn *insn)
5080 {
5081 	if (is_ctx_reg(env, regno))
5082 		return false;
5083 	if (is_pkt_reg(env, regno))
5084 		return false;
5085 	if (is_flow_key_reg(env, regno))
5086 		return false;
5087 	if (is_sk_reg(env, regno))
5088 		return false;
5089 	if (is_arena_reg(env, regno))
5090 		return bpf_jit_supports_insn(insn, true);
5091 	if (is_load_acq_unsafe(env, regno, insn))
5092 		return false;
5093 	return true;
5094 }
5095 
5096 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5097 #ifdef CONFIG_NET
5098 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5099 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5100 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5101 #endif
5102 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5103 };
5104 
5105 static enum bpf_reg_type lookup_reg2btf_ids(u32 ref_id)
5106 {
5107 	enum bpf_reg_type type;
5108 
5109 	for (type = 0; type < __BPF_REG_TYPE_MAX; type++) {
5110 		if (reg2btf_ids[type] && *reg2btf_ids[type] == ref_id)
5111 			return type;
5112 	}
5113 
5114 	return NOT_INIT;
5115 }
5116 
5117 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
5118 {
5119 	/* A referenced register is always trusted. */
5120 	if (reg_is_referenced(env, reg))
5121 		return true;
5122 
5123 	/* Types listed in the reg2btf_ids are always trusted */
5124 	if (reg2btf_ids[base_type(reg->type)] &&
5125 	    !bpf_type_has_unsafe_modifiers(reg->type))
5126 		return true;
5127 
5128 	/* If a register is not referenced, it is trusted if it has the
5129 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5130 	 * other type modifiers may be safe, but we elect to take an opt-in
5131 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5132 	 * not.
5133 	 *
5134 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5135 	 * for whether a register is trusted.
5136 	 */
5137 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5138 	       !bpf_type_has_unsafe_modifiers(reg->type);
5139 }
5140 
5141 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5142 {
5143 	return reg->type & MEM_RCU;
5144 }
5145 
5146 static void clear_trusted_flags(enum bpf_type_flag *flag)
5147 {
5148 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5149 }
5150 
5151 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5152 				   const struct bpf_reg_state *reg,
5153 				   int off, int size, bool strict)
5154 {
5155 	struct tnum reg_off;
5156 	int ip_align;
5157 
5158 	/* Byte size accesses are always allowed. */
5159 	if (!strict || size == 1)
5160 		return 0;
5161 
5162 	/* For platforms that do not have a Kconfig enabling
5163 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5164 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5165 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5166 	 * to this code only in strict mode where we want to emulate
5167 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5168 	 * unconditional IP align value of '2'.
5169 	 */
5170 	ip_align = 2;
5171 
5172 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
5173 	if (!tnum_is_aligned(reg_off, size)) {
5174 		char tn_buf[48];
5175 
5176 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5177 		verbose(env,
5178 			"misaligned packet access off %d+%s+%d size %d\n",
5179 			ip_align, tn_buf, off, size);
5180 		return -EACCES;
5181 	}
5182 
5183 	return 0;
5184 }
5185 
5186 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5187 				       const struct bpf_reg_state *reg,
5188 				       const char *pointer_desc,
5189 				       int off, int size, bool strict)
5190 {
5191 	struct tnum reg_off;
5192 
5193 	/* Byte size accesses are always allowed. */
5194 	if (!strict || size == 1)
5195 		return 0;
5196 
5197 	reg_off = tnum_add(reg->var_off, tnum_const(off));
5198 	if (!tnum_is_aligned(reg_off, size)) {
5199 		char tn_buf[48];
5200 
5201 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5202 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
5203 			pointer_desc, tn_buf, off, size);
5204 		return -EACCES;
5205 	}
5206 
5207 	return 0;
5208 }
5209 
5210 static int check_ptr_alignment(struct bpf_verifier_env *env,
5211 			       const struct bpf_reg_state *reg, int off,
5212 			       int size, bool strict_alignment_once)
5213 {
5214 	bool strict = env->strict_alignment || strict_alignment_once;
5215 	const char *pointer_desc = "";
5216 
5217 	switch (reg->type) {
5218 	case PTR_TO_PACKET:
5219 	case PTR_TO_PACKET_META:
5220 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5221 		 * right in front, treat it the very same way.
5222 		 */
5223 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5224 	case PTR_TO_FLOW_KEYS:
5225 		pointer_desc = "flow keys ";
5226 		break;
5227 	case PTR_TO_MAP_KEY:
5228 		pointer_desc = "key ";
5229 		break;
5230 	case PTR_TO_MAP_VALUE:
5231 		pointer_desc = "value ";
5232 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
5233 			strict = true;
5234 		break;
5235 	case PTR_TO_CTX:
5236 		pointer_desc = "context ";
5237 		break;
5238 	case PTR_TO_STACK:
5239 		pointer_desc = "stack ";
5240 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5241 		 * and check_stack_read_fixed_off() relies on stack accesses being
5242 		 * aligned.
5243 		 */
5244 		strict = true;
5245 		break;
5246 	case PTR_TO_SOCKET:
5247 		pointer_desc = "sock ";
5248 		break;
5249 	case PTR_TO_SOCK_COMMON:
5250 		pointer_desc = "sock_common ";
5251 		break;
5252 	case PTR_TO_TCP_SOCK:
5253 		pointer_desc = "tcp_sock ";
5254 		break;
5255 	case PTR_TO_XDP_SOCK:
5256 		pointer_desc = "xdp_sock ";
5257 		break;
5258 	case PTR_TO_ARENA:
5259 		return 0;
5260 	default:
5261 		break;
5262 	}
5263 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5264 					   strict);
5265 }
5266 
5267 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5268 {
5269 	if (!bpf_jit_supports_private_stack())
5270 		return NO_PRIV_STACK;
5271 
5272 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5273 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5274 	 * explicitly.
5275 	 */
5276 	switch (prog->type) {
5277 	case BPF_PROG_TYPE_KPROBE:
5278 	case BPF_PROG_TYPE_TRACEPOINT:
5279 	case BPF_PROG_TYPE_PERF_EVENT:
5280 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5281 		return PRIV_STACK_ADAPTIVE;
5282 	case BPF_PROG_TYPE_TRACING:
5283 	case BPF_PROG_TYPE_LSM:
5284 	case BPF_PROG_TYPE_STRUCT_OPS:
5285 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5286 			return PRIV_STACK_ADAPTIVE;
5287 		fallthrough;
5288 	default:
5289 		break;
5290 	}
5291 
5292 	return NO_PRIV_STACK;
5293 }
5294 
5295 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5296 {
5297 	if (env->prog->jit_requested)
5298 		return round_up(stack_depth, 16);
5299 
5300 	/* round up to 32-bytes, since this is granularity
5301 	 * of interpreter stack size
5302 	 */
5303 	return round_up(max_t(u32, stack_depth, 1), 32);
5304 }
5305 
5306 /* temporary state used for call frame depth calculation */
5307 struct bpf_subprog_call_depth_info {
5308 	int ret_insn; /* caller instruction where we return to. */
5309 	int caller; /* caller subprogram idx */
5310 	int frame; /* # of consecutive static call stack frames on top of stack */
5311 };
5312 
5313 /* starting from main bpf function walk all instructions of the function
5314  * and recursively walk all callees that given function can call.
5315  * Ignore jump and exit insns.
5316  */
5317 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5318 					 struct bpf_subprog_call_depth_info *dinfo,
5319 					 bool priv_stack_supported)
5320 {
5321 	struct bpf_subprog_info *subprog = env->subprog_info;
5322 	struct bpf_insn *insn = env->prog->insnsi;
5323 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5324 	bool tail_call_reachable = false;
5325 	int total;
5326 	int tmp;
5327 
5328 	/* no caller idx */
5329 	dinfo[idx].caller = -1;
5330 
5331 	i = subprog[idx].start;
5332 	if (!priv_stack_supported)
5333 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5334 process_func:
5335 	if (subprog[idx].has_ld_abs) {
5336 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5337 			if (subprog[tmp].is_cb) {
5338 				verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
5339 				return -EINVAL;
5340 			}
5341 		}
5342 	}
5343 
5344 	/* protect against potential stack overflow that might happen when
5345 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5346 	 * depth for such case down to 256 so that the worst case scenario
5347 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5348 	 * 8k).
5349 	 *
5350 	 * To get the idea what might happen, see an example:
5351 	 * func1 -> sub rsp, 128
5352 	 *  subfunc1 -> sub rsp, 256
5353 	 *  tailcall1 -> add rsp, 256
5354 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5355 	 *   subfunc2 -> sub rsp, 64
5356 	 *   subfunc22 -> sub rsp, 128
5357 	 *   tailcall2 -> add rsp, 128
5358 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5359 	 *
5360 	 * tailcall will unwind the current stack frame but it will not get rid
5361 	 * of caller's stack as shown on the example above.
5362 	 */
5363 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5364 		verbose(env,
5365 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5366 			depth);
5367 		return -EACCES;
5368 	}
5369 
5370 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5371 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5372 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5373 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5374 	} else if (priv_stack_supported) {
5375 		/* Request private stack support only if the subprog stack
5376 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5377 		 * avoid jit penalty if the stack usage is small.
5378 		 */
5379 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5380 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5381 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5382 	}
5383 
5384 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5385 		if (subprog_depth > env->max_stack_depth)
5386 			env->max_stack_depth = subprog_depth;
5387 		if (subprog_depth > MAX_BPF_STACK) {
5388 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5389 				idx, subprog_depth);
5390 			return -EACCES;
5391 		}
5392 	} else {
5393 		depth += subprog_depth;
5394 		if (depth > env->max_stack_depth)
5395 			env->max_stack_depth = depth;
5396 		if (depth > MAX_BPF_STACK) {
5397 			total = 0;
5398 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5399 				total++;
5400 
5401 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5402 				total, depth);
5403 			return -EACCES;
5404 		}
5405 	}
5406 continue_func:
5407 	subprog_end = subprog[idx + 1].start;
5408 	for (; i < subprog_end; i++) {
5409 		int next_insn, sidx;
5410 
5411 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5412 			bool err = false;
5413 
5414 			if (!bpf_is_throw_kfunc(insn + i))
5415 				continue;
5416 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5417 				if (subprog[tmp].is_cb) {
5418 					err = true;
5419 					break;
5420 				}
5421 			}
5422 			if (!err)
5423 				continue;
5424 			verbose(env,
5425 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5426 				i, idx);
5427 			return -EINVAL;
5428 		}
5429 
5430 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5431 			continue;
5432 		/* remember insn and function to return to */
5433 
5434 		/* find the callee */
5435 		next_insn = i + insn[i].imm + 1;
5436 		sidx = bpf_find_subprog(env, next_insn);
5437 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5438 			return -EFAULT;
5439 		if (subprog[sidx].is_async_cb) {
5440 			/* async callbacks don't increase bpf prog stack size unless called directly */
5441 			if (!bpf_pseudo_call(insn + i))
5442 				continue;
5443 			if (subprog[sidx].is_exception_cb) {
5444 				verbose(env, "insn %d cannot call exception cb directly", i);
5445 				return -EINVAL;
5446 			}
5447 		}
5448 
5449 		/* store caller info for after we return from callee */
5450 		dinfo[idx].frame = frame;
5451 		dinfo[idx].ret_insn = i + 1;
5452 
5453 		/* push caller idx into callee's dinfo */
5454 		dinfo[sidx].caller = idx;
5455 
5456 		i = next_insn;
5457 
5458 		idx = sidx;
5459 		if (!priv_stack_supported)
5460 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5461 
5462 		/* sync tail_call_reachable with callee state on entry */
5463 		tail_call_reachable = subprog[idx].has_tail_call;
5464 
5465 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5466 		if (frame >= MAX_CALL_FRAMES) {
5467 			verbose(env, "the call stack of %d frames is too deep !\n",
5468 				frame);
5469 			return -E2BIG;
5470 		}
5471 		goto process_func;
5472 	}
5473 	/* if tail call got detected across bpf2bpf calls then mark each of the
5474 	 * currently present subprog frames as tail call reachable subprogs;
5475 	 * this info will be utilized by JIT so that we will be preserving the
5476 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5477 	 */
5478 	if (tail_call_reachable) {
5479 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5480 			if (subprog[tmp].is_cb) {
5481 				verbose(env, "cannot tail call within callback\n");
5482 				return -EINVAL;
5483 			}
5484 			if (subprog[tmp].stack_arg_cnt) {
5485 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5486 				return -EINVAL;
5487 			}
5488 			subprog[tmp].tail_call_reachable = true;
5489 		}
5490 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
5491 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
5492 		return -EINVAL;
5493 	}
5494 
5495 	if (subprog[0].tail_call_reachable)
5496 		env->prog->aux->tail_call_reachable = true;
5497 
5498 	/* end of for() loop means the last insn of the 'subprog'
5499 	 * was reached. Doesn't matter whether it was JA or EXIT
5500 	 */
5501 	if (frame == 0 && dinfo[idx].caller < 0)
5502 		return 0;
5503 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
5504 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5505 
5506 	/* pop caller idx from callee */
5507 	idx = dinfo[idx].caller;
5508 
5509 	/* retrieve caller state from its frame */
5510 	frame = dinfo[idx].frame;
5511 	i = dinfo[idx].ret_insn;
5512 
5513 	/* reset tail_call_reachable to the parent's actual state */
5514 	tail_call_reachable = subprog[idx].tail_call_reachable;
5515 
5516 	goto continue_func;
5517 }
5518 
5519 static int check_max_stack_depth(struct bpf_verifier_env *env)
5520 {
5521 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
5522 	struct bpf_subprog_call_depth_info *dinfo;
5523 	struct bpf_subprog_info *si = env->subprog_info;
5524 	bool priv_stack_supported;
5525 	int ret;
5526 
5527 	dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
5528 	if (!dinfo)
5529 		return -ENOMEM;
5530 
5531 	for (int i = 0; i < env->subprog_cnt; i++) {
5532 		if (si[i].has_tail_call) {
5533 			priv_stack_mode = NO_PRIV_STACK;
5534 			break;
5535 		}
5536 	}
5537 
5538 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
5539 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
5540 
5541 	/* All async_cb subprogs use normal kernel stack. If a particular
5542 	 * subprog appears in both main prog and async_cb subtree, that
5543 	 * subprog will use normal kernel stack to avoid potential nesting.
5544 	 * The reverse subprog traversal ensures when main prog subtree is
5545 	 * checked, the subprogs appearing in async_cb subtrees are already
5546 	 * marked as using normal kernel stack, so stack size checking can
5547 	 * be done properly.
5548 	 */
5549 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
5550 		if (!i || si[i].is_async_cb) {
5551 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
5552 			ret = check_max_stack_depth_subprog(env, i, dinfo,
5553 					priv_stack_supported);
5554 			if (ret < 0) {
5555 				kvfree(dinfo);
5556 				return ret;
5557 			}
5558 		}
5559 	}
5560 
5561 	for (int i = 0; i < env->subprog_cnt; i++) {
5562 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5563 			env->prog->aux->jits_use_priv_stack = true;
5564 			break;
5565 		}
5566 	}
5567 
5568 	kvfree(dinfo);
5569 
5570 	return 0;
5571 }
5572 
5573 static int __check_buffer_access(struct bpf_verifier_env *env,
5574 				 const char *buf_info,
5575 				 const struct bpf_reg_state *reg,
5576 				 argno_t argno, int off, int size,
5577 				 u32 *access_end)
5578 {
5579 	s64 start;
5580 
5581 	if (!tnum_is_const(reg->var_off)) {
5582 		char tn_buf[48];
5583 
5584 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5585 		verbose(env,
5586 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
5587 			reg_arg_name(env, argno), off, tn_buf);
5588 		return -EACCES;
5589 	}
5590 
5591 	start = (s64)reg->var_off.value + off;
5592 	if (start < 0) {
5593 		verbose(env,
5594 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
5595 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
5596 		return -EACCES;
5597 	}
5598 
5599 	*access_end = start + size;
5600 	return 0;
5601 }
5602 
5603 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5604 				  const struct bpf_reg_state *reg,
5605 				  argno_t argno, int off, int size)
5606 {
5607 	u32 access_end;
5608 	int err;
5609 
5610 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
5611 	if (err)
5612 		return err;
5613 
5614 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
5615 
5616 	return 0;
5617 }
5618 
5619 static int check_buffer_access(struct bpf_verifier_env *env,
5620 			       const struct bpf_reg_state *reg,
5621 			       argno_t argno, int off, int size,
5622 			       bool zero_size_allowed,
5623 			       u32 *max_access)
5624 {
5625 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5626 	u32 access_end;
5627 	int err;
5628 
5629 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
5630 	if (err)
5631 		return err;
5632 
5633 	*max_access = max(access_end, *max_access);
5634 
5635 	return 0;
5636 }
5637 
5638 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5639 static void zext_32_to_64(struct bpf_reg_state *reg)
5640 {
5641 	reg->var_off = tnum_subreg(reg->var_off);
5642 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
5643 }
5644 
5645 /* truncate register to smaller size (in bytes)
5646  * must be called with size < BPF_REG_SIZE
5647  */
5648 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5649 {
5650 	u64 mask;
5651 
5652 	/* clear high bits in bit representation */
5653 	reg->var_off = tnum_cast(reg->var_off, size);
5654 
5655 	/* fix arithmetic bounds */
5656 	mask = ((u64)1 << (size * 8)) - 1;
5657 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
5658 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
5659 	else
5660 		reg_set_urange64(reg, 0, mask);
5661 
5662 	/* If size is smaller than 32bit register the 32bit register
5663 	 * values are also truncated so we push 64-bit bounds into
5664 	 * 32-bit bounds. Above were truncated < 32-bits already.
5665 	 */
5666 	if (size < 4)
5667 		__mark_reg32_unbounded(reg);
5668 
5669 	reg_bounds_sync(reg);
5670 }
5671 
5672 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5673 {
5674 	if (size == 1) {
5675 		reg_set_srange64(reg, S8_MIN, S8_MAX);
5676 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5677 	} else if (size == 2) {
5678 		reg_set_srange64(reg, S16_MIN, S16_MAX);
5679 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5680 	} else {
5681 		/* size == 4 */
5682 		reg_set_srange64(reg, S32_MIN, S32_MAX);
5683 		reg_set_srange32(reg, S32_MIN, S32_MAX);
5684 	}
5685 	reg->var_off = tnum_unknown;
5686 }
5687 
5688 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5689 {
5690 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5691 	u64 top_smax_value, top_smin_value;
5692 	u64 num_bits = size * 8;
5693 
5694 	if (tnum_is_const(reg->var_off)) {
5695 		u64_cval = reg->var_off.value;
5696 		if (size == 1)
5697 			reg->var_off = tnum_const((s8)u64_cval);
5698 		else if (size == 2)
5699 			reg->var_off = tnum_const((s16)u64_cval);
5700 		else
5701 			/* size == 4 */
5702 			reg->var_off = tnum_const((s32)u64_cval);
5703 
5704 		u64_cval = reg->var_off.value;
5705 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
5706 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
5707 		return;
5708 	}
5709 
5710 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
5711 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
5712 
5713 	if (top_smax_value != top_smin_value)
5714 		goto out;
5715 
5716 	/* find the s64_min and s64_min after sign extension */
5717 	if (size == 1) {
5718 		init_s64_max = (s8)reg_smax(reg);
5719 		init_s64_min = (s8)reg_smin(reg);
5720 	} else if (size == 2) {
5721 		init_s64_max = (s16)reg_smax(reg);
5722 		init_s64_min = (s16)reg_smin(reg);
5723 	} else {
5724 		init_s64_max = (s32)reg_smax(reg);
5725 		init_s64_min = (s32)reg_smin(reg);
5726 	}
5727 
5728 	s64_max = max(init_s64_max, init_s64_min);
5729 	s64_min = min(init_s64_max, init_s64_min);
5730 
5731 	/* both of s64_max/s64_min positive or negative */
5732 	if ((s64_max >= 0) == (s64_min >= 0)) {
5733 		reg_set_srange64(reg, s64_min, s64_max);
5734 		reg_set_srange32(reg, s64_min, s64_max);
5735 		reg->var_off = tnum_range(s64_min, s64_max);
5736 		return;
5737 	}
5738 
5739 out:
5740 	set_sext64_default_val(reg, size);
5741 }
5742 
5743 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5744 {
5745 	if (size == 1)
5746 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5747 	else
5748 		/* size == 2 */
5749 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5750 	reg->var_off = tnum_subreg(tnum_unknown);
5751 }
5752 
5753 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5754 {
5755 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5756 	u32 top_smax_value, top_smin_value;
5757 	u32 num_bits = size * 8;
5758 
5759 	if (tnum_is_const(reg->var_off)) {
5760 		u32_val = reg->var_off.value;
5761 		if (size == 1)
5762 			reg->var_off = tnum_const((s8)u32_val);
5763 		else
5764 			reg->var_off = tnum_const((s16)u32_val);
5765 
5766 		u32_val = reg->var_off.value;
5767 		reg_set_srange32(reg, u32_val, u32_val);
5768 		return;
5769 	}
5770 
5771 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
5772 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
5773 
5774 	if (top_smax_value != top_smin_value)
5775 		goto out;
5776 
5777 	/* find the s32_min and s32_min after sign extension */
5778 	if (size == 1) {
5779 		init_s32_max = (s8)reg_s32_max(reg);
5780 		init_s32_min = (s8)reg_s32_min(reg);
5781 	} else {
5782 		/* size == 2 */
5783 		init_s32_max = (s16)reg_s32_max(reg);
5784 		init_s32_min = (s16)reg_s32_min(reg);
5785 	}
5786 	s32_max = max(init_s32_max, init_s32_min);
5787 	s32_min = min(init_s32_max, init_s32_min);
5788 
5789 	if ((s32_min >= 0) == (s32_max >= 0)) {
5790 		reg_set_srange32(reg, s32_min, s32_max);
5791 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
5792 		return;
5793 	}
5794 
5795 out:
5796 	set_sext32_default_val(reg, size);
5797 }
5798 
5799 bool bpf_map_is_rdonly(const struct bpf_map *map)
5800 {
5801 	/* A map is considered read-only if the following condition are true:
5802 	 *
5803 	 * 1) BPF program side cannot change any of the map content. The
5804 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5805 	 *    and was set at map creation time.
5806 	 * 2) The map value(s) have been initialized from user space by a
5807 	 *    loader and then "frozen", such that no new map update/delete
5808 	 *    operations from syscall side are possible for the rest of
5809 	 *    the map's lifetime from that point onwards.
5810 	 * 3) Any parallel/pending map update/delete operations from syscall
5811 	 *    side have been completed. Only after that point, it's safe to
5812 	 *    assume that map value(s) are immutable.
5813 	 */
5814 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5815 	       READ_ONCE(map->frozen) &&
5816 	       !bpf_map_write_active(map);
5817 }
5818 
5819 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5820 			bool is_ldsx)
5821 {
5822 	void *ptr;
5823 	u64 addr;
5824 	int err;
5825 
5826 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY || map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY)
5827 		return -EINVAL;
5828 	err = map->ops->map_direct_value_addr(map, &addr, off);
5829 	if (err)
5830 		return err;
5831 	ptr = (void *)(long)addr + off;
5832 
5833 	switch (size) {
5834 	case sizeof(u8):
5835 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
5836 		break;
5837 	case sizeof(u16):
5838 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
5839 		break;
5840 	case sizeof(u32):
5841 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
5842 		break;
5843 	case sizeof(u64):
5844 		*val = *(u64 *)ptr;
5845 		break;
5846 	default:
5847 		return -EINVAL;
5848 	}
5849 	return 0;
5850 }
5851 
5852 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5853 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5854 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5855 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
5856 
5857 /*
5858  * Allow list few fields as RCU trusted or full trusted.
5859  * This logic doesn't allow mix tagging and will be removed once GCC supports
5860  * btf_type_tag.
5861  */
5862 
5863 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5864 BTF_TYPE_SAFE_RCU(struct task_struct) {
5865 	const cpumask_t *cpus_ptr;
5866 	struct css_set __rcu *cgroups;
5867 	struct task_struct __rcu *real_parent;
5868 	struct task_struct *group_leader;
5869 };
5870 
5871 BTF_TYPE_SAFE_RCU(struct cgroup) {
5872 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5873 	struct kernfs_node *kn;
5874 };
5875 
5876 BTF_TYPE_SAFE_RCU(struct css_set) {
5877 	struct cgroup *dfl_cgrp;
5878 };
5879 
5880 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
5881 	struct cgroup *cgroup;
5882 };
5883 
5884 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5885 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5886 	struct file __rcu *exe_file;
5887 #ifdef CONFIG_MEMCG
5888 	struct task_struct __rcu *owner;
5889 #endif
5890 };
5891 
5892 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5893  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5894  */
5895 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5896 	struct sock *sk;
5897 };
5898 
5899 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5900 	struct sock *sk;
5901 };
5902 
5903 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5904 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5905 	struct seq_file *seq;
5906 };
5907 
5908 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5909 	struct bpf_iter_meta *meta;
5910 	struct task_struct *task;
5911 };
5912 
5913 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5914 	struct file *file;
5915 };
5916 
5917 BTF_TYPE_SAFE_TRUSTED(struct file) {
5918 	struct inode *f_inode;
5919 };
5920 
5921 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
5922 	struct inode *d_inode;
5923 };
5924 
5925 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
5926 	struct sock *sk;
5927 };
5928 
5929 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
5930 	struct mm_struct *vm_mm;
5931 	struct file *vm_file;
5932 };
5933 
5934 static bool type_is_rcu(struct bpf_verifier_env *env,
5935 			struct bpf_reg_state *reg,
5936 			const char *field_name, u32 btf_id)
5937 {
5938 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5939 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5940 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5941 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
5942 
5943 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5944 }
5945 
5946 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5947 				struct bpf_reg_state *reg,
5948 				const char *field_name, u32 btf_id)
5949 {
5950 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5951 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5952 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5953 
5954 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5955 }
5956 
5957 static bool type_is_trusted(struct bpf_verifier_env *env,
5958 			    struct bpf_reg_state *reg,
5959 			    const char *field_name, u32 btf_id)
5960 {
5961 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5962 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5963 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5964 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5965 
5966 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5967 }
5968 
5969 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
5970 				    struct bpf_reg_state *reg,
5971 				    const char *field_name, u32 btf_id)
5972 {
5973 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
5974 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
5975 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
5976 
5977 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
5978 					  "__safe_trusted_or_null");
5979 }
5980 
5981 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5982 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
5983 				   argno_t argno, int off, int size,
5984 				   enum bpf_access_type atype,
5985 				   int value_regno)
5986 {
5987 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5988 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5989 	const char *field_name = NULL;
5990 	enum bpf_type_flag flag = 0;
5991 	u32 btf_id = 0;
5992 	int ret;
5993 
5994 	if (!env->allow_ptr_leaks) {
5995 		verbose(env,
5996 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5997 			tname);
5998 		return -EPERM;
5999 	}
6000 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6001 		verbose(env,
6002 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6003 			tname);
6004 		return -EINVAL;
6005 	}
6006 
6007 	if (!tnum_is_const(reg->var_off)) {
6008 		char tn_buf[48];
6009 
6010 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6011 		verbose(env,
6012 			"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6013 			reg_arg_name(env, argno), tname, off, tn_buf);
6014 		return -EACCES;
6015 	}
6016 
6017 	off += reg->var_off.value;
6018 
6019 	if (off < 0) {
6020 		verbose(env,
6021 			"%s is ptr_%s invalid negative access: off=%d\n",
6022 			reg_arg_name(env, argno), tname, off);
6023 		return -EACCES;
6024 	}
6025 
6026 	if (reg->type & MEM_USER) {
6027 		verbose(env,
6028 			"%s is ptr_%s access user memory: off=%d\n",
6029 			reg_arg_name(env, argno), tname, off);
6030 		return -EACCES;
6031 	}
6032 
6033 	if (reg->type & MEM_PERCPU) {
6034 		verbose(env,
6035 			"%s is ptr_%s access percpu memory: off=%d\n",
6036 			reg_arg_name(env, argno), tname, off);
6037 		return -EACCES;
6038 	}
6039 
6040 	if (atype != BPF_READ && bpf_may_fault_on_deref(reg->type)) {
6041 		verbose(env, "only read is supported\n");
6042 		return -EACCES;
6043 	}
6044 
6045 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6046 		if (!btf_is_kernel(reg->btf)) {
6047 			verifier_bug(env, "reg->btf must be kernel btf");
6048 			return -EFAULT;
6049 		}
6050 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6051 		if (ret < 0)
6052 			verbose(env,
6053 				"%s cannot write into ptr_%s at off=%d size=%d\n",
6054 				reg_arg_name(env, argno), tname, off, size);
6055 	} else {
6056 		/* Writes are permitted with default btf_struct_access for
6057 		 * program allocated objects (which always have id > 0).
6058 		 */
6059 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6060 			verbose(env, "only read is supported\n");
6061 			return -EACCES;
6062 		}
6063 
6064 		/*
6065 		 * A fault-prone allocated object may still be read through a
6066 		 * BPF_PROBE_MEM load after its lifetime protection ends. Writes
6067 		 * through such pointers were rejected above.
6068 		 */
6069 		if (type_is_alloc(reg->type) && !bpf_may_fault_on_deref(reg->type) &&
6070 		    !type_is_non_owning_ref(reg->type) &&
6071 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
6072 			verifier_bug(env, "allocated object must have a referenced id");
6073 			return -EFAULT;
6074 		}
6075 
6076 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6077 	}
6078 
6079 	if (ret < 0)
6080 		return ret;
6081 
6082 	if (ret != PTR_TO_BTF_ID) {
6083 		/* just mark; */
6084 
6085 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6086 		/* If this is an untrusted pointer, all pointers formed by walking it
6087 		 * also inherit the untrusted flag.
6088 		 */
6089 		flag = PTR_UNTRUSTED;
6090 
6091 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
6092 		/* By default any pointer obtained from walking a trusted pointer is no
6093 		 * longer trusted, unless the field being accessed has explicitly been
6094 		 * marked as inheriting its parent's state of trust (either full or RCU).
6095 		 * For example:
6096 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6097 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6098 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6099 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6100 		 *
6101 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6102 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6103 		 */
6104 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6105 			flag |= PTR_TRUSTED;
6106 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6107 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6108 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6109 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6110 				/* ignore __rcu tag and mark it MEM_RCU */
6111 				flag |= MEM_RCU;
6112 			} else if (flag & MEM_RCU ||
6113 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6114 				/* __rcu tagged pointers can be NULL */
6115 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6116 
6117 				/* We always trust them */
6118 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6119 				    flag & PTR_UNTRUSTED)
6120 					flag &= ~PTR_UNTRUSTED;
6121 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6122 				/* keep as-is */
6123 			} else {
6124 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6125 				clear_trusted_flags(&flag);
6126 			}
6127 		} else {
6128 			/*
6129 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6130 			 * aggressively mark as untrusted otherwise such
6131 			 * pointers will be plain PTR_TO_BTF_ID without flags
6132 			 * and will be allowed to be passed into helpers for
6133 			 * compat reasons.
6134 			 */
6135 			flag = PTR_UNTRUSTED;
6136 		}
6137 	} else {
6138 		/* Old compat. Deprecated */
6139 		clear_trusted_flags(&flag);
6140 	}
6141 
6142 	if (atype == BPF_READ && value_regno >= 0) {
6143 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6144 		if (ret < 0)
6145 			return ret;
6146 	}
6147 
6148 	return 0;
6149 }
6150 
6151 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6152 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
6153 				   argno_t argno, int off, int size,
6154 				   enum bpf_access_type atype,
6155 				   int value_regno)
6156 {
6157 	struct bpf_map *map = reg->map_ptr;
6158 	struct bpf_reg_state map_reg;
6159 	enum bpf_type_flag flag = 0;
6160 	const struct btf_type *t;
6161 	const char *tname;
6162 	u32 btf_id;
6163 	int ret;
6164 
6165 	if (!btf_vmlinux) {
6166 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6167 		return -ENOTSUPP;
6168 	}
6169 
6170 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6171 		verbose(env, "map_ptr access not supported for map type %d\n",
6172 			map->map_type);
6173 		return -ENOTSUPP;
6174 	}
6175 
6176 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6177 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6178 
6179 	if (!env->allow_ptr_leaks) {
6180 		verbose(env,
6181 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6182 			tname);
6183 		return -EPERM;
6184 	}
6185 
6186 	if (off < 0) {
6187 		verbose(env, "%s is %s invalid negative access: off=%d\n",
6188 			reg_arg_name(env, argno), tname, off);
6189 		return -EACCES;
6190 	}
6191 
6192 	if (atype != BPF_READ) {
6193 		verbose(env, "only read from %s is supported\n", tname);
6194 		return -EACCES;
6195 	}
6196 
6197 	/* Simulate access to a PTR_TO_BTF_ID */
6198 	memset(&map_reg, 0, sizeof(map_reg));
6199 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
6200 			      btf_vmlinux, *map->ops->map_btf_id, 0);
6201 	if (ret < 0)
6202 		return ret;
6203 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6204 	if (ret < 0)
6205 		return ret;
6206 
6207 	if (value_regno >= 0) {
6208 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6209 		if (ret < 0)
6210 			return ret;
6211 	}
6212 
6213 	return 0;
6214 }
6215 
6216 /* Check that the stack access at the given offset is within bounds. The
6217  * maximum valid offset is -1.
6218  *
6219  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6220  * -state->allocated_stack for reads.
6221  */
6222 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6223                                           s64 off,
6224                                           struct bpf_func_state *state,
6225                                           enum bpf_access_type t)
6226 {
6227 	int min_valid_off;
6228 
6229 	if (t == BPF_WRITE || env->allow_uninit_stack)
6230 		min_valid_off = -MAX_BPF_STACK;
6231 	else
6232 		min_valid_off = -state->allocated_stack;
6233 
6234 	if (off < min_valid_off || off > -1)
6235 		return -EACCES;
6236 	return 0;
6237 }
6238 
6239 /* Check that the stack access at 'regno + off' falls within the maximum stack
6240  * bounds.
6241  *
6242  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6243  */
6244 static int check_stack_access_within_bounds(
6245 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6246 		argno_t argno, int off, int access_size,
6247 		enum bpf_access_type type)
6248 {
6249 	struct bpf_func_state *state = bpf_func(env, reg);
6250 	s64 min_off, max_off;
6251 	int err;
6252 	char *err_extra;
6253 
6254 	if (type == BPF_READ)
6255 		err_extra = " read from";
6256 	else
6257 		err_extra = " write to";
6258 
6259 	if (tnum_is_const(reg->var_off)) {
6260 		min_off = (s64)reg->var_off.value + off;
6261 		max_off = min_off + access_size;
6262 	} else {
6263 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
6264 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
6265 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
6266 				err_extra, reg_arg_name(env, argno));
6267 			return -EACCES;
6268 		}
6269 		min_off = reg_smin(reg) + off;
6270 		max_off = reg_smax(reg) + off + access_size;
6271 	}
6272 
6273 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6274 	if (!err && max_off > 0)
6275 		err = -EINVAL; /* out of stack access into non-negative offsets */
6276 	if (!err && access_size < 0)
6277 		/* access_size should not be negative (or overflow an int); others checks
6278 		 * along the way should have prevented such an access.
6279 		 */
6280 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6281 
6282 	if (err) {
6283 		if (tnum_is_const(reg->var_off)) {
6284 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
6285 				err_extra, reg_arg_name(env, argno), min_off, access_size);
6286 		} else {
6287 			char tn_buf[48];
6288 
6289 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6290 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
6291 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
6292 		}
6293 		return err;
6294 	}
6295 
6296 	/* Note that there is no stack access with offset zero, so the needed stack
6297 	 * size is -min_off, not -min_off+1.
6298 	 */
6299 	return grow_stack_state(env, state, -min_off /* size */);
6300 }
6301 
6302 static bool get_func_retval_range(struct bpf_prog *prog,
6303 				  struct bpf_retval_range *range)
6304 {
6305 	if (prog->type == BPF_PROG_TYPE_LSM &&
6306 		prog->expected_attach_type == BPF_LSM_MAC &&
6307 		!bpf_lsm_get_retval_range(prog, range)) {
6308 		return true;
6309 	}
6310 	return false;
6311 }
6312 
6313 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
6314 {
6315 	struct bpf_reg_state fake_reg;
6316 
6317 	if (!val)
6318 		return;
6319 
6320 	fake_reg.type = SCALAR_VALUE;
6321 	__mark_reg_known(&fake_reg, val);
6322 
6323 	scalar32_min_max_add(dst_reg, &fake_reg);
6324 	scalar_min_max_add(dst_reg, &fake_reg);
6325 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
6326 
6327 	reg_bounds_sync(dst_reg);
6328 }
6329 
6330 static int check_map_mem_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off,
6331 			      int bpf_size, int value_regno, bool is_ldsx)
6332 {
6333 	struct bpf_reg_state *regs = cur_regs(env);
6334 	int size = bpf_size_to_bytes(bpf_size);
6335 	struct bpf_map *map = reg->map_ptr;
6336 
6337 	switch (map->map_type) {
6338 	case BPF_MAP_TYPE_INSN_ARRAY:
6339 		if (bpf_size != BPF_DW) {
6340 			verbose(env, "Invalid read of %d bytes from insn_array\n", size);
6341 			return -EACCES;
6342 		}
6343 		regs[value_regno] = *reg;
6344 		add_scalar_to_reg(&regs[value_regno], off);
6345 		regs[value_regno].type = PTR_TO_INSN;
6346 		return 0;
6347 	case BPF_MAP_TYPE_PERCPU_ARRAY:
6348 		goto reg_unknown;
6349 	default:
6350 		break;
6351 	}
6352 
6353 	/* If map is read-only, track its contents as scalars. */
6354 	if (tnum_is_const(reg->var_off) &&
6355 	    bpf_map_is_rdonly(map) &&
6356 	    map->ops->map_direct_value_addr) {
6357 		int map_off = off + reg->var_off.value;
6358 		u64 val = 0;
6359 		int err;
6360 
6361 		err = bpf_map_direct_read(map, map_off, size, &val, is_ldsx);
6362 		if (err)
6363 			return err;
6364 
6365 		regs[value_regno].type = SCALAR_VALUE;
6366 		__mark_reg_known(&regs[value_regno], val);
6367 		return 0;
6368 	}
6369 
6370 reg_unknown:
6371 	mark_reg_unknown(env, regs, value_regno);
6372 	return 0;
6373 }
6374 
6375 /* check whether memory at (regno + off) is accessible for t = (read | write)
6376  * if t==write, value_regno is a register which value is stored into memory
6377  * if t==read, value_regno is a register which will receive the value from memory
6378  * if t==write && value_regno==-1, some unknown value is stored into memory
6379  * if t==read && value_regno==-1, don't care what we read from memory
6380  */
6381 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
6382 			    int off, int bpf_size, enum bpf_access_type t,
6383 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6384 {
6385 	struct bpf_reg_state *regs = cur_regs(env);
6386 	int size, err = 0;
6387 
6388 	size = bpf_size_to_bytes(bpf_size);
6389 	if (size < 0)
6390 		return size;
6391 
6392 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6393 	if (err)
6394 		return err;
6395 
6396 	if (reg->type == PTR_TO_MAP_KEY) {
6397 		if (t == BPF_WRITE) {
6398 			verbose(env, "write to change key %s not allowed\n",
6399 				reg_arg_name(env, argno));
6400 			return -EACCES;
6401 		}
6402 
6403 		err = check_mem_region_access(env, reg, argno, off, size,
6404 					      reg->map_ptr->key_size, false);
6405 		if (err)
6406 			return err;
6407 		if (value_regno >= 0)
6408 			mark_reg_unknown(env, regs, value_regno);
6409 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6410 		struct btf_field *kptr_field = NULL;
6411 
6412 		if (t == BPF_WRITE && value_regno >= 0 &&
6413 		    is_pointer_value(env, value_regno)) {
6414 			verbose(env, "R%d leaks addr into map\n", value_regno);
6415 			return -EACCES;
6416 		}
6417 		err = check_map_access_type(env, reg, off, size, t);
6418 		if (err)
6419 			return err;
6420 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
6421 		if (err)
6422 			return err;
6423 		if (tnum_is_const(reg->var_off))
6424 			kptr_field = btf_record_find(reg->map_ptr->record,
6425 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
6426 		if (kptr_field) {
6427 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
6428 		} else if (t == BPF_READ && value_regno >= 0) {
6429 			err = check_map_mem_read(env, reg, off, bpf_size, value_regno, is_ldsx);
6430 		}
6431 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6432 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6433 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
6434 
6435 		if (type_may_be_null(reg->type)) {
6436 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6437 				reg_type_str(env, reg->type));
6438 			bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
6439 					       reg_arg_name(env, argno), reg,
6440 						      BPF_DIAG_DEREF_NULLABLE_PTR, 0);
6441 			return -EACCES;
6442 		}
6443 
6444 		if (t == BPF_WRITE && rdonly_mem) {
6445 			verbose(env, "%s cannot write into %s\n",
6446 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6447 			return -EACCES;
6448 		}
6449 
6450 		if (t == BPF_WRITE && value_regno >= 0 &&
6451 		    is_pointer_value(env, value_regno)) {
6452 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6453 			return -EACCES;
6454 		}
6455 
6456 		/*
6457 		 * Accesses to untrusted PTR_TO_MEM are done through probe
6458 		 * instructions, hence no need to check bounds in that case.
6459 		 */
6460 		if (!rdonly_untrusted)
6461 			err = check_mem_region_access(env, reg, argno, off, size,
6462 						      reg->mem_size, false);
6463 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6464 			mark_reg_unknown(env, regs, value_regno);
6465 	} else if (reg->type == PTR_TO_CTX) {
6466 		struct bpf_insn_access_aux info = {
6467 			.reg_type = SCALAR_VALUE,
6468 			.is_ldsx = is_ldsx,
6469 			.log = &env->log,
6470 		};
6471 		struct bpf_retval_range range;
6472 
6473 		if (t == BPF_WRITE && value_regno >= 0 &&
6474 		    is_pointer_value(env, value_regno)) {
6475 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6476 			return -EACCES;
6477 		}
6478 
6479 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
6480 		if (!err && t == BPF_READ && value_regno >= 0) {
6481 			/* ctx access returns either a scalar, or a
6482 			 * PTR_TO_PACKET[_META,_END]. In the latter
6483 			 * case, we know the offset is zero.
6484 			 */
6485 			if (info.reg_type == SCALAR_VALUE) {
6486 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
6487 					mark_reg_unknown(env, regs, value_regno);
6488 					err = __mark_reg_s32_range(env, regs, value_regno,
6489 								   range.minval, range.maxval);
6490 					if (err)
6491 						return err;
6492 				} else {
6493 					mark_reg_unknown(env, regs, value_regno);
6494 				}
6495 			} else {
6496 				mark_reg_known_zero(env, regs,
6497 						    value_regno);
6498 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
6499 					regs[value_regno].btf = info.btf;
6500 					regs[value_regno].btf_id = info.btf_id;
6501 					regs[value_regno].id = info.ref_id;
6502 				}
6503 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
6504 					regs[value_regno].id = ++env->id_gen;
6505 			}
6506 			regs[value_regno].type = info.reg_type;
6507 		}
6508 
6509 	} else if (reg->type == PTR_TO_STACK) {
6510 		/* Basic bounds checks. */
6511 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
6512 		if (err)
6513 			return err;
6514 
6515 		if (t == BPF_READ)
6516 			err = check_stack_read(env, reg, argno, off, size,
6517 					       value_regno);
6518 		else
6519 			err = check_stack_write(env, reg, off, size,
6520 						value_regno, insn_idx);
6521 	} else if (reg_is_pkt_pointer(reg)) {
6522 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6523 			verbose(env, "cannot write into packet\n");
6524 			return -EACCES;
6525 		}
6526 		if (t == BPF_WRITE && value_regno >= 0 &&
6527 		    is_pointer_value(env, value_regno)) {
6528 			verbose(env, "R%d leaks addr into packet\n",
6529 				value_regno);
6530 			return -EACCES;
6531 		}
6532 		err = check_packet_access(env, reg, argno, off, size, false);
6533 		if (!err && t == BPF_READ && value_regno >= 0)
6534 			mark_reg_unknown(env, regs, value_regno);
6535 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6536 		if (t == BPF_WRITE && value_regno >= 0 &&
6537 		    is_pointer_value(env, value_regno)) {
6538 			verbose(env, "R%d leaks addr into flow keys\n",
6539 				value_regno);
6540 			return -EACCES;
6541 		}
6542 
6543 		err = check_flow_keys_access(env, reg, argno, off, size);
6544 		if (!err && t == BPF_READ && value_regno >= 0)
6545 			mark_reg_unknown(env, regs, value_regno);
6546 	} else if (type_is_sk_pointer(reg->type)) {
6547 		if (t == BPF_WRITE) {
6548 			verbose(env, "%s cannot write into %s\n",
6549 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6550 			return -EACCES;
6551 		}
6552 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
6553 		if (!err && value_regno >= 0)
6554 			mark_reg_unknown(env, regs, value_regno);
6555 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6556 		err = check_tp_buffer_access(env, reg, argno, off, size);
6557 		if (!err && t == BPF_READ && value_regno >= 0)
6558 			mark_reg_unknown(env, regs, value_regno);
6559 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6560 		   !type_may_be_null(reg->type)) {
6561 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
6562 					      value_regno);
6563 	} else if (reg->type == CONST_PTR_TO_MAP) {
6564 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
6565 					      value_regno);
6566 	} else if (base_type(reg->type) == PTR_TO_BUF &&
6567 		   !type_may_be_null(reg->type)) {
6568 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6569 		u32 *max_access;
6570 
6571 		if (rdonly_mem) {
6572 			if (t == BPF_WRITE) {
6573 				verbose(env, "%s cannot write into %s\n",
6574 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6575 				return -EACCES;
6576 			}
6577 			max_access = &env->prog->aux->max_rdonly_access;
6578 		} else {
6579 			max_access = &env->prog->aux->max_rdwr_access;
6580 		}
6581 
6582 		err = check_buffer_access(env, reg, argno, off, size, false,
6583 					  max_access);
6584 
6585 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6586 			mark_reg_unknown(env, regs, value_regno);
6587 	} else if (reg->type == PTR_TO_ARENA) {
6588 		if (t == BPF_READ && value_regno >= 0)
6589 			mark_reg_unknown(env, regs, value_regno);
6590 	} else {
6591 		enum bpf_diag_invalid_deref_kind kind = BPF_DIAG_DEREF_INVALID_PTR;
6592 
6593 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6594 			reg_type_str(env, reg->type));
6595 		if (reg->type == SCALAR_VALUE)
6596 			kind = BPF_DIAG_DEREF_SCALAR;
6597 		else if (type_may_be_null(reg->type))
6598 			kind = BPF_DIAG_DEREF_NULLABLE_PTR;
6599 		bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno),
6600 				       reg_arg_name(env, argno), reg, kind, 0);
6601 		return -EACCES;
6602 	}
6603 
6604 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6605 	    regs[value_regno].type == SCALAR_VALUE) {
6606 		if (!is_ldsx) {
6607 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6608 			coerce_reg_to_size(&regs[value_regno], size);
6609 		} else {
6610 			/*
6611 			 * Sign-extension can change the register value relative
6612 			 * to a scalar it is linked with by id (e.g. a zero-
6613 			 * extending fill of the same spilled stack slot), thus
6614 			 * drop the shared id in that case.
6615 			 */
6616 			bool no_sext = reg_umax(&regs[value_regno]) <
6617 					(1ULL << (size * BITS_PER_BYTE - 1));
6618 
6619 			coerce_reg_to_size_sx(&regs[value_regno], size);
6620 			if (!no_sext)
6621 				clear_scalar_id(&regs[value_regno]);
6622 		}
6623 	}
6624 	return err;
6625 }
6626 
6627 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
6628 			     bool allow_trust_mismatch);
6629 
6630 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
6631 			  bool strict_alignment_once, bool is_ldsx,
6632 			  bool allow_trust_mismatch, const char *ctx)
6633 {
6634 	struct bpf_verifier_state *vstate = env->cur_state;
6635 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6636 	struct bpf_reg_state *regs = cur_regs(env);
6637 	enum bpf_reg_type src_reg_type;
6638 	int err;
6639 
6640 	/* Handle stack arg read */
6641 	if (is_stack_arg_ldx(insn)) {
6642 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6643 		if (err)
6644 			return err;
6645 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
6646 	}
6647 
6648 	/* check src operand */
6649 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6650 	if (err)
6651 		return err;
6652 
6653 	/* check dst operand */
6654 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6655 	if (err)
6656 		return err;
6657 
6658 	src_reg_type = regs[insn->src_reg].type;
6659 
6660 	/*
6661 	 * check_stack_read_fixed_off() may refine the modification's origin to
6662 	 * the source stack slot.
6663 	 */
6664 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
6665 	err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off,
6666 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
6667 			       strict_alignment_once, is_ldsx);
6668 	err = err ?: save_aux_ptr_type(env, src_reg_type,
6669 				       allow_trust_mismatch);
6670 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
6671 	if (!err)
6672 		bpf_diag_mod_end(env);
6673 
6674 	return err;
6675 }
6676 
6677 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
6678 			   bool strict_alignment_once)
6679 {
6680 	struct bpf_verifier_state *vstate = env->cur_state;
6681 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6682 	struct bpf_reg_state *regs = cur_regs(env);
6683 	enum bpf_reg_type dst_reg_type;
6684 	int err;
6685 
6686 	/* Handle stack arg write */
6687 	if (is_stack_arg_stx(insn)) {
6688 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
6689 		if (err)
6690 			return err;
6691 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
6692 	}
6693 
6694 	/* check src1 operand */
6695 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6696 	if (err)
6697 		return err;
6698 
6699 	/* check src2 operand */
6700 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6701 	if (err)
6702 		return err;
6703 
6704 	dst_reg_type = regs[insn->dst_reg].type;
6705 
6706 	/* Check if (dst_reg + off) is writeable. */
6707 	err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6708 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
6709 			       strict_alignment_once, false);
6710 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
6711 
6712 	return err;
6713 }
6714 
6715 static int check_atomic_rmw(struct bpf_verifier_env *env,
6716 			    struct bpf_insn *insn)
6717 {
6718 	struct bpf_reg_state *dst_reg;
6719 	int load_reg;
6720 	int err;
6721 
6722 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6723 		verbose(env, "invalid atomic operand size\n");
6724 		return -EINVAL;
6725 	}
6726 
6727 	/* check src1 operand */
6728 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6729 	if (err)
6730 		return err;
6731 
6732 	/* check src2 operand */
6733 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6734 	if (err)
6735 		return err;
6736 
6737 	if (insn->imm == BPF_CMPXCHG) {
6738 		/* Check comparison of R0 with memory location */
6739 		const u32 aux_reg = BPF_REG_0;
6740 
6741 		err = check_reg_arg(env, aux_reg, SRC_OP);
6742 		if (err)
6743 			return err;
6744 
6745 		if (is_pointer_value(env, aux_reg)) {
6746 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6747 			return -EACCES;
6748 		}
6749 	}
6750 
6751 	if (is_pointer_value(env, insn->src_reg)) {
6752 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6753 		return -EACCES;
6754 	}
6755 
6756 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6757 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6758 			insn->dst_reg,
6759 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6760 		return -EACCES;
6761 	}
6762 
6763 	load_reg = bpf_atomic_load_reg(insn);
6764 	if (load_reg >= 0) {
6765 		/* check and record load of old value */
6766 		err = check_reg_arg(env, load_reg, DST_OP);
6767 		if (err)
6768 			return err;
6769 	}
6770 
6771 	dst_reg = cur_regs(env) + insn->dst_reg;
6772 
6773 	/* Check whether we can read the memory, with second call for fetch
6774 	 * case to simulate the register fill.
6775 	 */
6776 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6777 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6778 	if (!err && load_reg >= 0) {
6779 		bpf_diag_mod_begin(env, cur_regs(env) + load_reg, NULL, BPF_DIAG_MOD_WRITE);
6780 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
6781 				       insn->off, BPF_SIZE(insn->code),
6782 				       BPF_READ, load_reg, true, false);
6783 		if (!err)
6784 			bpf_diag_mod_end(env);
6785 	}
6786 	if (err)
6787 		return err;
6788 
6789 	err = save_aux_ptr_type(env, dst_reg->type, false);
6790 	if (err)
6791 		return err;
6792 	/* Check whether we can write into the same memory. */
6793 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6794 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6795 	if (err)
6796 		return err;
6797 	return 0;
6798 }
6799 
6800 static int check_atomic_load(struct bpf_verifier_env *env,
6801 			     struct bpf_insn *insn)
6802 {
6803 	int err;
6804 
6805 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6806 	if (err)
6807 		return err;
6808 
6809 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
6810 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
6811 			insn->src_reg,
6812 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
6813 		return -EACCES;
6814 	}
6815 
6816 	return check_load_mem(env, insn, true, false, false, "atomic_load");
6817 }
6818 
6819 static int check_atomic_store(struct bpf_verifier_env *env,
6820 			      struct bpf_insn *insn)
6821 {
6822 	int err;
6823 
6824 	err = check_store_reg(env, insn, true);
6825 	if (err)
6826 		return err;
6827 
6828 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6829 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6830 			insn->dst_reg,
6831 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6832 		return -EACCES;
6833 	}
6834 
6835 	return 0;
6836 }
6837 
6838 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
6839 {
6840 	switch (insn->imm) {
6841 	case BPF_ADD:
6842 	case BPF_ADD | BPF_FETCH:
6843 	case BPF_AND:
6844 	case BPF_AND | BPF_FETCH:
6845 	case BPF_OR:
6846 	case BPF_OR | BPF_FETCH:
6847 	case BPF_XOR:
6848 	case BPF_XOR | BPF_FETCH:
6849 	case BPF_XCHG:
6850 	case BPF_CMPXCHG:
6851 		return check_atomic_rmw(env, insn);
6852 	case BPF_LOAD_ACQ:
6853 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6854 			verbose(env,
6855 				"64-bit load-acquires are only supported on 64-bit arches\n");
6856 			return -EOPNOTSUPP;
6857 		}
6858 		return check_atomic_load(env, insn);
6859 	case BPF_STORE_REL:
6860 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6861 			verbose(env,
6862 				"64-bit store-releases are only supported on 64-bit arches\n");
6863 			return -EOPNOTSUPP;
6864 		}
6865 		return check_atomic_store(env, insn);
6866 	default:
6867 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
6868 			insn->imm);
6869 		return -EINVAL;
6870 	}
6871 }
6872 
6873 /* When register 'regno' is used to read the stack (either directly or through
6874  * a helper function) make sure that it's within stack boundary and, depending
6875  * on the access type and privileges, that all elements of the stack are
6876  * initialized.
6877  *
6878  * All registers that have been spilled on the stack in the slots within the
6879  * read offsets are marked as read.
6880  */
6881 static int check_stack_range_initialized(
6882 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
6883 		int access_size, bool zero_size_allowed,
6884 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
6885 {
6886 	struct bpf_func_state *state = bpf_func(env, reg);
6887 	int err, min_off, max_off, i, j, slot, spi;
6888 	/* Some accesses can write anything into the stack, others are
6889 	 * read-only.
6890 	 */
6891 	bool clobber = type == BPF_WRITE;
6892 	/*
6893 	 * Negative access_size signals global subprog arg check where
6894 	 * STACK_POISON slots are acceptable. static stack liveness
6895 	 * might have determined that subprog doesn't read them,
6896 	 * but BTF based global subprog validation isn't accurate enough.
6897 	 */
6898 	bool allow_poison = access_size < 0 || clobber;
6899 	/* The call will initialize the memory; uninitialized stack allowed */
6900 	bool raw_mode = meta && meta->arg_raw_mem.regno == reg_from_argno(argno);
6901 
6902 	access_size = abs(access_size);
6903 
6904 	if (access_size == 0 && !zero_size_allowed) {
6905 		verbose(env, "invalid zero-sized read\n");
6906 		return -EACCES;
6907 	}
6908 
6909 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
6910 	if (err)
6911 		return err;
6912 
6913 	if (tnum_is_const(reg->var_off)) {
6914 		min_off = max_off = reg->var_off.value + off;
6915 	} else {
6916 		/* Variable offset is prohibited for unprivileged mode for
6917 		 * simplicity since it requires corresponding support in
6918 		 * Spectre masking for stack ALU.
6919 		 * See also retrieve_ptr_limit().
6920 		 */
6921 		if (!env->bypass_spec_v1) {
6922 			char tn_buf[48];
6923 
6924 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6925 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
6926 				reg_arg_name(env, argno), tn_buf);
6927 			return -EACCES;
6928 		}
6929 		/* Only initialized buffer on stack is allowed to be accessed
6930 		 * with variable offset. With uninitialized buffer it's hard to
6931 		 * guarantee that whole memory is marked as initialized on
6932 		 * helper return since specific bounds are unknown what may
6933 		 * cause uninitialized stack leaking.
6934 		 */
6935 		raw_mode = false;
6936 
6937 		min_off = reg_smin(reg) + off;
6938 		max_off = reg_smax(reg) + off;
6939 	}
6940 
6941 	if (raw_mode) {
6942 		meta->arg_raw_mem.size = access_size;
6943 		return 0;
6944 	}
6945 
6946 	for (i = min_off; i < max_off + access_size; i++) {
6947 		u8 *stype;
6948 
6949 		slot = -i - 1;
6950 		spi = slot / BPF_REG_SIZE;
6951 		if (state->allocated_stack <= slot) {
6952 			verbose(env, "allocated_stack too small\n");
6953 			return -EFAULT;
6954 		}
6955 
6956 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6957 		if (*stype == STACK_MISC)
6958 			goto mark;
6959 		if ((*stype == STACK_ZERO) ||
6960 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6961 			if (clobber) {
6962 				/* helper can write anything into the stack */
6963 				*stype = STACK_MISC;
6964 			}
6965 			goto mark;
6966 		}
6967 
6968 		if (bpf_is_spilled_reg(&state->stack[spi]) &&
6969 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6970 		     env->allow_ptr_leaks)) {
6971 			if (clobber) {
6972 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6973 				for (j = 0; j < BPF_REG_SIZE; j++)
6974 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6975 			}
6976 			goto mark;
6977 		}
6978 
6979 		if (*stype == STACK_POISON) {
6980 			if (allow_poison)
6981 				goto mark;
6982 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
6983 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6984 		} else if (tnum_is_const(reg->var_off)) {
6985 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
6986 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6987 		} else {
6988 			char tn_buf[48];
6989 
6990 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6991 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
6992 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
6993 		}
6994 		return -EACCES;
6995 mark:
6996 		;
6997 	}
6998 	return 0;
6999 }
7000 
7001 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7002 				   argno_t argno, int access_size,
7003 				   enum bpf_access_type access_type, bool zero_size_allowed,
7004 				   struct bpf_call_arg_meta *meta, bool *known_memory)
7005 {
7006 	struct bpf_reg_state *regs = cur_regs(env);
7007 	u32 *max_access;
7008 
7009 	if (known_memory)
7010 		*known_memory = true;
7011 
7012 	switch (base_type(reg->type)) {
7013 	case PTR_TO_PACKET:
7014 	case PTR_TO_PACKET_META:
7015 		return check_packet_access(env, reg, argno, 0, access_size,
7016 					   zero_size_allowed);
7017 	case PTR_TO_MAP_KEY:
7018 		if (access_type == BPF_WRITE) {
7019 			verbose(env, "%s cannot write into %s\n",
7020 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7021 			return -EACCES;
7022 		}
7023 		return check_mem_region_access(env, reg, argno, 0, access_size,
7024 					       reg->map_ptr->key_size, false);
7025 	case PTR_TO_MAP_VALUE:
7026 		if (check_map_access_type(env, reg, 0, access_size, access_type))
7027 			return -EACCES;
7028 		return check_map_access(env, reg, argno, 0, access_size,
7029 					zero_size_allowed, ACCESS_HELPER);
7030 	case PTR_TO_MEM:
7031 		if (type_is_rdonly_mem(reg->type)) {
7032 			if (access_type == BPF_WRITE) {
7033 				verbose(env, "%s cannot write into %s\n",
7034 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7035 				return -EACCES;
7036 			}
7037 		}
7038 		return check_mem_region_access(env, reg, argno, 0,
7039 					       access_size, reg->mem_size,
7040 					       zero_size_allowed);
7041 	case PTR_TO_BUF:
7042 		if (type_is_rdonly_mem(reg->type)) {
7043 			if (access_type == BPF_WRITE) {
7044 				verbose(env, "%s cannot write into %s\n",
7045 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
7046 				return -EACCES;
7047 			}
7048 
7049 			max_access = &env->prog->aux->max_rdonly_access;
7050 		} else {
7051 			max_access = &env->prog->aux->max_rdwr_access;
7052 		}
7053 		return check_buffer_access(env, reg, argno, 0,
7054 					   access_size, zero_size_allowed,
7055 					   max_access);
7056 	case PTR_TO_STACK:
7057 		return check_stack_range_initialized(
7058 				env, reg,
7059 				argno, 0, access_size,
7060 				zero_size_allowed, access_type, meta);
7061 	case PTR_TO_BTF_ID:
7062 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
7063 					       access_size, access_type, -1);
7064 	case PTR_TO_CTX:
7065 		/* Only permit reading or writing syscall context using helper calls. */
7066 		if (is_var_ctx_off_allowed(env->prog)) {
7067 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
7068 							  zero_size_allowed);
7069 			if (err)
7070 				return err;
7071 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
7072 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
7073 			return 0;
7074 		}
7075 		fallthrough;
7076 	default: /* scalar_value or invalid ptr */
7077 		/* Allow zero-byte read from NULL, regardless of pointer type */
7078 		if (zero_size_allowed && access_size == 0 &&
7079 		    bpf_register_is_null(reg))
7080 			return 0;
7081 		if (known_memory && base_type(reg->type) != PTR_TO_CTX)
7082 			*known_memory = false;
7083 
7084 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
7085 			reg_type_str(env, reg->type));
7086 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7087 		return -EACCES;
7088 	}
7089 }
7090 
7091 enum bpf_mem_size_failure {
7092 	BPF_MEM_SIZE_FAIL_NONE,
7093 	BPF_MEM_SIZE_FAIL_MEMORY,
7094 	BPF_MEM_SIZE_FAIL_SIZE,
7095 };
7096 
7097 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7098  * size.
7099  *
7100  * @mem_reg contains the pointer, @size_reg contains the access size.
7101  */
7102 static int check_mem_size_reg(struct bpf_verifier_env *env,
7103 			      struct bpf_reg_state *mem_reg,
7104 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
7105 			      argno_t size_argno, u32 access_type,
7106 			      bool zero_size_allowed,
7107 			      struct bpf_call_arg_meta *meta,
7108 			      enum bpf_mem_size_failure *failure)
7109 {
7110 	int err = 0;
7111 
7112 	if (failure)
7113 		*failure = BPF_MEM_SIZE_FAIL_NONE;
7114 
7115 	/* This is used to refine r0 return value bounds for helpers
7116 	 * that enforce this value as an upper bound on return values.
7117 	 * See do_refine_retval_range() for helpers that can refine
7118 	 * the return value. C type of helper is u32 so we pull register
7119 	 * bound from umax_value however, if negative verifier errors
7120 	 * out. Only upper bounds can be learned because retval is an
7121 	 * int type and negative retvals are allowed.
7122 	 */
7123 	meta->msize_max_value = reg_umax(size_reg);
7124 
7125 	/* The register is SCALAR_VALUE; the access check happens using
7126 	 * its boundaries. For unprivileged variable accesses, disable
7127 	 * raw mode so that the program is required to initialize all
7128 	 * the memory that the helper could just partially fill up.
7129 	 */
7130 	if (!tnum_is_const(size_reg->var_off))
7131 		meta = NULL;
7132 
7133 	if (reg_smin(size_reg) < 0) {
7134 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
7135 			reg_arg_name(env, size_argno));
7136 		err = -EACCES;
7137 		goto size_error;
7138 	}
7139 
7140 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
7141 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
7142 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
7143 		err = -EACCES;
7144 		goto size_error;
7145 	}
7146 
7147 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
7148 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7149 			reg_arg_name(env, size_argno));
7150 		err = -EACCES;
7151 		goto size_error;
7152 	}
7153 
7154 	if (access_type & BPF_READ)
7155 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
7156 					      BPF_READ, zero_size_allowed, meta, NULL);
7157 	if (!err && access_type & BPF_WRITE)
7158 		err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
7159 					      BPF_WRITE, zero_size_allowed, meta, NULL);
7160 	if (err && failure)
7161 		*failure = BPF_MEM_SIZE_FAIL_MEMORY;
7162 
7163 	if (!err)
7164 		err = mark_arg_precision(env, size_argno);
7165 
7166 	return err;
7167 
7168 size_error:
7169 	if (failure)
7170 		*failure = BPF_MEM_SIZE_FAIL_SIZE;
7171 	return err;
7172 }
7173 
7174 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7175 			 argno_t argno, u32 mem_size, enum bpf_access_type access_type,
7176 			 struct bpf_call_arg_meta *meta, bool *known_memory)
7177 {
7178 	int size, err = 0;
7179 
7180 	if (bpf_register_is_null(reg))
7181 		return mark_arg_precision(env, argno);
7182 	if (known_memory)
7183 		*known_memory = true;
7184 
7185 	if (mem_size > S32_MAX) {
7186 		verbose(env, "%s memory size %u is too large\n",
7187 			reg_arg_name(env, argno), mem_size);
7188 		return -EACCES;
7189 	}
7190 
7191 	/*
7192 	 * Only a global subprog (meta == NULL) may read poisoned stack slots:
7193 	 * its static stack liveness proved the callee body skips them.
7194 	 */
7195 	size = (!meta && base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size;
7196 
7197 	if (access_type & BPF_READ)
7198 		err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta,
7199 					      known_memory);
7200 	if (!err && (access_type & BPF_WRITE))
7201 		err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta,
7202 					      known_memory);
7203 
7204 	return err;
7205 }
7206 
7207 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7208 					argno_t argno, struct ret_mem_desc *ret_mem)
7209 {
7210 	int regno = reg_from_argno(argno);
7211 	int err;
7212 
7213 	if (ret_mem->found) {
7214 		verifier_bug(env, "only one allocation size argument permitted");
7215 		return -EFAULT;
7216 	}
7217 
7218 	if (!tnum_is_const(reg->var_off)) {
7219 		verbose(env, "%s is not a const\n", reg_arg_name(env, argno));
7220 		return -EINVAL;
7221 	}
7222 
7223 	if (reg->var_off.value > U32_MAX) {
7224 		verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno));
7225 		return -EINVAL;
7226 	}
7227 
7228 	if (regno >= 0)
7229 		err = mark_chain_precision(env, regno);
7230 	else
7231 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
7232 	if (err)
7233 		return err;
7234 
7235 	ret_mem->size = reg->var_off.value;
7236 	ret_mem->found = true;
7237 
7238 	return 0;
7239 }
7240 
7241 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7242 			     argno_t argno, struct bpf_call_arg_meta *meta)
7243 {
7244 	int regno = reg_from_argno(argno);
7245 	int err;
7246 
7247 	if (meta->arg_constant.found) {
7248 		verifier_bug(env, "only one constant argument permitted");
7249 		return -EFAULT;
7250 	}
7251 
7252 	if (!tnum_is_const(reg->var_off)) {
7253 		verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno));
7254 		return -EINVAL;
7255 	}
7256 
7257 	if (regno >= 0)
7258 		err = mark_chain_precision(env, regno);
7259 	else
7260 		err = mark_stack_arg_precision(env, arg_idx_from_argno(argno));
7261 	if (err < 0)
7262 		return err;
7263 
7264 	meta->arg_constant.found = true;
7265 	meta->arg_constant.value = reg->var_off.value;
7266 
7267 	return 0;
7268 }
7269 
7270 enum {
7271 	PROCESS_SPIN_LOCK = (1 << 0),
7272 	PROCESS_RES_LOCK  = (1 << 1),
7273 	PROCESS_LOCK_IRQ  = (1 << 2),
7274 };
7275 
7276 /* Implementation details:
7277  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7278  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7279  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7280  * Two separate bpf_obj_new will also have different reg->id.
7281  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7282  * clears reg->id after value_or_null->value transition, since the verifier only
7283  * cares about the range of access to valid map value pointer and doesn't care
7284  * about actual address of the map element.
7285  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7286  * reg->id > 0 after value_or_null->value transition. By doing so
7287  * two bpf_map_lookups will be considered two different pointers that
7288  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7289  * returned from bpf_obj_new.
7290  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7291  * dead-locks.
7292  * Since only one bpf_spin_lock is allowed the checks are simpler than
7293  * reg_is_refcounted() logic. The verifier needs to remember only
7294  * one spin_lock instead of array of acquired_refs.
7295  * env->cur_state->active_locks remembers which map value element or allocated
7296  * object got locked and clears it after bpf_spin_unlock.
7297  */
7298 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
7299 {
7300 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
7301 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
7302 	struct bpf_verifier_state *cur = env->cur_state;
7303 	struct bpf_reference_state *lock;
7304 	bool is_const = tnum_is_const(reg->var_off);
7305 	bool is_irq = flags & PROCESS_LOCK_IRQ;
7306 	u64 val = reg->var_off.value;
7307 	struct bpf_map *map = NULL;
7308 	struct btf *btf = NULL;
7309 	struct btf_record *rec;
7310 	u32 spin_lock_off;
7311 	int err;
7312 
7313 	if (!is_const) {
7314 		verbose(env,
7315 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
7316 			reg_arg_name(env, argno), lock_str);
7317 		return -EINVAL;
7318 	}
7319 	if (reg->type == PTR_TO_MAP_VALUE) {
7320 		map = reg->map_ptr;
7321 		if (!map->btf) {
7322 			verbose(env,
7323 				"map '%s' has to have BTF in order to use %s_lock\n",
7324 				map->name, lock_str);
7325 			return -EINVAL;
7326 		}
7327 	} else {
7328 		btf = reg->btf;
7329 	}
7330 
7331 	rec = reg_btf_record(reg);
7332 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
7333 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
7334 			map ? map->name : "kptr", lock_str);
7335 		return -EINVAL;
7336 	}
7337 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
7338 	if (spin_lock_off != val) {
7339 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
7340 			val, lock_str, spin_lock_off);
7341 		return -EINVAL;
7342 	}
7343 	if (is_lock) {
7344 		void *ptr;
7345 		int type;
7346 
7347 		if (map)
7348 			ptr = map;
7349 		else
7350 			ptr = btf;
7351 
7352 		if (!is_res_lock && cur->active_locks) {
7353 			lock = find_lock_state(cur, REF_TYPE_LOCK, 0, NULL);
7354 			if (lock) {
7355 				verbose(env,
7356 					"Locking two bpf_spin_locks are not allowed\n");
7357 				bpf_diag_lock(
7358 					env, env->insn_idx, "nested spin lock",
7359 					"This path already holds a bpf_spin_lock. The verifier allows only one regular BPF spin lock at a time.",
7360 					"Unlock the current bpf_spin_lock before taking another one.", lock);
7361 				return -EINVAL;
7362 			}
7363 		} else if (is_res_lock && cur->active_locks) {
7364 			lock = find_lock_state(cur, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
7365 					       reg->id, ptr);
7366 			if (lock) {
7367 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
7368 				bpf_diag_lock(
7369 					env, env->insn_idx, "recursive resource spin lock",
7370 					"This path already holds the same resource spin lock. Taking it again would deadlock.",
7371 					"Avoid reacquiring the same resource spin lock before it is unlocked.", lock);
7372 				return -EINVAL;
7373 			}
7374 		}
7375 
7376 		if (is_res_lock && is_irq)
7377 			type = REF_TYPE_RES_LOCK_IRQ;
7378 		else if (is_res_lock)
7379 			type = REF_TYPE_RES_LOCK;
7380 		else
7381 			type = REF_TYPE_LOCK;
7382 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
7383 		if (err < 0) {
7384 			verbose(env, "Failed to acquire lock state\n");
7385 			return err;
7386 		}
7387 	} else {
7388 		void *ptr;
7389 		int type;
7390 
7391 		if (map)
7392 			ptr = map;
7393 		else
7394 			ptr = btf;
7395 
7396 		if (!cur->active_locks) {
7397 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
7398 			bpf_diag_res(
7399 				env, env->insn_idx, "unlock without lock",
7400 				"This unlock operation has no matching active lock on the current path.",
7401 				"Take the matching lock before this unlock, or remove the unmatched unlock path.");
7402 			return -EINVAL;
7403 		}
7404 
7405 		if (is_res_lock && is_irq)
7406 			type = REF_TYPE_RES_LOCK_IRQ;
7407 		else if (is_res_lock)
7408 			type = REF_TYPE_RES_LOCK;
7409 		else
7410 			type = REF_TYPE_LOCK;
7411 
7412 		lock = find_lock_state(cur, type, reg->id, ptr);
7413 		if (!lock) {
7414 			verbose(env, "%s_unlock of different lock\n", lock_str);
7415 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
7416 					       cur->active_lock_ptr);
7417 			bpf_diag_lock(
7418 				env, env->insn_idx, "unlock of a different lock",
7419 				"This unlock does not match any active lock with the same tracked identity on the current path.",
7420 				"Unlock the same lock object that was most recently acquired.", lock);
7421 			return -EINVAL;
7422 		}
7423 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
7424 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
7425 			lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id,
7426 					       cur->active_lock_ptr);
7427 			bpf_diag_lock(
7428 				env, env->insn_idx, "unlock out of order",
7429 				"Locks must be released in last-in, first-out order, but this unlock does not match the currently active lock.",
7430 				"Release nested locks in the reverse order they were acquired.", lock);
7431 			return -EINVAL;
7432 		}
7433 		if (release_lock_state(env, type, reg->id, ptr)) {
7434 			verbose(env, "%s_unlock of different lock\n", lock_str);
7435 			bpf_diag_lock(
7436 				env, env->insn_idx, "unlock of a different lock",
7437 				"The verifier could not release a lock state matching this unlock operation.",
7438 				"Pass the same lock object and lock kind that were used for the matching lock operation.",
7439 				lock);
7440 			return -EINVAL;
7441 		}
7442 		/*
7443 		 * Invalidate non-owning refs before RCU demotion clears their
7444 		 * NON_OWN_REF flag.
7445 		 */
7446 		invalidate_non_owning_refs(env);
7447 
7448 		if (!in_rcu_cs(env))
7449 			invalidate_rcu_protected_refs(env);
7450 	}
7451 	return 0;
7452 }
7453 
7454 /* Check if @regno is a pointer to a specific field in a map value */
7455 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7456 				   enum btf_field_type field_type,
7457 				   struct bpf_map_desc *map_desc)
7458 {
7459 	bool is_const = tnum_is_const(reg->var_off);
7460 	struct bpf_map *map = reg->map_ptr;
7461 	u64 val = reg->var_off.value;
7462 	const char *struct_name = btf_field_type_name(field_type);
7463 	int field_off = -1;
7464 
7465 	if (!is_const) {
7466 		verbose(env,
7467 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
7468 			reg_arg_name(env, argno), struct_name);
7469 		return -EINVAL;
7470 	}
7471 	if (!map->btf) {
7472 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
7473 			struct_name);
7474 		return -EINVAL;
7475 	}
7476 	if (!btf_record_has_field(map->record, field_type)) {
7477 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
7478 		return -EINVAL;
7479 	}
7480 	switch (field_type) {
7481 	case BPF_TIMER:
7482 		field_off = map->record->timer_off;
7483 		break;
7484 	case BPF_TASK_WORK:
7485 		field_off = map->record->task_work_off;
7486 		break;
7487 	case BPF_WORKQUEUE:
7488 		field_off = map->record->wq_off;
7489 		break;
7490 	default:
7491 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
7492 		return -EINVAL;
7493 	}
7494 	if (field_off != val) {
7495 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
7496 			val, struct_name, field_off);
7497 		return -EINVAL;
7498 	}
7499 	if (map_desc->ptr) {
7500 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
7501 		return -EFAULT;
7502 	}
7503 	map_desc->uid = reg->map_uid;
7504 	map_desc->ptr = map;
7505 	return 0;
7506 }
7507 
7508 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7509 			      struct bpf_map_desc *map)
7510 {
7511 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
7512 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
7513 		return -EOPNOTSUPP;
7514 	}
7515 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
7516 }
7517 
7518 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7519 			     struct bpf_call_arg_meta *meta)
7520 {
7521 	struct bpf_reg_state *reg = reg_state(env, regno);
7522 	struct btf_field *kptr_field;
7523 	struct bpf_map *map_ptr;
7524 	struct btf_record *rec;
7525 	u32 kptr_off;
7526 
7527 	if (type_is_ptr_alloc_obj(reg->type)) {
7528 		rec = reg_btf_record(reg);
7529 	} else { /* PTR_TO_MAP_VALUE */
7530 		map_ptr = reg->map_ptr;
7531 		if (!map_ptr->btf) {
7532 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7533 				map_ptr->name);
7534 			return -EINVAL;
7535 		}
7536 		rec = map_ptr->record;
7537 		meta->map.ptr = map_ptr;
7538 	}
7539 
7540 	if (!tnum_is_const(reg->var_off)) {
7541 		verbose(env,
7542 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7543 			regno);
7544 		return -EINVAL;
7545 	}
7546 
7547 	if (!btf_record_has_field(rec, BPF_KPTR)) {
7548 		verbose(env, "R%d has no valid kptr\n", regno);
7549 		return -EINVAL;
7550 	}
7551 
7552 	kptr_off = reg->var_off.value;
7553 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
7554 	if (!kptr_field) {
7555 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7556 		return -EACCES;
7557 	}
7558 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7559 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7560 		return -EACCES;
7561 	}
7562 	meta->kptr_field = kptr_field;
7563 	return 0;
7564 }
7565 
7566 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
7567 			      const char *call_name, const char *reason, const char *suggestion);
7568 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
7569 						 argno_t argno, const char *call_name,
7570 						 const char *suggestion, const char *fmt, ...);
7571 
7572 /*
7573  * Validate dynptr arguments for helper, kfunc and subprog.
7574  *
7575  * @dynptr is both input and output. It is populated when the argument is
7576  * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed)
7577  * and consumed when the argument is expecting to be an initialized dynptr.
7578  * @parent_id is used to track the referenced parent object (e.g., file or skb in
7579  * qdisc program) when constructing a dynptr.
7580  *
7581  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7582  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7583  *
7584  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7585  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7586  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7587  *
7588  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
7589  * dynptr points to. At the first level, the verifier will make sure a
7590  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
7591  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
7592  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
7593  * and checked dynamically during runtime.
7594  */
7595 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7596 			       argno_t argno, int insn_idx, const char *call_name,
7597 			       enum bpf_arg_type arg_type,
7598 			       struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
7599 {
7600 	int spi, err = 0;
7601 
7602 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7603 		verbose(env,
7604 			"%s expected pointer to stack or const struct bpf_dynptr\n",
7605 			reg_arg_name(env, argno));
7606 		bpf_diag_call_arg_fmt(
7607 			env, insn_idx, argno, call_name,
7608 			"Pass the address of a stack dynptr object, or use a const dynptr pointer returned by the verifier-supported path.",
7609 			"a dynptr argument must be a pointer to a dynptr stack slot or a verifier-provided const struct bpf_dynptr, but %s is %s",
7610 			reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type));
7611 		return -EINVAL;
7612 	}
7613 
7614 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7615 	 *		 constructing a mutable bpf_dynptr object.
7616 	 *
7617 	 *		 Currently, this is only possible with PTR_TO_STACK
7618 	 *		 pointing to a region of at least 16 bytes which doesn't
7619 	 *		 contain an existing bpf_dynptr.
7620 	 *
7621 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
7622 	 *		  destroyed.
7623 	 *
7624 	 *  None       - Points to a initialized dynptr that cannot be
7625 	 *		 reinitialized or destroyed. However, the view of the
7626 	 *		 dynptr and the memory it points to may be mutated.
7627 	 */
7628 	if (arg_type & MEM_UNINIT) {
7629 		int i;
7630 
7631 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7632 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7633 			bpf_diag_res(
7634 				env, insn_idx, "dynptr is already initialized",
7635 				"This kfunc constructs a dynptr and requires an uninitialized dynptr stack slot, but the selected slot already holds dynptr state.",
7636 				"Use a fresh stack dynptr slot, or release/destroy the existing dynptr before reusing the slot.");
7637 			return -EINVAL;
7638 		}
7639 
7640 		/* we write BPF_DW bits (8 bytes) at a time */
7641 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7642 			err = check_mem_access(env, insn_idx, reg, argno,
7643 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7644 			if (err)
7645 				return err;
7646 		}
7647 
7648 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr);
7649 	} else /* OBJ_RELEASE and None case from above */ {
7650 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7651 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
7652 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
7653 			bpf_diag_res(
7654 				env, insn_idx, "const dynptr release",
7655 				"This release operation was given a const dynptr. Const dynptr values are verifier-provided views and cannot be released by the program.",
7656 				"Release only mutable dynptrs that the program initialized or reserved.");
7657 			return -EINVAL;
7658 		}
7659 
7660 		if (!is_dynptr_reg_valid_init(env, reg)) {
7661 			verbose(env, "Expected an initialized dynptr as %s\n",
7662 				reg_arg_name(env, argno));
7663 			bpf_diag_res(
7664 				env, insn_idx, "uninitialized dynptr use",
7665 				"This operation requires an initialized dynptr, but the stack slot does not currently hold a valid dynptr on this path.",
7666 				"Initialize the dynptr on every path before this call, and avoid overwriting or releasing it before this use.");
7667 			return -EINVAL;
7668 		}
7669 
7670 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
7671 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
7672 			enum bpf_dynptr_type expected_type = arg_to_dynptr_type(arg_type);
7673 			enum bpf_dynptr_type actual_type = dynptr_reg_type(env, reg);
7674 
7675 			verbose(env, "Expected a dynptr of type %s as %s\n",
7676 				dynptr_type_str(expected_type), reg_arg_name(env, argno));
7677 			bpf_diag_call_arg_fmt(
7678 				env, insn_idx, argno, call_name,
7679 				"Use a dynptr constructor that matches this operation, or call an operation that accepts the dynptr's current type.",
7680 				"the dynptr is initialized with backing object type %s, but this operation expects dynptr type %s",
7681 				dynptr_type_str(actual_type), dynptr_type_str(expected_type));
7682 			return -EINVAL;
7683 		}
7684 
7685 		if (reg->type != CONST_PTR_TO_DYNPTR) {
7686 			struct bpf_func_state *state = bpf_func(env, reg);
7687 
7688 			spi = dynptr_get_spi(env, reg);
7689 			if (spi < 0)
7690 				return spi;
7691 
7692 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
7693 
7694 			reg = &state->stack[spi].spilled_ptr;
7695 		}
7696 
7697 		if (dynptr) {
7698 			dynptr->type = reg->dynptr.type;
7699 			dynptr->id = reg->id;
7700 			dynptr->parent_id = reg->parent_id;
7701 		}
7702 	}
7703 	return err;
7704 }
7705 
7706 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta)
7707 {
7708 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7709 }
7710 
7711 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta)
7712 {
7713 	return meta->kfunc_flags & KF_ITER_NEW;
7714 }
7715 
7716 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta)
7717 {
7718 	return meta->kfunc_flags & KF_ITER_DESTROY;
7719 }
7720 
7721 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx,
7722 			      const struct btf_param *arg)
7723 {
7724 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7725 	 * kfunc is iter state pointer
7726 	 */
7727 	if (is_iter_kfunc(meta))
7728 		return arg_idx == 0;
7729 
7730 	/* iter passed as an argument to a generic kfunc */
7731 	return btf_param_match_suffix(meta->btf, arg, "__iter");
7732 }
7733 
7734 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx,
7735 			    struct bpf_call_arg_meta *meta)
7736 {
7737 	struct bpf_func_state *state = bpf_func(env, reg);
7738 	const struct btf_type *t;
7739 	u32 arg_idx = arg_idx_from_argno(argno);
7740 	int spi, err, i, nr_slots, btf_id;
7741 
7742 	if (reg->type != PTR_TO_STACK) {
7743 		verbose(env, "%s expected pointer to an iterator on stack\n",
7744 			reg_arg_name(env, argno));
7745 		bpf_diag_call_arg_fmt(
7746 			env, insn_idx, argno, meta->func_name,
7747 			"Pass the address of a stack iterator object for iterator new, next, and destroy calls.",
7748 			"iterator state must live in verifier-tracked stack memory, but %s is %s",
7749 			reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type));
7750 		return -EINVAL;
7751 	}
7752 
7753 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
7754 	 * ensures struct convention, so we wouldn't need to do any BTF
7755 	 * validation here. But given iter state can be passed as a parameter
7756 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
7757 	 * conservative here.
7758 	 */
7759 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx);
7760 	if (btf_id < 0) {
7761 		verbose(env, "expected valid iter pointer as %s\n",
7762 			reg_arg_name(env, argno));
7763 		bpf_diag_call_arg(
7764 			env, insn_idx, argno, meta->func_name,
7765 			"the kfunc expects a recognized iterator state pointer, but this argument does not match a valid iterator type",
7766 			"Pass the exact iterator state type expected by this kfunc.");
7767 		return -EINVAL;
7768 	}
7769 	t = btf_type_by_id(meta->btf, btf_id);
7770 	nr_slots = t->size / BPF_REG_SIZE;
7771 
7772 	if (is_iter_new_kfunc(meta)) {
7773 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7774 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7775 			verbose(env, "expected uninitialized iter_%s as %s\n",
7776 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7777 			bpf_diag_res(
7778 				env, insn_idx, "iterator is already initialized",
7779 				"Iterator creation requires an uninitialized iterator stack object, but this stack range already contains iterator state.",
7780 				"Use a fresh iterator stack slot, or destroy the existing iterator before reusing the slot.");
7781 			return -EINVAL;
7782 		}
7783 
7784 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7785 			err = check_mem_access(env, insn_idx, reg, argno,
7786 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7787 			if (err)
7788 				return err;
7789 		}
7790 
7791 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7792 		if (err)
7793 			return err;
7794 	} else {
7795 		/* iter_next() or iter_destroy(), as well as any kfunc
7796 		 * accepting iter argument, expect initialized iter state
7797 		 */
7798 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7799 		switch (err) {
7800 		case 0:
7801 			break;
7802 		case -EINVAL:
7803 			verbose(env, "expected an initialized iter_%s as %s\n",
7804 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7805 			bpf_diag_res(
7806 				env, insn_idx, "uninitialized iterator use",
7807 				"This iterator operation requires an initialized iterator state object, but the stack range does not contain a live iterator on this path.",
7808 				"Call the matching iterator new kfunc on every path before calling next or destroy, and do not destroy the iterator before this use.");
7809 			return err;
7810 		case -EPROTO:
7811 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7812 			bpf_diag_ctx_required(
7813 				env, insn_idx, meta->func_name, BPF_DIAG_CONTEXT_RCU,
7814 				"Wrap iterator use in bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
7815 			return err;
7816 		default:
7817 			return err;
7818 		}
7819 
7820 		spi = iter_get_spi(env, reg, nr_slots);
7821 		if (spi < 0)
7822 			return spi;
7823 
7824 		mark_stack_slots_scratched(env, spi, nr_slots);
7825 
7826 		/* remember meta->iter info for process_iter_next_call() */
7827 		meta->iter.spi = spi;
7828 		meta->iter.frameno = reg->frameno;
7829 		update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr);
7830 
7831 		if (is_iter_destroy_kfunc(meta)) {
7832 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7833 			if (err)
7834 				return err;
7835 		}
7836 	}
7837 
7838 	return 0;
7839 }
7840 
7841 /* Look for a previous loop entry at insn_idx: nearest parent state
7842  * stopped at insn_idx with callsites matching those in cur->frame.
7843  */
7844 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7845 						  struct bpf_verifier_state *cur,
7846 						  int insn_idx)
7847 {
7848 	struct bpf_verifier_state_list *sl;
7849 	struct bpf_verifier_state *st;
7850 	struct list_head *pos, *head;
7851 
7852 	/* Explored states are pushed in stack order, most recent states come first */
7853 	head = bpf_explored_state(env, insn_idx);
7854 	list_for_each(pos, head) {
7855 		sl = container_of(pos, struct bpf_verifier_state_list, node);
7856 		/* If st->branches != 0 state is a part of current DFS verification path,
7857 		 * hence cur & st for a loop.
7858 		 */
7859 		st = &sl->state;
7860 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7861 		    st->dfs_depth < cur->dfs_depth)
7862 			return st;
7863 	}
7864 
7865 	return NULL;
7866 }
7867 
7868 /*
7869  * Check if scalar registers are exact for the purpose of not widening.
7870  * More lenient than regs_exact()
7871  */
7872 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
7873 				    const struct bpf_reg_state *rcur)
7874 {
7875 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
7876 }
7877 
7878 static void maybe_widen_reg(struct bpf_verifier_env *env,
7879 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
7880 {
7881 	if (rold->type != SCALAR_VALUE)
7882 		return;
7883 	if (rold->type != rcur->type)
7884 		return;
7885 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
7886 		return;
7887 	__mark_reg_unknown(env, rcur);
7888 }
7889 
7890 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7891 				   struct bpf_verifier_state *old,
7892 				   struct bpf_verifier_state *cur)
7893 {
7894 	struct bpf_func_state *fold, *fcur;
7895 	int i, fr, num_slots;
7896 
7897 	for (fr = old->curframe; fr >= 0; fr--) {
7898 		fold = old->frame[fr];
7899 		fcur = cur->frame[fr];
7900 
7901 		for (i = 0; i < MAX_BPF_REG; i++)
7902 			maybe_widen_reg(env,
7903 					&fold->regs[i],
7904 					&fcur->regs[i]);
7905 
7906 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
7907 				fcur->allocated_stack / BPF_REG_SIZE);
7908 		for (i = 0; i < num_slots; i++) {
7909 			if (!bpf_is_spilled_reg(&fold->stack[i]) ||
7910 			    !bpf_is_spilled_reg(&fcur->stack[i]))
7911 				continue;
7912 
7913 			maybe_widen_reg(env,
7914 					&fold->stack[i].spilled_ptr,
7915 					&fcur->stack[i].spilled_ptr);
7916 		}
7917 	}
7918 	return 0;
7919 }
7920 
7921 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7922 						 struct bpf_call_arg_meta *meta)
7923 {
7924 	int iter_frameno = meta->iter.frameno;
7925 	int iter_spi = meta->iter.spi;
7926 
7927 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7928 }
7929 
7930 /* process_iter_next_call() is called when verifier gets to iterator's next
7931  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7932  * to it as just "iter_next()" in comments below.
7933  *
7934  * BPF verifier relies on a crucial contract for any iter_next()
7935  * implementation: it should *eventually* return NULL, and once that happens
7936  * it should keep returning NULL. That is, once iterator exhausts elements to
7937  * iterate, it should never reset or spuriously return new elements.
7938  *
7939  * With the assumption of such contract, process_iter_next_call() simulates
7940  * a fork in the verifier state to validate loop logic correctness and safety
7941  * without having to simulate infinite amount of iterations.
7942  *
7943  * In current state, we first assume that iter_next() returned NULL and
7944  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7945  * conditions we should not form an infinite loop and should eventually reach
7946  * exit.
7947  *
7948  * Besides that, we also fork current state and enqueue it for later
7949  * verification. In a forked state we keep iterator state as ACTIVE
7950  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7951  * also bump iteration depth to prevent erroneous infinite loop detection
7952  * later on (see iter_active_depths_differ() comment for details). In this
7953  * state we assume that we'll eventually loop back to another iter_next()
7954  * calls (it could be in exactly same location or in some other instruction,
7955  * it doesn't matter, we don't make any unnecessary assumptions about this,
7956  * everything revolves around iterator state in a stack slot, not which
7957  * instruction is calling iter_next()). When that happens, we either will come
7958  * to iter_next() with equivalent state and can conclude that next iteration
7959  * will proceed in exactly the same way as we just verified, so it's safe to
7960  * assume that loop converges. If not, we'll go on another iteration
7961  * simulation with a different input state, until all possible starting states
7962  * are validated or we reach maximum number of instructions limit.
7963  *
7964  * This way, we will either exhaustively discover all possible input states
7965  * that iterator loop can start with and eventually will converge, or we'll
7966  * effectively regress into bounded loop simulation logic and either reach
7967  * maximum number of instructions if loop is not provably convergent, or there
7968  * is some statically known limit on number of iterations (e.g., if there is
7969  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7970  *
7971  * Iteration convergence logic in is_state_visited() relies on exact
7972  * states comparison, which ignores read and precision marks.
7973  * This is necessary because read and precision marks are not finalized
7974  * while in the loop. Exact comparison might preclude convergence for
7975  * simple programs like below:
7976  *
7977  *     i = 0;
7978  *     while(iter_next(&it))
7979  *       i++;
7980  *
7981  * At each iteration step i++ would produce a new distinct state and
7982  * eventually instruction processing limit would be reached.
7983  *
7984  * To avoid such behavior speculatively forget (widen) range for
7985  * imprecise scalar registers, if those registers were not precise at the
7986  * end of the previous iteration and do not match exactly.
7987  *
7988  * This is a conservative heuristic that allows to verify wide range of programs,
7989  * however it precludes verification of programs that conjure an
7990  * imprecise value on the first loop iteration and use it as precise on a second.
7991  * For example, the following safe program would fail to verify:
7992  *
7993  *     struct bpf_num_iter it;
7994  *     int arr[10];
7995  *     int i = 0, a = 0;
7996  *     bpf_iter_num_new(&it, 0, 10);
7997  *     while (bpf_iter_num_next(&it)) {
7998  *       if (a == 0) {
7999  *         a = 1;
8000  *         i = 7; // Because i changed verifier would forget
8001  *                // it's range on second loop entry.
8002  *       } else {
8003  *         arr[i] = 42; // This would fail to verify.
8004  *       }
8005  *     }
8006  *     bpf_iter_num_destroy(&it);
8007  */
8008 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8009 				  struct bpf_call_arg_meta *meta)
8010 {
8011 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8012 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8013 	struct bpf_reg_state *cur_iter, *queued_iter;
8014 
8015 	BTF_TYPE_EMIT(struct bpf_iter);
8016 
8017 	cur_iter = get_iter_from_state(cur_st, meta);
8018 
8019 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8020 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8021 		verifier_bug(env, "unexpected iterator state %d (%s)",
8022 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8023 		return -EFAULT;
8024 	}
8025 
8026 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8027 		/* Because iter_next() call is a checkpoint is_state_visitied()
8028 		 * should guarantee parent state with same call sites and insn_idx.
8029 		 */
8030 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8031 		    !same_callsites(cur_st->parent, cur_st)) {
8032 			verifier_bug(env, "bad parent state for iter next call");
8033 			return -EFAULT;
8034 		}
8035 		/* Note cur_st->parent in the call below, it is necessary to skip
8036 		 * checkpoint created for cur_st by is_state_visited()
8037 		 * right at this instruction.
8038 		 */
8039 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8040 		/* branch out active iter state */
8041 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8042 		if (IS_ERR(queued_st))
8043 			return PTR_ERR(queued_st);
8044 
8045 		queued_iter = get_iter_from_state(queued_st, meta);
8046 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8047 		queued_iter->iter.depth++;
8048 		if (prev_st)
8049 			widen_imprecise_scalars(env, prev_st, queued_st);
8050 
8051 		queued_fr = queued_st->frame[queued_st->curframe];
8052 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8053 	}
8054 
8055 	/* switch to DRAINED state, but keep the depth unchanged */
8056 	/* mark current iter state as drained and assume returned NULL */
8057 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8058 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8059 
8060 	return 0;
8061 }
8062 
8063 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8064 {
8065 	return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO;
8066 }
8067 
8068 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8069 {
8070 	/*
8071 	 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw
8072 	 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be
8073 	 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized().
8074 	 */
8075 	return (base_type(type) == ARG_PTR_TO_MEM ||
8076 		base_type(type) == ARG_PTR_TO_MAP_VALUE) &&
8077 	       type & MEM_UNINIT;
8078 }
8079 
8080 static bool arg_type_is_release(enum bpf_arg_type type)
8081 {
8082 	return type & OBJ_RELEASE;
8083 }
8084 
8085 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8086 {
8087 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8088 }
8089 
8090 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8091 				 const struct bpf_call_arg_meta *meta,
8092 				 enum bpf_arg_type *arg_type)
8093 {
8094 	if (!meta->map.ptr) {
8095 		/* kernel subsystem misconfigured verifier */
8096 		verifier_bug(env, "invalid map_ptr to access map->type");
8097 		return -EFAULT;
8098 	}
8099 
8100 	switch (meta->map.ptr->map_type) {
8101 	case BPF_MAP_TYPE_SOCKMAP:
8102 	case BPF_MAP_TYPE_SOCKHASH:
8103 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8104 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8105 		} else {
8106 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8107 			return -EINVAL;
8108 		}
8109 		break;
8110 	case BPF_MAP_TYPE_BLOOM_FILTER:
8111 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8112 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8113 		break;
8114 	default:
8115 		break;
8116 	}
8117 	return 0;
8118 }
8119 
8120 struct bpf_reg_types {
8121 	const enum bpf_reg_type types[10];
8122 	u32 *btf_id;
8123 };
8124 
8125 static const struct bpf_reg_types sock_types = {
8126 	.types = {
8127 		PTR_TO_SOCK_COMMON,
8128 		PTR_TO_SOCKET,
8129 		PTR_TO_TCP_SOCK,
8130 		PTR_TO_XDP_SOCK,
8131 	},
8132 };
8133 
8134 #ifdef CONFIG_NET
8135 static const struct bpf_reg_types btf_id_sock_common_types = {
8136 	.types = {
8137 		PTR_TO_SOCK_COMMON,
8138 		PTR_TO_SOCKET,
8139 		PTR_TO_TCP_SOCK,
8140 		PTR_TO_XDP_SOCK,
8141 		PTR_TO_BTF_ID,
8142 		PTR_TO_BTF_ID | PTR_TRUSTED,
8143 	},
8144 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8145 };
8146 #endif
8147 
8148 static const struct bpf_reg_types mem_types = {
8149 	.types = {
8150 		PTR_TO_STACK,
8151 		PTR_TO_PACKET,
8152 		PTR_TO_PACKET_META,
8153 		PTR_TO_MAP_KEY,
8154 		PTR_TO_MAP_VALUE,
8155 		PTR_TO_MEM,
8156 		PTR_TO_MEM | MEM_RINGBUF,
8157 		PTR_TO_BUF,
8158 		PTR_TO_BTF_ID | PTR_TRUSTED,
8159 		PTR_TO_CTX,
8160 	},
8161 };
8162 
8163 static const struct bpf_reg_types spin_lock_types = {
8164 	.types = {
8165 		PTR_TO_MAP_VALUE,
8166 		PTR_TO_BTF_ID | MEM_ALLOC,
8167 	}
8168 };
8169 
8170 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8171 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8172 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8173 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8174 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8175 static const struct bpf_reg_types btf_ptr_types = {
8176 	.types = {
8177 		PTR_TO_BTF_ID,
8178 		PTR_TO_BTF_ID | PTR_TRUSTED,
8179 		PTR_TO_BTF_ID | MEM_RCU,
8180 	},
8181 };
8182 static const struct bpf_reg_types percpu_btf_ptr_types = {
8183 	.types = {
8184 		PTR_TO_BTF_ID | MEM_PERCPU,
8185 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8186 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8187 	}
8188 };
8189 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8190 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8191 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8192 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8193 static const struct bpf_reg_types kptr_xchg_dest_types = {
8194 	.types = {
8195 		PTR_TO_MAP_VALUE,
8196 		PTR_TO_BTF_ID | MEM_ALLOC,
8197 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
8198 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
8199 	}
8200 };
8201 static const struct bpf_reg_types dynptr_types = {
8202 	.types = {
8203 		PTR_TO_STACK,
8204 		CONST_PTR_TO_DYNPTR,
8205 	}
8206 };
8207 
8208 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8209 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8210 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8211 	[ARG_MEM_SIZE]			= &scalar_types,
8212 	[ARG_MEM_SIZE_OR_ZERO]		= &scalar_types,
8213 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8214 	[ARG_SCALAR]			= &scalar_types,
8215 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8216 	[ARG_PTR_TO_CTX]		= &context_types,
8217 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8218 #ifdef CONFIG_NET
8219 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8220 #endif
8221 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8222 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8223 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8224 	[ARG_PTR_TO_MEM]		= &mem_types,
8225 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8226 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8227 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8228 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8229 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8230 	[ARG_PTR_TO_TIMER]		= &timer_types,
8231 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
8232 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8233 };
8234 
8235 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno,
8236 			      const char *call_name, const char *reason,
8237 			      const char *suggestion)
8238 {
8239 	int arg = arg_from_argno(argno);
8240 	int regno = reg_from_argno(argno);
8241 	int stack_slot = -1;
8242 
8243 	if (arg < 0 && regno >= BPF_REG_1 && regno <= BPF_REG_5)
8244 		arg = regno;
8245 	if (arg > MAX_BPF_FUNC_REG_ARGS)
8246 		stack_slot = arg - MAX_BPF_FUNC_REG_ARGS - 1;
8247 
8248 	bpf_diag_call_type(env, insn_idx, arg, regno, stack_slot,
8249 			   call_name && *call_name ? call_name : "call",
8250 			   reg_arg_name(env, argno), reason, suggestion);
8251 }
8252 
8253 static const char *bpf_diag_arg_name(struct bpf_verifier_env *env, argno_t argno)
8254 {
8255 	return bpf_diag_fmt(env, "%s", reg_arg_name(env, argno));
8256 }
8257 
8258 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,
8259 						 argno_t argno, const char *call_name,
8260 						 const char *suggestion, const char *fmt, ...)
8261 {
8262 	const char *reason;
8263 	va_list args;
8264 
8265 	va_start(args, fmt);
8266 	reason = bpf_diag_vfmt(env, fmt, args);
8267 	va_end(args);
8268 
8269 	bpf_diag_call_arg(env, insn_idx, argno, call_name, reason, suggestion);
8270 }
8271 
8272 static const char *bpf_diag_expected_reg_types(struct bpf_verifier_env *env,
8273 					       const enum bpf_reg_type *types, int count)
8274 {
8275 	size_t len = 0, size = 1;
8276 	char *buf;
8277 	int i;
8278 
8279 	for (i = 0; i < count; i++)
8280 		size += strlen(reg_type_str(env, types[i])) + (i ? 2 : 0);
8281 
8282 	buf = bpf_diag_fmt_buf(env, size);
8283 	if (!buf)
8284 		return "";
8285 
8286 	for (i = 0; i < count; i++)
8287 		len += scnprintf(buf + len, size - len, "%s%s", i ? ", " : "",
8288 				 reg_type_str(env, types[i]));
8289 	return buf;
8290 }
8291 
8292 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
8293 			  enum bpf_arg_type arg_type, const u32 *arg_btf_id,
8294 			  struct bpf_call_arg_meta *meta, const char *call_name)
8295 {
8296 	enum bpf_reg_type expected, type = reg->type;
8297 	const struct bpf_reg_types *compatible;
8298 	const char *actual, *accepted;
8299 	int i, j, err;
8300 
8301 	compatible = compatible_reg_types[base_type(arg_type)];
8302 	if (!compatible) {
8303 		verifier_bug(env, "unsupported arg type %d", arg_type);
8304 		return -EFAULT;
8305 	}
8306 
8307 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8308 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8309 	 *
8310 	 * Same for MAYBE_NULL:
8311 	 *
8312 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8313 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8314 	 *
8315 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8316 	 *
8317 	 * Therefore we fold these flags depending on the arg_type before comparison.
8318 	 */
8319 	if (arg_type & MEM_RDONLY)
8320 		type &= ~MEM_RDONLY;
8321 	if (arg_type & PTR_MAYBE_NULL)
8322 		type &= ~PTR_MAYBE_NULL;
8323 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8324 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8325 
8326 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8327 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) {
8328 		type &= ~MEM_ALLOC;
8329 		type &= ~MEM_PERCPU;
8330 	}
8331 
8332 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8333 		expected = compatible->types[i];
8334 		if (expected == NOT_INIT)
8335 			break;
8336 
8337 		if (type == expected)
8338 			goto found;
8339 	}
8340 
8341 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
8342 	for (j = 0; j + 1 < i; j++)
8343 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8344 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8345 	actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type));
8346 	accepted = bpf_diag_expected_reg_types(env, compatible->types, i);
8347 	bpf_diag_call_arg_fmt(env, env->insn_idx, argno, call_name,
8348 			      "Pass a value with one of the accepted pointer or scalar types for this call.",
8349 			      "it has type %s, but this argument accepts %s",
8350 			      actual, accepted);
8351 	return -EACCES;
8352 
8353 found:
8354 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8355 		return 0;
8356 
8357 	if (compatible == &mem_types) {
8358 		if (!(arg_type & MEM_RDONLY)) {
8359 			verbose(env,
8360 				"%s() may write into memory pointed by %s type=%s\n",
8361 				func_id_name(meta->func_id),
8362 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
8363 			return -EACCES;
8364 		}
8365 		return 0;
8366 	}
8367 
8368 	switch ((int)reg->type) {
8369 	case PTR_TO_BTF_ID:
8370 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8371 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8372 	case PTR_TO_BTF_ID | MEM_RCU:
8373 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8374 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8375 	{
8376 		/* For bpf_sk_release, it needs to match against first member
8377 		 * 'struct sock_common', hence make an exception for it. This
8378 		 * allows bpf_sk_release to work for multiple socket types.
8379 		 */
8380 		bool strict_type_match = arg_type_is_release(arg_type) &&
8381 					 meta->func_id != BPF_FUNC_sk_release;
8382 
8383 		if (type_may_be_null(reg->type) &&
8384 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8385 			verbose(env, "Possibly NULL pointer passed to helper %s\n",
8386 				reg_arg_name(env, argno));
8387 			bpf_diag_call_arg(
8388 				env, env->insn_idx, argno, call_name,
8389 				"the pointer may be NULL, but this call requires a non-NULL pointer",
8390 				"Add a NULL check and make the call only on the non-NULL path.");
8391 			return -EACCES;
8392 		}
8393 
8394 		if (!arg_btf_id) {
8395 			if (!compatible->btf_id) {
8396 				verifier_bug(env, "missing arg compatible BTF ID");
8397 				return -EFAULT;
8398 			}
8399 			arg_btf_id = compatible->btf_id;
8400 		}
8401 
8402 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8403 			if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno)))
8404 				return -EACCES;
8405 		} else {
8406 			if (arg_btf_id == BPF_PTR_POISON) {
8407 				verbose(env, "verifier internal error:");
8408 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
8409 					reg_arg_name(env, argno));
8410 				return -EACCES;
8411 			}
8412 
8413 			err = __check_ptr_off_reg(env, reg, argno, true);
8414 			if (err)
8415 				return err;
8416 
8417 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id,
8418 						  reg->var_off.value, btf_vmlinux, *arg_btf_id,
8419 						  strict_type_match, !type_is_alloc(reg->type))) {
8420 				verbose(env, "%s is of type %s but %s is expected\n",
8421 					reg_arg_name(env, argno),
8422 					btf_type_name(reg->btf, reg->btf_id),
8423 					btf_type_name(btf_vmlinux, *arg_btf_id));
8424 				return -EACCES;
8425 			}
8426 		}
8427 		break;
8428 	}
8429 	case PTR_TO_BTF_ID | MEM_ALLOC:
8430 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8431 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8432 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8433 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8434 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8435 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
8436 			return -EFAULT;
8437 		}
8438 		/* Check if local kptr in src arg matches kptr in dst arg */
8439 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8440 			int regno = reg_from_argno(argno);
8441 
8442 			if (regno == BPF_REG_2 &&
8443 			    map_kptr_match_type(env, meta->kptr_field, reg, regno))
8444 				return -EACCES;
8445 		}
8446 		break;
8447 	case PTR_TO_BTF_ID | MEM_PERCPU:
8448 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8449 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8450 		/* Handled by helper specific checks */
8451 		break;
8452 	default:
8453 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
8454 		return -EFAULT;
8455 	}
8456 	return 0;
8457 }
8458 
8459 static struct btf_field *
8460 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8461 {
8462 	struct btf_field *field;
8463 	struct btf_record *rec;
8464 
8465 	rec = reg_btf_record(reg);
8466 	if (!rec)
8467 		return NULL;
8468 
8469 	field = btf_record_find(rec, off, fields);
8470 	if (!field)
8471 		return NULL;
8472 
8473 	return field;
8474 }
8475 
8476 static int __check_func_arg_reg_off(struct bpf_verifier_env *env,
8477 				    const struct bpf_reg_state *reg, argno_t argno,
8478 				    enum bpf_arg_type arg_type,
8479 				    bool btf_id_fixed_off_ok)
8480 {
8481 	u32 type = reg->type;
8482 
8483 	/* When referenced register is passed to release function, its fixed
8484 	 * offset must be 0.
8485 	 *
8486 	 * We will check arg_type_is_release reg has id when storing
8487 	 * meta->release_regno.
8488 	 */
8489 	if (arg_type_is_release(arg_type)) {
8490 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8491 		 * may not directly point to the object being released, but to
8492 		 * dynptr pointing to such object, which might be at some offset
8493 		 * on the stack. In that case, we simply to fallback to the
8494 		 * default handling.
8495 		 */
8496 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8497 			return 0;
8498 
8499 		/* Doing check_ptr_off_reg check for the offset will catch this
8500 		 * because fixed_off_ok is false, but checking here allows us
8501 		 * to give the user a better error message.
8502 		 */
8503 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
8504 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
8505 				reg_arg_name(env, argno));
8506 			return -EINVAL;
8507 		}
8508 	}
8509 
8510 	switch (type) {
8511 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8512 	case PTR_TO_STACK:
8513 	case PTR_TO_PACKET:
8514 	case PTR_TO_PACKET_META:
8515 	case PTR_TO_MAP_KEY:
8516 	case PTR_TO_MAP_VALUE:
8517 	case PTR_TO_MEM:
8518 	case PTR_TO_MEM | MEM_RDONLY:
8519 	case PTR_TO_MEM | MEM_RINGBUF:
8520 	case PTR_TO_BUF:
8521 	case PTR_TO_BUF | MEM_RDONLY:
8522 	case PTR_TO_ARENA:
8523 	case SCALAR_VALUE:
8524 		return 0;
8525 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8526 	 * fixed offset.
8527 	 */
8528 	case PTR_TO_BTF_ID:
8529 	case PTR_TO_BTF_ID | MEM_ALLOC:
8530 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8531 	case PTR_TO_BTF_ID | MEM_RCU:
8532 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8533 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8534 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8535 		 * its fixed offset must be 0. In the other cases, fixed offset
8536 		 * can be non-zero unless the caller requires otherwise.
8537 		 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still
8538 		 * need to do checks instead of returning.
8539 		 */
8540 		return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok);
8541 	case PTR_TO_CTX:
8542 		/*
8543 		 * Allow fixed and variable offsets for syscall context, but
8544 		 * only when the argument is passed as memory, not ctx,
8545 		 * otherwise we may get modified ctx in tail called programs and
8546 		 * global subprogs (that may act as extension prog hooks).
8547 		 */
8548 		if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
8549 			return 0;
8550 		fallthrough;
8551 	default:
8552 		return __check_ptr_off_reg(env, reg, argno, false);
8553 	}
8554 }
8555 
8556 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8557 				  const struct bpf_reg_state *reg, argno_t argno,
8558 				  enum bpf_arg_type arg_type)
8559 {
8560 	return __check_func_arg_reg_off(env, reg, argno, arg_type, true);
8561 }
8562 
8563 static int check_arg_const_str(struct bpf_verifier_env *env,
8564 			       struct bpf_reg_state *reg, argno_t argno)
8565 {
8566 	struct bpf_map *map = reg->map_ptr;
8567 	int err;
8568 	int map_off;
8569 	u64 map_addr;
8570 	char *str_ptr;
8571 
8572 	if (reg->type != PTR_TO_MAP_VALUE)
8573 		return -EINVAL;
8574 
8575 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
8576 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
8577 			reg_arg_name(env, argno));
8578 		return -EACCES;
8579 	}
8580 
8581 	if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
8582 		verbose(env, "%s points to percpu_array map which cannot be used as const string\n",
8583 			reg_arg_name(env, argno));
8584 		return -EACCES;
8585 	}
8586 
8587 	if (!bpf_map_is_rdonly(map)) {
8588 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
8589 		return -EACCES;
8590 	}
8591 
8592 	if (!tnum_is_const(reg->var_off)) {
8593 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
8594 		return -EACCES;
8595 	}
8596 
8597 	if (!map->ops->map_direct_value_addr) {
8598 		verbose(env, "no direct value access support for this map type\n");
8599 		return -EACCES;
8600 	}
8601 
8602 	err = check_map_access(env, reg, argno, 0,
8603 			       map->value_size - reg->var_off.value, false,
8604 			       ACCESS_HELPER);
8605 	if (err)
8606 		return err;
8607 
8608 	map_off = reg->var_off.value;
8609 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8610 	if (err) {
8611 		verbose(env, "direct value access on string failed\n");
8612 		return err;
8613 	}
8614 
8615 	str_ptr = (char *)(long)(map_addr);
8616 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8617 		verbose(env, "string is not zero-terminated\n");
8618 		return -EINVAL;
8619 	}
8620 	return 0;
8621 }
8622 
8623 /* Returns constant key value in `value` if possible, else negative error */
8624 static int get_constant_map_key(struct bpf_verifier_env *env,
8625 				struct bpf_reg_state *key,
8626 				u32 key_size,
8627 				s64 *value)
8628 {
8629 	struct bpf_func_state *state = bpf_func(env, key);
8630 	struct bpf_reg_state *reg;
8631 	int slot, spi, off;
8632 	int spill_size = 0;
8633 	int zero_size = 0;
8634 	int stack_off;
8635 	int i, err;
8636 	u8 *stype;
8637 
8638 	if (!env->bpf_capable)
8639 		return -EOPNOTSUPP;
8640 	if (key->type != PTR_TO_STACK)
8641 		return -EOPNOTSUPP;
8642 	if (!tnum_is_const(key->var_off))
8643 		return -EOPNOTSUPP;
8644 
8645 	stack_off = key->var_off.value;
8646 	slot = -stack_off - 1;
8647 	spi = slot / BPF_REG_SIZE;
8648 	off = slot % BPF_REG_SIZE;
8649 	stype = state->stack[spi].slot_type;
8650 
8651 	/* First handle precisely tracked STACK_ZERO */
8652 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
8653 		zero_size++;
8654 	if (zero_size >= key_size) {
8655 		*value = 0;
8656 		return 0;
8657 	}
8658 
8659 	/* Check that stack contains a scalar spill of expected size */
8660 	if (!bpf_is_spilled_scalar_reg(&state->stack[spi]))
8661 		return -EOPNOTSUPP;
8662 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
8663 		spill_size++;
8664 	if (spill_size != key_size)
8665 		return -EOPNOTSUPP;
8666 
8667 	reg = &state->stack[spi].spilled_ptr;
8668 	if (!tnum_is_const(reg->var_off))
8669 		/* Stack value not statically known */
8670 		return -EOPNOTSUPP;
8671 
8672 	/* We are relying on a constant value. So mark as precise
8673 	 * to prevent pruning on it.
8674 	 */
8675 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
8676 	err = mark_chain_precision_batch(env, env->cur_state);
8677 	if (err < 0)
8678 		return err;
8679 
8680 	*value = reg->var_off.value;
8681 	return 0;
8682 }
8683 
8684 static bool can_elide_value_nullness(const struct bpf_map *map);
8685 
8686 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8687 			       argno_t argno, struct bpf_call_arg_meta *meta)
8688 {
8689 	/* Use map_uid (which is unique id of inner map) to reject:
8690 	 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8691 	 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8692 	 * if (inner_map1 && inner_map2) {
8693 	 *     timer = bpf_map_lookup_elem(inner_map1);
8694 	 *     if (timer)
8695 	 *         // mismatch would have been allowed
8696 	 *         bpf_timer_init(timer, inner_map2);
8697 	 * }
8698 	 *
8699 	 * Comparing map_ptr is enough to distinguish normal and outer maps.
8700 	 */
8701 	if (meta->map.ptr &&
8702 	    (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) {
8703 		argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1);
8704 		struct btf_record *rec = meta->map.ptr->record;
8705 		const char *obj_name = "workqueue";
8706 
8707 		if (rec->timer_off >= 0)
8708 			obj_name = "timer";
8709 		else if (rec->task_work_off >= 0)
8710 			obj_name = "bpf_task_work";
8711 
8712 		verbose(env, "%s pointer in %s map_uid=%d ",
8713 			obj_name, reg_arg_name(env, obj_argno), meta->map.uid);
8714 		verbose(env, "doesn't match map pointer in %s map_uid=%d\n",
8715 			reg_arg_name(env, argno), reg->map_uid);
8716 		return -EINVAL;
8717 	}
8718 
8719 	meta->map.ptr = reg->map_ptr;
8720 	meta->map.uid = reg->map_uid;
8721 	return 0;
8722 }
8723 
8724 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8725 			  struct bpf_call_arg_meta *meta,
8726 			  int insn_idx)
8727 {
8728 	const struct bpf_func_proto *fn = meta->fn;
8729 	u32 regno = BPF_REG_1 + arg;
8730 	struct bpf_reg_state *reg = reg_state(env, regno);
8731 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8732 	argno_t argno = argno_from_reg(regno);
8733 	enum bpf_reg_type type = reg->type;
8734 	u32 *arg_btf_id = NULL;
8735 	u32 key_size;
8736 	int err = 0;
8737 
8738 	if (arg_type == ARG_DONTCARE)
8739 		return 0;
8740 
8741 	err = check_reg_arg(env, regno, SRC_OP);
8742 	if (err)
8743 		return err;
8744 
8745 	if (arg_type == ARG_ANYTHING) {
8746 		if (is_pointer_value(env, regno)) {
8747 			verbose(env, "R%d leaks addr into helper function\n",
8748 				regno);
8749 			return -EACCES;
8750 		}
8751 		return 0;
8752 	}
8753 
8754 	if (type_is_pkt_pointer(type) &&
8755 	    !may_access_direct_pkt_data(env, fn, BPF_READ)) {
8756 		verbose(env, "helper access to the packet is not allowed\n");
8757 		return -EACCES;
8758 	}
8759 
8760 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8761 		err = resolve_map_arg_type(env, meta, &arg_type);
8762 		if (err)
8763 			return err;
8764 	}
8765 
8766 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) {
8767 		/* A NULL register has a SCALAR_VALUE type, so skip
8768 		 * type checking.
8769 		 */
8770 		err = mark_chain_precision(env, regno);
8771 		if (err)
8772 			return err;
8773 		goto skip_type_check;
8774 	}
8775 
8776 	/* arg_btf_id and arg_size are in a union. */
8777 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8778 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8779 		arg_btf_id = fn->arg_btf_id[arg];
8780 
8781 	err = check_reg_type(env, reg, argno, arg_type, arg_btf_id, meta,
8782 			     func_id_name(meta->func_id));
8783 	if (err)
8784 		return err;
8785 
8786 	err = check_func_arg_reg_off(env, reg, argno, arg_type);
8787 	if (err)
8788 		return err;
8789 
8790 skip_type_check:
8791 	if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) &&
8792 	    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
8793 		verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n",
8794 			func_id_name(meta->func_id), reg_arg_name(env, argno));
8795 		bpf_diag_call_arg(
8796 			env, insn_idx, argno, func_id_name(meta->func_id),
8797 			"release helpers require a value that owns a live resource returned by a matching acquire helper",
8798 			"Pass the resource-owning pointer returned by the matching acquire helper, and avoid calling the release helper after ownership has already been transferred or released.");
8799 		return -EINVAL;
8800 	}
8801 
8802 	if (reg_is_referenced(env, reg))
8803 		update_ref_obj(&meta->ref_obj, reg);
8804 
8805 	switch (base_type(arg_type)) {
8806 	case ARG_CONST_MAP_PTR:
8807 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8808 		err = process_map_ptr_arg(env, reg, argno, meta);
8809 		if (err)
8810 			return err;
8811 		break;
8812 	case ARG_PTR_TO_MAP_KEY:
8813 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8814 		 * check that [key, key + map->key_size) are within
8815 		 * stack limits and initialized
8816 		 */
8817 		if (!meta->map.ptr) {
8818 			/* in function declaration map_ptr must come before
8819 			 * map_key, so that it's verified and known before
8820 			 * we have to check map_key here. Otherwise it means
8821 			 * that kernel subsystem misconfigured verifier
8822 			 */
8823 			verifier_bug(env, "invalid map_ptr to access map->key");
8824 			return -EFAULT;
8825 		}
8826 		key_size = meta->map.ptr->key_size;
8827 		err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, NULL,
8828 					      NULL);
8829 		if (err)
8830 			return err;
8831 		if (can_elide_value_nullness(meta->map.ptr)) {
8832 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
8833 			if (err < 0) {
8834 				meta->const_map_key = -1;
8835 				if (err == -EOPNOTSUPP)
8836 					err = 0;
8837 				else
8838 					return err;
8839 			}
8840 		}
8841 		break;
8842 	case ARG_PTR_TO_MAP_VALUE:
8843 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
8844 			return 0;
8845 
8846 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8847 		 * check [value, value + map->value_size) validity
8848 		 */
8849 		if (!meta->map.ptr) {
8850 			/* kernel subsystem misconfigured verifier */
8851 			verifier_bug(env, "invalid map_ptr to access map->value");
8852 			return -EFAULT;
8853 		}
8854 
8855 		/*
8856 		 * Disable raw mode for bpf_map_peek_elem() on a bloom filter. The helper reads
8857 		 * the value buffer as an input rather than filling it.
8858 		 */
8859 		if (meta->func_id == BPF_FUNC_map_peek_elem &&
8860 		    meta->map.ptr->map_type == BPF_MAP_TYPE_BLOOM_FILTER)
8861 			meta->arg_raw_mem.regno = 0;
8862 
8863 		err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size,
8864 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8865 					      false, meta, NULL);
8866 		break;
8867 	case ARG_PTR_TO_PERCPU_BTF_ID:
8868 		if (!reg->btf_id) {
8869 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8870 			return -EACCES;
8871 		}
8872 		meta->ret_btf = reg->btf;
8873 		meta->ret_btf_id = reg->btf_id;
8874 		break;
8875 	case ARG_PTR_TO_SPIN_LOCK:
8876 		if (in_rbtree_lock_required_cb(env)) {
8877 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8878 			return -EACCES;
8879 		}
8880 		if (meta->func_id == BPF_FUNC_spin_lock) {
8881 			err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK);
8882 			if (err)
8883 				return err;
8884 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8885 			err = process_spin_lock(env, reg, argno, 0);
8886 			if (err)
8887 				return err;
8888 		} else {
8889 			verifier_bug(env, "spin lock arg on unexpected helper");
8890 			return -EFAULT;
8891 		}
8892 		break;
8893 	case ARG_PTR_TO_TIMER:
8894 		err = process_timer_func(env, reg, argno, &meta->map);
8895 		if (err)
8896 			return err;
8897 		break;
8898 	case ARG_PTR_TO_FUNC:
8899 		meta->subprogno = reg->subprogno;
8900 		break;
8901 	case ARG_PTR_TO_MEM:
8902 		/* The access to this pointer is only checked when we hit the
8903 		 * next is_mem_size argument below.
8904 		 */
8905 		if (arg_type & MEM_FIXED_SIZE) {
8906 			err = check_mem_reg(env, reg, argno_from_reg(regno), fn->arg_size[arg],
8907 					    arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, meta, NULL);
8908 			if (err)
8909 				return err;
8910 			if (arg_type & MEM_ALIGNED)
8911 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8912 		}
8913 		break;
8914 	case ARG_MEM_SIZE:
8915 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg,
8916 					 argno_from_reg(regno - 1), argno,
8917 					 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ,
8918 					 false, meta, NULL);
8919 		break;
8920 	case ARG_MEM_SIZE_OR_ZERO:
8921 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg,
8922 					 argno_from_reg(regno - 1), argno,
8923 					 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ,
8924 					 true, meta, NULL);
8925 		break;
8926 	case ARG_PTR_TO_DYNPTR:
8927 		err = process_dynptr_func(env, reg, argno, insn_idx, func_id_name(meta->func_id),
8928 					  arg_type, &meta->ref_obj, &meta->dynptr);
8929 		if (err)
8930 			return err;
8931 		break;
8932 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8933 		err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem);
8934 		if (err)
8935 			return err;
8936 		break;
8937 	case ARG_PTR_TO_CONST_STR:
8938 	{
8939 		err = check_arg_const_str(env, reg, argno);
8940 		if (err)
8941 			return err;
8942 		break;
8943 	}
8944 	case ARG_KPTR_XCHG_DEST:
8945 		err = process_kptr_func(env, regno, meta);
8946 		if (err)
8947 			return err;
8948 		break;
8949 	}
8950 
8951 	return err;
8952 }
8953 
8954 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8955 {
8956 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8957 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8958 
8959 	if (func_id != BPF_FUNC_map_update_elem &&
8960 	    func_id != BPF_FUNC_map_delete_elem)
8961 		return false;
8962 
8963 	/* It's not possible to get access to a locked struct sock in these
8964 	 * contexts, so updating is safe.
8965 	 */
8966 	switch (type) {
8967 	case BPF_PROG_TYPE_TRACING:
8968 		if (eatype == BPF_TRACE_ITER)
8969 			return true;
8970 		break;
8971 	case BPF_PROG_TYPE_SOCK_OPS:
8972 		/* map_update allowed only via dedicated helpers with event type checks */
8973 		if (func_id == BPF_FUNC_map_delete_elem)
8974 			return true;
8975 		break;
8976 	case BPF_PROG_TYPE_SK_REUSEPORT:
8977 	case BPF_PROG_TYPE_SK_LOOKUP:
8978 		return true;
8979 	default:
8980 		break;
8981 	}
8982 
8983 	verbose(env, "cannot update sockmap in this context\n");
8984 	return false;
8985 }
8986 
8987 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8988 {
8989 	return env->prog->jit_requested &&
8990 	       bpf_jit_supports_subprog_tailcalls();
8991 }
8992 
8993 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8994 					struct bpf_map *map, int func_id)
8995 {
8996 	if (!map)
8997 		return 0;
8998 
8999 	/* We need a two way check, first is from map perspective ... */
9000 	switch (map->map_type) {
9001 	case BPF_MAP_TYPE_PROG_ARRAY:
9002 		if (func_id != BPF_FUNC_tail_call)
9003 			goto error;
9004 		break;
9005 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9006 		if (func_id != BPF_FUNC_perf_event_read &&
9007 		    func_id != BPF_FUNC_perf_event_output &&
9008 		    func_id != BPF_FUNC_skb_output &&
9009 		    func_id != BPF_FUNC_perf_event_read_value &&
9010 		    func_id != BPF_FUNC_xdp_output)
9011 			goto error;
9012 		break;
9013 	case BPF_MAP_TYPE_RINGBUF:
9014 		if (func_id != BPF_FUNC_ringbuf_output &&
9015 		    func_id != BPF_FUNC_ringbuf_reserve &&
9016 		    func_id != BPF_FUNC_ringbuf_query &&
9017 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9018 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9019 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9020 			goto error;
9021 		break;
9022 	case BPF_MAP_TYPE_USER_RINGBUF:
9023 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9024 			goto error;
9025 		break;
9026 	case BPF_MAP_TYPE_STACK_TRACE:
9027 		if (func_id != BPF_FUNC_get_stackid)
9028 			goto error;
9029 		break;
9030 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9031 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9032 		    func_id != BPF_FUNC_current_task_under_cgroup)
9033 			goto error;
9034 		break;
9035 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9036 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9037 		if (func_id != BPF_FUNC_get_local_storage)
9038 			goto error;
9039 		break;
9040 	case BPF_MAP_TYPE_DEVMAP:
9041 	case BPF_MAP_TYPE_DEVMAP_HASH:
9042 		if (func_id != BPF_FUNC_redirect_map &&
9043 		    func_id != BPF_FUNC_map_lookup_elem)
9044 			goto error;
9045 		break;
9046 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9047 	 * appear.
9048 	 */
9049 	case BPF_MAP_TYPE_CPUMAP:
9050 		if (func_id != BPF_FUNC_redirect_map)
9051 			goto error;
9052 		break;
9053 	case BPF_MAP_TYPE_XSKMAP:
9054 		if (func_id != BPF_FUNC_redirect_map &&
9055 		    func_id != BPF_FUNC_map_lookup_elem)
9056 			goto error;
9057 		break;
9058 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9059 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9060 		if (func_id != BPF_FUNC_map_lookup_elem)
9061 			goto error;
9062 		break;
9063 	case BPF_MAP_TYPE_SOCKMAP:
9064 		if (func_id != BPF_FUNC_sk_redirect_map &&
9065 		    func_id != BPF_FUNC_sock_map_update &&
9066 		    func_id != BPF_FUNC_msg_redirect_map &&
9067 		    func_id != BPF_FUNC_sk_select_reuseport &&
9068 		    func_id != BPF_FUNC_map_lookup_elem &&
9069 		    !may_update_sockmap(env, func_id))
9070 			goto error;
9071 		break;
9072 	case BPF_MAP_TYPE_SOCKHASH:
9073 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9074 		    func_id != BPF_FUNC_sock_hash_update &&
9075 		    func_id != BPF_FUNC_msg_redirect_hash &&
9076 		    func_id != BPF_FUNC_sk_select_reuseport &&
9077 		    func_id != BPF_FUNC_map_lookup_elem &&
9078 		    !may_update_sockmap(env, func_id))
9079 			goto error;
9080 		break;
9081 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9082 		if (func_id != BPF_FUNC_sk_select_reuseport)
9083 			goto error;
9084 		break;
9085 	case BPF_MAP_TYPE_QUEUE:
9086 	case BPF_MAP_TYPE_STACK:
9087 		if (func_id != BPF_FUNC_map_peek_elem &&
9088 		    func_id != BPF_FUNC_map_pop_elem &&
9089 		    func_id != BPF_FUNC_map_push_elem)
9090 			goto error;
9091 		break;
9092 	case BPF_MAP_TYPE_SK_STORAGE:
9093 		if (func_id != BPF_FUNC_sk_storage_get &&
9094 		    func_id != BPF_FUNC_sk_storage_delete &&
9095 		    func_id != BPF_FUNC_kptr_xchg)
9096 			goto error;
9097 		break;
9098 	case BPF_MAP_TYPE_INODE_STORAGE:
9099 		if (func_id != BPF_FUNC_inode_storage_get &&
9100 		    func_id != BPF_FUNC_inode_storage_delete &&
9101 		    func_id != BPF_FUNC_kptr_xchg)
9102 			goto error;
9103 		break;
9104 	case BPF_MAP_TYPE_TASK_STORAGE:
9105 		if (func_id != BPF_FUNC_task_storage_get &&
9106 		    func_id != BPF_FUNC_task_storage_delete &&
9107 		    func_id != BPF_FUNC_kptr_xchg)
9108 			goto error;
9109 		break;
9110 	case BPF_MAP_TYPE_CGRP_STORAGE:
9111 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9112 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9113 		    func_id != BPF_FUNC_kptr_xchg)
9114 			goto error;
9115 		break;
9116 	case BPF_MAP_TYPE_BLOOM_FILTER:
9117 		if (func_id != BPF_FUNC_map_peek_elem &&
9118 		    func_id != BPF_FUNC_map_push_elem)
9119 			goto error;
9120 		break;
9121 	case BPF_MAP_TYPE_INSN_ARRAY:
9122 		goto error;
9123 	default:
9124 		break;
9125 	}
9126 
9127 	/* ... and second from the function itself. */
9128 	switch (func_id) {
9129 	case BPF_FUNC_tail_call:
9130 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9131 			goto error;
9132 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
9133 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
9134 			return -EINVAL;
9135 		}
9136 		break;
9137 	case BPF_FUNC_perf_event_read:
9138 	case BPF_FUNC_perf_event_output:
9139 	case BPF_FUNC_perf_event_read_value:
9140 	case BPF_FUNC_skb_output:
9141 	case BPF_FUNC_xdp_output:
9142 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9143 			goto error;
9144 		break;
9145 	case BPF_FUNC_ringbuf_output:
9146 	case BPF_FUNC_ringbuf_reserve:
9147 	case BPF_FUNC_ringbuf_query:
9148 	case BPF_FUNC_ringbuf_reserve_dynptr:
9149 	case BPF_FUNC_ringbuf_submit_dynptr:
9150 	case BPF_FUNC_ringbuf_discard_dynptr:
9151 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9152 			goto error;
9153 		break;
9154 	case BPF_FUNC_user_ringbuf_drain:
9155 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9156 			goto error;
9157 		break;
9158 	case BPF_FUNC_get_stackid:
9159 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9160 			goto error;
9161 		break;
9162 	case BPF_FUNC_current_task_under_cgroup:
9163 	case BPF_FUNC_skb_under_cgroup:
9164 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9165 			goto error;
9166 		break;
9167 	case BPF_FUNC_redirect_map:
9168 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9169 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9170 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9171 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9172 			goto error;
9173 		break;
9174 	case BPF_FUNC_sk_redirect_map:
9175 	case BPF_FUNC_msg_redirect_map:
9176 	case BPF_FUNC_sock_map_update:
9177 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9178 			goto error;
9179 		break;
9180 	case BPF_FUNC_sk_redirect_hash:
9181 	case BPF_FUNC_msg_redirect_hash:
9182 	case BPF_FUNC_sock_hash_update:
9183 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9184 			goto error;
9185 		break;
9186 	case BPF_FUNC_get_local_storage:
9187 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9188 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9189 			goto error;
9190 		break;
9191 	case BPF_FUNC_sk_select_reuseport:
9192 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9193 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9194 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9195 			goto error;
9196 		break;
9197 	case BPF_FUNC_map_pop_elem:
9198 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9199 		    map->map_type != BPF_MAP_TYPE_STACK)
9200 			goto error;
9201 		break;
9202 	case BPF_FUNC_map_peek_elem:
9203 	case BPF_FUNC_map_push_elem:
9204 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9205 		    map->map_type != BPF_MAP_TYPE_STACK &&
9206 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9207 			goto error;
9208 		break;
9209 	case BPF_FUNC_map_lookup_percpu_elem:
9210 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9211 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9212 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9213 			goto error;
9214 		break;
9215 	case BPF_FUNC_sk_storage_get:
9216 	case BPF_FUNC_sk_storage_delete:
9217 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9218 			goto error;
9219 		break;
9220 	case BPF_FUNC_inode_storage_get:
9221 	case BPF_FUNC_inode_storage_delete:
9222 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9223 			goto error;
9224 		break;
9225 	case BPF_FUNC_task_storage_get:
9226 	case BPF_FUNC_task_storage_delete:
9227 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9228 			goto error;
9229 		break;
9230 	case BPF_FUNC_cgrp_storage_get:
9231 	case BPF_FUNC_cgrp_storage_delete:
9232 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9233 			goto error;
9234 		break;
9235 	default:
9236 		break;
9237 	}
9238 
9239 	return 0;
9240 error:
9241 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9242 		map->map_type, func_id_name(func_id), func_id);
9243 	return -EINVAL;
9244 }
9245 
9246 static bool check_raw_mode_ok(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
9247 {
9248 	int i;
9249 
9250 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9251 		if (fn->arg_type[i] == ARG_DONTCARE)
9252 			break;
9253 		if (!arg_type_is_raw_mem(fn->arg_type[i]))
9254 			continue;
9255 		if (meta->arg_raw_mem.regno)
9256 			return false;
9257 		meta->arg_raw_mem.regno = i + 1;
9258 	}
9259 
9260 	return true;
9261 }
9262 
9263 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9264 {
9265 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9266 	bool has_size = fn->arg_size[arg] != 0;
9267 	bool is_next_size = false;
9268 
9269 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9270 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9271 
9272 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9273 		return is_next_size;
9274 
9275 	return has_size == is_next_size || is_next_size == is_fixed;
9276 }
9277 
9278 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9279 {
9280 	/* bpf_xxx(..., buf, len) call will access 'len'
9281 	 * bytes from memory 'buf'. Both arg types need
9282 	 * to be paired, so make sure there's no buggy
9283 	 * helper function specification.
9284 	 */
9285 	if (arg_type_is_mem_size(fn->arg1_type) ||
9286 	    check_args_pair_invalid(fn, 0) ||
9287 	    check_args_pair_invalid(fn, 1) ||
9288 	    check_args_pair_invalid(fn, 2) ||
9289 	    check_args_pair_invalid(fn, 3) ||
9290 	    check_args_pair_invalid(fn, 4))
9291 		return false;
9292 
9293 	return true;
9294 }
9295 
9296 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9297 {
9298 	int i;
9299 
9300 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9301 		if (fn->arg_type[i] == ARG_DONTCARE)
9302 			break;
9303 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9304 			return !!fn->arg_btf_id[i];
9305 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9306 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9307 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9308 		    /* arg_btf_id and arg_size are in a union. */
9309 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9310 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9311 			return false;
9312 	}
9313 
9314 	return true;
9315 }
9316 
9317 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
9318 {
9319 	int i;
9320 
9321 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9322 		enum bpf_arg_type arg_type = fn->arg_type[i];
9323 
9324 		if (arg_type == ARG_DONTCARE)
9325 			break;
9326 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
9327 			continue;
9328 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
9329 			return false;
9330 	}
9331 
9332 	return true;
9333 }
9334 
9335 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
9336 {
9337 	int i;
9338 
9339 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9340 		enum bpf_arg_type arg_type = fn->arg_type[i];
9341 
9342 		if (arg_type == ARG_DONTCARE)
9343 			break;
9344 		if (arg_type_is_release(arg_type)) {
9345 			if (meta->release_regno)
9346 				return false;
9347 			meta->release_regno = i + 1;
9348 		}
9349 	}
9350 
9351 	return true;
9352 }
9353 
9354 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
9355 {
9356 	return check_raw_mode_ok(fn, meta) &&
9357 	       check_arg_pair_ok(fn) &&
9358 	       check_mem_arg_rw_flag_ok(fn) &&
9359 	       check_proto_release_reg(fn, meta) &&
9360 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9361 }
9362 
9363 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9364  * are now invalid, so turn them into unknown SCALAR_VALUE.
9365  *
9366  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9367  * since these slices point to packet data.
9368  */
9369 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9370 {
9371 	struct bpf_func_state *state;
9372 	struct bpf_reg_state *reg;
9373 
9374 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9375 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) {
9376 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_PKT_DATA_CHANGE);
9377 			mark_reg_invalid(env, reg);
9378 		}
9379 	}));
9380 }
9381 
9382 enum {
9383 	AT_PKT_END = -1,
9384 	BEYOND_PKT_END = -2,
9385 };
9386 
9387 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9388 {
9389 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9390 	struct bpf_reg_state *reg = &state->regs[regn];
9391 
9392 	if (reg->type != PTR_TO_PACKET)
9393 		/* PTR_TO_PACKET_META is not supported yet */
9394 		return;
9395 
9396 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9397 	 * How far beyond pkt_end it goes is unknown.
9398 	 * if (!range_open) it's the case of pkt >= pkt_end
9399 	 * if (range_open) it's the case of pkt > pkt_end
9400 	 * hence this pointer is at least 1 byte bigger than pkt_end
9401 	 */
9402 	if (range_open)
9403 		reg->range = BEYOND_PKT_END;
9404 	else
9405 		reg->range = AT_PKT_END;
9406 }
9407 
9408 static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
9409 {
9410 	int i;
9411 
9412 	for (i = 0; i < state->acquired_refs; i++) {
9413 		if (state->refs[i].type != REF_TYPE_PTR)
9414 			continue;
9415 		if (state->refs[i].id == id) {
9416 			release_reference_state(state, i);
9417 			return 0;
9418 		}
9419 	}
9420 	return -EINVAL;
9421 }
9422 
9423 static int release_reference_nomark(struct bpf_verifier_env *env, int id)
9424 {
9425 	int err;
9426 
9427 	err = __release_reference_nomark(env->cur_state, id);
9428 	if (!err)
9429 		bpf_diag_record_ref_release(env, env->insn_idx, id);
9430 	return err;
9431 }
9432 
9433 static int idstack_push(struct bpf_idmap *idmap, u32 id)
9434 {
9435 	int i;
9436 
9437 	if (!id)
9438 		return 0;
9439 
9440 	for (i = 0; i < idmap->cnt; i++)
9441 		if (idmap->map[i].old == id)
9442 			return 0;
9443 
9444 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
9445 		return -EFAULT;
9446 
9447 	idmap->map[idmap->cnt++].old = id;
9448 	return 0;
9449 }
9450 
9451 static int idstack_pop(struct bpf_idmap *idmap)
9452 {
9453 	if (!idmap->cnt)
9454 		return 0;
9455 
9456 	return idmap->map[--idmap->cnt].old;
9457 }
9458 
9459 /* Release id and objects derived from it iteratively in a DFS manner */
9460 static int release_reference(struct bpf_verifier_env *env, int id)
9461 {
9462 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
9463 	struct bpf_verifier_state *vstate = env->cur_state;
9464 	struct bpf_idmap *idstack = &env->idmap_scratch;
9465 	struct bpf_stack_state *stack;
9466 	struct bpf_func_state *state;
9467 	struct bpf_reg_state *reg;
9468 	int i, err;
9469 
9470 	idstack->cnt = 0;
9471 	err = idstack_push(idstack, id);
9472 	if (err)
9473 		return err;
9474 
9475 	if (find_reference_state(vstate, id)) {
9476 		err = release_reference_nomark(env, id);
9477 		WARN_ON_ONCE(err);
9478 	}
9479 
9480 	while ((id = idstack_pop(idstack))) {
9481 		/*
9482 		 * Child references are inaccessible after parent is released,
9483 		 * any child references that exist at this point are a leak.
9484 		 */
9485 		for (i = 0; i < vstate->acquired_refs; i++) {
9486 			if (vstate->refs[i].type != REF_TYPE_PTR)
9487 				continue;
9488 			if (vstate->refs[i].parent_id != id)
9489 				continue;
9490 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
9491 				vstate->refs[i].id, vstate->refs[i].insn_idx);
9492 			return -EINVAL;
9493 		}
9494 
9495 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
9496 			if (reg->id != id && reg->parent_id != id)
9497 				continue;
9498 
9499 			/* Free objects derived from the current object */
9500 			if (reg->parent_id == id) {
9501 				err = idstack_push(idstack, reg->id);
9502 				if (err)
9503 					return err;
9504 			}
9505 
9506 			/*
9507 			 * A dynptr occupies two stack slots that invalidate_dynptr()
9508 			 * clears together. Record both scrubs before invalidating it.
9509 			 */
9510 			if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) {
9511 				struct bpf_stack_state *dyn_stack = stack;
9512 
9513 				if (reg->dynptr.first_slot)
9514 					dyn_stack--;
9515 				bpf_diag_record_scrub(env, &dyn_stack[0].spilled_ptr,
9516 						      BPF_DIAG_MOD_REF_RELEASE);
9517 				bpf_diag_record_scrub(env, &dyn_stack[1].spilled_ptr,
9518 						      BPF_DIAG_MOD_REF_RELEASE);
9519 				invalidate_dynptr(env, dyn_stack);
9520 				continue;
9521 			}
9522 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_REF_RELEASE);
9523 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
9524 				mark_reg_invalid(env, reg);
9525 		}));
9526 	}
9527 
9528 	return 0;
9529 }
9530 
9531 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9532 {
9533 	struct bpf_func_state *unused;
9534 	struct bpf_reg_state *reg;
9535 
9536 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9537 		if (type_is_non_owning_ref(reg->type)) {
9538 			bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_NON_OWN_REF);
9539 			mark_reg_invalid(env, reg);
9540 		}
9541 	}));
9542 }
9543 
9544 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
9545 {
9546 	struct bpf_stack_state *stack;
9547 	struct bpf_func_state *state;
9548 	struct bpf_reg_state *reg;
9549 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
9550 
9551 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
9552 		if (reg->type & MEM_RCU) {
9553 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
9554 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL | NON_OWN_REF);
9555 			reg->type |= PTR_UNTRUSTED;
9556 			bpf_diag_mod_end(env);
9557 		}
9558 	}));
9559 }
9560 
9561 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
9562 {
9563 	struct bpf_func_state *state;
9564 	struct bpf_reg_state *reg;
9565 	int err;
9566 
9567 	err = release_reference_nomark(env, id);
9568 	if (err)
9569 		return err;
9570 
9571 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9572 		if (reg->id != id)
9573 			continue;
9574 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
9575 			bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE);
9576 			reg->id = 0;
9577 			reg->type &= ~MEM_ALLOC;
9578 			reg->type |= MEM_RCU;
9579 			bpf_diag_mod_end(env);
9580 		}
9581 	}));
9582 
9583 	return err;
9584 }
9585 
9586 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9587 				    struct bpf_reg_state *regs)
9588 {
9589 	int i;
9590 
9591 	bpf_diag_record_caller_saved(env, regs);
9592 
9593 	/* after the call registers r0 - r5 were scratched */
9594 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9595 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
9596 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9597 	}
9598 }
9599 
9600 static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,
9601 					   struct bpf_func_state *state)
9602 {
9603 	int i, nslots = state->out_stack_arg_cnt;
9604 
9605 	for (i = 0; i < nslots; i++) {
9606 		bpf_diag_record_scrub(env, &state->stack_arg_regs[i], BPF_DIAG_MOD_CALLER_SAVED);
9607 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
9608 	}
9609 }
9610 
9611 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9612 				   struct bpf_func_state *caller,
9613 				   struct bpf_func_state *callee,
9614 				   int insn_idx);
9615 
9616 static int set_callee_state(struct bpf_verifier_env *env,
9617 			    struct bpf_func_state *caller,
9618 			    struct bpf_func_state *callee, int insn_idx);
9619 
9620 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9621 			    set_callee_state_fn set_callee_state_cb,
9622 			    struct bpf_verifier_state *state)
9623 {
9624 	struct bpf_func_state *caller, *callee;
9625 	int err;
9626 
9627 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9628 		verbose(env, "the call stack of %d frames is too deep\n",
9629 			state->curframe + 2);
9630 		return -E2BIG;
9631 	}
9632 
9633 	if (state->frame[state->curframe + 1]) {
9634 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
9635 		return -EFAULT;
9636 	}
9637 
9638 	caller = state->frame[state->curframe];
9639 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
9640 	if (!callee)
9641 		return -ENOMEM;
9642 	state->frame[state->curframe + 1] = callee;
9643 
9644 	/* callee cannot access r0, r6 - r9 for reading and has to write
9645 	 * into its own stack before reading from it.
9646 	 * callee can read/write into caller's stack
9647 	 */
9648 	init_func_state(env, callee,
9649 			/* remember the callsite, it will be used by bpf_exit */
9650 			callsite,
9651 			state->curframe + 1 /* frameno within this callchain */,
9652 			subprog /* subprog number within this prog */);
9653 	err = set_callee_state_cb(env, caller, callee, callsite);
9654 	if (err)
9655 		goto err_out;
9656 
9657 	/* only increment it after check_reg_arg() finished */
9658 	state->curframe++;
9659 
9660 	return 0;
9661 
9662 err_out:
9663 	free_func_state(callee);
9664 	state->frame[state->curframe + 1] = NULL;
9665 	return err;
9666 }
9667 
9668 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9669 				    const struct btf *btf,
9670 				    struct bpf_reg_state *regs)
9671 {
9672 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9673 	struct bpf_func_state *caller = cur_func(env);
9674 	struct bpf_verifier_log *log = &env->log;
9675 	struct ref_obj_desc ref_obj = {};
9676 	const struct btf_param *args;
9677 	const struct btf_type *func, *func_proto;
9678 	u32 i;
9679 	int ret, err;
9680 
9681 	ret = btf_prepare_func_args(env, subprog);
9682 	if (ret) {
9683 		if (bpf_in_stack_arg_cnt(sub) > 0) {
9684 			err = check_outgoing_stack_args(env, caller, sub->arg_cnt,
9685 							bpf_subprog_name(env, subprog),
9686 							NULL, NULL);
9687 			if (err)
9688 				return err;
9689 		}
9690 		return ret;
9691 	}
9692 
9693 	func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id);
9694 	func_proto = btf_type_by_id(btf, func->type);
9695 	args = btf_params(func_proto);
9696 	ret = check_outgoing_stack_args(env, caller, sub->arg_cnt,
9697 					bpf_subprog_name(env, subprog), btf, args);
9698 	if (ret)
9699 		return ret;
9700 
9701 	/* check that BTF function arguments match actual types that the
9702 	 * verifier sees.
9703 	 */
9704 	for (i = 0; i < sub->arg_cnt; i++) {
9705 		argno_t argno = argno_from_arg(i + 1);
9706 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
9707 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9708 
9709 		if (arg->arg_type == ARG_ANYTHING) {
9710 			if (reg->type != SCALAR_VALUE) {
9711 				bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno));
9712 				return -EINVAL;
9713 			}
9714 		} else if (arg->arg_type & PTR_UNTRUSTED) {
9715 			/*
9716 			 * Anything is allowed for untrusted arguments, as these are
9717 			 * read-only and probe read instructions would protect against
9718 			 * invalid memory access.
9719 			 */
9720 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9721 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX);
9722 			if (ret < 0)
9723 				return ret;
9724 			/* If function expects ctx type in BTF check that caller
9725 			 * is passing PTR_TO_CTX.
9726 			 */
9727 			if (reg->type != PTR_TO_CTX) {
9728 				bpf_log(log, "%s expects pointer to ctx\n",
9729 					reg_arg_name(env, argno));
9730 				return -EINVAL;
9731 			}
9732 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9733 			ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE);
9734 			if (ret < 0)
9735 				return ret;
9736 			if (check_mem_reg(env, reg, argno, arg->mem_size, BPF_READ | BPF_WRITE, NULL,
9737 					  NULL))
9738 				return -EINVAL;
9739 			if (!(arg->arg_type & PTR_MAYBE_NULL) &&
9740 			    (type_may_be_null(reg->type) || bpf_register_is_null(reg))) {
9741 				bpf_log(log, "%s is expected to be non-NULL\n",
9742 					reg_arg_name(env, argno));
9743 				return -EINVAL;
9744 			}
9745 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9746 			/*
9747 			 * Can pass any value and the kernel won't crash, but
9748 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9749 			 * else is a bug in the bpf program. Point it out to
9750 			 * the user at the verification time instead of
9751 			 * run-time debug nightmare.
9752 			 */
9753 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9754 				bpf_log(log, "%s is not a pointer to arena or scalar.\n",
9755 					reg_arg_name(env, argno));
9756 				return -EINVAL;
9757 			}
9758 		} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
9759 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR);
9760 			if (ret)
9761 				return ret;
9762 
9763 			ret = process_dynptr_func(env, reg, argno, env->insn_idx,
9764 						  bpf_subprog_name(env, subprog), arg->arg_type,
9765 						  &ref_obj, NULL);
9766 			if (ret)
9767 				return ret;
9768 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9769 			struct bpf_call_arg_meta meta;
9770 			int err;
9771 
9772 			if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) {
9773 				err = mark_arg_precision(env, argno);
9774 				if (err)
9775 					return err;
9776 				continue;
9777 			}
9778 
9779 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9780 			err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta,
9781 					     bpf_subprog_name(env, subprog));
9782 			err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type);
9783 			if (err)
9784 				return err;
9785 		} else {
9786 			verifier_bug(env, "unrecognized %s type %d",
9787 				     reg_arg_name(env, argno), arg->arg_type);
9788 			return -EFAULT;
9789 		}
9790 	}
9791 
9792 	return 0;
9793 }
9794 
9795 /* Compare BTF of a function call with given bpf_reg_state.
9796  * Returns:
9797  * EFAULT - there is a verifier bug. Abort verification.
9798  * EINVAL - there is a type mismatch or BTF is not available.
9799  * 0 - BTF matches with what bpf_reg_state expects.
9800  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9801  */
9802 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9803 				  struct bpf_reg_state *regs)
9804 {
9805 	struct bpf_prog *prog = env->prog;
9806 	struct btf *btf = prog->aux->btf;
9807 	u32 btf_id;
9808 	int err;
9809 
9810 	if (!prog->aux->func_info)
9811 		return -EINVAL;
9812 
9813 	btf_id = prog->aux->func_info[subprog].type_id;
9814 	if (!btf_id)
9815 		return -EFAULT;
9816 
9817 	if (prog->aux->func_info_aux[subprog].unreliable)
9818 		return -EINVAL;
9819 
9820 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9821 	/* Compiler optimizations can remove arguments from static functions
9822 	 * or mismatched type can be passed into a global function.
9823 	 * In such cases mark the function as unreliable from BTF point of view.
9824 	 */
9825 	if (err)
9826 		prog->aux->func_info_aux[subprog].unreliable = true;
9827 	return err;
9828 }
9829 
9830 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9831 			      int insn_idx, int subprog,
9832 			      set_callee_state_fn set_callee_state_cb)
9833 {
9834 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9835 	struct bpf_func_state *caller, *callee;
9836 	int err;
9837 
9838 	caller = state->frame[state->curframe];
9839 	err = btf_check_subprog_call(env, subprog, caller->regs);
9840 	if (err == -EFAULT)
9841 		return err;
9842 
9843 	/* set_callee_state is used for direct subprog calls, but we are
9844 	 * interested in validating only BPF helpers that can call subprogs as
9845 	 * callbacks
9846 	 */
9847 	env->subprog_info[subprog].is_cb = true;
9848 	if (bpf_pseudo_kfunc_call(insn) &&
9849 	    !is_callback_calling_kfunc(insn->imm)) {
9850 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
9851 			     func_id_name(insn->imm), insn->imm);
9852 		return -EFAULT;
9853 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9854 		   !is_callback_calling_function(insn->imm)) { /* helper */
9855 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
9856 			     func_id_name(insn->imm), insn->imm);
9857 		return -EFAULT;
9858 	}
9859 
9860 	if (bpf_is_async_callback_calling_insn(insn)) {
9861 		struct bpf_verifier_state *async_cb;
9862 
9863 		/* there is no real recursion here. timer and workqueue callbacks are async */
9864 		env->subprog_info[subprog].is_async_cb = true;
9865 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9866 					 insn_idx, subprog,
9867 					 is_async_cb_sleepable(env, insn));
9868 		if (IS_ERR(async_cb))
9869 			return PTR_ERR(async_cb);
9870 		callee = async_cb->frame[0];
9871 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9872 
9873 		/* Convert bpf_timer_set_callback() args into timer callback args */
9874 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9875 		if (err)
9876 			return err;
9877 
9878 		return 0;
9879 	}
9880 
9881 	/* for callback functions enqueue entry to callback and
9882 	 * proceed with next instruction within current frame.
9883 	 */
9884 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9885 	if (IS_ERR(callback_state))
9886 		return PTR_ERR(callback_state);
9887 
9888 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9889 			       callback_state);
9890 	if (err)
9891 		return err;
9892 
9893 	callback_state->callback_unroll_depth++;
9894 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9895 	caller->callback_depth = 0;
9896 	return 0;
9897 }
9898 
9899 static int process_bpf_exit_full(struct bpf_verifier_env *env,
9900 				 bool *do_print_state, bool exception_exit);
9901 
9902 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9903 			   int *insn_idx)
9904 {
9905 	struct bpf_verifier_state *state = env->cur_state;
9906 	struct bpf_subprog_info *caller_info;
9907 	u16 callee_incoming, stack_arg_cnt;
9908 	struct bpf_func_state *caller;
9909 	int err, subprog, target_insn;
9910 
9911 	target_insn = *insn_idx + insn->imm + 1;
9912 	subprog = bpf_find_subprog(env, target_insn);
9913 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
9914 			    target_insn))
9915 		return -EFAULT;
9916 
9917 	caller = state->frame[state->curframe];
9918 	err = btf_check_subprog_call(env, subprog, caller->regs);
9919 	if (err == -EFAULT)
9920 		return err;
9921 	if (bpf_subprog_is_global(env, subprog)) {
9922 		const char *sub_name = bpf_subprog_name(env, subprog);
9923 		const char *operation;
9924 		bool returns_void;
9925 
9926 		if (env->cur_state->active_locks) {
9927 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9928 				     "use static function instead\n");
9929 			operation = bpf_diag_fmt(env, "global function %s()", sub_name);
9930 			bpf_diag_ctx_active(env, *insn_idx, operation, BPF_DIAG_CONTEXT_LOCK,
9931 					    "Release the lock before calling the global function, or use a static function instead.");
9932 			return -EINVAL;
9933 		}
9934 
9935 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
9936 			verbose(env, "sleepable global function %s() called in %s\n",
9937 				sub_name, non_sleepable_context_description(env));
9938 			operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name);
9939 			bpf_diag_ctx_forbidden(env, *insn_idx, operation,
9940 				"Move the call outside the critical section, or use a non-sleepable function.");
9941 			return -EINVAL;
9942 		}
9943 
9944 		if (err) {
9945 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9946 				subprog, sub_name);
9947 			return err;
9948 		}
9949 
9950 		if (env->log.level & BPF_LOG_LEVEL)
9951 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9952 				subprog, sub_name);
9953 		returns_void = subprog_returns_void(env, subprog);
9954 		if (env->subprog_info[subprog].changes_pkt_data)
9955 			clear_all_pkt_pointers(env);
9956 		/* mark global subprog for verifying after main prog */
9957 		subprog_aux(env, subprog)->called = true;
9958 		if (returns_void)
9959 			bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
9960 		else
9961 			bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
9962 		clear_caller_saved_regs(env, caller->regs);
9963 		invalidate_outgoing_stack_args(env, cur_func(env));
9964 
9965 		/* All non-void global functions return a 64-bit SCALAR_VALUE. */
9966 		if (!returns_void) {
9967 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
9968 			bpf_diag_mod_end(env);
9969 		}
9970 
9971 		if (env->subprog_info[subprog].might_throw) {
9972 			struct bpf_verifier_state *branch;
9973 
9974 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
9975 			if (IS_ERR(branch)) {
9976 				verbose(env, "failed to push state for global subprog exception path\n");
9977 				return PTR_ERR(branch);
9978 			}
9979 			return process_bpf_exit_full(env, NULL, true);
9980 		}
9981 
9982 		/* continue with next insn after call */
9983 		return 0;
9984 	}
9985 
9986 	/*
9987 	 * Track caller's total stack arg count (incoming + max outgoing).
9988 	 * This is needed so the JIT knows how much stack arg space to allocate.
9989 	 */
9990 	caller_info = &env->subprog_info[caller->subprogno];
9991 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
9992 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
9993 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
9994 		caller_info->stack_arg_cnt = stack_arg_cnt;
9995 
9996 	/* for regular function entry setup new frame and continue
9997 	 * from that frame.
9998 	 */
9999 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10000 	if (err)
10001 		return err;
10002 
10003 	bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
10004 	clear_caller_saved_regs(env, caller->regs);
10005 
10006 	/* and go analyze first insn of the callee */
10007 	*insn_idx = env->subprog_info[subprog].start - 1;
10008 
10009 	if (env->log.level & BPF_LOG_LEVEL) {
10010 		verbose(env, "caller:\n");
10011 		print_verifier_state(env, state, caller->frameno, true);
10012 		verbose(env, "callee:\n");
10013 		print_verifier_state(env, state, state->curframe, true);
10014 	}
10015 
10016 	return 0;
10017 }
10018 
10019 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10020 				   struct bpf_func_state *caller,
10021 				   struct bpf_func_state *callee)
10022 {
10023 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10024 	 *      void *callback_ctx, u64 flags);
10025 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10026 	 *      void *callback_ctx);
10027 	 */
10028 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10029 
10030 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10031 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10032 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10033 	callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid;
10034 
10035 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10036 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10037 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10038 	callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid;
10039 
10040 	/* pointer to stack or null */
10041 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10042 
10043 	/* unused */
10044 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10045 	return 0;
10046 }
10047 
10048 static int set_callee_state(struct bpf_verifier_env *env,
10049 			    struct bpf_func_state *caller,
10050 			    struct bpf_func_state *callee, int insn_idx)
10051 {
10052 	int i;
10053 
10054 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10055 	 * pointers, which connects us up to the liveness chain
10056 	 */
10057 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10058 		callee->regs[i] = caller->regs[i];
10059 	return 0;
10060 }
10061 
10062 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10063 				       struct bpf_func_state *caller,
10064 				       struct bpf_func_state *callee,
10065 				       int insn_idx)
10066 {
10067 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10068 	struct bpf_map *map;
10069 	int err;
10070 
10071 	/* valid map_ptr and poison value does not matter */
10072 	map = insn_aux->map_ptr_state.map_ptr;
10073 	if (!map->ops->map_set_for_each_callback_args ||
10074 	    !map->ops->map_for_each_callback) {
10075 		verbose(env, "callback function not allowed for map\n");
10076 		return -ENOTSUPP;
10077 	}
10078 
10079 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10080 	if (err)
10081 		return err;
10082 
10083 	callee->in_callback_fn = true;
10084 	callee->callback_ret_range = retval_range(0, 1);
10085 	return 0;
10086 }
10087 
10088 static int set_loop_callback_state(struct bpf_verifier_env *env,
10089 				   struct bpf_func_state *caller,
10090 				   struct bpf_func_state *callee,
10091 				   int insn_idx)
10092 {
10093 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10094 	 *	    u64 flags);
10095 	 * callback_fn(u64 index, void *callback_ctx);
10096 	 */
10097 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10098 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10099 
10100 	/* unused */
10101 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10102 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10103 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10104 
10105 	callee->in_callback_fn = true;
10106 	callee->callback_ret_range = retval_range(0, 1);
10107 	return 0;
10108 }
10109 
10110 static int set_timer_callback_state(struct bpf_verifier_env *env,
10111 				    struct bpf_func_state *caller,
10112 				    struct bpf_func_state *callee,
10113 				    int insn_idx)
10114 {
10115 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10116 	u32 map_uid = caller->regs[BPF_REG_1].map_uid;
10117 
10118 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10119 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10120 	 */
10121 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10122 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10123 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10124 	callee->regs[BPF_REG_1].map_uid = map_uid;
10125 
10126 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10127 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10128 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10129 	callee->regs[BPF_REG_2].map_uid = map_uid;
10130 
10131 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10132 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10133 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10134 	callee->regs[BPF_REG_3].map_uid = map_uid;
10135 
10136 	/* unused */
10137 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10138 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10139 	callee->in_async_callback_fn = true;
10140 	callee->callback_ret_range = retval_range(0, 0);
10141 	return 0;
10142 }
10143 
10144 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10145 				       struct bpf_func_state *caller,
10146 				       struct bpf_func_state *callee,
10147 				       int insn_idx)
10148 {
10149 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10150 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10151 	 * (callback_fn)(struct task_struct *task,
10152 	 *               struct vm_area_struct *vma, void *callback_ctx);
10153 	 */
10154 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10155 
10156 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10157 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10158 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10159 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10160 
10161 	/* pointer to stack or null */
10162 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10163 
10164 	/* unused */
10165 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10166 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10167 	callee->in_callback_fn = true;
10168 	callee->callback_ret_range = retval_range(0, 1);
10169 	return 0;
10170 }
10171 
10172 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10173 					   struct bpf_func_state *caller,
10174 					   struct bpf_func_state *callee,
10175 					   int insn_idx)
10176 {
10177 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10178 	 *			  callback_ctx, u64 flags);
10179 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10180 	 */
10181 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10182 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10183 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10184 
10185 	/* unused */
10186 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10187 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10188 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10189 
10190 	callee->in_callback_fn = true;
10191 	callee->callback_ret_range = retval_range(0, 1);
10192 	return 0;
10193 }
10194 
10195 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10196 					 struct bpf_func_state *caller,
10197 					 struct bpf_func_state *callee,
10198 					 int insn_idx)
10199 {
10200 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10201 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10202 	 *
10203 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10204 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10205 	 * by this point, so look at 'root'
10206 	 */
10207 	struct btf_field *field;
10208 
10209 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
10210 				      caller->regs[BPF_REG_1].var_off.value,
10211 				      BPF_RB_ROOT);
10212 	if (!field || !field->graph_root.value_btf_id)
10213 		return -EFAULT;
10214 
10215 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10216 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10217 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10218 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10219 
10220 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10221 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10222 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10223 	callee->in_callback_fn = true;
10224 	callee->callback_ret_range = retval_range(0, 1);
10225 	return 0;
10226 }
10227 
10228 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
10229 						 struct bpf_func_state *caller,
10230 						 struct bpf_func_state *callee,
10231 						 int insn_idx)
10232 {
10233 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
10234 	u32 map_uid = caller->regs[BPF_REG_3].map_uid;
10235 
10236 	/*
10237 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10238 	 */
10239 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10240 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10241 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10242 	callee->regs[BPF_REG_1].map_uid = map_uid;
10243 
10244 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10245 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10246 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10247 	callee->regs[BPF_REG_2].map_uid = map_uid;
10248 
10249 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10250 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10251 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10252 	callee->regs[BPF_REG_3].map_uid = map_uid;
10253 
10254 	/* unused */
10255 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10256 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10257 	callee->in_async_callback_fn = true;
10258 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
10259 	return 0;
10260 }
10261 
10262 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10263 
10264 static void account_processed_insn(struct bpf_verifier_env *env)
10265 {
10266 	struct bpf_func_state *frame = cur_func(env);
10267 
10268 	env->insn_processed++;
10269 	frame->insns_subtotal++;
10270 	env->subprog_info[frame->subprogno].insns_self++;
10271 }
10272 
10273 static void account_processed_insns(struct bpf_verifier_env *env,
10274 				    struct bpf_func_state *callee,
10275 				    struct bpf_func_state *caller)
10276 {
10277 	u32 insns;
10278 
10279 	if (!callee)
10280 		return;
10281 
10282 	insns = callee->insns_subtotal;
10283 
10284 	env->subprog_info[callee->subprogno].insns_total += insns;
10285 	if (caller)
10286 		caller->insns_subtotal += insns;
10287 	callee->insns_subtotal = 0;
10288 }
10289 
10290 static void account_current_path(struct bpf_verifier_env *env)
10291 {
10292 	struct bpf_verifier_state *state = env->cur_state;
10293 	int frame;
10294 
10295 	for (frame = state->curframe; frame >= 0; frame--)
10296 		account_processed_insns(env, state->frame[frame],
10297 					frame ? state->frame[frame - 1] : NULL);
10298 }
10299 
10300 /*
10301  * Are we currently verifying the callback for an rbtree kfunc that must
10302  * be called with a lock held, or one of that callback's subprogs? If so,
10303  * no need to complain about an unreleased lock.
10304  */
10305 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10306 {
10307 	struct bpf_verifier_state *state = env->cur_state;
10308 	struct bpf_insn *insn = env->prog->insnsi;
10309 	struct bpf_func_state *callee;
10310 	int kfunc_btf_id;
10311 	u32 frame;
10312 
10313 	for (frame = state->curframe; frame; frame--) {
10314 		callee = state->frame[frame];
10315 		if (!callee->in_callback_fn)
10316 			continue;
10317 
10318 		kfunc_btf_id = insn[callee->callsite].imm;
10319 		if (is_rbtree_lock_required_kfunc(kfunc_btf_id))
10320 			return true;
10321 	}
10322 
10323 	return false;
10324 }
10325 
10326 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
10327 {
10328 	if (range.return_32bit)
10329 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
10330 	else
10331 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
10332 }
10333 
10334 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10335 {
10336 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10337 	struct bpf_func_state *caller, *callee;
10338 	struct bpf_reg_state *r0;
10339 	bool in_callback_fn;
10340 	int err;
10341 
10342 	callee = state->frame[state->curframe];
10343 	r0 = &callee->regs[BPF_REG_0];
10344 	if (r0->type == PTR_TO_STACK) {
10345 		/* technically it's ok to return caller's stack pointer
10346 		 * (or caller's caller's pointer) back to the caller,
10347 		 * since these pointers are valid. Only current stack
10348 		 * pointer will be invalid as soon as function exits,
10349 		 * but let's be conservative
10350 		 */
10351 		verbose(env, "cannot return stack pointer to the caller\n");
10352 		return -EINVAL;
10353 	}
10354 
10355 	caller = state->frame[state->curframe - 1];
10356 	if (callee->in_callback_fn) {
10357 		if (r0->type != SCALAR_VALUE) {
10358 			verbose(env, "R0 not a scalar value\n");
10359 			return -EACCES;
10360 		}
10361 
10362 		/* we are going to rely on register's precise value */
10363 		err = mark_chain_precision(env, BPF_REG_0);
10364 		if (err)
10365 			return err;
10366 
10367 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
10368 		if (!retval_range_within(callee->callback_ret_range, r0)) {
10369 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10370 					       "At callback return", "R0");
10371 			return -EINVAL;
10372 		}
10373 		if (!bpf_calls_callback(env, callee->callsite)) {
10374 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
10375 				     *insn_idx, callee->callsite);
10376 			return -EFAULT;
10377 		}
10378 	} else {
10379 		/* return to the caller whatever r0 had in the callee */
10380 		bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], r0, BPF_DIAG_MOD_WRITE);
10381 		caller->regs[BPF_REG_0] = *r0;
10382 		bpf_diag_mod_end(env);
10383 	}
10384 
10385 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10386 	 * there function call logic would reschedule callback visit. If iteration
10387 	 * converges is_state_visited() would prune that visit eventually.
10388 	 */
10389 	in_callback_fn = callee->in_callback_fn;
10390 	if (in_callback_fn)
10391 		*insn_idx = callee->callsite;
10392 	else
10393 		*insn_idx = callee->callsite + 1;
10394 
10395 	if (env->log.level & BPF_LOG_LEVEL) {
10396 		verbose(env, "returning from callee:\n");
10397 		print_verifier_state(env, state, callee->frameno, true);
10398 		verbose(env, "to caller at %d:\n", *insn_idx);
10399 		print_verifier_state(env, state, caller->frameno, true);
10400 	}
10401 	account_processed_insns(env, callee, caller);
10402 	/* clear everything in the callee. In case of exceptional exits using
10403 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10404 	free_func_state(callee);
10405 	state->frame[state->curframe--] = NULL;
10406 	invalidate_outgoing_stack_args(env, caller);
10407 
10408 	/* for callbacks widen imprecise scalars to make programs like below verify:
10409 	 *
10410 	 *   struct ctx { int i; }
10411 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10412 	 *   ...
10413 	 *   struct ctx = { .i = 0; }
10414 	 *   bpf_loop(100, cb, &ctx, 0);
10415 	 *
10416 	 * This is similar to what is done in process_iter_next_call() for open
10417 	 * coded iterators.
10418 	 */
10419 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10420 	if (prev_st) {
10421 		err = widen_imprecise_scalars(env, prev_st, state);
10422 		if (err)
10423 			return err;
10424 	}
10425 	return 0;
10426 }
10427 
10428 static int do_refine_retval_range(struct bpf_verifier_env *env,
10429 				  struct bpf_reg_state *regs, int ret_type,
10430 				  int func_id,
10431 				  struct bpf_call_arg_meta *meta)
10432 {
10433 	struct bpf_retval_range range;
10434 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10435 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10436 
10437 	if (ret_type != RET_INTEGER)
10438 		return 0;
10439 
10440 	switch (func_id) {
10441 	case BPF_FUNC_get_stack:
10442 	case BPF_FUNC_get_task_stack:
10443 	case BPF_FUNC_probe_read_str:
10444 	case BPF_FUNC_probe_read_kernel_str:
10445 	case BPF_FUNC_probe_read_user_str:
10446 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
10447 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
10448 		reg_bounds_sync(ret_reg);
10449 		break;
10450 	case BPF_FUNC_get_smp_processor_id:
10451 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
10452 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
10453 		reg_bounds_sync(ret_reg);
10454 		break;
10455 	case BPF_FUNC_get_retval:
10456 		/*
10457 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
10458 		 * CGROUP_GETSOCKOPT type.
10459 		 */
10460 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
10461 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
10462 			break;
10463 
10464 		if (prog_type == BPF_PROG_TYPE_LSM &&
10465 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10466 			if (!env->prog->aux->attach_func_proto->type)
10467 				break;
10468 			bpf_lsm_get_retval_range(env->prog, &range);
10469 		} else {
10470 			range.minval = -MAX_ERRNO;
10471 			range.maxval = 0;
10472 		}
10473 
10474 		reg_set_srange64(ret_reg, range.minval, range.maxval);
10475 		reg_set_srange32(ret_reg, range.minval, range.maxval);
10476 		reg_bounds_sync(ret_reg);
10477 		break;
10478 	}
10479 
10480 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10481 }
10482 
10483 static int
10484 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10485 		int func_id, int insn_idx)
10486 {
10487 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10488 	struct bpf_map *map = meta->map.ptr;
10489 
10490 	if (func_id != BPF_FUNC_tail_call &&
10491 	    func_id != BPF_FUNC_map_lookup_elem &&
10492 	    func_id != BPF_FUNC_map_update_elem &&
10493 	    func_id != BPF_FUNC_map_delete_elem &&
10494 	    func_id != BPF_FUNC_map_push_elem &&
10495 	    func_id != BPF_FUNC_map_pop_elem &&
10496 	    func_id != BPF_FUNC_map_peek_elem &&
10497 	    func_id != BPF_FUNC_for_each_map_elem &&
10498 	    func_id != BPF_FUNC_redirect_map &&
10499 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10500 		return 0;
10501 
10502 	if (map == NULL) {
10503 		verifier_bug(env, "expected map for helper call");
10504 		return -EFAULT;
10505 	}
10506 
10507 	/* In case of read-only, some additional restrictions
10508 	 * need to be applied in order to prevent altering the
10509 	 * state of the map from program side.
10510 	 */
10511 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10512 	    (func_id == BPF_FUNC_map_delete_elem ||
10513 	     func_id == BPF_FUNC_map_update_elem ||
10514 	     func_id == BPF_FUNC_map_push_elem ||
10515 	     func_id == BPF_FUNC_map_pop_elem)) {
10516 		verbose(env, "write into map forbidden\n");
10517 		return -EACCES;
10518 	}
10519 
10520 	if (!aux->map_ptr_state.map_ptr)
10521 		bpf_map_ptr_store(aux, meta->map.ptr,
10522 				  !meta->map.ptr->bypass_spec_v1, false);
10523 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
10524 		bpf_map_ptr_store(aux, meta->map.ptr,
10525 				  !meta->map.ptr->bypass_spec_v1, true);
10526 	return 0;
10527 }
10528 
10529 static int
10530 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10531 		int func_id, int insn_idx)
10532 {
10533 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10534 	struct bpf_reg_state *reg;
10535 	struct bpf_map *map = meta->map.ptr;
10536 	u64 val, max;
10537 	int err;
10538 
10539 	if (func_id != BPF_FUNC_tail_call)
10540 		return 0;
10541 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10542 		verbose(env, "expected prog array map for tail call");
10543 		return -EINVAL;
10544 	}
10545 
10546 	reg = reg_state(env, BPF_REG_3);
10547 	val = reg->var_off.value;
10548 	max = map->max_entries;
10549 
10550 	if (!(is_reg_const(reg, false) && val < max)) {
10551 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10552 		return 0;
10553 	}
10554 
10555 	err = mark_chain_precision(env, BPF_REG_3);
10556 	if (err)
10557 		return err;
10558 	if (bpf_map_key_unseen(aux))
10559 		bpf_map_key_store(aux, val);
10560 	else if (!bpf_map_key_poisoned(aux) &&
10561 		  bpf_map_key_immediate(aux) != val)
10562 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10563 	return 0;
10564 }
10565 
10566 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10567 {
10568 	struct bpf_verifier_state *state = env->cur_state;
10569 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10570 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
10571 	bool refs_lingering = false;
10572 	int i;
10573 
10574 	if (!exception_exit && cur_func(env)->frameno)
10575 		return 0;
10576 
10577 	for (i = 0; i < state->acquired_refs; i++) {
10578 		if (state->refs[i].type != REF_TYPE_PTR)
10579 			continue;
10580 		/* Allow struct_ops programs to return a referenced kptr back to
10581 		 * kernel. Type checks are performed later in check_return_code.
10582 		 */
10583 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
10584 		    reg->id == state->refs[i].id)
10585 			continue;
10586 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10587 			state->refs[i].id, state->refs[i].insn_idx);
10588 		bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx);
10589 		refs_lingering = true;
10590 	}
10591 	return refs_lingering ? -EINVAL : 0;
10592 }
10593 
10594 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
10595 {
10596 	int err;
10597 
10598 	if (check_lock && env->cur_state->active_locks) {
10599 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
10600 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_LOCK,
10601 				    "Release the BPF spin lock before this operation on every path.");
10602 		return -EINVAL;
10603 	}
10604 
10605 	err = check_reference_leak(env, exception_exit);
10606 	if (err) {
10607 		verbose(env, "%s would lead to reference leak\n", prefix);
10608 		return err;
10609 	}
10610 
10611 	if (check_lock && env->cur_state->active_irq_id) {
10612 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
10613 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_IRQ,
10614 				    "Restore the saved IRQ state before this operation on every path.");
10615 		return -EINVAL;
10616 	}
10617 
10618 	if (check_lock && env->cur_state->active_rcu_locks) {
10619 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
10620 		bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_RCU,
10621 				    "Call bpf_rcu_read_unlock() before this operation on every path.");
10622 		return -EINVAL;
10623 	}
10624 
10625 	if (check_lock && env->cur_state->active_preempt_locks) {
10626 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
10627 		bpf_diag_ctx_active(
10628 			env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_PREEMPT,
10629 			"Call bpf_preempt_enable() before this operation on every path.");
10630 		return -EINVAL;
10631 	}
10632 
10633 	return 0;
10634 }
10635 
10636 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10637 				   struct bpf_reg_state *regs)
10638 {
10639 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10640 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10641 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10642 	struct bpf_bprintf_data data = {};
10643 	int err, fmt_map_off, num_args;
10644 	u64 fmt_addr;
10645 	char *fmt;
10646 
10647 	/* data must be an array of u64 */
10648 	if (data_len_reg->var_off.value % 8)
10649 		return -EINVAL;
10650 	num_args = data_len_reg->var_off.value / 8;
10651 
10652 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10653 	 * and map_direct_value_addr is set.
10654 	 */
10655 	fmt_map_off = fmt_reg->var_off.value;
10656 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10657 						  fmt_map_off);
10658 	if (err) {
10659 		verbose(env, "failed to retrieve map value address\n");
10660 		return -EFAULT;
10661 	}
10662 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10663 
10664 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10665 	 * can focus on validating the format specifiers.
10666 	 */
10667 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10668 	if (err < 0)
10669 		verbose(env, "Invalid format string\n");
10670 
10671 	return err;
10672 }
10673 
10674 static int check_get_func_ip(struct bpf_verifier_env *env)
10675 {
10676 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10677 	int func_id = BPF_FUNC_get_func_ip;
10678 
10679 	if (type == BPF_PROG_TYPE_TRACING) {
10680 		if (!bpf_prog_has_trampoline(env->prog)) {
10681 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
10682 				func_id_name(func_id), func_id);
10683 			return -ENOTSUPP;
10684 		}
10685 		return 0;
10686 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10687 		return 0;
10688 	}
10689 
10690 	verbose(env, "func %s#%d not supported for program type %d\n",
10691 		func_id_name(func_id), func_id, type);
10692 	return -ENOTSUPP;
10693 }
10694 
10695 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
10696 {
10697 	return &env->insn_aux_data[env->insn_idx];
10698 }
10699 
10700 /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */
10701 static int loop_flag_is_zero(struct bpf_verifier_env *env)
10702 {
10703 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
10704 	int err;
10705 
10706 	if (!bpf_register_is_null(reg))
10707 		return 0;
10708 
10709 	err = mark_chain_precision(env, BPF_REG_4);
10710 	if (err)
10711 		return err;
10712 	return 1;
10713 }
10714 
10715 static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10716 {
10717 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10718 	int flag_is_zero;
10719 
10720 	if (!state->initialized) {
10721 		flag_is_zero = loop_flag_is_zero(env);
10722 		if (flag_is_zero < 0)
10723 			return flag_is_zero;
10724 		state->initialized = 1;
10725 		state->fit_for_inline = flag_is_zero;
10726 		state->callback_subprogno = subprogno;
10727 		return 0;
10728 	}
10729 
10730 	if (!state->fit_for_inline)
10731 		return 0;
10732 
10733 	flag_is_zero = loop_flag_is_zero(env);
10734 	if (flag_is_zero < 0)
10735 		return flag_is_zero;
10736 	state->fit_for_inline = (flag_is_zero &&
10737 				 state->callback_subprogno == subprogno);
10738 	return 0;
10739 }
10740 
10741 /* Returns whether or not the given map can potentially elide
10742  * lookup return value nullness check. This is possible if the key
10743  * is statically known.
10744  */
10745 static bool can_elide_value_nullness(const struct bpf_map *map)
10746 {
10747 	if (map->map_flags & BPF_F_INNER_MAP)
10748 		return false;
10749 
10750 	switch (map->map_type) {
10751 	case BPF_MAP_TYPE_ARRAY:
10752 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10753 		return true;
10754 	default:
10755 		return false;
10756 	}
10757 }
10758 
10759 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
10760 			 const struct bpf_func_proto **ptr)
10761 {
10762 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10763 		return -ERANGE;
10764 
10765 	if (!env->ops->get_func_proto)
10766 		return -EINVAL;
10767 
10768 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10769 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
10770 }
10771 
10772 /* Check if we're in a sleepable context. */
10773 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
10774 {
10775 	return !env->cur_state->active_rcu_locks &&
10776 	       !env->cur_state->active_preempt_locks &&
10777 	       !env->cur_state->active_locks &&
10778 	       !env->cur_state->active_irq_id &&
10779 	       in_sleepable(env);
10780 }
10781 
10782 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
10783 {
10784 	if (env->cur_state->active_rcu_locks)
10785 		return "rcu_read_lock region";
10786 	if (env->cur_state->active_preempt_locks)
10787 		return "non-preemptible region";
10788 	if (env->cur_state->active_irq_id)
10789 		return "IRQ-disabled region";
10790 	if (env->cur_state->active_locks)
10791 		return "lock region";
10792 	return "non-sleepable prog";
10793 }
10794 
10795 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
10796 		       bool convert_rcu, bool release_dynptr)
10797 {
10798 	int err = -EINVAL;
10799 
10800 	if (bpf_register_is_null(reg))
10801 		return 0;
10802 
10803 	if (release_dynptr)
10804 		err = unmark_stack_slots_dynptr(env, reg);
10805 	else if (convert_rcu)
10806 		err = ref_convert_alloc_rcu_protected(env, reg->id);
10807 	else if (reg_is_referenced(env, reg))
10808 		err = release_reference(env, reg->id);
10809 
10810 	return err;
10811 }
10812 
10813 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10814 			     int *insn_idx_p)
10815 {
10816 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10817 	bool returns_cpu_specific_alloc_ptr = false;
10818 	const struct bpf_func_proto *fn = NULL;
10819 	enum bpf_return_type ret_type;
10820 	enum bpf_type_flag ret_flag;
10821 	struct bpf_reg_state *regs;
10822 	struct bpf_call_arg_meta meta;
10823 	const char *operation;
10824 	int insn_idx = *insn_idx_p;
10825 	bool changes_data;
10826 	int i, err, func_id;
10827 
10828 	/* find function prototype */
10829 	func_id = insn->imm;
10830 	err = bpf_get_helper_proto(env, insn->imm, &fn);
10831 	if (err == -ERANGE) {
10832 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10833 		return -EINVAL;
10834 	}
10835 
10836 	if (err) {
10837 		verbose(env, "program of this type cannot use helper %s#%d\n",
10838 			func_id_name(func_id), func_id);
10839 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
10840 		bpf_diag_policy(
10841 			env, insn_idx, operation, "this program type does not allow the helper",
10842 			"Use a helper allowed for this program type, or move the logic to a compatible program type.");
10843 		return err;
10844 	}
10845 
10846 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10847 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10848 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10849 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
10850 		bpf_diag_policy(
10851 			env, insn_idx, operation,
10852 			"this helper is restricted to GPL-compatible programs",
10853 			"Use a GPL-compatible license, or replace the helper with one that is available to non-GPL programs.");
10854 		return -EINVAL;
10855 	}
10856 
10857 	if (fn->allowed && !fn->allowed(env->prog)) {
10858 		verbose(env, "helper call is not allowed in probe\n");
10859 		operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id);
10860 		bpf_diag_policy(
10861 			env, insn_idx, operation,
10862 			"the helper-specific policy callback rejected this program",
10863 			"Use the helper only from an allowed attach point or program configuration.");
10864 		return -EINVAL;
10865 	}
10866 
10867 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10868 	changes_data = bpf_helper_changes_pkt_data(func_id);
10869 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10870 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
10871 		return -EFAULT;
10872 	}
10873 
10874 	memset(&meta, 0, sizeof(meta));
10875 
10876 	err = check_func_proto(fn, &meta);
10877 	if (err) {
10878 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
10879 		return err;
10880 	}
10881 
10882 	if (fn->might_sleep && !in_sleepable_context(env)) {
10883 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
10884 			non_sleepable_context_description(env));
10885 		operation = bpf_diag_fmt(env, "sleepable helper %s#%d",
10886 					 func_id_name(func_id), func_id);
10887 		bpf_diag_ctx_forbidden(env, insn_idx, operation,
10888 			"Move the helper call outside the critical section, or use a non-sleepable helper.");
10889 		return -EINVAL;
10890 	}
10891 
10892 	/* Track non-sleepable context for helpers. */
10893 	if (!in_sleepable_context(env))
10894 		env->insn_aux_data[insn_idx].non_sleepable = true;
10895 
10896 	meta.func_id = func_id;
10897 	meta.fn = fn;
10898 	/* check args */
10899 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10900 		err = check_func_arg(env, i, &meta, insn_idx);
10901 		if (err)
10902 			return err;
10903 	}
10904 
10905 	err = record_func_map(env, &meta, func_id, insn_idx);
10906 	if (err)
10907 		return err;
10908 
10909 	err = record_func_key(env, &meta, func_id, insn_idx);
10910 	if (err)
10911 		return err;
10912 
10913 	regs = cur_regs(env);
10914 
10915 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10916 	 * is inferred from register state.
10917 	 */
10918 	for (i = 0; i < meta.arg_raw_mem.size; i++) {
10919 		err = check_mem_access(env, insn_idx, regs + meta.arg_raw_mem.regno,
10920 				       argno_from_reg(meta.arg_raw_mem.regno), i, BPF_B,
10921 				       BPF_WRITE, -1, false, false);
10922 		if (err)
10923 			return err;
10924 	}
10925 
10926 	if (meta.release_regno) {
10927 		struct bpf_reg_state *reg = &regs[meta.release_regno];
10928 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
10929 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
10930 
10931 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
10932 		if (err)
10933 			return err;
10934 	}
10935 
10936 	switch (func_id) {
10937 	case BPF_FUNC_tail_call:
10938 		err = check_resource_leak(env, false, true, "tail_call");
10939 		if (err)
10940 			return err;
10941 		break;
10942 	case BPF_FUNC_get_local_storage:
10943 		/* check that flags argument in get_local_storage(map, flags) is 0,
10944 		 * this is required because get_local_storage() can't return an error.
10945 		 */
10946 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
10947 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10948 			return -EINVAL;
10949 		}
10950 		err = mark_chain_precision(env, BPF_REG_2);
10951 		if (err)
10952 			return err;
10953 		break;
10954 	case BPF_FUNC_for_each_map_elem:
10955 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10956 					 set_map_elem_callback_state);
10957 		break;
10958 	case BPF_FUNC_timer_set_callback:
10959 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10960 					 set_timer_callback_state);
10961 		break;
10962 	case BPF_FUNC_find_vma:
10963 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10964 					 set_find_vma_callback_state);
10965 		break;
10966 	case BPF_FUNC_snprintf:
10967 		err = check_bpf_snprintf_call(env, regs);
10968 		break;
10969 	case BPF_FUNC_loop:
10970 		err = update_loop_inline_state(env, meta.subprogno);
10971 		if (err)
10972 			return err;
10973 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10974 		 * is finished, thus mark it precise.
10975 		 */
10976 		err = mark_chain_precision(env, BPF_REG_1);
10977 		if (err)
10978 			return err;
10979 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
10980 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10981 						 set_loop_callback_state);
10982 		} else {
10983 			cur_func(env)->callback_depth = 0;
10984 			if (env->log.level & BPF_LOG_LEVEL2)
10985 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10986 					env->cur_state->curframe);
10987 		}
10988 		break;
10989 	case BPF_FUNC_dynptr_from_mem:
10990 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10991 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10992 				reg_type_str(env, regs[BPF_REG_1].type));
10993 			return -EACCES;
10994 		}
10995 		break;
10996 	case BPF_FUNC_set_retval:
10997 	{
10998 		struct bpf_retval_range range = {
10999 			.minval = -MAX_ERRNO,
11000 			.maxval = 0,
11001 			.return_32bit = true
11002 		};
11003 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
11004 
11005 		if (r1->type != SCALAR_VALUE) {
11006 			verbose(env, "R1 is not a scalar\n");
11007 			return -EINVAL;
11008 		}
11009 
11010 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
11011 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
11012 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
11013 			break;
11014 
11015 		if (prog_type == BPF_PROG_TYPE_LSM &&
11016 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11017 			if (!env->prog->aux->attach_func_proto->type) {
11018 				/* Make sure programs that attach to void
11019 				 * hooks don't try to modify return value.
11020 				 */
11021 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11022 				return -EINVAL;
11023 			}
11024 			bpf_lsm_get_retval_range(env->prog, &range);
11025 		}
11026 
11027 		err = mark_chain_precision(env, BPF_REG_1);
11028 		if (err)
11029 			return err;
11030 
11031 		if (!retval_range_within(range, r1)) {
11032 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
11033 			return -EINVAL;
11034 		}
11035 
11036 		break;
11037 	}
11038 	case BPF_FUNC_dynptr_write:
11039 	{
11040 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
11041 
11042 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11043 			return -EFAULT;
11044 
11045 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11046 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11047 			/* this will trigger clear_all_pkt_pointers(), which will
11048 			 * invalidate all dynptr slices associated with the skb
11049 			 */
11050 			changes_data = true;
11051 
11052 		break;
11053 	}
11054 	case BPF_FUNC_per_cpu_ptr:
11055 	case BPF_FUNC_this_cpu_ptr:
11056 	{
11057 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11058 		const struct btf_type *type;
11059 
11060 		if (reg->type & MEM_RCU) {
11061 			type = btf_type_by_id(reg->btf, reg->btf_id);
11062 			if (!type || !btf_type_is_struct(type)) {
11063 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11064 				return -EFAULT;
11065 			}
11066 			returns_cpu_specific_alloc_ptr = true;
11067 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11068 		}
11069 		break;
11070 	}
11071 	case BPF_FUNC_user_ringbuf_drain:
11072 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11073 					 set_user_ringbuf_callback_state);
11074 		break;
11075 	}
11076 
11077 	if (err)
11078 		return err;
11079 
11080 	/* reset caller saved regs */
11081 	bpf_diag_record_caller_saved(env, regs);
11082 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
11083 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11084 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
11085 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11086 	}
11087 	invalidate_outgoing_stack_args(env, cur_func(env));
11088 
11089 	/* update return register (already marked as written above) */
11090 	ret_type = fn->ret_type;
11091 	ret_flag = type_flag(ret_type);
11092 
11093 	switch (base_type(ret_type)) {
11094 	case RET_INTEGER:
11095 		/* sets type to SCALAR_VALUE */
11096 		mark_reg_unknown(env, regs, BPF_REG_0);
11097 		break;
11098 	case RET_VOID:
11099 		regs[BPF_REG_0].type = NOT_INIT;
11100 		break;
11101 	case RET_PTR_TO_MAP_VALUE:
11102 		/* There is no offset yet applied, variable or fixed */
11103 		mark_reg_known_zero(env, regs, BPF_REG_0);
11104 		/* remember map_ptr, so that check_map_access()
11105 		 * can check 'value_size' boundary of memory access
11106 		 * to map element returned from bpf_map_lookup_elem()
11107 		 */
11108 		if (meta.map.ptr == NULL) {
11109 			verifier_bug(env, "unexpected null map_ptr");
11110 			return -EFAULT;
11111 		}
11112 
11113 		if (func_id == BPF_FUNC_map_lookup_elem &&
11114 		    can_elide_value_nullness(meta.map.ptr) &&
11115 		    meta.const_map_key >= 0 &&
11116 		    meta.const_map_key < meta.map.ptr->max_entries)
11117 			ret_flag &= ~PTR_MAYBE_NULL;
11118 
11119 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
11120 		regs[BPF_REG_0].map_uid = meta.map.uid;
11121 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11122 		if (type_may_be_null(ret_flag) ||
11123 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11124 			regs[BPF_REG_0].id = ++env->id_gen;
11125 		}
11126 		/* requires regs[BPF_REG_0].id to be set because of the map-in-map case */
11127 		refine_map_lookup_value(&regs[BPF_REG_0]);
11128 		break;
11129 	case RET_PTR_TO_SOCKET:
11130 		mark_reg_known_zero(env, regs, BPF_REG_0);
11131 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11132 		break;
11133 	case RET_PTR_TO_SOCK_COMMON:
11134 		mark_reg_known_zero(env, regs, BPF_REG_0);
11135 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11136 		break;
11137 	case RET_PTR_TO_TCP_SOCK:
11138 		mark_reg_known_zero(env, regs, BPF_REG_0);
11139 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11140 		break;
11141 	case RET_PTR_TO_MEM:
11142 		mark_reg_known_zero(env, regs, BPF_REG_0);
11143 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11144 		regs[BPF_REG_0].mem_size = meta.ret_mem.size;
11145 		break;
11146 	case RET_PTR_TO_MEM_OR_BTF_ID:
11147 	{
11148 		const struct btf_type *t;
11149 
11150 		mark_reg_known_zero(env, regs, BPF_REG_0);
11151 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11152 		if (!btf_type_is_struct(t)) {
11153 			u32 tsize;
11154 			const struct btf_type *ret;
11155 			const char *tname;
11156 
11157 			/* resolve the type size of ksym. */
11158 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11159 			if (IS_ERR(ret)) {
11160 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11161 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11162 					tname, PTR_ERR(ret));
11163 				return -EINVAL;
11164 			}
11165 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11166 			regs[BPF_REG_0].mem_size = tsize;
11167 		} else {
11168 			if (returns_cpu_specific_alloc_ptr) {
11169 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11170 			} else {
11171 				/* MEM_RDONLY may be carried from ret_flag, but it
11172 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11173 				 * it will confuse the check of PTR_TO_BTF_ID in
11174 				 * check_mem_access().
11175 				 */
11176 				ret_flag &= ~MEM_RDONLY;
11177 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11178 			}
11179 
11180 			regs[BPF_REG_0].btf = meta.ret_btf;
11181 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11182 		}
11183 		break;
11184 	}
11185 	case RET_PTR_TO_BTF_ID:
11186 	{
11187 		struct btf *ret_btf;
11188 		int ret_btf_id;
11189 
11190 		mark_reg_known_zero(env, regs, BPF_REG_0);
11191 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11192 		if (func_id == BPF_FUNC_kptr_xchg) {
11193 			ret_btf = meta.kptr_field->kptr.btf;
11194 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11195 			if (!btf_is_kernel(ret_btf)) {
11196 				regs[BPF_REG_0].type |= MEM_ALLOC;
11197 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11198 					regs[BPF_REG_0].type |= MEM_PERCPU;
11199 			}
11200 		} else {
11201 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11202 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11203 					     func_id_name(func_id));
11204 				return -EFAULT;
11205 			}
11206 			ret_btf = btf_vmlinux;
11207 			ret_btf_id = *fn->ret_btf_id;
11208 		}
11209 		if (ret_btf_id == 0) {
11210 			verbose(env, "invalid return type %u of func %s#%d\n",
11211 				base_type(ret_type), func_id_name(func_id),
11212 				func_id);
11213 			return -EINVAL;
11214 		}
11215 		regs[BPF_REG_0].btf = ret_btf;
11216 		regs[BPF_REG_0].btf_id = ret_btf_id;
11217 		break;
11218 	}
11219 	default:
11220 		verbose(env, "unknown return type %u of func %s#%d\n",
11221 			base_type(ret_type), func_id_name(func_id), func_id);
11222 		return -EINVAL;
11223 	}
11224 
11225 	if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id)
11226 		regs[BPF_REG_0].id = ++env->id_gen;
11227 
11228 	if (is_ptr_cast_function(func_id) &&
11229 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
11230 		struct bpf_verifier_state *branch;
11231 		struct bpf_reg_state *r0;
11232 
11233 		err = validate_ref_obj(env, &meta.ref_obj);
11234 		if (err)
11235 			return err;
11236 
11237 		bpf_diag_mod_end(env);
11238 
11239 		/*
11240 		 * In order for a release of any of the original or cast pointers
11241 		 * to invalidate all other pointers, reuse the same reference id for
11242 		 * the cast result.
11243 		 * This reference id can't be used for nullness propagation,
11244 		 * as cast might return NULL for a non-NULL input.
11245 		 * Hence, explore the NULL case as a separate branch.
11246 		 */
11247 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11248 		if (IS_ERR(branch))
11249 			return PTR_ERR(branch);
11250 
11251 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
11252 		__mark_reg_known_zero(r0);
11253 		r0->type = SCALAR_VALUE;
11254 
11255 		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
11256 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
11257 		regs[BPF_REG_0].id = meta.ref_obj.id;
11258 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
11259 		int id = acquire_reference(env, insn_idx, 0);
11260 
11261 		if (id < 0)
11262 			return id;
11263 
11264 		regs[BPF_REG_0].id = id;
11265 	}
11266 
11267 	if (func_id == BPF_FUNC_dynptr_data)
11268 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
11269 
11270 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11271 	if (err)
11272 		return err;
11273 
11274 	bpf_diag_mod_end(env);
11275 
11276 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
11277 	if (err)
11278 		return err;
11279 
11280 	if ((func_id == BPF_FUNC_get_stack ||
11281 	     func_id == BPF_FUNC_get_task_stack) &&
11282 	    !env->prog->has_callchain_buf) {
11283 		const char *err_str;
11284 
11285 #ifdef CONFIG_PERF_EVENTS
11286 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11287 		err_str = "cannot get callchain buffer for func %s#%d\n";
11288 #else
11289 		err = -ENOTSUPP;
11290 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11291 #endif
11292 		if (err) {
11293 			verbose(env, err_str, func_id_name(func_id), func_id);
11294 			return err;
11295 		}
11296 
11297 		env->prog->has_callchain_buf = true;
11298 	}
11299 
11300 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11301 		env->prog->call_get_stack = true;
11302 
11303 	if (func_id == BPF_FUNC_get_func_ip) {
11304 		if (check_get_func_ip(env))
11305 			return -ENOTSUPP;
11306 		env->prog->call_get_func_ip = true;
11307 	}
11308 
11309 	if (func_id == BPF_FUNC_tail_call) {
11310 		if (env->cur_state->curframe) {
11311 			struct bpf_verifier_state *branch;
11312 
11313 			/*
11314 			 * A taken tail call is modeled as a return from the current
11315 			 * frame. A callback frame cannot be left that way because
11316 			 * prepare_func_exit() would apply its return contract to the
11317 			 * unknown R0 synthesized below. Stack-depth validation rejects
11318 			 * this construct anyway.
11319 			 */
11320 			if (cur_func(env)->in_callback_fn) {
11321 				verbose(env, "cannot tail call within callback\n");
11322 				return -EINVAL;
11323 			}
11324 			mark_reg_scratched(env, BPF_REG_0);
11325 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11326 			if (IS_ERR(branch))
11327 				return PTR_ERR(branch);
11328 			clear_all_pkt_pointers(env);
11329 			mark_reg_unknown(env, regs, BPF_REG_0);
11330 			err = prepare_func_exit(env, &env->insn_idx);
11331 			if (err)
11332 				return err;
11333 			env->insn_idx--;
11334 		} else {
11335 			changes_data = false;
11336 		}
11337 	}
11338 
11339 	if (changes_data)
11340 		clear_all_pkt_pointers(env);
11341 	return 0;
11342 }
11343 
11344 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta)
11345 {
11346 	return meta->kfunc_flags & KF_ACQUIRE;
11347 }
11348 
11349 static bool is_kfunc_release(struct bpf_call_arg_meta *meta)
11350 {
11351 	return meta->kfunc_flags & KF_RELEASE;
11352 }
11353 
11354 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta)
11355 {
11356 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11357 }
11358 
11359 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta)
11360 {
11361 	return meta->kfunc_flags & KF_RCU;
11362 }
11363 
11364 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta)
11365 {
11366 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11367 }
11368 
11369 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11370 				  const struct btf_param *arg)
11371 {
11372 	const struct btf_type *t;
11373 
11374 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11375 	if (!btf_type_is_scalar(t))
11376 		return false;
11377 
11378 	return btf_param_match_suffix(btf, arg, "__sz");
11379 }
11380 
11381 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11382 					const struct btf_param *arg)
11383 {
11384 	const struct btf_type *t;
11385 
11386 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11387 	if (!btf_type_is_scalar(t))
11388 		return false;
11389 
11390 	return btf_param_match_suffix(btf, arg, "__szk");
11391 }
11392 
11393 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11394 {
11395 	return btf_param_match_suffix(btf, arg, "__k");
11396 }
11397 
11398 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11399 {
11400 	return btf_param_match_suffix(btf, arg, "__ign");
11401 }
11402 
11403 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11404 {
11405 	return btf_param_match_suffix(btf, arg, "__map");
11406 }
11407 
11408 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg)
11409 {
11410 	return btf_param_match_suffix(btf, arg, "__const_map");
11411 }
11412 
11413 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11414 {
11415 	return btf_param_match_suffix(btf, arg, "__alloc");
11416 }
11417 
11418 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11419 {
11420 	return btf_param_match_suffix(btf, arg, "__uninit");
11421 }
11422 
11423 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11424 {
11425 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11426 }
11427 
11428 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11429 {
11430 	return btf_param_match_suffix(btf, arg, "__nullable") ||
11431 	       btf_param_match_suffix(btf, arg, "__arena");
11432 }
11433 
11434 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
11435 {
11436 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
11437 }
11438 
11439 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11440 {
11441 	return btf_param_match_suffix(btf, arg, "__str");
11442 }
11443 
11444 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
11445 {
11446 	return btf_param_match_suffix(btf, arg, "__irq_flag");
11447 }
11448 
11449 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg)
11450 {
11451 	return btf_param_match_suffix(btf, arg, "__arena__nullable") ||
11452 	       btf_param_match_suffix(btf, arg, "__arena");
11453 }
11454 
11455 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11456 					  const struct btf_param *arg,
11457 					  const char *name)
11458 {
11459 	int len, target_len = strlen(name);
11460 	const char *param_name;
11461 
11462 	param_name = btf_name_by_offset(btf, arg->name_off);
11463 	if (str_is_empty(param_name))
11464 		return false;
11465 	len = strlen(param_name);
11466 	if (len != target_len)
11467 		return false;
11468 	if (strcmp(param_name, name))
11469 		return false;
11470 
11471 	return true;
11472 }
11473 
11474 enum {
11475 	KF_ARG_DYNPTR_ID,
11476 	KF_ARG_LIST_HEAD_ID,
11477 	KF_ARG_LIST_NODE_ID,
11478 	KF_ARG_RB_ROOT_ID,
11479 	KF_ARG_RB_NODE_ID,
11480 	KF_ARG_WORKQUEUE_ID,
11481 	KF_ARG_RES_SPIN_LOCK_ID,
11482 	KF_ARG_TASK_WORK_ID,
11483 	KF_ARG_PROG_AUX_ID,
11484 	KF_ARG_TIMER_ID
11485 };
11486 
11487 BTF_ID_LIST(kf_arg_btf_ids)
11488 BTF_ID(struct, bpf_dynptr)
11489 BTF_ID(struct, bpf_list_head)
11490 BTF_ID(struct, bpf_list_node)
11491 BTF_ID(struct, bpf_rb_root)
11492 BTF_ID(struct, bpf_rb_node)
11493 BTF_ID(struct, bpf_wq)
11494 BTF_ID(struct, bpf_res_spin_lock)
11495 BTF_ID(struct, bpf_task_work)
11496 BTF_ID(struct, bpf_prog_aux)
11497 BTF_ID(struct, bpf_timer)
11498 
11499 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11500 				    const struct btf_param *arg, int type)
11501 {
11502 	const struct btf_type *t;
11503 	u32 res_id;
11504 
11505 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11506 	if (!t)
11507 		return false;
11508 	if (!btf_type_is_ptr(t))
11509 		return false;
11510 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
11511 	if (!t)
11512 		return false;
11513 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11514 }
11515 
11516 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11517 {
11518 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11519 }
11520 
11521 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11522 {
11523 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11524 }
11525 
11526 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11527 {
11528 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11529 }
11530 
11531 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11532 {
11533 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11534 }
11535 
11536 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11537 {
11538 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11539 }
11540 
11541 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
11542 {
11543 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
11544 }
11545 
11546 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11547 {
11548 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11549 }
11550 
11551 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
11552 {
11553 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
11554 }
11555 
11556 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
11557 {
11558 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
11559 }
11560 
11561 static bool is_rbtree_node_type(const struct btf_type *t)
11562 {
11563 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
11564 }
11565 
11566 static bool is_list_node_type(const struct btf_type *t)
11567 {
11568 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
11569 }
11570 
11571 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11572 				  const struct btf_param *arg)
11573 {
11574 	const struct btf_type *t;
11575 
11576 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11577 	if (!t)
11578 		return false;
11579 
11580 	return true;
11581 }
11582 
11583 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
11584 {
11585 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
11586 }
11587 
11588 /*
11589  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
11590  *   - the _impl prototype with full arg list (meta->func_proto)
11591  *   - the BPF API prototype w/o implicit args (func->type in BTF)
11592  * To determine whether an argument is implicit, we compare its position
11593  * against the number of arguments in the prototype w/o implicit args.
11594  */
11595 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx)
11596 {
11597 	const struct btf_type *func, *func_proto;
11598 	u32 argn;
11599 
11600 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
11601 		return false;
11602 
11603 	func = btf_type_by_id(meta->btf, meta->func_id);
11604 	func_proto = btf_type_by_id(meta->btf, func->type);
11605 	argn = btf_type_vlen(func_proto);
11606 
11607 	return argn <= arg_idx;
11608 }
11609 
11610 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11611 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11612 					const struct btf *btf,
11613 					const struct btf_type *t, int rec)
11614 {
11615 	const struct btf_type *member_type;
11616 	const struct btf_member *member;
11617 	u32 i;
11618 
11619 	if (!btf_type_is_struct(t))
11620 		return false;
11621 
11622 	for_each_member(i, t, member) {
11623 		const struct btf_array *array;
11624 
11625 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11626 		if (btf_type_is_struct(member_type)) {
11627 			if (rec >= 3) {
11628 				verbose(env, "max struct nesting depth exceeded\n");
11629 				return false;
11630 			}
11631 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11632 				return false;
11633 			continue;
11634 		}
11635 		if (btf_type_is_array(member_type)) {
11636 			array = btf_array(member_type);
11637 			if (!array->nelems)
11638 				return false;
11639 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11640 			if (!btf_type_is_scalar(member_type))
11641 				return false;
11642 			continue;
11643 		}
11644 		if (!btf_type_is_scalar(member_type))
11645 			return false;
11646 	}
11647 	return true;
11648 }
11649 
11650 enum kfunc_ptr_arg_type {
11651 	KF_ARG_CONST_MEM_SIZE,
11652 	KF_ARG_MEM_SIZE,
11653 	KF_ARG_CONST,
11654 	KF_ARG_CONST_ALLOC_SIZE_OR_ZERO,
11655 	KF_ARG_ANYTHING,
11656 	KF_ARG_PTR_TO_CTX,
11657 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11658 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11659 	KF_ARG_PTR_TO_DYNPTR,
11660 	KF_ARG_PTR_TO_ITER,
11661 	KF_ARG_PTR_TO_LIST_HEAD,
11662 	KF_ARG_PTR_TO_LIST_NODE,
11663 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11664 	KF_ARG_PTR_TO_MEM,
11665 	KF_ARG_PTR_TO_CALLBACK,
11666 	KF_ARG_PTR_TO_RB_ROOT,
11667 	KF_ARG_PTR_TO_RB_NODE,
11668 	KF_ARG_PTR_TO_CONST_STR,
11669 	KF_ARG_CONST_MAP_PTR,
11670 	KF_ARG_PTR_TO_TIMER,
11671 	KF_ARG_PTR_TO_WORKQUEUE,
11672 	KF_ARG_PTR_TO_IRQ_FLAG,
11673 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
11674 	KF_ARG_PTR_TO_TASK_WORK,
11675 	KF_ARG_PTR_TO_ARENA,
11676 };
11677 
11678 enum special_kfunc_type {
11679 	KF_bpf_obj_new_impl,
11680 	KF_bpf_obj_new,
11681 	KF_bpf_obj_drop_impl,
11682 	KF_bpf_obj_drop,
11683 	KF_bpf_refcount_acquire_impl,
11684 	KF_bpf_refcount_acquire,
11685 	KF_bpf_list_push_front_impl,
11686 	KF_bpf_list_push_front,
11687 	KF_bpf_list_push_back_impl,
11688 	KF_bpf_list_push_back,
11689 	KF_bpf_list_add,
11690 	KF_bpf_list_pop_front,
11691 	KF_bpf_list_pop_back,
11692 	KF_bpf_list_del,
11693 	KF_bpf_list_front,
11694 	KF_bpf_list_back,
11695 	KF_bpf_list_is_first,
11696 	KF_bpf_list_is_last,
11697 	KF_bpf_list_empty,
11698 	KF_bpf_cast_to_kern_ctx,
11699 	KF_bpf_rdonly_cast,
11700 	KF_bpf_rcu_read_lock,
11701 	KF_bpf_rcu_read_unlock,
11702 	KF_bpf_rbtree_remove,
11703 	KF_bpf_rbtree_add_impl,
11704 	KF_bpf_rbtree_add,
11705 	KF_bpf_rbtree_first,
11706 	KF_bpf_rbtree_root,
11707 	KF_bpf_rbtree_left,
11708 	KF_bpf_rbtree_right,
11709 	KF_bpf_dynptr_from_skb,
11710 	KF_bpf_dynptr_from_xdp,
11711 	KF_bpf_dynptr_from_skb_meta,
11712 	KF_bpf_xdp_pull_data,
11713 	KF_bpf_dynptr_slice,
11714 	KF_bpf_dynptr_slice_rdwr,
11715 	KF_bpf_dynptr_clone,
11716 	KF_bpf_percpu_obj_new_impl,
11717 	KF_bpf_percpu_obj_new,
11718 	KF_bpf_percpu_obj_drop_impl,
11719 	KF_bpf_percpu_obj_drop,
11720 	KF_bpf_throw,
11721 	KF_bpf_wq_set_callback,
11722 	KF_bpf_preempt_disable,
11723 	KF_bpf_preempt_enable,
11724 	KF_bpf_iter_css_task_new,
11725 	KF_bpf_session_cookie,
11726 	KF_bpf_get_kmem_cache,
11727 	KF_bpf_local_irq_save,
11728 	KF_bpf_local_irq_restore,
11729 	KF_bpf_iter_num_new,
11730 	KF_bpf_iter_num_next,
11731 	KF_bpf_iter_num_destroy,
11732 	KF_bpf_set_dentry_xattr,
11733 	KF_bpf_remove_dentry_xattr,
11734 	KF_bpf_res_spin_lock,
11735 	KF_bpf_res_spin_unlock,
11736 	KF_bpf_res_spin_lock_irqsave,
11737 	KF_bpf_res_spin_unlock_irqrestore,
11738 	KF_bpf_dynptr_from_file,
11739 	KF_bpf_dynptr_file_discard,
11740 	KF___bpf_trap,
11741 	KF_bpf_task_work_schedule_signal,
11742 	KF_bpf_task_work_schedule_resume,
11743 	KF_bpf_arena_alloc_pages,
11744 	KF_bpf_arena_free_pages,
11745 	KF_bpf_session_is_return,
11746 };
11747 
11748 BTF_ID_LIST(special_kfunc_list)
11749 BTF_ID(func, bpf_obj_new_impl)
11750 BTF_ID(func, bpf_obj_new)
11751 BTF_ID(func, bpf_obj_drop_impl)
11752 BTF_ID(func, bpf_obj_drop)
11753 BTF_ID(func, bpf_refcount_acquire_impl)
11754 BTF_ID(func, bpf_refcount_acquire)
11755 BTF_ID(func, bpf_list_push_front_impl)
11756 BTF_ID(func, bpf_list_push_front)
11757 BTF_ID(func, bpf_list_push_back_impl)
11758 BTF_ID(func, bpf_list_push_back)
11759 BTF_ID(func, bpf_list_add)
11760 BTF_ID(func, bpf_list_pop_front)
11761 BTF_ID(func, bpf_list_pop_back)
11762 BTF_ID(func, bpf_list_del)
11763 BTF_ID(func, bpf_list_front)
11764 BTF_ID(func, bpf_list_back)
11765 BTF_ID(func, bpf_list_is_first)
11766 BTF_ID(func, bpf_list_is_last)
11767 BTF_ID(func, bpf_list_empty)
11768 BTF_ID(func, bpf_cast_to_kern_ctx)
11769 BTF_ID(func, bpf_rdonly_cast)
11770 BTF_ID(func, bpf_rcu_read_lock)
11771 BTF_ID(func, bpf_rcu_read_unlock)
11772 BTF_ID(func, bpf_rbtree_remove)
11773 BTF_ID(func, bpf_rbtree_add_impl)
11774 BTF_ID(func, bpf_rbtree_add)
11775 BTF_ID(func, bpf_rbtree_first)
11776 BTF_ID(func, bpf_rbtree_root)
11777 BTF_ID(func, bpf_rbtree_left)
11778 BTF_ID(func, bpf_rbtree_right)
11779 #ifdef CONFIG_NET
11780 BTF_ID(func, bpf_dynptr_from_skb)
11781 BTF_ID(func, bpf_dynptr_from_xdp)
11782 BTF_ID(func, bpf_dynptr_from_skb_meta)
11783 BTF_ID(func, bpf_xdp_pull_data)
11784 #else
11785 BTF_ID_UNUSED
11786 BTF_ID_UNUSED
11787 BTF_ID_UNUSED
11788 BTF_ID_UNUSED
11789 #endif
11790 BTF_ID(func, bpf_dynptr_slice)
11791 BTF_ID(func, bpf_dynptr_slice_rdwr)
11792 BTF_ID(func, bpf_dynptr_clone)
11793 BTF_ID(func, bpf_percpu_obj_new_impl)
11794 BTF_ID(func, bpf_percpu_obj_new)
11795 BTF_ID(func, bpf_percpu_obj_drop_impl)
11796 BTF_ID(func, bpf_percpu_obj_drop)
11797 BTF_ID(func, bpf_throw)
11798 BTF_ID(func, bpf_wq_set_callback)
11799 BTF_ID(func, bpf_preempt_disable)
11800 BTF_ID(func, bpf_preempt_enable)
11801 #ifdef CONFIG_CGROUPS
11802 BTF_ID(func, bpf_iter_css_task_new)
11803 #else
11804 BTF_ID_UNUSED
11805 #endif
11806 #ifdef CONFIG_BPF_EVENTS
11807 BTF_ID(func, bpf_session_cookie)
11808 #else
11809 BTF_ID_UNUSED
11810 #endif
11811 BTF_ID(func, bpf_get_kmem_cache)
11812 BTF_ID(func, bpf_local_irq_save)
11813 BTF_ID(func, bpf_local_irq_restore)
11814 BTF_ID(func, bpf_iter_num_new)
11815 BTF_ID(func, bpf_iter_num_next)
11816 BTF_ID(func, bpf_iter_num_destroy)
11817 #ifdef CONFIG_BPF_LSM
11818 BTF_ID(func, bpf_set_dentry_xattr)
11819 BTF_ID(func, bpf_remove_dentry_xattr)
11820 #else
11821 BTF_ID_UNUSED
11822 BTF_ID_UNUSED
11823 #endif
11824 BTF_ID(func, bpf_res_spin_lock)
11825 BTF_ID(func, bpf_res_spin_unlock)
11826 BTF_ID(func, bpf_res_spin_lock_irqsave)
11827 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
11828 BTF_ID(func, bpf_dynptr_from_file)
11829 BTF_ID(func, bpf_dynptr_file_discard)
11830 BTF_ID(func, __bpf_trap)
11831 BTF_ID(func, bpf_task_work_schedule_signal)
11832 BTF_ID(func, bpf_task_work_schedule_resume)
11833 BTF_ID(func, bpf_arena_alloc_pages)
11834 BTF_ID(func, bpf_arena_free_pages)
11835 #ifdef CONFIG_BPF_EVENTS
11836 BTF_ID(func, bpf_session_is_return)
11837 #else
11838 BTF_ID_UNUSED
11839 #endif
11840 
11841 static bool is_bpf_obj_new_kfunc(u32 func_id)
11842 {
11843 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
11844 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
11845 }
11846 
11847 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
11848 {
11849 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
11850 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
11851 }
11852 
11853 static bool is_bpf_obj_drop_kfunc(u32 func_id)
11854 {
11855 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
11856 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
11857 }
11858 
11859 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
11860 {
11861 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
11862 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
11863 }
11864 
11865 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
11866 {
11867 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
11868 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11869 }
11870 
11871 static bool is_bpf_list_push_kfunc(u32 func_id)
11872 {
11873 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
11874 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11875 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
11876 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11877 	       func_id == special_kfunc_list[KF_bpf_list_add];
11878 }
11879 
11880 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
11881 {
11882 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
11883 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11884 }
11885 
11886 static bool is_task_work_add_kfunc(u32 func_id)
11887 {
11888 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
11889 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
11890 }
11891 
11892 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta)
11893 {
11894 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
11895 		return false;
11896 
11897 	return meta->kfunc_flags & KF_RET_NULL;
11898 }
11899 
11900 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta)
11901 {
11902 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11903 }
11904 
11905 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta)
11906 {
11907 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11908 }
11909 
11910 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta)
11911 {
11912 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11913 }
11914 
11915 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta)
11916 {
11917 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11918 }
11919 
11920 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta)
11921 {
11922 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
11923 }
11924 
11925 static int
11926 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11927 		   const struct btf_param *args, int arg, int nargs)
11928 {
11929 	const struct btf_type *t, *ref_t = NULL;
11930 	argno_t argno = argno_from_arg(arg + 1);
11931 	const char *ref_tname = NULL;
11932 	int arg_type;
11933 
11934 	t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL);
11935 
11936 	/* Scalar arguments are classified from their BTF suffix/name alone. */
11937 	if (btf_type_is_scalar(t)) {
11938 		if (is_kfunc_arg_constant(meta->btf, &args[arg]))
11939 			return KF_ARG_CONST;
11940 		if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg]))
11941 			return KF_ARG_CONST_MEM_SIZE;
11942 		if (is_kfunc_arg_mem_size(meta->btf, &args[arg]))
11943 			return KF_ARG_MEM_SIZE;
11944 		if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") ||
11945 		    is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size"))
11946 			return KF_ARG_CONST_ALLOC_SIZE_OR_ZERO;
11947 		return KF_ARG_ANYTHING;
11948 	}
11949 
11950 	if (!btf_type_is_ptr(t)) {
11951 		verbose(env, "Unrecognized %s type %s\n",
11952 			reg_arg_name(env, argno), btf_type_str(t));
11953 		return -EINVAL;
11954 	}
11955 	ref_t = btf_type_skip_modifiers(meta->btf, t->type, NULL);
11956 	ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
11957 
11958 	/* In this function, we verify the kfunc's BTF as per the argument type,
11959 	 * leaving the rest of the verification with respect to the register
11960 	 * type to our caller. When a set of conditions hold in the BTF type of
11961 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11962 	 */
11963 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
11964 	    meta->func_id == special_kfunc_list[KF_bpf_session_is_return] ||
11965 	    meta->func_id == special_kfunc_list[KF_bpf_session_cookie])
11966 		arg_type = KF_ARG_PTR_TO_CTX;
11967 	else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
11968 		arg_type = KF_ARG_PTR_TO_CTX;
11969 	else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
11970 		arg_type = KF_ARG_PTR_TO_ALLOC_BTF_ID;
11971 	else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
11972 		arg_type = KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11973 	else if (is_kfunc_arg_dynptr(meta->btf, &args[arg]))
11974 		arg_type = KF_ARG_PTR_TO_DYNPTR;
11975 	else if (is_kfunc_arg_iter(meta, arg, &args[arg]))
11976 		arg_type = KF_ARG_PTR_TO_ITER;
11977 	else if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
11978 		arg_type = KF_ARG_PTR_TO_LIST_HEAD;
11979 	else if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
11980 		arg_type = KF_ARG_PTR_TO_LIST_NODE;
11981 	else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
11982 		arg_type = KF_ARG_PTR_TO_RB_ROOT;
11983 	else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
11984 		arg_type = KF_ARG_PTR_TO_RB_NODE;
11985 	else if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
11986 		arg_type = KF_ARG_PTR_TO_CONST_STR;
11987 	else if (is_kfunc_arg_const_map(meta->btf, &args[arg]))
11988 		arg_type = KF_ARG_CONST_MAP_PTR;
11989 	else if (is_kfunc_arg_map(meta->btf, &args[arg]))
11990 		arg_type = KF_ARG_PTR_TO_BTF_ID;
11991 	else if (is_kfunc_arg_wq(meta->btf, &args[arg]))
11992 		arg_type = KF_ARG_PTR_TO_WORKQUEUE;
11993 	else if (is_kfunc_arg_timer(meta->btf, &args[arg]))
11994 		arg_type = KF_ARG_PTR_TO_TIMER;
11995 	else if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
11996 		arg_type = KF_ARG_PTR_TO_TASK_WORK;
11997 	else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
11998 		arg_type = KF_ARG_PTR_TO_IRQ_FLAG;
11999 	else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
12000 		arg_type = KF_ARG_PTR_TO_RES_SPIN_LOCK;
12001 	else if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
12002 		arg_type = KF_ARG_PTR_TO_CALLBACK;
12003 	else if (is_kfunc_arg_arena(meta->btf, &args[arg])) {
12004 		if (!bpf_jit_supports_arena_args()) {
12005 			verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n",
12006 				meta->func_name);
12007 			return -ENOTSUPP;
12008 		}
12009 		if (!env->prog->aux->arena) {
12010 			verbose(env,
12011 				"%s arena pointer requires a program with an associated arena\n",
12012 				reg_arg_name(env, argno));
12013 			return -EINVAL;
12014 		}
12015 		if (reg_from_argno(argno) < 0) {
12016 			verbose(env, "%s arena pointer cannot be a stack argument\n",
12017 				reg_arg_name(env, argno));
12018 			return -EINVAL;
12019 		}
12020 		/*
12021 		 * Both suffixes accept a constant zero. The function model determines
12022 		 * whether the JIT rebases it to the arena base or preserves NULL.
12023 		 * The common nullable path below records that verifier property.
12024 		 */
12025 		arg_type = KF_ARG_PTR_TO_ARENA;
12026 	} else if (arg + 1 < nargs &&
12027 		 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) ||
12028 		  is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) {
12029 		if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) &&
12030 		    !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) {
12031 			verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n",
12032 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
12033 			return -EINVAL;
12034 		}
12035 		arg_type = KF_ARG_PTR_TO_MEM;
12036 	} else if (btf_type_is_struct(ref_t))
12037 		/* A pointer to a struct without a size argument is classified as KF_ARG_PTR_TO_BTF_ID */
12038 		arg_type = KF_ARG_PTR_TO_BTF_ID;
12039 	else {
12040 		/*
12041 		 * Otherwise this is a fixed-size memory buffer supported by
12042 		 * check_helper_mem_access(): a pointer to a scalar or a struct of
12043 		 * scalars. The access size is derived from the pointed-to BTF type.
12044 		 */
12045 		if (!btf_type_is_scalar(ref_t) &&
12046 		    !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) {
12047 			verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n",
12048 				reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname);
12049 			return -EINVAL;
12050 		}
12051 		arg_type = KF_ARG_PTR_TO_MEM | MEM_FIXED_SIZE;
12052 	}
12053 
12054 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]))
12055 		arg_type |= PTR_MAYBE_NULL;
12056 
12057 	return arg_type;
12058 }
12059 
12060 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12061 			       struct bpf_func_proto *proto)
12062 {
12063 	const struct btf *btf = meta->btf;
12064 	const struct btf_param *args;
12065 	u32 i, nargs;
12066 	int arg_type;
12067 
12068 	args = (const struct btf_param *)(meta->func_proto + 1);
12069 	nargs = btf_type_vlen(meta->func_proto);
12070 	if (nargs > MAX_BPF_FUNC_ARGS) {
12071 		verbose(env, "Function %s has %d > %d args\n", meta->func_name,
12072 			nargs, MAX_BPF_FUNC_ARGS);
12073 		return -EINVAL;
12074 	}
12075 	if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
12076 		verbose(env, "JIT does not support kfunc %s() with %d args\n",
12077 			meta->func_name, nargs);
12078 		return -ENOTSUPP;
12079 	}
12080 
12081 	for (i = 0; i < nargs; i++) {
12082 		if (is_kfunc_arg_prog_aux(btf, &args[i]) ||
12083 		    is_kfunc_arg_ignore(btf, &args[i]) ||
12084 		    is_kfunc_arg_implicit(meta, i))
12085 			continue;
12086 
12087 		arg_type = get_kfunc_arg_type(env, meta, args, i, nargs);
12088 		if (arg_type < 0)
12089 			return arg_type;
12090 
12091 		proto->arg_type[i] = arg_type;
12092 	}
12093 
12094 	return 0;
12095 }
12096 
12097 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12098 					struct bpf_reg_state *reg,
12099 					const struct btf_type *ref_t,
12100 					const char *ref_tname, u32 ref_id,
12101 					struct bpf_call_arg_meta *meta,
12102 					int arg, argno_t argno)
12103 {
12104 	const struct btf_type *reg_ref_t;
12105 	bool strict_type_match = false;
12106 	const struct btf *reg_btf;
12107 	const char *reg_ref_tname;
12108 	bool taking_projection;
12109 	bool struct_same;
12110 	u32 reg_ref_id;
12111 
12112 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12113 		reg_btf = reg->btf;
12114 		reg_ref_id = reg->btf_id;
12115 	} else {
12116 		reg_btf = btf_vmlinux;
12117 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12118 	}
12119 
12120 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12121 	 * or releasing a reference, or are no-cast aliases. We do _not_
12122 	 * enforce strict matching for kfuncs by default,
12123 	 * as we want to enable BPF programs to pass types that are bitwise
12124 	 * equivalent without forcing them to explicitly cast with something
12125 	 * like bpf_cast_to_kern_ctx().
12126 	 *
12127 	 * For example, say we had a type like the following:
12128 	 *
12129 	 * struct bpf_cpumask {
12130 	 *	cpumask_t cpumask;
12131 	 *	refcount_t usage;
12132 	 * };
12133 	 *
12134 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12135 	 * to a struct cpumask, so it would be safe to pass a struct
12136 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12137 	 *
12138 	 * The philosophy here is similar to how we allow scalars of different
12139 	 * types to be passed to kfuncs as long as the size is the same. The
12140 	 * only difference here is that we're simply allowing
12141 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12142 	 * resolve types.
12143 	 */
12144 	if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) ||
12145 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12146 		strict_type_match = true;
12147 
12148 	WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off));
12149 
12150 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12151 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12152 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value,
12153 					   meta->btf, ref_id, strict_type_match,
12154 					   !type_is_alloc(reg->type));
12155 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12156 	 * actually use it -- it must cast to the underlying type. So we allow
12157 	 * caller to pass in the underlying type.
12158 	 */
12159 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12160 	if (!taking_projection && !struct_same) {
12161 		verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
12162 			meta->func_name, reg_arg_name(env, argno),
12163 			btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno),
12164 			btf_type_str(reg_ref_t), reg_ref_tname);
12165 		return -EINVAL;
12166 	}
12167 	return 0;
12168 }
12169 
12170 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
12171 			     struct bpf_call_arg_meta *meta)
12172 {
12173 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
12174 	bool irq_save;
12175 
12176 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12177 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12178 		irq_save = true;
12179 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12180 			kfunc_class = IRQ_LOCK_KFUNC;
12181 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12182 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12183 		irq_save = false;
12184 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12185 			kfunc_class = IRQ_LOCK_KFUNC;
12186 	} else {
12187 		verifier_bug(env, "unknown irq flags kfunc");
12188 		return -EFAULT;
12189 	}
12190 
12191 	if (irq_save) {
12192 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12193 			verbose(env, "expected uninitialized irq flag as %s\n",
12194 				reg_arg_name(env, argno));
12195 			bpf_diag_res(env, env->insn_idx, "IRQ flag is already initialized",
12196 				     "Saving IRQ state requires an uninitialized stack slot for "
12197 				     "the IRQ flag, but this slot already contains tracked IRQ "
12198 				     "flag state.",
12199 				     "Use a fresh stack slot for this save operation, or restore "
12200 				     "the existing IRQ flag before reusing the slot.");
12201 			return -EINVAL;
12202 		}
12203 
12204 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
12205 				       BPF_WRITE, -1, false, false);
12206 		if (err)
12207 			return err;
12208 
12209 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12210 		if (err)
12211 			return err;
12212 	} else {
12213 		err = is_irq_flag_reg_valid_init(env, reg);
12214 		if (err) {
12215 			verbose(env, "expected an initialized irq flag as %s\n",
12216 				reg_arg_name(env, argno));
12217 			bpf_diag_res(env, env->insn_idx, "uninitialized IRQ flag restore",
12218 				     "Restoring IRQ state requires a stack slot that was "
12219 				     "initialized by a matching IRQ save operation on this path.",
12220 				     "Pass the same stack slot that was previously initialized by "
12221 				     "the matching IRQ save kfunc.");
12222 			return err;
12223 		}
12224 
12225 		spi = irq_flag_get_spi(env, reg);
12226 		if (spi < 0)
12227 			return spi;
12228 
12229 		mark_stack_slots_scratched(env, spi, 1);
12230 
12231 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12232 		if (err)
12233 			return err;
12234 
12235 		if (!in_rcu_cs(env))
12236 			invalidate_rcu_protected_refs(env);
12237 	}
12238 	return 0;
12239 }
12240 
12241 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12242 {
12243 	struct btf_record *rec = reg_btf_record(reg);
12244 
12245 	if (!env->cur_state->active_locks) {
12246 		verifier_bug(env, "%s w/o active lock", __func__);
12247 		return -EFAULT;
12248 	}
12249 
12250 	if (type_flag(reg->type) & NON_OWN_REF) {
12251 		verifier_bug(env, "NON_OWN_REF already set");
12252 		return -EFAULT;
12253 	}
12254 
12255 	reg->type |= NON_OWN_REF;
12256 	if (rec->refcount_off >= 0)
12257 		reg->type |= MEM_RCU;
12258 
12259 	return 0;
12260 }
12261 
12262 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
12263 {
12264 	struct bpf_func_state *unused;
12265 	struct bpf_reg_state *reg;
12266 	int err;
12267 
12268 	err = release_reference_nomark(env, id);
12269 	WARN_ON_ONCE(err);
12270 
12271 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12272 		if (reg->id == id) {
12273 			reg->id = 0;
12274 			ref_set_non_owning(env, reg);
12275 		}
12276 	}));
12277 
12278 	return;
12279 }
12280 
12281 /* Implementation details:
12282  *
12283  * Each register points to some region of memory, which we define as an
12284  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12285  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12286  * allocation. The lock and the data it protects are colocated in the same
12287  * memory region.
12288  *
12289  * Hence, everytime a register holds a pointer value pointing to such
12290  * allocation, the verifier preserves a unique reg->id for it.
12291  *
12292  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12293  * bpf_spin_lock is called.
12294  *
12295  * To enable this, lock state in the verifier captures two values:
12296  *	active_lock.ptr = Register's type specific pointer
12297  *	active_lock.id  = A unique ID for each register pointer value
12298  *
12299  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12300  * supported register types.
12301  *
12302  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12303  * allocated objects is the reg->btf pointer.
12304  *
12305  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12306  * can establish the provenance of the map value statically for each distinct
12307  * lookup into such maps. They always contain a single map value hence unique
12308  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12309  *
12310  * So, in case of global variables, they use array maps with max_entries = 1,
12311  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12312  * into the same map value as max_entries is 1, as described above).
12313  *
12314  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12315  * outer map pointer (in verifier context), but each lookup into an inner map
12316  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12317  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12318  * will get different reg->id assigned to each lookup, hence different
12319  * active_lock.id.
12320  *
12321  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12322  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12323  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12324  */
12325 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12326 {
12327 	struct bpf_reference_state *s;
12328 	void *ptr;
12329 	u32 id;
12330 
12331 	switch ((int)reg->type) {
12332 	case PTR_TO_MAP_VALUE:
12333 		ptr = reg->map_ptr;
12334 		break;
12335 	case PTR_TO_BTF_ID | MEM_ALLOC:
12336 		ptr = reg->btf;
12337 		break;
12338 	default:
12339 		verifier_bug(env, "unknown reg type for lock check");
12340 		return -EFAULT;
12341 	}
12342 	id = reg->id;
12343 
12344 	if (!env->cur_state->active_locks)
12345 		return -EINVAL;
12346 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12347 	if (!s) {
12348 		verbose(env, "held lock and object are not in the same allocation\n");
12349 		return -EINVAL;
12350 	}
12351 	return 0;
12352 }
12353 
12354 static bool is_bpf_list_api_kfunc(u32 btf_id)
12355 {
12356 	return is_bpf_list_push_kfunc(btf_id) ||
12357 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12358 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12359 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
12360 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12361 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
12362 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
12363 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
12364 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
12365 }
12366 
12367 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12368 {
12369 	return is_bpf_rbtree_add_kfunc(btf_id) ||
12370 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12371 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12372 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12373 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12374 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12375 }
12376 
12377 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12378 {
12379 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12380 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12381 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12382 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12383 }
12384 
12385 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset)
12386 {
12387 	struct bpf_kfunc_meta kfunc;
12388 	int err;
12389 
12390 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
12391 	if (err || !kfunc.flags)
12392 		return false;
12393 
12394 	return *kfunc.flags & KF_SPINLOCK_SAFE;
12395 }
12396 
12397 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12398 {
12399 	return is_bpf_rbtree_add_kfunc(btf_id);
12400 }
12401 
12402 static bool is_async_callback_calling_kfunc(u32 btf_id)
12403 {
12404 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
12405 	       is_task_work_add_kfunc(btf_id);
12406 }
12407 
12408 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
12409 {
12410 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12411 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12412 }
12413 
12414 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
12415 {
12416 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
12417 }
12418 
12419 static bool is_callback_calling_kfunc(u32 btf_id)
12420 {
12421 	return is_sync_callback_calling_kfunc(btf_id) ||
12422 	       is_async_callback_calling_kfunc(btf_id);
12423 }
12424 
12425 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12426 {
12427 	return is_bpf_rbtree_api_kfunc(btf_id);
12428 }
12429 
12430 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12431 					  enum btf_field_type head_field_type,
12432 					  u32 kfunc_btf_id)
12433 {
12434 	bool ret;
12435 
12436 	switch (head_field_type) {
12437 	case BPF_LIST_HEAD:
12438 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12439 		break;
12440 	case BPF_RB_ROOT:
12441 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12442 		break;
12443 	default:
12444 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12445 			btf_field_type_name(head_field_type));
12446 		return false;
12447 	}
12448 
12449 	if (!ret)
12450 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12451 			btf_field_type_name(head_field_type));
12452 	return ret;
12453 }
12454 
12455 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12456 					  enum btf_field_type node_field_type,
12457 					  u32 kfunc_btf_id)
12458 {
12459 	bool ret;
12460 
12461 	switch (node_field_type) {
12462 	case BPF_LIST_NODE:
12463 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
12464 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
12465 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
12466 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
12467 		break;
12468 	case BPF_RB_NODE:
12469 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
12470 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12471 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12472 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12473 		break;
12474 	default:
12475 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12476 			btf_field_type_name(node_field_type));
12477 		return false;
12478 	}
12479 
12480 	if (!ret)
12481 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12482 			btf_field_type_name(node_field_type));
12483 	return ret;
12484 }
12485 
12486 static int
12487 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12488 				   struct bpf_reg_state *reg, argno_t argno,
12489 				   struct bpf_call_arg_meta *meta,
12490 				   enum btf_field_type head_field_type,
12491 				   struct btf_field **head_field)
12492 {
12493 	const char *head_type_name;
12494 	struct btf_field *field;
12495 	struct btf_record *rec;
12496 	u32 head_off;
12497 
12498 	if (meta->btf != btf_vmlinux) {
12499 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12500 		return -EFAULT;
12501 	}
12502 
12503 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12504 		return -EFAULT;
12505 
12506 	head_type_name = btf_field_type_name(head_field_type);
12507 	if (!tnum_is_const(reg->var_off)) {
12508 		verbose(env,
12509 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
12510 			reg_arg_name(env, argno), head_type_name);
12511 		return -EINVAL;
12512 	}
12513 
12514 	rec = reg_btf_record(reg);
12515 	head_off = reg->var_off.value;
12516 	field = btf_record_find(rec, head_off, head_field_type);
12517 	if (!field) {
12518 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12519 		return -EINVAL;
12520 	}
12521 
12522 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12523 	if (check_reg_allocation_locked(env, reg)) {
12524 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12525 			rec->spin_lock_off, head_type_name);
12526 		return -EINVAL;
12527 	}
12528 
12529 	if (*head_field) {
12530 		verifier_bug(env, "repeating %s arg", head_type_name);
12531 		return -EFAULT;
12532 	}
12533 	*head_field = field;
12534 	return 0;
12535 }
12536 
12537 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12538 					   struct bpf_reg_state *reg, argno_t argno,
12539 					   struct bpf_call_arg_meta *meta)
12540 {
12541 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
12542 							  &meta->arg_list_head.field);
12543 }
12544 
12545 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12546 					     struct bpf_reg_state *reg, argno_t argno,
12547 					     struct bpf_call_arg_meta *meta)
12548 {
12549 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
12550 							  &meta->arg_rbtree_root.field);
12551 }
12552 
12553 static int
12554 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12555 				   struct bpf_reg_state *reg, argno_t argno,
12556 				   struct bpf_call_arg_meta *meta,
12557 				   enum btf_field_type head_field_type,
12558 				   enum btf_field_type node_field_type,
12559 				   struct btf_field **node_field)
12560 {
12561 	const char *node_type_name;
12562 	const struct btf_type *et, *t;
12563 	struct btf_field *field;
12564 	u32 node_off;
12565 
12566 	if (meta->btf != btf_vmlinux) {
12567 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12568 		return -EFAULT;
12569 	}
12570 
12571 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12572 		return -EFAULT;
12573 
12574 	node_type_name = btf_field_type_name(node_field_type);
12575 	if (!tnum_is_const(reg->var_off)) {
12576 		verbose(env,
12577 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
12578 			reg_arg_name(env, argno), node_type_name);
12579 		return -EINVAL;
12580 	}
12581 
12582 	node_off = reg->var_off.value;
12583 	field = reg_find_field_offset(reg, node_off, node_field_type);
12584 	if (!field) {
12585 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12586 		return -EINVAL;
12587 	}
12588 
12589 	field = *node_field;
12590 
12591 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12592 	t = btf_type_by_id(reg->btf, reg->btf_id);
12593 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12594 				  field->graph_root.value_btf_id, true,
12595 				  !type_is_alloc(reg->type))) {
12596 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12597 			"in struct %s, but arg is at offset=%d in struct %s\n",
12598 			btf_field_type_name(head_field_type),
12599 			btf_field_type_name(node_field_type),
12600 			field->graph_root.node_offset,
12601 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12602 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12603 		return -EINVAL;
12604 	}
12605 	meta->arg_btf = reg->btf;
12606 	meta->arg_btf_id = reg->btf_id;
12607 
12608 	if (node_off != field->graph_root.node_offset) {
12609 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12610 			node_off, btf_field_type_name(node_field_type),
12611 			field->graph_root.node_offset,
12612 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12613 		return -EINVAL;
12614 	}
12615 
12616 	return 0;
12617 }
12618 
12619 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12620 					   struct bpf_reg_state *reg, argno_t argno,
12621 					   struct bpf_call_arg_meta *meta)
12622 {
12623 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
12624 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12625 						  &meta->arg_list_head.field);
12626 }
12627 
12628 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12629 					     struct bpf_reg_state *reg, argno_t argno,
12630 					     struct bpf_call_arg_meta *meta)
12631 {
12632 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
12633 						  BPF_RB_ROOT, BPF_RB_NODE,
12634 						  &meta->arg_rbtree_root.field);
12635 }
12636 
12637 /*
12638  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12639  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12640  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12641  * them can only be attached to some specific hook points.
12642  */
12643 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12644 {
12645 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12646 
12647 	switch (prog_type) {
12648 	case BPF_PROG_TYPE_LSM:
12649 		return true;
12650 	case BPF_PROG_TYPE_TRACING:
12651 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12652 			return true;
12653 		fallthrough;
12654 	default:
12655 		return in_sleepable(env);
12656 	}
12657 }
12658 
12659 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
12660 			    int insn_idx)
12661 {
12662 	const char *func_name = meta->func_name, *ref_tname;
12663 	struct bpf_func_state *caller = cur_func(env);
12664 	struct bpf_reg_state *regs = cur_regs(env);
12665 	const struct btf *btf = meta->btf;
12666 	const struct btf_param *args;
12667 	struct btf_record *rec;
12668 	u32 i, nargs;
12669 	int ret;
12670 
12671 	args = (const struct btf_param *)(meta->func_proto + 1);
12672 	nargs = btf_type_vlen(meta->func_proto);
12673 
12674 	ret = check_outgoing_stack_args(env, caller, nargs, func_name, btf, args);
12675 	if (ret)
12676 		return ret;
12677 
12678 	/* Check that BTF function arguments match actual types that the
12679 	 * verifier sees.
12680 	 */
12681 	for (i = 0; i < nargs; i++) {
12682 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
12683 		const struct btf_type *t, *ref_t, *resolve_ret;
12684 		enum bpf_arg_type arg_type = ARG_DONTCARE;
12685 		argno_t argno = argno_from_arg(i + 1);
12686 		int regno = reg_from_argno(argno);
12687 		bool btf_id_fixed_off_ok = true;
12688 		u32 ref_id = args[i].type, type_size;
12689 		int kf_arg_type = meta->fn->arg_type[i];
12690 
12691 		if (is_kfunc_arg_prog_aux(btf, &args[i])) {
12692 			/* Reject repeated use bpf_prog_aux */
12693 			if (meta->arg_prog) {
12694 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
12695 				return -EFAULT;
12696 			}
12697 			if (regno < 0) {
12698 				verbose(env, "%s prog->aux cannot be a stack argument\n",
12699 					reg_arg_name(env, argno));
12700 				return -EINVAL;
12701 			}
12702 			meta->arg_prog = true;
12703 			cur_aux(env)->arg_prog = regno;
12704 			continue;
12705 		}
12706 
12707 		if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i))
12708 			continue;
12709 
12710 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
12711 
12712 		if (btf_type_is_ptr(t)) {
12713 			ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12714 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12715 		}
12716 
12717 		if (btf_type_is_ptr(t) &&
12718 		    (bpf_register_is_null(reg) || type_may_be_null(reg->type)) &&
12719 		    !type_may_be_null(kf_arg_type)) {
12720 			const char *expected_type;
12721 
12722 			expected_type = bpf_diag_fmt_btf_type(env, btf, args[i].type);
12723 			verbose(env, "Possibly NULL pointer passed to trusted %s\n",
12724 				reg_arg_name(env, argno));
12725 			bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12726 					      "Add a NULL check and call the kfunc only on the non-NULL path.",
12727 					      "the pointer may be NULL, but this kfunc requires a non-NULL value of type %s",
12728 					      expected_type);
12729 			return -EACCES;
12730 		}
12731 
12732 		if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) &&
12733 		    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
12734 			const char *expected_type;
12735 
12736 			expected_type = bpf_diag_fmt_btf_type(env, btf, ref_id);
12737 			verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n",
12738 				func_name, reg_arg_name(env, argno));
12739 			bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12740 					      "Pass the resource-owning pointer returned by the matching acquire kfunc, and avoid calling the release kfunc after ownership has already been transferred or released.",
12741 					      "release kfuncs require a resource-owning value of type %s returned by a matching acquire kfunc",
12742 					      expected_type);
12743 			return -EINVAL;
12744 		}
12745 
12746 		if (reg_is_referenced(env, reg))
12747 			update_ref_obj(&meta->ref_obj, reg);
12748 
12749 		if (bpf_register_is_null(reg) && type_may_be_null(kf_arg_type)) {
12750 			ret = mark_arg_precision(env, argno);
12751 			if (ret)
12752 				return ret;
12753 			continue;
12754 		}
12755 
12756 		if (is_kfunc_arg_map(btf, &args[i])) {
12757 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12758 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12759 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12760 		}
12761 
12762 		switch (base_type(kf_arg_type)) {
12763 		case KF_ARG_CONST:
12764 		case KF_ARG_CONST_MEM_SIZE:
12765 		case KF_ARG_MEM_SIZE:
12766 		case KF_ARG_ANYTHING:
12767 		case KF_ARG_CONST_ALLOC_SIZE_OR_ZERO:
12768 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12769 		case KF_ARG_PTR_TO_BTF_ID:
12770 		case KF_ARG_CONST_MAP_PTR:
12771 		case KF_ARG_PTR_TO_ITER:
12772 		case KF_ARG_PTR_TO_LIST_HEAD:
12773 		case KF_ARG_PTR_TO_LIST_NODE:
12774 		case KF_ARG_PTR_TO_RB_ROOT:
12775 		case KF_ARG_PTR_TO_RB_NODE:
12776 		case KF_ARG_PTR_TO_MEM:
12777 		case KF_ARG_PTR_TO_CALLBACK:
12778 		case KF_ARG_PTR_TO_CONST_STR:
12779 		case KF_ARG_PTR_TO_WORKQUEUE:
12780 		case KF_ARG_PTR_TO_TIMER:
12781 		case KF_ARG_PTR_TO_TASK_WORK:
12782 		case KF_ARG_PTR_TO_IRQ_FLAG:
12783 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
12784 		case KF_ARG_PTR_TO_ARENA:
12785 			break;
12786 		case KF_ARG_PTR_TO_DYNPTR:
12787 			arg_type = ARG_PTR_TO_DYNPTR;
12788 			break;
12789 		case KF_ARG_PTR_TO_CTX:
12790 			arg_type = ARG_PTR_TO_CTX;
12791 			break;
12792 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12793 			arg_type = ARG_PTR_TO_BTF_ID;
12794 			btf_id_fixed_off_ok = false;
12795 			break;
12796 		default:
12797 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
12798 			return -EFAULT;
12799 		}
12800 
12801 		if (regno == meta->release_regno)
12802 			arg_type |= OBJ_RELEASE;
12803 		ret = __check_func_arg_reg_off(env, reg, argno, arg_type,
12804 					       btf_id_fixed_off_ok);
12805 		if (ret < 0)
12806 			return ret;
12807 
12808 		switch (base_type(kf_arg_type)) {
12809 		case KF_ARG_CONST:
12810 			if (reg->type != SCALAR_VALUE) {
12811 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
12812 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12813 						      "Pass an integer scalar value for this argument, not a pointer or resource object.",
12814 						      "the kfunc expects an integer scalar, but %s is %s",
12815 						      reg_arg_name(env, argno),
12816 						      bpf_diag_reg_type_plain(env, reg->type));
12817 				return -EINVAL;
12818 			}
12819 
12820 			ret = process_const_arg(env, reg, argno, meta);
12821 			if (ret < 0) {
12822 				if (ret == -EINVAL)
12823 					bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12824 							      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
12825 							      "the kfunc requires this scalar argument to be a verifier-known constant, but %s is variable on this path",
12826 							      reg_arg_name(env, argno));
12827 				return ret;
12828 			}
12829 			break;
12830 		case KF_ARG_ANYTHING:
12831 			if (reg->type != SCALAR_VALUE) {
12832 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
12833 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12834 						      "Pass an integer scalar value for this argument, not a pointer or resource object.",
12835 						      "the kfunc expects an integer scalar, but %s is %s",
12836 						      reg_arg_name(env, argno),
12837 						      bpf_diag_reg_type_plain(env, reg->type));
12838 				return -EINVAL;
12839 			}
12840 			break;
12841 		case KF_ARG_CONST_ALLOC_SIZE_OR_ZERO:
12842 			if (reg->type != SCALAR_VALUE) {
12843 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
12844 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12845 						      "Pass an integer scalar value for this argument, not a pointer or resource object.",
12846 						      "the kfunc expects an integer scalar, but %s is %s",
12847 						      reg_arg_name(env, argno),
12848 						      bpf_diag_reg_type_plain(env, reg->type));
12849 				return -EINVAL;
12850 			}
12851 
12852 			if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size"))
12853 				meta->r0_rdonly = true;
12854 			ret = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem);
12855 			if (ret < 0) {
12856 				if (ret == -EINVAL)
12857 					bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12858 							      "Pass a verifier-known constant size for this kfunc buffer argument.",
12859 							      "the kfunc uses this argument as a return-buffer size, but %s is invalid or variable on this path",
12860 							      reg_arg_name(env, argno));
12861 				return ret;
12862 			}
12863 			break;
12864 		case KF_ARG_PTR_TO_CTX:
12865 			if (reg->type != PTR_TO_CTX) {
12866 				verbose(env, "%s expected pointer to ctx, but got %s\n",
12867 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
12868 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12869 						      "Pass the original program context pointer or preserve it before modifying registers.",
12870 						      "the kfunc expects a context pointer, but %s is %s",
12871 						      reg_arg_name(env, argno),
12872 						      bpf_diag_reg_type_plain(env, reg->type));
12873 				return -EINVAL;
12874 			}
12875 
12876 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12877 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12878 				if (ret < 0)
12879 					return -EINVAL;
12880 				meta->ret_btf_id  = ret;
12881 			}
12882 			break;
12883 		case KF_ARG_PTR_TO_ARENA:
12884 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
12885 				verbose(env, "%s is not a pointer to arena or scalar\n",
12886 					reg_arg_name(env, argno));
12887 				return -EINVAL;
12888 			}
12889 			break;
12890 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12891 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12892 				if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
12893 					verbose(env, "%s expected for bpf_obj_drop()\n",
12894 						reg_arg_name(env, argno));
12895 					return -EINVAL;
12896 				}
12897 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12898 				if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
12899 					verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
12900 						reg_arg_name(env, argno));
12901 					return -EINVAL;
12902 				}
12903 			} else {
12904 				verbose(env, "%s expected pointer to allocated object\n",
12905 					reg_arg_name(env, argno));
12906 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12907 						      "Pass a pointer returned by the matching BPF object allocation path.",
12908 						      "the kfunc expects an allocated object pointer, but %s is %s",
12909 						      reg_arg_name(env, argno),
12910 						      bpf_diag_reg_type_plain(env, reg->type));
12911 				return -EINVAL;
12912 			}
12913 			if (!reg_is_referenced(env, reg)) {
12914 				verbose(env, "allocated object must be referenced\n");
12915 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
12916 						      "Pass the owned object pointer before it is released or transferred.",
12917 						      "the allocated object pointer in %s must still carry verifier-tracked ownership, but this pointer no longer owns a live resource",
12918 						      reg_arg_name(env, argno));
12919 				return -EINVAL;
12920 			}
12921 			if (meta->btf == btf_vmlinux) {
12922 				meta->arg_btf = reg->btf;
12923 				meta->arg_btf_id = reg->btf_id;
12924 			}
12925 			break;
12926 		case KF_ARG_PTR_TO_DYNPTR:
12927 		{
12928 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12929 
12930 			if (is_kfunc_arg_uninit(btf, &args[i]))
12931 				dynptr_arg_type |= MEM_UNINIT;
12932 
12933 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12934 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12935 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12936 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12937 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
12938 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
12939 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
12940 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
12941 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
12942 				dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE;
12943 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12944 				   (dynptr_arg_type & MEM_UNINIT)) {
12945 				enum bpf_dynptr_type parent_type = meta->dynptr.type;
12946 
12947 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12948 					verifier_bug(env, "no dynptr type for parent of clone");
12949 					return -EFAULT;
12950 				}
12951 
12952 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12953 			}
12954 
12955 			ret = process_dynptr_func(env, reg, argno, insn_idx, func_name,
12956 						  dynptr_arg_type, &meta->ref_obj, &meta->dynptr);
12957 			if (ret < 0)
12958 				return ret;
12959 			break;
12960 		}
12961 		case KF_ARG_PTR_TO_ITER:
12962 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12963 				if (!check_css_task_iter_allowlist(env)) {
12964 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12965 					return -EINVAL;
12966 				}
12967 			}
12968 			ret = process_iter_arg(env, reg, argno, insn_idx, meta);
12969 			if (ret < 0)
12970 				return ret;
12971 			break;
12972 		case KF_ARG_PTR_TO_LIST_HEAD:
12973 			if (reg->type != PTR_TO_MAP_VALUE &&
12974 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12975 				verbose(env, "%s expected pointer to map value or allocated object\n",
12976 					reg_arg_name(env, argno));
12977 				return -EINVAL;
12978 			}
12979 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12980 			    !reg_is_referenced(env, reg)) {
12981 				verbose(env, "allocated object must be referenced\n");
12982 				return -EINVAL;
12983 			}
12984 			ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
12985 			if (ret < 0)
12986 				return ret;
12987 			break;
12988 		case KF_ARG_PTR_TO_RB_ROOT:
12989 			if (reg->type != PTR_TO_MAP_VALUE &&
12990 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12991 				verbose(env, "%s expected pointer to map value or allocated object\n",
12992 					reg_arg_name(env, argno));
12993 				return -EINVAL;
12994 			}
12995 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12996 			    !reg_is_referenced(env, reg)) {
12997 				verbose(env, "allocated object must be referenced\n");
12998 				return -EINVAL;
12999 			}
13000 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
13001 			if (ret < 0)
13002 				return ret;
13003 			break;
13004 		case KF_ARG_PTR_TO_LIST_NODE:
13005 			if (is_kfunc_arg_nonown_allowed(btf, &args[i]) &&
13006 			    type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) {
13007 				/* Allow bpf_list_front/back return value for
13008 				 * __nonown_allowed list-node arguments.
13009 				 */
13010 				goto check_ok;
13011 			}
13012 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13013 				verbose(env, "%s expected pointer to allocated object\n",
13014 					reg_arg_name(env, argno));
13015 				return -EINVAL;
13016 			}
13017 			if (!reg_is_referenced(env, reg)) {
13018 				verbose(env, "allocated object must be referenced\n");
13019 				return -EINVAL;
13020 			}
13021 check_ok:
13022 			ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
13023 			if (ret < 0)
13024 				return ret;
13025 			break;
13026 		case KF_ARG_PTR_TO_RB_NODE:
13027 			if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
13028 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13029 					verbose(env, "%s expected pointer to allocated object\n",
13030 						reg_arg_name(env, argno));
13031 					return -EINVAL;
13032 				}
13033 				if (!reg_is_referenced(env, reg)) {
13034 					verbose(env, "allocated object must be referenced\n");
13035 					return -EINVAL;
13036 				}
13037 			} else {
13038 				if (!type_is_non_owning_ref(reg->type) &&
13039 				    !reg_is_referenced(env, reg)) {
13040 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13041 					return -EINVAL;
13042 				}
13043 				if (in_rbtree_lock_required_cb(env)) {
13044 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13045 					return -EINVAL;
13046 				}
13047 			}
13048 
13049 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
13050 			if (ret < 0)
13051 				return ret;
13052 			break;
13053 		case KF_ARG_CONST_MAP_PTR:
13054 			if (base_type(reg->type) != CONST_PTR_TO_MAP ||
13055 			    type_may_be_null(reg->type)) {
13056 				verbose(env, "pointer in %s isn't map pointer\n",
13057 					reg_arg_name(env, argno));
13058 				return -EINVAL;
13059 			}
13060 			ret = process_map_ptr_arg(env, reg, argno, meta);
13061 			if (ret < 0)
13062 				return ret;
13063 			break;
13064 		case KF_ARG_PTR_TO_BTF_ID:
13065 			/* Only base_type is checked, further checks are done here */
13066 			if (base_type(reg->type) == PTR_TO_BTF_ID ||
13067 			    reg2btf_ids[base_type(reg->type)]) {
13068 				if (!is_trusted_reg(env, reg) ||
13069 				    bpf_type_has_unsafe_modifiers(reg->type)) {
13070 					if (!is_kfunc_rcu(meta)) {
13071 						const char *expected_type;
13072 
13073 						expected_type = bpf_diag_fmt_btf_type(env, btf, ref_id);
13074 						verbose(env, "%s must be referenced or trusted\n",
13075 							reg_arg_name(env, argno));
13076 						bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13077 								      "Pass a pointer acquired from a verifier-tracked source, or call this kfunc only inside the required protection if it accepts RCU pointers.",
13078 								      "the kfunc requires a trusted or resource-owning pointer to %s, but %s is %s",
13079 								      expected_type,
13080 								      reg_arg_name(env, argno),
13081 								      bpf_diag_reg_type_plain(env, reg->type));
13082 						return -EINVAL;
13083 					}
13084 					if (!is_rcu_reg(reg)) {
13085 						const char *expected_type;
13086 
13087 						expected_type = bpf_diag_fmt_btf_type(env, btf, ref_id);
13088 						verbose(env, "%s must be a rcu pointer\n",
13089 							reg_arg_name(env, argno));
13090 						bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13091 								      "Use this kfunc with a pointer that is valid in an RCU read lock region.",
13092 								      "the kfunc requires an RCU-protected pointer to %s, but %s is %s",
13093 								      expected_type,
13094 								      reg_arg_name(env, argno),
13095 								      bpf_diag_reg_type_plain(env, reg->type));
13096 						return -EINVAL;
13097 					}
13098 				}
13099 
13100 				ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno);
13101 				if (ret < 0)
13102 					return ret;
13103 				break;
13104 			}
13105 
13106 			if (!__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) {
13107 				enum bpf_reg_type reg2btf_type = lookup_reg2btf_ids(ref_id);
13108 				const char *expected_type;
13109 
13110 				verbose(env, "%s is %s expected %s %s",
13111 					reg_arg_name(env, argno), reg_type_str(env, reg->type),
13112 					btf_type_str(ref_t), ref_tname);
13113 				if (reg2btf_type != NOT_INIT)
13114 					verbose(env, " or %s", reg_type_str(env, reg2btf_type));
13115 				verbose(env, "\n");
13116 				expected_type = bpf_diag_fmt_btf_type(env, btf, ref_id);
13117 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13118 						      "Pass a verifier-tracked pointer to the expected kernel object type, not a pointer to stack storage or another memory buffer.",
13119 						      "the kfunc expects a pointer to %s, but this argument is %s and cannot be used as that kernel object pointer",
13120 						      expected_type,
13121 						      bpf_diag_reg_type_plain(env, reg->type));
13122 				return -EINVAL;
13123 			}
13124 
13125 			/*
13126 			 * If the register does not contain btf id but the argument type is a pointer to
13127 			 * scalar-only struct, allow verifying it as a fixed size memory.
13128 			 */
13129 			kf_arg_type = KF_ARG_PTR_TO_MEM | MEM_FIXED_SIZE;
13130 			fallthrough;
13131 		case KF_ARG_PTR_TO_MEM:
13132 			if (kf_arg_type & MEM_FIXED_SIZE) {
13133 				bool known_memory;
13134 
13135 				resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13136 				if (IS_ERR(resolve_ret)) {
13137 					verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
13138 						reg_arg_name(env, argno), btf_type_str(ref_t),
13139 						ref_tname, PTR_ERR(resolve_ret));
13140 					return -EINVAL;
13141 				}
13142 				ret = check_mem_reg(env, reg, argno, type_size, BPF_READ | BPF_WRITE,
13143 						    meta, &known_memory);
13144 				if (ret < 0) {
13145 					const char *expected_type;
13146 
13147 					expected_type = bpf_diag_fmt_btf_type(env, btf, ref_id);
13148 					if (known_memory)
13149 						bpf_diag_call_arg_fmt(
13150 							env, insn_idx, argno, func_name,
13151 							"Pass memory with at least the required number of accessible bytes and suitable read and write access.",
13152 							"the kfunc expects %u bytes of memory for %s, but the verifier cannot prove that %s provides a readable and writable range of that size",
13153 							type_size, expected_type,
13154 							bpf_diag_reg_type_plain(env, reg->type));
13155 					else
13156 						bpf_diag_call_arg_fmt(
13157 							env, insn_idx, argno, func_name,
13158 							"Pass stack, map, context, or other verifier-known memory of the expected type and size, not an integer cast to a pointer.",
13159 							"the kfunc expects %u bytes of memory for %s, but it is %s and not verifier-known memory",
13160 							type_size, expected_type,
13161 							bpf_diag_reg_type_plain(env, reg->type));
13162 					return ret;
13163 				}
13164 			}
13165 			break;
13166 		case KF_ARG_CONST_MEM_SIZE:
13167 			ret = process_const_arg(env, reg, argno, meta);
13168 			if (ret < 0) {
13169 				if (ret == -EINVAL)
13170 					bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13171 							      "Pass a compile-time constant or a value the verifier can prove is constant at this call.",
13172 							      "the kfunc requires this memory size to be a verifier-known constant, but %s is variable on this path",
13173 							      reg_arg_name(env, argno));
13174 				return ret;
13175 			}
13176 			fallthrough;
13177 		case KF_ARG_MEM_SIZE:
13178 		{
13179 			struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, i - 1);
13180 			struct bpf_reg_state *size_reg = reg;
13181 			argno_t buff_argno = argno_from_arg(i);
13182 			enum bpf_mem_size_failure failure;
13183 
13184 			if (reg->type != SCALAR_VALUE) {
13185 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
13186 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13187 						      "Pass an integer scalar length for this memory argument.",
13188 						      "the kfunc expects a scalar memory size, but %s is %s",
13189 						      reg_arg_name(env, argno),
13190 						      bpf_diag_reg_type_plain(env, reg->type));
13191 				return -EINVAL;
13192 			}
13193 
13194 			if (bpf_register_is_null(buff_reg))
13195 				break;
13196 
13197 			ret = check_mem_size_reg(env, buff_reg, size_reg, buff_argno, argno,
13198 						 BPF_READ | BPF_WRITE, true, meta, &failure);
13199 			if (ret < 0) {
13200 				const char *buff_arg, *size_arg;
13201 
13202 				buff_arg = bpf_diag_arg_name(env, buff_argno);
13203 				size_arg = bpf_diag_arg_name(env, argno);
13204 				verbose(env, "%s and ", reg_arg_name(env, buff_argno));
13205 				verbose(env, "%s memory, len pair leads to invalid memory access\n",
13206 					reg_arg_name(env, argno));
13207 				if (failure == BPF_MEM_SIZE_FAIL_MEMORY) {
13208 					bpf_diag_call_arg_fmt(env, insn_idx, buff_argno, func_name,
13209 							      "Pass a stack, map, context, or other verifier-known memory pointer, and keep the paired length within that object.",
13210 							      "it is the memory pointer in a memory/length pair with %s, but %s does not describe verifier-readable memory for the requested length",
13211 							      size_arg, buff_arg);
13212 				} else if (failure == BPF_MEM_SIZE_FAIL_SIZE) {
13213 					if (reg_smin(size_reg) < 0)
13214 						bpf_diag_call_arg_fmt(
13215 							env, insn_idx, argno, func_name,
13216 							"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
13217 							"the memory size in %s may be negative because its signed minimum is %lld",
13218 							size_arg, reg_smin(size_reg));
13219 					else
13220 						bpf_diag_call_arg_fmt(
13221 							env, insn_idx, argno, func_name,
13222 							"Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.",
13223 							"the memory size in %s may reach %llu bytes, but variable memory accesses must stay below %u bytes",
13224 							size_arg, reg_umax(size_reg), BPF_MAX_VAR_SIZ);
13225 				}
13226 				return ret;
13227 			}
13228 			break;
13229 		}
13230 		case KF_ARG_PTR_TO_CALLBACK:
13231 			if (reg->type != PTR_TO_FUNC) {
13232 				verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno));
13233 				return -EINVAL;
13234 			}
13235 			meta->subprogno = reg->subprogno;
13236 			break;
13237 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13238 			if (!type_is_ptr_alloc_obj(reg->type)) {
13239 				verbose(env, "%s is neither owning or non-owning ref\n",
13240 					reg_arg_name(env, argno));
13241 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13242 						      "Pass an owning or non-owning pointer to a BPF-managed object containing a bpf_refcount field.",
13243 						      "the kfunc expects a pointer to a BPF-managed refcounted object, but %s is %s",
13244 						      reg_arg_name(env, argno),
13245 						      bpf_diag_reg_type_plain(env, reg->type));
13246 				return -EINVAL;
13247 			}
13248 			if (!type_is_non_owning_ref(reg->type) && reg_is_referenced(env, reg))
13249 				meta->arg_owning_ref = true;
13250 
13251 			rec = reg_btf_record(reg);
13252 			if (!rec) {
13253 				verifier_bug(env, "Couldn't find btf_record");
13254 				return -EFAULT;
13255 			}
13256 
13257 			if (rec->refcount_off < 0) {
13258 				verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
13259 					reg_arg_name(env, argno));
13260 				return -EINVAL;
13261 			}
13262 
13263 			meta->arg_btf = reg->btf;
13264 			meta->arg_btf_id = reg->btf_id;
13265 			break;
13266 		case KF_ARG_PTR_TO_CONST_STR:
13267 			if (reg->type != PTR_TO_MAP_VALUE) {
13268 				verbose(env, "%s doesn't point to a const string\n",
13269 					reg_arg_name(env, argno));
13270 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13271 						      "Pass a constant string pointer that the verifier recognizes, such as a string stored in a read-only map value.",
13272 						      "the kfunc expects a pointer to a constant string stored in verifier-known memory, but %s is %s",
13273 						      reg_arg_name(env, argno),
13274 						      bpf_diag_reg_type_plain(env, reg->type));
13275 				return -EINVAL;
13276 			}
13277 			ret = check_arg_const_str(env, reg, argno);
13278 			if (ret)
13279 				return ret;
13280 			break;
13281 		case KF_ARG_PTR_TO_WORKQUEUE:
13282 			if (reg->type != PTR_TO_MAP_VALUE) {
13283 				verbose(env, "%s doesn't point to a map value\n",
13284 					reg_arg_name(env, argno));
13285 				return -EINVAL;
13286 			}
13287 			ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
13288 			if (ret < 0)
13289 				return ret;
13290 			break;
13291 		case KF_ARG_PTR_TO_TIMER:
13292 			if (reg->type != PTR_TO_MAP_VALUE) {
13293 				verbose(env, "%s doesn't point to a map value\n",
13294 					reg_arg_name(env, argno));
13295 				return -EINVAL;
13296 			}
13297 			ret = process_timer_func(env, reg, argno, &meta->map);
13298 			if (ret < 0)
13299 				return ret;
13300 			break;
13301 		case KF_ARG_PTR_TO_TASK_WORK:
13302 			if (reg->type != PTR_TO_MAP_VALUE) {
13303 				verbose(env, "%s doesn't point to a map value\n",
13304 					reg_arg_name(env, argno));
13305 				return -EINVAL;
13306 			}
13307 			ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
13308 			if (ret < 0)
13309 				return ret;
13310 			break;
13311 		case KF_ARG_PTR_TO_IRQ_FLAG:
13312 			if (reg->type != PTR_TO_STACK) {
13313 				verbose(env, "%s doesn't point to an irq flag on stack\n",
13314 					reg_arg_name(env, argno));
13315 				bpf_diag_call_arg_fmt(env, insn_idx, argno, func_name,
13316 						      "Pass the same stack slot used by bpf_local_irq_save() or bpf_res_spin_lock_irqsave().",
13317 						      "the kfunc expects a stack pointer to an IRQ flag slot, but %s is %s",
13318 						      reg_arg_name(env, argno),
13319 						      bpf_diag_reg_type_plain(env, reg->type));
13320 				return -EINVAL;
13321 			}
13322 			ret = process_irq_flag(env, reg, argno, meta);
13323 			if (ret < 0)
13324 				return ret;
13325 			break;
13326 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13327 		{
13328 			int flags = PROCESS_RES_LOCK;
13329 
13330 			if (in_rbtree_lock_required_cb(env)) {
13331 				verbose(env, "can't res_spin_{lock,unlock} in rbtree cb\n");
13332 				return -EACCES;
13333 			}
13334 
13335 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13336 				verbose(env, "%s doesn't point to map value or allocated object\n",
13337 					reg_arg_name(env, argno));
13338 				return -EINVAL;
13339 			}
13340 
13341 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13342 				return -EFAULT;
13343 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13344 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13345 				flags |= PROCESS_SPIN_LOCK;
13346 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13347 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13348 				flags |= PROCESS_LOCK_IRQ;
13349 			ret = process_spin_lock(env, reg, argno, flags);
13350 			if (ret < 0)
13351 				return ret;
13352 			break;
13353 		}
13354 		}
13355 	}
13356 
13357 	return 0;
13358 }
13359 
13360 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
13361 			     s32 func_id,
13362 			     s16 offset,
13363 			     struct bpf_call_arg_meta *meta)
13364 {
13365 	struct bpf_kfunc_meta kfunc;
13366 	int err;
13367 
13368 	memset(meta, 0, sizeof(*meta));
13369 
13370 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
13371 	if (err)
13372 		return err;
13373 
13374 	meta->btf = kfunc.btf;
13375 	meta->func_id = kfunc.id;
13376 	meta->func_proto = kfunc.proto;
13377 	meta->func_name = kfunc.name;
13378 
13379 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
13380 		return -EACCES;
13381 
13382 	meta->kfunc_flags = *kfunc.flags;
13383 
13384 	/* Only support release referenced argument passed by register */
13385 	if (is_kfunc_release(meta))
13386 		meta->release_regno = BPF_REG_1;
13387 
13388 	return 0;
13389 }
13390 
13391 /*
13392  * Determine how many bytes a helper accesses through a stack pointer at
13393  * argument position @arg (0-based, corresponding to R1-R5).
13394  *
13395  * Returns:
13396  *   > 0   known read access size in bytes
13397  *     0   doesn't read anything directly
13398  * S64_MIN unknown
13399  *   < 0   known write access of (-return) bytes
13400  */
13401 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
13402 				  int arg, int insn_idx)
13403 {
13404 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
13405 	const struct bpf_func_proto *fn;
13406 	enum bpf_arg_type at;
13407 	s64 size;
13408 
13409 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
13410 		return S64_MIN;
13411 
13412 	at = fn->arg_type[arg];
13413 
13414 	switch (base_type(at)) {
13415 	case ARG_PTR_TO_MAP_KEY:
13416 	case ARG_PTR_TO_MAP_VALUE: {
13417 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
13418 		u64 val;
13419 		int i, map_reg;
13420 
13421 		for (i = 0; i < arg; i++) {
13422 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
13423 				break;
13424 		}
13425 		if (i >= arg)
13426 			goto scan_all_maps;
13427 
13428 		map_reg = BPF_REG_1 + i;
13429 
13430 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
13431 			goto scan_all_maps;
13432 
13433 		i = aux->const_reg_vals[map_reg];
13434 		if (i < env->used_map_cnt) {
13435 			size = is_key ? env->used_maps[i]->key_size
13436 				      : env->used_maps[i]->value_size;
13437 			goto out;
13438 		}
13439 scan_all_maps:
13440 		/*
13441 		 * Map pointer is not known at this call site (e.g. different
13442 		 * maps on merged paths).  Conservatively return the largest
13443 		 * key_size or value_size across all maps used by the program.
13444 		 */
13445 		val = 0;
13446 		for (i = 0; i < env->used_map_cnt; i++) {
13447 			struct bpf_map *map = env->used_maps[i];
13448 			u32 sz = is_key ? map->key_size : map->value_size;
13449 
13450 			if (sz > val)
13451 				val = sz;
13452 			if (map->inner_map_meta) {
13453 				sz = is_key ? map->inner_map_meta->key_size
13454 					    : map->inner_map_meta->value_size;
13455 				if (sz > val)
13456 					val = sz;
13457 			}
13458 		}
13459 		if (!val)
13460 			return S64_MIN;
13461 		size = val;
13462 		goto out;
13463 	}
13464 	case ARG_PTR_TO_MEM:
13465 		if (at & MEM_FIXED_SIZE) {
13466 			size = fn->arg_size[arg];
13467 			goto out;
13468 		}
13469 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
13470 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
13471 			int size_reg = BPF_REG_1 + arg + 1;
13472 
13473 			if (aux->const_reg_mask & BIT(size_reg)) {
13474 				size = (s64)aux->const_reg_vals[size_reg];
13475 				goto out;
13476 			}
13477 			/*
13478 			 * Size arg is const on each path but differs across merged
13479 			 * paths. MAX_BPF_STACK is a safe upper bound for reads.
13480 			 */
13481 			if (at & MEM_UNINIT)
13482 				return 0;
13483 			return MAX_BPF_STACK;
13484 		}
13485 		return S64_MIN;
13486 	case ARG_PTR_TO_DYNPTR:
13487 		size = BPF_DYNPTR_SIZE;
13488 		break;
13489 	case ARG_PTR_TO_STACK:
13490 		/*
13491 		 * Only used by bpf_calls_callback() helpers. The helper itself
13492 		 * doesn't access stack. The callback subprog does and it's
13493 		 * analyzed separately.
13494 		 */
13495 		return 0;
13496 	default:
13497 		return S64_MIN;
13498 	}
13499 out:
13500 	/*
13501 	 * MEM_UNINIT args are write-only: the helper initializes the
13502 	 * buffer without reading it.
13503 	 */
13504 	if (at & MEM_UNINIT)
13505 		return -size;
13506 	return size;
13507 }
13508 
13509 /*
13510  * Determine how many bytes a kfunc accesses through a stack pointer at
13511  * argument position @arg (0-based, corresponding to R1-R5).
13512  *
13513  * Returns:
13514  *   > 0      known read access size in bytes
13515  *     0      doesn't access memory through that argument (ex: not a pointer)
13516  *   S64_MIN  unknown
13517  *   < 0      known write access of (-return) bytes
13518  */
13519 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
13520 				 int arg, int insn_idx)
13521 {
13522 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
13523 	struct bpf_call_arg_meta meta;
13524 	const struct btf_param *args;
13525 	const struct btf_type *t, *ref_t;
13526 	const struct btf *btf;
13527 	u32 nargs, type_size;
13528 	s64 size;
13529 
13530 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
13531 		return S64_MIN;
13532 
13533 	btf = meta.btf;
13534 	args = btf_params(meta.func_proto);
13535 	nargs = btf_type_vlen(meta.func_proto);
13536 	if (arg >= nargs)
13537 		return 0;
13538 
13539 	t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
13540 	if (!btf_type_is_ptr(t))
13541 		return 0;
13542 
13543 	/* dynptr: fixed 16-byte on-stack representation */
13544 	if (is_kfunc_arg_dynptr(btf, &args[arg])) {
13545 		size = BPF_DYNPTR_SIZE;
13546 		goto out;
13547 	}
13548 
13549 	/* ptr + __sz/__szk pair: size is in the next register */
13550 	if (arg + 1 < nargs &&
13551 	    (btf_param_match_suffix(btf, &args[arg + 1], "__sz") ||
13552 	     btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) {
13553 		int size_reg = BPF_REG_1 + arg + 1;
13554 
13555 		if (aux->const_reg_mask & BIT(size_reg)) {
13556 			size = (s64)aux->const_reg_vals[size_reg];
13557 			goto out;
13558 		}
13559 		return MAX_BPF_STACK;
13560 	}
13561 
13562 	/* fixed-size pointed-to type: resolve via BTF */
13563 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
13564 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
13565 		size = type_size;
13566 		goto out;
13567 	}
13568 
13569 	return S64_MIN;
13570 out:
13571 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
13572 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
13573 		return -size;
13574 	if (is_kfunc_arg_uninit(btf, &args[arg]))
13575 		return -size;
13576 	return size;
13577 }
13578 
13579 /* check special kfuncs and return:
13580  *  1  - not fall-through to 'else' branch, continue verification
13581  *  0  - fall-through to 'else' branch
13582  * < 0 - not fall-through to 'else' branch, return error
13583  */
13584 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
13585 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13586 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13587 {
13588 	const struct btf_type *ret_t;
13589 	int err = 0;
13590 
13591 	if (meta->btf != btf_vmlinux)
13592 		return 0;
13593 
13594 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
13595 		struct btf_struct_meta *struct_meta;
13596 		struct btf *ret_btf;
13597 		u32 ret_btf_id;
13598 
13599 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
13600 			return -ENOMEM;
13601 
13602 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13603 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13604 			return -EINVAL;
13605 		}
13606 
13607 		ret_btf = env->prog->aux->btf;
13608 		ret_btf_id = meta->arg_constant.value;
13609 
13610 		/* This may be NULL due to user not supplying a BTF */
13611 		if (!ret_btf) {
13612 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13613 			return -EINVAL;
13614 		}
13615 
13616 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13617 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13618 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13619 			return -EINVAL;
13620 		}
13621 
13622 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
13623 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13624 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13625 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13626 				return -EINVAL;
13627 			}
13628 
13629 			if (!bpf_global_percpu_ma_set) {
13630 				mutex_lock(&bpf_percpu_ma_lock);
13631 				if (!bpf_global_percpu_ma_set) {
13632 					/* Charge memory allocated with bpf_global_percpu_ma to
13633 					 * root memcg. The obj_cgroup for root memcg is NULL.
13634 					 */
13635 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13636 					if (!err)
13637 						bpf_global_percpu_ma_set = true;
13638 				}
13639 				mutex_unlock(&bpf_percpu_ma_lock);
13640 				if (err)
13641 					return err;
13642 			}
13643 
13644 			mutex_lock(&bpf_percpu_ma_lock);
13645 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13646 			mutex_unlock(&bpf_percpu_ma_lock);
13647 			if (err)
13648 				return err;
13649 		}
13650 
13651 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13652 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
13653 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13654 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13655 				return -EINVAL;
13656 			}
13657 
13658 			if (struct_meta) {
13659 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13660 				return -EINVAL;
13661 			}
13662 		}
13663 
13664 		mark_reg_known_zero(env, regs, BPF_REG_0);
13665 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13666 		regs[BPF_REG_0].btf = ret_btf;
13667 		regs[BPF_REG_0].btf_id = ret_btf_id;
13668 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
13669 			regs[BPF_REG_0].type |= MEM_PERCPU;
13670 
13671 		insn_aux->obj_new_size = ret_t->size;
13672 		insn_aux->kptr_struct_meta = struct_meta;
13673 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
13674 		mark_reg_known_zero(env, regs, BPF_REG_0);
13675 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13676 		regs[BPF_REG_0].btf = meta->arg_btf;
13677 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13678 
13679 		insn_aux->kptr_struct_meta =
13680 			btf_find_struct_meta(meta->arg_btf,
13681 					     meta->arg_btf_id);
13682 	} else if (is_list_node_type(ptr_type)) {
13683 		struct btf_field *field = meta->arg_list_head.field;
13684 
13685 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13686 	} else if (is_rbtree_node_type(ptr_type)) {
13687 		struct btf_field *field = meta->arg_rbtree_root.field;
13688 
13689 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13690 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13691 		mark_reg_known_zero(env, regs, BPF_REG_0);
13692 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13693 		regs[BPF_REG_0].btf = desc_btf;
13694 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13695 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13696 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13697 		if (!ret_t) {
13698 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13699 				meta->arg_constant.value);
13700 			return -EINVAL;
13701 		} else if (btf_type_is_struct(ret_t)) {
13702 			mark_reg_known_zero(env, regs, BPF_REG_0);
13703 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13704 			regs[BPF_REG_0].btf = desc_btf;
13705 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13706 		} else if (btf_type_is_void(ret_t)) {
13707 			mark_reg_known_zero(env, regs, BPF_REG_0);
13708 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13709 			regs[BPF_REG_0].mem_size = 0;
13710 		} else {
13711 			verbose(env,
13712 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13713 			return -EINVAL;
13714 		}
13715 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13716 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13717 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
13718 
13719 		mark_reg_known_zero(env, regs, BPF_REG_0);
13720 
13721 		if (!meta->arg_constant.found) {
13722 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13723 			return -EFAULT;
13724 		}
13725 
13726 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13727 
13728 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13729 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13730 
13731 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13732 			regs[BPF_REG_0].type |= MEM_RDONLY;
13733 		} else {
13734 			/* this will set env->seen_direct_write to true */
13735 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13736 				verbose(env, "the prog does not allow writes to packet data\n");
13737 				return -EINVAL;
13738 			}
13739 		}
13740 
13741 		if (!meta->dynptr.id) {
13742 			verifier_bug(env, "no dynptr id");
13743 			return -EFAULT;
13744 		}
13745 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
13746 	} else {
13747 		return 0;
13748 	}
13749 
13750 	return 1;
13751 }
13752 
13753 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13754 
13755 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13756 			    int *insn_idx_p)
13757 {
13758 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13759 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13760 	struct bpf_reg_state *regs = cur_regs(env);
13761 	const char *func_name, *ptr_type_name;
13762 	const struct btf_type *t, *ptr_type;
13763 	struct bpf_call_arg_meta meta;
13764 	struct bpf_insn_aux_data *insn_aux;
13765 	const char *operation;
13766 	int err, insn_idx = *insn_idx_p;
13767 	u32 i, nargs, ptr_type_id;
13768 	struct bpf_kfunc_desc *desc;
13769 	struct btf *desc_btf;
13770 	int id;
13771 
13772 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13773 	if (!insn->imm)
13774 		return 0;
13775 
13776 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
13777 	if (err == -EACCES && meta.func_name) {
13778 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
13779 		operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name);
13780 		bpf_diag_policy(
13781 			env, insn_idx, operation, "this program cannot call the kfunc",
13782 			"Use a kfunc allowed for this program type and attach point, or change the program context.");
13783 	}
13784 	if (err)
13785 		return err;
13786 	desc_btf = meta.btf;
13787 	func_name = meta.func_name;
13788 	insn_aux = &env->insn_aux_data[insn_idx];
13789 
13790 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13791 	if (!desc) {
13792 		verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm);
13793 		return -EFAULT;
13794 	}
13795 	meta.fn = &desc->proto;
13796 
13797 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
13798 
13799 	if (!insn->off &&
13800 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13801 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13802 		struct bpf_verifier_state *branch;
13803 		struct bpf_reg_state *regs;
13804 
13805 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13806 		if (IS_ERR(branch)) {
13807 			verbose(env, "failed to push state for failed lock acquisition\n");
13808 			return PTR_ERR(branch);
13809 		}
13810 
13811 		regs = branch->frame[branch->curframe]->regs;
13812 
13813 		/* Clear r0-r5 registers in forked state */
13814 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13815 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
13816 
13817 		mark_reg_unknown(env, regs, BPF_REG_0);
13818 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13819 		if (err) {
13820 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13821 			return err;
13822 		}
13823 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13824 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13825 		return -EFAULT;
13826 	}
13827 
13828 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13829 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13830 		operation = bpf_diag_fmt(env, "destructive kfunc %s", meta.func_name);
13831 		bpf_diag_policy(
13832 			env, insn_idx, operation, "destructive kfuncs require CAP_SYS_BOOT",
13833 			"Load the program with CAP_SYS_BOOT, or avoid destructive kfuncs.");
13834 		return -EACCES;
13835 	}
13836 
13837 	sleepable = bpf_is_kfunc_sleepable(&meta);
13838 	if (sleepable && !in_sleepable(env)) {
13839 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13840 		operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name);
13841 		bpf_diag_ctx_forbidden(env, insn_idx, operation,
13842 			"Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc.");
13843 		return -EACCES;
13844 	}
13845 
13846 	/* Track non-sleepable context for kfuncs, same as for helpers. */
13847 	if (!in_sleepable_context(env))
13848 		insn_aux->non_sleepable = true;
13849 
13850 	/* Check the arguments */
13851 	err = check_kfunc_args(env, &meta, insn_idx);
13852 	if (err < 0)
13853 		return err;
13854 
13855 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
13856 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
13857 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
13858 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
13859 	      && !env->prog->sleepable))) {
13860 		struct btf_struct_meta *struct_meta;
13861 
13862 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13863 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
13864 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
13865 				func_name);
13866 			return -EINVAL;
13867 		}
13868 	}
13869 
13870 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
13871 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13872 					 set_rbtree_add_callback_state);
13873 		if (err) {
13874 			verbose(env, "kfunc %s#%d failed callback verification\n",
13875 				func_name, meta.func_id);
13876 			return err;
13877 		}
13878 	}
13879 
13880 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
13881 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13882 					 set_timer_callback_state);
13883 		if (err) {
13884 			verbose(env, "kfunc %s#%d failed callback verification\n",
13885 				func_name, meta.func_id);
13886 			return err;
13887 		}
13888 	}
13889 
13890 	if (is_task_work_add_kfunc(meta.func_id)) {
13891 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13892 					 set_task_work_schedule_callback_state);
13893 		if (err) {
13894 			verbose(env, "kfunc %s#%d failed callback verification\n",
13895 				func_name, meta.func_id);
13896 			return err;
13897 		}
13898 	}
13899 
13900 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13901 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13902 
13903 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13904 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13905 
13906 	if (rcu_lock) {
13907 		env->cur_state->active_rcu_locks++;
13908 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true,
13909 					env->cur_state->active_rcu_locks);
13910 	} else if (rcu_unlock) {
13911 		if (env->cur_state->active_rcu_locks == 0) {
13912 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13913 			bpf_diag_ctx_underflow(
13914 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
13915 				"Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region.");
13916 			return -EINVAL;
13917 		}
13918 		env->cur_state->active_rcu_locks--;
13919 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
13920 					env->cur_state->active_rcu_locks);
13921 		if (!in_rcu_cs(env))
13922 			invalidate_rcu_protected_refs(env);
13923 	} else if (preempt_disable) {
13924 		env->cur_state->active_preempt_locks++;
13925 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true,
13926 					env->cur_state->active_preempt_locks);
13927 	} else if (preempt_enable) {
13928 		if (env->cur_state->active_preempt_locks == 0) {
13929 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13930 			bpf_diag_ctx_underflow(
13931 				env, insn_idx, func_name, BPF_DIAG_CONTEXT_PREEMPT,
13932 				"Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption.");
13933 			return -EINVAL;
13934 		}
13935 		env->cur_state->active_preempt_locks--;
13936 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
13937 					env->cur_state->active_preempt_locks);
13938 		if (!in_rcu_cs(env))
13939 			invalidate_rcu_protected_refs(env);
13940 	}
13941 
13942 	if (sleepable && !in_sleepable_context(env)) {
13943 		verbose(env, "kernel func %s is sleepable within %s\n",
13944 			func_name, non_sleepable_context_description(env));
13945 		operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name);
13946 		bpf_diag_ctx_forbidden(env, insn_idx, operation,
13947 			"Move the kfunc call outside the critical section, or use a non-sleepable kfunc.");
13948 		return -EACCES;
13949 	}
13950 
13951 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13952 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13953 		return -EACCES;
13954 	}
13955 
13956 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13957 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13958 		bpf_diag_ctx_required(
13959 			env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU,
13960 			"Call this kfunc between bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced.");
13961 		return -EACCES;
13962 	}
13963 
13964 	/* In case of release function, we get register number of refcounted
13965 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13966 	 */
13967 	if (meta.release_regno) {
13968 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
13969 		if (err)
13970 			return err;
13971 	}
13972 
13973 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
13974 		id = regs[BPF_REG_2].id;
13975 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
13976 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13977 		ref_convert_owning_non_owning(env, id);
13978 	}
13979 
13980 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13981 		if (!bpf_jit_supports_exceptions()) {
13982 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13983 				func_name, meta.func_id);
13984 			return -ENOTSUPP;
13985 		}
13986 		env->seen_exception = true;
13987 
13988 		/* In the case of the default callback, the cookie value passed
13989 		 * to bpf_throw becomes the return value of the program.
13990 		 */
13991 		if (!env->exception_callback_subprog) {
13992 			err = check_return_code(env, BPF_REG_1, "R1");
13993 			if (err < 0)
13994 				return err;
13995 		}
13996 	}
13997 
13998 	bpf_diag_record_caller_saved(env, regs);
13999 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
14000 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14001 		u32 regno = caller_saved[i];
14002 
14003 		bpf_mark_reg_not_init(env, &regs[regno]);
14004 	}
14005 	invalidate_outgoing_stack_args(env, cur_func(env));
14006 
14007 	/* Check return type */
14008 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14009 
14010 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14011 		if (meta.btf != btf_vmlinux ||
14012 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
14013 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
14014 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
14015 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14016 			return -EINVAL;
14017 		}
14018 	}
14019 
14020 	if (btf_type_is_scalar(t)) {
14021 		mark_reg_unknown(env, regs, BPF_REG_0);
14022 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14023 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14024 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14025 	} else if (btf_type_is_ptr(t)) {
14026 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14027 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14028 		if (err) {
14029 			if (err < 0)
14030 				return err;
14031 		} else if (btf_type_is_void(ptr_type)) {
14032 			/* kfunc returning 'void *' is equivalent to returning scalar */
14033 			mark_reg_unknown(env, regs, BPF_REG_0);
14034 		} else if (!__btf_type_is_struct(ptr_type)) {
14035 			if (!meta.ret_mem.found) {
14036 				__u32 sz;
14037 
14038 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14039 					meta.ret_mem.found = true;
14040 					meta.ret_mem.size = sz;
14041 					meta.r0_rdonly = true;
14042 				}
14043 
14044 				if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
14045 					meta.r0_rdonly = false;
14046 			}
14047 			if (!meta.ret_mem.found) {
14048 				ptr_type_name = btf_name_by_offset(desc_btf,
14049 								   ptr_type->name_off);
14050 				verbose(env,
14051 					"kernel function %s returns pointer type %s %s is not supported\n",
14052 					func_name,
14053 					btf_type_str(ptr_type),
14054 					ptr_type_name);
14055 				return -EINVAL;
14056 			}
14057 
14058 			mark_reg_known_zero(env, regs, BPF_REG_0);
14059 			regs[BPF_REG_0].type = PTR_TO_MEM;
14060 			regs[BPF_REG_0].mem_size = meta.ret_mem.size;
14061 
14062 			if (meta.r0_rdonly)
14063 				regs[BPF_REG_0].type |= MEM_RDONLY;
14064 
14065 			/* Ensures we don't access the memory after a release_reference() */
14066 			if (meta.ref_obj.id) {
14067 				err = validate_ref_obj(env, &meta.ref_obj);
14068 				if (err)
14069 					return err;
14070 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
14071 			}
14072 
14073 			if (is_kfunc_rcu_protected(&meta))
14074 				regs[BPF_REG_0].type |= MEM_RCU;
14075 		} else {
14076 			enum bpf_reg_type type = PTR_TO_BTF_ID;
14077 
14078 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14079 				type |= PTR_UNTRUSTED;
14080 			else if (is_kfunc_rcu_protected(&meta) ||
14081 				 (bpf_is_iter_next_kfunc(&meta) &&
14082 				  (get_iter_from_state(env->cur_state, &meta)
14083 					   ->type & MEM_RCU))) {
14084 				/*
14085 				 * If the iterator's constructor (the _new
14086 				 * function e.g., bpf_iter_task_new) has been
14087 				 * annotated with BPF kfunc flag
14088 				 * KF_RCU_PROTECTED and was called within a RCU
14089 				 * read-side critical section, also propagate
14090 				 * the MEM_RCU flag to the pointer returned from
14091 				 * the iterator's next function (e.g.,
14092 				 * bpf_iter_task_next).
14093 				 */
14094 				type |= MEM_RCU;
14095 			} else {
14096 				/*
14097 				 * Any PTR_TO_BTF_ID that is returned from a BPF
14098 				 * kfunc should by default be treated as
14099 				 * implicitly trusted.
14100 				 */
14101 				type |= PTR_TRUSTED;
14102 			}
14103 
14104 			mark_reg_known_zero(env, regs, BPF_REG_0);
14105 			regs[BPF_REG_0].btf = desc_btf;
14106 			regs[BPF_REG_0].type = type;
14107 			regs[BPF_REG_0].btf_id = ptr_type_id;
14108 		}
14109 
14110 		if (is_kfunc_ret_null(&meta)) {
14111 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14112 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14113 			regs[BPF_REG_0].id = ++env->id_gen;
14114 		}
14115 		if (is_kfunc_acquire(&meta)) {
14116 			id = acquire_reference(env, insn_idx, 0);
14117 			if (id < 0)
14118 				return id;
14119 			regs[BPF_REG_0].id = id;
14120 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14121 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14122 		}
14123 
14124 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14125 			regs[BPF_REG_0].id = ++env->id_gen;
14126 	} else if (btf_type_is_void(t)) {
14127 		if (meta.btf == btf_vmlinux) {
14128 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
14129 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
14130 				insn_aux->kptr_struct_meta =
14131 					btf_find_struct_meta(meta.arg_btf,
14132 							     meta.arg_btf_id);
14133 			}
14134 		}
14135 	}
14136 
14137 	if (bpf_is_kfunc_pkt_changing(&meta))
14138 		clear_all_pkt_pointers(env);
14139 
14140 	nargs = btf_type_vlen(meta.func_proto);
14141 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
14142 		struct bpf_func_state *caller = cur_func(env);
14143 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
14144 		u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS;
14145 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
14146 
14147 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
14148 			caller_info->stack_arg_cnt = stack_arg_cnt;
14149 	}
14150 
14151 	/*
14152 	 * Record R0 before process_iter_next_call() snapshots the alternate
14153 	 * iterator path's diagnostic position.
14154 	 */
14155 	bpf_diag_mod_end(env);
14156 
14157 	if (bpf_is_iter_next_kfunc(&meta)) {
14158 		err = process_iter_next_call(env, insn_idx, &meta);
14159 		if (err)
14160 			return err;
14161 	}
14162 
14163 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
14164 		env->prog->call_session_cookie = true;
14165 
14166 	if (bpf_is_throw_kfunc(insn))
14167 		return process_bpf_exit_full(env, NULL, true);
14168 
14169 	return 0;
14170 }
14171 
14172 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
14173 					 const struct bpf_reg_state *reg,
14174 					 enum bpf_reg_type type)
14175 {
14176 	bool known = tnum_is_const(reg->var_off);
14177 	s64 val = reg->var_off.value;
14178 	s64 smin = reg_smin(reg);
14179 
14180 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14181 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14182 			reg_type_str(env, type), val);
14183 		return false;
14184 	}
14185 
14186 	if (smin == S64_MIN) {
14187 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14188 			reg_type_str(env, type));
14189 		return false;
14190 	}
14191 
14192 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14193 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14194 			smin, reg_type_str(env, type));
14195 		return false;
14196 	}
14197 
14198 	return true;
14199 }
14200 
14201 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
14202 				      const struct bpf_reg_state *reg,
14203 				      enum bpf_reg_type type)
14204 {
14205 	bool known = tnum_is_const(reg->var_off);
14206 	s64 val = reg->var_off.value;
14207 	s64 smin = reg_smin(reg);
14208 
14209 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14210 		verbose(env, "%s pointer offset %lld is not allowed\n",
14211 			reg_type_str(env, type), val);
14212 		return false;
14213 	}
14214 
14215 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14216 		verbose(env, "%s pointer offset %lld is not allowed\n",
14217 			reg_type_str(env, type), smin);
14218 		return false;
14219 	}
14220 
14221 	return true;
14222 }
14223 
14224 enum {
14225 	REASON_BOUNDS	= -1,
14226 	REASON_TYPE	= -2,
14227 	REASON_PATHS	= -3,
14228 	REASON_LIMIT	= -4,
14229 	REASON_STACK	= -5,
14230 };
14231 
14232 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14233 			      u32 *alu_limit, bool mask_to_left)
14234 {
14235 	u32 max = 0, ptr_limit = 0;
14236 
14237 	switch (ptr_reg->type) {
14238 	case PTR_TO_STACK:
14239 		/* Offset 0 is out-of-bounds, but acceptable start for the
14240 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14241 		 * offset where we would need to deal with min/max bounds is
14242 		 * currently prohibited for unprivileged.
14243 		 */
14244 		max = MAX_BPF_STACK + mask_to_left;
14245 		ptr_limit = -ptr_reg->var_off.value;
14246 		break;
14247 	case PTR_TO_MAP_VALUE:
14248 		max = ptr_reg->map_ptr->value_size;
14249 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
14250 		break;
14251 	default:
14252 		return REASON_TYPE;
14253 	}
14254 
14255 	if (ptr_limit >= max)
14256 		return REASON_LIMIT;
14257 	*alu_limit = ptr_limit;
14258 	return 0;
14259 }
14260 
14261 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14262 				    const struct bpf_insn *insn)
14263 {
14264 	return env->bypass_spec_v1 ||
14265 		BPF_SRC(insn->code) == BPF_K ||
14266 		cur_aux(env)->nospec;
14267 }
14268 
14269 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14270 				       u32 alu_state, u32 alu_limit)
14271 {
14272 	/* If we arrived here from different branches with different
14273 	 * state or limits to sanitize, then this won't work.
14274 	 */
14275 	if (aux->alu_state &&
14276 	    (aux->alu_state != alu_state ||
14277 	     aux->alu_limit != alu_limit))
14278 		return REASON_PATHS;
14279 
14280 	/* Corresponding fixup done in do_misc_fixups(). */
14281 	aux->alu_state = alu_state;
14282 	aux->alu_limit = alu_limit;
14283 	return 0;
14284 }
14285 
14286 static int sanitize_val_alu(struct bpf_verifier_env *env,
14287 			    struct bpf_insn *insn)
14288 {
14289 	struct bpf_insn_aux_data *aux = cur_aux(env);
14290 
14291 	if (can_skip_alu_sanitation(env, insn))
14292 		return 0;
14293 
14294 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14295 }
14296 
14297 static bool sanitize_needed(u8 opcode)
14298 {
14299 	return opcode == BPF_ADD || opcode == BPF_SUB;
14300 }
14301 
14302 struct bpf_sanitize_info {
14303 	struct bpf_insn_aux_data aux;
14304 	bool mask_to_left;
14305 };
14306 
14307 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14308 				     const struct bpf_insn *insn,
14309 				     u32 next_idx, u32 curr_idx)
14310 {
14311 	struct bpf_verifier_state *branch;
14312 	struct bpf_reg_state *regs;
14313 
14314 	branch = push_stack(env, next_idx, curr_idx, true);
14315 	if (!IS_ERR(branch) && insn) {
14316 		regs = branch->frame[branch->curframe]->regs;
14317 		if (BPF_SRC(insn->code) == BPF_K) {
14318 			mark_reg_unknown(env, regs, insn->dst_reg);
14319 		} else if (BPF_SRC(insn->code) == BPF_X) {
14320 			mark_reg_unknown(env, regs, insn->dst_reg);
14321 			mark_reg_unknown(env, regs, insn->src_reg);
14322 		}
14323 	}
14324 	return PTR_ERR_OR_ZERO(branch);
14325 }
14326 
14327 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14328 			    struct bpf_insn *insn,
14329 			    const struct bpf_reg_state *ptr_reg,
14330 			    const struct bpf_reg_state *off_reg,
14331 			    struct bpf_reg_state *dst_reg,
14332 			    struct bpf_sanitize_info *info,
14333 			    const bool commit_window)
14334 {
14335 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14336 	struct bpf_verifier_state *vstate = env->cur_state;
14337 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14338 	bool off_is_neg = reg_smin(off_reg) < 0;
14339 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14340 	u8 opcode = BPF_OP(insn->code);
14341 	u32 alu_state, alu_limit;
14342 	struct bpf_reg_state tmp;
14343 	int err;
14344 
14345 	if (can_skip_alu_sanitation(env, insn))
14346 		return 0;
14347 
14348 	/* We already marked aux for masking from non-speculative
14349 	 * paths, thus we got here in the first place. We only care
14350 	 * to explore bad access from here.
14351 	 */
14352 	if (vstate->speculative)
14353 		goto do_sim;
14354 
14355 	if (!commit_window) {
14356 		if (!tnum_is_const(off_reg->var_off) &&
14357 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
14358 			return REASON_BOUNDS;
14359 
14360 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14361 				     (opcode == BPF_SUB && !off_is_neg);
14362 	}
14363 
14364 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14365 	if (err < 0)
14366 		return err;
14367 
14368 	if (commit_window) {
14369 		/* In commit phase we narrow the masking window based on
14370 		 * the observed pointer move after the simulated operation.
14371 		 */
14372 		alu_state = info->aux.alu_state;
14373 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14374 	} else {
14375 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14376 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14377 		alu_state |= ptr_is_dst_reg ?
14378 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14379 
14380 		/* Limit pruning on unknown scalars to enable deep search for
14381 		 * potential masking differences from other program paths.
14382 		 */
14383 		if (!off_is_imm)
14384 			env->explore_alu_limits = true;
14385 	}
14386 
14387 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14388 	if (err < 0)
14389 		return err;
14390 do_sim:
14391 	/* If we're in commit phase, we're done here given we already
14392 	 * pushed the truncated dst_reg into the speculative verification
14393 	 * stack.
14394 	 *
14395 	 * Also, when register is a known constant, we rewrite register-based
14396 	 * operation to immediate-based, and thus do not need masking (and as
14397 	 * a consequence, do not need to simulate the zero-truncation either).
14398 	 */
14399 	if (commit_window || off_is_imm)
14400 		return 0;
14401 
14402 	/* Simulate and find potential out-of-bounds access under
14403 	 * speculative execution from truncation as a result of
14404 	 * masking when off was not within expected range. If off
14405 	 * sits in dst, then we temporarily need to move ptr there
14406 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14407 	 * for cases where we use K-based arithmetic in one direction
14408 	 * and truncated reg-based in the other in order to explore
14409 	 * bad access.
14410 	 */
14411 	if (!ptr_is_dst_reg) {
14412 		tmp = *dst_reg;
14413 		*dst_reg = *ptr_reg;
14414 	}
14415 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14416 	if (err < 0)
14417 		return REASON_STACK;
14418 	if (!ptr_is_dst_reg)
14419 		*dst_reg = tmp;
14420 	return 0;
14421 }
14422 
14423 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14424 {
14425 	struct bpf_verifier_state *vstate = env->cur_state;
14426 
14427 	/* If we simulate paths under speculation, we don't update the
14428 	 * insn as 'seen' such that when we verify unreachable paths in
14429 	 * the non-speculative domain, sanitize_dead_code() can still
14430 	 * rewrite/sanitize them.
14431 	 */
14432 	if (!vstate->speculative)
14433 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14434 }
14435 
14436 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason)
14437 {
14438 	static const char *err = "pointer arithmetic with it prohibited for !root";
14439 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14440 	u32 dst = insn->dst_reg, src = insn->src_reg;
14441 	struct bpf_reg_state *regs = cur_regs(env);
14442 
14443 	switch (reason) {
14444 	case REASON_BOUNDS:
14445 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14446 			regs[src].type == SCALAR_VALUE ? src : dst, err);
14447 		break;
14448 	case REASON_TYPE:
14449 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14450 			regs[src].type == SCALAR_VALUE ? dst : src, err);
14451 		break;
14452 	case REASON_PATHS:
14453 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14454 			dst, op, err);
14455 		break;
14456 	case REASON_LIMIT:
14457 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14458 			dst, op, err);
14459 		break;
14460 	case REASON_STACK:
14461 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14462 			dst, err);
14463 		return -ENOMEM;
14464 	default:
14465 		verifier_bug(env, "unknown reason (%d)", reason);
14466 		break;
14467 	}
14468 
14469 	return -EACCES;
14470 }
14471 
14472 /* check that stack access falls within stack limits and that 'reg' doesn't
14473  * have a variable offset.
14474  *
14475  * Variable offset is prohibited for unprivileged mode for simplicity since it
14476  * requires corresponding support in Spectre masking for stack ALU.  See also
14477  * retrieve_ptr_limit().
14478  */
14479 static int check_stack_access_for_ptr_arithmetic(
14480 				struct bpf_verifier_env *env,
14481 				int regno,
14482 				const struct bpf_reg_state *reg,
14483 				int off)
14484 {
14485 	if (!tnum_is_const(reg->var_off)) {
14486 		char tn_buf[48];
14487 
14488 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14489 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14490 			regno, tn_buf, off);
14491 		return -EACCES;
14492 	}
14493 
14494 	if (off >= 0 || off < -MAX_BPF_STACK) {
14495 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14496 			"prohibited for !root; off=%d\n", regno, off);
14497 		return -EACCES;
14498 	}
14499 
14500 	return 0;
14501 }
14502 
14503 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14504 				 const struct bpf_insn *insn,
14505 				 struct bpf_reg_state *dst_reg)
14506 {
14507 	u32 dst = insn->dst_reg;
14508 
14509 	/* For unprivileged we require that resulting offset must be in bounds
14510 	 * in order to be able to sanitize access later on.
14511 	 */
14512 	if (env->bypass_spec_v1)
14513 		return 0;
14514 
14515 	switch (dst_reg->type) {
14516 	case PTR_TO_STACK:
14517 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14518 							  dst_reg->var_off.value))
14519 			return -EACCES;
14520 		break;
14521 	case PTR_TO_MAP_VALUE:
14522 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
14523 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14524 				"prohibited for !root\n", dst);
14525 			return -EACCES;
14526 		}
14527 		break;
14528 	default:
14529 		return -EOPNOTSUPP;
14530 	}
14531 
14532 	return 0;
14533 }
14534 
14535 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14536  * Caller should also handle BPF_MOV case separately.
14537  * If we return -EACCES, caller may want to try again treating pointer as a
14538  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14539  */
14540 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,
14541 				   u32 ptr_regno, const struct bpf_reg_state *ptr_reg,
14542 				   const struct bpf_reg_state *off_reg)
14543 {
14544 	struct bpf_verifier_state *vstate = env->cur_state;
14545 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14546 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14547 	bool known = tnum_is_const(off_reg->var_off);
14548 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
14549 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
14550 	struct bpf_sanitize_info info = {};
14551 	u8 opcode = BPF_OP(insn->code);
14552 	u32 dst = insn->dst_reg;
14553 	const char *reason;
14554 	int ret, bounds_ret;
14555 
14556 	dst_reg = &regs[dst];
14557 
14558 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14559 	    smin_val > smax_val || umin_val > umax_val) {
14560 		/* Taint dst register if offset had invalid bounds derived from
14561 		 * e.g. dead branches.
14562 		 */
14563 		__mark_reg_unknown(env, dst_reg);
14564 		return 0;
14565 	}
14566 
14567 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14568 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14569 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14570 			__mark_reg_unknown(env, dst_reg);
14571 			return 0;
14572 		}
14573 
14574 		verbose(env,
14575 			"R%d 32-bit pointer arithmetic prohibited\n",
14576 			dst);
14577 		reason = bpf_diag_fmt(
14578 			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.",
14579 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
14580 		bpf_diag_register_type(
14581 			env, env->insn_idx, ptr_regno, "32-bit pointer arithmetic", reason,
14582 			"Use a 64-bit ALU instruction with an allowed, bounded scalar offset.");
14583 		return -EACCES;
14584 	}
14585 
14586 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14587 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14588 			dst, reg_type_str(env, ptr_reg->type));
14589 		reason = bpf_diag_fmt(
14590 			env, "R%d may be NULL (%s). Pointer arithmetic is allowed only after the program proves the pointer is non-NULL on this path.",
14591 			ptr_regno, reg_type_str(env, ptr_reg->type));
14592 		bpf_diag_register_type(
14593 			env, env->insn_idx, ptr_regno, "pointer arithmetic before NULL check", reason,
14594 			"Make sure that a NULL check precedes any arithmetic performed on the pointer.");
14595 		return -EACCES;
14596 	}
14597 
14598 	switch (base_type(ptr_reg->type)) {
14599 	case PTR_TO_CTX:
14600 	case PTR_TO_MAP_VALUE:
14601 	case PTR_TO_MAP_KEY:
14602 	case PTR_TO_STACK:
14603 	case PTR_TO_PACKET_META:
14604 	case PTR_TO_PACKET:
14605 	case PTR_TO_TP_BUFFER:
14606 	case PTR_TO_BTF_ID:
14607 	case PTR_TO_MEM:
14608 	case PTR_TO_BUF:
14609 	case PTR_TO_FUNC:
14610 	case CONST_PTR_TO_DYNPTR:
14611 		break;
14612 	case PTR_TO_FLOW_KEYS:
14613 		if (known)
14614 			break;
14615 		fallthrough;
14616 	case CONST_PTR_TO_MAP:
14617 		/* smin_val represents the known value */
14618 		if (known && smin_val == 0 && opcode == BPF_ADD)
14619 			break;
14620 		fallthrough;
14621 	default:
14622 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14623 			dst, reg_type_str(env, ptr_reg->type));
14624 		reason = bpf_diag_fmt(
14625 			env, "R%d holds %s. This pointer kind does not allow offset arithmetic.",
14626 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type));
14627 		bpf_diag_register_type(
14628 			env, env->insn_idx, ptr_regno, "pointer arithmetic is not allowed", reason,
14629 			"Do not change this pointer's offset; use it only in operations accepted for its kind.");
14630 		return -EACCES;
14631 	}
14632 
14633 	/* For 'scalar += pointer', dst_reg inherits the complete pointer
14634 	 * register state. Individual fields may be adjusted later by pointer
14635 	 * arithmetic. Callers guarantee that below does not overwrite off_reg.
14636 	 */
14637 	if (dst_reg != ptr_reg)
14638 		*dst_reg = *ptr_reg;
14639 
14640 	/*
14641 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14642 	 * instructions, hence no need to track offsets.
14643 	 */
14644 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14645 		return 0;
14646 
14647 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) {
14648 		reason = bpf_diag_fmt(
14649 			env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].",
14650 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF);
14651 		bpf_diag_register_type(
14652 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
14653 			"Clamp or bounds-check the scalar offset before applying it to the pointer.");
14654 		return -EINVAL;
14655 	}
14656 	if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) {
14657 		reason = bpf_diag_fmt(
14658 			env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.",
14659 			ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
14660 			bpf_diag_reg_type_plain(env, ptr_reg->type));
14661 		bpf_diag_register_type(
14662 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
14663 			"Keep the base pointer within the verifier's allowed offset range before applying more arithmetic.");
14664 		return -EINVAL;
14665 	}
14666 
14667 	if (sanitize_needed(opcode)) {
14668 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14669 				       &info, false);
14670 		if (ret < 0)
14671 			return sanitize_err(env, insn, ret);
14672 	}
14673 
14674 	/*
14675 	 * Pointer types do not carry 32-bit bounds at the moment. Blank r32
14676 	 * only after sanitize_ptr_alu() may have snapshotted dst_reg into a
14677 	 * speculative path: otherwise reg_bounds_sanity_check() might hit some
14678 	 * constraints violations.
14679 	 */
14680 	__mark_reg32_unbounded(dst_reg);
14681 
14682 	switch (opcode) {
14683 	case BPF_ADD:
14684 		/*
14685 		 * dst_reg gets the pointer type and since some positive
14686 		 * integer value was added to the pointer, give it a new 'id'
14687 		 * if it's a PTR_TO_PACKET.
14688 		 * this creates a new 'base' pointer, off_reg (variable) gets
14689 		 * added into the variable offset, and we copy the fixed offset
14690 		 * from ptr_reg.
14691 		 */
14692 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
14693 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14694 		dst_reg->raw = ptr_reg->raw;
14695 		if (reg_is_pkt_pointer(ptr_reg)) {
14696 			if (!known)
14697 				dst_reg->id = ++env->id_gen;
14698 			/*
14699 			 * Clear range for unknown addends since we can't know
14700 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
14701 			 * BEYOND_PKT_END from prior comparison as any pointer
14702 			 * arithmetic invalidates them.
14703 			 */
14704 			if (!known || dst_reg->range < 0)
14705 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14706 		}
14707 		break;
14708 	case BPF_SUB:
14709 		if (dst_reg != ptr_reg) {
14710 			/* scalar -= pointer.  Creates an unknown scalar */
14711 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14712 				dst);
14713 			reason = bpf_diag_fmt(
14714 				env, "This operation subtracts pointer register R%d from scalar register R%d. "
14715 				"The verifier only tracks pointer-minus-scalar arithmetic for allowed pointer types.",
14716 				ptr_regno, dst);
14717 			bpf_diag_register_type(
14718 				env, env->insn_idx, ptr_regno, "pointer subtracted from scalar", reason,
14719 				"Keep the pointer as the base; only add or subtract bounded scalars when permitted.");
14720 			return -EACCES;
14721 		}
14722 		/* We don't allow subtraction from FP, because (according to
14723 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14724 		 * be able to deal with it.
14725 		 */
14726 		if (ptr_reg->type == PTR_TO_STACK) {
14727 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14728 				dst);
14729 			reason = bpf_diag_fmt(
14730 				env, "R%d is a stack pointer. The verifier does not allow BPF_SUB to move stack pointers.",
14731 				ptr_regno);
14732 			bpf_diag_register_type(
14733 				env, env->insn_idx, ptr_regno, "subtraction from stack pointer", reason,
14734 				"Use addition from R10 to form stack addresses within the tracked stack frame.");
14735 			return -EACCES;
14736 		}
14737 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
14738 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14739 		dst_reg->raw = ptr_reg->raw;
14740 		if (reg_is_pkt_pointer(ptr_reg)) {
14741 			if (!known)
14742 				dst_reg->id = ++env->id_gen;
14743 			/*
14744 			 * Clear range if the subtrahend may be negative since
14745 			 * pkt pointer could move past its bounds. A positive
14746 			 * subtrahend moves it backwards keeping positive range
14747 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
14748 			 * prior comparison as arithmetic invalidates them.
14749 			 */
14750 			if ((!known && smin_val < 0) || dst_reg->range < 0)
14751 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14752 		}
14753 		break;
14754 	case BPF_AND:
14755 	case BPF_OR:
14756 	case BPF_XOR:
14757 		/* bitwise ops on pointers are troublesome, prohibit. */
14758 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14759 			dst, bpf_alu_string[opcode >> 4]);
14760 		reason = bpf_diag_fmt(
14761 			env, "R%d holds %s. Bitwise operator %s would destroy the pointer value the verifier is tracking.",
14762 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
14763 			bpf_alu_string[opcode >> 4]);
14764 		bpf_diag_register_type(
14765 			env, env->insn_idx, ptr_regno, "bitwise operation on pointer", reason,
14766 			"Do bitwise operations on scalar values, not on pointer-valued registers.");
14767 		return -EACCES;
14768 	default:
14769 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14770 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14771 			dst, bpf_alu_string[opcode >> 4]);
14772 		reason = bpf_diag_fmt(
14773 			env, "R%d holds %s. Operator %s is not one of the limited pointer arithmetic operations the verifier can track.",
14774 			ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type),
14775 			bpf_alu_string[opcode >> 4]);
14776 		bpf_diag_register_type(
14777 			env, env->insn_idx, ptr_regno, "invalid pointer arithmetic operator", reason,
14778 			"Use only verifier-supported addition or subtraction with a bounded scalar offset, or perform this operation on a scalar value.");
14779 		return -EACCES;
14780 	}
14781 
14782 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) {
14783 		reason = bpf_diag_fmt(
14784 			env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.",
14785 			dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF,
14786 			bpf_diag_reg_type_plain(env, ptr_reg->type));
14787 		bpf_diag_register_type(
14788 			env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason,
14789 			"Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range.");
14790 		return -EINVAL;
14791 	}
14792 	reg_bounds_sync(dst_reg);
14793 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14794 	if (bounds_ret == -EACCES)
14795 		return bounds_ret;
14796 	if (sanitize_needed(opcode)) {
14797 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14798 				       &info, true);
14799 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14800 				    && !env->cur_state->speculative
14801 				    && bounds_ret
14802 				    && !ret,
14803 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14804 			return -EFAULT;
14805 		}
14806 		if (ret < 0)
14807 			return sanitize_err(env, insn, ret);
14808 	}
14809 
14810 	return 0;
14811 }
14812 
14813 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14814 				 struct bpf_reg_state *src_reg)
14815 {
14816 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
14817 }
14818 
14819 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14820 			       struct bpf_reg_state *src_reg)
14821 {
14822 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
14823 }
14824 
14825 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14826 				 struct bpf_reg_state *src_reg)
14827 {
14828 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
14829 }
14830 
14831 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14832 			       struct bpf_reg_state *src_reg)
14833 {
14834 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
14835 }
14836 
14837 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14838 				 struct bpf_reg_state *src_reg)
14839 {
14840 	s32 smin = reg_s32_min(dst_reg);
14841 	s32 smax = reg_s32_max(dst_reg);
14842 	u32 umin = reg_u32_min(dst_reg);
14843 	u32 umax = reg_u32_max(dst_reg);
14844 	s32 tmp_prod[4];
14845 
14846 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
14847 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
14848 		/* Overflow possible, we know nothing */
14849 		umin = 0;
14850 		umax = U32_MAX;
14851 	}
14852 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
14853 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
14854 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
14855 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
14856 		/* Overflow possible, we know nothing */
14857 		smin = S32_MIN;
14858 		smax = S32_MAX;
14859 	} else {
14860 		smin = min_array(tmp_prod, 4);
14861 		smax = max_array(tmp_prod, 4);
14862 	}
14863 
14864 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
14865 					cnum32_from_srange(smin, smax));
14866 }
14867 
14868 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14869 			       struct bpf_reg_state *src_reg)
14870 {
14871 	s64 smin = reg_smin(dst_reg);
14872 	s64 smax = reg_smax(dst_reg);
14873 	u64 umin = reg_umin(dst_reg);
14874 	u64 umax = reg_umax(dst_reg);
14875 	s64 tmp_prod[4];
14876 
14877 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
14878 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
14879 		/* Overflow possible, we know nothing */
14880 		umin = 0;
14881 		umax = U64_MAX;
14882 	}
14883 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
14884 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
14885 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
14886 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
14887 		/* Overflow possible, we know nothing */
14888 		smin = S64_MIN;
14889 		smax = S64_MAX;
14890 	} else {
14891 		smin = min_array(tmp_prod, 4);
14892 		smax = max_array(tmp_prod, 4);
14893 	}
14894 
14895 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
14896 					cnum64_from_srange(smin, smax));
14897 }
14898 
14899 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
14900 				  struct bpf_reg_state *src_reg)
14901 {
14902 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
14903 
14904 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
14905 			 reg_u32_max(dst_reg) / src_val);
14906 
14907 	/* Reset other ranges/tnum to unbounded/unknown. */
14908 	reset_reg64_and_tnum(dst_reg);
14909 }
14910 
14911 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
14912 				struct bpf_reg_state *src_reg)
14913 {
14914 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
14915 
14916 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
14917 			 div64_u64(reg_umax(dst_reg), src_val));
14918 
14919 	/* Reset other ranges/tnum to unbounded/unknown. */
14920 	reset_reg32_and_tnum(dst_reg);
14921 }
14922 
14923 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
14924 				  struct bpf_reg_state *src_reg)
14925 {
14926 	s32 smin = reg_s32_min(dst_reg);
14927 	s32 smax = reg_s32_max(dst_reg);
14928 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
14929 	s32 res1, res2;
14930 
14931 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
14932 	if (smin == S32_MIN && src_val == -1) {
14933 		/*
14934 		 * If the dividend range contains more than just S32_MIN,
14935 		 * we cannot precisely track the result, so it becomes unbounded.
14936 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
14937 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
14938 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
14939 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
14940 		 */
14941 		if (smax != S32_MIN) {
14942 			smin = S32_MIN;
14943 			smax = S32_MAX;
14944 		}
14945 		goto reset;
14946 	}
14947 
14948 	res1 = smin / src_val;
14949 	res2 = smax / src_val;
14950 	smin = min(res1, res2);
14951 	smax = max(res1, res2);
14952 
14953 reset:
14954 	reg_set_srange32(dst_reg, smin, smax);
14955 	/* Reset other ranges/tnum to unbounded/unknown. */
14956 	reset_reg64_and_tnum(dst_reg);
14957 }
14958 
14959 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
14960 				struct bpf_reg_state *src_reg)
14961 {
14962 	s64 smin = reg_smin(dst_reg);
14963 	s64 smax = reg_smax(dst_reg);
14964 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
14965 	s64 res1, res2;
14966 
14967 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
14968 	if (smin == S64_MIN && src_val == -1) {
14969 		/*
14970 		 * If the dividend range contains more than just S64_MIN,
14971 		 * we cannot precisely track the result, so it becomes unbounded.
14972 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
14973 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
14974 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
14975 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
14976 		 */
14977 		if (smax != S64_MIN) {
14978 			smin = S64_MIN;
14979 			smax = S64_MAX;
14980 		}
14981 		goto reset;
14982 	}
14983 
14984 	res1 = div64_s64(smin, src_val);
14985 	res2 = div64_s64(smax, src_val);
14986 	smin = min(res1, res2);
14987 	smax = max(res1, res2);
14988 
14989 reset:
14990 	reg_set_srange64(dst_reg, smin, smax);
14991 	/* Reset other ranges/tnum to unbounded/unknown. */
14992 	reset_reg32_and_tnum(dst_reg);
14993 }
14994 
14995 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
14996 				  struct bpf_reg_state *src_reg)
14997 {
14998 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
14999 	u32 res_max = src_val - 1;
15000 
15001 	/*
15002 	 * If dst_umax <= res_max, the result remains unchanged.
15003 	 * e.g., [2, 5] % 10 = [2, 5].
15004 	 */
15005 	if (reg_u32_max(dst_reg) <= res_max)
15006 		return;
15007 
15008 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
15009 
15010 	/* Reset other ranges/tnum to unbounded/unknown. */
15011 	reset_reg64_and_tnum(dst_reg);
15012 }
15013 
15014 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
15015 				struct bpf_reg_state *src_reg)
15016 {
15017 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
15018 	u64 res_max = src_val - 1;
15019 
15020 	/*
15021 	 * If dst_umax <= res_max, the result remains unchanged.
15022 	 * e.g., [2, 5] % 10 = [2, 5].
15023 	 */
15024 	if (reg_umax(dst_reg) <= res_max)
15025 		return;
15026 
15027 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
15028 
15029 	/* Reset other ranges/tnum to unbounded/unknown. */
15030 	reset_reg32_and_tnum(dst_reg);
15031 }
15032 
15033 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
15034 				  struct bpf_reg_state *src_reg)
15035 {
15036 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
15037 
15038 	/*
15039 	 * Safe absolute value calculation:
15040 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
15041 	 * Here use unsigned integer to avoid overflow.
15042 	 */
15043 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
15044 
15045 	/*
15046 	 * Calculate the maximum possible absolute value of the result.
15047 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
15048 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
15049 	 */
15050 	s32 res_max_abs = src_abs - 1;
15051 
15052 	/*
15053 	 * If the dividend is already within the result range,
15054 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15055 	 */
15056 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
15057 		return;
15058 
15059 	/* General case: result has the same sign as the dividend. */
15060 	if (reg_s32_min(dst_reg) >= 0) {
15061 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
15062 	} else if (reg_s32_max(dst_reg) <= 0) {
15063 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
15064 	} else {
15065 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
15066 	}
15067 
15068 	/* Reset other ranges/tnum to unbounded/unknown. */
15069 	reset_reg64_and_tnum(dst_reg);
15070 }
15071 
15072 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
15073 				struct bpf_reg_state *src_reg)
15074 {
15075 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
15076 
15077 	/*
15078 	 * Safe absolute value calculation:
15079 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
15080 	 * Here use unsigned integer to avoid overflow.
15081 	 */
15082 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
15083 
15084 	/*
15085 	 * Calculate the maximum possible absolute value of the result.
15086 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
15087 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
15088 	 */
15089 	s64 res_max_abs = src_abs - 1;
15090 
15091 	/*
15092 	 * If the dividend is already within the result range,
15093 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
15094 	 */
15095 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
15096 		return;
15097 
15098 	/* General case: result has the same sign as the dividend. */
15099 	if (reg_smin(dst_reg) >= 0) {
15100 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
15101 	} else if (reg_smax(dst_reg) <= 0) {
15102 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
15103 	} else {
15104 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
15105 	}
15106 
15107 	/* Reset other ranges/tnum to unbounded/unknown. */
15108 	reset_reg32_and_tnum(dst_reg);
15109 }
15110 
15111 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15112 				 struct bpf_reg_state *src_reg)
15113 {
15114 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15115 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15116 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15117 	u32 umax_val = reg_u32_max(src_reg);
15118 
15119 	if (src_known && dst_known) {
15120 		__mark_reg32_known(dst_reg, var32_off.value);
15121 		return;
15122 	}
15123 
15124 	/* We get our minimum from the var_off, since that's inherently
15125 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15126 	 */
15127 	reg_set_urange32(dst_reg,
15128 			 var32_off.value,
15129 			 min(reg_u32_max(dst_reg), umax_val));
15130 }
15131 
15132 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15133 			       struct bpf_reg_state *src_reg)
15134 {
15135 	bool src_known = tnum_is_const(src_reg->var_off);
15136 	bool dst_known = tnum_is_const(dst_reg->var_off);
15137 	u64 umax_val = reg_umax(src_reg);
15138 
15139 	if (src_known && dst_known) {
15140 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15141 		return;
15142 	}
15143 
15144 	/* We get our minimum from the var_off, since that's inherently
15145 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
15146 	 */
15147 	reg_set_urange64(dst_reg,
15148 			 dst_reg->var_off.value,
15149 			 min(reg_umax(dst_reg), umax_val));
15150 
15151 	/* We may learn something more from the var_off */
15152 	__update_reg_bounds(dst_reg);
15153 }
15154 
15155 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15156 				struct bpf_reg_state *src_reg)
15157 {
15158 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15159 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15160 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15161 	u32 umin_val = reg_u32_min(src_reg);
15162 
15163 	if (src_known && dst_known) {
15164 		__mark_reg32_known(dst_reg, var32_off.value);
15165 		return;
15166 	}
15167 
15168 	/* We get our maximum from the var_off, and our minimum is the
15169 	 * maximum of the operands' minima
15170 	 */
15171 	reg_set_urange32(dst_reg,
15172 			 max(reg_u32_min(dst_reg), umin_val),
15173 			 var32_off.value | var32_off.mask);
15174 }
15175 
15176 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15177 			      struct bpf_reg_state *src_reg)
15178 {
15179 	bool src_known = tnum_is_const(src_reg->var_off);
15180 	bool dst_known = tnum_is_const(dst_reg->var_off);
15181 	u64 umin_val = reg_umin(src_reg);
15182 
15183 	if (src_known && dst_known) {
15184 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15185 		return;
15186 	}
15187 
15188 	/* We get our maximum from the var_off, and our minimum is the
15189 	 * maximum of the operands' minima
15190 	 */
15191 	reg_set_urange64(dst_reg,
15192 			 max(reg_umin(dst_reg), umin_val),
15193 			 dst_reg->var_off.value | dst_reg->var_off.mask);
15194 
15195 	/* We may learn something more from the var_off */
15196 	__update_reg_bounds(dst_reg);
15197 }
15198 
15199 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15200 				 struct bpf_reg_state *src_reg)
15201 {
15202 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15203 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15204 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15205 
15206 	if (src_known && dst_known) {
15207 		__mark_reg32_known(dst_reg, var32_off.value);
15208 		return;
15209 	}
15210 
15211 	/* We get both minimum and maximum from the var32_off. */
15212 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
15213 }
15214 
15215 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15216 			       struct bpf_reg_state *src_reg)
15217 {
15218 	bool src_known = tnum_is_const(src_reg->var_off);
15219 	bool dst_known = tnum_is_const(dst_reg->var_off);
15220 
15221 	if (src_known && dst_known) {
15222 		/* dst_reg->var_off.value has been updated earlier */
15223 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15224 		return;
15225 	}
15226 
15227 	/* We get both minimum and maximum from the var_off. */
15228 	reg_set_urange64(dst_reg,
15229 			 dst_reg->var_off.value,
15230 			 dst_reg->var_off.value | dst_reg->var_off.mask);
15231 }
15232 
15233 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15234 				   u64 umin_val, u64 umax_val)
15235 {
15236 	/* If we might shift our top bit out, then we know nothing */
15237 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
15238 		reg_set_urange32(dst_reg, 0, U32_MAX);
15239 	else
15240 		/* We lose all sign bit information (except what we can pick
15241 		 * up from var_off)
15242 		 */
15243 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
15244 				 reg_u32_max(dst_reg) << umax_val);
15245 }
15246 
15247 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15248 				 struct bpf_reg_state *src_reg)
15249 {
15250 	u32 umax_val = reg_u32_max(src_reg);
15251 	u32 umin_val = reg_u32_min(src_reg);
15252 	/* u32 alu operation will zext upper bits */
15253 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15254 
15255 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15256 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15257 	/* Not required but being careful mark reg64 bounds as unknown so
15258 	 * that we are forced to pick them up from tnum and zext later and
15259 	 * if some path skips this step we are still safe.
15260 	 */
15261 	__mark_reg64_unbounded(dst_reg);
15262 	__update_reg32_bounds(dst_reg);
15263 }
15264 
15265 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15266 				   u64 umin_val, u64 umax_val)
15267 {
15268 	struct cnum64 u, s;
15269 
15270 	/* Special case <<32 because it is a common compiler pattern to sign
15271 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
15272 	 * because s32 bounds don't flip sign when shifting to the left by
15273 	 * 32bits.
15274 	 */
15275 	if (umin_val == 32 && umax_val == 32)
15276 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
15277 				       (s64)reg_s32_max(dst_reg) << 32);
15278 	else
15279 		s = CNUM64_UNBOUNDED;
15280 
15281 	/* If we might shift our top bit out, then we know nothing */
15282 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
15283 		u = CNUM64_UNBOUNDED;
15284 	else
15285 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
15286 				       reg_umax(dst_reg) << umax_val);
15287 
15288 	dst_reg->r64 = cnum64_intersect(u, s);
15289 }
15290 
15291 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15292 			       struct bpf_reg_state *src_reg)
15293 {
15294 	u64 umax_val = reg_umax(src_reg);
15295 	u64 umin_val = reg_umin(src_reg);
15296 
15297 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15298 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15299 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15300 
15301 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15302 	/* We may learn something more from the var_off */
15303 	__update_reg_bounds(dst_reg);
15304 }
15305 
15306 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15307 				 struct bpf_reg_state *src_reg)
15308 {
15309 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15310 	u32 umax_val = reg_u32_max(src_reg);
15311 	u32 umin_val = reg_u32_min(src_reg);
15312 
15313 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15314 	 * be negative, then either:
15315 	 * 1) src_reg might be zero, so the sign bit of the result is
15316 	 *    unknown, so we lose our signed bounds
15317 	 * 2) it's known negative, thus the unsigned bounds capture the
15318 	 *    signed bounds
15319 	 * 3) the signed bounds cross zero, so they tell us nothing
15320 	 *    about the result
15321 	 * If the value in dst_reg is known nonnegative, then again the
15322 	 * unsigned bounds capture the signed bounds.
15323 	 * Thus, in all cases it suffices to blow away our signed bounds
15324 	 * and rely on inferring new ones from the unsigned bounds and
15325 	 * var_off of the result.
15326 	 */
15327 
15328 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15329 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
15330 			 reg_u32_max(dst_reg) >> umin_val);
15331 
15332 	__mark_reg64_unbounded(dst_reg);
15333 	__update_reg32_bounds(dst_reg);
15334 }
15335 
15336 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15337 			       struct bpf_reg_state *src_reg)
15338 {
15339 	u64 umax_val = reg_umax(src_reg);
15340 	u64 umin_val = reg_umin(src_reg);
15341 
15342 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15343 	 * be negative, then either:
15344 	 * 1) src_reg might be zero, so the sign bit of the result is
15345 	 *    unknown, so we lose our signed bounds
15346 	 * 2) it's known negative, thus the unsigned bounds capture the
15347 	 *    signed bounds
15348 	 * 3) the signed bounds cross zero, so they tell us nothing
15349 	 *    about the result
15350 	 * If the value in dst_reg is known nonnegative, then again the
15351 	 * unsigned bounds capture the signed bounds.
15352 	 * Thus, in all cases it suffices to blow away our signed bounds
15353 	 * and rely on inferring new ones from the unsigned bounds and
15354 	 * var_off of the result.
15355 	 */
15356 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15357 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
15358 			 reg_umax(dst_reg) >> umin_val);
15359 
15360 	/* Its not easy to operate on alu32 bounds here because it depends
15361 	 * on bits being shifted in. Take easy way out and mark unbounded
15362 	 * so we can recalculate later from tnum.
15363 	 */
15364 	__mark_reg32_unbounded(dst_reg);
15365 	__update_reg_bounds(dst_reg);
15366 }
15367 
15368 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15369 				  struct bpf_reg_state *src_reg)
15370 {
15371 	u64 umin_val = reg_u32_min(src_reg);
15372 
15373 	/* Upon reaching here, src_known is true and
15374 	 * umax_val is equal to umin_val.
15375 	 * Blow away the dst_reg umin_value/umax_value and rely on
15376 	 * dst_reg var_off to refine the result.
15377 	 */
15378 	reg_set_srange32(dst_reg,
15379 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
15380 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
15381 
15382 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15383 
15384 	__mark_reg64_unbounded(dst_reg);
15385 	__update_reg32_bounds(dst_reg);
15386 }
15387 
15388 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15389 				struct bpf_reg_state *src_reg)
15390 {
15391 	u64 umin_val = reg_umin(src_reg);
15392 
15393 	/* Upon reaching here, src_known is true and umax_val is equal
15394 	 * to umin_val.
15395 	 */
15396 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
15397 			 reg_smax(dst_reg) >> umin_val);
15398 
15399 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15400 
15401 	/* Its not easy to operate on alu32 bounds here because it depends
15402 	 * on bits being shifted in from upper 32-bits. Take easy way out
15403 	 * and mark unbounded so we can recalculate later from tnum.
15404 	 */
15405 	__mark_reg32_unbounded(dst_reg);
15406 	__update_reg_bounds(dst_reg);
15407 }
15408 
15409 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
15410 {
15411 	/*
15412 	 * Byte swap operation - update var_off using tnum_bswap.
15413 	 * Three cases:
15414 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
15415 	 *    unconditional swap
15416 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
15417 	 *    swap on big-endian, truncation or no-op on little-endian
15418 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
15419 	 *    swap on little-endian, truncation or no-op on big-endian
15420 	 */
15421 
15422 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
15423 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
15424 	bool is_big_endian;
15425 #ifdef CONFIG_CPU_BIG_ENDIAN
15426 	is_big_endian = true;
15427 #else
15428 	is_big_endian = false;
15429 #endif
15430 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
15431 	bool need_bswap = alu64 || (to_le == is_big_endian);
15432 
15433 	/*
15434 	 * If the register is mutated, manually reset its scalar ID to break
15435 	 * any existing ties and avoid incorrect bounds propagation.
15436 	 */
15437 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
15438 		clear_scalar_id(dst_reg);
15439 
15440 	if (need_bswap) {
15441 		if (insn->imm == 16)
15442 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
15443 		else if (insn->imm == 32)
15444 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
15445 		else if (insn->imm == 64)
15446 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
15447 		/*
15448 		 * Byteswap scrambles the range, so we must reset bounds.
15449 		 * Bounds will be re-derived from the new tnum later.
15450 		 */
15451 		__mark_reg_unbounded(dst_reg);
15452 	}
15453 	/* For bswap16/32, truncate dst register to match the swapped size */
15454 	if (insn->imm == 16 || insn->imm == 32)
15455 		coerce_reg_to_size(dst_reg, insn->imm / 8);
15456 }
15457 
15458 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15459 					     const struct bpf_reg_state *src_reg)
15460 {
15461 	bool src_is_const = false;
15462 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15463 
15464 	if (insn_bitness == 32) {
15465 		if (tnum_subreg_is_const(src_reg->var_off)
15466 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
15467 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
15468 			src_is_const = true;
15469 	} else {
15470 		if (tnum_is_const(src_reg->var_off)
15471 		    && reg_smin(src_reg) == reg_smax(src_reg)
15472 		    && reg_umin(src_reg) == reg_umax(src_reg))
15473 			src_is_const = true;
15474 	}
15475 
15476 	switch (BPF_OP(insn->code)) {
15477 	case BPF_ADD:
15478 	case BPF_SUB:
15479 	case BPF_NEG:
15480 	case BPF_AND:
15481 	case BPF_XOR:
15482 	case BPF_OR:
15483 	case BPF_MUL:
15484 	case BPF_END:
15485 		return true;
15486 
15487 	/*
15488 	 * Division and modulo operators range is only safe to compute when the
15489 	 * divisor is a constant.
15490 	 */
15491 	case BPF_DIV:
15492 	case BPF_MOD:
15493 		return src_is_const;
15494 
15495 	/* Shift operators range is only computable if shift dimension operand
15496 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15497 	 * includes shifts by a negative number.
15498 	 */
15499 	case BPF_LSH:
15500 	case BPF_RSH:
15501 	case BPF_ARSH:
15502 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
15503 	default:
15504 		return false;
15505 	}
15506 }
15507 
15508 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
15509 			      struct bpf_reg_state *dst_reg)
15510 {
15511 	struct bpf_verifier_state *branch;
15512 	struct bpf_reg_state *regs;
15513 	bool alu32;
15514 
15515 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
15516 		alu32 = false;
15517 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
15518 		alu32 = true;
15519 	else
15520 		return 0;
15521 
15522 	branch = push_stack(env, env->insn_idx, env->insn_idx, false);
15523 	if (IS_ERR(branch))
15524 		return PTR_ERR(branch);
15525 
15526 	regs = branch->frame[branch->curframe]->regs;
15527 	if (alu32) {
15528 		__mark_reg32_known(&regs[insn->dst_reg], 0);
15529 		__mark_reg32_known(dst_reg, -1ull);
15530 	} else {
15531 		__mark_reg_known(&regs[insn->dst_reg], 0);
15532 		__mark_reg_known(dst_reg, -1ull);
15533 	}
15534 	return 0;
15535 }
15536 
15537 /* WARNING: This function does calculations on 64-bit values, but the actual
15538  * execution may occur on 32-bit values. Therefore, things like bitshifts
15539  * need extra checks in the 32-bit case.
15540  */
15541 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15542 				      struct bpf_insn *insn,
15543 				      struct bpf_reg_state *dst_reg,
15544 				      struct bpf_reg_state src_reg)
15545 {
15546 	u8 opcode = BPF_OP(insn->code);
15547 	s16 off = insn->off;
15548 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15549 	int ret;
15550 
15551 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15552 		__mark_reg_unknown(env, dst_reg);
15553 		return 0;
15554 	}
15555 
15556 	if (sanitize_needed(opcode)) {
15557 		ret = sanitize_val_alu(env, insn);
15558 		if (ret < 0)
15559 			return sanitize_err(env, insn, ret);
15560 	}
15561 
15562 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15563 	 * There are two classes of instructions: The first class we track both
15564 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15565 	 * greatest amount of precision when alu operations are mixed with jmp32
15566 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15567 	 * and BPF_OR. This is possible because these ops have fairly easy to
15568 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15569 	 * See alu32 verifier tests for examples. The second class of
15570 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15571 	 * with regards to tracking sign/unsigned bounds because the bits may
15572 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15573 	 * the reg unbounded in the subreg bound space and use the resulting
15574 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15575 	 */
15576 	switch (opcode) {
15577 	case BPF_ADD:
15578 		scalar32_min_max_add(dst_reg, &src_reg);
15579 		scalar_min_max_add(dst_reg, &src_reg);
15580 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15581 		break;
15582 	case BPF_SUB:
15583 		scalar32_min_max_sub(dst_reg, &src_reg);
15584 		scalar_min_max_sub(dst_reg, &src_reg);
15585 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15586 		break;
15587 	case BPF_NEG:
15588 		env->fake_reg[0] = *dst_reg;
15589 		__mark_reg_known(dst_reg, 0);
15590 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15591 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15592 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15593 		break;
15594 	case BPF_MUL:
15595 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15596 		scalar32_min_max_mul(dst_reg, &src_reg);
15597 		scalar_min_max_mul(dst_reg, &src_reg);
15598 		break;
15599 	case BPF_DIV:
15600 		/* BPF div specification: x / 0 = 0 */
15601 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
15602 			___mark_reg_known(dst_reg, 0);
15603 			break;
15604 		}
15605 		if (alu32)
15606 			if (off == 1)
15607 				scalar32_min_max_sdiv(dst_reg, &src_reg);
15608 			else
15609 				scalar32_min_max_udiv(dst_reg, &src_reg);
15610 		else
15611 			if (off == 1)
15612 				scalar_min_max_sdiv(dst_reg, &src_reg);
15613 			else
15614 				scalar_min_max_udiv(dst_reg, &src_reg);
15615 		break;
15616 	case BPF_MOD:
15617 		/* BPF mod specification: x % 0 = x */
15618 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
15619 			break;
15620 		if (alu32)
15621 			if (off == 1)
15622 				scalar32_min_max_smod(dst_reg, &src_reg);
15623 			else
15624 				scalar32_min_max_umod(dst_reg, &src_reg);
15625 		else
15626 			if (off == 1)
15627 				scalar_min_max_smod(dst_reg, &src_reg);
15628 			else
15629 				scalar_min_max_umod(dst_reg, &src_reg);
15630 		break;
15631 	case BPF_AND:
15632 		if (tnum_is_const(src_reg.var_off)) {
15633 			ret = maybe_fork_scalars(env, insn, dst_reg);
15634 			if (ret)
15635 				return ret;
15636 		}
15637 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15638 		scalar32_min_max_and(dst_reg, &src_reg);
15639 		scalar_min_max_and(dst_reg, &src_reg);
15640 		break;
15641 	case BPF_OR:
15642 		if (tnum_is_const(src_reg.var_off)) {
15643 			ret = maybe_fork_scalars(env, insn, dst_reg);
15644 			if (ret)
15645 				return ret;
15646 		}
15647 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15648 		scalar32_min_max_or(dst_reg, &src_reg);
15649 		scalar_min_max_or(dst_reg, &src_reg);
15650 		break;
15651 	case BPF_XOR:
15652 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15653 		scalar32_min_max_xor(dst_reg, &src_reg);
15654 		scalar_min_max_xor(dst_reg, &src_reg);
15655 		break;
15656 	case BPF_LSH:
15657 		if (alu32)
15658 			scalar32_min_max_lsh(dst_reg, &src_reg);
15659 		else
15660 			scalar_min_max_lsh(dst_reg, &src_reg);
15661 		break;
15662 	case BPF_RSH:
15663 		if (alu32)
15664 			scalar32_min_max_rsh(dst_reg, &src_reg);
15665 		else
15666 			scalar_min_max_rsh(dst_reg, &src_reg);
15667 		break;
15668 	case BPF_ARSH:
15669 		if (alu32)
15670 			scalar32_min_max_arsh(dst_reg, &src_reg);
15671 		else
15672 			scalar_min_max_arsh(dst_reg, &src_reg);
15673 		break;
15674 	case BPF_END:
15675 		scalar_byte_swap(dst_reg, insn);
15676 		break;
15677 	default:
15678 		break;
15679 	}
15680 
15681 	/*
15682 	 * ALU32 ops are zero extended into 64bit register.
15683 	 *
15684 	 * BPF_END is already handled inside the helper (truncation),
15685 	 * so skip zext here to avoid unexpected zero extension.
15686 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
15687 	 * This is a 64bit byte swap operation with alu32==true,
15688 	 * but we should not zero extend the result.
15689 	 */
15690 	if (alu32 && opcode != BPF_END)
15691 		zext_32_to_64(dst_reg);
15692 	reg_bounds_sync(dst_reg);
15693 	return 0;
15694 }
15695 
15696 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15697  * and var_off.
15698  */
15699 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15700 				   struct bpf_insn *insn)
15701 {
15702 	struct bpf_verifier_state *vstate = env->cur_state;
15703 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15704 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15705 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15706 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15707 	u8 opcode = BPF_OP(insn->code);
15708 	int err;
15709 
15710 	dst_reg = &regs[insn->dst_reg];
15711 	if (BPF_SRC(insn->code) == BPF_X)
15712 		src_reg = &regs[insn->src_reg];
15713 	else
15714 		src_reg = NULL;
15715 
15716 	/* Case where at least one operand is an arena. */
15717 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
15718 		struct bpf_insn_aux_data *aux = cur_aux(env);
15719 
15720 		if (dst_reg->type != PTR_TO_ARENA)
15721 			*dst_reg = *src_reg;
15722 
15723 		if (BPF_CLASS(insn->code) == BPF_ALU64) {
15724 			/*
15725 			 * 32-bit operations zero upper bits automatically.
15726 			 * 64-bit operations need to be converted to 32.
15727 			 */
15728 			aux->needs_zext = true;
15729 			aux->zext_dst = true;
15730 		}
15731 
15732 		/* Any arithmetic operations are allowed on arena pointers */
15733 		return 0;
15734 	}
15735 
15736 	if (dst_reg->type != SCALAR_VALUE)
15737 		ptr_reg = dst_reg;
15738 
15739 	if (BPF_SRC(insn->code) == BPF_X) {
15740 		if (src_reg->type != SCALAR_VALUE) {
15741 			if (dst_reg->type != SCALAR_VALUE) {
15742 				/* Combining two pointers by any ALU op yields
15743 				 * an arbitrary scalar. Disallow all math except
15744 				 * pointer subtraction
15745 				 */
15746 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15747 					mark_reg_unknown(env, regs, insn->dst_reg);
15748 					return 0;
15749 				}
15750 				verbose(env, "R%d pointer %s pointer prohibited\n",
15751 					insn->dst_reg,
15752 					bpf_alu_string[opcode >> 4]);
15753 				return -EACCES;
15754 			} else {
15755 				/* scalar += pointer
15756 				 * This is legal, but we have to reverse our
15757 				 * src/dest handling in computing the range
15758 				 */
15759 				err = mark_chain_precision(env, insn->dst_reg);
15760 				if (err)
15761 					return err;
15762 				off_reg = *dst_reg;
15763 				return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg,
15764 							       &off_reg);
15765 			}
15766 		} else if (ptr_reg) {
15767 			/* pointer += scalar */
15768 			err = mark_chain_precision(env, insn->src_reg);
15769 			if (err)
15770 				return err;
15771 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg);
15772 		} else if (dst_reg->precise) {
15773 			/* if dst_reg is precise, src_reg should be precise as well */
15774 			err = mark_chain_precision(env, insn->src_reg);
15775 			if (err)
15776 				return err;
15777 		}
15778 	} else {
15779 		/* Pretend the src is a reg with a known value, since we only
15780 		 * need to be able to read from this state.
15781 		 */
15782 		off_reg.type = SCALAR_VALUE;
15783 		__mark_reg_known(&off_reg, insn->imm);
15784 		src_reg = &off_reg;
15785 		if (ptr_reg) /* pointer += K */
15786 			return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, ptr_reg, src_reg);
15787 	}
15788 
15789 	/* Got here implies adding two SCALAR_VALUEs */
15790 	if (WARN_ON_ONCE(ptr_reg)) {
15791 		print_verifier_state(env, vstate, vstate->curframe, true);
15792 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15793 		return -EFAULT;
15794 	}
15795 	if (WARN_ON(!src_reg)) {
15796 		print_verifier_state(env, vstate, vstate->curframe, true);
15797 		verbose(env, "verifier internal error: no src_reg\n");
15798 		return -EFAULT;
15799 	}
15800 	/*
15801 	 * For alu32 linked register tracking, we need to check dst_reg's
15802 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
15803 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
15804 	 */
15805 	u64 dst_umax = reg_umax(dst_reg);
15806 
15807 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15808 	if (err)
15809 		return err;
15810 	/*
15811 	 * Compilers can generate the code
15812 	 * r1 = r2
15813 	 * r1 += 0x1
15814 	 * if r2 < 1000 goto ...
15815 	 * use r1 in memory access
15816 	 * So remember constant delta between r2 and r1 and update r1 after
15817 	 * 'if' condition.
15818 	 */
15819 	if (env->bpf_capable &&
15820 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
15821 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
15822 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
15823 		u64 val = reg_const_value(src_reg, alu32);
15824 		s32 off;
15825 
15826 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
15827 			goto clear_id;
15828 
15829 		if (alu32 && (dst_umax > U32_MAX))
15830 			goto clear_id;
15831 
15832 		off = (s32)val;
15833 
15834 		if (BPF_OP(insn->code) == BPF_SUB) {
15835 			/* Negating S32_MIN would overflow */
15836 			if (off == S32_MIN)
15837 				goto clear_id;
15838 			off = -off;
15839 		}
15840 
15841 		if (dst_reg->id & BPF_ADD_CONST) {
15842 			/*
15843 			 * If the register already went through rX += val
15844 			 * we cannot accumulate another val into rx->off.
15845 			 */
15846 clear_id:
15847 			clear_scalar_id(dst_reg);
15848 		} else {
15849 			if (alu32)
15850 				dst_reg->id |= BPF_ADD_CONST32;
15851 			else
15852 				dst_reg->id |= BPF_ADD_CONST64;
15853 			dst_reg->delta = off;
15854 		}
15855 	} else {
15856 		/*
15857 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15858 		 * incorrectly propagated into other registers by sync_linked_regs()
15859 		 */
15860 		clear_scalar_id(dst_reg);
15861 	}
15862 	return 0;
15863 }
15864 
15865 /* check validity of 32-bit and 64-bit arithmetic operations */
15866 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15867 {
15868 	struct bpf_reg_state *regs = cur_regs(env);
15869 	u8 opcode = BPF_OP(insn->code);
15870 	int err;
15871 
15872 	bpf_diag_mod_begin(env, &regs[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE);
15873 
15874 	if (opcode == BPF_END || opcode == BPF_NEG) {
15875 		/* check src operand */
15876 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15877 		if (err)
15878 			return err;
15879 
15880 		if (is_pointer_value(env, insn->dst_reg)) {
15881 			verbose(env, "R%d pointer arithmetic prohibited\n",
15882 				insn->dst_reg);
15883 			return -EACCES;
15884 		}
15885 
15886 		/* check dest operand */
15887 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
15888 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15889 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15890 							 &regs[insn->dst_reg],
15891 							 regs[insn->dst_reg]);
15892 		} else {
15893 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15894 		}
15895 		if (err)
15896 			return err;
15897 
15898 	} else if (opcode == BPF_MOV) {
15899 
15900 		if (BPF_SRC(insn->code) == BPF_X) {
15901 			if (insn->off == BPF_ADDR_SPACE_CAST) {
15902 				if (!env->prog->aux->arena) {
15903 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15904 					return -EINVAL;
15905 				}
15906 			}
15907 
15908 			/* check src operand */
15909 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15910 			if (err)
15911 				return err;
15912 		}
15913 
15914 		/* check dest operand, mark as required later */
15915 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15916 		if (err)
15917 			return err;
15918 
15919 		if (BPF_SRC(insn->code) == BPF_X) {
15920 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15921 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15922 
15923 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15924 				if (insn->imm) {
15925 					/* off == BPF_ADDR_SPACE_CAST */
15926 					mark_reg_unknown(env, regs, insn->dst_reg);
15927 					if (insn->imm == 1) /* cast from as(1) to as(0) */
15928 						dst_reg->type = PTR_TO_ARENA;
15929 				} else if (insn->off == 0) {
15930 					/* case: R1 = R2
15931 					 * copy register state to dest reg
15932 					 */
15933 					assign_scalar_id_before_mov(env, src_reg);
15934 					*dst_reg = *src_reg;
15935 				} else {
15936 					/* case: R1 = (s8, s16 s32)R2 */
15937 					if (is_pointer_value(env, insn->src_reg)) {
15938 						verbose(env,
15939 							"R%d sign-extension part of pointer\n",
15940 							insn->src_reg);
15941 						return -EACCES;
15942 					} else if (src_reg->type == SCALAR_VALUE) {
15943 						bool no_sext;
15944 
15945 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
15946 						if (no_sext)
15947 							assign_scalar_id_before_mov(env, src_reg);
15948 						*dst_reg = *src_reg;
15949 						if (!no_sext)
15950 							clear_scalar_id(dst_reg);
15951 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15952 					} else {
15953 						mark_reg_unknown(env, regs, insn->dst_reg);
15954 					}
15955 				}
15956 			} else {
15957 				/* R1 = (u32) R2 */
15958 				if (is_pointer_value(env, insn->src_reg)) {
15959 					verbose(env,
15960 						"R%d partial copy of pointer\n",
15961 						insn->src_reg);
15962 					return -EACCES;
15963 				} else if (src_reg->type == SCALAR_VALUE) {
15964 					if (insn->off == 0) {
15965 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15966 
15967 						if (is_src_reg_u32)
15968 							assign_scalar_id_before_mov(env, src_reg);
15969 						*dst_reg = *src_reg;
15970 						/* Make sure ID is cleared if src_reg is not in u32
15971 						 * range otherwise dst_reg min/max could be incorrectly
15972 						 * propagated into src_reg by sync_linked_regs()
15973 						 */
15974 						if (!is_src_reg_u32)
15975 							clear_scalar_id(dst_reg);
15976 					} else {
15977 						/* case: W1 = (s8, s16)W2 */
15978 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
15979 
15980 						if (no_sext)
15981 							assign_scalar_id_before_mov(env, src_reg);
15982 						*dst_reg = *src_reg;
15983 						if (!no_sext)
15984 							clear_scalar_id(dst_reg);
15985 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15986 					}
15987 				} else {
15988 					mark_reg_unknown(env, regs,
15989 							 insn->dst_reg);
15990 				}
15991 				zext_32_to_64(dst_reg);
15992 				reg_bounds_sync(dst_reg);
15993 			}
15994 		} else {
15995 			/* case: R = imm
15996 			 * remember the value we stored into this reg
15997 			 */
15998 			/* clear any state __mark_reg_known doesn't set */
15999 			mark_reg_unknown(env, regs, insn->dst_reg);
16000 			regs[insn->dst_reg].type = SCALAR_VALUE;
16001 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
16002 				__mark_reg_known(regs + insn->dst_reg,
16003 						 insn->imm);
16004 			} else {
16005 				__mark_reg_known(regs + insn->dst_reg,
16006 						 (u32)insn->imm);
16007 			}
16008 		}
16009 
16010 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
16011 
16012 		if (BPF_SRC(insn->code) == BPF_X) {
16013 			/* check src1 operand */
16014 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
16015 			if (err)
16016 				return err;
16017 		}
16018 
16019 		/* check src2 operand */
16020 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16021 		if (err)
16022 			return err;
16023 
16024 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
16025 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
16026 			verbose(env, "div by zero\n");
16027 			return -EINVAL;
16028 		}
16029 
16030 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
16031 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
16032 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
16033 
16034 			if (insn->imm < 0 || insn->imm >= size) {
16035 				verbose(env, "invalid shift %d\n", insn->imm);
16036 				return -EINVAL;
16037 			}
16038 		}
16039 
16040 		/* check dest operand */
16041 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16042 		err = err ?: adjust_reg_min_max_vals(env, insn);
16043 		if (err)
16044 			return err;
16045 	}
16046 
16047 	err = reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
16048 	if (err)
16049 		return err;
16050 
16051 	bpf_diag_mod_end(env);
16052 	return 0;
16053 }
16054 
16055 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
16056 				   struct bpf_reg_state *dst_reg,
16057 				   enum bpf_reg_type type,
16058 				   bool range_right_open)
16059 {
16060 	struct bpf_func_state *state;
16061 	struct bpf_reg_state *reg;
16062 	int new_range;
16063 
16064 	if (reg_umax(dst_reg) == 0 && range_right_open)
16065 		/* This doesn't give us any range */
16066 		return;
16067 
16068 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
16069 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
16070 		 * than pkt_end, but that's because it's also less than pkt.
16071 		 */
16072 		return;
16073 
16074 	new_range = reg_umax(dst_reg);
16075 	if (range_right_open)
16076 		new_range++;
16077 
16078 	/* Examples for register markings:
16079 	 *
16080 	 * pkt_data in dst register:
16081 	 *
16082 	 *   r2 = r3;
16083 	 *   r2 += 8;
16084 	 *   if (r2 > pkt_end) goto <handle exception>
16085 	 *   <access okay>
16086 	 *
16087 	 *   r2 = r3;
16088 	 *   r2 += 8;
16089 	 *   if (r2 < pkt_end) goto <access okay>
16090 	 *   <handle exception>
16091 	 *
16092 	 *   Where:
16093 	 *     r2 == dst_reg, pkt_end == src_reg
16094 	 *     r2=pkt(id=n,off=8,r=0)
16095 	 *     r3=pkt(id=n,off=0,r=0)
16096 	 *
16097 	 * pkt_data in src register:
16098 	 *
16099 	 *   r2 = r3;
16100 	 *   r2 += 8;
16101 	 *   if (pkt_end >= r2) goto <access okay>
16102 	 *   <handle exception>
16103 	 *
16104 	 *   r2 = r3;
16105 	 *   r2 += 8;
16106 	 *   if (pkt_end <= r2) goto <handle exception>
16107 	 *   <access okay>
16108 	 *
16109 	 *   Where:
16110 	 *     pkt_end == dst_reg, r2 == src_reg
16111 	 *     r2=pkt(id=n,off=8,r=0)
16112 	 *     r3=pkt(id=n,off=0,r=0)
16113 	 *
16114 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16115 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16116 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
16117 	 * the check.
16118 	 */
16119 
16120 	/* If our ids match, then we must have the same max_value.  And we
16121 	 * don't care about the other reg's fixed offset, since if it's too big
16122 	 * the range won't allow anything.
16123 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
16124 	 */
16125 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16126 		if (reg->type == type && reg->id == dst_reg->id)
16127 			/* keep the maximum range already checked */
16128 			reg->range = max(reg->range, new_range);
16129 	}));
16130 }
16131 
16132 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16133 				u8 opcode, bool is_jmp32);
16134 static u8 rev_opcode(u8 opcode);
16135 
16136 /*
16137  * Learn more information about live branches by simulating refinement on both branches.
16138  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
16139  * that branch is dead.
16140  */
16141 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
16142 {
16143 	/* Fallthrough (FALSE) branch */
16144 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32);
16145 	reg_bounds_sync(&env->false_reg1);
16146 	reg_bounds_sync(&env->false_reg2);
16147 	/*
16148 	 * If there is a range bounds violation in *any* of the abstract values in either
16149 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
16150 	 * TRUE branch will be taken.
16151 	 */
16152 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
16153 		return 1;
16154 
16155 	/* Jump (TRUE) branch */
16156 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
16157 	reg_bounds_sync(&env->true_reg1);
16158 	reg_bounds_sync(&env->true_reg2);
16159 	/*
16160 	 * If there is a range bounds violation in *any* of the abstract values in either
16161 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
16162 	 * Only FALSE branch will be taken.
16163 	 */
16164 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
16165 		return 0;
16166 
16167 	/* Both branches are possible, we can't determine which one will be taken. */
16168 	return -1;
16169 }
16170 
16171 /*
16172  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16173  */
16174 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
16175 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
16176 {
16177 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16178 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16179 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
16180 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
16181 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
16182 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
16183 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
16184 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
16185 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
16186 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
16187 
16188 	if (reg1 == reg2) {
16189 		switch (opcode) {
16190 		case BPF_JGE:
16191 		case BPF_JLE:
16192 		case BPF_JSGE:
16193 		case BPF_JSLE:
16194 		case BPF_JEQ:
16195 			return 1;
16196 		case BPF_JGT:
16197 		case BPF_JLT:
16198 		case BPF_JSGT:
16199 		case BPF_JSLT:
16200 		case BPF_JNE:
16201 			return 0;
16202 		case BPF_JSET:
16203 			if (tnum_is_const(t1))
16204 				return t1.value != 0;
16205 			else
16206 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16207 		default:
16208 			return -1;
16209 		}
16210 	}
16211 
16212 	switch (opcode) {
16213 	case BPF_JEQ:
16214 		/* constants, umin/umax and smin/smax checks would be
16215 		 * redundant in this case because they all should match
16216 		 */
16217 		if (tnum_is_const(t1) && tnum_is_const(t2))
16218 			return t1.value == t2.value;
16219 		if (!tnum_overlap(t1, t2))
16220 			return 0;
16221 		/* non-overlapping ranges */
16222 		if (umin1 > umax2 || umax1 < umin2)
16223 			return 0;
16224 		if (smin1 > smax2 || smax1 < smin2)
16225 			return 0;
16226 		if (!is_jmp32) {
16227 			/* if 64-bit ranges are inconclusive, see if we can
16228 			 * utilize 32-bit subrange knowledge to eliminate
16229 			 * branches that can't be taken a priori
16230 			 */
16231 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
16232 			    reg_u32_max(reg1) < reg_u32_min(reg2))
16233 				return 0;
16234 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
16235 			    reg_s32_max(reg1) < reg_s32_min(reg2))
16236 				return 0;
16237 		}
16238 		break;
16239 	case BPF_JNE:
16240 		/* constants, umin/umax and smin/smax checks would be
16241 		 * redundant in this case because they all should match
16242 		 */
16243 		if (tnum_is_const(t1) && tnum_is_const(t2))
16244 			return t1.value != t2.value;
16245 		if (!tnum_overlap(t1, t2))
16246 			return 1;
16247 		/* non-overlapping ranges */
16248 		if (umin1 > umax2 || umax1 < umin2)
16249 			return 1;
16250 		if (smin1 > smax2 || smax1 < smin2)
16251 			return 1;
16252 		if (!is_jmp32) {
16253 			/* if 64-bit ranges are inconclusive, see if we can
16254 			 * utilize 32-bit subrange knowledge to eliminate
16255 			 * branches that can't be taken a priori
16256 			 */
16257 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
16258 			    reg_u32_max(reg1) < reg_u32_min(reg2))
16259 				return 1;
16260 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
16261 			    reg_s32_max(reg1) < reg_s32_min(reg2))
16262 				return 1;
16263 		}
16264 		break;
16265 	case BPF_JSET:
16266 		if (!is_reg_const(reg2, is_jmp32)) {
16267 			swap(reg1, reg2);
16268 			swap(t1, t2);
16269 		}
16270 		if (!is_reg_const(reg2, is_jmp32))
16271 			return -1;
16272 		if ((~t1.mask & t1.value) & t2.value)
16273 			return 1;
16274 		if (!((t1.mask | t1.value) & t2.value))
16275 			return 0;
16276 		break;
16277 	case BPF_JGT:
16278 		if (umin1 > umax2)
16279 			return 1;
16280 		else if (umax1 <= umin2)
16281 			return 0;
16282 		break;
16283 	case BPF_JSGT:
16284 		if (smin1 > smax2)
16285 			return 1;
16286 		else if (smax1 <= smin2)
16287 			return 0;
16288 		break;
16289 	case BPF_JLT:
16290 		if (umax1 < umin2)
16291 			return 1;
16292 		else if (umin1 >= umax2)
16293 			return 0;
16294 		break;
16295 	case BPF_JSLT:
16296 		if (smax1 < smin2)
16297 			return 1;
16298 		else if (smin1 >= smax2)
16299 			return 0;
16300 		break;
16301 	case BPF_JGE:
16302 		if (umin1 >= umax2)
16303 			return 1;
16304 		else if (umax1 < umin2)
16305 			return 0;
16306 		break;
16307 	case BPF_JSGE:
16308 		if (smin1 >= smax2)
16309 			return 1;
16310 		else if (smax1 < smin2)
16311 			return 0;
16312 		break;
16313 	case BPF_JLE:
16314 		if (umax1 <= umin2)
16315 			return 1;
16316 		else if (umin1 > umax2)
16317 			return 0;
16318 		break;
16319 	case BPF_JSLE:
16320 		if (smax1 <= smin2)
16321 			return 1;
16322 		else if (smin1 > smax2)
16323 			return 0;
16324 		break;
16325 	}
16326 
16327 	return simulate_both_branches_taken(env, opcode, is_jmp32);
16328 }
16329 
16330 static int flip_opcode(u32 opcode)
16331 {
16332 	/* How can we transform "a <op> b" into "b <op> a"? */
16333 	static const u8 opcode_flip[16] = {
16334 		/* these stay the same */
16335 		[BPF_JEQ  >> 4] = BPF_JEQ,
16336 		[BPF_JNE  >> 4] = BPF_JNE,
16337 		[BPF_JSET >> 4] = BPF_JSET,
16338 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16339 		[BPF_JGE  >> 4] = BPF_JLE,
16340 		[BPF_JGT  >> 4] = BPF_JLT,
16341 		[BPF_JLE  >> 4] = BPF_JGE,
16342 		[BPF_JLT  >> 4] = BPF_JGT,
16343 		[BPF_JSGE >> 4] = BPF_JSLE,
16344 		[BPF_JSGT >> 4] = BPF_JSLT,
16345 		[BPF_JSLE >> 4] = BPF_JSGE,
16346 		[BPF_JSLT >> 4] = BPF_JSGT
16347 	};
16348 	return opcode_flip[opcode >> 4];
16349 }
16350 
16351 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16352 				   struct bpf_reg_state *src_reg,
16353 				   u8 opcode)
16354 {
16355 	struct bpf_reg_state *pkt;
16356 
16357 	if (src_reg->type == PTR_TO_PACKET_END) {
16358 		pkt = dst_reg;
16359 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16360 		pkt = src_reg;
16361 		opcode = flip_opcode(opcode);
16362 	} else {
16363 		return -1;
16364 	}
16365 
16366 	if (pkt->range >= 0)
16367 		return -1;
16368 
16369 	switch (opcode) {
16370 	case BPF_JLE:
16371 		/* pkt <= pkt_end */
16372 		fallthrough;
16373 	case BPF_JGT:
16374 		/* pkt > pkt_end */
16375 		if (pkt->range == BEYOND_PKT_END)
16376 			/* pkt has at last one extra byte beyond pkt_end */
16377 			return opcode == BPF_JGT;
16378 		break;
16379 	case BPF_JLT:
16380 		/* pkt < pkt_end */
16381 		fallthrough;
16382 	case BPF_JGE:
16383 		/* pkt >= pkt_end */
16384 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16385 			return opcode == BPF_JGE;
16386 		break;
16387 	}
16388 	return -1;
16389 }
16390 
16391 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16392  * and return:
16393  *  1 - branch will be taken and "goto target" will be executed
16394  *  0 - branch will not be taken and fall-through to next insn
16395  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16396  *      range [0,10]
16397  */
16398 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
16399 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
16400 {
16401 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16402 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16403 
16404 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16405 		u64 val;
16406 
16407 		/*
16408 		 * The low 32 bits of a valid pointer may well be zero, hence
16409 		 * nothing below applies to a 32-bit comparison.
16410 		 */
16411 		if (is_jmp32)
16412 			return -1;
16413 
16414 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16415 		if (!is_reg_const(reg2, is_jmp32)) {
16416 			opcode = flip_opcode(opcode);
16417 			swap(reg1, reg2);
16418 		}
16419 		/* and ensure that reg2 is a constant */
16420 		if (!is_reg_const(reg2, is_jmp32))
16421 			return -1;
16422 
16423 		if (!reg_not_null(env, reg1))
16424 			return -1;
16425 
16426 		/* If pointer is valid tests against zero will fail so we can
16427 		 * use this to direct branch taken.
16428 		 */
16429 		val = reg_const_value(reg2, is_jmp32);
16430 		if (val != 0)
16431 			return -1;
16432 
16433 		switch (opcode) {
16434 		case BPF_JEQ:
16435 			return 0;
16436 		case BPF_JNE:
16437 			return 1;
16438 		default:
16439 			return -1;
16440 		}
16441 	}
16442 
16443 	/* now deal with two scalars, but not necessarily constants */
16444 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
16445 }
16446 
16447 /* Opcode that corresponds to a *false* branch condition.
16448  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16449  */
16450 static u8 rev_opcode(u8 opcode)
16451 {
16452 	switch (opcode) {
16453 	case BPF_JEQ:		return BPF_JNE;
16454 	case BPF_JNE:		return BPF_JEQ;
16455 	/* JSET doesn't have it's reverse opcode in BPF, so add
16456 	 * BPF_X flag to denote the reverse of that operation
16457 	 */
16458 	case BPF_JSET:		return BPF_JSET | BPF_X;
16459 	case BPF_JSET | BPF_X:	return BPF_JSET;
16460 	case BPF_JGE:		return BPF_JLT;
16461 	case BPF_JGT:		return BPF_JLE;
16462 	case BPF_JLE:		return BPF_JGT;
16463 	case BPF_JLT:		return BPF_JGE;
16464 	case BPF_JSGE:		return BPF_JSLT;
16465 	case BPF_JSGT:		return BPF_JSLE;
16466 	case BPF_JSLE:		return BPF_JSGT;
16467 	case BPF_JSLT:		return BPF_JSGE;
16468 	default:		return 0;
16469 	}
16470 }
16471 
16472 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
16473 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16474 				u8 opcode, bool is_jmp32)
16475 {
16476 	struct tnum t;
16477 	u64 val;
16478 
16479 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16480 	switch (opcode) {
16481 	case BPF_JGE:
16482 	case BPF_JGT:
16483 	case BPF_JSGE:
16484 	case BPF_JSGT:
16485 		opcode = flip_opcode(opcode);
16486 		swap(reg1, reg2);
16487 		break;
16488 	default:
16489 		break;
16490 	}
16491 
16492 	switch (opcode) {
16493 	case BPF_JEQ:
16494 		if (is_jmp32) {
16495 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
16496 			reg2->r32 = reg1->r32;
16497 
16498 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16499 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16500 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16501 		} else {
16502 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
16503 			reg2->r64 = reg1->r64;
16504 
16505 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16506 			reg2->var_off = reg1->var_off;
16507 		}
16508 		break;
16509 	case BPF_JNE:
16510 		if (!is_reg_const(reg2, is_jmp32))
16511 			swap(reg1, reg2);
16512 		if (!is_reg_const(reg2, is_jmp32))
16513 			break;
16514 
16515 		/* try to recompute the bound of reg1 if reg2 is a const and
16516 		 * is exactly the edge of reg1.
16517 		 */
16518 		val = reg_const_value(reg2, is_jmp32);
16519 		if (is_jmp32) {
16520 			/* Complement of the range [val, val] as cnum32. */
16521 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
16522 		} else {
16523 			/* Complement of the range [val, val] as cnum64. */
16524 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
16525 		}
16526 		break;
16527 	case BPF_JSET:
16528 		if (!is_reg_const(reg2, is_jmp32))
16529 			swap(reg1, reg2);
16530 		if (!is_reg_const(reg2, is_jmp32))
16531 			break;
16532 		val = reg_const_value(reg2, is_jmp32);
16533 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16534 		 * requires single bit to learn something useful. E.g., if we
16535 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16536 		 * are actually set? We can learn something definite only if
16537 		 * it's a single-bit value to begin with.
16538 		 *
16539 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16540 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16541 		 * bit 1 is set, which we can readily use in adjustments.
16542 		 */
16543 		if (!is_power_of_2(val))
16544 			break;
16545 		if (is_jmp32) {
16546 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16547 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16548 		} else {
16549 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16550 		}
16551 		break;
16552 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16553 		if (!is_reg_const(reg2, is_jmp32))
16554 			swap(reg1, reg2);
16555 		if (!is_reg_const(reg2, is_jmp32))
16556 			break;
16557 		val = reg_const_value(reg2, is_jmp32);
16558 		/* Forget the ranges before narrowing tnums, to avoid invariant
16559 		 * violations if we're on a dead branch.
16560 		 */
16561 		__mark_reg_unbounded(reg1);
16562 		if (is_jmp32) {
16563 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16564 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16565 		} else {
16566 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16567 		}
16568 		break;
16569 	case BPF_JLE:
16570 		if (is_jmp32) {
16571 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
16572 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
16573 		} else {
16574 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
16575 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
16576 		}
16577 		break;
16578 	case BPF_JLT:
16579 		if (is_jmp32) {
16580 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
16581 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
16582 		} else {
16583 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
16584 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
16585 		}
16586 		break;
16587 	case BPF_JSLE:
16588 		if (is_jmp32) {
16589 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
16590 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
16591 		} else {
16592 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
16593 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
16594 		}
16595 		break;
16596 	case BPF_JSLT:
16597 		if (is_jmp32) {
16598 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
16599 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
16600 		} else {
16601 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
16602 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
16603 		}
16604 		break;
16605 	default:
16606 		return;
16607 	}
16608 }
16609 
16610 /* Check for invariant violations on the registers for both branches of a condition */
16611 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
16612 {
16613 	int err;
16614 
16615 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
16616 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
16617 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
16618 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
16619 	return err;
16620 }
16621 
16622 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16623 				 struct bpf_reg_state *reg, u32 id,
16624 				 bool is_null)
16625 {
16626 	if (type_may_be_null(reg->type) && reg->id == id &&
16627 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16628 		/* Old offset should have been known-zero, because we don't
16629 		 * allow pointer arithmetic on pointers that might be NULL.
16630 		 * If we see this happening, don't convert the register.
16631 		 *
16632 		 * But in some cases, some helpers that return local kptrs
16633 		 * advance offset for the returned pointer. In those cases,
16634 		 * it is fine to expect to see reg->var_off.
16635 		 */
16636 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16637 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
16638 			return;
16639 		if (is_null) {
16640 			/* We don't need id from this point
16641 			 * onwards anymore, thus we should better reset it,
16642 			 * so that state pruning has chances to take effect.
16643 			 */
16644 			__mark_reg_known_zero(reg);
16645 			reg->type = SCALAR_VALUE;
16646 
16647 			return;
16648 		}
16649 
16650 		mark_ptr_not_null_reg(reg);
16651 
16652 		/*
16653 		 * reg->id is preserved for object relationship tracking
16654 		 * and spin_lock lock state tracking
16655 		 */
16656 	}
16657 }
16658 
16659 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16660  * be folded together at some point.
16661  */
16662 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16663 				  bool is_null)
16664 {
16665 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16666 	struct bpf_reg_state *regs = state->regs, *reg;
16667 	u32 id = regs[regno].id;
16668 
16669 	if (is_null && find_reference_state(vstate, id))
16670 		/* regs[regno] is in the " == NULL" branch.
16671 		 * No one could have freed the reference state before
16672 		 * doing the NULL check.
16673 		 */
16674 		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
16675 
16676 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16677 		mark_ptr_or_null_reg(state, reg, id, is_null);
16678 	}));
16679 }
16680 
16681 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16682 				   struct bpf_reg_state *dst_reg,
16683 				   struct bpf_reg_state *src_reg,
16684 				   struct bpf_verifier_state *this_branch,
16685 				   struct bpf_verifier_state *other_branch)
16686 {
16687 	if (BPF_SRC(insn->code) != BPF_X)
16688 		return false;
16689 
16690 	/* Pointers are always 64-bit. */
16691 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16692 		return false;
16693 
16694 	switch (BPF_OP(insn->code)) {
16695 	case BPF_JGT:
16696 		if ((dst_reg->type == PTR_TO_PACKET &&
16697 		     src_reg->type == PTR_TO_PACKET_END) ||
16698 		    (dst_reg->type == PTR_TO_PACKET_META &&
16699 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16700 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16701 			find_good_pkt_pointers(this_branch, dst_reg,
16702 					       dst_reg->type, false);
16703 			mark_pkt_end(other_branch, insn->dst_reg, true);
16704 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16705 			    src_reg->type == PTR_TO_PACKET) ||
16706 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16707 			    src_reg->type == PTR_TO_PACKET_META)) {
16708 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16709 			find_good_pkt_pointers(other_branch, src_reg,
16710 					       src_reg->type, true);
16711 			mark_pkt_end(this_branch, insn->src_reg, false);
16712 		} else {
16713 			return false;
16714 		}
16715 		break;
16716 	case BPF_JLT:
16717 		if ((dst_reg->type == PTR_TO_PACKET &&
16718 		     src_reg->type == PTR_TO_PACKET_END) ||
16719 		    (dst_reg->type == PTR_TO_PACKET_META &&
16720 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16721 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16722 			find_good_pkt_pointers(other_branch, dst_reg,
16723 					       dst_reg->type, true);
16724 			mark_pkt_end(this_branch, insn->dst_reg, false);
16725 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16726 			    src_reg->type == PTR_TO_PACKET) ||
16727 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16728 			    src_reg->type == PTR_TO_PACKET_META)) {
16729 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16730 			find_good_pkt_pointers(this_branch, src_reg,
16731 					       src_reg->type, false);
16732 			mark_pkt_end(other_branch, insn->src_reg, true);
16733 		} else {
16734 			return false;
16735 		}
16736 		break;
16737 	case BPF_JGE:
16738 		if ((dst_reg->type == PTR_TO_PACKET &&
16739 		     src_reg->type == PTR_TO_PACKET_END) ||
16740 		    (dst_reg->type == PTR_TO_PACKET_META &&
16741 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16742 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16743 			find_good_pkt_pointers(this_branch, dst_reg,
16744 					       dst_reg->type, true);
16745 			mark_pkt_end(other_branch, insn->dst_reg, false);
16746 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16747 			    src_reg->type == PTR_TO_PACKET) ||
16748 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16749 			    src_reg->type == PTR_TO_PACKET_META)) {
16750 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16751 			find_good_pkt_pointers(other_branch, src_reg,
16752 					       src_reg->type, false);
16753 			mark_pkt_end(this_branch, insn->src_reg, true);
16754 		} else {
16755 			return false;
16756 		}
16757 		break;
16758 	case BPF_JLE:
16759 		if ((dst_reg->type == PTR_TO_PACKET &&
16760 		     src_reg->type == PTR_TO_PACKET_END) ||
16761 		    (dst_reg->type == PTR_TO_PACKET_META &&
16762 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16763 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16764 			find_good_pkt_pointers(other_branch, dst_reg,
16765 					       dst_reg->type, false);
16766 			mark_pkt_end(this_branch, insn->dst_reg, true);
16767 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16768 			    src_reg->type == PTR_TO_PACKET) ||
16769 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16770 			    src_reg->type == PTR_TO_PACKET_META)) {
16771 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16772 			find_good_pkt_pointers(this_branch, src_reg,
16773 					       src_reg->type, true);
16774 			mark_pkt_end(other_branch, insn->src_reg, false);
16775 		} else {
16776 			return false;
16777 		}
16778 		break;
16779 	default:
16780 		return false;
16781 	}
16782 
16783 	return true;
16784 }
16785 
16786 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16787 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16788 {
16789 	struct linked_reg *e;
16790 
16791 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16792 		return;
16793 
16794 	e = linked_regs_push(reg_set);
16795 	if (e) {
16796 		e->frameno = frameno;
16797 		e->is_reg = is_reg;
16798 		e->regno = spi_or_reg;
16799 	} else {
16800 		clear_scalar_id(reg);
16801 	}
16802 }
16803 
16804 /* For all R being scalar registers or spilled scalar registers
16805  * in verifier state, save R in linked_regs if R->id == id.
16806  * If there are too many Rs sharing same id, reset id for leftover Rs.
16807  */
16808 static void collect_linked_regs(struct bpf_verifier_env *env,
16809 				struct bpf_verifier_state *vstate,
16810 				u32 id,
16811 				struct linked_regs *linked_regs)
16812 {
16813 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
16814 	struct bpf_func_state *func;
16815 	struct bpf_reg_state *reg;
16816 	u16 live_regs;
16817 	int i, j;
16818 
16819 	id = id & ~BPF_ADD_CONST;
16820 	for (i = vstate->curframe; i >= 0; i--) {
16821 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
16822 		func = vstate->frame[i];
16823 		for (j = 0; j < BPF_REG_FP; j++) {
16824 			if (!(live_regs & BIT(j)))
16825 				continue;
16826 			reg = &func->regs[j];
16827 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16828 		}
16829 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16830 			if (!bpf_is_spilled_reg(&func->stack[j]))
16831 				continue;
16832 			reg = &func->stack[j].spilled_ptr;
16833 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16834 		}
16835 	}
16836 }
16837 
16838 /* For all R in linked_regs, copy known_reg range into R
16839  * if R->id == known_reg->id.
16840  */
16841 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
16842 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
16843 {
16844 	struct bpf_reg_state fake_reg;
16845 	struct bpf_reg_state *reg;
16846 	struct linked_reg *e;
16847 	int i;
16848 
16849 	for (i = 0; i < linked_regs->cnt; ++i) {
16850 		e = &linked_regs->entries[i];
16851 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16852 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16853 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16854 			continue;
16855 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16856 			continue;
16857 		/*
16858 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
16859 		 * hold across different ALU widths.
16860 		 */
16861 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
16862 			continue;
16863 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16864 		    reg->delta == known_reg->delta) {
16865 			*reg = *known_reg;
16866 		} else {
16867 			s32 saved_off = reg->delta;
16868 			u32 saved_id = reg->id;
16869 
16870 			fake_reg.type = SCALAR_VALUE;
16871 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
16872 
16873 			/* reg = known_reg; reg += delta */
16874 			*reg = *known_reg;
16875 			/*
16876 			 * Must preserve off and id, otherwise another sync_linked_regs()
16877 			 * will be incorrect.
16878 			 */
16879 			reg->delta = saved_off;
16880 			reg->id = saved_id;
16881 
16882 			scalar32_min_max_add(reg, &fake_reg);
16883 			scalar_min_max_add(reg, &fake_reg);
16884 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16885 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
16886 				zext_32_to_64(reg);
16887 			reg_bounds_sync(reg);
16888 		}
16889 		if (e->is_reg)
16890 			mark_reg_scratched(env, e->regno);
16891 		else
16892 			mark_stack_slot_scratched(env, e->spi);
16893 	}
16894 }
16895 
16896 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16897 			     struct bpf_insn *insn, int *insn_idx)
16898 {
16899 	struct bpf_verifier_state *this_branch = env->cur_state;
16900 	struct bpf_verifier_state *other_branch;
16901 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16902 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16903 	struct bpf_reg_state *eq_branch_regs;
16904 	struct linked_regs linked_regs = {};
16905 	u8 opcode = BPF_OP(insn->code);
16906 	int insn_flags = 0;
16907 	bool is_jmp32;
16908 	int pred = -1;
16909 	int err;
16910 
16911 	/* Only conditional jumps are expected to reach here. */
16912 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16913 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16914 		return -EINVAL;
16915 	}
16916 
16917 	if (opcode == BPF_JCOND) {
16918 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16919 		int idx = *insn_idx;
16920 
16921 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16922 
16923 		/* branch out 'fallthrough' insn as a new state to explore */
16924 		queued_st = push_stack(env, idx + 1, idx, false);
16925 		if (IS_ERR(queued_st))
16926 			return PTR_ERR(queued_st);
16927 
16928 		queued_st->may_goto_depth++;
16929 		if (prev_st)
16930 			widen_imprecise_scalars(env, prev_st, queued_st);
16931 		*insn_idx += insn->off;
16932 		return 0;
16933 	}
16934 
16935 	/* check src2 operand */
16936 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16937 	if (err)
16938 		return err;
16939 
16940 	dst_reg = &regs[insn->dst_reg];
16941 	if (BPF_SRC(insn->code) == BPF_X) {
16942 		/* check src1 operand */
16943 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16944 		if (err)
16945 			return err;
16946 
16947 		src_reg = &regs[insn->src_reg];
16948 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16949 		    is_pointer_value(env, insn->src_reg)) {
16950 			verbose(env, "R%d pointer comparison prohibited\n",
16951 				insn->src_reg);
16952 			return -EACCES;
16953 		}
16954 
16955 		if (src_reg->type == PTR_TO_STACK)
16956 			insn_flags |= INSN_F_SRC_REG_STACK;
16957 		if (dst_reg->type == PTR_TO_STACK)
16958 			insn_flags |= INSN_F_DST_REG_STACK;
16959 	} else {
16960 		src_reg = &env->fake_reg[0];
16961 		memset(src_reg, 0, sizeof(*src_reg));
16962 		src_reg->type = SCALAR_VALUE;
16963 		__mark_reg_known(src_reg, insn->imm);
16964 
16965 		if (dst_reg->type == PTR_TO_STACK)
16966 			insn_flags |= INSN_F_DST_REG_STACK;
16967 	}
16968 
16969 	if (insn_flags) {
16970 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0);
16971 		if (err)
16972 			return err;
16973 	}
16974 
16975 	/*
16976 	 * Collect the linked registers before env->{true,false}_reg{1,2} setup,
16977 	 * otherwise ids dropped by collect_linked_regs() would be resurrected
16978 	 * when env->{true,false}_reg{1,2} are copied back.
16979 	 */
16980 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16981 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
16982 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16983 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
16984 
16985 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16986 	env->false_reg1 = *dst_reg;
16987 	env->false_reg2 = *src_reg;
16988 	env->true_reg1 = *dst_reg;
16989 	env->true_reg2 = *src_reg;
16990 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
16991 	if (pred >= 0) {
16992 		/* If we get here with a dst_reg pointer type it is because
16993 		 * above is_branch_taken() special cased the 0 comparison.
16994 		 */
16995 		if (!__is_pointer_value(false, dst_reg))
16996 			err = mark_chain_precision(env, insn->dst_reg);
16997 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16998 		    !__is_pointer_value(false, src_reg))
16999 			err = mark_chain_precision(env, insn->src_reg);
17000 		if (err)
17001 			return err;
17002 	}
17003 
17004 	if (pred == 1) {
17005 		/* Only follow the goto, ignore fall-through. If needed, push
17006 		 * the fall-through branch for simulation under speculative
17007 		 * execution.
17008 		 */
17009 		if (!env->bypass_spec_v1) {
17010 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
17011 			if (err < 0)
17012 				return err;
17013 		}
17014 		if (env->log.level & BPF_LOG_LEVEL)
17015 			print_insn_state(env, this_branch, this_branch->curframe);
17016 		*insn_idx += insn->off;
17017 		return 0;
17018 	} else if (pred == 0) {
17019 		/* Only follow the fall-through branch, since that's where the
17020 		 * program will go. If needed, push the goto branch for
17021 		 * simulation under speculative execution.
17022 		 */
17023 		if (!env->bypass_spec_v1) {
17024 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
17025 							*insn_idx);
17026 			if (err < 0)
17027 				return err;
17028 		}
17029 		if (env->log.level & BPF_LOG_LEVEL)
17030 			print_insn_state(env, this_branch, this_branch->curframe);
17031 		return 0;
17032 	}
17033 
17034 	/* Push scalar registers sharing same ID to jump history,
17035 	 * do this before creating 'other_branch', so that both
17036 	 * 'this_branch' and 'other_branch' share this history
17037 	 * if parent state is created.
17038 	 */
17039 	if (linked_regs.cnt > 1) {
17040 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs));
17041 		if (err)
17042 			return err;
17043 	}
17044 
17045 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17046 	if (IS_ERR(other_branch))
17047 		return PTR_ERR(other_branch);
17048 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17049 
17050 	err = regs_bounds_sanity_check_branches(env);
17051 	if (err)
17052 		return err;
17053 
17054 	*dst_reg = env->false_reg1;
17055 	*src_reg = env->false_reg2;
17056 	other_branch_regs[insn->dst_reg] = env->true_reg1;
17057 	if (BPF_SRC(insn->code) == BPF_X)
17058 		other_branch_regs[insn->src_reg] = env->true_reg2;
17059 
17060 	if (BPF_SRC(insn->code) == BPF_X &&
17061 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
17062 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17063 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
17064 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
17065 				 &linked_regs);
17066 	}
17067 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17068 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17069 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
17070 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
17071 				 &linked_regs);
17072 	}
17073 
17074 	/* if one pointer register is compared to another pointer
17075 	 * register check if PTR_MAYBE_NULL could be lifted.
17076 	 * E.g. register A - maybe null
17077 	 *      register B - not null
17078 	 * for JNE A, B, ... - A is not null in the false branch;
17079 	 * for JEQ A, B, ... - A is not null in the true branch.
17080 	 *
17081 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
17082 	 * not need to be null checked by the BPF program, i.e.,
17083 	 * could be null even without PTR_MAYBE_NULL marking, so
17084 	 * only propagate nullness when neither reg is that type.
17085 	 */
17086 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17087 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17088 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
17089 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17090 		eq_branch_regs = NULL;
17091 		switch (opcode) {
17092 		case BPF_JEQ:
17093 			eq_branch_regs = other_branch_regs;
17094 			break;
17095 		case BPF_JNE:
17096 			eq_branch_regs = regs;
17097 			break;
17098 		default:
17099 			/* do nothing */
17100 			break;
17101 		}
17102 		if (eq_branch_regs) {
17103 			/* src == dst && dst != NULL => src != NULL */
17104 			if (reg_not_null(env, dst_reg) && type_may_be_null(src_reg->type))
17105 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17106 			/* src == dst && src != NULL => dst != NULL */
17107 			if (reg_not_null(env, src_reg) && type_may_be_null(dst_reg->type))
17108 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17109 		}
17110 	}
17111 
17112 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17113 	 * Also does the same detection for a register whose the value is
17114 	 * known to be 0.
17115 	 * NOTE: these optimizations below are related with pointer comparison
17116 	 *       which will never be JMP32.
17117 	 */
17118 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17119 	    type_may_be_null(dst_reg->type) &&
17120 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
17121 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
17122 		/*
17123 		 * For BPF_X the zero is a property of this execution path,
17124 		 * hence src_reg has to be precise.
17125 		 */
17126 		if (BPF_SRC(insn->code) == BPF_X) {
17127 			err = mark_chain_precision(env, insn->src_reg);
17128 			if (err)
17129 				return err;
17130 		}
17131 		/* Mark all identical registers in each branch as either
17132 		 * safe or unknown depending R == 0 or R != 0 conditional.
17133 		 */
17134 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17135 				      opcode == BPF_JNE);
17136 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17137 				      opcode == BPF_JEQ);
17138 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
17139 					   this_branch, other_branch) &&
17140 		   is_pointer_value(env, insn->dst_reg)) {
17141 		verbose(env, "R%d pointer comparison prohibited\n",
17142 			insn->dst_reg);
17143 		return -EACCES;
17144 	}
17145 	if (env->log.level & BPF_LOG_LEVEL)
17146 		print_insn_state(env, this_branch, this_branch->curframe);
17147 	return 0;
17148 }
17149 
17150 /* verify BPF_LD_IMM64 instruction */
17151 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17152 {
17153 	struct bpf_insn_aux_data *aux = cur_aux(env);
17154 	struct bpf_reg_state *regs = cur_regs(env);
17155 	struct bpf_reg_state *dst_reg;
17156 	struct bpf_map *map;
17157 	int err;
17158 
17159 	if (BPF_SIZE(insn->code) != BPF_DW) {
17160 		verbose(env, "invalid BPF_LD_IMM insn\n");
17161 		return -EINVAL;
17162 	}
17163 
17164 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
17165 	if (err)
17166 		return err;
17167 
17168 	dst_reg = &regs[insn->dst_reg];
17169 	bpf_diag_mod_begin(env, dst_reg, NULL, BPF_DIAG_MOD_WRITE);
17170 	if (insn->src_reg == 0) {
17171 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17172 
17173 		dst_reg->type = SCALAR_VALUE;
17174 		__mark_reg_known(&regs[insn->dst_reg], imm);
17175 		bpf_diag_mod_end(env);
17176 		return 0;
17177 	}
17178 
17179 	/* All special src_reg cases are listed below. From this point onwards
17180 	 * we either succeed and assign a corresponding dst_reg->type after
17181 	 * zeroing the offset, or fail and reject the program.
17182 	 */
17183 	mark_reg_known_zero(env, regs, insn->dst_reg);
17184 
17185 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17186 		dst_reg->type = aux->btf_var.reg_type;
17187 		switch (base_type(dst_reg->type)) {
17188 		case PTR_TO_MEM:
17189 			dst_reg->mem_size = aux->btf_var.mem_size;
17190 			break;
17191 		case PTR_TO_BTF_ID:
17192 			dst_reg->btf = aux->btf_var.btf;
17193 			dst_reg->btf_id = aux->btf_var.btf_id;
17194 			break;
17195 		default:
17196 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17197 			return -EFAULT;
17198 		}
17199 		bpf_diag_mod_end(env);
17200 		return 0;
17201 	}
17202 
17203 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
17204 		struct bpf_prog_aux *aux = env->prog->aux;
17205 		u32 subprogno = bpf_find_subprog(env,
17206 						 env->insn_idx + insn->imm + 1);
17207 
17208 		if (!aux->func_info) {
17209 			verbose(env, "missing btf func_info\n");
17210 			return -EINVAL;
17211 		}
17212 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17213 			verbose(env, "callback function not static\n");
17214 			return -EINVAL;
17215 		}
17216 		/*
17217 		 * When env->subprog_cnt == 1 this instruction won't be rewritten
17218 		 * to hold a real function address. Assume that no usable program
17219 		 * combines e.g. main and timer callback and just reject here.
17220 		 */
17221 		if (subprogno == 0) {
17222 			verbose(env, "callback function cannot be the main program\n");
17223 			return -EINVAL;
17224 		}
17225 
17226 		dst_reg->type = PTR_TO_FUNC;
17227 		dst_reg->subprogno = subprogno;
17228 		bpf_diag_mod_end(env);
17229 		return 0;
17230 	}
17231 
17232 	map = env->used_maps[aux->map_index];
17233 
17234 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17235 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17236 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17237 			__mark_reg_unknown(env, dst_reg);
17238 			dst_reg->map_ptr = map;
17239 			bpf_diag_mod_end(env);
17240 			return 0;
17241 		}
17242 		__mark_reg_known(dst_reg, aux->map_off);
17243 		dst_reg->type = PTR_TO_MAP_VALUE;
17244 		dst_reg->map_ptr = map;
17245 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17246 			     map->max_entries != 1);
17247 		/* We want reg->id to be same (0) as map_value is not distinct */
17248 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17249 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17250 		dst_reg->type = CONST_PTR_TO_MAP;
17251 		dst_reg->map_ptr = map;
17252 	} else {
17253 		verifier_bug(env, "unexpected src reg value for ldimm64");
17254 		return -EFAULT;
17255 	}
17256 
17257 	bpf_diag_mod_end(env);
17258 	return 0;
17259 }
17260 
17261 static bool may_access_skb(enum bpf_prog_type type)
17262 {
17263 	switch (type) {
17264 	case BPF_PROG_TYPE_SOCKET_FILTER:
17265 	case BPF_PROG_TYPE_SCHED_CLS:
17266 	case BPF_PROG_TYPE_SCHED_ACT:
17267 		return true;
17268 	default:
17269 		return false;
17270 	}
17271 }
17272 
17273 /* verify safety of LD_ABS|LD_IND instructions:
17274  * - they can only appear in the programs where ctx == skb
17275  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17276  *   preserve R6-R9, and store return value into R0
17277  *
17278  * Implicit input:
17279  *   ctx == skb == R6 == CTX
17280  *
17281  * Explicit input:
17282  *   SRC == any register
17283  *   IMM == 32-bit immediate
17284  *
17285  * Output:
17286  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17287  */
17288 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17289 {
17290 	struct bpf_verifier_state *state = env->cur_state;
17291 	struct bpf_reg_state *regs = cur_regs(env);
17292 	static const int ctx_reg = BPF_REG_6;
17293 	u8 mode = BPF_MODE(insn->code);
17294 	int i, err;
17295 
17296 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17297 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17298 		return -EINVAL;
17299 	}
17300 
17301 	for (i = state->curframe; i; i--) {
17302 		if (state->frame[i]->in_callback_fn) {
17303 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
17304 			return -EINVAL;
17305 		}
17306 	}
17307 
17308 	if (!env->ops->gen_ld_abs) {
17309 		verifier_bug(env, "gen_ld_abs is null");
17310 		return -EFAULT;
17311 	}
17312 
17313 	/* check whether implicit source operand (register R6) is readable */
17314 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17315 	if (err)
17316 		return err;
17317 
17318 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17319 	 * gen_ld_abs() may terminate the program at runtime, leading to
17320 	 * reference leak.
17321 	 */
17322 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17323 	if (err)
17324 		return err;
17325 
17326 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17327 		verbose(env,
17328 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17329 		return -EINVAL;
17330 	}
17331 
17332 	if (mode == BPF_IND) {
17333 		/* check explicit source operand */
17334 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17335 		if (err)
17336 			return err;
17337 	}
17338 
17339 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17340 	if (err < 0)
17341 		return err;
17342 
17343 	/* reset caller saved regs to unreadable */
17344 	bpf_diag_record_caller_saved(env, regs);
17345 	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
17346 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17347 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
17348 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17349 	}
17350 
17351 	/* mark destination R0 register as readable, since it contains
17352 	 * the value fetched from the packet.
17353 	 * Already marked as written above.
17354 	 */
17355 	mark_reg_unknown(env, regs, BPF_REG_0);
17356 	bpf_diag_mod_end(env);
17357 	/*
17358 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
17359 	 * which must be explored by the verifier when in a subprog.
17360 	 */
17361 	if (env->cur_state->curframe) {
17362 		struct bpf_verifier_state *branch;
17363 
17364 		mark_reg_scratched(env, BPF_REG_0);
17365 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
17366 		if (IS_ERR(branch))
17367 			return PTR_ERR(branch);
17368 		mark_reg_known_zero(env, regs, BPF_REG_0);
17369 		err = prepare_func_exit(env, &env->insn_idx);
17370 		if (err)
17371 			return err;
17372 		env->insn_idx--;
17373 	}
17374 	return 0;
17375 }
17376 
17377 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
17378 {
17379 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17380 
17381 	/* Default return value range. */
17382 	*range = retval_range(0, 1);
17383 
17384 	switch (prog_type) {
17385 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17386 		switch (env->prog->expected_attach_type) {
17387 		case BPF_CGROUP_UDP4_RECVMSG:
17388 		case BPF_CGROUP_UDP6_RECVMSG:
17389 		case BPF_CGROUP_UNIX_RECVMSG:
17390 		case BPF_CGROUP_INET4_GETPEERNAME:
17391 		case BPF_CGROUP_INET6_GETPEERNAME:
17392 		case BPF_CGROUP_UNIX_GETPEERNAME:
17393 		case BPF_CGROUP_INET4_GETSOCKNAME:
17394 		case BPF_CGROUP_INET6_GETSOCKNAME:
17395 		case BPF_CGROUP_UNIX_GETSOCKNAME:
17396 			*range = retval_range(1, 1);
17397 			break;
17398 		case BPF_CGROUP_INET4_BIND:
17399 		case BPF_CGROUP_INET6_BIND:
17400 			*range = retval_range(0, 3);
17401 			break;
17402 		default:
17403 			break;
17404 		}
17405 		break;
17406 	case BPF_PROG_TYPE_CGROUP_SKB:
17407 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
17408 			*range = retval_range(0, 3);
17409 		break;
17410 	case BPF_PROG_TYPE_CGROUP_SOCK:
17411 	case BPF_PROG_TYPE_SOCK_OPS:
17412 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17413 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17414 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17415 		break;
17416 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17417 		if (!env->prog->aux->attach_btf_id)
17418 			return false;
17419 		*range = retval_range(0, 0);
17420 		break;
17421 	case BPF_PROG_TYPE_TRACING:
17422 		switch (env->prog->expected_attach_type) {
17423 		case BPF_TRACE_FENTRY:
17424 		case BPF_TRACE_FEXIT:
17425 		case BPF_TRACE_FSESSION:
17426 		case BPF_TRACE_FENTRY_MULTI:
17427 		case BPF_TRACE_FEXIT_MULTI:
17428 		case BPF_TRACE_FSESSION_MULTI:
17429 			*range = retval_range(0, 0);
17430 			break;
17431 		case BPF_TRACE_RAW_TP:
17432 		case BPF_MODIFY_RETURN:
17433 			return false;
17434 		case BPF_TRACE_ITER:
17435 		default:
17436 			break;
17437 		}
17438 		break;
17439 	case BPF_PROG_TYPE_KPROBE:
17440 		switch (env->prog->expected_attach_type) {
17441 		case BPF_TRACE_KPROBE_SESSION:
17442 		case BPF_TRACE_UPROBE_SESSION:
17443 			break;
17444 		default:
17445 			return false;
17446 		}
17447 		break;
17448 	case BPF_PROG_TYPE_SK_LOOKUP:
17449 		*range = retval_range(SK_DROP, SK_PASS);
17450 		break;
17451 
17452 	case BPF_PROG_TYPE_LSM:
17453 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17454 			/* no range found, any return value is allowed */
17455 			if (!get_func_retval_range(env->prog, range))
17456 				return false;
17457 			/* no restricted range, any return value is allowed */
17458 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
17459 				return false;
17460 			range->return_32bit = true;
17461 		} else if (!env->prog->aux->attach_func_proto->type) {
17462 			/* Make sure programs that attach to void
17463 			 * hooks don't try to modify return value.
17464 			 */
17465 			*range = retval_range(1, 1);
17466 		}
17467 		break;
17468 
17469 	case BPF_PROG_TYPE_NETFILTER:
17470 		*range = retval_range(NF_DROP, NF_ACCEPT);
17471 		break;
17472 	case BPF_PROG_TYPE_STRUCT_OPS:
17473 		*range = retval_range(0, 0);
17474 		break;
17475 	case BPF_PROG_TYPE_EXT:
17476 		/* freplace program can return anything as its return value
17477 		 * depends on the to-be-replaced kernel func or bpf program.
17478 		 */
17479 	default:
17480 		return false;
17481 	}
17482 
17483 	/* Continue calculating. */
17484 
17485 	return true;
17486 }
17487 
17488 static bool program_returns_void(struct bpf_verifier_env *env)
17489 {
17490 	const struct bpf_prog *prog = env->prog;
17491 	enum bpf_prog_type prog_type = prog->type;
17492 
17493 	switch (prog_type) {
17494 	case BPF_PROG_TYPE_LSM:
17495 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
17496 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
17497 		    !prog->aux->attach_func_proto->type)
17498 			return true;
17499 		break;
17500 	case BPF_PROG_TYPE_STRUCT_OPS:
17501 		if (!prog->aux->attach_func_proto->type)
17502 			return true;
17503 		break;
17504 	case BPF_PROG_TYPE_EXT:
17505 		/*
17506 		 * If the actual program is an extension, let it
17507 		 * return void - attaching will succeed only if the
17508 		 * program being replaced also returns void, and since
17509 		 * it has passed verification its actual type doesn't matter.
17510 		 */
17511 		if (subprog_returns_void(env, 0))
17512 			return true;
17513 		break;
17514 	default:
17515 		break;
17516 	}
17517 	return false;
17518 }
17519 
17520 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17521 {
17522 	const char *exit_ctx = "At program exit";
17523 	struct tnum enforce_attach_type_range = tnum_unknown;
17524 	const struct bpf_prog *prog = env->prog;
17525 	struct bpf_reg_state *reg = reg_state(env, regno);
17526 	struct bpf_retval_range range = retval_range(0, 1);
17527 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17528 	struct bpf_func_state *frame = env->cur_state->frame[0];
17529 	const struct btf_type *reg_type, *ret_type = NULL;
17530 	int err;
17531 
17532 	/* LSM and struct_ops func-ptr's return type could be "void" */
17533 	if (!frame->in_async_callback_fn && program_returns_void(env))
17534 		return 0;
17535 
17536 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
17537 		/* Allow a struct_ops program to return a referenced kptr if it
17538 		 * matches the operator's return type and is in its unmodified
17539 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
17540 		 */
17541 		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17542 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17543 						prog->aux->attach_func_proto->type,
17544 						NULL);
17545 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
17546 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
17547 	}
17548 
17549 	/* eBPF calling convention is such that R0 is used
17550 	 * to return the value from eBPF program.
17551 	 * Make sure that it's readable at this time
17552 	 * of bpf_exit, which means that program wrote
17553 	 * something into it earlier
17554 	 */
17555 	err = check_reg_arg(env, regno, SRC_OP);
17556 	if (err)
17557 		return err;
17558 
17559 	if (is_pointer_value(env, regno)) {
17560 		verbose(env, "R%d leaks addr as return value\n", regno);
17561 		return -EACCES;
17562 	}
17563 
17564 	if (frame->in_async_callback_fn) {
17565 		exit_ctx = "At async callback return";
17566 		range = frame->callback_ret_range;
17567 		goto enforce_retval;
17568 	}
17569 
17570 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
17571 		return 0;
17572 
17573 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
17574 		enforce_attach_type_range = tnum_range(2, 3);
17575 
17576 	if (!return_retval_range(env, &range))
17577 		return 0;
17578 
17579 enforce_retval:
17580 	if (reg->type != SCALAR_VALUE) {
17581 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17582 			exit_ctx, regno, reg_type_str(env, reg->type));
17583 		return -EINVAL;
17584 	}
17585 
17586 	err = mark_chain_precision(env, regno);
17587 	if (err)
17588 		return err;
17589 
17590 	if (!retval_range_within(range, reg)) {
17591 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17592 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
17593 		    prog_type == BPF_PROG_TYPE_LSM &&
17594 		    !prog->aux->attach_func_proto->type)
17595 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17596 		return -EINVAL;
17597 	}
17598 
17599 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17600 	    tnum_in(enforce_attach_type_range, reg->var_off))
17601 		env->prog->enforce_expected_attach_type = 1;
17602 	return 0;
17603 }
17604 
17605 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
17606 {
17607 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
17608 	struct bpf_func_state *cur_frame = cur_func(env);
17609 	int err;
17610 
17611 	if (subprog_returns_void(env, cur_frame->subprogno))
17612 		return 0;
17613 
17614 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
17615 	if (err)
17616 		return err;
17617 
17618 	/* Pointers to arena are safe to pass between subprograms. */
17619 	if (is_arena_reg(env, BPF_REG_0))
17620 		return 0;
17621 
17622 	if (is_pointer_value(env, BPF_REG_0)) {
17623 		verbose(env, "R%d leaks addr as return value\n", BPF_REG_0);
17624 		return -EACCES;
17625 	}
17626 
17627 	if (reg->type != SCALAR_VALUE) {
17628 		verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
17629 			reg_type_str(env, reg->type));
17630 		return -EINVAL;
17631 	}
17632 
17633 	return 0;
17634 }
17635 
17636 /* Bitmask with 1s for all caller saved registers */
17637 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17638 
17639 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17640  * replacement patch is presumed to follow bpf_fastcall contract
17641  * (see mark_fastcall_pattern_for_call() below).
17642  */
17643 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17644 {
17645 	switch (imm) {
17646 #ifdef CONFIG_X86_64
17647 	case BPF_FUNC_get_smp_processor_id:
17648 #ifdef CONFIG_SMP
17649 	case BPF_FUNC_get_current_task_btf:
17650 	case BPF_FUNC_get_current_task:
17651 #endif
17652 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17653 #endif
17654 	default:
17655 		return false;
17656 	}
17657 }
17658 
17659 /* If @call is a kfunc or helper call, fills @cs and returns true,
17660  * otherwise returns false.
17661  */
17662 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17663 			  struct bpf_call_summary *cs)
17664 {
17665 	struct bpf_call_arg_meta meta;
17666 	const struct bpf_func_proto *fn;
17667 	int i;
17668 
17669 	if (bpf_helper_call(call)) {
17670 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
17671 			/* error would be reported later */
17672 			return false;
17673 		cs->fastcall = fn->allow_fastcall &&
17674 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
17675 				bpf_jit_inlines_helper_call(call->imm));
17676 		cs->is_void = fn->ret_type == RET_VOID;
17677 		cs->num_params = 0;
17678 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17679 			if (fn->arg_type[i] == ARG_DONTCARE)
17680 				break;
17681 			cs->num_params++;
17682 		}
17683 		return true;
17684 	}
17685 
17686 	if (bpf_pseudo_kfunc_call(call)) {
17687 		int err;
17688 
17689 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
17690 		if (err < 0)
17691 			/* error would be reported later */
17692 			return false;
17693 		cs->num_params = btf_type_vlen(meta.func_proto);
17694 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17695 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17696 		return true;
17697 	}
17698 
17699 	return false;
17700 }
17701 
17702 /* LLVM define a bpf_fastcall function attribute.
17703  * This attribute means that function scratches only some of
17704  * the caller saved registers defined by ABI.
17705  * For BPF the set of such registers could be defined as follows:
17706  * - R0 is scratched only if function is non-void;
17707  * - R1-R5 are scratched only if corresponding parameter type is defined
17708  *   in the function prototype.
17709  *
17710  * The contract between kernel and clang allows to simultaneously use
17711  * such functions and maintain backwards compatibility with old
17712  * kernels that don't understand bpf_fastcall calls:
17713  *
17714  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17715  *   registers are not scratched by the call;
17716  *
17717  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17718  *   spill/fill for every live r0-r5;
17719  *
17720  * - stack offsets used for the spill/fill are allocated as lowest
17721  *   stack offsets in whole function and are not used for any other
17722  *   purposes;
17723  *
17724  * - when kernel loads a program, it looks for such patterns
17725  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17726  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17727  *
17728  * - if so, and if verifier or current JIT inlines the call to the
17729  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17730  *   spill/fill pairs;
17731  *
17732  * - when old kernel loads a program, presence of spill/fill pairs
17733  *   keeps BPF program valid, albeit slightly less efficient.
17734  *
17735  * For example:
17736  *
17737  *   r1 = 1;
17738  *   r2 = 2;
17739  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17740  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17741  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17742  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17743  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17744  *   r0 = r1;                            exit;
17745  *   r0 += r2;
17746  *   exit;
17747  *
17748  * The purpose of mark_fastcall_pattern_for_call is to:
17749  * - look for such patterns;
17750  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17751  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17752  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17753  *   at which bpf_fastcall spill/fill stack slots start;
17754  * - update env->subprog_info[*]->keep_fastcall_stack.
17755  *
17756  * The .fastcall_pattern and .fastcall_stack_off are used by
17757  * check_fastcall_stack_contract() to check if every stack access to
17758  * fastcall spill/fill stack slot originates from spill/fill
17759  * instructions, members of fastcall patterns.
17760  *
17761  * If such condition holds true for a subprogram, fastcall patterns could
17762  * be rewritten by remove_fastcall_spills_fills().
17763  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17764  * (code, presumably, generated by an older clang version).
17765  *
17766  * For example, it is *not* safe to remove spill/fill below:
17767  *
17768  *   r1 = 1;
17769  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17770  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17771  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17772  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17773  *   r0 += r1;                           exit;
17774  *   exit;
17775  *
17776  * Both uses of the marks assume that a pattern is entered at its first
17777  * spill and thus executes as a unit, hence a pattern is not grown past
17778  * an instruction targeted by a jump.
17779  */
17780 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17781 					   struct bpf_subprog_info *subprog,
17782 					   int insn_idx, s16 lowest_off)
17783 {
17784 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17785 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17786 	u32 clobbered_regs_mask;
17787 	struct bpf_call_summary cs;
17788 	u32 expected_regs_mask;
17789 	s16 off;
17790 	int i;
17791 
17792 	if (!bpf_get_call_summary(env, call, &cs))
17793 		return;
17794 
17795 	/* A bitmask specifying which caller saved registers are clobbered
17796 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17797 	 * bpf_fastcall contract:
17798 	 * - includes R0 if function is non-void;
17799 	 * - includes R1-R5 if corresponding parameter has is described
17800 	 *   in the function prototype.
17801 	 */
17802 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17803 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17804 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17805 
17806 	/* match pairs of form:
17807 	 *
17808 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17809 	 * ...
17810 	 * call %[to_be_inlined]
17811 	 * ...
17812 	 * rX = *(u64 *)(r10 - Y)
17813 	 */
17814 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17815 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17816 			break;
17817 		/* stx/ldx/call must not be a jump targets, a jump to the first stx is fine */
17818 		if (bpf_is_jump_target(env, insn_idx - i + 1) ||
17819 		    bpf_is_jump_target(env, insn_idx + i))
17820 			break;
17821 		stx = &insns[insn_idx - i];
17822 		ldx = &insns[insn_idx + i];
17823 		/* must be a stack spill/fill pair */
17824 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17825 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17826 		    stx->dst_reg != BPF_REG_10 ||
17827 		    ldx->src_reg != BPF_REG_10)
17828 			break;
17829 		/* must be a spill/fill for the same reg */
17830 		if (stx->src_reg != ldx->dst_reg)
17831 			break;
17832 		/* must be one of the previously unseen registers */
17833 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17834 			break;
17835 		/* must be a spill/fill for the same expected offset,
17836 		 * no need to check offset alignment, BPF_DW stack access
17837 		 * is always 8-byte aligned.
17838 		 */
17839 		if (stx->off != off || ldx->off != off)
17840 			break;
17841 		expected_regs_mask &= ~BIT(stx->src_reg);
17842 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17843 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17844 	}
17845 	if (i == 1)
17846 		return;
17847 
17848 	/* Conditionally set 'fastcall_spills_num' to allow forward
17849 	 * compatibility when more helper functions are marked as
17850 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17851 	 *
17852 	 *   1: *(u64 *)(r10 - 8) = r1
17853 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17854 	 *   3: r1 = *(u64 *)(r10 - 8)
17855 	 *   4: *(u64 *)(r10 - 8) = r1
17856 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17857 	 *   6: r1 = *(u64 *)(r10 - 8)
17858 	 *
17859 	 * There is no need to block bpf_fastcall rewrite for such program.
17860 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17861 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17862 	 * does not remove spill/fill pair {4,6}.
17863 	 */
17864 	if (cs.fastcall)
17865 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17866 	else
17867 		subprog->keep_fastcall_stack = 1;
17868 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17869 }
17870 
17871 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17872 {
17873 	struct bpf_subprog_info *subprog = env->subprog_info;
17874 	struct bpf_insn *insn;
17875 	s16 lowest_off;
17876 	int s, i;
17877 
17878 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17879 		/* find lowest stack spill offset used in this subprog */
17880 		lowest_off = 0;
17881 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17882 			insn = env->prog->insnsi + i;
17883 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17884 			    insn->dst_reg != BPF_REG_10)
17885 				continue;
17886 			lowest_off = min(lowest_off, insn->off);
17887 		}
17888 		/* use this offset to find fastcall patterns */
17889 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17890 			insn = env->prog->insnsi + i;
17891 			if (insn->code != (BPF_JMP | BPF_CALL))
17892 				continue;
17893 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17894 		}
17895 	}
17896 	return 0;
17897 }
17898 
17899 static void adjust_btf_func(struct bpf_verifier_env *env)
17900 {
17901 	struct bpf_prog_aux *aux = env->prog->aux;
17902 	int i;
17903 
17904 	if (!aux->func_info)
17905 		return;
17906 
17907 	/* func_info is not available for hidden subprogs */
17908 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
17909 		aux->func_info[i].insn_off = env->subprog_info[i].start;
17910 }
17911 
17912 /* Find id in idset and increment its count, or add new entry */
17913 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
17914 {
17915 	u32 i;
17916 
17917 	for (i = 0; i < idset->num_ids; i++) {
17918 		if (idset->entries[i].id == id) {
17919 			idset->entries[i].cnt++;
17920 			return;
17921 		}
17922 	}
17923 	/* New id */
17924 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
17925 		idset->entries[idset->num_ids].id = id;
17926 		idset->entries[idset->num_ids].cnt = 1;
17927 		idset->num_ids++;
17928 	}
17929 }
17930 
17931 /* Find id in idset and return its count, or 0 if not found */
17932 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
17933 {
17934 	u32 i;
17935 
17936 	for (i = 0; i < idset->num_ids; i++) {
17937 		if (idset->entries[i].id == id)
17938 			return idset->entries[i].cnt;
17939 	}
17940 	return 0;
17941 }
17942 
17943 /*
17944  * Clear singular scalar ids in a state.
17945  * A register with a non-zero id is called singular if no other register shares
17946  * the same base id. Such registers can be treated as independent (id=0).
17947  */
17948 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
17949 			    struct bpf_verifier_state *st)
17950 {
17951 	struct bpf_idset *idset = &env->idset_scratch;
17952 	struct bpf_func_state *func;
17953 	struct bpf_reg_state *reg;
17954 
17955 	idset->num_ids = 0;
17956 
17957 	bpf_for_each_reg_in_vstate(st, func, reg, ({
17958 		if (reg->type != SCALAR_VALUE)
17959 			continue;
17960 		if (!reg->id)
17961 			continue;
17962 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
17963 	}));
17964 
17965 	bpf_for_each_reg_in_vstate(st, func, reg, ({
17966 		if (reg->type != SCALAR_VALUE)
17967 			continue;
17968 		if (!reg->id)
17969 			continue;
17970 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
17971 			clear_scalar_id(reg);
17972 	}));
17973 }
17974 
17975 /* Return true if it's OK to have the same insn return a different type. */
17976 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17977 {
17978 	switch (base_type(type)) {
17979 	case PTR_TO_CTX:
17980 	case PTR_TO_SOCKET:
17981 	case PTR_TO_SOCK_COMMON:
17982 	case PTR_TO_TCP_SOCK:
17983 	case PTR_TO_XDP_SOCK:
17984 	case PTR_TO_BTF_ID:
17985 	case PTR_TO_ARENA:
17986 		return false;
17987 	case PTR_TO_MEM:
17988 		return !bpf_may_fault_on_deref(type);
17989 	default:
17990 		return true;
17991 	}
17992 }
17993 
17994 /* If an instruction was previously used with particular pointer types, then we
17995  * need to be careful to avoid cases such as the below, where it may be ok
17996  * for one branch accessing the pointer, but not ok for the other branch:
17997  *
17998  * R1 = sock_ptr
17999  * goto X;
18000  * ...
18001  * R1 = some_other_valid_ptr;
18002  * goto X;
18003  * ...
18004  * R2 = *(u32 *)(R1 + 0);
18005  */
18006 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18007 {
18008 	return src != prev && (!reg_type_mismatch_ok(src) ||
18009 			       !reg_type_mismatch_ok(prev));
18010 }
18011 
18012 static bool is_ptr_to_mem(enum bpf_reg_type type)
18013 {
18014 	return base_type(type) == PTR_TO_MEM;
18015 }
18016 
18017 static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a,
18018 					 enum bpf_reg_type type_b)
18019 {
18020 	bool to_mem = is_ptr_to_mem(type_a) || is_ptr_to_mem(type_b);
18021 	enum bpf_reg_type type_merged = to_mem ? PTR_TO_MEM : PTR_TO_BTF_ID;
18022 
18023 	if (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b))
18024 		type_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED :
18025 					PTR_UNTRUSTED;
18026 	else
18027 		type_merged |= ((type_a | type_b) & MEM_RDONLY);
18028 	return type_merged;
18029 }
18030 
18031 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18032 			     bool allow_trust_mismatch)
18033 {
18034 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18035 
18036 	if (*prev_type == NOT_INIT) {
18037 		/* Saw a valid insn
18038 		 * dst_reg = *(u32 *)(src_reg + off)
18039 		 * save type to validate intersecting paths
18040 		 */
18041 		*prev_type = type;
18042 	} else if (reg_type_mismatch(type, *prev_type)) {
18043 		/* Abuser program is trying to use the same insn
18044 		 * dst_reg = *(u32*) (src_reg + off)
18045 		 * with different pointer types:
18046 		 * src_reg == ctx in one branch and
18047 		 * src_reg == stack|map in some other branch.
18048 		 * Reject it.
18049 		 */
18050 		if (allow_trust_mismatch &&
18051 		    bpf_is_ptr_to_mem_or_btf_id(type) &&
18052 		    bpf_is_ptr_to_mem_or_btf_id(*prev_type)) {
18053 			/*
18054 			 * Have to support a use case when one path through
18055 			 * the program yields a TRUSTED pointer while another
18056 			 * is UNTRUSTED. Merge them into a type which keeps
18057 			 * the BPF_PROBE_MEM/BPF_PROBE_MEMSX rewrite when
18058 			 * either side needs it.
18059 			 */
18060 			*prev_type = merge_ptr_types(type, *prev_type);
18061 		} else {
18062 			verbose(env, "same insn cannot be used with different pointers\n");
18063 			return -EINVAL;
18064 		}
18065 	}
18066 
18067 	return 0;
18068 }
18069 
18070 enum {
18071 	PROCESS_BPF_EXIT = 1,
18072 	INSN_IDX_UPDATED = 2,
18073 };
18074 
18075 static int process_bpf_exit_full(struct bpf_verifier_env *env,
18076 				 bool *do_print_state,
18077 				 bool exception_exit)
18078 {
18079 	struct bpf_func_state *cur_frame = cur_func(env);
18080 
18081 	/* We must do check_reference_leak here before
18082 	 * prepare_func_exit to handle the case when
18083 	 * state->curframe > 0, it may be a callback function,
18084 	 * for which reference_state must match caller reference
18085 	 * state when it exits.
18086 	 */
18087 	int err = check_resource_leak(env, exception_exit,
18088 				      exception_exit || !env->cur_state->curframe,
18089 				      exception_exit ? "bpf_throw" :
18090 				      "BPF_EXIT instruction in main prog");
18091 	if (err)
18092 		return err;
18093 
18094 	/* The side effect of the prepare_func_exit which is
18095 	 * being skipped is that it frees bpf_func_state.
18096 	 * Typically, process_bpf_exit will only be hit with
18097 	 * outermost exit. copy_verifier_state in pop_stack will
18098 	 * handle freeing of any extra bpf_func_state left over
18099 	 * from not processing all nested function exits. We
18100 	 * also skip return code checks as they are not needed
18101 	 * for exceptional exits.
18102 	 */
18103 	if (exception_exit)
18104 		return PROCESS_BPF_EXIT;
18105 
18106 	if (env->cur_state->curframe) {
18107 		/* exit from nested function */
18108 		err = prepare_func_exit(env, &env->insn_idx);
18109 		if (err)
18110 			return err;
18111 		*do_print_state = true;
18112 		return INSN_IDX_UPDATED;
18113 	}
18114 
18115 	/*
18116 	 * Return from a regular global subprogram differs from return
18117 	 * from the main program or async/exception callback.
18118 	 * Main program exit implies return code restrictions
18119 	 * that depend on program type.
18120 	 * Exit from exception callback is equivalent to main program exit.
18121 	 * Exit from async callback implies return code restrictions
18122 	 * that depend on async scheduling mechanism.
18123 	 */
18124 	if (cur_frame->subprogno &&
18125 	    !cur_frame->in_async_callback_fn &&
18126 	    !cur_frame->in_exception_callback_fn)
18127 		err = check_global_subprog_return_code(env);
18128 	else
18129 		err = check_return_code(env, BPF_REG_0, "R0");
18130 	if (err)
18131 		return err;
18132 	return PROCESS_BPF_EXIT;
18133 }
18134 
18135 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
18136 				       int regno,
18137 				       struct bpf_map *map,
18138 				       u32 *pmin_index, u32 *pmax_index)
18139 {
18140 	struct bpf_reg_state *reg = reg_state(env, regno);
18141 	u64 min_index = reg_umin(reg);
18142 	u64 max_index = reg_umax(reg);
18143 	const u32 size = 8;
18144 
18145 	if (min_index > (u64) U32_MAX * size) {
18146 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
18147 		return -ERANGE;
18148 	}
18149 	if (max_index > (u64) U32_MAX * size) {
18150 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
18151 		return -ERANGE;
18152 	}
18153 
18154 	min_index /= size;
18155 	max_index /= size;
18156 
18157 	if (max_index >= map->max_entries) {
18158 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
18159 			     regno, min_index, max_index, map->max_entries);
18160 		return -EINVAL;
18161 	}
18162 
18163 	*pmin_index = min_index;
18164 	*pmax_index = max_index;
18165 	return 0;
18166 }
18167 
18168 /* gotox *dst_reg */
18169 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
18170 {
18171 	struct bpf_verifier_state *other_branch;
18172 	struct bpf_reg_state *dst_reg;
18173 	struct bpf_map *map;
18174 	u32 min_index, max_index;
18175 	int err = 0;
18176 	int n;
18177 	int i;
18178 
18179 	dst_reg = reg_state(env, insn->dst_reg);
18180 	if (dst_reg->type != PTR_TO_INSN) {
18181 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
18182 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
18183 		return -EINVAL;
18184 	}
18185 
18186 	map = dst_reg->map_ptr;
18187 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
18188 		return -EFAULT;
18189 
18190 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
18191 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
18192 		return -EFAULT;
18193 
18194 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
18195 	if (err)
18196 		return err;
18197 
18198 	/* Ensure that the buffer is large enough */
18199 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
18200 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
18201 						        max_index - min_index + 1);
18202 		if (!env->gotox_tmp_buf)
18203 			return -ENOMEM;
18204 	}
18205 
18206 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
18207 	if (n < 0)
18208 		return n;
18209 	if (n == 0) {
18210 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
18211 			     insn->dst_reg, map->id);
18212 		return -EINVAL;
18213 	}
18214 
18215 	for (i = 0; i < n - 1; i++) {
18216 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
18217 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
18218 					  env->insn_idx, env->cur_state->speculative);
18219 		if (IS_ERR(other_branch))
18220 			return PTR_ERR(other_branch);
18221 	}
18222 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
18223 	mark_indirect_target(env, env->insn_idx);
18224 	return INSN_IDX_UPDATED;
18225 }
18226 
18227 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
18228 {
18229 	int err;
18230 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
18231 	u8 class = BPF_CLASS(insn->code);
18232 
18233 	switch (class) {
18234 	case BPF_ALU:
18235 	case BPF_ALU64:
18236 		return check_alu_op(env, insn);
18237 
18238 	case BPF_LDX:
18239 		return check_load_mem(env, insn, false,
18240 				      BPF_MODE(insn->code) == BPF_MEMSX,
18241 				      true, "ldx");
18242 
18243 	case BPF_STX:
18244 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
18245 			return check_atomic(env, insn);
18246 		return check_store_reg(env, insn, false);
18247 
18248 	case BPF_ST: {
18249 		/* Handle stack arg write (store immediate) */
18250 		if (is_stack_arg_st(insn)) {
18251 			struct bpf_verifier_state *vstate = env->cur_state;
18252 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
18253 
18254 			return check_stack_arg_write(env, state, insn->off, NULL);
18255 		}
18256 
18257 		enum bpf_reg_type dst_reg_type;
18258 
18259 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18260 		if (err)
18261 			return err;
18262 
18263 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
18264 
18265 		err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg),
18266 				       insn->off, BPF_SIZE(insn->code),
18267 				       BPF_WRITE, -1, false, false);
18268 		if (err)
18269 			return err;
18270 
18271 		return save_aux_ptr_type(env, dst_reg_type, false);
18272 	}
18273 	case BPF_JMP:
18274 	case BPF_JMP32: {
18275 		u8 opcode = BPF_OP(insn->code);
18276 
18277 		env->jmps_processed++;
18278 		if (opcode == BPF_CALL) {
18279 			if (env->cur_state->active_locks) {
18280 				if ((insn->src_reg == BPF_REG_0 &&
18281 				     insn->imm != BPF_FUNC_spin_unlock &&
18282 				     insn->imm != BPF_FUNC_kptr_xchg) ||
18283 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
18284 				     !kfunc_spin_allowed(env, insn->imm, insn->off))) {
18285 					verbose(env,
18286 						"function calls are not allowed while holding a lock\n");
18287 					bpf_diag_ctx_active(
18288 						env, env->insn_idx,
18289 						"function call", BPF_DIAG_CONTEXT_LOCK,
18290 						"Release the BPF spin lock before making this call, or move the call outside the locked region.");
18291 					return -EINVAL;
18292 				}
18293 			}
18294 			mark_reg_scratched(env, BPF_REG_0);
18295 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
18296 				cur_func(env)->no_stack_arg_load = true;
18297 			if (insn->src_reg == BPF_PSEUDO_CALL)
18298 				return check_func_call(env, insn, &env->insn_idx);
18299 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
18300 				return check_kfunc_call(env, insn, &env->insn_idx);
18301 			return check_helper_call(env, insn, &env->insn_idx);
18302 		} else if (opcode == BPF_JA) {
18303 			if (BPF_SRC(insn->code) == BPF_X)
18304 				return check_indirect_jump(env, insn);
18305 
18306 			if (class == BPF_JMP)
18307 				env->insn_idx += insn->off + 1;
18308 			else
18309 				env->insn_idx += insn->imm + 1;
18310 			return INSN_IDX_UPDATED;
18311 		} else if (opcode == BPF_EXIT) {
18312 			return process_bpf_exit_full(env, do_print_state, false);
18313 		}
18314 		return check_cond_jmp_op(env, insn, &env->insn_idx);
18315 	}
18316 	case BPF_LD: {
18317 		u8 mode = BPF_MODE(insn->code);
18318 
18319 		if (mode == BPF_ABS || mode == BPF_IND)
18320 			return check_ld_abs(env, insn);
18321 
18322 		if (mode == BPF_IMM) {
18323 			err = check_ld_imm(env, insn);
18324 			if (err)
18325 				return err;
18326 
18327 			env->insn_idx++;
18328 			sanitize_mark_insn_seen(env);
18329 		}
18330 		return 0;
18331 	}
18332 	}
18333 	/* all class values are handled above. silence compiler warning */
18334 	return -EFAULT;
18335 }
18336 
18337 static int do_check(struct bpf_verifier_env *env)
18338 {
18339 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18340 	struct bpf_verifier_state *state = env->cur_state;
18341 	struct bpf_insn *insns = env->prog->insnsi;
18342 	int insn_cnt = env->prog->len;
18343 	bool do_print_state = false;
18344 	int prev_insn_idx = -1;
18345 
18346 	for (;;) {
18347 		struct bpf_insn *insn;
18348 		struct bpf_insn_aux_data *insn_aux;
18349 		int err;
18350 
18351 		/* reset current history entry on each new instruction */
18352 		env->cur_hist_ent = NULL;
18353 
18354 		env->prev_insn_idx = prev_insn_idx;
18355 		if (env->insn_idx >= insn_cnt) {
18356 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
18357 				env->insn_idx, insn_cnt);
18358 			return -EFAULT;
18359 		}
18360 
18361 		insn = &insns[env->insn_idx];
18362 		insn_aux = &env->insn_aux_data[env->insn_idx];
18363 
18364 		account_processed_insn(env);
18365 
18366 		if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18367 			verbose(env,
18368 				"BPF program is too large. Processed %d insn\n",
18369 				env->insn_processed);
18370 			return -E2BIG;
18371 		}
18372 
18373 		state->last_insn_idx = env->prev_insn_idx;
18374 		state->insn_idx = env->insn_idx;
18375 		/*
18376 		 * Record the incoming edge so active and queued paths use the same
18377 		 * branch-recording path. A zero-offset conditional has identical
18378 		 * successors, so its outcome cannot be reconstructed from the edge.
18379 		 */
18380 		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
18381 			struct bpf_insn *prev_insn = &insns[prev_insn_idx];
18382 			int fallthrough_idx = prev_insn_idx + 1;
18383 			int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1;
18384 			u8 class = BPF_CLASS(prev_insn->code);
18385 			u8 opcode = BPF_OP(prev_insn->code);
18386 
18387 			if ((class == BPF_JMP || class == BPF_JMP32) &&
18388 			    opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT &&
18389 			    opcode <= BPF_JCOND && branch_idx != fallthrough_idx) {
18390 				if (env->insn_idx == branch_idx)
18391 					bpf_diag_record_branch(env, prev_insn_idx, true);
18392 				else if (env->insn_idx == fallthrough_idx)
18393 					bpf_diag_record_branch(env, prev_insn_idx, false);
18394 			}
18395 		}
18396 
18397 		if (bpf_is_prune_point(env, env->insn_idx)) {
18398 			err = bpf_is_state_visited(env, env->insn_idx);
18399 			if (err < 0)
18400 				return err;
18401 			if (err == 1) {
18402 				/* found equivalent state, can prune the search */
18403 				if (env->log.level & BPF_LOG_LEVEL) {
18404 					if (do_print_state)
18405 						verbose(env, "\nfrom %d to %d%s: safe\n",
18406 							env->prev_insn_idx, env->insn_idx,
18407 							env->cur_state->speculative ?
18408 							" (speculative execution)" : "");
18409 					else
18410 						verbose(env, "%d: safe\n", env->insn_idx);
18411 				}
18412 				goto process_bpf_exit;
18413 			}
18414 		}
18415 
18416 		if (bpf_is_jmp_point(env, env->insn_idx)) {
18417 			err = bpf_push_jmp_history(env, state, 0, 0, 0, 0);
18418 			if (err)
18419 				return err;
18420 		}
18421 
18422 		if (signal_pending(current))
18423 			return -EAGAIN;
18424 
18425 		if (need_resched())
18426 			cond_resched();
18427 
18428 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18429 			verbose(env, "\nfrom %d to %d%s:",
18430 				env->prev_insn_idx, env->insn_idx,
18431 				env->cur_state->speculative ?
18432 				" (speculative execution)" : "");
18433 			print_verifier_state(env, state, state->curframe, true);
18434 			do_print_state = false;
18435 		}
18436 
18437 		if (env->log.level & BPF_LOG_LEVEL) {
18438 			if (verifier_state_scratched(env))
18439 				print_insn_state(env, state, state->curframe);
18440 
18441 			verbose_linfo(env, env->insn_idx, "; ");
18442 			env->prev_log_pos = env->log.end_pos;
18443 			verbose(env, "%d: ", env->insn_idx);
18444 			bpf_verbose_insn(env, insn);
18445 			verbose(env, "\n");
18446 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
18447 			env->prev_log_pos = env->log.end_pos;
18448 		}
18449 
18450 		if (bpf_prog_is_offloaded(env->prog->aux)) {
18451 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
18452 							   env->prev_insn_idx);
18453 			if (err)
18454 				return err;
18455 		}
18456 
18457 		sanitize_mark_insn_seen(env);
18458 		prev_insn_idx = env->insn_idx;
18459 
18460 		/* Sanity check: precomputed constants must match verifier state */
18461 		if (!state->speculative && insn_aux->const_reg_mask) {
18462 			struct bpf_reg_state *regs = cur_regs(env);
18463 			u16 mask = insn_aux->const_reg_mask;
18464 
18465 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
18466 				u32 cval = insn_aux->const_reg_vals[r];
18467 
18468 				if (!(mask & BIT(r)))
18469 					continue;
18470 				if (regs[r].type != SCALAR_VALUE)
18471 					continue;
18472 				if (!tnum_is_const(regs[r].var_off))
18473 					continue;
18474 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
18475 						    env, "const R%d: %u != %llu",
18476 						    r, cval, regs[r].var_off.value))
18477 					return -EFAULT;
18478 			}
18479 		}
18480 
18481 		/* Reduce verification complexity by stopping speculative path
18482 		 * verification when a nospec is encountered.
18483 		 */
18484 		if (state->speculative && insn_aux->nospec)
18485 			goto process_bpf_exit;
18486 
18487 		err = do_check_insn(env, &do_print_state);
18488 		if (error_recoverable_with_nospec(err) && state->speculative) {
18489 			/* Prevent this speculative path from ever reaching the
18490 			 * insn that would have been unsafe to execute.
18491 			 */
18492 			insn_aux->nospec = true;
18493 			/* If it was an ADD/SUB insn, potentially remove any
18494 			 * markings for alu sanitization.
18495 			 */
18496 			insn_aux->alu_state = 0;
18497 			goto process_bpf_exit;
18498 		} else if (err < 0) {
18499 			return err;
18500 		} else if (err == PROCESS_BPF_EXIT) {
18501 			goto process_bpf_exit;
18502 		} else if (err == INSN_IDX_UPDATED) {
18503 		} else if (err == 0) {
18504 			env->insn_idx++;
18505 		}
18506 
18507 		if (state->speculative && insn_aux->nospec_result) {
18508 			/* If we are on a path that performed a jump-op, this
18509 			 * may skip a nospec patched-in after the jump. This can
18510 			 * currently never happen because nospec_result is only
18511 			 * used for the write-ops
18512 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
18513 			 * calls. These must never skip the following insn
18514 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
18515 			 * is false). Still, add a warning to document this in
18516 			 * case nospec_result is used elsewhere in the future.
18517 			 *
18518 			 * All non-branch instructions have a single
18519 			 * fall-through edge. For these, nospec_result should
18520 			 * already work.
18521 			 */
18522 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
18523 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
18524 					    BPF_OP(insn->code) != BPF_CALL, env,
18525 					    "speculation barrier after jump instruction may not have the desired effect"))
18526 				return -EFAULT;
18527 process_bpf_exit:
18528 			account_current_path(env);
18529 			mark_verifier_state_scratched(env);
18530 			err = bpf_update_branch_counts(env, env->cur_state);
18531 			if (err)
18532 				return err;
18533 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
18534 					pop_log);
18535 			if (err < 0) {
18536 				if (err != -ENOENT)
18537 					return err;
18538 				break;
18539 			} else {
18540 				do_print_state = true;
18541 				continue;
18542 			}
18543 		}
18544 	}
18545 
18546 	return 0;
18547 }
18548 
18549 static int find_btf_percpu_datasec(struct btf *btf)
18550 {
18551 	const struct btf_type *t;
18552 	const char *tname;
18553 	int i, n;
18554 
18555 	/*
18556 	 * Both vmlinux and module each have their own ".data..percpu"
18557 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18558 	 * types to look at only module's own BTF types.
18559 	 */
18560 	n = btf_nr_types(btf);
18561 	for (i = btf_named_start_id(btf, true); i < n; i++) {
18562 		t = btf_type_by_id(btf, i);
18563 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18564 			continue;
18565 
18566 		tname = btf_name_by_offset(btf, t->name_off);
18567 		if (!strcmp(tname, ".data..percpu"))
18568 			return i;
18569 	}
18570 
18571 	return -ENOENT;
18572 }
18573 
18574 /*
18575  * Add btf to the env->used_btfs array. If needed, refcount the
18576  * corresponding kernel module. To simplify caller's logic
18577  * in case of error or if btf was added before the function
18578  * decreases the btf refcount.
18579  */
18580 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
18581 {
18582 	struct btf_mod_pair *btf_mod;
18583 	int ret = 0;
18584 	int i;
18585 
18586 	/* check whether we recorded this BTF (and maybe module) already */
18587 	for (i = 0; i < env->used_btf_cnt; i++)
18588 		if (env->used_btfs[i].btf == btf)
18589 			goto ret_put;
18590 
18591 	if (env->signature) {
18592 		verbose(env, "signed program cannot bind any BTF\n");
18593 		ret = -EACCES;
18594 		goto ret_put;
18595 	}
18596 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18597 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
18598 			MAX_USED_BTFS);
18599 		ret = -E2BIG;
18600 		goto ret_put;
18601 	}
18602 
18603 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18604 	btf_mod->btf = btf;
18605 	btf_mod->module = NULL;
18606 
18607 	/* if we reference variables from kernel module, bump its refcount */
18608 	if (btf_is_module(btf)) {
18609 		btf_mod->module = btf_try_get_module(btf);
18610 		if (!btf_mod->module) {
18611 			ret = -ENXIO;
18612 			goto ret_put;
18613 		}
18614 	}
18615 
18616 	env->used_btf_cnt++;
18617 	return 0;
18618 
18619 ret_put:
18620 	/* Either error or this BTF was already added */
18621 	btf_put(btf);
18622 	return ret;
18623 }
18624 
18625 /* replace pseudo btf_id with kernel symbol address */
18626 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
18627 				 struct bpf_insn *insn,
18628 				 struct bpf_insn_aux_data *aux,
18629 				 struct btf *btf)
18630 {
18631 	const struct btf_var_secinfo *vsi;
18632 	const struct btf_type *datasec;
18633 	const struct btf_type *t;
18634 	const char *sym_name;
18635 	bool percpu = false;
18636 	u32 type, id = insn->imm;
18637 	s32 datasec_id;
18638 	u64 addr;
18639 	int i;
18640 
18641 	t = btf_type_by_id(btf, id);
18642 	if (!t) {
18643 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18644 		return -ENOENT;
18645 	}
18646 
18647 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18648 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18649 		return -EINVAL;
18650 	}
18651 
18652 	sym_name = btf_name_by_offset(btf, t->name_off);
18653 	addr = kallsyms_lookup_name(sym_name);
18654 	if (!addr) {
18655 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18656 			sym_name);
18657 		return -ENOENT;
18658 	}
18659 	insn[0].imm = (u32)addr;
18660 	insn[1].imm = addr >> 32;
18661 
18662 	if (btf_type_is_func(t)) {
18663 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18664 		aux->btf_var.mem_size = 0;
18665 		return 0;
18666 	}
18667 
18668 	datasec_id = find_btf_percpu_datasec(btf);
18669 	if (datasec_id > 0) {
18670 		datasec = btf_type_by_id(btf, datasec_id);
18671 		for_each_vsi(i, datasec, vsi) {
18672 			if (vsi->type == id) {
18673 				percpu = true;
18674 				break;
18675 			}
18676 		}
18677 	}
18678 
18679 	type = t->type;
18680 	t = btf_type_skip_modifiers(btf, type, NULL);
18681 	if (percpu) {
18682 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18683 		aux->btf_var.btf = btf;
18684 		aux->btf_var.btf_id = type;
18685 	} else if (!btf_type_is_struct(t)) {
18686 		const struct btf_type *ret;
18687 		const char *tname;
18688 		u32 tsize;
18689 
18690 		/* resolve the type size of ksym. */
18691 		ret = btf_resolve_size(btf, t, &tsize);
18692 		if (IS_ERR(ret)) {
18693 			tname = btf_name_by_offset(btf, t->name_off);
18694 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18695 				tname, PTR_ERR(ret));
18696 			return -EINVAL;
18697 		}
18698 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18699 		aux->btf_var.mem_size = tsize;
18700 	} else {
18701 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18702 		aux->btf_var.btf = btf;
18703 		aux->btf_var.btf_id = type;
18704 	}
18705 
18706 	return 0;
18707 }
18708 
18709 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18710 			       struct bpf_insn *insn,
18711 			       struct bpf_insn_aux_data *aux)
18712 {
18713 	struct btf *btf;
18714 	int btf_fd;
18715 	int err;
18716 
18717 	btf_fd = insn[1].imm;
18718 	if (btf_fd) {
18719 		btf = btf_get_by_fd(btf_fd);
18720 		if (IS_ERR(btf)) {
18721 			verbose(env, "invalid module BTF object FD specified.\n");
18722 			return -EINVAL;
18723 		}
18724 	} else {
18725 		if (!btf_vmlinux) {
18726 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18727 			return -EINVAL;
18728 		}
18729 		btf_get(btf_vmlinux);
18730 		btf = btf_vmlinux;
18731 	}
18732 
18733 	err = __check_pseudo_btf_id(env, insn, aux, btf);
18734 	if (err) {
18735 		btf_put(btf);
18736 		return err;
18737 	}
18738 
18739 	return __add_used_btf(env, btf);
18740 }
18741 
18742 static bool is_tracing_prog_type(enum bpf_prog_type type)
18743 {
18744 	switch (type) {
18745 	case BPF_PROG_TYPE_KPROBE:
18746 	case BPF_PROG_TYPE_TRACEPOINT:
18747 	case BPF_PROG_TYPE_PERF_EVENT:
18748 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18749 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18750 		return true;
18751 	default:
18752 		return false;
18753 	}
18754 }
18755 
18756 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18757 {
18758 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18759 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18760 }
18761 
18762 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18763 					struct bpf_map *map,
18764 					struct bpf_prog *prog)
18765 
18766 {
18767 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18768 
18769 	if (map->excl_prog_sha &&
18770 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
18771 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
18772 		return -EACCES;
18773 	}
18774 
18775 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18776 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18777 		if (is_tracing_prog_type(prog_type)) {
18778 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18779 			return -EINVAL;
18780 		}
18781 	}
18782 
18783 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
18784 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18785 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18786 			return -EINVAL;
18787 		}
18788 	}
18789 
18790 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18791 		if (is_tracing_prog_type(prog_type)) {
18792 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18793 			return -EINVAL;
18794 		}
18795 	}
18796 
18797 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18798 	    !bpf_offload_prog_map_match(prog, map)) {
18799 		verbose(env, "offload device mismatch between prog and map\n");
18800 		return -EINVAL;
18801 	}
18802 
18803 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18804 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18805 		return -EINVAL;
18806 	}
18807 
18808 	if (prog->sleepable)
18809 		switch (map->map_type) {
18810 		case BPF_MAP_TYPE_HASH:
18811 		case BPF_MAP_TYPE_RHASH:
18812 		case BPF_MAP_TYPE_LRU_HASH:
18813 		case BPF_MAP_TYPE_ARRAY:
18814 		case BPF_MAP_TYPE_PERCPU_HASH:
18815 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18816 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18817 		case BPF_MAP_TYPE_LPM_TRIE:
18818 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18819 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18820 		case BPF_MAP_TYPE_RINGBUF:
18821 		case BPF_MAP_TYPE_USER_RINGBUF:
18822 		case BPF_MAP_TYPE_INODE_STORAGE:
18823 		case BPF_MAP_TYPE_SK_STORAGE:
18824 		case BPF_MAP_TYPE_TASK_STORAGE:
18825 		case BPF_MAP_TYPE_CGRP_STORAGE:
18826 		case BPF_MAP_TYPE_QUEUE:
18827 		case BPF_MAP_TYPE_STACK:
18828 		case BPF_MAP_TYPE_ARENA:
18829 		case BPF_MAP_TYPE_INSN_ARRAY:
18830 		case BPF_MAP_TYPE_PROG_ARRAY:
18831 			break;
18832 		default:
18833 			verbose(env,
18834 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18835 			return -EINVAL;
18836 		}
18837 
18838 	if (bpf_map_is_cgroup_storage(map) &&
18839 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18840 		verbose(env, "only one cgroup storage of each type is allowed\n");
18841 		return -EBUSY;
18842 	}
18843 
18844 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
18845 		if (env->prog->aux->arena) {
18846 			verbose(env, "Only one arena per program\n");
18847 			return -EBUSY;
18848 		}
18849 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
18850 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18851 			return -EPERM;
18852 		}
18853 		if (!env->prog->jit_requested) {
18854 			verbose(env, "JIT is required to use arena\n");
18855 			return -EOPNOTSUPP;
18856 		}
18857 		if (!bpf_jit_supports_arena()) {
18858 			verbose(env, "JIT doesn't support arena\n");
18859 			return -EOPNOTSUPP;
18860 		}
18861 		env->prog->aux->arena = (void *)map;
18862 		env->prog->jit_required = true;
18863 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18864 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18865 			return -EINVAL;
18866 		}
18867 	}
18868 
18869 	return 0;
18870 }
18871 
18872 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
18873 {
18874 	int i, err;
18875 
18876 	/* check whether we recorded this map already */
18877 	for (i = 0; i < env->used_map_cnt; i++)
18878 		if (env->used_maps[i] == map)
18879 			return i;
18880 
18881 	if (env->signature &&
18882 	    env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) {
18883 		verbose(env, "signed program cannot bind map '%s' not covered by the signature\n",
18884 			map->name);
18885 		return -EACCES;
18886 	}
18887 	if (env->used_map_cnt >= MAX_USED_MAPS) {
18888 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
18889 			MAX_USED_MAPS);
18890 		return -E2BIG;
18891 	}
18892 
18893 	err = check_map_prog_compatibility(env, map, env->prog);
18894 	if (err)
18895 		return err;
18896 
18897 	if (env->prog->sleepable)
18898 		atomic64_inc(&map->sleepable_refcnt);
18899 
18900 	/* hold the map. If the program is rejected by verifier,
18901 	 * the map will be released by release_maps() or it
18902 	 * will be used by the valid program until it's unloaded
18903 	 * and all maps are released in bpf_free_used_maps()
18904 	 */
18905 	bpf_map_inc(map);
18906 
18907 	env->used_maps[env->used_map_cnt++] = map;
18908 
18909 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
18910 		err = bpf_insn_array_init(map, env->prog);
18911 		if (err) {
18912 			verbose(env, "Failed to properly initialize insn array\n");
18913 			return err;
18914 		}
18915 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
18916 		env->prog->jit_required = true;
18917 	}
18918 
18919 	return env->used_map_cnt - 1;
18920 }
18921 
18922 /* Add map behind fd to used maps list, if it's not already there, and return
18923  * its index.
18924  * Returns <0 on error, or >= 0 index, on success.
18925  */
18926 static int add_used_map(struct bpf_verifier_env *env, int fd)
18927 {
18928 	struct bpf_map *map;
18929 	CLASS(fd, f)(fd);
18930 
18931 	map = __bpf_map_get(f);
18932 	if (IS_ERR(map)) {
18933 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18934 		return PTR_ERR(map);
18935 	}
18936 
18937 	return __add_used_map(env, map);
18938 }
18939 
18940 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx)
18941 {
18942 	struct bpf_map *map;
18943 
18944 	if (idx >= env->fd_array_cnt) {
18945 		verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n",
18946 			idx, env->fd_array_cnt);
18947 		return -EINVAL;
18948 	}
18949 	map = fd_slot_map(env->fd_array[idx]);
18950 	if (!map) {
18951 		verbose(env, "fd_idx %u is not a map\n", idx);
18952 		return -EINVAL;
18953 	}
18954 	return __add_used_map(env, map);
18955 }
18956 
18957 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx)
18958 {
18959 	int fd;
18960 
18961 	if (copy_from_bpfptr_offset(&fd, env->fd_array_raw,
18962 				    (size_t)idx * sizeof(fd), sizeof(fd)))
18963 		return -EFAULT;
18964 	return add_used_map(env, fd);
18965 }
18966 
18967 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx)
18968 {
18969 	if (env->fd_array)
18970 		return fd_array_get_map_idx_continuous(env, idx);
18971 	if (env->signature) {
18972 		verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n");
18973 		return -EACCES;
18974 	}
18975 	if (!bpfptr_is_null(env->fd_array_raw))
18976 		return fd_array_get_map_idx_sparse(env, idx);
18977 
18978 	verbose(env, "fd_idx without fd_array is invalid\n");
18979 	return -EPROTO;
18980 }
18981 
18982 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
18983 {
18984 	u8 class = BPF_CLASS(insn->code);
18985 	u8 opcode = BPF_OP(insn->code);
18986 
18987 	switch (opcode) {
18988 	case BPF_NEG:
18989 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
18990 		    insn->off != 0 || insn->imm != 0) {
18991 			verbose(env, "BPF_NEG uses reserved fields\n");
18992 			return -EINVAL;
18993 		}
18994 		return 0;
18995 	case BPF_END:
18996 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
18997 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
18998 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
18999 			verbose(env, "BPF_END uses reserved fields\n");
19000 			return -EINVAL;
19001 		}
19002 		return 0;
19003 	case BPF_MOV:
19004 		if (BPF_SRC(insn->code) == BPF_X) {
19005 			if (class == BPF_ALU) {
19006 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
19007 				    insn->imm) {
19008 					verbose(env, "BPF_MOV uses reserved fields\n");
19009 					return -EINVAL;
19010 				}
19011 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
19012 				if (insn->imm != 1 && insn->imm != 1u << 16) {
19013 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
19014 					return -EINVAL;
19015 				}
19016 			} else if ((insn->off != 0 && insn->off != 8 &&
19017 				    insn->off != 16 && insn->off != 32) || insn->imm) {
19018 				verbose(env, "BPF_MOV uses reserved fields\n");
19019 				return -EINVAL;
19020 			}
19021 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
19022 			verbose(env, "BPF_MOV uses reserved fields\n");
19023 			return -EINVAL;
19024 		}
19025 		return 0;
19026 	case BPF_ADD:
19027 	case BPF_SUB:
19028 	case BPF_AND:
19029 	case BPF_OR:
19030 	case BPF_XOR:
19031 	case BPF_LSH:
19032 	case BPF_RSH:
19033 	case BPF_ARSH:
19034 	case BPF_MUL:
19035 	case BPF_DIV:
19036 	case BPF_MOD:
19037 		if (BPF_SRC(insn->code) == BPF_X) {
19038 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
19039 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
19040 				verbose(env, "BPF_ALU uses reserved fields\n");
19041 				return -EINVAL;
19042 			}
19043 		} else if (insn->src_reg != BPF_REG_0 ||
19044 			   (insn->off != 0 && insn->off != 1) ||
19045 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
19046 			verbose(env, "BPF_ALU uses reserved fields\n");
19047 			return -EINVAL;
19048 		}
19049 		return 0;
19050 	default:
19051 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
19052 		return -EINVAL;
19053 	}
19054 }
19055 
19056 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
19057 {
19058 	u8 class = BPF_CLASS(insn->code);
19059 	u8 opcode = BPF_OP(insn->code);
19060 
19061 	switch (opcode) {
19062 	case BPF_CALL:
19063 		if (BPF_SRC(insn->code) != BPF_K ||
19064 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
19065 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
19066 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19067 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19068 			verbose(env, "BPF_CALL uses reserved fields\n");
19069 			return -EINVAL;
19070 		}
19071 		return 0;
19072 	case BPF_JA:
19073 		if (BPF_SRC(insn->code) == BPF_X) {
19074 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
19075 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
19076 				return -EINVAL;
19077 			}
19078 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
19079 			   (class == BPF_JMP && insn->imm != 0) ||
19080 			   (class == BPF_JMP32 && insn->off != 0)) {
19081 			verbose(env, "BPF_JA uses reserved fields\n");
19082 			return -EINVAL;
19083 		}
19084 		return 0;
19085 	case BPF_EXIT:
19086 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
19087 		    insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
19088 		    class == BPF_JMP32) {
19089 			verbose(env, "BPF_EXIT uses reserved fields\n");
19090 			return -EINVAL;
19091 		}
19092 		return 0;
19093 	case BPF_JCOND:
19094 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO ||
19095 		    insn->dst_reg || insn->imm) {
19096 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
19097 			return -EINVAL;
19098 		}
19099 		return 0;
19100 	default:
19101 		if (BPF_SRC(insn->code) == BPF_X) {
19102 			if (insn->imm != 0) {
19103 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
19104 				return -EINVAL;
19105 			}
19106 		} else if (insn->src_reg != BPF_REG_0) {
19107 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
19108 			return -EINVAL;
19109 		}
19110 		return 0;
19111 	}
19112 }
19113 
19114 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
19115 {
19116 	switch (BPF_CLASS(insn->code)) {
19117 	case BPF_ALU:
19118 	case BPF_ALU64:
19119 		return check_alu_fields(env, insn);
19120 	case BPF_LDX:
19121 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
19122 		    insn->imm != 0) {
19123 			verbose(env, "BPF_LDX uses reserved fields\n");
19124 			return -EINVAL;
19125 		}
19126 		return 0;
19127 	case BPF_STX:
19128 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
19129 			return 0;
19130 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19131 			verbose(env, "BPF_STX uses reserved fields\n");
19132 			return -EINVAL;
19133 		}
19134 		return 0;
19135 	case BPF_ST:
19136 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
19137 			verbose(env, "BPF_ST uses reserved fields\n");
19138 			return -EINVAL;
19139 		}
19140 		return 0;
19141 	case BPF_JMP:
19142 	case BPF_JMP32:
19143 		return check_jmp_fields(env, insn);
19144 	case BPF_LD: {
19145 		u8 mode = BPF_MODE(insn->code);
19146 
19147 		if (mode == BPF_ABS || mode == BPF_IND) {
19148 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
19149 			    BPF_SIZE(insn->code) == BPF_DW ||
19150 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
19151 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
19152 				return -EINVAL;
19153 			}
19154 		} else if (mode != BPF_IMM) {
19155 			verbose(env, "invalid BPF_LD mode\n");
19156 			return -EINVAL;
19157 		}
19158 		return 0;
19159 	}
19160 	default:
19161 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
19162 		return -EINVAL;
19163 	}
19164 }
19165 
19166 /*
19167  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
19168  *
19169  * 1. if it accesses map FD, replace it with actual map pointer.
19170  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
19171  *
19172  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
19173  */
19174 static int check_and_resolve_insns(struct bpf_verifier_env *env)
19175 {
19176 	struct bpf_insn *insn = env->prog->insnsi;
19177 	int insn_cnt = env->prog->len;
19178 	int i, err;
19179 
19180 	err = bpf_prog_calc_tag(env->prog);
19181 	if (err)
19182 		return err;
19183 
19184 	for (i = 0; i < insn_cnt; i++, insn++) {
19185 		if (insn->dst_reg >= MAX_BPF_REG &&
19186 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
19187 			verbose(env, "R%d is invalid\n", insn->dst_reg);
19188 			return -EINVAL;
19189 		}
19190 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
19191 			verbose(env, "R%d is invalid\n", insn->src_reg);
19192 			return -EINVAL;
19193 		}
19194 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
19195 			struct bpf_insn_aux_data *aux;
19196 			struct bpf_map *map;
19197 			int map_idx;
19198 			u64 addr;
19199 
19200 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
19201 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19202 			    insn[1].off != 0) {
19203 				verbose(env, "invalid bpf_ld_imm64 insn\n");
19204 				return -EINVAL;
19205 			}
19206 
19207 			if (insn[0].off != 0) {
19208 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
19209 				return -EINVAL;
19210 			}
19211 
19212 			if (insn[0].src_reg == 0)
19213 				/* valid generic load 64-bit imm */
19214 				goto next_insn;
19215 
19216 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19217 				aux = &env->insn_aux_data[i];
19218 				err = check_pseudo_btf_id(env, insn, aux);
19219 				if (err)
19220 					return err;
19221 				goto next_insn;
19222 			}
19223 
19224 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19225 				aux = &env->insn_aux_data[i];
19226 				aux->ptr_type = PTR_TO_FUNC;
19227 				goto next_insn;
19228 			}
19229 
19230 			/* In final convert_pseudo_ld_imm64() step, this is
19231 			 * converted into regular 64-bit imm load insn.
19232 			 */
19233 			switch (insn[0].src_reg) {
19234 			case BPF_PSEUDO_MAP_VALUE:
19235 			case BPF_PSEUDO_MAP_IDX_VALUE:
19236 				break;
19237 			case BPF_PSEUDO_MAP_FD:
19238 			case BPF_PSEUDO_MAP_IDX:
19239 				if (insn[1].imm == 0)
19240 					break;
19241 				fallthrough;
19242 			default:
19243 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19244 				return -EINVAL;
19245 			}
19246 
19247 			switch (insn[0].src_reg) {
19248 			case BPF_PSEUDO_MAP_IDX_VALUE:
19249 			case BPF_PSEUDO_MAP_IDX:
19250 				map_idx = fd_array_get_map_idx(env, insn[0].imm);
19251 				break;
19252 			default:
19253 				if (env->signature) {
19254 					verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n");
19255 					return -EINVAL;
19256 				}
19257 				map_idx = add_used_map(env, insn[0].imm);
19258 				break;
19259 			}
19260 
19261 			if (map_idx < 0)
19262 				return map_idx;
19263 			map = env->used_maps[map_idx];
19264 
19265 			aux = &env->insn_aux_data[i];
19266 			aux->map_index = map_idx;
19267 
19268 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19269 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19270 				addr = (unsigned long)map;
19271 			} else {
19272 				u32 off = insn[1].imm;
19273 
19274 				if (!map->ops->map_direct_value_addr) {
19275 					verbose(env, "no direct value access support for this map type\n");
19276 					return -EINVAL;
19277 				}
19278 
19279 				err = map->ops->map_direct_value_addr(map, &addr, off);
19280 				if (err) {
19281 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19282 						map->value_size, off);
19283 					return err;
19284 				}
19285 
19286 				aux->map_off = off;
19287 				addr += off;
19288 			}
19289 
19290 			insn[0].imm = (u32)addr;
19291 			insn[1].imm = addr >> 32;
19292 
19293 next_insn:
19294 			insn++;
19295 			i++;
19296 			continue;
19297 		}
19298 
19299 		/* Basic sanity check before we invest more work here. */
19300 		if (!bpf_opcode_in_insntable(insn->code)) {
19301 			verbose(env, "unknown opcode %02x\n", insn->code);
19302 			return -EINVAL;
19303 		}
19304 
19305 		err = check_insn_fields(env, insn);
19306 		if (err)
19307 			return err;
19308 	}
19309 
19310 	/* now all pseudo BPF_LD_IMM64 instructions load valid
19311 	 * 'struct bpf_map *' into a register instead of user map_fd.
19312 	 * These pointers will be used later by verifier to validate map access.
19313 	 */
19314 	return 0;
19315 }
19316 
19317 /* drop refcnt of maps used by the rejected program */
19318 static void release_maps(struct bpf_verifier_env *env)
19319 {
19320 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
19321 			     env->used_map_cnt);
19322 }
19323 
19324 /* drop refcnt of maps used by the rejected program */
19325 static void release_btfs(struct bpf_verifier_env *env)
19326 {
19327 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19328 }
19329 
19330 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19331 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19332 {
19333 	struct bpf_insn *insn = env->prog->insnsi;
19334 	int insn_cnt = env->prog->len;
19335 	int i;
19336 
19337 	for (i = 0; i < insn_cnt; i++, insn++) {
19338 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19339 			continue;
19340 		if (insn->src_reg == BPF_PSEUDO_FUNC)
19341 			continue;
19342 		insn->src_reg = 0;
19343 	}
19344 }
19345 
19346 static void release_insn_arrays(struct bpf_verifier_env *env)
19347 {
19348 	int i;
19349 
19350 	for (i = 0; i < env->insn_array_map_cnt; i++)
19351 		bpf_insn_array_release(env->insn_array_maps[i]);
19352 }
19353 
19354 /* The verifier does more data flow analysis than llvm and will not
19355  * explore branches that are dead at run time. Malicious programs can
19356  * have dead code too. Therefore replace all dead at-run-time code
19357  * with 'ja -1'.
19358  *
19359  * Just nops are not optimal, e.g. if they would sit at the end of the
19360  * program and through another bug we would manage to jump there, then
19361  * we'd execute beyond program memory otherwise. Returning exception
19362  * code also wouldn't work since we can have subprogs where the dead
19363  * code could be located.
19364  */
19365 static void sanitize_dead_code(struct bpf_verifier_env *env)
19366 {
19367 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19368 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
19369 	struct bpf_insn *insn = env->prog->insnsi;
19370 	const int insn_cnt = env->prog->len;
19371 	int i;
19372 
19373 	for (i = 0; i < insn_cnt; i++) {
19374 		if (aux_data[i].seen)
19375 			continue;
19376 		memcpy(insn + i, &trap, sizeof(trap));
19377 		aux_data[i].zext_dst = false;
19378 	}
19379 }
19380 
19381 static void free_states(struct bpf_verifier_env *env)
19382 {
19383 	struct bpf_verifier_state_list *sl;
19384 	struct list_head *head, *pos, *tmp;
19385 	struct bpf_scc_info *info;
19386 	int i, j;
19387 
19388 	bpf_free_verifier_state(env->cur_state, true);
19389 	env->cur_state = NULL;
19390 	while (!pop_stack(env, NULL, NULL, false));
19391 
19392 	list_for_each_safe(pos, tmp, &env->free_list) {
19393 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19394 		bpf_free_verifier_state(&sl->state, false);
19395 		kfree(sl);
19396 	}
19397 	INIT_LIST_HEAD(&env->free_list);
19398 
19399 	for (i = 0; i < env->scc_cnt; ++i) {
19400 		info = env->scc_info[i];
19401 		if (!info)
19402 			continue;
19403 		for (j = 0; j < info->num_visits; j++)
19404 			bpf_free_backedges(&info->visits[j]);
19405 		kvfree(info);
19406 		env->scc_info[i] = NULL;
19407 	}
19408 
19409 	if (!env->explored_states)
19410 		return;
19411 
19412 	for (i = 0; i < state_htab_size(env); i++) {
19413 		head = &env->explored_states[i];
19414 
19415 		list_for_each_safe(pos, tmp, head) {
19416 			sl = container_of(pos, struct bpf_verifier_state_list, node);
19417 			bpf_free_verifier_state(&sl->state, false);
19418 			kfree(sl);
19419 		}
19420 		INIT_LIST_HEAD(&env->explored_states[i]);
19421 	}
19422 }
19423 
19424 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19425 {
19426 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19427 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
19428 	struct bpf_prog_aux *aux = env->prog->aux;
19429 	struct bpf_verifier_state *state;
19430 	struct bpf_reg_state *regs;
19431 	u32 insn_processed = env->insn_processed;
19432 	int ret, i;
19433 
19434 	env->prev_linfo = NULL;
19435 	env->pass_cnt++;
19436 
19437 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
19438 	if (!state)
19439 		return -ENOMEM;
19440 	state->curframe = 0;
19441 	state->speculative = false;
19442 	state->branches = 1;
19443 	state->in_sleepable = env->prog->sleepable;
19444 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
19445 	if (!state->frame[0]) {
19446 		kfree(state);
19447 		return -ENOMEM;
19448 	}
19449 	env->cur_state = state;
19450 	init_func_state(env, state->frame[0],
19451 			BPF_MAIN_FUNC /* callsite */,
19452 			0 /* frameno */,
19453 			subprog);
19454 	state->first_insn_idx = env->subprog_info[subprog].start;
19455 	state->last_insn_idx = -1;
19456 
19457 	regs = state->frame[state->curframe]->regs;
19458 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19459 		const char *sub_name = bpf_subprog_name(env, subprog);
19460 		struct bpf_subprog_arg_info *arg;
19461 		struct bpf_reg_state *reg;
19462 
19463 		if (env->log.level & BPF_LOG_LEVEL)
19464 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
19465 		ret = btf_prepare_func_args(env, subprog);
19466 		if (ret)
19467 			goto out;
19468 
19469 		if (subprog_is_exc_cb(env, subprog)) {
19470 			state->frame[0]->in_exception_callback_fn = true;
19471 
19472 			/*
19473 			 * Global functions are scalar or void, make sure
19474 			 * we return a scalar.
19475 			 */
19476 			if (subprog_returns_void(env, subprog)) {
19477 				verbose(env, "exception cb cannot return void\n");
19478 				ret = -EINVAL;
19479 				goto out;
19480 			}
19481 
19482 			/* Also ensure the callback only has a single scalar argument. */
19483 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
19484 				verbose(env, "exception cb only supports single integer argument\n");
19485 				ret = -EINVAL;
19486 				goto out;
19487 			}
19488 		}
19489 		for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
19490 			arg = &sub->args[i - BPF_REG_1];
19491 			reg = &regs[i];
19492 
19493 			if (arg->arg_type == ARG_PTR_TO_CTX) {
19494 				reg->type = PTR_TO_CTX;
19495 				mark_reg_known_zero(env, regs, i);
19496 			} else if (arg->arg_type == ARG_ANYTHING) {
19497 				reg->type = SCALAR_VALUE;
19498 				mark_reg_unknown(env, regs, i);
19499 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
19500 				/* assume unspecial LOCAL dynptr type */
19501 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0);
19502 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
19503 				reg->type = PTR_TO_MEM;
19504 				reg->type |= arg->arg_type &
19505 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
19506 				mark_reg_known_zero(env, regs, i);
19507 				reg->mem_size = arg->mem_size;
19508 				if (arg->arg_type & PTR_MAYBE_NULL)
19509 					reg->id = ++env->id_gen;
19510 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
19511 				reg->type = PTR_TO_BTF_ID;
19512 				if (arg->arg_type & PTR_MAYBE_NULL)
19513 					reg->type |= PTR_MAYBE_NULL;
19514 				if (arg->arg_type & PTR_UNTRUSTED)
19515 					reg->type |= PTR_UNTRUSTED;
19516 				if (arg->arg_type & PTR_TRUSTED)
19517 					reg->type |= PTR_TRUSTED;
19518 				mark_reg_known_zero(env, regs, i);
19519 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
19520 				reg->btf_id = arg->btf_id;
19521 				reg->id = ++env->id_gen;
19522 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
19523 				/* caller can pass either PTR_TO_ARENA or SCALAR */
19524 				mark_reg_unknown(env, regs, i);
19525 			} else {
19526 				verifier_bug(env, "unhandled arg#%d type %d",
19527 					     i - BPF_REG_1 + 1, arg->arg_type);
19528 				ret = -EFAULT;
19529 				goto out;
19530 			}
19531 		}
19532 		if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) {
19533 			verbose(env, "freplace programs with >%d args not supported yet\n",
19534 				MAX_BPF_FUNC_REG_ARGS);
19535 			ret = -EINVAL;
19536 			goto out;
19537 		}
19538 	} else {
19539 		/* if main BPF program has associated BTF info, validate that
19540 		 * it's matching expected signature, and otherwise mark BTF
19541 		 * info for main program as unreliable
19542 		 */
19543 		if (env->prog->aux->func_info_aux) {
19544 			ret = btf_prepare_func_args(env, 0);
19545 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) {
19546 				env->prog->aux->func_info_aux[0].unreliable = true;
19547 				sub->arg_cnt = 1;
19548 				sub->stack_arg_cnt = 0;
19549 			}
19550 		}
19551 
19552 		/* 1st arg to a function */
19553 		regs[BPF_REG_1].type = PTR_TO_CTX;
19554 		mark_reg_known_zero(env, regs, BPF_REG_1);
19555 	}
19556 
19557 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
19558 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
19559 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
19560 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
19561 			if (ret < 0)
19562 				goto out;
19563 
19564 			aux->ctx_arg_info[i].ref_id = ret;
19565 		}
19566 	}
19567 
19568 	ret = do_check(env);
19569 out:
19570 	account_current_path(env);
19571 	if (!ret) {
19572 		if (pop_log)
19573 			bpf_vlog_reset(&env->log, 0);
19574 		bpf_diag_event_log_restore(env, 0);
19575 	}
19576 	free_states(env);
19577 
19578 	/*
19579 	 * The override is needed to account for async subprograms, which
19580 	 * are verified with their own set of stack frames and thus are
19581 	 * not accounted as callees by account_current_path().
19582 	 * Accumulate their total counts as total counts of the main or
19583 	 * global subprog hosting the async call.
19584 	 */
19585 	env->subprog_info[subprog].insns_total = env->insn_processed - insn_processed;
19586 	return ret;
19587 }
19588 
19589 /* Lazily verify all global functions based on their BTF, if they are called
19590  * from main BPF program or any of subprograms transitively.
19591  * BPF global subprogs called from dead code are not validated.
19592  * All callable global functions must pass verification.
19593  * Otherwise the whole program is rejected.
19594  * Consider:
19595  * int bar(int);
19596  * int foo(int f)
19597  * {
19598  *    return bar(f);
19599  * }
19600  * int bar(int b)
19601  * {
19602  *    ...
19603  * }
19604  * foo() will be verified first for R1=any_scalar_value. During verification it
19605  * will be assumed that bar() already verified successfully and call to bar()
19606  * from foo() will be checked for type match only. Later bar() will be verified
19607  * independently to check that it's safe for R1=any_scalar_value.
19608  */
19609 static int do_check_subprogs(struct bpf_verifier_env *env)
19610 {
19611 	struct bpf_prog_aux *aux = env->prog->aux;
19612 	struct bpf_func_info_aux *sub_aux;
19613 	int i, ret, new_cnt;
19614 
19615 	if (!aux->func_info)
19616 		return 0;
19617 
19618 	/* exception callback is presumed to be always called */
19619 	if (env->exception_callback_subprog)
19620 		subprog_aux(env, env->exception_callback_subprog)->called = true;
19621 
19622 again:
19623 	new_cnt = 0;
19624 	for (i = 1; i < env->subprog_cnt; i++) {
19625 		if (!bpf_subprog_is_global(env, i))
19626 			continue;
19627 
19628 		sub_aux = subprog_aux(env, i);
19629 		if (!sub_aux->called || sub_aux->verified)
19630 			continue;
19631 
19632 		env->insn_idx = env->subprog_info[i].start;
19633 		WARN_ON_ONCE(env->insn_idx == 0);
19634 		ret = do_check_common(env, i);
19635 		if (ret) {
19636 			return ret;
19637 		} else if (env->log.level & BPF_LOG_LEVEL) {
19638 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
19639 				i, bpf_subprog_name(env, i));
19640 		}
19641 
19642 		/* We verified new global subprog, it might have called some
19643 		 * more global subprogs that we haven't verified yet, so we
19644 		 * need to do another pass over subprogs to verify those.
19645 		 */
19646 		sub_aux->verified = true;
19647 		new_cnt++;
19648 	}
19649 
19650 	/* We can't loop forever as we verify at least one global subprog on
19651 	 * each pass.
19652 	 */
19653 	if (new_cnt)
19654 		goto again;
19655 
19656 	return 0;
19657 }
19658 
19659 static int do_check_main(struct bpf_verifier_env *env)
19660 {
19661 	int ret;
19662 
19663 	env->insn_idx = 0;
19664 	ret = do_check_common(env, 0);
19665 	if (!ret)
19666 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19667 	return ret;
19668 }
19669 
19670 static void print_verification_stats(struct bpf_verifier_env *env)
19671 {
19672 	/* Skip over hidden subprogs which are not verified. */
19673 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19674 
19675 	if (env->log.level & BPF_LOG_STATS) {
19676 		verbose(env, "verification time %lld usec\n",
19677 			div_u64(env->verification_time, 1000));
19678 		verbose(env, "stack depth max %d\n", env->max_stack_depth);
19679 		for (i = 0; i < subprog_cnt; i++) {
19680 			const char *name = env->subprog_info[i].name;
19681 			const char *kind;
19682 
19683 			if (!name || !name[0])
19684 				name = "<unknown>";
19685 			kind = i == 0 ? "main" :
19686 			       bpf_subprog_is_global(env, i) ? "global" : "static";
19687 			verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n",
19688 				i, name, kind, env->subprog_info[i].insns_self,
19689 				env->subprog_info[i].insns_total,
19690 				env->subprog_info[i].stack_depth);
19691 		}
19692 	}
19693 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19694 		"total_states %d peak_states %d mark_read %d\n",
19695 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19696 		env->max_states_per_insn, env->total_states,
19697 		env->peak_states, env->longest_mark_read_walk);
19698 }
19699 
19700 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
19701 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
19702 {
19703 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
19704 	prog->aux->ctx_arg_info_size = cnt;
19705 
19706 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
19707 }
19708 
19709 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19710 {
19711 	const struct btf_type *t, *func_proto;
19712 	const struct bpf_struct_ops_desc *st_ops_desc;
19713 	const struct bpf_struct_ops_arg_info *arg_info;
19714 	const struct bpf_struct_ops *st_ops;
19715 	const struct btf_member *member;
19716 	struct bpf_prog *prog = env->prog;
19717 	bool has_refcounted_arg = false;
19718 	u32 btf_id, member_idx, member_off;
19719 	struct btf *btf;
19720 	const char *mname;
19721 	int i, err;
19722 
19723 	if (!prog->gpl_compatible) {
19724 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19725 		return -EINVAL;
19726 	}
19727 
19728 	if (!prog->aux->attach_btf_id)
19729 		return -ENOTSUPP;
19730 
19731 	btf = prog->aux->attach_btf;
19732 	if (btf_is_module(btf)) {
19733 		/* Make sure st_ops is valid through the lifetime of env */
19734 		env->attach_btf_mod = btf_try_get_module(btf);
19735 		if (!env->attach_btf_mod) {
19736 			verbose(env, "struct_ops module %s is not found\n",
19737 				btf_get_name(btf));
19738 			return -ENOTSUPP;
19739 		}
19740 	}
19741 
19742 	btf_id = prog->aux->attach_btf_id;
19743 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
19744 	if (!st_ops_desc) {
19745 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19746 			btf_id);
19747 		return -ENOTSUPP;
19748 	}
19749 	st_ops = st_ops_desc->st_ops;
19750 
19751 	t = st_ops_desc->type;
19752 	member_idx = prog->expected_attach_type;
19753 	if (member_idx >= btf_type_vlen(t)) {
19754 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19755 			member_idx, st_ops->name);
19756 		return -EINVAL;
19757 	}
19758 
19759 	member = &btf_type_member(t)[member_idx];
19760 	mname = btf_name_by_offset(btf, member->name_off);
19761 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
19762 					       NULL);
19763 	if (!func_proto) {
19764 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19765 			mname, member_idx, st_ops->name);
19766 		return -EINVAL;
19767 	}
19768 
19769 	member_off = __btf_member_bit_offset(t, member) / 8;
19770 	err = bpf_struct_ops_supported(st_ops, member_off);
19771 	if (err) {
19772 		verbose(env, "attach to unsupported member %s of struct %s\n",
19773 			mname, st_ops->name);
19774 		return err;
19775 	}
19776 
19777 	if (st_ops->check_member) {
19778 		err = st_ops->check_member(t, member, prog);
19779 
19780 		if (err) {
19781 			verbose(env, "attach to unsupported member %s of struct %s\n",
19782 				mname, st_ops->name);
19783 			return err;
19784 		}
19785 	}
19786 
19787 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
19788 		verbose(env, "Private stack not supported by jit\n");
19789 		return -EACCES;
19790 	}
19791 
19792 	arg_info = &st_ops_desc->arg_info[member_idx];
19793 	for (i = 0; i < arg_info->cnt; i++) {
19794 		const struct bpf_ctx_arg_aux *info = &arg_info->info[i];
19795 
19796 		if (info->refcounted)
19797 			has_refcounted_arg = true;
19798 		if (base_type(info->reg_type) == PTR_TO_ARENA) {
19799 			if (!bpf_jit_supports_arena_args()) {
19800 				verbose(env, "JIT does not support arena arguments\n");
19801 				return -ENOTSUPP;
19802 			}
19803 			if (!prog->aux->arena) {
19804 				verbose(env,
19805 					"arena argument of %s requires a program with an associated arena\n",
19806 					mname);
19807 				return -EINVAL;
19808 			}
19809 		}
19810 	}
19811 
19812 	/* Tail call is not allowed for programs with refcounted arguments since we
19813 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
19814 	 */
19815 	for (i = 0; i < env->subprog_cnt; i++) {
19816 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
19817 			verbose(env, "program with __ref argument cannot tail call\n");
19818 			return -EINVAL;
19819 		}
19820 	}
19821 
19822 	prog->aux->st_ops = st_ops;
19823 	prog->aux->attach_st_ops_member_off = member_off;
19824 
19825 	prog->aux->attach_func_proto = func_proto;
19826 	prog->aux->attach_func_name = mname;
19827 	env->ops = st_ops->verifier_ops;
19828 
19829 	return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt);
19830 }
19831 #define SECURITY_PREFIX "security_"
19832 
19833 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
19834 
19835 /* list of non-sleepable functions that are otherwise on
19836  * ALLOW_ERROR_INJECTION list
19837  */
19838 BTF_SET_START(btf_non_sleepable_error_inject)
19839 /* Three functions below can be called from sleepable and non-sleepable context.
19840  * Assume non-sleepable from bpf safety point of view.
19841  */
19842 BTF_ID(func, __filemap_add_folio)
19843 #ifdef CONFIG_FAIL_PAGE_ALLOC
19844 BTF_ID(func, should_fail_alloc_page)
19845 #endif
19846 #ifdef CONFIG_FAILSLAB
19847 BTF_ID(func, should_failslab)
19848 #endif
19849 BTF_SET_END(btf_non_sleepable_error_inject)
19850 
19851 static int check_non_sleepable_error_inject(u32 btf_id)
19852 {
19853 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19854 }
19855 
19856 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
19857 {
19858 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
19859 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19860 	 */
19861 	if (!check_non_sleepable_error_inject(btf_id) &&
19862 	    within_error_injection_list(addr))
19863 		return 0;
19864 
19865 	return -EINVAL;
19866 }
19867 
19868 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19869 {
19870 	if (within_error_injection_list(addr) ||
19871 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19872 		return 0;
19873 
19874 	return -EINVAL;
19875 }
19876 
19877 #else
19878 
19879 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
19880  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
19881  * but that just compares two concrete function names.
19882  */
19883 static bool has_arch_syscall_prefix(const char *func_name)
19884 {
19885 #if defined(__x86_64__)
19886 	return !strncmp(func_name, "__x64_", 6);
19887 #elif defined(__i386__)
19888 	return !strncmp(func_name, "__ia32_", 7);
19889 #elif defined(__s390x__)
19890 	return !strncmp(func_name, "__s390x_", 8);
19891 #elif defined(__aarch64__)
19892 	return !strncmp(func_name, "__arm64_", 8);
19893 #elif defined(__riscv)
19894 	return !strncmp(func_name, "__riscv_", 8);
19895 #elif defined(__powerpc__) || defined(__powerpc64__)
19896 	return !strncmp(func_name, "sys_", 4);
19897 #elif defined(__loongarch__)
19898 	return !strncmp(func_name, "sys_", 4);
19899 #else
19900 	return false;
19901 #endif
19902 }
19903 
19904 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
19905 
19906 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
19907 {
19908 	if (has_arch_syscall_prefix(func_name))
19909 		return 0;
19910 
19911 	return -EINVAL;
19912 }
19913 
19914 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19915 {
19916 	if (has_arch_syscall_prefix(func_name) ||
19917 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19918 		return 0;
19919 
19920 	return -EINVAL;
19921 }
19922 
19923 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
19924 
19925 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
19926 {
19927 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
19928 }
19929 
19930 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
19931 				  const struct btf *btf)
19932 {
19933 	const struct btf_type *t;
19934 	const char *tname;
19935 
19936 	if (!btf_is_kernel(btf))
19937 		return -EINVAL;
19938 
19939 	switch (prog->type) {
19940 	case BPF_PROG_TYPE_TRACING:
19941 		t = btf_type_by_id(btf, btf_id);
19942 		if (!t)
19943 			return -EINVAL;
19944 		tname = btf_name_by_offset(btf, t->name_off);
19945 		if (!tname)
19946 			return -EINVAL;
19947 
19948 		/*
19949 		 * *.multi sleepable programs will pass initial sleepable check,
19950 		 * the actual attached btf ids are checked later during the link
19951 		 * attachment.
19952 		 */
19953 		if (is_tracing_multi_id(prog, btf_id))
19954 			return 0;
19955 		if (!check_attach_sleepable(btf_id, addr, tname))
19956 			return 0;
19957 		/*
19958 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
19959 		 * in the fmodret id set with the KF_SLEEPABLE flag.
19960 		 */
19961 		else {
19962 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
19963 
19964 			if (flags && (*flags & KF_SLEEPABLE))
19965 				return 0;
19966 		}
19967 		break;
19968 	case BPF_PROG_TYPE_LSM:
19969 		/*
19970 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
19971 		 * Only some of them are sleepable.
19972 		 */
19973 		if (bpf_lsm_is_sleepable_hook(btf_id))
19974 			return 0;
19975 		break;
19976 	default:
19977 		break;
19978 	}
19979 	return -EINVAL;
19980 }
19981 
19982 /*
19983  * Resolve the prototype describing a trace target's real ABI. A
19984  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
19985  * prototype, so use the _impl prototype; other targets use their own.
19986  */
19987 static const struct btf_type *
19988 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
19989 {
19990 	const struct btf_type *func;
19991 	struct module *mod = NULL;
19992 	const char *name;
19993 	int implicit;
19994 
19995 	func = btf_type_by_id(btf, func_id);
19996 	if (!func || !btf_type_is_func(func))
19997 		return NULL;
19998 	name = btf_name_by_offset(btf, func->name_off);
19999 
20000 	/*
20001 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
20002 	 * stable only once it is live; hold a module ref across the read to
20003 	 * exclude a concurrent module load.
20004 	 */
20005 	if (btf_is_module(btf)) {
20006 		mod = btf_try_get_module(btf);
20007 		if (!mod)
20008 			return NULL;
20009 	}
20010 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
20011 	module_put(mod);
20012 
20013 	if (implicit == -EINVAL) {
20014 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
20015 		return NULL;
20016 	}
20017 	if (implicit > 0)
20018 		return find_kfunc_impl_proto(log, btf, name);
20019 
20020 	return btf_type_by_id(btf, func->type);
20021 }
20022 
20023 static bool attach_uses_trampoline_retval(enum bpf_attach_type type)
20024 {
20025 	switch (type) {
20026 	case BPF_MODIFY_RETURN:
20027 	case BPF_TRACE_FEXIT:
20028 	case BPF_TRACE_FEXIT_MULTI:
20029 	case BPF_TRACE_FSESSION:
20030 	case BPF_TRACE_FSESSION_MULTI:
20031 		return true;
20032 	default:
20033 		return false;
20034 	}
20035 }
20036 
20037 int bpf_check_attach_target(struct bpf_verifier_log *log,
20038 			    const struct bpf_prog *prog,
20039 			    const struct bpf_prog *tgt_prog,
20040 			    u32 btf_id,
20041 			    struct bpf_attach_target_info *tgt_info)
20042 {
20043 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20044 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20045 	char trace_symbol[KSYM_SYMBOL_LEN];
20046 	const char prefix[] = "btf_trace_";
20047 	struct bpf_raw_event_map *btp;
20048 	int ret = 0, subprog = -1, i;
20049 	const struct btf_type *t;
20050 	bool conservative = true;
20051 	const char *tname, *fname;
20052 	struct btf *btf;
20053 	long addr = 0;
20054 	struct module *mod = NULL;
20055 
20056 	if (!btf_id) {
20057 		bpf_log(log, "Tracing programs must provide btf_id\n");
20058 		return -EINVAL;
20059 	}
20060 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20061 	if (!btf) {
20062 		bpf_log(log,
20063 			"Tracing program can only be attached to another program annotated with BTF\n");
20064 		return -EINVAL;
20065 	}
20066 	t = btf_type_by_id(btf, btf_id);
20067 	if (!t) {
20068 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20069 		return -EINVAL;
20070 	}
20071 	tname = btf_name_by_offset(btf, t->name_off);
20072 	if (!tname) {
20073 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20074 		return -EINVAL;
20075 	}
20076 	if (tgt_prog) {
20077 		struct bpf_prog_aux *aux = tgt_prog->aux;
20078 		bool tgt_changes_pkt_data;
20079 		bool tgt_might_sleep;
20080 
20081 		if (bpf_prog_is_dev_bound(prog->aux) &&
20082 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20083 			bpf_log(log, "Target program bound device mismatch");
20084 			return -EINVAL;
20085 		}
20086 
20087 		for (i = 0; i < aux->func_info_cnt; i++)
20088 			if (aux->func_info[i].type_id == btf_id) {
20089 				subprog = i;
20090 				break;
20091 			}
20092 		if (subprog == -1) {
20093 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
20094 			return -EINVAL;
20095 		}
20096 		/*
20097 		 * A struct_ops indirect trampoline converts arena arguments
20098 		 * before invoking its program. A tracing or extension program
20099 		 * attached to the main program would see the converted offset as a
20100 		 * regular BTF pointer.
20101 		 */
20102 		if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) {
20103 			bpf_log(log, "Cannot attach to a target with arena context arguments\n");
20104 			return -EOPNOTSUPP;
20105 		}
20106 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
20107 			bpf_log(log,
20108 				"%s programs cannot attach to exception callback\n",
20109 				prog_extension ? "Extension" : "Tracing");
20110 			return -EINVAL;
20111 		}
20112 		conservative = aux->func_info_aux[subprog].unreliable;
20113 		if (prog_extension) {
20114 			if (conservative) {
20115 				bpf_log(log,
20116 					"Cannot replace static functions\n");
20117 				return -EINVAL;
20118 			}
20119 			if (!prog->jit_requested) {
20120 				bpf_log(log,
20121 					"Extension programs should be JITed\n");
20122 				return -EINVAL;
20123 			}
20124 			tgt_changes_pkt_data = aux->func
20125 					       ? aux->func[subprog]->aux->changes_pkt_data
20126 					       : aux->changes_pkt_data;
20127 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
20128 				bpf_log(log,
20129 					"Extension program changes packet data, while original does not\n");
20130 				return -EINVAL;
20131 			}
20132 
20133 			tgt_might_sleep = aux->func
20134 					  ? aux->func[subprog]->aux->might_sleep
20135 					  : aux->might_sleep;
20136 			if (prog->aux->might_sleep && !tgt_might_sleep) {
20137 				bpf_log(log,
20138 					"Extension program may sleep, while original does not\n");
20139 				return -EINVAL;
20140 			}
20141 		}
20142 		if (!tgt_prog->jited) {
20143 			bpf_log(log, "Can attach to only JITed progs\n");
20144 			return -EINVAL;
20145 		}
20146 		if (prog_tracing) {
20147 			if (aux->attach_tracing_prog) {
20148 				/*
20149 				 * Target program is an fentry/fexit which is already attached
20150 				 * to another tracing program. More levels of nesting
20151 				 * attachment are not allowed.
20152 				 */
20153 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
20154 				return -EINVAL;
20155 			}
20156 		} else if (tgt_prog->type == prog->type) {
20157 			/*
20158 			 * To avoid potential call chain cycles, prevent attaching of a
20159 			 * program extension to another extension. It's ok to attach
20160 			 * fentry/fexit to extension program.
20161 			 */
20162 			bpf_log(log, "Cannot recursively attach\n");
20163 			return -EINVAL;
20164 		}
20165 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20166 		    prog_extension &&
20167 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20168 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
20169 		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
20170 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
20171 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
20172 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
20173 			/* Program extensions can extend all program types
20174 			 * except fentry/fexit. The reason is the following.
20175 			 * The fentry/fexit programs are used for performance
20176 			 * analysis, stats and can be attached to any program
20177 			 * type. When extension program is replacing XDP function
20178 			 * it is necessary to allow performance analysis of all
20179 			 * functions. Both original XDP program and its program
20180 			 * extension. Hence attaching fentry/fexit to
20181 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
20182 			 * fentry/fexit was allowed it would be possible to create
20183 			 * long call chain fentry->extension->fentry->extension
20184 			 * beyond reasonable stack size. Hence extending fentry
20185 			 * is not allowed.
20186 			 */
20187 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
20188 			return -EINVAL;
20189 		}
20190 	} else {
20191 		if (prog_extension) {
20192 			bpf_log(log, "Cannot replace kernel functions\n");
20193 			return -EINVAL;
20194 		}
20195 	}
20196 
20197 	switch (prog->expected_attach_type) {
20198 	case BPF_TRACE_RAW_TP:
20199 		if (tgt_prog) {
20200 			bpf_log(log,
20201 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
20202 			return -EINVAL;
20203 		}
20204 		if (!btf_type_is_typedef(t)) {
20205 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20206 				btf_id);
20207 			return -EINVAL;
20208 		}
20209 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20210 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20211 				btf_id, tname);
20212 			return -EINVAL;
20213 		}
20214 		tname += sizeof(prefix) - 1;
20215 
20216 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
20217 		 * names. Thus using bpf_raw_event_map to get argument names.
20218 		 */
20219 		btp = bpf_get_raw_tracepoint(tname);
20220 		if (!btp)
20221 			return -EINVAL;
20222 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
20223 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
20224 				tname);
20225 			bpf_put_raw_tracepoint(btp);
20226 			return -EINVAL;
20227 		}
20228 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
20229 					trace_symbol);
20230 		bpf_put_raw_tracepoint(btp);
20231 
20232 		if (fname)
20233 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
20234 
20235 		if (!fname || ret < 0) {
20236 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
20237 				prefix, tname);
20238 			t = btf_type_by_id(btf, t->type);
20239 			if (!btf_type_is_ptr(t))
20240 				/* should never happen in valid vmlinux build */
20241 				return -EINVAL;
20242 		} else {
20243 			t = btf_type_by_id(btf, ret);
20244 			if (!btf_type_is_func(t))
20245 				/* should never happen in valid vmlinux build */
20246 				return -EINVAL;
20247 		}
20248 
20249 		t = btf_type_by_id(btf, t->type);
20250 		if (!btf_type_is_func_proto(t))
20251 			/* should never happen in valid vmlinux build */
20252 			return -EINVAL;
20253 
20254 		break;
20255 	case BPF_TRACE_ITER:
20256 		if (!btf_type_is_func(t)) {
20257 			bpf_log(log, "attach_btf_id %u is not a function\n",
20258 				btf_id);
20259 			return -EINVAL;
20260 		}
20261 		t = btf_type_by_id(btf, t->type);
20262 		if (!btf_type_is_func_proto(t))
20263 			return -EINVAL;
20264 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20265 		if (ret)
20266 			return ret;
20267 		break;
20268 	default:
20269 		if (!prog_extension)
20270 			return -EINVAL;
20271 		fallthrough;
20272 	case BPF_MODIFY_RETURN:
20273 	case BPF_LSM_MAC:
20274 	case BPF_LSM_CGROUP:
20275 	case BPF_TRACE_FENTRY:
20276 	case BPF_TRACE_FEXIT:
20277 	case BPF_TRACE_FSESSION:
20278 	case BPF_TRACE_FSESSION_MULTI:
20279 	case BPF_TRACE_FENTRY_MULTI:
20280 	case BPF_TRACE_FEXIT_MULTI:
20281 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
20282 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
20283 		    !bpf_jit_supports_fsession()) {
20284 			bpf_log(log, "JIT does not support fsession\n");
20285 			return -EOPNOTSUPP;
20286 		}
20287 		if (!btf_type_is_func(t)) {
20288 			bpf_log(log, "attach_btf_id %u is not a function\n",
20289 				btf_id);
20290 			return -EINVAL;
20291 		}
20292 		if (prog_extension &&
20293 		    btf_check_type_match(log, prog, btf, t))
20294 			return -EINVAL;
20295 		t = btf_attach_func_proto(log, btf, btf_id);
20296 		if (!t || !btf_type_is_func_proto(t))
20297 			return -EINVAL;
20298 
20299 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20300 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20301 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20302 			return -EINVAL;
20303 
20304 		if (tgt_prog && conservative)
20305 			t = NULL;
20306 
20307 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20308 		if (ret < 0)
20309 			return ret;
20310 
20311 		if (tgt_info->fmodel.ret_size > 8 &&
20312 		    attach_uses_trampoline_retval(prog->expected_attach_type)) {
20313 			bpf_log(log,
20314 				"Attach to function %s with a >8 byte return value is not supported for this attach type\n",
20315 				tname);
20316 			return -EOPNOTSUPP;
20317 		}
20318 
20319 		/*
20320 		 * *.multi programs don't need an address during program
20321 		 * verification, we just take the module ref if needed.
20322 		 */
20323 		if (is_tracing_multi_id(prog, btf_id)) {
20324 			if (btf_is_module(btf)) {
20325 				mod = btf_try_get_module(btf);
20326 				if (!mod)
20327 					return -ENOENT;
20328 			}
20329 			addr = 0;
20330 		} else if (tgt_prog) {
20331 			if (subprog == 0)
20332 				addr = (long) tgt_prog->bpf_func;
20333 			else
20334 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20335 		} else {
20336 			if (btf_is_module(btf)) {
20337 				mod = btf_try_get_module(btf);
20338 				if (mod)
20339 					addr = find_kallsyms_symbol_value(mod, tname);
20340 				else
20341 					addr = 0;
20342 			} else {
20343 				addr = kallsyms_lookup_name(tname);
20344 			}
20345 			if (!addr) {
20346 				module_put(mod);
20347 				bpf_log(log,
20348 					"The address of function %s cannot be found\n",
20349 					tname);
20350 				return -ENOENT;
20351 			}
20352 		}
20353 
20354 		if (prog->sleepable) {
20355 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
20356 			if (ret) {
20357 				module_put(mod);
20358 				bpf_log(log, "%s is not sleepable\n", tname);
20359 				return ret;
20360 			}
20361 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20362 			if (tgt_prog) {
20363 				module_put(mod);
20364 				bpf_log(log, "can't modify return codes of BPF programs\n");
20365 				return -EINVAL;
20366 			}
20367 			ret = -EINVAL;
20368 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20369 			    !check_attach_modify_return(addr, tname))
20370 				ret = 0;
20371 			if (ret) {
20372 				module_put(mod);
20373 				bpf_log(log, "%s() is not modifiable\n", tname);
20374 				return ret;
20375 			}
20376 		}
20377 
20378 		break;
20379 	}
20380 	tgt_info->tgt_addr = addr;
20381 	tgt_info->tgt_name = tname;
20382 	tgt_info->tgt_type = t;
20383 	tgt_info->tgt_mod = mod;
20384 	return 0;
20385 }
20386 
20387 BTF_SET_START(btf_id_deny)
20388 BTF_ID_UNUSED
20389 #ifdef CONFIG_SMP
20390 BTF_ID(func, ___migrate_enable)
20391 BTF_ID(func, migrate_disable)
20392 BTF_ID(func, migrate_enable)
20393 #endif
20394 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20395 BTF_ID(func, rcu_read_unlock_strict)
20396 #endif
20397 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20398 BTF_ID(func, preempt_count_add)
20399 BTF_ID(func, preempt_count_sub)
20400 #endif
20401 #ifdef CONFIG_PREEMPT_RCU
20402 BTF_ID(func, __rcu_read_lock)
20403 BTF_ID(func, __rcu_read_unlock)
20404 #endif
20405 BTF_SET_END(btf_id_deny)
20406 
20407 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
20408  * Currently, we must manually list all __noreturn functions here. Once a more
20409  * robust solution is implemented, this workaround can be removed.
20410  */
20411 BTF_SET_START(noreturn_deny)
20412 #ifdef CONFIG_IA32_EMULATION
20413 BTF_ID(func, __ia32_sys_exit)
20414 BTF_ID(func, __ia32_sys_exit_group)
20415 #endif
20416 #ifdef CONFIG_KUNIT
20417 BTF_ID(func, __kunit_abort)
20418 BTF_ID(func, kunit_try_catch_throw)
20419 #endif
20420 #ifdef CONFIG_MODULES
20421 BTF_ID(func, __module_put_and_kthread_exit)
20422 #endif
20423 #ifdef CONFIG_X86_64
20424 BTF_ID(func, __x64_sys_exit)
20425 BTF_ID(func, __x64_sys_exit_group)
20426 #endif
20427 BTF_ID(func, do_exit)
20428 BTF_ID(func, do_group_exit)
20429 BTF_ID(func, kthread_complete_and_exit)
20430 BTF_ID(func, make_task_dead)
20431 BTF_SET_END(noreturn_deny)
20432 
20433 static bool can_be_sleepable(struct bpf_prog *prog)
20434 {
20435 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20436 		switch (prog->expected_attach_type) {
20437 		case BPF_TRACE_FENTRY:
20438 		case BPF_TRACE_FEXIT:
20439 		case BPF_MODIFY_RETURN:
20440 		case BPF_TRACE_ITER:
20441 		case BPF_TRACE_FSESSION:
20442 		case BPF_TRACE_RAW_TP:
20443 		case BPF_TRACE_FENTRY_MULTI:
20444 		case BPF_TRACE_FEXIT_MULTI:
20445 		case BPF_TRACE_FSESSION_MULTI:
20446 			return true;
20447 		default:
20448 			return false;
20449 		}
20450 	}
20451 	if (prog->type == BPF_PROG_TYPE_LSM)
20452 		return prog->expected_attach_type != BPF_LSM_CGROUP;
20453 
20454 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20455 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
20456 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
20457 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
20458 }
20459 
20460 static int check_attach_btf_id(struct bpf_verifier_env *env)
20461 {
20462 	struct bpf_prog *prog = env->prog;
20463 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20464 	struct bpf_attach_target_info tgt_info = {};
20465 	u32 btf_id = prog->aux->attach_btf_id;
20466 	struct bpf_trampoline *tr;
20467 	int ret;
20468 	u64 key;
20469 
20470 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20471 		if (prog->sleepable)
20472 			/* attach_btf_id checked to be zero already */
20473 			return 0;
20474 		verbose(env, "Syscall programs can only be sleepable\n");
20475 		return -EINVAL;
20476 	}
20477 
20478 	if (prog->sleepable && !can_be_sleepable(prog)) {
20479 		verbose(env, "Program of this type cannot be sleepable\n");
20480 		return -EINVAL;
20481 	}
20482 
20483 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20484 		return check_struct_ops_btf_id(env);
20485 
20486 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20487 	    prog->type != BPF_PROG_TYPE_LSM &&
20488 	    prog->type != BPF_PROG_TYPE_EXT)
20489 		return 0;
20490 
20491 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20492 	if (ret)
20493 		return ret;
20494 
20495 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20496 		/* to make freplace equivalent to their targets, they need to
20497 		 * inherit env->ops and expected_attach_type for the rest of the
20498 		 * verification
20499 		 */
20500 		env->ops = bpf_verifier_ops[tgt_prog->type];
20501 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20502 	}
20503 
20504 	/* store info about the attachment target that will be used later */
20505 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20506 	prog->aux->attach_func_name = tgt_info.tgt_name;
20507 	prog->aux->mod = tgt_info.tgt_mod;
20508 
20509 	if (tgt_prog) {
20510 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20511 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20512 	}
20513 
20514 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20515 		prog->aux->attach_btf_trace = true;
20516 		return 0;
20517 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20518 		return bpf_iter_prog_supported(prog);
20519 	}
20520 
20521 	if (prog->type == BPF_PROG_TYPE_LSM) {
20522 		ret = bpf_lsm_verify_prog(&env->log, prog);
20523 		if (ret < 0)
20524 			return ret;
20525 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20526 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20527 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
20528 			tgt_info.tgt_name);
20529 		return -EINVAL;
20530 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
20531 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
20532 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
20533 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
20534 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
20535 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
20536 			tgt_info.tgt_name);
20537 		return -EINVAL;
20538 	}
20539 
20540 	/*
20541 	 * We don't get trampoline for tracing_multi programs at this point,
20542 	 * it's done when tracing_multi link is created.
20543 	 */
20544 	if (prog->type == BPF_PROG_TYPE_TRACING &&
20545 	    is_tracing_multi(prog->expected_attach_type))
20546 		return 0;
20547 
20548 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20549 	tr = bpf_trampoline_get(key, &tgt_info);
20550 	if (!tr)
20551 		return -ENOMEM;
20552 
20553 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20554 		bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX);
20555 
20556 	prog->aux->dst_trampoline = tr;
20557 	return 0;
20558 }
20559 
20560 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
20561 				  struct bpf_attach_target_info *tgt_info)
20562 {
20563 	const struct btf_type *t;
20564 	unsigned long addr;
20565 	const char *tname;
20566 	int err;
20567 
20568 	if (!btf_id || !btf)
20569 		return -EINVAL;
20570 
20571 	/* Check noreturn attachment. */
20572 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
20573 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
20574 	     btf_id_set_contains(&noreturn_deny, btf_id))
20575 		return -EINVAL;
20576 	/* Check denied attachment. */
20577 	if (btf_id_set_contains(&btf_id_deny, btf_id))
20578 		return -EINVAL;
20579 
20580 	/* Check and get function target data. */
20581 	t = btf_type_by_id(btf, btf_id);
20582 	if (!t)
20583 		return -EINVAL;
20584 	tname = btf_name_by_offset(btf, t->name_off);
20585 	if (!tname)
20586 		return -EINVAL;
20587 	t = btf_attach_func_proto(NULL, btf, btf_id);
20588 	if (!t || !btf_type_is_func_proto(t))
20589 		return -EINVAL;
20590 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
20591 	if (err < 0)
20592 		return err;
20593 	if (tgt_info->fmodel.ret_size > 8 &&
20594 	    attach_uses_trampoline_retval(prog->expected_attach_type))
20595 		return -EOPNOTSUPP;
20596 	if (btf_is_module(btf)) {
20597 		/* The bpf program already holds reference to module. */
20598 		if (WARN_ON_ONCE(!prog->aux->mod))
20599 			return -EINVAL;
20600 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
20601 	} else {
20602 		addr = kallsyms_lookup_name(tname);
20603 	}
20604 	if (!addr || !ftrace_location(addr))
20605 		return -ENOENT;
20606 
20607 	/* Check sleepable program attachment. */
20608 	if (prog->sleepable) {
20609 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
20610 		if (err)
20611 			return err;
20612 	}
20613 	tgt_info->tgt_addr = addr;
20614 	return 0;
20615 }
20616 
20617 struct btf *bpf_get_btf_vmlinux(void)
20618 {
20619 	/* Pairs with the smp_store_release() on the parse path below. */
20620 	struct btf *btf = smp_load_acquire(&btf_vmlinux);
20621 
20622 	if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20623 		mutex_lock(&btf_vmlinux_lock);
20624 		btf = btf_vmlinux;
20625 		if (!btf) {
20626 			btf = btf_parse_vmlinux();
20627 			/*
20628 			 * Order the parsed BTF contents and the globals the
20629 			 * parse populated (e.g. bpf_ctx_convert.t) before
20630 			 * the pointer publication. Pairs with the acquire
20631 			 * on the lockless fast path above.
20632 			 */
20633 			smp_store_release(&btf_vmlinux, btf);
20634 		}
20635 		mutex_unlock(&btf_vmlinux_lock);
20636 	}
20637 	return btf;
20638 }
20639 
20640 /*
20641  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
20642  * this case expect that every file descriptor in the array is either a map or
20643  * a BTF. Everything else is considered to be trash.
20644  */
20645 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd)
20646 {
20647 	struct bpf_map *map;
20648 	struct btf *btf;
20649 	CLASS(fd, f)(fd);
20650 	int err;
20651 
20652 	map = __bpf_map_get(f);
20653 	if (!IS_ERR(map)) {
20654 		err = __add_used_map(env, map);
20655 		if (err < 0)
20656 			return err;
20657 		fd_slot_set_map(&env->fd_array[idx], map);
20658 		return 0;
20659 	}
20660 
20661 	btf = __btf_get_by_fd(f);
20662 	if (!IS_ERR(btf)) {
20663 		btf_get(btf);
20664 		err = __add_used_btf(env, btf);
20665 		if (err < 0)
20666 			return err;
20667 		fd_slot_set_btf(&env->fd_array[idx], btf);
20668 		return 0;
20669 	}
20670 
20671 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
20672 	return PTR_ERR(map);
20673 }
20674 
20675 /*
20676  * A continuous fd_array is resolved into an in-memory cache with one slot
20677  * per entry. The bound here is deliberately generous and not derived from
20678  * the per-program object limits: Duplicate entries /are/ permitted, and
20679  * the number of distinct maps and BTFs a program can bind is enforced when
20680  * each entry is resolved by __add_used_map() and __add_used_btf().
20681  */
20682 #define MAX_FD_ARRAY_CNT 4096
20683 
20684 static int process_fd_array_continuous(struct bpf_verifier_env *env,
20685 				       bpfptr_t fd_array, u32 cnt)
20686 {
20687 	int fd, ret;
20688 	u32 i;
20689 
20690 	if (cnt > MAX_FD_ARRAY_CNT) {
20691 		verbose(env, "fd_array has too many entries (%u, max %u)\n",
20692 			cnt, MAX_FD_ARRAY_CNT);
20693 		return -E2BIG;
20694 	}
20695 
20696 	env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT);
20697 	if (!env->fd_array)
20698 		return -ENOMEM;
20699 	env->fd_array_cnt = cnt;
20700 	for (i = 0; i < cnt; i++) {
20701 		if (copy_from_bpfptr_offset(&fd, fd_array,
20702 					    (size_t)i * sizeof(fd), sizeof(fd)))
20703 			return -EFAULT;
20704 		ret = add_fd_from_fd_array(env, i, fd);
20705 		if (ret)
20706 			return ret;
20707 	}
20708 	return 0;
20709 }
20710 
20711 static int process_fd_array(struct bpf_verifier_env *env,
20712 			    union bpf_attr *attr, bpfptr_t uattr)
20713 {
20714 	bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20715 
20716 	if (bpfptr_is_null(fd_array)) {
20717 		if (attr->fd_array_cnt) {
20718 			verbose(env, "fd_array_cnt %u without fd_array is invalid\n",
20719 				attr->fd_array_cnt);
20720 			return -EINVAL;
20721 		}
20722 		return 0;
20723 	}
20724 	/*
20725 	 * New API: the caller passes fd_array_cnt and a continuous array that
20726 	 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep
20727 	 * the caller's array and resolve entries on the spot at each reference.
20728 	 */
20729 	if (attr->fd_array_cnt)
20730 		return process_fd_array_continuous(env, fd_array,
20731 						   attr->fd_array_cnt);
20732 	env->fd_array_raw = fd_array;
20733 	return 0;
20734 }
20735 
20736 /* replace a generic kfunc with a specialized version if necessary */
20737 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
20738 {
20739 	struct bpf_prog *prog = env->prog;
20740 	bool seen_direct_write;
20741 	void *xdp_kfunc;
20742 	bool is_rdonly;
20743 	u32 func_id = desc->func_id;
20744 	u16 offset = desc->offset;
20745 	unsigned long addr = desc->addr;
20746 
20747 	if (offset) /* return if module BTF is used */
20748 		return 0;
20749 
20750 	if (bpf_dev_bound_kfunc_id(func_id)) {
20751 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20752 		if (xdp_kfunc)
20753 			addr = (unsigned long)xdp_kfunc;
20754 		/* fallback to default kfunc when not supported by netdev */
20755 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20756 		seen_direct_write = env->seen_direct_write;
20757 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20758 
20759 		if (is_rdonly)
20760 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20761 
20762 		/* restore env->seen_direct_write to its original value, since
20763 		 * may_access_direct_pkt_data mutates it
20764 		 */
20765 		env->seen_direct_write = seen_direct_write;
20766 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
20767 		if (bpf_lsm_has_d_inode_locked(prog))
20768 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
20769 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
20770 		if (bpf_lsm_has_d_inode_locked(prog))
20771 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
20772 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
20773 		if (!env->insn_aux_data[insn_idx].non_sleepable)
20774 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
20775 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
20776 		if (env->insn_aux_data[insn_idx].non_sleepable)
20777 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
20778 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
20779 		if (env->insn_aux_data[insn_idx].non_sleepable)
20780 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
20781 	}
20782 	desc->addr = addr;
20783 	return 0;
20784 }
20785 
20786 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20787 					    u16 struct_meta_reg,
20788 					    u16 node_offset_reg,
20789 					    struct bpf_insn *insn,
20790 					    struct bpf_insn *insn_buf,
20791 					    int *cnt)
20792 {
20793 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20794 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20795 
20796 	insn_buf[0] = addr[0];
20797 	insn_buf[1] = addr[1];
20798 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20799 	insn_buf[3] = *insn;
20800 	*cnt = 4;
20801 }
20802 
20803 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20804 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20805 {
20806 	struct bpf_kfunc_desc *desc;
20807 	int err;
20808 
20809 	if (!insn->imm) {
20810 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20811 		return -EINVAL;
20812 	}
20813 
20814 	*cnt = 0;
20815 
20816 	/* insn->imm has the btf func_id. Replace it with an offset relative to
20817 	 * __bpf_call_base, unless the JIT needs to call functions that are
20818 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20819 	 */
20820 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20821 	if (!desc) {
20822 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
20823 			     insn->imm);
20824 		return -EFAULT;
20825 	}
20826 
20827 	err = specialize_kfunc(env, desc, insn_idx);
20828 	if (err)
20829 		return err;
20830 
20831 	if (!bpf_jit_supports_far_kfunc_call())
20832 		insn->imm = BPF_CALL_IMM(desc->addr);
20833 
20834 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
20835 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20836 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20837 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20838 
20839 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
20840 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
20841 				     insn_idx);
20842 			return -EFAULT;
20843 		}
20844 
20845 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20846 		insn_buf[1] = addr[0];
20847 		insn_buf[2] = addr[1];
20848 		insn_buf[3] = *insn;
20849 		*cnt = 4;
20850 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
20851 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
20852 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
20853 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20854 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20855 
20856 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
20857 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
20858 				     insn_idx);
20859 			return -EFAULT;
20860 		}
20861 
20862 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
20863 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
20864 				     insn_idx);
20865 			return -EFAULT;
20866 		}
20867 
20868 		insn_buf[0] = addr[0];
20869 		insn_buf[1] = addr[1];
20870 		insn_buf[2] = *insn;
20871 		*cnt = 3;
20872 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
20873 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
20874 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20875 		int struct_meta_reg = BPF_REG_3;
20876 		int node_offset_reg = BPF_REG_4;
20877 
20878 		/* list_add/rbtree_add have an extra arg (prev/less),
20879 		 * so args-to-fixup are in diff regs.
20880 		 */
20881 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
20882 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
20883 			struct_meta_reg = BPF_REG_4;
20884 			node_offset_reg = BPF_REG_5;
20885 		}
20886 
20887 		if (!kptr_struct_meta) {
20888 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
20889 				     insn_idx);
20890 			return -EFAULT;
20891 		}
20892 
20893 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
20894 						node_offset_reg, insn, insn_buf, cnt);
20895 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
20896 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
20897 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20898 		*cnt = 1;
20899 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
20900 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
20901 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
20902 
20903 		/*
20904 		 * inline the bpf_session_is_return() for fsession:
20905 		 *   bool bpf_session_is_return(void *ctx)
20906 		 *   {
20907 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
20908 		 *   }
20909 		 */
20910 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20911 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
20912 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
20913 		*cnt = 3;
20914 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
20915 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
20916 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
20917 		/*
20918 		 * inline bpf_session_cookie() for fsession:
20919 		 *   __u64 *bpf_session_cookie(void *ctx)
20920 		 *   {
20921 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
20922 		 *       return &((u64 *)ctx)[-off];
20923 		 *   }
20924 		 */
20925 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20926 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
20927 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
20928 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20929 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
20930 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
20931 		*cnt = 6;
20932 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) {
20933 		/* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */
20934 		int i = 0;
20935 
20936 		/* if (start > end) goto einval; */
20937 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8);
20938 		/* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */
20939 		insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3);
20940 		insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2);
20941 		insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8);
20942 		/* s->cur = start - 1; s->end = end; return 0; */
20943 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1);
20944 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0);
20945 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4);
20946 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
20947 		insn_buf[i++] = BPF_JMP_A(5);
20948 		/* einval: s->cur = s->end = 0; return -EINVAL; */
20949 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
20950 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20951 		insn_buf[i++] = BPF_JMP_A(2);
20952 		/* e2big: s->cur = s->end = 0; return -E2BIG; */
20953 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
20954 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
20955 		*cnt = i;
20956 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) {
20957 		/* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */
20958 		int i = 0;
20959 
20960 		/* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */
20961 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0);
20962 		insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1);
20963 		insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4);
20964 		insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3);
20965 		/* s->cur = r0; return &s->cur; */
20966 		insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0);
20967 		insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20968 		insn_buf[i++] = BPF_JMP_A(2);
20969 		/* done: s->cur = s->end = 0; return NULL; */
20970 		insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0);
20971 		insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0);
20972 		*cnt = i;
20973 	} else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) {
20974 		/* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */
20975 		insn_buf[0] = BPF_JMP_A(0);
20976 		*cnt = 1;
20977 	}
20978 
20979 	if (env->insn_aux_data[insn_idx].arg_prog) {
20980 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
20981 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
20982 		int idx = *cnt;
20983 
20984 		insn_buf[idx++] = ld_addrs[0];
20985 		insn_buf[idx++] = ld_addrs[1];
20986 		insn_buf[idx++] = *insn;
20987 		*cnt = idx;
20988 	}
20989 	return 0;
20990 }
20991 
20992 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id)
20993 {
20994 	switch (keyring_id) {
20995 	case 0:
20996 		return BPF_SIG_KEYRING_BUILTIN;
20997 	case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING:
20998 		return BPF_SIG_KEYRING_SECONDARY;
20999 	case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING:
21000 		return BPF_SIG_KEYRING_PLATFORM;
21001 	default:
21002 		return BPF_SIG_KEYRING_USER;
21003 	}
21004 }
21005 
21006 /*
21007  * Verify the PKCS#7 signature of a loaded program. Called from bpf_check()
21008  * once the program's metadata maps have been resolved into used_maps, so
21009  * the exact maps folded into the signature are the ones the program binds.
21010  *
21011  * The signature covers the instructions followed by the frozen contents of
21012  * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the
21013  * verdict and keyring info are recorded on prog->aux.
21014  */
21015 static int bpf_prog_verify_signature(struct bpf_verifier_env *env,
21016 				     union bpf_attr *attr, bool is_kernel)
21017 {
21018 	bpfptr_t usig = make_bpfptr(attr->signature, is_kernel);
21019 	struct bpf_dynptr_kern sig_ptr, data_ptr;
21020 	struct bpf_prog *prog = env->prog;
21021 	struct bpf_map **maps = env->used_maps;
21022 	struct bpf_key *key = NULL;
21023 	void *sig, *data = NULL;
21024 	u32 map_cnt = env->used_map_cnt;
21025 	u32 i, off, insns_sz;
21026 	u64 data_sz;
21027 	int err = 0;
21028 
21029 	/*
21030 	 * Don't attempt to use kmalloc_large or vmalloc for signatures.
21031 	 * Practical signature for BPF program should be below this limit.
21032 	 */
21033 	if (!attr->signature_size ||
21034 	    attr->signature_size > KMALLOC_MAX_CACHE_SIZE)
21035 		return -EINVAL;
21036 	if (system_keyring_id_check(attr->keyring_id) == 0)
21037 		key = bpf_lookup_system_key(attr->keyring_id);
21038 	else
21039 		key = bpf_lookup_user_key(attr->keyring_id, 0);
21040 	if (!key) {
21041 		verbose(env, "cannot resolve signing keyring with keyring_id %d\n",
21042 			attr->keyring_id);
21043 		return -EINVAL;
21044 	}
21045 
21046 	sig = kvmemdup_bpfptr(usig, attr->signature_size);
21047 	if (IS_ERR(sig)) {
21048 		bpf_key_put(key);
21049 		return PTR_ERR(sig);
21050 	}
21051 
21052 	insns_sz = prog->len * sizeof(struct bpf_insn);
21053 	data_sz = insns_sz;
21054 	for (i = 0; i < map_cnt; i++) {
21055 		struct bpf_map *map = maps[i];
21056 
21057 		if (map->map_type != BPF_MAP_TYPE_ARRAY ||
21058 		    !map->ops->map_direct_value_addr) {
21059 			verbose(env, "signed program metadata map '%s' must be an array\n",
21060 				map->name);
21061 			err = -EINVAL;
21062 			goto out;
21063 		}
21064 		if (!READ_ONCE(map->frozen)) {
21065 			verbose(env, "signed program metadata map '%s' must be frozen\n",
21066 				map->name);
21067 			err = -EPERM;
21068 			goto out;
21069 		}
21070 		if (bpf_map_write_active(map)) {
21071 			verbose(env, "signed program metadata map '%s' has active writers\n",
21072 				map->name);
21073 			err = -EBUSY;
21074 			goto out;
21075 		}
21076 		if (!map->excl_prog_sha) {
21077 			verbose(env, "signed program metadata map '%s' must be exclusive\n",
21078 				map->name);
21079 			err = -EPERM;
21080 			goto out;
21081 		}
21082 		data_sz += map->value_size;
21083 	}
21084 	if (bpf_dynptr_check_size(data_sz)) {
21085 		verbose(env, "signed payload too large: %llu bytes\n", data_sz);
21086 		err = -E2BIG;
21087 		goto out;
21088 	}
21089 	data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21090 	if (!data) {
21091 		err = -ENOMEM;
21092 		goto out;
21093 	}
21094 	memcpy(data, prog->insnsi, insns_sz);
21095 	off = insns_sz;
21096 	for (i = 0; i < map_cnt; i++) {
21097 		struct bpf_map *map = maps[i];
21098 		u64 addr;
21099 
21100 		err = map->ops->map_direct_value_addr(map, &addr, 0);
21101 		if (err) {
21102 			verbose(env, "failed to read signed metadata map '%s': %d\n",
21103 				map->name, err);
21104 			goto out;
21105 		}
21106 		memcpy(data + off, (void *)(unsigned long)addr,
21107 		       map->value_size);
21108 		off += map->value_size;
21109 	}
21110 
21111 	bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz);
21112 	bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0,
21113 			attr->signature_size);
21114 
21115 	err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr,
21116 					 (struct bpf_dynptr *)&sig_ptr, key);
21117 	if (err) {
21118 		verbose(env, "signature verification failed: %d\n", err);
21119 	} else {
21120 		verbose(env, "signature verification passed\n");
21121 		prog->aux->sig.keyring_serial = bpf_key_serial(key);
21122 		prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id);
21123 		prog->aux->sig.verdict = BPF_SIG_VERIFIED;
21124 	}
21125 out:
21126 	kvfree(data);
21127 	bpf_key_put(key);
21128 	kvfree(sig);
21129 	return err;
21130 }
21131 
21132 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
21133 	      struct bpf_log_attr *attr_log)
21134 {
21135 	u64 start_time = ktime_get_ns();
21136 	struct bpf_verifier_env *env;
21137 	int i, len, ret = -EINVAL, err;
21138 	bool is_priv;
21139 
21140 	BTF_TYPE_EMIT(enum bpf_features);
21141 
21142 	/* no program is valid */
21143 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21144 		return -EINVAL;
21145 
21146 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
21147 	 * allocate/free it every time bpf_check() is called
21148 	 */
21149 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
21150 	if (!env)
21151 		return -ENOMEM;
21152 
21153 	env->bt.env = env;
21154 	env->prog = *prog;
21155 	env->ops = bpf_verifier_ops[env->prog->type];
21156 
21157 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21158 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21159 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21160 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21161 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21162 	env->signature = attr->signature;
21163 
21164 	/* user could have requested verbose verifier output
21165 	 * and supplied buffer to store the verification trace
21166 	 */
21167 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
21168 	if (ret)
21169 		goto err_free_env;
21170 	ret = bpf_diag_init(env);
21171 	if (ret)
21172 		goto err_prep;
21173 	if (env->signature) {
21174 		ret = bpf_prog_calc_tag(env->prog);
21175 		if (ret < 0)
21176 			goto err_prep;
21177 	}
21178 
21179 	ret = process_fd_array(env, attr, uattr);
21180 	if (ret)
21181 		goto err_prep;
21182 
21183 	if (env->signature) {
21184 		ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel);
21185 		if (ret)
21186 			goto err_prep;
21187 	}
21188 
21189 	ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token,
21190 				     uattr.is_kernel);
21191 	if (ret)
21192 		goto err_prep;
21193 
21194 	bpf_get_btf_vmlinux();
21195 
21196 	/* Serialize verification of unprivileged programs. */
21197 	if (!is_priv)
21198 		mutex_lock(&bpf_verifier_lock);
21199 
21200 	len = env->insn_aux_data_len = env->prog->len;
21201 	env->insn_aux_data =
21202 		__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),
21203 			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21204 	ret = -ENOMEM;
21205 	if (!env->insn_aux_data)
21206 		goto skip_full_check;
21207 	for (i = 0; i < len; i++)
21208 		env->insn_aux_data[i].orig_idx = i;
21209 	env->succ = bpf_iarray_realloc(NULL, 2);
21210 	if (!env->succ)
21211 		goto skip_full_check;
21212 
21213 	mark_verifier_state_clean(env);
21214 
21215 	if (IS_ERR(btf_vmlinux)) {
21216 		/* Either gcc or pahole or kernel are broken. */
21217 		verbose(env, "in-kernel BTF is malformed\n");
21218 		ret = PTR_ERR(btf_vmlinux);
21219 		goto skip_full_check;
21220 	}
21221 
21222 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21223 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21224 		env->strict_alignment = true;
21225 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21226 		env->strict_alignment = false;
21227 
21228 	if (is_priv)
21229 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21230 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21231 
21232 	env->explored_states = kvzalloc_objs(struct list_head,
21233 					     state_htab_size(env),
21234 					     GFP_KERNEL_ACCOUNT);
21235 	ret = -ENOMEM;
21236 	if (!env->explored_states)
21237 		goto skip_full_check;
21238 
21239 	for (i = 0; i < state_htab_size(env); i++)
21240 		INIT_LIST_HEAD(&env->explored_states[i]);
21241 	INIT_LIST_HEAD(&env->free_list);
21242 
21243 	/* Prepare BTF and func_info needed to discover all subprograms. */
21244 	ret = bpf_prepare_btf_info(env, attr, uattr);
21245 	if (ret < 0)
21246 		goto skip_full_check;
21247 
21248 	/* Discover all subprograms before validating their layout and BTF. */
21249 	ret = add_subprogs(env);
21250 	if (ret < 0)
21251 		goto skip_full_check;
21252 
21253 	ret = check_subprogs(env);
21254 	if (ret < 0)
21255 		goto skip_full_check;
21256 
21257 	/* Validate BTF against the complete subprogram layout and apply CO-RE. */
21258 	ret = bpf_check_btf_info(env, attr, uattr);
21259 	if (ret < 0)
21260 		goto skip_full_check;
21261 
21262 	/* Validate instructions and resolve the program's referenced resources. */
21263 	ret = check_and_resolve_insns(env);
21264 	if (ret < 0)
21265 		goto skip_full_check;
21266 
21267 	/* Build kfunc prototypes after resolving program resources. */
21268 	ret = add_kfuncs(env);
21269 	if (ret < 0)
21270 		goto skip_full_check;
21271 
21272 	if (bpf_prog_is_offloaded(env->prog->aux)) {
21273 		ret = bpf_prog_offload_verifier_prep(env->prog);
21274 		if (ret)
21275 			goto skip_full_check;
21276 	}
21277 
21278 	ret = bpf_check_cfg(env);
21279 	if (ret < 0)
21280 		goto skip_full_check;
21281 
21282 	ret = bpf_compute_postorder(env);
21283 	if (ret < 0)
21284 		goto skip_full_check;
21285 
21286 	ret = bpf_stack_liveness_init(env);
21287 	if (ret)
21288 		goto skip_full_check;
21289 
21290 	ret = check_attach_btf_id(env);
21291 	if (ret)
21292 		goto skip_full_check;
21293 
21294 	ret = bpf_compute_const_regs(env);
21295 	if (ret < 0)
21296 		goto skip_full_check;
21297 
21298 	ret = bpf_prune_dead_branches(env);
21299 	if (ret < 0)
21300 		goto skip_full_check;
21301 
21302 	ret = sort_subprogs_topo(env);
21303 	if (ret < 0)
21304 		goto skip_full_check;
21305 
21306 	ret = bpf_compute_scc(env);
21307 	if (ret < 0)
21308 		goto skip_full_check;
21309 
21310 	ret = bpf_compute_live_registers(env);
21311 	if (ret < 0)
21312 		goto skip_full_check;
21313 
21314 	ret = mark_fastcall_patterns(env);
21315 	if (ret < 0)
21316 		goto skip_full_check;
21317 
21318 	ret = do_check_main(env);
21319 	ret = ret ?: do_check_subprogs(env);
21320 
21321 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21322 		ret = bpf_prog_offload_finalize(env);
21323 
21324 skip_full_check:
21325 	kvfree(env->explored_states);
21326 
21327 	/* might decrease stack depth, keep it before passes that
21328 	 * allocate additional slots.
21329 	 */
21330 	if (ret == 0)
21331 		ret = bpf_remove_fastcall_spills_fills(env);
21332 
21333 	if (ret == 0)
21334 		ret = check_max_stack_depth(env);
21335 
21336 	/* instruction rewrites happen after this point */
21337 	if (ret == 0)
21338 		ret = bpf_optimize_bpf_loop(env);
21339 
21340 	if (is_priv) {
21341 		if (ret == 0)
21342 			bpf_opt_hard_wire_dead_code_branches(env);
21343 		if (ret == 0)
21344 			ret = bpf_opt_remove_dead_code(env);
21345 		if (ret == 0)
21346 			ret = bpf_opt_remove_nops(env);
21347 	} else {
21348 		if (ret == 0)
21349 			sanitize_dead_code(env);
21350 	}
21351 
21352 	if (ret == 0)
21353 		/* program is valid, convert *(u32*)(ctx + off) accesses */
21354 		ret = bpf_convert_ctx_accesses(env);
21355 
21356 	if (ret == 0)
21357 		ret = bpf_do_misc_fixups(env);
21358 
21359 	/* do 32-bit optimization after insn patching has done so those patched
21360 	 * insns could be handled correctly.
21361 	 */
21362 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21363 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
21364 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21365 								     : false;
21366 	}
21367 
21368 	if (ret == 0)
21369 		ret = bpf_fixup_call_args(env);
21370 
21371 	env->verification_time = ktime_get_ns() - start_time;
21372 	print_verification_stats(env);
21373 	env->prog->aux->verified_insns = env->insn_processed;
21374 
21375 	/* preserve original error even if log finalization is successful */
21376 	err = bpf_log_attr_finalize(attr_log, &env->log);
21377 	if (err)
21378 		ret = err;
21379 
21380 	if (ret)
21381 		goto err_release_maps;
21382 
21383 	if (env->used_map_cnt) {
21384 		/* if program passed verifier, update used_maps in bpf_prog_info */
21385 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
21386 							 env->used_map_cnt,
21387 							 GFP_KERNEL_ACCOUNT);
21388 
21389 		if (!env->prog->aux->used_maps) {
21390 			ret = -ENOMEM;
21391 			goto err_release_maps;
21392 		}
21393 
21394 		memcpy(env->prog->aux->used_maps, env->used_maps,
21395 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
21396 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21397 	}
21398 	if (env->used_btf_cnt) {
21399 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21400 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
21401 							 env->used_btf_cnt,
21402 							 GFP_KERNEL_ACCOUNT);
21403 		if (!env->prog->aux->used_btfs) {
21404 			ret = -ENOMEM;
21405 			goto err_release_maps;
21406 		}
21407 
21408 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21409 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21410 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21411 	}
21412 	if (env->used_map_cnt || env->used_btf_cnt) {
21413 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21414 		 * bpf_ld_imm64 instructions
21415 		 */
21416 		convert_pseudo_ld_imm64(env);
21417 	}
21418 
21419 	adjust_btf_func(env);
21420 
21421 	/* extension progs temporarily inherit the attach_type of their targets
21422 	   for verification purposes, so set it back to zero before returning
21423 	 */
21424 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21425 		env->prog->expected_attach_type = 0;
21426 
21427 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
21428 
21429 err_release_maps:
21430 	if (ret)
21431 		release_insn_arrays(env);
21432 	if (!env->prog->aux->used_maps)
21433 		/* if we didn't copy map pointers into bpf_prog_info, release
21434 		 * them now. Otherwise free_used_maps() will release them.
21435 		 */
21436 		release_maps(env);
21437 	if (!env->prog->aux->used_btfs)
21438 		release_btfs(env);
21439 
21440 	*prog = env->prog;
21441 
21442 	module_put(env->attach_btf_mod);
21443 	if (!is_priv)
21444 		mutex_unlock(&bpf_verifier_lock);
21445 	goto err_free_env;
21446 err_prep:
21447 	err = bpf_log_attr_finalize(attr_log, &env->log);
21448 	if (err)
21449 		ret = err;
21450 	release_insn_arrays(env);
21451 	release_maps(env);
21452 	release_btfs(env);
21453 err_free_env:
21454 	if (env->insn_aux_data)
21455 		bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
21456 	vfree(env->insn_aux_data);
21457 	kvfree(env->fd_array);
21458 	bpf_stack_liveness_free(env);
21459 	kvfree(env->cfg.insn_postorder);
21460 	kvfree(env->scc_info);
21461 	kvfree(env->succ);
21462 	kvfree(env->gotox_tmp_buf);
21463 	bpf_diag_free(env);
21464 	kvfree(env);
21465 	return ret;
21466 }
21467