xref: /linux/kernel/bpf/verifier.c (revision 3ef975893041b9f826475298c802b5c046d0ba16)
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/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/cnum.h>
30 #include <linux/bpf_mem_alloc.h>
31 #include <net/xdp.h>
32 #include <linux/trace_events.h>
33 #include <linux/kallsyms.h>
34 
35 #include "disasm.h"
36 
37 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
38 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
39 	[_id] = & _name ## _verifier_ops,
40 #define BPF_MAP_TYPE(_id, _ops)
41 #define BPF_LINK_TYPE(_id, _name)
42 #include <linux/bpf_types.h>
43 #undef BPF_PROG_TYPE
44 #undef BPF_MAP_TYPE
45 #undef BPF_LINK_TYPE
46 };
47 
48 enum bpf_features {
49 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
50 	BPF_FEAT_STREAMS	     = 1,
51 	__MAX_BPF_FEAT,
52 };
53 
54 struct bpf_mem_alloc bpf_global_percpu_ma;
55 static bool bpf_global_percpu_ma_set;
56 
57 /* bpf_check() is a static code analyzer that walks eBPF program
58  * instruction by instruction and updates register/stack state.
59  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
60  *
61  * The first pass is depth-first-search to check that the program is a DAG.
62  * It rejects the following programs:
63  * - larger than BPF_MAXINSNS insns
64  * - if loop is present (detected via back-edge)
65  * - unreachable insns exist (shouldn't be a forest. program = one function)
66  * - out of bounds or malformed jumps
67  * The second pass is all possible path descent from the 1st insn.
68  * Since it's analyzing all paths through the program, the length of the
69  * analysis is limited to 64k insn, which may be hit even if total number of
70  * insn is less then 4K, but there are too many branches that change stack/regs.
71  * Number of 'branches to be analyzed' is limited to 1k
72  *
73  * On entry to each instruction, each register has a type, and the instruction
74  * changes the types of the registers depending on instruction semantics.
75  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
76  * copied to R1.
77  *
78  * All registers are 64-bit.
79  * R0 - return register
80  * R1-R5 argument passing registers
81  * R6-R9 callee saved registers
82  * R10 - frame pointer read-only
83  *
84  * At the start of BPF program the register R1 contains a pointer to bpf_context
85  * and has type PTR_TO_CTX.
86  *
87  * Verifier tracks arithmetic operations on pointers in case:
88  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
89  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
90  * 1st insn copies R10 (which has FRAME_PTR) type into R1
91  * and 2nd arithmetic instruction is pattern matched to recognize
92  * that it wants to construct a pointer to some element within stack.
93  * So after 2nd insn, the register R1 has type PTR_TO_STACK
94  * (and -20 constant is saved for further stack bounds checking).
95  * Meaning that this reg is a pointer to stack plus known immediate constant.
96  *
97  * Most of the time the registers have SCALAR_VALUE type, which
98  * means the register has some value, but it's not a valid pointer.
99  * (like pointer plus pointer becomes SCALAR_VALUE type)
100  *
101  * When verifier sees load or store instructions the type of base register
102  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
103  * four pointer types recognized by check_mem_access() function.
104  *
105  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
106  * and the range of [ptr, ptr + map's value_size) is accessible.
107  *
108  * registers used to pass values to function calls are checked against
109  * function argument constraints.
110  *
111  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
112  * It means that the register type passed to this function must be
113  * PTR_TO_STACK and it will be used inside the function as
114  * 'pointer to map element key'
115  *
116  * For example the argument constraints for bpf_map_lookup_elem():
117  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
118  *   .arg1_type = ARG_CONST_MAP_PTR,
119  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
120  *
121  * ret_type says that this function returns 'pointer to map elem value or null'
122  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
123  * 2nd argument should be a pointer to stack, which will be used inside
124  * the helper function as a pointer to map element key.
125  *
126  * On the kernel side the helper function looks like:
127  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
128  * {
129  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
130  *    void *key = (void *) (unsigned long) r2;
131  *    void *value;
132  *
133  *    here kernel can access 'key' and 'map' pointers safely, knowing that
134  *    [key, key + map->key_size) bytes are valid and were initialized on
135  *    the stack of eBPF program.
136  * }
137  *
138  * Corresponding eBPF program may look like:
139  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
140  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
141  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
142  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
143  * here verifier looks at prototype of map_lookup_elem() and sees:
144  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
145  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
146  *
147  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
148  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
149  * and were initialized prior to this call.
150  * If it's ok, then verifier allows this BPF_CALL insn and looks at
151  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
152  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
153  * returns either pointer to map value or NULL.
154  *
155  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
156  * insn, the register holding that pointer in the true branch changes state to
157  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
158  * branch. See check_cond_jmp_op().
159  *
160  * After the call R0 is set to return type of the function and registers R1-R5
161  * are set to NOT_INIT to indicate that they are no longer readable.
162  *
163  * The following reference types represent a potential reference to a kernel
164  * resource which, after first being allocated, must be checked and freed by
165  * the BPF program:
166  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
167  *
168  * When the verifier sees a helper call return a reference type, it allocates a
169  * pointer id for the reference and stores it in the current function state.
170  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
171  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
172  * passes through a NULL-check conditional. For the branch wherein the state is
173  * changed to CONST_IMM, the verifier releases the reference.
174  *
175  * For each helper function that allocates a reference, such as
176  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
177  * bpf_sk_release(). When a reference type passes into the release function,
178  * the verifier also releases the reference. If any unchecked or unreleased
179  * reference remains at the end of the program, the verifier rejects it.
180  */
181 
182 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
183 struct bpf_verifier_stack_elem {
184 	/* verifier state is 'st'
185 	 * before processing instruction 'insn_idx'
186 	 * and after processing instruction 'prev_insn_idx'
187 	 */
188 	struct bpf_verifier_state st;
189 	int insn_idx;
190 	int prev_insn_idx;
191 	struct bpf_verifier_stack_elem *next;
192 	/* length of verifier log at the time this state was pushed on stack */
193 	u32 log_pos;
194 };
195 
196 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
197 #define BPF_COMPLEXITY_LIMIT_STATES	64
198 
199 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
200 
201 #define BPF_PRIV_STACK_MIN_SIZE		64
202 
203 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
204 static int release_reference_nomark(struct bpf_verifier_state *state, int id);
205 static int release_reference(struct bpf_verifier_env *env, int id);
206 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
207 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
208 static bool is_tracing_prog_type(enum bpf_prog_type type);
209 static int ref_set_non_owning(struct bpf_verifier_env *env,
210 			      struct bpf_reg_state *reg);
211 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
212 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
213 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
214 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
215 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);
216 
217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
218 			      struct bpf_map *map,
219 			      bool unpriv, bool poison)
220 {
221 	unpriv |= bpf_map_ptr_unpriv(aux);
222 	aux->map_ptr_state.unpriv = unpriv;
223 	aux->map_ptr_state.poison = poison;
224 	aux->map_ptr_state.map_ptr = map;
225 }
226 
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
228 {
229 	bool poisoned = bpf_map_key_poisoned(aux);
230 
231 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
233 }
234 
235 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg)
236 {
237 	ref_obj->id = reg->id;
238 	ref_obj->parent_id = reg->parent_id;
239 	ref_obj->cnt++;
240 }
241 
242 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj)
243 {
244 	if (ref_obj->cnt > 1) {
245 		verifier_bug(env, "function expects only one referenced object but got %d\n",
246 			     ref_obj->cnt);
247 		return -EFAULT;
248 	}
249 
250 	return 0;
251 }
252 
253 struct bpf_call_arg_meta {
254 	struct bpf_map_desc map;
255 	struct bpf_dynptr_desc dynptr;
256 	struct ref_obj_desc ref_obj;
257 	bool raw_mode;
258 	bool pkt_access;
259 	u8 release_regno;
260 	int regno;
261 	int access_size;
262 	int mem_size;
263 	u64 msize_max_value;
264 	int func_id;
265 	struct btf *btf;
266 	u32 btf_id;
267 	struct btf *ret_btf;
268 	u32 ret_btf_id;
269 	u32 subprogno;
270 	struct btf_field *kptr_field;
271 	s64 const_map_key;
272 };
273 
274 struct bpf_kfunc_meta {
275 	struct btf *btf;
276 	const struct btf_type *proto;
277 	const char *name;
278 	const u32 *flags;
279 	s32 id;
280 };
281 
282 struct btf *btf_vmlinux;
283 
284 typedef struct argno {
285 	int argno;
286 } argno_t;
287 
288 static argno_t argno_from_reg(u32 regno)
289 {
290 	return (argno_t){ .argno = regno };
291 }
292 
293 static argno_t argno_from_arg(u32 arg)
294 {
295 	return (argno_t){ .argno = -arg };
296 }
297 
298 static int reg_from_argno(argno_t a)
299 {
300 	if (a.argno >= 0)
301 		return a.argno;
302 	if (a.argno >= -MAX_BPF_FUNC_REG_ARGS)
303 		return -a.argno;
304 	return -1;
305 }
306 
307 static int arg_from_argno(argno_t a)
308 {
309 	if (a.argno < 0)
310 		return -a.argno;
311 	return -1;
312 }
313 
314 static int arg_idx_from_argno(argno_t a)
315 {
316 	return arg_from_argno(a) - 1;
317 }
318 
319 static const char *btf_type_name(const struct btf *btf, u32 id)
320 {
321 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
322 }
323 
324 static DEFINE_MUTEX(bpf_verifier_lock);
325 static DEFINE_MUTEX(bpf_percpu_ma_lock);
326 
327 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
328 {
329 	struct bpf_verifier_env *env = private_data;
330 	va_list args;
331 
332 	if (!bpf_verifier_log_needed(&env->log))
333 		return;
334 
335 	va_start(args, fmt);
336 	bpf_verifier_vlog(&env->log, fmt, args);
337 	va_end(args);
338 }
339 
340 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
341 				   struct bpf_reg_state *reg,
342 				   struct bpf_retval_range range, const char *ctx,
343 				   const char *reg_name)
344 {
345 	bool unknown = true;
346 
347 	verbose(env, "%s the register %s has", ctx, reg_name);
348 	if (reg_smin(reg) > S64_MIN) {
349 		verbose(env, " smin=%lld", reg_smin(reg));
350 		unknown = false;
351 	}
352 	if (reg_smax(reg) < S64_MAX) {
353 		verbose(env, " smax=%lld", reg_smax(reg));
354 		unknown = false;
355 	}
356 	if (unknown)
357 		verbose(env, " unknown scalar value");
358 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
359 }
360 
361 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
362 {
363 	enum bpf_reg_type type;
364 
365 	type = reg->type;
366 	if (type_may_be_null(type))
367 		return false;
368 
369 	type = base_type(type);
370 	return type == PTR_TO_SOCKET ||
371 		type == PTR_TO_TCP_SOCK ||
372 		type == PTR_TO_MAP_VALUE ||
373 		type == PTR_TO_MAP_KEY ||
374 		type == PTR_TO_SOCK_COMMON ||
375 		(type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) ||
376 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
377 		type == CONST_PTR_TO_MAP;
378 }
379 
380 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
381 {
382 	struct btf_record *rec = NULL;
383 	struct btf_struct_meta *meta;
384 
385 	if (reg->type == PTR_TO_MAP_VALUE) {
386 		rec = reg->map_ptr->record;
387 	} else if (type_is_ptr_alloc_obj(reg->type)) {
388 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
389 		if (meta)
390 			rec = meta->record;
391 	}
392 	return rec;
393 }
394 
395 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog)
396 {
397 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
398 
399 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
400 }
401 
402 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
403 {
404 	const struct btf_type *type, *func, *func_proto;
405 	const struct btf *btf = env->prog->aux->btf;
406 	u32 btf_id;
407 
408 	btf_id = env->prog->aux->func_info[subprog].type_id;
409 
410 	func = btf_type_by_id(btf, btf_id);
411 	if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id))
412 		return false;
413 
414 	func_proto = btf_type_by_id(btf, func->type);
415 	if (!func_proto)
416 		return false;
417 
418 	type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
419 	if (!type)
420 		return false;
421 
422 	return btf_type_is_void(type);
423 }
424 
425 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
426 {
427 	struct bpf_func_info *info;
428 
429 	if (!env->prog->aux->func_info)
430 		return "";
431 
432 	info = &env->prog->aux->func_info[subprog];
433 	return btf_type_name(env->prog->aux->btf, info->type_id);
434 }
435 
436 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
437 {
438 	struct bpf_subprog_info *info = subprog_info(env, subprog);
439 
440 	info->is_cb = true;
441 	info->is_async_cb = true;
442 	info->is_exception_cb = true;
443 }
444 
445 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
446 {
447 	return subprog_info(env, subprog)->is_exception_cb;
448 }
449 
450 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
451 {
452 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
453 }
454 
455 static bool type_is_rdonly_mem(u32 type)
456 {
457 	return type & MEM_RDONLY;
458 }
459 
460 static bool is_acquire_function(enum bpf_func_id func_id,
461 				const struct bpf_map *map)
462 {
463 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
464 
465 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
466 	    func_id == BPF_FUNC_sk_lookup_udp ||
467 	    func_id == BPF_FUNC_skc_lookup_tcp ||
468 	    func_id == BPF_FUNC_ringbuf_reserve ||
469 	    func_id == BPF_FUNC_kptr_xchg)
470 		return true;
471 
472 	if (func_id == BPF_FUNC_map_lookup_elem &&
473 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
474 	     map_type == BPF_MAP_TYPE_SOCKHASH))
475 		return true;
476 
477 	return false;
478 }
479 
480 static bool is_ptr_cast_function(enum bpf_func_id func_id)
481 {
482 	return func_id == BPF_FUNC_tcp_sock ||
483 		func_id == BPF_FUNC_sk_fullsock ||
484 		func_id == BPF_FUNC_skc_to_tcp_sock ||
485 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
486 		func_id == BPF_FUNC_skc_to_udp6_sock ||
487 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
488 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
489 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
490 }
491 
492 static bool is_sync_callback_calling_kfunc(u32 btf_id);
493 static bool is_async_callback_calling_kfunc(u32 btf_id);
494 static bool is_callback_calling_kfunc(u32 btf_id);
495 
496 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id);
497 static bool is_task_work_add_kfunc(u32 func_id);
498 
499 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
500 {
501 	return func_id == BPF_FUNC_for_each_map_elem ||
502 	       func_id == BPF_FUNC_find_vma ||
503 	       func_id == BPF_FUNC_loop ||
504 	       func_id == BPF_FUNC_user_ringbuf_drain;
505 }
506 
507 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_timer_set_callback;
510 }
511 
512 static bool is_callback_calling_function(enum bpf_func_id func_id)
513 {
514 	return is_sync_callback_calling_function(func_id) ||
515 	       is_async_callback_calling_function(func_id);
516 }
517 
518 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn)
519 {
520 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
521 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
522 }
523 
524 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn)
525 {
526 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
527 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
528 }
529 
530 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
531 {
532 	/* bpf_timer callbacks are never sleepable. */
533 	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
534 		return false;
535 
536 	/* bpf_wq and bpf_task_work callbacks are always sleepable. */
537 	if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
538 	    (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
539 		return true;
540 
541 	verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
542 	return false;
543 }
544 
545 bool bpf_is_may_goto_insn(struct bpf_insn *insn)
546 {
547 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
548 }
549 
550 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
551 {
552        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
553 
554        /* We need to check that slots between [spi - nr_slots + 1, spi] are
555 	* within [0, allocated_stack).
556 	*
557 	* Please note that the spi grows downwards. For example, a dynptr
558 	* takes the size of two stack slots; the first slot will be at
559 	* spi and the second slot will be at spi - 1.
560 	*/
561        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
562 }
563 
564 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
565 			          const char *obj_kind, int nr_slots)
566 {
567 	int off, spi;
568 
569 	if (!tnum_is_const(reg->var_off)) {
570 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
571 		return -EINVAL;
572 	}
573 
574 	off = reg->var_off.value;
575 	if (off % BPF_REG_SIZE) {
576 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
577 		return -EINVAL;
578 	}
579 
580 	spi = bpf_get_spi(off);
581 	if (spi + 1 < nr_slots) {
582 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
583 		return -EINVAL;
584 	}
585 
586 	if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots))
587 		return -ERANGE;
588 	return spi;
589 }
590 
591 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
592 {
593 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
594 }
595 
596 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
597 {
598 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
599 }
600 
601 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
602 {
603 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
604 }
605 
606 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
607 {
608 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
609 	case DYNPTR_TYPE_LOCAL:
610 		return BPF_DYNPTR_TYPE_LOCAL;
611 	case DYNPTR_TYPE_RINGBUF:
612 		return BPF_DYNPTR_TYPE_RINGBUF;
613 	case DYNPTR_TYPE_SKB:
614 		return BPF_DYNPTR_TYPE_SKB;
615 	case DYNPTR_TYPE_XDP:
616 		return BPF_DYNPTR_TYPE_XDP;
617 	case DYNPTR_TYPE_SKB_META:
618 		return BPF_DYNPTR_TYPE_SKB_META;
619 	case DYNPTR_TYPE_FILE:
620 		return BPF_DYNPTR_TYPE_FILE;
621 	default:
622 		return BPF_DYNPTR_TYPE_INVALID;
623 	}
624 }
625 
626 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
627 {
628 	switch (type) {
629 	case BPF_DYNPTR_TYPE_LOCAL:
630 		return DYNPTR_TYPE_LOCAL;
631 	case BPF_DYNPTR_TYPE_RINGBUF:
632 		return DYNPTR_TYPE_RINGBUF;
633 	case BPF_DYNPTR_TYPE_SKB:
634 		return DYNPTR_TYPE_SKB;
635 	case BPF_DYNPTR_TYPE_XDP:
636 		return DYNPTR_TYPE_XDP;
637 	case BPF_DYNPTR_TYPE_SKB_META:
638 		return DYNPTR_TYPE_SKB_META;
639 	case BPF_DYNPTR_TYPE_FILE:
640 		return DYNPTR_TYPE_FILE;
641 	default:
642 		return 0;
643 	}
644 }
645 
646 static bool dynptr_type_referenced(enum bpf_dynptr_type type)
647 {
648 	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
649 }
650 
651 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
652 			      enum bpf_dynptr_type type,
653 			      bool first_slot, int id, int parent_id);
654 
655 
656 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
657 				   struct bpf_reg_state *sreg1,
658 				   struct bpf_reg_state *sreg2,
659 				   enum bpf_dynptr_type type, int parent_id)
660 {
661 	int id = ++env->id_gen;
662 
663 	__mark_dynptr_reg(sreg1, type, true, id, parent_id);
664 	__mark_dynptr_reg(sreg2, type, false, id, parent_id);
665 }
666 
667 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
668 			       struct bpf_reg_state *reg,
669 			       enum bpf_dynptr_type type)
670 {
671 	__mark_dynptr_reg(reg, type, true, ++env->id_gen, 0);
672 }
673 
674 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
675 				        struct bpf_func_state *state, int spi);
676 
677 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
678 				   enum bpf_arg_type arg_type, int insn_idx,
679 				   struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
680 {
681 	struct bpf_func_state *state = bpf_func(env, reg);
682 	int spi, i, err, parent_id = 0;
683 	enum bpf_dynptr_type type;
684 
685 	spi = dynptr_get_spi(env, reg);
686 	if (spi < 0)
687 		return spi;
688 
689 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
690 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
691 	 * to ensure that for the following example:
692 	 *	[d1][d1][d2][d2]
693 	 * spi    3   2   1   0
694 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
695 	 * case they do belong to same dynptr, second call won't see slot_type
696 	 * as STACK_DYNPTR and will simply skip destruction.
697 	 */
698 	err = destroy_if_dynptr_stack_slot(env, state, spi);
699 	if (err)
700 		return err;
701 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
702 	if (err)
703 		return err;
704 
705 	for (i = 0; i < BPF_REG_SIZE; i++) {
706 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
707 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
708 	}
709 
710 	type = arg_to_dynptr_type(arg_type);
711 	if (type == BPF_DYNPTR_TYPE_INVALID)
712 		return -EINVAL;
713 
714 	if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */
715 		err = validate_ref_obj(env, ref_obj);
716 		if (err)
717 			return err;
718 
719 		/* Track parent's id if the parent is a referenced object */
720 		parent_id = ref_obj->id;
721 
722 		if (dynptr_type_referenced(type)) {
723 			int id;
724 
725 			/*
726 			 * Create an intermediate reference that tracks the referenced
727 			 * object for the referenced dynptr. Freeing a referenced dynptr
728 			 * through helpers/kfuncs will invalidate all clones.
729 			 */
730 			id = acquire_reference(env, insn_idx, parent_id);
731 			if (id < 0)
732 				return id;
733 
734 			parent_id = id;
735 		}
736 	} else { /* bpf_dynptr_clone() */
737 		parent_id = dynptr->parent_id;
738 	}
739 
740 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
741 			       &state->stack[spi - 1].spilled_ptr, type, parent_id);
742 
743 	return 0;
744 }
745 
746 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack)
747 {
748 	int i;
749 
750 	for (i = 0; i < BPF_REG_SIZE; i++) {
751 		stack[0].slot_type[i] = STACK_INVALID;
752 		stack[1].slot_type[i] = STACK_INVALID;
753 	}
754 
755 	bpf_mark_reg_not_init(env, &stack[0].spilled_ptr);
756 	bpf_mark_reg_not_init(env, &stack[1].spilled_ptr);
757 }
758 
759 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
760 {
761 	struct bpf_func_state *state = bpf_func(env, reg);
762 	int spi;
763 
764 	spi = dynptr_get_spi(env, reg);
765 	if (spi < 0)
766 		return spi;
767 
768 	/*
769 	 * For referenced dynptr, release the parent ref which cascades to
770 	 * all clones and derived slices. For non-referenced dynptr, only
771 	 * the dynptr and slices derived from it will be invalidated.
772 	 */
773 	reg = &state->stack[spi].spilled_ptr;
774 	return release_reference(env, dynptr_type_referenced(reg->dynptr.type)
775 				      ? reg->parent_id
776 				      : reg->id);
777 }
778 
779 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
780 			       struct bpf_reg_state *reg);
781 
782 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
783 {
784 	if (!env->allow_ptr_leaks)
785 		bpf_mark_reg_not_init(env, reg);
786 	else
787 		__mark_reg_unknown(env, reg);
788 }
789 
790 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)
791 {
792 	struct bpf_stack_state *stack;
793 	struct bpf_func_state *state;
794 	struct bpf_reg_state *reg;
795 	int ref_cnt = 0;
796 
797 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({
798 		if (!stack || stack->slot_type[0] != STACK_DYNPTR)
799 			continue;
800 		if (!stack->spilled_ptr.dynptr.first_slot)
801 			continue;
802 		if (stack->spilled_ptr.parent_id == v_parent_id)
803 			ref_cnt++;
804 	}));
805 
806 	return ref_cnt;
807 }
808 
809 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
810 				        struct bpf_func_state *state, int spi)
811 {
812 	int err = 0;
813 
814 	/* We always ensure that STACK_DYNPTR is never set partially,
815 	 * hence just checking for slot_type[0] is enough. This is
816 	 * different for STACK_SPILL, where it may be only set for
817 	 * 1 byte, so code has to use is_spilled_reg.
818 	 */
819 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
820 		return 0;
821 
822 	/* Reposition spi to first slot */
823 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
824 		spi = spi + 1;
825 
826 	/*
827 	 * A referenced dynptr can be overwritten only if there is at
828 	 * least one other dynptr sharing the same virtual ref parent,
829 	 * ensuring the reference can still be properly released.
830 	 */
831 	if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) &&
832 	    dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) {
833 		verbose(env, "cannot overwrite referenced dynptr\n");
834 		return -EINVAL;
835 	}
836 
837 	/* Invalidate the dynptr and any derived slices */
838 	err = release_reference(env, state->stack[spi].spilled_ptr.id);
839 	if (!err) {
840 		mark_stack_slot_scratched(env, spi);
841 		mark_stack_slot_scratched(env, spi - 1);
842 	}
843 
844 	return err;
845 }
846 
847 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
848 {
849 	int spi;
850 
851 	if (reg->type == CONST_PTR_TO_DYNPTR)
852 		return false;
853 
854 	spi = dynptr_get_spi(env, reg);
855 
856 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
857 	 * error because this just means the stack state hasn't been updated yet.
858 	 * We will do check_mem_access to check and update stack bounds later.
859 	 */
860 	if (spi < 0 && spi != -ERANGE)
861 		return false;
862 
863 	/* We don't need to check if the stack slots are marked by previous
864 	 * dynptr initializations because we allow overwriting existing unreferenced
865 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
866 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
867 	 * touching are completely destructed before we reinitialize them for a new
868 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
869 	 * instead of delaying it until the end where the user will get "Unreleased
870 	 * reference" error.
871 	 */
872 	return true;
873 }
874 
875 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
876 {
877 	struct bpf_func_state *state = bpf_func(env, reg);
878 	int i, spi;
879 
880 	/* This already represents first slot of initialized bpf_dynptr.
881 	 *
882 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
883 	 * check_func_arg_reg_off's logic, so we don't need to check its
884 	 * offset and alignment.
885 	 */
886 	if (reg->type == CONST_PTR_TO_DYNPTR)
887 		return true;
888 
889 	spi = dynptr_get_spi(env, reg);
890 	if (spi < 0)
891 		return false;
892 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
893 		return false;
894 
895 	for (i = 0; i < BPF_REG_SIZE; i++) {
896 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
897 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
898 			return false;
899 	}
900 
901 	return true;
902 }
903 
904 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
905 				    enum bpf_arg_type arg_type)
906 {
907 	struct bpf_func_state *state = bpf_func(env, reg);
908 	enum bpf_dynptr_type dynptr_type;
909 	int spi;
910 
911 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
912 	if (arg_type == ARG_PTR_TO_DYNPTR)
913 		return true;
914 
915 	dynptr_type = arg_to_dynptr_type(arg_type);
916 	if (reg->type == CONST_PTR_TO_DYNPTR) {
917 		return reg->dynptr.type == dynptr_type;
918 	} else {
919 		spi = dynptr_get_spi(env, reg);
920 		if (spi < 0)
921 			return false;
922 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
923 	}
924 }
925 
926 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
927 
928 static bool in_rcu_cs(struct bpf_verifier_env *env);
929 
930 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
931 
932 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
933 				 struct bpf_kfunc_call_arg_meta *meta,
934 				 struct bpf_reg_state *reg, int insn_idx,
935 				 struct btf *btf, u32 btf_id, int nr_slots)
936 {
937 	struct bpf_func_state *state = bpf_func(env, reg);
938 	int spi, i, j, id;
939 
940 	spi = iter_get_spi(env, reg, nr_slots);
941 	if (spi < 0)
942 		return spi;
943 
944 	id = acquire_reference(env, insn_idx, 0);
945 	if (id < 0)
946 		return id;
947 
948 	for (i = 0; i < nr_slots; i++) {
949 		struct bpf_stack_state *slot = &state->stack[spi - i];
950 		struct bpf_reg_state *st = &slot->spilled_ptr;
951 
952 		__mark_reg_known_zero(st);
953 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
954 		if (is_kfunc_rcu_protected(meta)) {
955 			if (in_rcu_cs(env))
956 				st->type |= MEM_RCU;
957 			else
958 				st->type |= PTR_UNTRUSTED;
959 		}
960 		st->id = i == 0 ? id : 0;
961 		st->iter.btf = btf;
962 		st->iter.btf_id = btf_id;
963 		st->iter.state = BPF_ITER_STATE_ACTIVE;
964 		st->iter.depth = 0;
965 
966 		for (j = 0; j < BPF_REG_SIZE; j++)
967 			slot->slot_type[j] = STACK_ITER;
968 
969 		mark_stack_slot_scratched(env, spi - i);
970 	}
971 
972 	return 0;
973 }
974 
975 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
976 				   struct bpf_reg_state *reg, int nr_slots)
977 {
978 	struct bpf_func_state *state = bpf_func(env, reg);
979 	int spi, i, j;
980 
981 	spi = iter_get_spi(env, reg, nr_slots);
982 	if (spi < 0)
983 		return spi;
984 
985 	for (i = 0; i < nr_slots; i++) {
986 		struct bpf_stack_state *slot = &state->stack[spi - i];
987 		struct bpf_reg_state *st = &slot->spilled_ptr;
988 
989 		if (i == 0)
990 			WARN_ON_ONCE(release_reference(env, st->id));
991 
992 		bpf_mark_reg_not_init(env, st);
993 
994 		for (j = 0; j < BPF_REG_SIZE; j++)
995 			slot->slot_type[j] = STACK_INVALID;
996 
997 		mark_stack_slot_scratched(env, spi - i);
998 	}
999 
1000 	return 0;
1001 }
1002 
1003 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1004 				     struct bpf_reg_state *reg, int nr_slots)
1005 {
1006 	struct bpf_func_state *state = bpf_func(env, reg);
1007 	int spi, i, j;
1008 
1009 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1010 	 * will do check_mem_access to check and update stack bounds later, so
1011 	 * return true for that case.
1012 	 */
1013 	spi = iter_get_spi(env, reg, nr_slots);
1014 	if (spi == -ERANGE)
1015 		return true;
1016 	if (spi < 0)
1017 		return false;
1018 
1019 	for (i = 0; i < nr_slots; i++) {
1020 		struct bpf_stack_state *slot = &state->stack[spi - i];
1021 
1022 		for (j = 0; j < BPF_REG_SIZE; j++)
1023 			if (slot->slot_type[j] == STACK_ITER)
1024 				return false;
1025 	}
1026 
1027 	return true;
1028 }
1029 
1030 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1031 				   struct btf *btf, u32 btf_id, int nr_slots)
1032 {
1033 	struct bpf_func_state *state = bpf_func(env, reg);
1034 	int spi, i, j;
1035 
1036 	spi = iter_get_spi(env, reg, nr_slots);
1037 	if (spi < 0)
1038 		return -EINVAL;
1039 
1040 	for (i = 0; i < nr_slots; i++) {
1041 		struct bpf_stack_state *slot = &state->stack[spi - i];
1042 		struct bpf_reg_state *st = &slot->spilled_ptr;
1043 
1044 		if (st->type & PTR_UNTRUSTED)
1045 			return -EPROTO;
1046 		/* only main (first) slot has id set */
1047 		if (i == 0 && !st->id)
1048 			return -EINVAL;
1049 		if (i != 0 && st->id)
1050 			return -EINVAL;
1051 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1052 			return -EINVAL;
1053 
1054 		for (j = 0; j < BPF_REG_SIZE; j++)
1055 			if (slot->slot_type[j] != STACK_ITER)
1056 				return -EINVAL;
1057 	}
1058 
1059 	return 0;
1060 }
1061 
1062 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1063 static int release_irq_state(struct bpf_verifier_state *state, int id);
1064 
1065 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1066 				     struct bpf_kfunc_call_arg_meta *meta,
1067 				     struct bpf_reg_state *reg, int insn_idx,
1068 				     int kfunc_class)
1069 {
1070 	struct bpf_func_state *state = bpf_func(env, reg);
1071 	struct bpf_stack_state *slot;
1072 	struct bpf_reg_state *st;
1073 	int spi, i, id;
1074 
1075 	spi = irq_flag_get_spi(env, reg);
1076 	if (spi < 0)
1077 		return spi;
1078 
1079 	id = acquire_irq_state(env, insn_idx);
1080 	if (id < 0)
1081 		return id;
1082 
1083 	slot = &state->stack[spi];
1084 	st = &slot->spilled_ptr;
1085 
1086 	__mark_reg_known_zero(st);
1087 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1088 	st->id = id;
1089 	st->irq.kfunc_class = kfunc_class;
1090 
1091 	for (i = 0; i < BPF_REG_SIZE; i++)
1092 		slot->slot_type[i] = STACK_IRQ_FLAG;
1093 
1094 	mark_stack_slot_scratched(env, spi);
1095 	return 0;
1096 }
1097 
1098 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1099 				      int kfunc_class)
1100 {
1101 	struct bpf_func_state *state = bpf_func(env, reg);
1102 	struct bpf_stack_state *slot;
1103 	struct bpf_reg_state *st;
1104 	int spi, i, err;
1105 
1106 	spi = irq_flag_get_spi(env, reg);
1107 	if (spi < 0)
1108 		return spi;
1109 
1110 	slot = &state->stack[spi];
1111 	st = &slot->spilled_ptr;
1112 
1113 	if (st->irq.kfunc_class != kfunc_class) {
1114 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1115 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1116 
1117 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1118 			flag_kfunc, used_kfunc);
1119 		return -EINVAL;
1120 	}
1121 
1122 	err = release_irq_state(env->cur_state, st->id);
1123 	WARN_ON_ONCE(err && err != -EACCES);
1124 	if (err) {
1125 		int insn_idx = 0;
1126 
1127 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1128 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1129 				insn_idx = env->cur_state->refs[i].insn_idx;
1130 				break;
1131 			}
1132 		}
1133 
1134 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1135 			env->cur_state->active_irq_id, insn_idx);
1136 		return err;
1137 	}
1138 
1139 	bpf_mark_reg_not_init(env, st);
1140 
1141 	for (i = 0; i < BPF_REG_SIZE; i++)
1142 		slot->slot_type[i] = STACK_INVALID;
1143 
1144 	mark_stack_slot_scratched(env, spi);
1145 	return 0;
1146 }
1147 
1148 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1149 {
1150 	struct bpf_func_state *state = bpf_func(env, reg);
1151 	struct bpf_stack_state *slot;
1152 	int spi, i;
1153 
1154 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1155 	 * will do check_mem_access to check and update stack bounds later, so
1156 	 * return true for that case.
1157 	 */
1158 	spi = irq_flag_get_spi(env, reg);
1159 	if (spi == -ERANGE)
1160 		return true;
1161 	if (spi < 0)
1162 		return false;
1163 
1164 	slot = &state->stack[spi];
1165 
1166 	for (i = 0; i < BPF_REG_SIZE; i++)
1167 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1168 			return false;
1169 	return true;
1170 }
1171 
1172 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1173 {
1174 	struct bpf_func_state *state = bpf_func(env, reg);
1175 	struct bpf_stack_state *slot;
1176 	struct bpf_reg_state *st;
1177 	int spi, i;
1178 
1179 	spi = irq_flag_get_spi(env, reg);
1180 	if (spi < 0)
1181 		return -EINVAL;
1182 
1183 	slot = &state->stack[spi];
1184 	st = &slot->spilled_ptr;
1185 
1186 	if (!st->id)
1187 		return -EINVAL;
1188 
1189 	for (i = 0; i < BPF_REG_SIZE; i++)
1190 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1191 			return -EINVAL;
1192 	return 0;
1193 }
1194 
1195 /* Check if given stack slot is "special":
1196  *   - spilled register state (STACK_SPILL);
1197  *   - dynptr state (STACK_DYNPTR);
1198  *   - iter state (STACK_ITER).
1199  *   - irq flag state (STACK_IRQ_FLAG)
1200  */
1201 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1202 {
1203 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1204 
1205 	switch (type) {
1206 	case STACK_SPILL:
1207 	case STACK_DYNPTR:
1208 	case STACK_ITER:
1209 	case STACK_IRQ_FLAG:
1210 		return true;
1211 	case STACK_INVALID:
1212 	case STACK_POISON:
1213 	case STACK_MISC:
1214 	case STACK_ZERO:
1215 		return false;
1216 	default:
1217 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1218 		return true;
1219 	}
1220 }
1221 
1222 /* The reg state of a pointer or a bounded scalar was saved when
1223  * it was spilled to the stack.
1224  */
1225 
1226 /*
1227  * Mark stack slot as STACK_MISC, unless it is already:
1228  * - STACK_INVALID, in which case they are equivalent.
1229  * - STACK_ZERO, in which case we preserve more precise STACK_ZERO.
1230  * - STACK_POISON, which truly forbids access to the slot.
1231  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1232  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1233  * unnecessary as both are considered equivalent when loading data and pruning,
1234  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1235  * slots.
1236  */
1237 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1238 {
1239 	if (*stype == STACK_ZERO)
1240 		return;
1241 	if (*stype == STACK_INVALID || *stype == STACK_POISON)
1242 		return;
1243 	*stype = STACK_MISC;
1244 }
1245 
1246 static void scrub_spilled_slot(u8 *stype)
1247 {
1248 	if (*stype != STACK_INVALID && *stype != STACK_POISON)
1249 		*stype = STACK_MISC;
1250 }
1251 
1252 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1253  * small to hold src. This is different from krealloc since we don't want to preserve
1254  * the contents of dst.
1255  *
1256  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1257  * not be allocated.
1258  */
1259 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1260 {
1261 	size_t alloc_bytes;
1262 	void *orig = dst;
1263 	size_t bytes;
1264 
1265 	if (ZERO_OR_NULL_PTR(src))
1266 		goto out;
1267 
1268 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1269 		return NULL;
1270 
1271 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1272 	dst = krealloc(orig, alloc_bytes, flags);
1273 	if (!dst) {
1274 		kfree(orig);
1275 		return NULL;
1276 	}
1277 
1278 	memcpy(dst, src, bytes);
1279 out:
1280 	return dst ? dst : ZERO_SIZE_PTR;
1281 }
1282 
1283 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1284  * small to hold new_n items. new items are zeroed out if the array grows.
1285  *
1286  * Contrary to krealloc_array, does not free arr if new_n is zero.
1287  */
1288 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1289 {
1290 	size_t alloc_size;
1291 	void *new_arr;
1292 
1293 	if (!new_n || old_n == new_n)
1294 		goto out;
1295 
1296 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1297 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1298 	if (!new_arr) {
1299 		kfree(arr);
1300 		return NULL;
1301 	}
1302 	arr = new_arr;
1303 
1304 	if (new_n > old_n)
1305 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1306 
1307 out:
1308 	return arr ? arr : ZERO_SIZE_PTR;
1309 }
1310 
1311 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1312 {
1313 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1314 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1315 	if (!dst->refs)
1316 		return -ENOMEM;
1317 
1318 	dst->acquired_refs = src->acquired_refs;
1319 	dst->active_locks = src->active_locks;
1320 	dst->active_preempt_locks = src->active_preempt_locks;
1321 	dst->active_rcu_locks = src->active_rcu_locks;
1322 	dst->active_irq_id = src->active_irq_id;
1323 	dst->active_lock_id = src->active_lock_id;
1324 	dst->active_lock_ptr = src->active_lock_ptr;
1325 	return 0;
1326 }
1327 
1328 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1329 {
1330 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1331 
1332 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1333 				GFP_KERNEL_ACCOUNT);
1334 	if (!dst->stack)
1335 		return -ENOMEM;
1336 
1337 	dst->allocated_stack = src->allocated_stack;
1338 
1339 	/* copy stack args state */
1340 	n = src->out_stack_arg_cnt;
1341 	if (n) {
1342 		dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n,
1343 						 sizeof(struct bpf_reg_state),
1344 						 GFP_KERNEL_ACCOUNT);
1345 		if (!dst->stack_arg_regs)
1346 			return -ENOMEM;
1347 	}
1348 
1349 	dst->out_stack_arg_cnt = src->out_stack_arg_cnt;
1350 	return 0;
1351 }
1352 
1353 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1354 {
1355 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1356 				    sizeof(struct bpf_reference_state));
1357 	if (!state->refs)
1358 		return -ENOMEM;
1359 
1360 	state->acquired_refs = n;
1361 	return 0;
1362 }
1363 
1364 /* Possibly update state->allocated_stack to be at least size bytes. Also
1365  * possibly update the function's high-water mark in its bpf_subprog_info.
1366  */
1367 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1368 {
1369 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1370 
1371 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1372 	size = round_up(size, BPF_REG_SIZE);
1373 	n = size / BPF_REG_SIZE;
1374 
1375 	if (old_n >= n)
1376 		return 0;
1377 
1378 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1379 	if (!state->stack)
1380 		return -ENOMEM;
1381 
1382 	state->allocated_stack = size;
1383 
1384 	/* update known max for given subprogram */
1385 	if (env->subprog_info[state->subprogno].stack_depth < size)
1386 		env->subprog_info[state->subprogno].stack_depth = size;
1387 
1388 	return 0;
1389 }
1390 
1391 static int grow_stack_arg_slots(struct bpf_verifier_env *env,
1392 				struct bpf_func_state *state, int cnt)
1393 {
1394 	size_t old_n = state->out_stack_arg_cnt;
1395 
1396 	if (old_n >= cnt)
1397 		return 0;
1398 
1399 	state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt,
1400 					      sizeof(struct bpf_reg_state));
1401 	if (!state->stack_arg_regs)
1402 		return -ENOMEM;
1403 
1404 	state->out_stack_arg_cnt = cnt;
1405 	return 0;
1406 }
1407 
1408 /* Acquire a pointer id from the env and update the state->refs to include
1409  * this new pointer reference.
1410  * On success, returns a valid pointer id to associate with the register
1411  * On failure, returns a negative errno.
1412  */
1413 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1414 {
1415 	struct bpf_verifier_state *state = env->cur_state;
1416 	int new_ofs = state->acquired_refs;
1417 	int err;
1418 
1419 	err = resize_reference_state(state, state->acquired_refs + 1);
1420 	if (err)
1421 		return NULL;
1422 	state->refs[new_ofs].insn_idx = insn_idx;
1423 
1424 	return &state->refs[new_ofs];
1425 }
1426 
1427 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id)
1428 {
1429 	struct bpf_reference_state *s;
1430 
1431 	s = acquire_reference_state(env, insn_idx);
1432 	if (!s)
1433 		return -ENOMEM;
1434 	s->type = REF_TYPE_PTR;
1435 	s->id = ++env->id_gen;
1436 	s->parent_id = parent_id;
1437 	return s->id;
1438 }
1439 
1440 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1441 			      int id, void *ptr)
1442 {
1443 	struct bpf_verifier_state *state = env->cur_state;
1444 	struct bpf_reference_state *s;
1445 
1446 	s = acquire_reference_state(env, insn_idx);
1447 	if (!s)
1448 		return -ENOMEM;
1449 	s->type = type;
1450 	s->id = id;
1451 	s->ptr = ptr;
1452 
1453 	state->active_locks++;
1454 	state->active_lock_id = id;
1455 	state->active_lock_ptr = ptr;
1456 	return 0;
1457 }
1458 
1459 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1460 {
1461 	struct bpf_verifier_state *state = env->cur_state;
1462 	struct bpf_reference_state *s;
1463 
1464 	s = acquire_reference_state(env, insn_idx);
1465 	if (!s)
1466 		return -ENOMEM;
1467 	s->type = REF_TYPE_IRQ;
1468 	s->id = ++env->id_gen;
1469 
1470 	state->active_irq_id = s->id;
1471 	return s->id;
1472 }
1473 
1474 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1475 {
1476 	int last_idx;
1477 	size_t rem;
1478 
1479 	/* IRQ state requires the relative ordering of elements remaining the
1480 	 * same, since it relies on the refs array to behave as a stack, so that
1481 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1482 	 * the array instead of swapping the final element into the deleted idx.
1483 	 */
1484 	last_idx = state->acquired_refs - 1;
1485 	rem = state->acquired_refs - idx - 1;
1486 	if (last_idx && idx != last_idx)
1487 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1488 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1489 	state->acquired_refs--;
1490 	return;
1491 }
1492 
1493 static bool find_reference_state(struct bpf_verifier_state *state, int id)
1494 {
1495 	int i;
1496 
1497 	for (i = 0; i < state->acquired_refs; i++) {
1498 		if (state->refs[i].type != REF_TYPE_PTR)
1499 			continue;
1500 		if (state->refs[i].id == id)
1501 			return true;
1502 	}
1503 
1504 	return false;
1505 }
1506 
1507 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
1508 {
1509 	return find_reference_state(env->cur_state, reg->id);
1510 }
1511 
1512 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1513 {
1514 	void *prev_ptr = NULL;
1515 	u32 prev_id = 0;
1516 	int i;
1517 
1518 	for (i = 0; i < state->acquired_refs; i++) {
1519 		if (state->refs[i].type == type && state->refs[i].id == id &&
1520 		    state->refs[i].ptr == ptr) {
1521 			release_reference_state(state, i);
1522 			state->active_locks--;
1523 			/* Reassign active lock (id, ptr). */
1524 			state->active_lock_id = prev_id;
1525 			state->active_lock_ptr = prev_ptr;
1526 			return 0;
1527 		}
1528 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1529 			prev_id = state->refs[i].id;
1530 			prev_ptr = state->refs[i].ptr;
1531 		}
1532 	}
1533 	return -EINVAL;
1534 }
1535 
1536 static int release_irq_state(struct bpf_verifier_state *state, int id)
1537 {
1538 	u32 prev_id = 0;
1539 	int i;
1540 
1541 	if (id != state->active_irq_id)
1542 		return -EACCES;
1543 
1544 	for (i = 0; i < state->acquired_refs; i++) {
1545 		if (state->refs[i].type != REF_TYPE_IRQ)
1546 			continue;
1547 		if (state->refs[i].id == id) {
1548 			release_reference_state(state, i);
1549 			state->active_irq_id = prev_id;
1550 			return 0;
1551 		} else {
1552 			prev_id = state->refs[i].id;
1553 		}
1554 	}
1555 	return -EINVAL;
1556 }
1557 
1558 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1559 						   int id, void *ptr)
1560 {
1561 	int i;
1562 
1563 	for (i = 0; i < state->acquired_refs; i++) {
1564 		struct bpf_reference_state *s = &state->refs[i];
1565 
1566 		if (!(s->type & type))
1567 			continue;
1568 
1569 		if (s->id == id && s->ptr == ptr)
1570 			return s;
1571 	}
1572 	return NULL;
1573 }
1574 
1575 static void free_func_state(struct bpf_func_state *state)
1576 {
1577 	if (!state)
1578 		return;
1579 	kfree(state->stack_arg_regs);
1580 	kfree(state->stack);
1581 	kfree(state);
1582 }
1583 
1584 void bpf_clear_jmp_history(struct bpf_verifier_state *state)
1585 {
1586 	kfree(state->jmp_history);
1587 	state->jmp_history = NULL;
1588 	state->jmp_history_cnt = 0;
1589 }
1590 
1591 void bpf_free_verifier_state(struct bpf_verifier_state *state,
1592 			    bool free_self)
1593 {
1594 	int i;
1595 
1596 	for (i = 0; i <= state->curframe; i++) {
1597 		free_func_state(state->frame[i]);
1598 		state->frame[i] = NULL;
1599 	}
1600 	kfree(state->refs);
1601 	bpf_clear_jmp_history(state);
1602 	if (free_self)
1603 		kfree(state);
1604 }
1605 
1606 /* copy verifier state from src to dst growing dst stack space
1607  * when necessary to accommodate larger src stack
1608  */
1609 static int copy_func_state(struct bpf_func_state *dst,
1610 			   const struct bpf_func_state *src)
1611 {
1612 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1613 	return copy_stack_state(dst, src);
1614 }
1615 
1616 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1617 			   const struct bpf_verifier_state *src)
1618 {
1619 	struct bpf_func_state *dst;
1620 	int i, err;
1621 
1622 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1623 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1624 					  GFP_KERNEL_ACCOUNT);
1625 	if (!dst_state->jmp_history)
1626 		return -ENOMEM;
1627 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1628 
1629 	/* if dst has more stack frames then src frame, free them, this is also
1630 	 * necessary in case of exceptional exits using bpf_throw.
1631 	 */
1632 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1633 		free_func_state(dst_state->frame[i]);
1634 		dst_state->frame[i] = NULL;
1635 	}
1636 	err = copy_reference_state(dst_state, src);
1637 	if (err)
1638 		return err;
1639 	dst_state->speculative = src->speculative;
1640 	dst_state->in_sleepable = src->in_sleepable;
1641 	dst_state->curframe = src->curframe;
1642 	dst_state->branches = src->branches;
1643 	dst_state->parent = src->parent;
1644 	dst_state->first_insn_idx = src->first_insn_idx;
1645 	dst_state->last_insn_idx = src->last_insn_idx;
1646 	dst_state->dfs_depth = src->dfs_depth;
1647 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1648 	dst_state->may_goto_depth = src->may_goto_depth;
1649 	dst_state->equal_state = src->equal_state;
1650 	for (i = 0; i <= src->curframe; i++) {
1651 		dst = dst_state->frame[i];
1652 		if (!dst) {
1653 			dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT);
1654 			if (!dst)
1655 				return -ENOMEM;
1656 			dst_state->frame[i] = dst;
1657 		}
1658 		err = copy_func_state(dst, src->frame[i]);
1659 		if (err)
1660 			return err;
1661 	}
1662 	return 0;
1663 }
1664 
1665 static u32 state_htab_size(struct bpf_verifier_env *env)
1666 {
1667 	return env->prog->len;
1668 }
1669 
1670 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)
1671 {
1672 	struct bpf_verifier_state *cur = env->cur_state;
1673 	struct bpf_func_state *state = cur->frame[cur->curframe];
1674 
1675 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1676 }
1677 
1678 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1679 {
1680 	int fr;
1681 
1682 	if (a->curframe != b->curframe)
1683 		return false;
1684 
1685 	for (fr = a->curframe; fr >= 0; fr--)
1686 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1687 			return false;
1688 
1689 	return true;
1690 }
1691 
1692 
1693 void bpf_free_backedges(struct bpf_scc_visit *visit)
1694 {
1695 	struct bpf_scc_backedge *backedge, *next;
1696 
1697 	for (backedge = visit->backedges; backedge; backedge = next) {
1698 		bpf_free_verifier_state(&backedge->state, false);
1699 		next = backedge->next;
1700 		kfree(backedge);
1701 	}
1702 	visit->backedges = NULL;
1703 }
1704 
1705 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1706 		     int *insn_idx, bool pop_log)
1707 {
1708 	struct bpf_verifier_state *cur = env->cur_state;
1709 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1710 	int err;
1711 
1712 	if (env->head == NULL)
1713 		return -ENOENT;
1714 
1715 	if (cur) {
1716 		err = bpf_copy_verifier_state(cur, &head->st);
1717 		if (err)
1718 			return err;
1719 	}
1720 	if (pop_log)
1721 		bpf_vlog_reset(&env->log, head->log_pos);
1722 	if (insn_idx)
1723 		*insn_idx = head->insn_idx;
1724 	if (prev_insn_idx)
1725 		*prev_insn_idx = head->prev_insn_idx;
1726 	elem = head->next;
1727 	bpf_free_verifier_state(&head->st, false);
1728 	kfree(head);
1729 	env->head = elem;
1730 	env->stack_size--;
1731 	return 0;
1732 }
1733 
1734 static bool error_recoverable_with_nospec(int err)
1735 {
1736 	/* Should only return true for non-fatal errors that are allowed to
1737 	 * occur during speculative verification. For these we can insert a
1738 	 * nospec and the program might still be accepted. Do not include
1739 	 * something like ENOMEM because it is likely to re-occur for the next
1740 	 * architectural path once it has been recovered-from in all speculative
1741 	 * paths.
1742 	 */
1743 	return err == -EPERM || err == -EACCES || err == -EINVAL;
1744 }
1745 
1746 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1747 					     int insn_idx, int prev_insn_idx,
1748 					     bool speculative)
1749 {
1750 	struct bpf_verifier_state *cur = env->cur_state;
1751 	struct bpf_verifier_stack_elem *elem;
1752 	int err;
1753 
1754 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
1755 	if (!elem)
1756 		return ERR_PTR(-ENOMEM);
1757 
1758 	elem->insn_idx = insn_idx;
1759 	elem->prev_insn_idx = prev_insn_idx;
1760 	elem->next = env->head;
1761 	elem->log_pos = env->log.end_pos;
1762 	env->head = elem;
1763 	env->stack_size++;
1764 	err = bpf_copy_verifier_state(&elem->st, cur);
1765 	if (err)
1766 		return ERR_PTR(-ENOMEM);
1767 	elem->st.speculative |= speculative;
1768 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1769 		verbose(env, "The sequence of %d jumps is too complex.\n",
1770 			env->stack_size);
1771 		return ERR_PTR(-E2BIG);
1772 	}
1773 	if (elem->st.parent) {
1774 		++elem->st.parent->branches;
1775 		/* WARN_ON(branches > 2) technically makes sense here,
1776 		 * but
1777 		 * 1. speculative states will bump 'branches' for non-branch
1778 		 * instructions
1779 		 * 2. is_state_visited() heuristics may decide not to create
1780 		 * a new state for a sequence of branches and all such current
1781 		 * and cloned states will be pointing to a single parent state
1782 		 * which might have large 'branches' count.
1783 		 */
1784 	}
1785 	return &elem->st;
1786 }
1787 
1788 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
1789 {
1790 	char *buf = env->tmp_arg_name;
1791 	int len = sizeof(env->tmp_arg_name);
1792 	int arg, regno = reg_from_argno(argno);
1793 
1794 	if (regno >= 0) {
1795 		snprintf(buf, len, "R%d", regno);
1796 	} else {
1797 		arg = arg_from_argno(argno);
1798 		snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE);
1799 	}
1800 
1801 	return buf;
1802 }
1803 
1804 static const int caller_saved[CALLER_SAVED_REGS] = {
1805 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1806 };
1807 
1808 /* This helper doesn't clear reg->id */
1809 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1810 {
1811 	reg->var_off = tnum_const(imm);
1812 	reg->r64 = cnum64_from_urange(imm, imm);
1813 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1814 }
1815 
1816 /* Mark the unknown part of a register (variable offset or scalar value) as
1817  * known to have the value @imm.
1818  */
1819 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1820 {
1821 	/* Clear off and union(map_ptr, range) */
1822 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1823 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1824 	reg->id = 0;
1825 	reg->parent_id = 0;
1826 	___mark_reg_known(reg, imm);
1827 }
1828 
1829 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1830 {
1831 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1832 	reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
1833 }
1834 
1835 /* Mark the 'variable offset' part of a register as zero.  This should be
1836  * used only on registers holding a pointer type.
1837  */
1838 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1839 {
1840 	__mark_reg_known(reg, 0);
1841 }
1842 
1843 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1844 {
1845 	__mark_reg_known(reg, 0);
1846 	reg->type = SCALAR_VALUE;
1847 	/* all scalars are assumed imprecise initially (unless unprivileged,
1848 	 * in which case everything is forced to be precise)
1849 	 */
1850 	reg->precise = !env->bpf_capable;
1851 }
1852 
1853 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1854 				struct bpf_reg_state *regs, u32 regno)
1855 {
1856 	__mark_reg_known_zero(regs + regno);
1857 }
1858 
1859 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1860 			      bool first_slot, int id, int parent_id)
1861 {
1862 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1863 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1864 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1865 	 */
1866 	__mark_reg_known_zero(reg);
1867 	reg->type = CONST_PTR_TO_DYNPTR;
1868 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1869 	reg->id = id;
1870 	reg->parent_id = parent_id;
1871 	reg->dynptr.type = type;
1872 	reg->dynptr.first_slot = first_slot;
1873 }
1874 
1875 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1876 {
1877 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1878 		const struct bpf_map *map = reg->map_ptr;
1879 
1880 		if (map->inner_map_meta) {
1881 			reg->type = CONST_PTR_TO_MAP;
1882 			reg->map_ptr = map->inner_map_meta;
1883 			/* transfer reg's id which is unique for every map_lookup_elem
1884 			 * as UID of the inner map.
1885 			 */
1886 			if (btf_record_has_field(map->inner_map_meta->record,
1887 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
1888 				reg->map_uid = reg->id;
1889 			}
1890 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1891 			reg->type = PTR_TO_XDP_SOCK;
1892 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1893 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1894 			reg->type = PTR_TO_SOCKET;
1895 		} else {
1896 			reg->type = PTR_TO_MAP_VALUE;
1897 		}
1898 		return;
1899 	}
1900 
1901 	reg->type &= ~PTR_MAYBE_NULL;
1902 }
1903 
1904 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1905 				struct btf_field_graph_root *ds_head)
1906 {
1907 	__mark_reg_known(&regs[regno], ds_head->node_offset);
1908 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1909 	regs[regno].btf = ds_head->btf;
1910 	regs[regno].btf_id = ds_head->value_btf_id;
1911 }
1912 
1913 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1914 {
1915 	return type_is_pkt_pointer(reg->type);
1916 }
1917 
1918 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1919 {
1920 	return reg_is_pkt_pointer(reg) ||
1921 	       reg->type == PTR_TO_PACKET_END;
1922 }
1923 
1924 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1925 {
1926 	return base_type(reg->type) == PTR_TO_MEM &&
1927 	       (reg->type &
1928 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
1929 }
1930 
1931 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1932 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1933 				    enum bpf_reg_type which)
1934 {
1935 	/* The register can already have a range from prior markings.
1936 	 * This is fine as long as it hasn't been advanced from its
1937 	 * origin.
1938 	 */
1939 	return reg->type == which &&
1940 	       reg->id == 0 &&
1941 	       tnum_equals_const(reg->var_off, 0);
1942 }
1943 
1944 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1945 {
1946 	reg->r32 = CNUM32_UNBOUNDED;
1947 }
1948 
1949 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1950 {
1951 	reg->r64 = CNUM64_UNBOUNDED;
1952 }
1953 
1954 /* Reset the min/max bounds of a register */
1955 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1956 {
1957 	__mark_reg64_unbounded(reg);
1958 	__mark_reg32_unbounded(reg);
1959 }
1960 
1961 static void reset_reg64_and_tnum(struct bpf_reg_state *reg)
1962 {
1963 	__mark_reg64_unbounded(reg);
1964 	reg->var_off = tnum_unknown;
1965 }
1966 
1967 static void reset_reg32_and_tnum(struct bpf_reg_state *reg)
1968 {
1969 	__mark_reg32_unbounded(reg);
1970 	reg->var_off = tnum_unknown;
1971 }
1972 
1973 static struct cnum32 cnum32_from_tnum(struct tnum tnum)
1974 {
1975 	tnum = tnum_subreg(tnum);
1976 	if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN))
1977 		/* min signed is max(sign bit) | min(other bits) */
1978 		/* max signed is min(sign bit) | max(other bits) */
1979 		return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN),
1980 					  tnum.value | (tnum.mask & S32_MAX));
1981 	else
1982 		return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask));
1983 }
1984 
1985 static struct cnum64 cnum64_from_tnum(struct tnum tnum)
1986 {
1987 	if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN))
1988 		/* min signed is max(sign bit) | min(other bits) */
1989 		/* max signed is min(sign bit) | max(other bits) */
1990 		return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN),
1991 					  tnum.value | (tnum.mask & S64_MAX));
1992 	else
1993 		return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask));
1994 }
1995 
1996 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1997 {
1998 	cnum32_intersect_with(&reg->r32, cnum32_from_tnum(reg->var_off));
1999 }
2000 
2001 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2002 {
2003 	u64 tnum_next, tmax;
2004 	bool umin_in_tnum;
2005 
2006 	cnum64_intersect_with(&reg->r64, cnum64_from_tnum(reg->var_off));
2007 
2008 	/* Check if u64 and tnum overlap in a single value */
2009 	tnum_next = tnum_step(reg->var_off, reg_umin(reg));
2010 	umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value;
2011 	tmax = reg->var_off.value | reg->var_off.mask;
2012 	if (umin_in_tnum && tnum_next > reg_umax(reg)) {
2013 		/* The u64 range and the tnum only overlap in umin.
2014 		 * u64:  ---[xxxxxx]-----
2015 		 * tnum: --xx----------x-
2016 		 */
2017 		___mark_reg_known(reg, reg_umin(reg));
2018 	} else if (!umin_in_tnum && tnum_next == tmax) {
2019 		/* The u64 range and the tnum only overlap in the maximum value
2020 		 * represented by the tnum, called tmax.
2021 		 * u64:  ---[xxxxxx]-----
2022 		 * tnum: xx-----x--------
2023 		 */
2024 		___mark_reg_known(reg, tmax);
2025 	} else if (!umin_in_tnum && tnum_next <= reg_umax(reg) &&
2026 		   tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) {
2027 		/* The u64 range and the tnum only overlap in between umin
2028 		 * (excluded) and umax.
2029 		 * u64:  ---[xxxxxx]-----
2030 		 * tnum: xx----x-------x-
2031 		 */
2032 		___mark_reg_known(reg, tnum_next);
2033 	}
2034 }
2035 
2036 static void __update_reg_bounds(struct bpf_reg_state *reg)
2037 {
2038 	__update_reg32_bounds(reg);
2039 	__update_reg64_bounds(reg);
2040 }
2041 
2042 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg)
2043 {
2044 	cnum32_intersect_with(&reg->r32, cnum32_from_cnum64(reg->r64));
2045 }
2046 
2047 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
2048 {
2049 	reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
2050 }
2051 
2052 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2053 {
2054 	deduce_bounds_32_from_64(reg);
2055 	deduce_bounds_64_from_32(reg);
2056 }
2057 
2058 /* Attempts to improve var_off based on unsigned min/max information */
2059 static void __reg_bound_offset(struct bpf_reg_state *reg)
2060 {
2061 	struct tnum var64_off = tnum_intersect(reg->var_off,
2062 					       tnum_range(reg_umin(reg),
2063 							  reg_umax(reg)));
2064 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2065 					       tnum_range(reg_u32_min(reg),
2066 							  reg_u32_max(reg)));
2067 
2068 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2069 }
2070 
2071 static bool range_bounds_violation(struct bpf_reg_state *reg);
2072 
2073 static void reg_bounds_sync(struct bpf_reg_state *reg)
2074 {
2075 	/* If the input reg_state is invalid, we can exit early */
2076 	if (range_bounds_violation(reg))
2077 		return;
2078 	/* We might have learned new bounds from the var_off. */
2079 	__update_reg_bounds(reg);
2080 	/* We might have learned something about the sign bit. */
2081 	__reg_deduce_bounds(reg);
2082 	__reg_deduce_bounds(reg);
2083 	/* We might have learned some bits from the bounds. */
2084 	__reg_bound_offset(reg);
2085 	/* Intersecting with the old var_off might have improved our bounds
2086 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2087 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2088 	 */
2089 	__update_reg_bounds(reg);
2090 }
2091 
2092 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg)
2093 {
2094 	if (!tnum_is_const(reg->var_off))
2095 		return false;
2096 
2097 	return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value;
2098 }
2099 
2100 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg)
2101 {
2102 	if (!tnum_subreg_is_const(reg->var_off))
2103 		return false;
2104 
2105 	return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value;
2106 }
2107 
2108 static bool range_bounds_violation(struct bpf_reg_state *reg)
2109 {
2110 	return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64);
2111 }
2112 
2113 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2114 				   struct bpf_reg_state *reg, const char *ctx)
2115 {
2116 	const char *msg;
2117 
2118 	if (range_bounds_violation(reg)) {
2119 		msg = "range bounds violation";
2120 		goto out;
2121 	}
2122 
2123 	if (const_tnum_range_mismatch(reg)) {
2124 		msg = "const tnum out of sync with range bounds";
2125 		goto out;
2126 	}
2127 
2128 	if (const_tnum_range_mismatch_32(reg)) {
2129 		msg = "const subreg tnum out of sync with range bounds";
2130 		goto out;
2131 	}
2132 
2133 	return 0;
2134 out:
2135 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} "
2136 		     "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)",
2137 		     ctx, msg,
2138 		     reg->r64.base, reg->r64.size,
2139 		     reg->r32.base, reg->r32.size,
2140 		     reg->var_off.value, reg->var_off.mask);
2141 	if (env->test_reg_invariants)
2142 		return -EFAULT;
2143 	__mark_reg_unbounded(reg);
2144 	return 0;
2145 }
2146 
2147 /* Mark a register as having a completely unknown (scalar) value. */
2148 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2149 {
2150 	s32 subreg_def = reg->subreg_def;
2151 
2152 	memset(reg, 0, sizeof(*reg));
2153 	reg->type = SCALAR_VALUE;
2154 	reg->var_off = tnum_unknown;
2155 	reg->subreg_def = subreg_def;
2156 	__mark_reg_unbounded(reg);
2157 }
2158 
2159 /* Mark a register as having a completely unknown (scalar) value,
2160  * initialize .precise as true when not bpf capable.
2161  */
2162 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2163 			       struct bpf_reg_state *reg)
2164 {
2165 	bpf_mark_reg_unknown_imprecise(reg);
2166 	reg->precise = !env->bpf_capable;
2167 }
2168 
2169 static void mark_reg_unknown(struct bpf_verifier_env *env,
2170 			     struct bpf_reg_state *regs, u32 regno)
2171 {
2172 	__mark_reg_unknown(env, regs + regno);
2173 }
2174 
2175 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2176 				struct bpf_reg_state *regs,
2177 				u32 regno,
2178 				s32 s32_min,
2179 				s32 s32_max)
2180 {
2181 	struct bpf_reg_state *reg = regs + regno;
2182 
2183 	reg_set_srange32(reg,
2184 			 max_t(s32, reg_s32_min(reg), s32_min),
2185 			 min_t(s32, reg_s32_max(reg), s32_max));
2186 	reg_set_srange64(reg,
2187 			 max_t(s64, reg_smin(reg), s32_min),
2188 			 min_t(s64, reg_smax(reg), s32_max));
2189 
2190 	reg_bounds_sync(reg);
2191 
2192 	return reg_bounds_sanity_check(env, reg, "s32_range");
2193 }
2194 
2195 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
2196 			   struct bpf_reg_state *reg)
2197 {
2198 	__mark_reg_unknown(env, reg);
2199 	reg->type = NOT_INIT;
2200 }
2201 
2202 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2203 			   struct bpf_reg_state *regs, u32 regno,
2204 			   enum bpf_reg_type reg_type,
2205 			   struct btf *btf, u32 btf_id,
2206 			   enum bpf_type_flag flag)
2207 {
2208 	switch (reg_type) {
2209 	case SCALAR_VALUE:
2210 		mark_reg_unknown(env, regs, regno);
2211 		return 0;
2212 	case PTR_TO_BTF_ID:
2213 		mark_reg_known_zero(env, regs, regno);
2214 		regs[regno].type = PTR_TO_BTF_ID | flag;
2215 		regs[regno].btf = btf;
2216 		regs[regno].btf_id = btf_id;
2217 		if (type_may_be_null(flag))
2218 			regs[regno].id = ++env->id_gen;
2219 		return 0;
2220 	case PTR_TO_MEM:
2221 		mark_reg_known_zero(env, regs, regno);
2222 		regs[regno].type = PTR_TO_MEM | flag;
2223 		regs[regno].mem_size = 0;
2224 		return 0;
2225 	default:
2226 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2227 		return -EFAULT;
2228 	}
2229 }
2230 
2231 #define DEF_NOT_SUBREG	(0)
2232 static void init_reg_state(struct bpf_verifier_env *env,
2233 			   struct bpf_func_state *state)
2234 {
2235 	struct bpf_reg_state *regs = state->regs;
2236 	int i;
2237 
2238 	for (i = 0; i < MAX_BPF_REG; i++) {
2239 		bpf_mark_reg_not_init(env, &regs[i]);
2240 		regs[i].subreg_def = DEF_NOT_SUBREG;
2241 	}
2242 
2243 	/* frame pointer */
2244 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2245 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2246 	regs[BPF_REG_FP].frameno = state->frameno;
2247 }
2248 
2249 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2250 {
2251 	/*
2252 	 * return_32bit is set to false by default and set explicitly
2253 	 * by the caller when necessary.
2254 	 */
2255 	return (struct bpf_retval_range){ minval, maxval, false };
2256 }
2257 
2258 static void init_func_state(struct bpf_verifier_env *env,
2259 			    struct bpf_func_state *state,
2260 			    int callsite, int frameno, int subprogno)
2261 {
2262 	state->callsite = callsite;
2263 	state->frameno = frameno;
2264 	state->subprogno = subprogno;
2265 	state->callback_ret_range = retval_range(0, 0);
2266 	init_reg_state(env, state);
2267 	mark_verifier_state_scratched(env);
2268 }
2269 
2270 /* Similar to push_stack(), but for async callbacks */
2271 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2272 						int insn_idx, int prev_insn_idx,
2273 						int subprog, bool is_sleepable)
2274 {
2275 	struct bpf_verifier_stack_elem *elem;
2276 	struct bpf_func_state *frame;
2277 
2278 	elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT);
2279 	if (!elem)
2280 		return ERR_PTR(-ENOMEM);
2281 
2282 	elem->insn_idx = insn_idx;
2283 	elem->prev_insn_idx = prev_insn_idx;
2284 	elem->next = env->head;
2285 	elem->log_pos = env->log.end_pos;
2286 	env->head = elem;
2287 	env->stack_size++;
2288 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2289 		verbose(env,
2290 			"The sequence of %d jumps is too complex for async cb.\n",
2291 			env->stack_size);
2292 		return ERR_PTR(-E2BIG);
2293 	}
2294 	/* Unlike push_stack() do not bpf_copy_verifier_state().
2295 	 * The caller state doesn't matter.
2296 	 * This is async callback. It starts in a fresh stack.
2297 	 * Initialize it similar to do_check_common().
2298 	 */
2299 	elem->st.branches = 1;
2300 	elem->st.in_sleepable = is_sleepable;
2301 	frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT);
2302 	if (!frame)
2303 		return ERR_PTR(-ENOMEM);
2304 	init_func_state(env, frame,
2305 			BPF_MAIN_FUNC /* callsite */,
2306 			0 /* frameno within this callchain */,
2307 			subprog /* subprog number within this prog */);
2308 	elem->st.frame[0] = frame;
2309 	return &elem->st;
2310 }
2311 
2312 
2313 static int cmp_subprogs(const void *a, const void *b)
2314 {
2315 	return ((struct bpf_subprog_info *)a)->start -
2316 	       ((struct bpf_subprog_info *)b)->start;
2317 }
2318 
2319 /* Find subprogram that contains instruction at 'off' */
2320 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2321 {
2322 	struct bpf_subprog_info *vals = env->subprog_info;
2323 	int l, r, m;
2324 
2325 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2326 		return NULL;
2327 
2328 	l = 0;
2329 	r = env->subprog_cnt - 1;
2330 	while (l < r) {
2331 		m = l + (r - l + 1) / 2;
2332 		if (vals[m].start <= off)
2333 			l = m;
2334 		else
2335 			r = m - 1;
2336 	}
2337 	return &vals[l];
2338 }
2339 
2340 /* Find subprogram that starts exactly at 'off' */
2341 int bpf_find_subprog(struct bpf_verifier_env *env, int off)
2342 {
2343 	struct bpf_subprog_info *p;
2344 
2345 	p = bpf_find_containing_subprog(env, off);
2346 	if (!p || p->start != off)
2347 		return -ENOENT;
2348 	return p - env->subprog_info;
2349 }
2350 
2351 static int add_subprog(struct bpf_verifier_env *env, int off)
2352 {
2353 	int insn_cnt = env->prog->len;
2354 	int ret;
2355 
2356 	if (off >= insn_cnt || off < 0) {
2357 		verbose(env, "call to invalid destination\n");
2358 		return -EINVAL;
2359 	}
2360 	ret = bpf_find_subprog(env, off);
2361 	if (ret >= 0)
2362 		return ret;
2363 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2364 		verbose(env, "too many subprograms\n");
2365 		return -E2BIG;
2366 	}
2367 	/* determine subprog starts. The end is one before the next starts */
2368 	env->subprog_info[env->subprog_cnt++].start = off;
2369 	sort(env->subprog_info, env->subprog_cnt,
2370 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2371 	return env->subprog_cnt - 1;
2372 }
2373 
2374 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2375 {
2376 	struct bpf_prog_aux *aux = env->prog->aux;
2377 	struct btf *btf = aux->btf;
2378 	const struct btf_type *t;
2379 	u32 main_btf_id, id;
2380 	const char *name;
2381 	int ret, i;
2382 
2383 	/* Non-zero func_info_cnt implies valid btf */
2384 	if (!aux->func_info_cnt)
2385 		return 0;
2386 	main_btf_id = aux->func_info[0].type_id;
2387 
2388 	t = btf_type_by_id(btf, main_btf_id);
2389 	if (!t) {
2390 		verbose(env, "invalid btf id for main subprog in func_info\n");
2391 		return -EINVAL;
2392 	}
2393 
2394 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2395 	if (IS_ERR(name)) {
2396 		ret = PTR_ERR(name);
2397 		/* If there is no tag present, there is no exception callback */
2398 		if (ret == -ENOENT)
2399 			ret = 0;
2400 		else if (ret == -EEXIST)
2401 			verbose(env, "multiple exception callback tags for main subprog\n");
2402 		return ret;
2403 	}
2404 
2405 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2406 	if (ret < 0) {
2407 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2408 		return ret;
2409 	}
2410 	id = ret;
2411 	t = btf_type_by_id(btf, id);
2412 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2413 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2414 		return -EINVAL;
2415 	}
2416 	ret = 0;
2417 	for (i = 0; i < aux->func_info_cnt; i++) {
2418 		if (aux->func_info[i].type_id != id)
2419 			continue;
2420 		ret = aux->func_info[i].insn_off;
2421 		/* Further func_info and subprog checks will also happen
2422 		 * later, so assume this is the right insn_off for now.
2423 		 */
2424 		if (!ret) {
2425 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2426 			ret = -EINVAL;
2427 		}
2428 	}
2429 	if (!ret) {
2430 		verbose(env, "exception callback type id not found in func_info\n");
2431 		ret = -EINVAL;
2432 	}
2433 	return ret;
2434 }
2435 
2436 #define MAX_KFUNC_BTFS	256
2437 
2438 struct bpf_kfunc_btf {
2439 	struct btf *btf;
2440 	struct module *module;
2441 	u16 offset;
2442 };
2443 
2444 struct bpf_kfunc_btf_tab {
2445 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2446 	u32 nr_descs;
2447 };
2448 
2449 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2450 {
2451 	const struct bpf_kfunc_desc *d0 = a;
2452 	const struct bpf_kfunc_desc *d1 = b;
2453 
2454 	/* func_id is not greater than BTF_MAX_TYPE */
2455 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2456 }
2457 
2458 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2459 {
2460 	const struct bpf_kfunc_btf *d0 = a;
2461 	const struct bpf_kfunc_btf *d1 = b;
2462 
2463 	return d0->offset - d1->offset;
2464 }
2465 
2466 static struct bpf_kfunc_desc *
2467 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2468 {
2469 	struct bpf_kfunc_desc desc = {
2470 		.func_id = func_id,
2471 		.offset = offset,
2472 	};
2473 	struct bpf_kfunc_desc_tab *tab;
2474 
2475 	tab = prog->aux->kfunc_tab;
2476 	return bsearch(&desc, tab->descs, tab->nr_descs,
2477 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2478 }
2479 
2480 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2481 		       u16 btf_fd_idx, u8 **func_addr)
2482 {
2483 	const struct bpf_kfunc_desc *desc;
2484 
2485 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2486 	if (!desc)
2487 		return -EFAULT;
2488 
2489 	*func_addr = (u8 *)desc->addr;
2490 	return 0;
2491 }
2492 
2493 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2494 					 s16 offset)
2495 {
2496 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2497 	struct bpf_kfunc_btf_tab *tab;
2498 	struct bpf_kfunc_btf *b;
2499 	struct module *mod;
2500 	struct btf *btf;
2501 	int btf_fd;
2502 
2503 	tab = env->prog->aux->kfunc_btf_tab;
2504 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2505 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2506 	if (!b) {
2507 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2508 			verbose(env, "too many different module BTFs\n");
2509 			return ERR_PTR(-E2BIG);
2510 		}
2511 
2512 		if (bpfptr_is_null(env->fd_array)) {
2513 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2514 			return ERR_PTR(-EPROTO);
2515 		}
2516 
2517 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2518 					    offset * sizeof(btf_fd),
2519 					    sizeof(btf_fd)))
2520 			return ERR_PTR(-EFAULT);
2521 
2522 		btf = btf_get_by_fd(btf_fd);
2523 		if (IS_ERR(btf)) {
2524 			verbose(env, "invalid module BTF fd specified\n");
2525 			return btf;
2526 		}
2527 
2528 		if (!btf_is_module(btf)) {
2529 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2530 			btf_put(btf);
2531 			return ERR_PTR(-EINVAL);
2532 		}
2533 
2534 		mod = btf_try_get_module(btf);
2535 		if (!mod) {
2536 			btf_put(btf);
2537 			return ERR_PTR(-ENXIO);
2538 		}
2539 
2540 		b = &tab->descs[tab->nr_descs++];
2541 		b->btf = btf;
2542 		b->module = mod;
2543 		b->offset = offset;
2544 
2545 		/* sort() reorders entries by value, so b may no longer point
2546 		 * to the right entry after this
2547 		 */
2548 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2549 		     kfunc_btf_cmp_by_off, NULL);
2550 	} else {
2551 		btf = b->btf;
2552 	}
2553 
2554 	return btf;
2555 }
2556 
2557 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2558 {
2559 	if (!tab)
2560 		return;
2561 
2562 	while (tab->nr_descs--) {
2563 		module_put(tab->descs[tab->nr_descs].module);
2564 		btf_put(tab->descs[tab->nr_descs].btf);
2565 	}
2566 	kfree(tab);
2567 }
2568 
2569 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2570 {
2571 	if (offset) {
2572 		if (offset < 0) {
2573 			/* In the future, this can be allowed to increase limit
2574 			 * of fd index into fd_array, interpreted as u16.
2575 			 */
2576 			verbose(env, "negative offset disallowed for kernel module function call\n");
2577 			return ERR_PTR(-EINVAL);
2578 		}
2579 
2580 		return __find_kfunc_desc_btf(env, offset);
2581 	}
2582 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2583 }
2584 
2585 #define KF_IMPL_SUFFIX "_impl"
2586 
2587 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log,
2588 						    struct btf *btf,
2589 						    const char *func_name)
2590 {
2591 	const struct btf_type *func;
2592 	char buf[KSYM_NAME_LEN];
2593 	s32 impl_id;
2594 	int len;
2595 
2596 	len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX);
2597 	if (len < 0 || len >= sizeof(buf)) {
2598 		bpf_log(log, "function name %s%s is too long\n",
2599 			func_name, KF_IMPL_SUFFIX);
2600 		return NULL;
2601 	}
2602 
2603 	impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC);
2604 	if (impl_id <= 0) {
2605 		bpf_log(log, "cannot find function %s in BTF\n", buf);
2606 		return NULL;
2607 	}
2608 
2609 	func = btf_type_by_id(btf, impl_id);
2610 
2611 	return btf_type_by_id(btf, func->type);
2612 }
2613 
2614 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
2615 			    s32 func_id,
2616 			    s16 offset,
2617 			    struct bpf_kfunc_meta *kfunc)
2618 {
2619 	const struct btf_type *func, *func_proto;
2620 	const char *func_name;
2621 	u32 *kfunc_flags;
2622 	struct btf *btf;
2623 
2624 	if (func_id <= 0) {
2625 		verbose(env, "invalid kernel function btf_id %d\n", func_id);
2626 		return -EINVAL;
2627 	}
2628 
2629 	btf = find_kfunc_desc_btf(env, offset);
2630 	if (IS_ERR(btf)) {
2631 		verbose(env, "failed to find BTF for kernel function\n");
2632 		return PTR_ERR(btf);
2633 	}
2634 
2635 	/*
2636 	 * Note that kfunc_flags may be NULL at this point, which
2637 	 * means that we couldn't find func_id in any relevant
2638 	 * kfunc_id_set. This most likely indicates an invalid kfunc
2639 	 * call.  However we don't fail with an error here,
2640 	 * and let the caller decide what to do with NULL kfunc->flags.
2641 	 */
2642 	kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog);
2643 
2644 	func = btf_type_by_id(btf, func_id);
2645 	if (!func || !btf_type_is_func(func)) {
2646 		verbose(env, "kernel btf_id %d is not a function\n", func_id);
2647 		return -EINVAL;
2648 	}
2649 
2650 	func_name = btf_name_by_offset(btf, func->name_off);
2651 
2652 	/*
2653 	 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag
2654 	 * can be found through the counterpart _impl kfunc.
2655 	 */
2656 	if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS))
2657 		func_proto = find_kfunc_impl_proto(&env->log, btf, func_name);
2658 	else
2659 		func_proto = btf_type_by_id(btf, func->type);
2660 
2661 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2662 		verbose(env, "kernel function btf_id %d does not have a valid func_proto\n",
2663 			func_id);
2664 		return -EINVAL;
2665 	}
2666 
2667 	memset(kfunc, 0, sizeof(*kfunc));
2668 	kfunc->btf = btf;
2669 	kfunc->id = func_id;
2670 	kfunc->name = func_name;
2671 	kfunc->proto = func_proto;
2672 	kfunc->flags = kfunc_flags;
2673 
2674 	return 0;
2675 }
2676 
2677 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset)
2678 {
2679 	struct bpf_kfunc_btf_tab *btf_tab;
2680 	struct btf_func_model func_model;
2681 	struct bpf_kfunc_desc_tab *tab;
2682 	struct bpf_prog_aux *prog_aux;
2683 	struct bpf_kfunc_meta kfunc;
2684 	struct bpf_kfunc_desc *desc;
2685 	unsigned long addr;
2686 	int err;
2687 
2688 	prog_aux = env->prog->aux;
2689 	tab = prog_aux->kfunc_tab;
2690 	btf_tab = prog_aux->kfunc_btf_tab;
2691 	if (!tab) {
2692 		if (!btf_vmlinux) {
2693 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2694 			return -ENOTSUPP;
2695 		}
2696 
2697 		if (!env->prog->jit_requested) {
2698 			verbose(env, "JIT is required for calling kernel function\n");
2699 			return -ENOTSUPP;
2700 		}
2701 
2702 		if (!bpf_jit_supports_kfunc_call()) {
2703 			verbose(env, "JIT does not support calling kernel function\n");
2704 			return -ENOTSUPP;
2705 		}
2706 
2707 		if (!env->prog->gpl_compatible) {
2708 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2709 			return -EINVAL;
2710 		}
2711 
2712 		tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT);
2713 		if (!tab)
2714 			return -ENOMEM;
2715 		prog_aux->kfunc_tab = tab;
2716 	}
2717 
2718 	/* func_id == 0 is always invalid, but instead of returning an error, be
2719 	 * conservative and wait until the code elimination pass before returning
2720 	 * error, so that invalid calls that get pruned out can be in BPF programs
2721 	 * loaded from userspace.  It is also required that offset be untouched
2722 	 * for such calls.
2723 	 */
2724 	if (!func_id && !offset)
2725 		return 0;
2726 
2727 	if (!btf_tab && offset) {
2728 		btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT);
2729 		if (!btf_tab)
2730 			return -ENOMEM;
2731 		prog_aux->kfunc_btf_tab = btf_tab;
2732 	}
2733 
2734 	if (find_kfunc_desc(env->prog, func_id, offset))
2735 		return 0;
2736 
2737 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2738 		verbose(env, "too many different kernel function calls\n");
2739 		return -E2BIG;
2740 	}
2741 
2742 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
2743 	if (err)
2744 		return err;
2745 
2746 	addr = kallsyms_lookup_name(kfunc.name);
2747 	if (!addr) {
2748 		verbose(env, "cannot find address for kernel function %s\n", kfunc.name);
2749 		return -EINVAL;
2750 	}
2751 
2752 	if (bpf_dev_bound_kfunc_id(func_id)) {
2753 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2754 		if (err)
2755 			return err;
2756 	}
2757 
2758 	err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model);
2759 	if (err)
2760 		return err;
2761 
2762 	desc = &tab->descs[tab->nr_descs++];
2763 	desc->func_id = func_id;
2764 	desc->offset = offset;
2765 	desc->addr = addr;
2766 	desc->func_model = func_model;
2767 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2768 	     kfunc_desc_cmp_by_id_off, NULL);
2769 	return 0;
2770 }
2771 
2772 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2773 {
2774 	return !!prog->aux->kfunc_tab;
2775 }
2776 
2777 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2778 {
2779 	struct bpf_subprog_info *subprog = env->subprog_info;
2780 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2781 	struct bpf_insn *insn = env->prog->insnsi;
2782 
2783 	/* Add entry function. */
2784 	ret = add_subprog(env, 0);
2785 	if (ret)
2786 		return ret;
2787 
2788 	for (i = 0; i < insn_cnt; i++, insn++) {
2789 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2790 		    !bpf_pseudo_kfunc_call(insn))
2791 			continue;
2792 
2793 		if (!env->bpf_capable) {
2794 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2795 			return -EPERM;
2796 		}
2797 
2798 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2799 			ret = add_subprog(env, i + insn->imm + 1);
2800 		else
2801 			ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
2802 
2803 		if (ret < 0)
2804 			return ret;
2805 	}
2806 
2807 	ret = bpf_find_exception_callback_insn_off(env);
2808 	if (ret < 0)
2809 		return ret;
2810 	ex_cb_insn = ret;
2811 
2812 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2813 	 * marked using BTF decl tag to serve as the exception callback.
2814 	 */
2815 	if (ex_cb_insn) {
2816 		ret = add_subprog(env, ex_cb_insn);
2817 		if (ret < 0)
2818 			return ret;
2819 		for (i = 1; i < env->subprog_cnt; i++) {
2820 			if (env->subprog_info[i].start != ex_cb_insn)
2821 				continue;
2822 			env->exception_callback_subprog = i;
2823 			bpf_mark_subprog_exc_cb(env, i);
2824 			break;
2825 		}
2826 	}
2827 
2828 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2829 	 * logic. 'subprog_cnt' should not be increased.
2830 	 */
2831 	subprog[env->subprog_cnt].start = insn_cnt;
2832 
2833 	if (env->log.level & BPF_LOG_LEVEL2)
2834 		for (i = 0; i < env->subprog_cnt; i++)
2835 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2836 
2837 	return 0;
2838 }
2839 
2840 static int check_subprogs(struct bpf_verifier_env *env)
2841 {
2842 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2843 	struct bpf_subprog_info *subprog = env->subprog_info;
2844 	struct bpf_insn *insn = env->prog->insnsi;
2845 	int insn_cnt = env->prog->len;
2846 
2847 	/* now check that all jumps are within the same subprog */
2848 	subprog_start = subprog[cur_subprog].start;
2849 	subprog_end = subprog[cur_subprog + 1].start;
2850 	for (i = 0; i < insn_cnt; i++) {
2851 		u8 code = insn[i].code;
2852 
2853 		if (code == (BPF_JMP | BPF_CALL) &&
2854 		    insn[i].src_reg == 0 &&
2855 		    insn[i].imm == BPF_FUNC_tail_call) {
2856 			subprog[cur_subprog].has_tail_call = true;
2857 			subprog[cur_subprog].tail_call_reachable = true;
2858 		}
2859 		if (BPF_CLASS(code) == BPF_LD &&
2860 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2861 			subprog[cur_subprog].has_ld_abs = true;
2862 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2863 			goto next;
2864 		if (BPF_OP(code) == BPF_CALL)
2865 			goto next;
2866 		if (BPF_OP(code) == BPF_EXIT) {
2867 			subprog[cur_subprog].exit_idx = i;
2868 			goto next;
2869 		}
2870 		off = i + bpf_jmp_offset(&insn[i]) + 1;
2871 		if (off < subprog_start || off >= subprog_end) {
2872 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2873 			return -EINVAL;
2874 		}
2875 next:
2876 		if (i == subprog_end - 1) {
2877 			/* to avoid fall-through from one subprog into another
2878 			 * the last insn of the subprog should be either exit
2879 			 * or unconditional jump back or bpf_throw call
2880 			 */
2881 			if (code != (BPF_JMP | BPF_EXIT) &&
2882 			    code != (BPF_JMP32 | BPF_JA) &&
2883 			    code != (BPF_JMP | BPF_JA)) {
2884 				verbose(env, "last insn is not an exit or jmp\n");
2885 				return -EINVAL;
2886 			}
2887 			subprog_start = subprog_end;
2888 			cur_subprog++;
2889 			if (cur_subprog < env->subprog_cnt)
2890 				subprog_end = subprog[cur_subprog + 1].start;
2891 		}
2892 	}
2893 	return 0;
2894 }
2895 
2896 /*
2897  * Sort subprogs in topological order so that leaf subprogs come first and
2898  * their callers come later. This is a DFS post-order traversal of the call
2899  * graph. Scan only reachable instructions (those in the computed postorder) of
2900  * the current subprog to discover callees (direct subprogs and sync
2901  * callbacks).
2902  */
2903 static int sort_subprogs_topo(struct bpf_verifier_env *env)
2904 {
2905 	struct bpf_subprog_info *si = env->subprog_info;
2906 	int *insn_postorder = env->cfg.insn_postorder;
2907 	struct bpf_insn *insn = env->prog->insnsi;
2908 	int cnt = env->subprog_cnt;
2909 	int *dfs_stack = NULL;
2910 	int top = 0, order = 0;
2911 	int i, ret = 0;
2912 	u8 *color = NULL;
2913 
2914 	color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT);
2915 	dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT);
2916 	if (!color || !dfs_stack) {
2917 		ret = -ENOMEM;
2918 		goto out;
2919 	}
2920 
2921 	/*
2922 	 * DFS post-order traversal.
2923 	 * Color values: 0 = unvisited, 1 = on stack, 2 = done.
2924 	 */
2925 	for (i = 0; i < cnt; i++) {
2926 		if (color[i])
2927 			continue;
2928 		color[i] = 1;
2929 		dfs_stack[top++] = i;
2930 
2931 		while (top > 0) {
2932 			int cur = dfs_stack[top - 1];
2933 			int po_start = si[cur].postorder_start;
2934 			int po_end = si[cur + 1].postorder_start;
2935 			bool pushed = false;
2936 			int j;
2937 
2938 			for (j = po_start; j < po_end; j++) {
2939 				int idx = insn_postorder[j];
2940 				int callee;
2941 
2942 				if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx]))
2943 					continue;
2944 				callee = bpf_find_subprog(env, idx + insn[idx].imm + 1);
2945 				if (callee < 0) {
2946 					ret = -EFAULT;
2947 					goto out;
2948 				}
2949 				if (color[callee] == 2)
2950 					continue;
2951 				if (color[callee] == 1) {
2952 					if (bpf_pseudo_func(&insn[idx]))
2953 						continue;
2954 					verbose(env, "recursive call from %s() to %s()\n",
2955 						subprog_name(env, cur),
2956 						subprog_name(env, callee));
2957 					ret = -EINVAL;
2958 					goto out;
2959 				}
2960 				color[callee] = 1;
2961 				dfs_stack[top++] = callee;
2962 				pushed = true;
2963 				break;
2964 			}
2965 
2966 			if (!pushed) {
2967 				color[cur] = 2;
2968 				env->subprog_topo_order[order++] = cur;
2969 				top--;
2970 			}
2971 		}
2972 	}
2973 
2974 	if (env->log.level & BPF_LOG_LEVEL2)
2975 		for (i = 0; i < cnt; i++)
2976 			verbose(env, "topo_order[%d] = %s\n",
2977 				i, subprog_name(env, env->subprog_topo_order[i]));
2978 out:
2979 	kvfree(dfs_stack);
2980 	kvfree(color);
2981 	return ret;
2982 }
2983 
2984 static void mark_stack_slots_scratched(struct bpf_verifier_env *env,
2985 				       int spi, int nr_slots)
2986 {
2987 	int i;
2988 
2989 	for (i = 0; i < nr_slots; i++)
2990 		mark_stack_slot_scratched(env, spi - i);
2991 }
2992 
2993 /* This function is supposed to be used by the following 32-bit optimization
2994  * code only. It returns TRUE if the source or destination register operates
2995  * on 64-bit, otherwise return FALSE.
2996  */
2997 bool bpf_is_reg64(struct bpf_insn *insn,
2998 	      u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t)
2999 {
3000 	u8 code, class, op;
3001 
3002 	code = insn->code;
3003 	class = BPF_CLASS(code);
3004 	op = BPF_OP(code);
3005 	if (class == BPF_JMP) {
3006 		/* BPF_EXIT for "main" will reach here. Return TRUE
3007 		 * conservatively.
3008 		 */
3009 		if (op == BPF_EXIT)
3010 			return true;
3011 		if (op == BPF_CALL) {
3012 			/* BPF to BPF call will reach here because of marking
3013 			 * caller saved clobber with DST_OP_NO_MARK for which we
3014 			 * don't care the register def because they are anyway
3015 			 * marked as NOT_INIT already.
3016 			 */
3017 			if (insn->src_reg == BPF_PSEUDO_CALL)
3018 				return false;
3019 			/* Helper call will reach here because of arg type
3020 			 * check, conservatively return TRUE.
3021 			 */
3022 			if (t == SRC_OP)
3023 				return true;
3024 
3025 			return false;
3026 		}
3027 	}
3028 
3029 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3030 		return false;
3031 
3032 	if (class == BPF_ALU64 || class == BPF_JMP ||
3033 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3034 		return true;
3035 
3036 	if (class == BPF_ALU || class == BPF_JMP32)
3037 		return false;
3038 
3039 	if (class == BPF_LDX) {
3040 		if (t != SRC_OP)
3041 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3042 		/* LDX source must be ptr. */
3043 		return true;
3044 	}
3045 
3046 	if (class == BPF_STX) {
3047 		/* BPF_STX (including atomic variants) has one or more source
3048 		 * operands, one of which is a ptr. Check whether the caller is
3049 		 * asking about it.
3050 		 */
3051 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3052 			return true;
3053 		return BPF_SIZE(code) == BPF_DW;
3054 	}
3055 
3056 	if (class == BPF_LD) {
3057 		u8 mode = BPF_MODE(code);
3058 
3059 		/* LD_IMM64 */
3060 		if (mode == BPF_IMM)
3061 			return true;
3062 
3063 		/* Both LD_IND and LD_ABS return 32-bit data. */
3064 		if (t != SRC_OP)
3065 			return  false;
3066 
3067 		/* Implicit ctx ptr. */
3068 		if (regno == BPF_REG_6)
3069 			return true;
3070 
3071 		/* Explicit source could be any width. */
3072 		return true;
3073 	}
3074 
3075 	if (class == BPF_ST)
3076 		/* The only source register for BPF_ST is a ptr. */
3077 		return true;
3078 
3079 	/* Conservatively return true at default. */
3080 	return true;
3081 }
3082 
3083 static void mark_insn_zext(struct bpf_verifier_env *env,
3084 			   struct bpf_reg_state *reg)
3085 {
3086 	s32 def_idx = reg->subreg_def;
3087 
3088 	if (def_idx == DEF_NOT_SUBREG)
3089 		return;
3090 
3091 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3092 	/* The dst will be zero extended, so won't be sub-register anymore. */
3093 	reg->subreg_def = DEF_NOT_SUBREG;
3094 }
3095 
3096 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3097 			   enum bpf_reg_arg_type t)
3098 {
3099 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3100 	struct bpf_reg_state *reg;
3101 	bool rw64;
3102 
3103 	mark_reg_scratched(env, regno);
3104 
3105 	reg = &regs[regno];
3106 	rw64 = bpf_is_reg64(insn, regno, reg, t);
3107 	if (t == SRC_OP) {
3108 		/* check whether register used as source operand can be read */
3109 		if (reg->type == NOT_INIT) {
3110 			verbose(env, "R%d !read_ok\n", regno);
3111 			return -EACCES;
3112 		}
3113 		/* We don't need to worry about FP liveness because it's read-only */
3114 		if (regno == BPF_REG_FP)
3115 			return 0;
3116 
3117 		if (rw64)
3118 			mark_insn_zext(env, reg);
3119 
3120 		return 0;
3121 	} else {
3122 		/* check whether register used as dest operand can be written to */
3123 		if (regno == BPF_REG_FP) {
3124 			verbose(env, "frame pointer is read only\n");
3125 			return -EACCES;
3126 		}
3127 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3128 		if (t == DST_OP)
3129 			mark_reg_unknown(env, regs, regno);
3130 	}
3131 	return 0;
3132 }
3133 
3134 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3135 			 enum bpf_reg_arg_type t)
3136 {
3137 	struct bpf_verifier_state *vstate = env->cur_state;
3138 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3139 
3140 	return __check_reg_arg(env, state->regs, regno, t);
3141 }
3142 
3143 static void mark_indirect_target(struct bpf_verifier_env *env, int idx)
3144 {
3145 	env->insn_aux_data[idx].indirect_target = true;
3146 }
3147 
3148 #define LR_FRAMENO_BITS	4
3149 #define LR_SPI_BITS	6
3150 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3151 #define LR_SIZE_BITS	4
3152 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3153 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3154 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3155 #define LR_SPI_OFF	LR_FRAMENO_BITS
3156 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3157 #define LINKED_REGS_MAX	5
3158 
3159 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS));
3160 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS));
3161 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64);
3162 
3163 struct linked_reg {
3164 	u8 frameno;
3165 	union {
3166 		u8 spi;
3167 		u8 regno;
3168 	};
3169 	bool is_reg;
3170 };
3171 
3172 struct linked_regs {
3173 	int cnt;
3174 	struct linked_reg entries[LINKED_REGS_MAX];
3175 };
3176 
3177 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3178 {
3179 	if (s->cnt < LINKED_REGS_MAX)
3180 		return &s->entries[s->cnt++];
3181 
3182 	return NULL;
3183 }
3184 
3185 /*
3186  * Use u64 as a vector of 5 11-bit values, use first 4-bits to track
3187  * number of elements currently in stack.
3188  * Pack one history entry for linked registers as 11 bits in the following format:
3189  * - 4-bits frameno
3190  * - 6-bits spi_or_reg
3191  * - 1-bit  is_reg
3192  */
3193 static u64 linked_regs_pack(struct linked_regs *s)
3194 {
3195 	u64 val = 0;
3196 	int i;
3197 
3198 	for (i = 0; i < s->cnt; ++i) {
3199 		struct linked_reg *e = &s->entries[i];
3200 		u64 tmp = 0;
3201 
3202 		tmp |= e->frameno;
3203 		tmp |= e->spi << LR_SPI_OFF;
3204 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3205 
3206 		val <<= LR_ENTRY_BITS;
3207 		val |= tmp;
3208 	}
3209 	val <<= LR_SIZE_BITS;
3210 	val |= s->cnt;
3211 	return val;
3212 }
3213 
3214 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3215 {
3216 	int i;
3217 
3218 	s->cnt = val & LR_SIZE_MASK;
3219 	val >>= LR_SIZE_BITS;
3220 
3221 	for (i = 0; i < s->cnt; ++i) {
3222 		struct linked_reg *e = &s->entries[i];
3223 
3224 		e->frameno =  val & LR_FRAMENO_MASK;
3225 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3226 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3227 		val >>= LR_ENTRY_BITS;
3228 	}
3229 }
3230 
3231 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3232 {
3233 	const struct btf_type *func;
3234 	struct btf *desc_btf;
3235 
3236 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3237 		return NULL;
3238 
3239 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3240 	if (IS_ERR(desc_btf))
3241 		return "<error>";
3242 
3243 	func = btf_type_by_id(desc_btf, insn->imm);
3244 	return btf_name_by_offset(desc_btf, func->name_off);
3245 }
3246 
3247 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3248 {
3249 	const struct bpf_insn_cbs cbs = {
3250 		.cb_call	= disasm_kfunc_name,
3251 		.cb_print	= verbose,
3252 		.private_data	= env,
3253 	};
3254 
3255 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3256 }
3257 
3258 /* If any register R in hist->linked_regs is marked as precise in bt,
3259  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3260  */
3261 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3262 {
3263 	struct linked_regs linked_regs;
3264 	bool some_precise = false;
3265 	int i;
3266 
3267 	if (!hist || hist->linked_regs == 0)
3268 		return;
3269 
3270 	linked_regs_unpack(hist->linked_regs, &linked_regs);
3271 	for (i = 0; i < linked_regs.cnt; ++i) {
3272 		struct linked_reg *e = &linked_regs.entries[i];
3273 
3274 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3275 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3276 			some_precise = true;
3277 			break;
3278 		}
3279 	}
3280 
3281 	if (!some_precise)
3282 		return;
3283 
3284 	for (i = 0; i < linked_regs.cnt; ++i) {
3285 		struct linked_reg *e = &linked_regs.entries[i];
3286 
3287 		if (e->is_reg)
3288 			bpf_bt_set_frame_reg(bt, e->frameno, e->regno);
3289 		else
3290 			bpf_bt_set_frame_slot(bt, e->frameno, e->spi);
3291 	}
3292 }
3293 
3294 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3295 {
3296 	return bpf_mark_chain_precision(env, env->cur_state, regno, NULL);
3297 }
3298 
3299 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
3300  * desired reg and stack masks across all relevant frames
3301  */
3302 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
3303 				      struct bpf_verifier_state *starting_state)
3304 {
3305 	return bpf_mark_chain_precision(env, starting_state, -1, NULL);
3306 }
3307 
3308 static bool is_spillable_regtype(enum bpf_reg_type type)
3309 {
3310 	switch (base_type(type)) {
3311 	case PTR_TO_MAP_VALUE:
3312 	case PTR_TO_STACK:
3313 	case PTR_TO_CTX:
3314 	case PTR_TO_PACKET:
3315 	case PTR_TO_PACKET_META:
3316 	case PTR_TO_PACKET_END:
3317 	case PTR_TO_FLOW_KEYS:
3318 	case CONST_PTR_TO_MAP:
3319 	case PTR_TO_SOCKET:
3320 	case PTR_TO_SOCK_COMMON:
3321 	case PTR_TO_TCP_SOCK:
3322 	case PTR_TO_XDP_SOCK:
3323 	case PTR_TO_BTF_ID:
3324 	case PTR_TO_BUF:
3325 	case PTR_TO_MEM:
3326 	case PTR_TO_FUNC:
3327 	case PTR_TO_MAP_KEY:
3328 	case PTR_TO_ARENA:
3329 		return true;
3330 	default:
3331 		return false;
3332 	}
3333 }
3334 
3335 
3336 /* check if register is a constant scalar value */
3337 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
3338 {
3339 	return reg->type == SCALAR_VALUE &&
3340 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
3341 }
3342 
3343 /* assuming is_reg_const() is true, return constant value of a register */
3344 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
3345 {
3346 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
3347 }
3348 
3349 static bool __is_pointer_value(bool allow_ptr_leaks,
3350 			       const struct bpf_reg_state *reg)
3351 {
3352 	if (allow_ptr_leaks)
3353 		return false;
3354 
3355 	return reg->type != SCALAR_VALUE;
3356 }
3357 
3358 static void clear_scalar_id(struct bpf_reg_state *reg)
3359 {
3360 	reg->id = 0;
3361 	reg->delta = 0;
3362 }
3363 
3364 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
3365 					struct bpf_reg_state *src_reg)
3366 {
3367 	if (src_reg->type != SCALAR_VALUE)
3368 		return;
3369 	/*
3370 	 * The verifier is processing rX = rY insn and
3371 	 * rY->id has special linked register already.
3372 	 * Cleared it, since multiple rX += const are not supported.
3373 	 */
3374 	if (src_reg->id & BPF_ADD_CONST)
3375 		clear_scalar_id(src_reg);
3376 	/*
3377 	 * Ensure that src_reg has a valid ID that will be copied to
3378 	 * dst_reg and then will be used by sync_linked_regs() to
3379 	 * propagate min/max range.
3380 	 */
3381 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
3382 		src_reg->id = ++env->id_gen;
3383 }
3384 
3385 static void save_register_state(struct bpf_verifier_env *env,
3386 				struct bpf_func_state *state,
3387 				int spi, struct bpf_reg_state *reg,
3388 				int size)
3389 {
3390 	int i;
3391 
3392 	state->stack[spi].spilled_ptr = *reg;
3393 
3394 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3395 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3396 
3397 	/* size < 8 bytes spill */
3398 	for (; i; i--)
3399 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
3400 }
3401 
3402 static bool is_bpf_st_mem(struct bpf_insn *insn)
3403 {
3404 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3405 }
3406 
3407 static int get_reg_width(struct bpf_reg_state *reg)
3408 {
3409 	return fls64(reg_umax(reg));
3410 }
3411 
3412 /* See comment for mark_fastcall_pattern_for_call() */
3413 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
3414 					  struct bpf_func_state *state, int insn_idx, int off)
3415 {
3416 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
3417 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3418 	int i;
3419 
3420 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
3421 		return;
3422 	/* access to the region [max_stack_depth .. fastcall_stack_off)
3423 	 * from something that is not a part of the fastcall pattern,
3424 	 * disable fastcall rewrites for current subprogram by setting
3425 	 * fastcall_stack_off to a value smaller than any possible offset.
3426 	 */
3427 	subprog->fastcall_stack_off = S16_MIN;
3428 	/* reset fastcall aux flags within subprogram,
3429 	 * happens at most once per subprogram
3430 	 */
3431 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
3432 		aux[i].fastcall_spills_num = 0;
3433 		aux[i].fastcall_pattern = 0;
3434 	}
3435 }
3436 
3437 static void scrub_special_slot(struct bpf_func_state *state, int spi)
3438 {
3439 	int i;
3440 
3441 	/* regular write of data into stack destroys any spilled ptr */
3442 	state->stack[spi].spilled_ptr.type = NOT_INIT;
3443 	/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3444 	if (is_stack_slot_special(&state->stack[spi]))
3445 		for (i = 0; i < BPF_REG_SIZE; i++)
3446 			scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3447 }
3448 
3449 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3450  * stack boundary and alignment are checked in check_mem_access()
3451  */
3452 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3453 				       /* stack frame we're writing to */
3454 				       struct bpf_func_state *state,
3455 				       int off, int size, int value_regno,
3456 				       int insn_idx)
3457 {
3458 	struct bpf_func_state *cur; /* state of the current function */
3459 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3460 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3461 	struct bpf_reg_state *reg = NULL;
3462 	int insn_flags = INSN_F_STACK_ACCESS;
3463 	int hist_spi = spi, hist_frame = state->frameno;
3464 
3465 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3466 	 * so it's aligned access and [off, off + size) are within stack limits
3467 	 */
3468 	if (!env->allow_ptr_leaks &&
3469 	    bpf_is_spilled_reg(&state->stack[spi]) &&
3470 	    !bpf_is_spilled_scalar_reg(&state->stack[spi]) &&
3471 	    size != BPF_REG_SIZE) {
3472 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3473 		return -EACCES;
3474 	}
3475 
3476 	cur = env->cur_state->frame[env->cur_state->curframe];
3477 	if (value_regno >= 0)
3478 		reg = &cur->regs[value_regno];
3479 	if (!env->bypass_spec_v4) {
3480 		bool sanitize = reg && is_spillable_regtype(reg->type);
3481 
3482 		for (i = 0; i < size; i++) {
3483 			u8 type = state->stack[spi].slot_type[(slot - i) %
3484 							      BPF_REG_SIZE];
3485 
3486 			if (type != STACK_MISC && type != STACK_ZERO) {
3487 				sanitize = true;
3488 				break;
3489 			}
3490 		}
3491 
3492 		if (sanitize)
3493 			env->insn_aux_data[insn_idx].nospec_result = true;
3494 	}
3495 
3496 	err = destroy_if_dynptr_stack_slot(env, state, spi);
3497 	if (err)
3498 		return err;
3499 
3500 	check_fastcall_stack_contract(env, state, insn_idx, off);
3501 	mark_stack_slot_scratched(env, spi);
3502 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
3503 		bool reg_value_fits;
3504 
3505 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
3506 		/* Make sure that reg had an ID to build a relation on spill. */
3507 		if (reg_value_fits)
3508 			assign_scalar_id_before_mov(env, reg);
3509 		save_register_state(env, state, spi, reg, size);
3510 		/* Break the relation on a narrowing spill. */
3511 		if (!reg_value_fits)
3512 			state->stack[spi].spilled_ptr.id = 0;
3513 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3514 		   env->bpf_capable) {
3515 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
3516 
3517 		memset(tmp_reg, 0, sizeof(*tmp_reg));
3518 		__mark_reg_known(tmp_reg, insn->imm);
3519 		tmp_reg->type = SCALAR_VALUE;
3520 		save_register_state(env, state, spi, tmp_reg, size);
3521 	} else if (reg && is_spillable_regtype(reg->type)) {
3522 		/* register containing pointer is being spilled into stack */
3523 		if (size != BPF_REG_SIZE) {
3524 			verbose_linfo(env, insn_idx, "; ");
3525 			verbose(env, "invalid size of register spill\n");
3526 			return -EACCES;
3527 		}
3528 		if (state != cur && reg->type == PTR_TO_STACK) {
3529 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3530 			return -EINVAL;
3531 		}
3532 		save_register_state(env, state, spi, reg, size);
3533 	} else {
3534 		u8 type = STACK_MISC;
3535 
3536 		scrub_special_slot(state, spi);
3537 
3538 		/* when we zero initialize stack slots mark them as such */
3539 		if ((reg && bpf_register_is_null(reg)) ||
3540 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3541 			/* STACK_ZERO case happened because register spill
3542 			 * wasn't properly aligned at the stack slot boundary,
3543 			 * so it's not a register spill anymore; force
3544 			 * originating register to be precise to make
3545 			 * STACK_ZERO correct for subsequent states
3546 			 */
3547 			err = mark_chain_precision(env, value_regno);
3548 			if (err)
3549 				return err;
3550 			type = STACK_ZERO;
3551 		}
3552 
3553 		/* Mark slots affected by this stack write. */
3554 		for (i = 0; i < size; i++)
3555 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
3556 		insn_flags = 0; /* not a register spill */
3557 	}
3558 
3559 	if (insn_flags)
3560 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3561 					    hist_spi, hist_frame, 0);
3562 	return 0;
3563 }
3564 
3565 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is
3566  * known to contain a variable offset.
3567  * This function checks whether the write is permitted and conservatively
3568  * tracks the effects of the write, considering that each stack slot in the
3569  * dynamic range is potentially written to.
3570  *
3571  * 'value_regno' can be -1, meaning that an unknown value is being written to
3572  * the stack.
3573  *
3574  * Spilled pointers in range are not marked as written because we don't know
3575  * what's going to be actually written. This means that read propagation for
3576  * future reads cannot be terminated by this write.
3577  *
3578  * For privileged programs, uninitialized stack slots are considered
3579  * initialized by this write (even though we don't know exactly what offsets
3580  * are going to be written to). The idea is that we don't want the verifier to
3581  * reject future reads that access slots written to through variable offsets.
3582  */
3583 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3584 				     /* func where register points to */
3585 				     struct bpf_func_state *state,
3586 				     struct bpf_reg_state *ptr_reg, int off, int size,
3587 				     int value_regno, int insn_idx)
3588 {
3589 	struct bpf_func_state *cur; /* state of the current function */
3590 	int min_off, max_off;
3591 	int i, err;
3592 	struct bpf_reg_state *value_reg = NULL;
3593 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3594 	bool writing_zero = false;
3595 	/* set if the fact that we're writing a zero is used to let any
3596 	 * stack slots remain STACK_ZERO
3597 	 */
3598 	bool zero_used = false;
3599 
3600 	cur = env->cur_state->frame[env->cur_state->curframe];
3601 	min_off = reg_smin(ptr_reg) + off;
3602 	max_off = reg_smax(ptr_reg) + off + size;
3603 	if (value_regno >= 0)
3604 		value_reg = &cur->regs[value_regno];
3605 	if ((value_reg && bpf_register_is_null(value_reg)) ||
3606 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3607 		writing_zero = true;
3608 
3609 	for (i = min_off; i < max_off; i++) {
3610 		int spi;
3611 
3612 		spi = bpf_get_spi(i);
3613 		err = destroy_if_dynptr_stack_slot(env, state, spi);
3614 		if (err)
3615 			return err;
3616 	}
3617 
3618 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
3619 	/* Variable offset writes destroy any spilled pointers in range. */
3620 	for (i = min_off; i < max_off; i++) {
3621 		u8 new_type, *stype;
3622 		int slot, spi;
3623 
3624 		slot = -i - 1;
3625 		spi = slot / BPF_REG_SIZE;
3626 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3627 		mark_stack_slot_scratched(env, spi);
3628 
3629 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3630 			/* Reject the write if range we may write to has not
3631 			 * been initialized beforehand. If we didn't reject
3632 			 * here, the ptr status would be erased below (even
3633 			 * though not all slots are actually overwritten),
3634 			 * possibly opening the door to leaks.
3635 			 *
3636 			 * We do however catch STACK_INVALID case below, and
3637 			 * only allow reading possibly uninitialized memory
3638 			 * later for CAP_PERFMON, as the write may not happen to
3639 			 * that slot.
3640 			 */
3641 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3642 				insn_idx, i);
3643 			return -EINVAL;
3644 		}
3645 
3646 		/* If writing_zero and the spi slot contains a spill of value 0,
3647 		 * maintain the spill type.
3648 		 */
3649 		if (writing_zero && *stype == STACK_SPILL &&
3650 		    bpf_is_spilled_scalar_reg(&state->stack[spi])) {
3651 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
3652 
3653 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
3654 				zero_used = true;
3655 				continue;
3656 			}
3657 		}
3658 
3659 		/*
3660 		 * Scrub slots if variable-offset stack write goes over spilled pointers.
3661 		 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT
3662 		 * and valid program is rejected by check_stack_read_fixed_off()
3663 		 * with obscure "invalid size of register fill" message.
3664 		 */
3665 		scrub_special_slot(state, spi);
3666 
3667 		/* Update the slot type. */
3668 		new_type = STACK_MISC;
3669 		if (writing_zero && *stype == STACK_ZERO) {
3670 			new_type = STACK_ZERO;
3671 			zero_used = true;
3672 		}
3673 		/* If the slot is STACK_INVALID, we check whether it's OK to
3674 		 * pretend that it will be initialized by this write. The slot
3675 		 * might not actually be written to, and so if we mark it as
3676 		 * initialized future reads might leak uninitialized memory.
3677 		 * For privileged programs, we will accept such reads to slots
3678 		 * that may or may not be written because, if we're reject
3679 		 * them, the error would be too confusing.
3680 		 * Conservatively, treat STACK_POISON in a similar way.
3681 		 */
3682 		if ((*stype == STACK_INVALID || *stype == STACK_POISON) &&
3683 		    !env->allow_uninit_stack) {
3684 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3685 					insn_idx, i);
3686 			return -EINVAL;
3687 		}
3688 		*stype = new_type;
3689 	}
3690 	if (zero_used) {
3691 		/* backtracking doesn't work for STACK_ZERO yet. */
3692 		err = mark_chain_precision(env, value_regno);
3693 		if (err)
3694 			return err;
3695 	}
3696 	return 0;
3697 }
3698 
3699 /* When register 'dst_regno' is assigned some values from stack[min_off,
3700  * max_off), we set the register's type according to the types of the
3701  * respective stack slots. If all the stack values are known to be zeros, then
3702  * so is the destination reg. Otherwise, the register is considered to be
3703  * SCALAR. This function does not deal with register filling; the caller must
3704  * ensure that all spilled registers in the stack range have been marked as
3705  * read.
3706  */
3707 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3708 				/* func where src register points to */
3709 				struct bpf_func_state *ptr_state,
3710 				int min_off, int max_off, int dst_regno)
3711 {
3712 	struct bpf_verifier_state *vstate = env->cur_state;
3713 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3714 	int i, slot, spi;
3715 	u8 *stype;
3716 	int zeros = 0;
3717 
3718 	for (i = min_off; i < max_off; i++) {
3719 		slot = -i - 1;
3720 		spi = slot / BPF_REG_SIZE;
3721 		mark_stack_slot_scratched(env, spi);
3722 		stype = ptr_state->stack[spi].slot_type;
3723 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3724 			break;
3725 		zeros++;
3726 	}
3727 	if (zeros == max_off - min_off) {
3728 		/* Any access_size read into register is zero extended,
3729 		 * so the whole register == const_zero.
3730 		 */
3731 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
3732 	} else {
3733 		/* have read misc data from the stack */
3734 		mark_reg_unknown(env, state->regs, dst_regno);
3735 	}
3736 }
3737 
3738 /* Read the stack at 'off' and put the results into the register indicated by
3739  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3740  * spilled reg.
3741  *
3742  * 'dst_regno' can be -1, meaning that the read value is not going to a
3743  * register.
3744  *
3745  * The access is assumed to be within the current stack bounds.
3746  */
3747 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3748 				      /* func where src register points to */
3749 				      struct bpf_func_state *reg_state,
3750 				      int off, int size, int dst_regno)
3751 {
3752 	struct bpf_verifier_state *vstate = env->cur_state;
3753 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3754 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3755 	struct bpf_reg_state *reg;
3756 	u8 *stype, type;
3757 	int insn_flags = INSN_F_STACK_ACCESS;
3758 	int hist_spi = spi, hist_frame = reg_state->frameno;
3759 
3760 	stype = reg_state->stack[spi].slot_type;
3761 	reg = &reg_state->stack[spi].spilled_ptr;
3762 
3763 	mark_stack_slot_scratched(env, spi);
3764 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
3765 
3766 	if (bpf_is_spilled_reg(&reg_state->stack[spi])) {
3767 		u8 spill_size = 1;
3768 
3769 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3770 			spill_size++;
3771 
3772 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3773 			if (reg->type != SCALAR_VALUE) {
3774 				verbose_linfo(env, env->insn_idx, "; ");
3775 				verbose(env, "invalid size of register fill\n");
3776 				return -EACCES;
3777 			}
3778 
3779 			if (dst_regno < 0)
3780 				return 0;
3781 
3782 			if (size <= spill_size &&
3783 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
3784 				/* The earlier check_reg_arg() has decided the
3785 				 * subreg_def for this insn.  Save it first.
3786 				 */
3787 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3788 
3789 				if (env->bpf_capable && size == 4 && spill_size == 4 &&
3790 				    get_reg_width(reg) <= 32)
3791 					/* Ensure stack slot has an ID to build a relation
3792 					 * with the destination register on fill.
3793 					 */
3794 					assign_scalar_id_before_mov(env, reg);
3795 				state->regs[dst_regno] = *reg;
3796 				state->regs[dst_regno].subreg_def = subreg_def;
3797 
3798 				/* Break the relation on a narrowing fill.
3799 				 * coerce_reg_to_size will adjust the boundaries.
3800 				 */
3801 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
3802 					clear_scalar_id(&state->regs[dst_regno]);
3803 			} else {
3804 				int spill_cnt = 0, zero_cnt = 0;
3805 
3806 				for (i = 0; i < size; i++) {
3807 					type = stype[(slot - i) % BPF_REG_SIZE];
3808 					if (type == STACK_SPILL) {
3809 						spill_cnt++;
3810 						continue;
3811 					}
3812 					if (type == STACK_MISC)
3813 						continue;
3814 					if (type == STACK_ZERO) {
3815 						zero_cnt++;
3816 						continue;
3817 					}
3818 					if (type == STACK_INVALID && env->allow_uninit_stack)
3819 						continue;
3820 					if (type == STACK_POISON) {
3821 						verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3822 							off, i, size);
3823 					} else {
3824 						verbose(env, "invalid read from stack off %d+%d size %d\n",
3825 							off, i, size);
3826 					}
3827 					return -EACCES;
3828 				}
3829 
3830 				if (spill_cnt == size &&
3831 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
3832 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3833 					/* this IS register fill, so keep insn_flags */
3834 				} else if (zero_cnt == size) {
3835 					/* similarly to mark_reg_stack_read(), preserve zeroes */
3836 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
3837 					insn_flags = 0; /* not restoring original register state */
3838 				} else {
3839 					mark_reg_unknown(env, state->regs, dst_regno);
3840 					insn_flags = 0; /* not restoring original register state */
3841 				}
3842 			}
3843 		} else if (dst_regno >= 0) {
3844 			/* restore register state from stack */
3845 			if (env->bpf_capable)
3846 				/* Ensure stack slot has an ID to build a relation
3847 				 * with the destination register on fill.
3848 				 */
3849 				assign_scalar_id_before_mov(env, reg);
3850 			state->regs[dst_regno] = *reg;
3851 			/* mark reg as written since spilled pointer state likely
3852 			 * has its liveness marks cleared by is_state_visited()
3853 			 * which resets stack/reg liveness for state transitions
3854 			 */
3855 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3856 			/* If dst_regno==-1, the caller is asking us whether
3857 			 * it is acceptable to use this value as a SCALAR_VALUE
3858 			 * (e.g. for XADD).
3859 			 * We must not allow unprivileged callers to do that
3860 			 * with spilled pointers.
3861 			 */
3862 			verbose(env, "leaking pointer from stack off %d\n",
3863 				off);
3864 			return -EACCES;
3865 		}
3866 	} else {
3867 		for (i = 0; i < size; i++) {
3868 			type = stype[(slot - i) % BPF_REG_SIZE];
3869 			if (type == STACK_MISC)
3870 				continue;
3871 			if (type == STACK_ZERO)
3872 				continue;
3873 			if (type == STACK_INVALID && env->allow_uninit_stack)
3874 				continue;
3875 			if (type == STACK_POISON) {
3876 				verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n",
3877 					off, i, size);
3878 			} else {
3879 				verbose(env, "invalid read from stack off %d+%d size %d\n",
3880 					off, i, size);
3881 			}
3882 			return -EACCES;
3883 		}
3884 		if (dst_regno >= 0)
3885 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3886 		insn_flags = 0; /* we are not restoring spilled register */
3887 	}
3888 	if (insn_flags)
3889 		return bpf_push_jmp_history(env, env->cur_state, insn_flags,
3890 					    hist_spi, hist_frame, 0);
3891 	return 0;
3892 }
3893 
3894 enum bpf_access_src {
3895 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3896 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3897 };
3898 
3899 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3900 					 argno_t argno, int off, int access_size,
3901 					 bool zero_size_allowed,
3902 					 enum bpf_access_type type,
3903 					 struct bpf_call_arg_meta *meta);
3904 
3905 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3906 {
3907 	return cur_regs(env) + regno;
3908 }
3909 
3910 /* Read the stack at 'reg + off' and put the result into the register
3911  * 'dst_regno'.
3912  * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'),
3913  * but not its variable offset.
3914  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3915  *
3916  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3917  * filling registers (i.e. reads of spilled register cannot be detected when
3918  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3919  * SCALAR_VALUE. That's why we assert that the 'reg' has a variable
3920  * offset; for a fixed offset check_stack_read_fixed_off should be used
3921  * instead.
3922  */
3923 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3924 				    argno_t ptr_argno, int off, int size, int dst_regno)
3925 {
3926 	struct bpf_func_state *ptr_state = bpf_func(env, reg);
3927 	int err;
3928 	int min_off, max_off;
3929 
3930 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3931 	 */
3932 	err = check_stack_range_initialized(env, reg, ptr_argno, off, size,
3933 					    false, BPF_READ, NULL);
3934 	if (err)
3935 		return err;
3936 
3937 	min_off = reg_smin(reg) + off;
3938 	max_off = reg_smax(reg) + off;
3939 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3940 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
3941 	return 0;
3942 }
3943 
3944 /* check_stack_read dispatches to check_stack_read_fixed_off or
3945  * check_stack_read_var_off.
3946  *
3947  * The caller must ensure that the offset falls within the allocated stack
3948  * bounds.
3949  *
3950  * 'dst_regno' is a register which will receive the value from the stack. It
3951  * can be -1, meaning that the read value is not going to a register.
3952  */
3953 static int check_stack_read(struct bpf_verifier_env *env,
3954 			    struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size,
3955 			    int dst_regno)
3956 {
3957 	struct bpf_func_state *state = bpf_func(env, reg);
3958 	int err;
3959 	/* Some accesses are only permitted with a static offset. */
3960 	bool var_off = !tnum_is_const(reg->var_off);
3961 
3962 	/* The offset is required to be static when reads don't go to a
3963 	 * register, in order to not leak pointers (see
3964 	 * check_stack_read_fixed_off).
3965 	 */
3966 	if (dst_regno < 0 && var_off) {
3967 		char tn_buf[48];
3968 
3969 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3970 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3971 			tn_buf, off, size);
3972 		return -EACCES;
3973 	}
3974 	/* Variable offset is prohibited for unprivileged mode for simplicity
3975 	 * since it requires corresponding support in Spectre masking for stack
3976 	 * ALU. See also retrieve_ptr_limit(). The check in
3977 	 * check_stack_access_for_ptr_arithmetic() called by
3978 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3979 	 * with variable offsets, therefore no check is required here. Further,
3980 	 * just checking it here would be insufficient as speculative stack
3981 	 * writes could still lead to unsafe speculative behaviour.
3982 	 */
3983 	if (!var_off) {
3984 		off += reg->var_off.value;
3985 		err = check_stack_read_fixed_off(env, state, off, size,
3986 						 dst_regno);
3987 	} else {
3988 		/* Variable offset stack reads need more conservative handling
3989 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3990 		 * branch.
3991 		 */
3992 		err = check_stack_read_var_off(env, reg, ptr_argno, off, size,
3993 					       dst_regno);
3994 	}
3995 	return err;
3996 }
3997 
3998 
3999 /* check_stack_write dispatches to check_stack_write_fixed_off or
4000  * check_stack_write_var_off.
4001  *
4002  * 'reg' is the register used as a pointer into the stack.
4003  * 'value_regno' is the register whose value we're writing to the stack. It can
4004  * be -1, meaning that we're not writing from a register.
4005  *
4006  * The caller must ensure that the offset falls within the maximum stack size.
4007  */
4008 static int check_stack_write(struct bpf_verifier_env *env,
4009 			     struct bpf_reg_state *reg, int off, int size,
4010 			     int value_regno, int insn_idx)
4011 {
4012 	struct bpf_func_state *state = bpf_func(env, reg);
4013 	int err;
4014 
4015 	if (tnum_is_const(reg->var_off)) {
4016 		off += reg->var_off.value;
4017 		err = check_stack_write_fixed_off(env, state, off, size,
4018 						  value_regno, insn_idx);
4019 	} else {
4020 		/* Variable offset stack reads need more conservative handling
4021 		 * than fixed offset ones.
4022 		 */
4023 		err = check_stack_write_var_off(env, state,
4024 						reg, off, size,
4025 						value_regno, insn_idx);
4026 	}
4027 	return err;
4028 }
4029 
4030 /*
4031  * Write a value to the outgoing stack arg area.
4032  * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7).
4033  */
4034 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,
4035 				 int off, struct bpf_reg_state *value_reg)
4036 {
4037 	int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS;
4038 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4039 	int spi = -off / BPF_REG_SIZE - 1;
4040 	struct bpf_reg_state *arg;
4041 	int err;
4042 
4043 	if (spi >= max_stack_arg_regs) {
4044 		verbose(env, "stack arg write offset %d exceeds max %d stack args\n",
4045 			off, max_stack_arg_regs);
4046 		return -EINVAL;
4047 	}
4048 
4049 	err = grow_stack_arg_slots(env, state, spi + 1);
4050 	if (err)
4051 		return err;
4052 
4053 	/* Track the max outgoing stack arg slot count. */
4054 	if (spi + 1 > subprog->max_out_stack_arg_cnt)
4055 		subprog->max_out_stack_arg_cnt = spi + 1;
4056 
4057 	if (value_reg) {
4058 		state->stack_arg_regs[spi] = *value_reg;
4059 	} else {
4060 		/* BPF_ST: store immediate, treat as scalar */
4061 		arg = &state->stack_arg_regs[spi];
4062 		arg->type = SCALAR_VALUE;
4063 		__mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm);
4064 	}
4065 	state->no_stack_arg_load = true;
4066 	return bpf_push_jmp_history(env, env->cur_state,
4067 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4068 }
4069 
4070 /*
4071  * Read a value from the incoming stack arg area.
4072  * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7).
4073  */
4074 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,
4075 				int off, int dst_regno)
4076 {
4077 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4078 	struct bpf_verifier_state *vstate = env->cur_state;
4079 	int spi = off / BPF_REG_SIZE - 1;
4080 	struct bpf_func_state *caller, *cur;
4081 	struct bpf_reg_state *arg;
4082 
4083 	if (state->no_stack_arg_load) {
4084 		verbose(env, "r11 load must be before any r11 store or call insn\n");
4085 		return -EINVAL;
4086 	}
4087 
4088 	if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) {
4089 		verbose(env, "invalid read from stack arg off %d depth %d\n",
4090 			off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE);
4091 		return -EACCES;
4092 	}
4093 
4094 	caller = vstate->frame[vstate->curframe - 1];
4095 	arg = &caller->stack_arg_regs[spi];
4096 	cur = vstate->frame[vstate->curframe];
4097 	cur->regs[dst_regno] = *arg;
4098 	return bpf_push_jmp_history(env, env->cur_state,
4099 				    INSN_F_STACK_ARG_ACCESS, spi, 0, 0);
4100 }
4101 
4102 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)
4103 {
4104 	struct bpf_func_state *caller = cur_func(env);
4105 	int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;
4106 
4107 	bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi);
4108 	return mark_chain_precision_batch(env, env->cur_state);
4109 }
4110 
4111 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,
4112 				     int nargs)
4113 {
4114 	int i, spi;
4115 
4116 	for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) {
4117 		spi = i - MAX_BPF_FUNC_REG_ARGS;
4118 		if (spi >= caller->out_stack_arg_cnt ||
4119 		    caller->stack_arg_regs[spi].type == NOT_INIT) {
4120 			verbose(env, "callee expects %d args, stack arg%d is not initialized\n",
4121 				nargs, spi + 1);
4122 			return -EFAULT;
4123 		}
4124 	}
4125 
4126 	return 0;
4127 }
4128 
4129 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,
4130 					      struct bpf_reg_state *regs, int arg)
4131 {
4132 	if (arg < MAX_BPF_FUNC_REG_ARGS)
4133 		return &regs[arg + 1];
4134 
4135 	return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS];
4136 }
4137 
4138 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4139 				 int off, int size, enum bpf_access_type type)
4140 {
4141 	struct bpf_map *map = reg->map_ptr;
4142 	u32 cap = bpf_map_flags_to_cap(map);
4143 
4144 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4145 		verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n",
4146 			map->value_size, reg_smin(reg) + off, size);
4147 		return -EACCES;
4148 	}
4149 
4150 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4151 		verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n",
4152 			map->value_size, reg_smin(reg) + off, size);
4153 		return -EACCES;
4154 	}
4155 
4156 	return 0;
4157 }
4158 
4159 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4160 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4161 			      int off, int size, u32 mem_size,
4162 			      bool zero_size_allowed)
4163 {
4164 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4165 
4166 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4167 		return 0;
4168 
4169 	switch (reg->type) {
4170 	case PTR_TO_MAP_KEY:
4171 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4172 			mem_size, off, size);
4173 		break;
4174 	case PTR_TO_MAP_VALUE:
4175 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4176 			mem_size, off, size);
4177 		break;
4178 	case PTR_TO_PACKET:
4179 	case PTR_TO_PACKET_META:
4180 	case PTR_TO_PACKET_END:
4181 		verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n",
4182 			off, size, reg_arg_name(env, argno), reg->id, off, mem_size);
4183 		break;
4184 	case PTR_TO_CTX:
4185 		verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n",
4186 			mem_size, off, size);
4187 		break;
4188 	case PTR_TO_MEM:
4189 	default:
4190 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4191 			mem_size, off, size);
4192 	}
4193 
4194 	return -EACCES;
4195 }
4196 
4197 /* check read/write into a memory region with possible variable offset */
4198 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4199 				   int off, int size, u32 mem_size,
4200 				   bool zero_size_allowed)
4201 {
4202 	int err;
4203 
4204 	/* We may have adjusted the register pointing to memory region, so we
4205 	 * need to try adding each of min_value and max_value to off
4206 	 * to make sure our theoretical access will be safe.
4207 	 *
4208 	 * The minimum value is only important with signed
4209 	 * comparisons where we can't assume the floor of a
4210 	 * value is 0.  If we are using signed variables for our
4211 	 * index'es we need to make sure that whatever we use
4212 	 * will have a set floor within our range.
4213 	 */
4214 	if (reg_smin(reg) < 0 &&
4215 	    (reg_smin(reg) == S64_MIN ||
4216 	     (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) ||
4217 	      reg_smin(reg) + off < 0)) {
4218 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4219 			reg_arg_name(env, argno));
4220 		return -EACCES;
4221 	}
4222 	err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size,
4223 				 mem_size, zero_size_allowed);
4224 	if (err) {
4225 		verbose(env, "%s min value is outside of the allowed memory range\n",
4226 			reg_arg_name(env, argno));
4227 		return err;
4228 	}
4229 
4230 	/* If we haven't set a max value then we need to bail since we can't be
4231 	 * sure we won't do bad things.
4232 	 * If reg_umax(reg) + off could overflow, treat that as unbounded too.
4233 	 */
4234 	if (reg_umax(reg) >= BPF_MAX_VAR_OFF) {
4235 		verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n",
4236 			reg_arg_name(env, argno));
4237 		return -EACCES;
4238 	}
4239 	err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size,
4240 				 mem_size, zero_size_allowed);
4241 	if (err) {
4242 		verbose(env, "%s max value is outside of the allowed memory range\n",
4243 			reg_arg_name(env, argno));
4244 		return err;
4245 	}
4246 
4247 	return 0;
4248 }
4249 
4250 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4251 			       const struct bpf_reg_state *reg, argno_t argno,
4252 			       bool fixed_off_ok)
4253 {
4254 	/* Access to this pointer-typed register or passing it to a helper
4255 	 * is only allowed in its original, unmodified form.
4256 	 */
4257 
4258 	if (!tnum_is_const(reg->var_off)) {
4259 		char tn_buf[48];
4260 
4261 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4262 		verbose(env, "variable %s access var_off=%s disallowed\n",
4263 			reg_type_str(env, reg->type), tn_buf);
4264 		return -EACCES;
4265 	}
4266 
4267 	if (reg_smin(reg) < 0) {
4268 		verbose(env, "negative offset %s ptr %s off=%lld disallowed\n",
4269 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4270 		return -EACCES;
4271 	}
4272 
4273 	if (!fixed_off_ok && reg->var_off.value != 0) {
4274 		verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n",
4275 			reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value);
4276 		return -EACCES;
4277 	}
4278 
4279 	return 0;
4280 }
4281 
4282 static int check_ptr_off_reg(struct bpf_verifier_env *env,
4283 		             const struct bpf_reg_state *reg, int regno)
4284 {
4285 	return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
4286 }
4287 
4288 static int map_kptr_match_type(struct bpf_verifier_env *env,
4289 			       struct btf_field *kptr_field,
4290 			       struct bpf_reg_state *reg, u32 regno)
4291 {
4292 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4293 	int perm_flags;
4294 	const char *reg_name = "";
4295 
4296 	if (base_type(reg->type) != PTR_TO_BTF_ID)
4297 		goto bad_type;
4298 
4299 	if (btf_is_kernel(reg->btf)) {
4300 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4301 
4302 		/* Only unreferenced case accepts untrusted pointers */
4303 		if (kptr_field->type == BPF_KPTR_UNREF)
4304 			perm_flags |= PTR_UNTRUSTED;
4305 	} else {
4306 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
4307 		if (kptr_field->type == BPF_KPTR_PERCPU)
4308 			perm_flags |= MEM_PERCPU;
4309 	}
4310 
4311 	if (type_flag(reg->type) & ~perm_flags)
4312 		goto bad_type;
4313 
4314 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
4315 	reg_name = btf_type_name(reg->btf, reg->btf_id);
4316 
4317 	/* For ref_ptr case, release function check should ensure we get one
4318 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4319 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
4320 	 * Since ref_ptr cannot be accessed directly by BPF insns, check for
4321 	 * reg->id is not needed here.
4322 	 */
4323 	if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true))
4324 		return -EACCES;
4325 
4326 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
4327 	 * we also need to take into account the reg->var_off.
4328 	 *
4329 	 * We want to support cases like:
4330 	 *
4331 	 * struct foo {
4332 	 *         struct bar br;
4333 	 *         struct baz bz;
4334 	 * };
4335 	 *
4336 	 * struct foo *v;
4337 	 * v = func();	      // PTR_TO_BTF_ID
4338 	 * val->foo = v;      // reg->var_off is zero, btf and btf_id match type
4339 	 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with
4340 	 *                    // first member type of struct after comparison fails
4341 	 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked
4342 	 *                    // to match type
4343 	 *
4344 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off
4345 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
4346 	 * the struct to match type against first member of struct, i.e. reject
4347 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
4348 	 * strict mode to true for type match.
4349 	 */
4350 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value,
4351 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4352 				  kptr_field->type != BPF_KPTR_UNREF))
4353 		goto bad_type;
4354 	return 0;
4355 bad_type:
4356 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4357 		reg_type_str(env, reg->type), reg_name);
4358 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4359 	if (kptr_field->type == BPF_KPTR_UNREF)
4360 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4361 			targ_name);
4362 	else
4363 		verbose(env, "\n");
4364 	return -EINVAL;
4365 }
4366 
4367 static bool in_sleepable(struct bpf_verifier_env *env)
4368 {
4369 	return env->cur_state->in_sleepable;
4370 }
4371 
4372 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4373  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4374  */
4375 static bool in_rcu_cs(struct bpf_verifier_env *env)
4376 {
4377 	return env->cur_state->active_rcu_locks ||
4378 	       env->cur_state->active_locks ||
4379 	       !in_sleepable(env);
4380 }
4381 
4382 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4383 BTF_SET_START(rcu_protected_types)
4384 #ifdef CONFIG_NET
4385 BTF_ID(struct, prog_test_ref_kfunc)
4386 #endif
4387 #ifdef CONFIG_CGROUPS
4388 BTF_ID(struct, cgroup)
4389 #endif
4390 #ifdef CONFIG_BPF_JIT
4391 BTF_ID(struct, bpf_cpumask)
4392 #endif
4393 BTF_ID(struct, task_struct)
4394 #ifdef CONFIG_CRYPTO
4395 BTF_ID(struct, bpf_crypto_ctx)
4396 #endif
4397 BTF_SET_END(rcu_protected_types)
4398 
4399 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4400 {
4401 	if (!btf_is_kernel(btf))
4402 		return true;
4403 	return btf_id_set_contains(&rcu_protected_types, btf_id);
4404 }
4405 
4406 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
4407 {
4408 	struct btf_struct_meta *meta;
4409 
4410 	if (btf_is_kernel(kptr_field->kptr.btf))
4411 		return NULL;
4412 
4413 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
4414 				    kptr_field->kptr.btf_id);
4415 
4416 	return meta ? meta->record : NULL;
4417 }
4418 
4419 static bool rcu_safe_kptr(const struct btf_field *field)
4420 {
4421 	const struct btf_field_kptr *kptr = &field->kptr;
4422 
4423 	return field->type == BPF_KPTR_PERCPU ||
4424 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
4425 }
4426 
4427 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
4428 {
4429 	struct btf_record *rec;
4430 	u32 ret;
4431 
4432 	ret = PTR_MAYBE_NULL;
4433 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
4434 		ret |= MEM_RCU;
4435 		if (kptr_field->type == BPF_KPTR_PERCPU)
4436 			ret |= MEM_PERCPU;
4437 		else if (!btf_is_kernel(kptr_field->kptr.btf))
4438 			ret |= MEM_ALLOC;
4439 
4440 		rec = kptr_pointee_btf_record(kptr_field);
4441 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
4442 			ret |= NON_OWN_REF;
4443 	} else {
4444 		ret |= PTR_UNTRUSTED;
4445 	}
4446 
4447 	return ret;
4448 }
4449 
4450 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
4451 			    struct btf_field *field)
4452 {
4453 	struct bpf_reg_state *reg;
4454 	const struct btf_type *t;
4455 
4456 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
4457 	mark_reg_known_zero(env, cur_regs(env), regno);
4458 	reg = reg_state(env, regno);
4459 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
4460 	reg->mem_size = t->size;
4461 	reg->id = ++env->id_gen;
4462 
4463 	return 0;
4464 }
4465 
4466 static int check_map_kptr_access(struct bpf_verifier_env *env,
4467 				 int value_regno, int insn_idx,
4468 				 struct btf_field *kptr_field)
4469 {
4470 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4471 	int class = BPF_CLASS(insn->code);
4472 	struct bpf_reg_state *val_reg;
4473 	int ret;
4474 
4475 	/* Things we already checked for in check_map_access and caller:
4476 	 *  - Reject cases where variable offset may touch kptr
4477 	 *  - size of access (must be BPF_DW)
4478 	 *  - tnum_is_const(reg->var_off)
4479 	 *  - kptr_field->offset == off + reg->var_off.value
4480 	 */
4481 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4482 	if (BPF_MODE(insn->code) != BPF_MEM) {
4483 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4484 		return -EACCES;
4485 	}
4486 
4487 	/* We only allow loading referenced kptr, since it will be marked as
4488 	 * untrusted, similar to unreferenced kptr.
4489 	 */
4490 	if (class != BPF_LDX &&
4491 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
4492 		verbose(env, "store to referenced kptr disallowed\n");
4493 		return -EACCES;
4494 	}
4495 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
4496 		verbose(env, "store to uptr disallowed\n");
4497 		return -EACCES;
4498 	}
4499 
4500 	if (class == BPF_LDX) {
4501 		if (kptr_field->type == BPF_UPTR)
4502 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
4503 
4504 		/* We can simply mark the value_regno receiving the pointer
4505 		 * value from map as PTR_TO_BTF_ID, with the correct type.
4506 		 */
4507 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
4508 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4509 				      btf_ld_kptr_type(env, kptr_field));
4510 		if (ret < 0)
4511 			return ret;
4512 	} else if (class == BPF_STX) {
4513 		val_reg = reg_state(env, value_regno);
4514 		if (!bpf_register_is_null(val_reg) &&
4515 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4516 			return -EACCES;
4517 	} else if (class == BPF_ST) {
4518 		if (insn->imm) {
4519 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4520 				kptr_field->offset);
4521 			return -EACCES;
4522 		}
4523 	} else {
4524 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4525 		return -EACCES;
4526 	}
4527 	return 0;
4528 }
4529 
4530 /*
4531  * Return the size of the memory region accessible from a pointer to map value.
4532  * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
4533  */
4534 static u32 map_mem_size(const struct bpf_map *map)
4535 {
4536 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
4537 		return map->max_entries * sizeof(long);
4538 
4539 	return map->value_size;
4540 }
4541 
4542 /* check read/write into a map element with possible variable offset */
4543 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
4544 			    int off, int size, bool zero_size_allowed,
4545 			    enum bpf_access_src src)
4546 {
4547 	struct bpf_map *map = reg->map_ptr;
4548 	u32 mem_size = map_mem_size(map);
4549 	struct btf_record *rec;
4550 	int err, i;
4551 
4552 	err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed);
4553 	if (err)
4554 		return err;
4555 
4556 	if (IS_ERR_OR_NULL(map->record))
4557 		return 0;
4558 	rec = map->record;
4559 	for (i = 0; i < rec->cnt; i++) {
4560 		struct btf_field *field = &rec->fields[i];
4561 		u32 p = field->offset;
4562 
4563 		/* If any part of a field  can be touched by load/store, reject
4564 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
4565 		 * it is sufficient to check x1 < y2 && y1 < x2.
4566 		 */
4567 		if (reg_smin(reg) + off < p + field->size &&
4568 		    p < reg_umax(reg) + off + size) {
4569 			switch (field->type) {
4570 			case BPF_KPTR_UNREF:
4571 			case BPF_KPTR_REF:
4572 			case BPF_KPTR_PERCPU:
4573 			case BPF_UPTR:
4574 				if (src != ACCESS_DIRECT) {
4575 					verbose(env, "%s cannot be accessed indirectly by helper\n",
4576 						btf_field_type_name(field->type));
4577 					return -EACCES;
4578 				}
4579 				if (!tnum_is_const(reg->var_off)) {
4580 					verbose(env, "%s access cannot have variable offset\n",
4581 						btf_field_type_name(field->type));
4582 					return -EACCES;
4583 				}
4584 				if (p != off + reg->var_off.value) {
4585 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
4586 						btf_field_type_name(field->type),
4587 						p, off + reg->var_off.value);
4588 					return -EACCES;
4589 				}
4590 				if (size != bpf_size_to_bytes(BPF_DW)) {
4591 					verbose(env, "%s access size must be BPF_DW\n",
4592 						btf_field_type_name(field->type));
4593 					return -EACCES;
4594 				}
4595 				break;
4596 			default:
4597 				verbose(env, "%s cannot be accessed directly by load/store\n",
4598 					btf_field_type_name(field->type));
4599 				return -EACCES;
4600 			}
4601 		}
4602 	}
4603 	return 0;
4604 }
4605 
4606 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4607 			       const struct bpf_call_arg_meta *meta,
4608 			       enum bpf_access_type t)
4609 {
4610 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4611 
4612 	switch (prog_type) {
4613 	/* Program types only with direct read access go here! */
4614 	case BPF_PROG_TYPE_LWT_IN:
4615 	case BPF_PROG_TYPE_LWT_OUT:
4616 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4617 	case BPF_PROG_TYPE_SK_REUSEPORT:
4618 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4619 	case BPF_PROG_TYPE_CGROUP_SKB:
4620 		if (t == BPF_WRITE)
4621 			return false;
4622 		fallthrough;
4623 
4624 	/* Program types with direct read + write access go here! */
4625 	case BPF_PROG_TYPE_SCHED_CLS:
4626 	case BPF_PROG_TYPE_SCHED_ACT:
4627 	case BPF_PROG_TYPE_XDP:
4628 	case BPF_PROG_TYPE_LWT_XMIT:
4629 	case BPF_PROG_TYPE_SK_SKB:
4630 	case BPF_PROG_TYPE_SK_MSG:
4631 		if (meta)
4632 			return meta->pkt_access;
4633 
4634 		env->seen_direct_write = true;
4635 		return true;
4636 
4637 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4638 		if (t == BPF_WRITE)
4639 			env->seen_direct_write = true;
4640 
4641 		return true;
4642 
4643 	default:
4644 		return false;
4645 	}
4646 }
4647 
4648 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
4649 			       int size, bool zero_size_allowed)
4650 {
4651 	int err;
4652 
4653 	if (reg->range < 0) {
4654 		verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno));
4655 		return -EINVAL;
4656 	}
4657 
4658 	err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed);
4659 	if (err)
4660 		return err;
4661 
4662 	/* __check_mem_access has made sure "off + size - 1" is within u16.
4663 	 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff,
4664 	 * otherwise find_good_pkt_pointers would have refused to set range info
4665 	 * that __check_mem_access would have rejected this pkt access.
4666 	 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32.
4667 	 */
4668 	env->prog->aux->max_pkt_offset =
4669 		max_t(u32, env->prog->aux->max_pkt_offset,
4670 		      off + reg_umax(reg) + size - 1);
4671 
4672 	return 0;
4673 }
4674 
4675 static bool is_var_ctx_off_allowed(struct bpf_prog *prog)
4676 {
4677 	return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL;
4678 }
4679 
4680 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4681 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4682 			      enum bpf_access_type t, struct bpf_insn_access_aux *info)
4683 {
4684 	if (env->ops->is_valid_access &&
4685 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
4686 		/* A non zero info.ctx_field_size indicates that this field is a
4687 		 * candidate for later verifier transformation to load the whole
4688 		 * field and then apply a mask when accessed with a narrower
4689 		 * access than actual ctx access size. A zero info.ctx_field_size
4690 		 * will only allow for whole field access and rejects any other
4691 		 * type of narrower access.
4692 		 */
4693 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
4694 			if (info->ref_id &&
4695 			    !find_reference_state(env->cur_state, info->ref_id)) {
4696 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
4697 					off);
4698 				return -EACCES;
4699 			}
4700 		} else {
4701 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
4702 		}
4703 		/* remember the offset of last byte accessed in ctx */
4704 		if (env->prog->aux->max_ctx_offset < off + size)
4705 			env->prog->aux->max_ctx_offset = off + size;
4706 		return 0;
4707 	}
4708 
4709 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4710 	return -EACCES;
4711 }
4712 
4713 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
4714 			    int off, int access_size, enum bpf_access_type t,
4715 			    struct bpf_insn_access_aux *info)
4716 {
4717 	/*
4718 	 * Program types that don't rewrite ctx accesses can safely
4719 	 * dereference ctx pointers with fixed offsets.
4720 	 */
4721 	bool var_off_ok = is_var_ctx_off_allowed(env->prog);
4722 	bool fixed_off_ok = !env->ops->convert_ctx_access;
4723 	int err;
4724 
4725 	if (var_off_ok)
4726 		err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false);
4727 	else
4728 		err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok);
4729 	if (err)
4730 		return err;
4731 	off += reg_umax(reg);
4732 
4733 	err = __check_ctx_access(env, insn_idx, off, access_size, t, info);
4734 	if (err)
4735 		verbose_linfo(env, insn_idx, "; ");
4736 	return err;
4737 }
4738 
4739 static int check_flow_keys_access(struct bpf_verifier_env *env,
4740 				  struct bpf_reg_state *reg, argno_t argno,
4741 				  int off, int size)
4742 {
4743 	/* Only a constant offset is allowed here; fold it into off. */
4744 	if (!tnum_is_const(reg->var_off)) {
4745 		char tn_buf[48];
4746 
4747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4748 		verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n",
4749 			reg_arg_name(env, argno), off, tn_buf);
4750 		return -EACCES;
4751 	}
4752 	off += reg->var_off.value;
4753 
4754 	if (size < 0 || off < 0 ||
4755 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4756 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4757 			off, size);
4758 		return -EACCES;
4759 	}
4760 	return 0;
4761 }
4762 
4763 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4764 			     struct bpf_reg_state *reg, argno_t argno, int off, int size,
4765 			     enum bpf_access_type t)
4766 {
4767 	struct bpf_insn_access_aux info = {};
4768 	bool valid;
4769 
4770 	if (reg_smin(reg) < 0) {
4771 		verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4772 			reg_arg_name(env, argno));
4773 		return -EACCES;
4774 	}
4775 
4776 	switch (reg->type) {
4777 	case PTR_TO_SOCK_COMMON:
4778 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4779 		break;
4780 	case PTR_TO_SOCKET:
4781 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4782 		break;
4783 	case PTR_TO_TCP_SOCK:
4784 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4785 		break;
4786 	case PTR_TO_XDP_SOCK:
4787 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4788 		break;
4789 	default:
4790 		valid = false;
4791 	}
4792 
4793 
4794 	if (valid) {
4795 		env->insn_aux_data[insn_idx].ctx_field_size =
4796 			info.ctx_field_size;
4797 		return 0;
4798 	}
4799 
4800 	verbose(env, "%s invalid %s access off=%d size=%d\n",
4801 		reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size);
4802 
4803 	return -EACCES;
4804 }
4805 
4806 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4807 {
4808 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4809 }
4810 
4811 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4812 {
4813 	const struct bpf_reg_state *reg = reg_state(env, regno);
4814 
4815 	return reg->type == PTR_TO_CTX;
4816 }
4817 
4818 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4819 {
4820 	const struct bpf_reg_state *reg = reg_state(env, regno);
4821 
4822 	return type_is_sk_pointer(reg->type);
4823 }
4824 
4825 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4826 {
4827 	const struct bpf_reg_state *reg = reg_state(env, regno);
4828 
4829 	return type_is_pkt_pointer(reg->type);
4830 }
4831 
4832 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4833 {
4834 	const struct bpf_reg_state *reg = reg_state(env, regno);
4835 
4836 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4837 	return reg->type == PTR_TO_FLOW_KEYS;
4838 }
4839 
4840 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
4841 {
4842 	const struct bpf_reg_state *reg = reg_state(env, regno);
4843 
4844 	return reg->type == PTR_TO_ARENA;
4845 }
4846 
4847 /* Return false if @regno contains a pointer whose type isn't supported for
4848  * atomic instruction @insn.
4849  */
4850 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
4851 			       struct bpf_insn *insn)
4852 {
4853 	if (is_ctx_reg(env, regno))
4854 		return false;
4855 	if (is_pkt_reg(env, regno))
4856 		return false;
4857 	if (is_flow_key_reg(env, regno))
4858 		return false;
4859 	if (is_sk_reg(env, regno))
4860 		return false;
4861 	if (is_arena_reg(env, regno))
4862 		return bpf_jit_supports_insn(insn, true);
4863 
4864 	return true;
4865 }
4866 
4867 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
4868 #ifdef CONFIG_NET
4869 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
4870 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4871 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
4872 #endif
4873 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
4874 };
4875 
4876 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
4877 {
4878 	/* A referenced register is always trusted. */
4879 	if (reg_is_referenced(env, reg))
4880 		return true;
4881 
4882 	/* Types listed in the reg2btf_ids are always trusted */
4883 	if (reg2btf_ids[base_type(reg->type)] &&
4884 	    !bpf_type_has_unsafe_modifiers(reg->type))
4885 		return true;
4886 
4887 	/* If a register is not referenced, it is trusted if it has the
4888 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4889 	 * other type modifiers may be safe, but we elect to take an opt-in
4890 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4891 	 * not.
4892 	 *
4893 	 * Eventually, we should make PTR_TRUSTED the single source of truth
4894 	 * for whether a register is trusted.
4895 	 */
4896 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4897 	       !bpf_type_has_unsafe_modifiers(reg->type);
4898 }
4899 
4900 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4901 {
4902 	return reg->type & MEM_RCU;
4903 }
4904 
4905 static void clear_trusted_flags(enum bpf_type_flag *flag)
4906 {
4907 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
4908 }
4909 
4910 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4911 				   const struct bpf_reg_state *reg,
4912 				   int off, int size, bool strict)
4913 {
4914 	struct tnum reg_off;
4915 	int ip_align;
4916 
4917 	/* Byte size accesses are always allowed. */
4918 	if (!strict || size == 1)
4919 		return 0;
4920 
4921 	/* For platforms that do not have a Kconfig enabling
4922 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4923 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4924 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4925 	 * to this code only in strict mode where we want to emulate
4926 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4927 	 * unconditional IP align value of '2'.
4928 	 */
4929 	ip_align = 2;
4930 
4931 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off));
4932 	if (!tnum_is_aligned(reg_off, size)) {
4933 		char tn_buf[48];
4934 
4935 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4936 		verbose(env,
4937 			"misaligned packet access off %d+%s+%d size %d\n",
4938 			ip_align, tn_buf, off, size);
4939 		return -EACCES;
4940 	}
4941 
4942 	return 0;
4943 }
4944 
4945 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4946 				       const struct bpf_reg_state *reg,
4947 				       const char *pointer_desc,
4948 				       int off, int size, bool strict)
4949 {
4950 	struct tnum reg_off;
4951 
4952 	/* Byte size accesses are always allowed. */
4953 	if (!strict || size == 1)
4954 		return 0;
4955 
4956 	reg_off = tnum_add(reg->var_off, tnum_const(off));
4957 	if (!tnum_is_aligned(reg_off, size)) {
4958 		char tn_buf[48];
4959 
4960 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4961 		verbose(env, "misaligned %saccess off %s+%d size %d\n",
4962 			pointer_desc, tn_buf, off, size);
4963 		return -EACCES;
4964 	}
4965 
4966 	return 0;
4967 }
4968 
4969 static int check_ptr_alignment(struct bpf_verifier_env *env,
4970 			       const struct bpf_reg_state *reg, int off,
4971 			       int size, bool strict_alignment_once)
4972 {
4973 	bool strict = env->strict_alignment || strict_alignment_once;
4974 	const char *pointer_desc = "";
4975 
4976 	switch (reg->type) {
4977 	case PTR_TO_PACKET:
4978 	case PTR_TO_PACKET_META:
4979 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4980 		 * right in front, treat it the very same way.
4981 		 */
4982 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4983 	case PTR_TO_FLOW_KEYS:
4984 		pointer_desc = "flow keys ";
4985 		break;
4986 	case PTR_TO_MAP_KEY:
4987 		pointer_desc = "key ";
4988 		break;
4989 	case PTR_TO_MAP_VALUE:
4990 		pointer_desc = "value ";
4991 		if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
4992 			strict = true;
4993 		break;
4994 	case PTR_TO_CTX:
4995 		pointer_desc = "context ";
4996 		break;
4997 	case PTR_TO_STACK:
4998 		pointer_desc = "stack ";
4999 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5000 		 * and check_stack_read_fixed_off() relies on stack accesses being
5001 		 * aligned.
5002 		 */
5003 		strict = true;
5004 		break;
5005 	case PTR_TO_SOCKET:
5006 		pointer_desc = "sock ";
5007 		break;
5008 	case PTR_TO_SOCK_COMMON:
5009 		pointer_desc = "sock_common ";
5010 		break;
5011 	case PTR_TO_TCP_SOCK:
5012 		pointer_desc = "tcp_sock ";
5013 		break;
5014 	case PTR_TO_XDP_SOCK:
5015 		pointer_desc = "xdp_sock ";
5016 		break;
5017 	case PTR_TO_ARENA:
5018 		return 0;
5019 	default:
5020 		break;
5021 	}
5022 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5023 					   strict);
5024 }
5025 
5026 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
5027 {
5028 	if (!bpf_jit_supports_private_stack())
5029 		return NO_PRIV_STACK;
5030 
5031 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
5032 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
5033 	 * explicitly.
5034 	 */
5035 	switch (prog->type) {
5036 	case BPF_PROG_TYPE_KPROBE:
5037 	case BPF_PROG_TYPE_TRACEPOINT:
5038 	case BPF_PROG_TYPE_PERF_EVENT:
5039 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5040 		return PRIV_STACK_ADAPTIVE;
5041 	case BPF_PROG_TYPE_TRACING:
5042 	case BPF_PROG_TYPE_LSM:
5043 	case BPF_PROG_TYPE_STRUCT_OPS:
5044 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
5045 			return PRIV_STACK_ADAPTIVE;
5046 		fallthrough;
5047 	default:
5048 		break;
5049 	}
5050 
5051 	return NO_PRIV_STACK;
5052 }
5053 
5054 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5055 {
5056 	if (env->prog->jit_requested)
5057 		return round_up(stack_depth, 16);
5058 
5059 	/* round up to 32-bytes, since this is granularity
5060 	 * of interpreter stack size
5061 	 */
5062 	return round_up(max_t(u32, stack_depth, 1), 32);
5063 }
5064 
5065 /* temporary state used for call frame depth calculation */
5066 struct bpf_subprog_call_depth_info {
5067 	int ret_insn; /* caller instruction where we return to. */
5068 	int caller; /* caller subprogram idx */
5069 	int frame; /* # of consecutive static call stack frames on top of stack */
5070 };
5071 
5072 /* starting from main bpf function walk all instructions of the function
5073  * and recursively walk all callees that given function can call.
5074  * Ignore jump and exit insns.
5075  */
5076 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
5077 					 struct bpf_subprog_call_depth_info *dinfo,
5078 					 bool priv_stack_supported)
5079 {
5080 	struct bpf_subprog_info *subprog = env->subprog_info;
5081 	struct bpf_insn *insn = env->prog->insnsi;
5082 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
5083 	bool tail_call_reachable = false;
5084 	int total;
5085 	int tmp;
5086 
5087 	/* no caller idx */
5088 	dinfo[idx].caller = -1;
5089 
5090 	i = subprog[idx].start;
5091 	if (!priv_stack_supported)
5092 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5093 process_func:
5094 	/* protect against potential stack overflow that might happen when
5095 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5096 	 * depth for such case down to 256 so that the worst case scenario
5097 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5098 	 * 8k).
5099 	 *
5100 	 * To get the idea what might happen, see an example:
5101 	 * func1 -> sub rsp, 128
5102 	 *  subfunc1 -> sub rsp, 256
5103 	 *  tailcall1 -> add rsp, 256
5104 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5105 	 *   subfunc2 -> sub rsp, 64
5106 	 *   subfunc22 -> sub rsp, 128
5107 	 *   tailcall2 -> add rsp, 128
5108 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5109 	 *
5110 	 * tailcall will unwind the current stack frame but it will not get rid
5111 	 * of caller's stack as shown on the example above.
5112 	 */
5113 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5114 		verbose(env,
5115 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5116 			depth);
5117 		return -EACCES;
5118 	}
5119 
5120 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
5121 	if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) {
5122 		/* x86-64 uses R9 for both private stack frame pointer and arg6. */
5123 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5124 	} else if (priv_stack_supported) {
5125 		/* Request private stack support only if the subprog stack
5126 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
5127 		 * avoid jit penalty if the stack usage is small.
5128 		 */
5129 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
5130 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
5131 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
5132 	}
5133 
5134 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5135 		if (subprog_depth > env->max_stack_depth)
5136 			env->max_stack_depth = subprog_depth;
5137 		if (subprog_depth > MAX_BPF_STACK) {
5138 			verbose(env, "stack size of subprog %d is %d. Too large\n",
5139 				idx, subprog_depth);
5140 			return -EACCES;
5141 		}
5142 	} else {
5143 		depth += subprog_depth;
5144 		if (depth > env->max_stack_depth)
5145 			env->max_stack_depth = depth;
5146 		if (depth > MAX_BPF_STACK) {
5147 			total = 0;
5148 			for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller)
5149 				total++;
5150 
5151 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
5152 				total, depth);
5153 			return -EACCES;
5154 		}
5155 	}
5156 continue_func:
5157 	subprog_end = subprog[idx + 1].start;
5158 	for (; i < subprog_end; i++) {
5159 		int next_insn, sidx;
5160 
5161 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5162 			bool err = false;
5163 
5164 			if (!bpf_is_throw_kfunc(insn + i))
5165 				continue;
5166 			for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) {
5167 				if (subprog[tmp].is_cb) {
5168 					err = true;
5169 					break;
5170 				}
5171 			}
5172 			if (!err)
5173 				continue;
5174 			verbose(env,
5175 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5176 				i, idx);
5177 			return -EINVAL;
5178 		}
5179 
5180 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5181 			continue;
5182 		/* remember insn and function to return to */
5183 
5184 		/* find the callee */
5185 		next_insn = i + insn[i].imm + 1;
5186 		sidx = bpf_find_subprog(env, next_insn);
5187 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
5188 			return -EFAULT;
5189 		if (subprog[sidx].is_async_cb) {
5190 			if (subprog[sidx].has_tail_call) {
5191 				verifier_bug(env, "subprog has tail_call and async cb");
5192 				return -EFAULT;
5193 			}
5194 			/* async callbacks don't increase bpf prog stack size unless called directly */
5195 			if (!bpf_pseudo_call(insn + i))
5196 				continue;
5197 			if (subprog[sidx].is_exception_cb) {
5198 				verbose(env, "insn %d cannot call exception cb directly", i);
5199 				return -EINVAL;
5200 			}
5201 		}
5202 
5203 		/* store caller info for after we return from callee */
5204 		dinfo[idx].frame = frame;
5205 		dinfo[idx].ret_insn = i + 1;
5206 
5207 		/* push caller idx into callee's dinfo */
5208 		dinfo[sidx].caller = idx;
5209 
5210 		i = next_insn;
5211 
5212 		idx = sidx;
5213 		if (!priv_stack_supported)
5214 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
5215 
5216 		if (subprog[idx].has_tail_call)
5217 			tail_call_reachable = true;
5218 
5219 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
5220 		if (frame >= MAX_CALL_FRAMES) {
5221 			verbose(env, "the call stack of %d frames is too deep !\n",
5222 				frame);
5223 			return -E2BIG;
5224 		}
5225 		goto process_func;
5226 	}
5227 	/* if tail call got detected across bpf2bpf calls then mark each of the
5228 	 * currently present subprog frames as tail call reachable subprogs;
5229 	 * this info will be utilized by JIT so that we will be preserving the
5230 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5231 	 */
5232 	if (tail_call_reachable) {
5233 		for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) {
5234 			if (subprog[tmp].is_exception_cb) {
5235 				verbose(env, "cannot tail call within exception cb\n");
5236 				return -EINVAL;
5237 			}
5238 			if (subprog[tmp].stack_arg_cnt) {
5239 				verbose(env, "tail_calls are not allowed in programs with stack args\n");
5240 				return -EINVAL;
5241 			}
5242 			subprog[tmp].tail_call_reachable = true;
5243 		}
5244 	} else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) {
5245 		verbose(env, "tail_calls are not allowed in programs with stack args\n");
5246 		return -EINVAL;
5247 	}
5248 
5249 	if (subprog[0].tail_call_reachable)
5250 		env->prog->aux->tail_call_reachable = true;
5251 
5252 	/* end of for() loop means the last insn of the 'subprog'
5253 	 * was reached. Doesn't matter whether it was JA or EXIT
5254 	 */
5255 	if (frame == 0 && dinfo[idx].caller < 0)
5256 		return 0;
5257 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
5258 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5259 
5260 	/* pop caller idx from callee */
5261 	idx = dinfo[idx].caller;
5262 
5263 	/* retrieve caller state from its frame */
5264 	frame = dinfo[idx].frame;
5265 	i = dinfo[idx].ret_insn;
5266 
5267 	/* reset tail_call_reachable to the parent's actual state */
5268 	tail_call_reachable = subprog[idx].tail_call_reachable;
5269 
5270 	goto continue_func;
5271 }
5272 
5273 static int check_max_stack_depth(struct bpf_verifier_env *env)
5274 {
5275 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
5276 	struct bpf_subprog_call_depth_info *dinfo;
5277 	struct bpf_subprog_info *si = env->subprog_info;
5278 	bool priv_stack_supported;
5279 	int ret;
5280 
5281 	dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT);
5282 	if (!dinfo)
5283 		return -ENOMEM;
5284 
5285 	for (int i = 0; i < env->subprog_cnt; i++) {
5286 		if (si[i].has_tail_call) {
5287 			priv_stack_mode = NO_PRIV_STACK;
5288 			break;
5289 		}
5290 	}
5291 
5292 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
5293 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
5294 
5295 	/* All async_cb subprogs use normal kernel stack. If a particular
5296 	 * subprog appears in both main prog and async_cb subtree, that
5297 	 * subprog will use normal kernel stack to avoid potential nesting.
5298 	 * The reverse subprog traversal ensures when main prog subtree is
5299 	 * checked, the subprogs appearing in async_cb subtrees are already
5300 	 * marked as using normal kernel stack, so stack size checking can
5301 	 * be done properly.
5302 	 */
5303 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
5304 		if (!i || si[i].is_async_cb) {
5305 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
5306 			ret = check_max_stack_depth_subprog(env, i, dinfo,
5307 					priv_stack_supported);
5308 			if (ret < 0) {
5309 				kvfree(dinfo);
5310 				return ret;
5311 			}
5312 		}
5313 	}
5314 
5315 	for (int i = 0; i < env->subprog_cnt; i++) {
5316 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
5317 			env->prog->aux->jits_use_priv_stack = true;
5318 			break;
5319 		}
5320 	}
5321 
5322 	kvfree(dinfo);
5323 
5324 	return 0;
5325 }
5326 
5327 static int __check_buffer_access(struct bpf_verifier_env *env,
5328 				 const char *buf_info,
5329 				 const struct bpf_reg_state *reg,
5330 				 argno_t argno, int off, int size,
5331 				 u32 *access_end)
5332 {
5333 	s64 start;
5334 
5335 	if (!tnum_is_const(reg->var_off)) {
5336 		char tn_buf[48];
5337 
5338 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5339 		verbose(env,
5340 			"%s invalid variable buffer offset: off=%d, var_off=%s\n",
5341 			reg_arg_name(env, argno), off, tn_buf);
5342 		return -EACCES;
5343 	}
5344 
5345 	start = (s64)reg->var_off.value + off;
5346 	if (start < 0) {
5347 		verbose(env,
5348 			"%s invalid negative %s buffer offset: off=%d, var_off=%lld\n",
5349 			reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value);
5350 		return -EACCES;
5351 	}
5352 
5353 	*access_end = start + size;
5354 	return 0;
5355 }
5356 
5357 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5358 				  const struct bpf_reg_state *reg,
5359 				  argno_t argno, int off, int size)
5360 {
5361 	u32 access_end;
5362 	int err;
5363 
5364 	err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end);
5365 	if (err)
5366 		return err;
5367 
5368 	env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access);
5369 
5370 	return 0;
5371 }
5372 
5373 static int check_buffer_access(struct bpf_verifier_env *env,
5374 			       const struct bpf_reg_state *reg,
5375 			       argno_t argno, int off, int size,
5376 			       bool zero_size_allowed,
5377 			       u32 *max_access)
5378 {
5379 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5380 	u32 access_end;
5381 	int err;
5382 
5383 	err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end);
5384 	if (err)
5385 		return err;
5386 
5387 	*max_access = max(access_end, *max_access);
5388 
5389 	return 0;
5390 }
5391 
5392 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5393 static void zext_32_to_64(struct bpf_reg_state *reg)
5394 {
5395 	reg->var_off = tnum_subreg(reg->var_off);
5396 	reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg));
5397 }
5398 
5399 /* truncate register to smaller size (in bytes)
5400  * must be called with size < BPF_REG_SIZE
5401  */
5402 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5403 {
5404 	u64 mask;
5405 
5406 	/* clear high bits in bit representation */
5407 	reg->var_off = tnum_cast(reg->var_off, size);
5408 
5409 	/* fix arithmetic bounds */
5410 	mask = ((u64)1 << (size * 8)) - 1;
5411 	if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask))
5412 		reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask);
5413 	else
5414 		reg_set_urange64(reg, 0, mask);
5415 
5416 	/* If size is smaller than 32bit register the 32bit register
5417 	 * values are also truncated so we push 64-bit bounds into
5418 	 * 32-bit bounds. Above were truncated < 32-bits already.
5419 	 */
5420 	if (size < 4)
5421 		__mark_reg32_unbounded(reg);
5422 
5423 	reg_bounds_sync(reg);
5424 }
5425 
5426 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5427 {
5428 	if (size == 1) {
5429 		reg_set_srange64(reg, S8_MIN, S8_MAX);
5430 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5431 	} else if (size == 2) {
5432 		reg_set_srange64(reg, S16_MIN, S16_MAX);
5433 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5434 	} else {
5435 		/* size == 4 */
5436 		reg_set_srange64(reg, S32_MIN, S32_MAX);
5437 		reg_set_srange32(reg, S32_MIN, S32_MAX);
5438 	}
5439 	reg->var_off = tnum_unknown;
5440 }
5441 
5442 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5443 {
5444 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5445 	u64 top_smax_value, top_smin_value;
5446 	u64 num_bits = size * 8;
5447 
5448 	if (tnum_is_const(reg->var_off)) {
5449 		u64_cval = reg->var_off.value;
5450 		if (size == 1)
5451 			reg->var_off = tnum_const((s8)u64_cval);
5452 		else if (size == 2)
5453 			reg->var_off = tnum_const((s16)u64_cval);
5454 		else
5455 			/* size == 4 */
5456 			reg->var_off = tnum_const((s32)u64_cval);
5457 
5458 		u64_cval = reg->var_off.value;
5459 		reg->r64 = cnum64_from_urange(u64_cval, u64_cval);
5460 		reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval);
5461 		return;
5462 	}
5463 
5464 	top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits;
5465 	top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits;
5466 
5467 	if (top_smax_value != top_smin_value)
5468 		goto out;
5469 
5470 	/* find the s64_min and s64_min after sign extension */
5471 	if (size == 1) {
5472 		init_s64_max = (s8)reg_smax(reg);
5473 		init_s64_min = (s8)reg_smin(reg);
5474 	} else if (size == 2) {
5475 		init_s64_max = (s16)reg_smax(reg);
5476 		init_s64_min = (s16)reg_smin(reg);
5477 	} else {
5478 		init_s64_max = (s32)reg_smax(reg);
5479 		init_s64_min = (s32)reg_smin(reg);
5480 	}
5481 
5482 	s64_max = max(init_s64_max, init_s64_min);
5483 	s64_min = min(init_s64_max, init_s64_min);
5484 
5485 	/* both of s64_max/s64_min positive or negative */
5486 	if ((s64_max >= 0) == (s64_min >= 0)) {
5487 		reg_set_srange64(reg, s64_min, s64_max);
5488 		reg_set_srange32(reg, s64_min, s64_max);
5489 		reg->var_off = tnum_range(s64_min, s64_max);
5490 		return;
5491 	}
5492 
5493 out:
5494 	set_sext64_default_val(reg, size);
5495 }
5496 
5497 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5498 {
5499 	if (size == 1)
5500 		reg_set_srange32(reg, S8_MIN, S8_MAX);
5501 	else
5502 		/* size == 2 */
5503 		reg_set_srange32(reg, S16_MIN, S16_MAX);
5504 	reg->var_off = tnum_subreg(tnum_unknown);
5505 }
5506 
5507 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5508 {
5509 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5510 	u32 top_smax_value, top_smin_value;
5511 	u32 num_bits = size * 8;
5512 
5513 	if (tnum_is_const(reg->var_off)) {
5514 		u32_val = reg->var_off.value;
5515 		if (size == 1)
5516 			reg->var_off = tnum_const((s8)u32_val);
5517 		else
5518 			reg->var_off = tnum_const((s16)u32_val);
5519 
5520 		u32_val = reg->var_off.value;
5521 		reg_set_srange32(reg, u32_val, u32_val);
5522 		return;
5523 	}
5524 
5525 	top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits;
5526 	top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits;
5527 
5528 	if (top_smax_value != top_smin_value)
5529 		goto out;
5530 
5531 	/* find the s32_min and s32_min after sign extension */
5532 	if (size == 1) {
5533 		init_s32_max = (s8)reg_s32_max(reg);
5534 		init_s32_min = (s8)reg_s32_min(reg);
5535 	} else {
5536 		/* size == 2 */
5537 		init_s32_max = (s16)reg_s32_max(reg);
5538 		init_s32_min = (s16)reg_s32_min(reg);
5539 	}
5540 	s32_max = max(init_s32_max, init_s32_min);
5541 	s32_min = min(init_s32_max, init_s32_min);
5542 
5543 	if ((s32_min >= 0) == (s32_max >= 0)) {
5544 		reg_set_srange32(reg, s32_min, s32_max);
5545 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
5546 		return;
5547 	}
5548 
5549 out:
5550 	set_sext32_default_val(reg, size);
5551 }
5552 
5553 bool bpf_map_is_rdonly(const struct bpf_map *map)
5554 {
5555 	/* A map is considered read-only if the following condition are true:
5556 	 *
5557 	 * 1) BPF program side cannot change any of the map content. The
5558 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5559 	 *    and was set at map creation time.
5560 	 * 2) The map value(s) have been initialized from user space by a
5561 	 *    loader and then "frozen", such that no new map update/delete
5562 	 *    operations from syscall side are possible for the rest of
5563 	 *    the map's lifetime from that point onwards.
5564 	 * 3) Any parallel/pending map update/delete operations from syscall
5565 	 *    side have been completed. Only after that point, it's safe to
5566 	 *    assume that map value(s) are immutable.
5567 	 */
5568 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
5569 	       READ_ONCE(map->frozen) &&
5570 	       !bpf_map_write_active(map);
5571 }
5572 
5573 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5574 			bool is_ldsx)
5575 {
5576 	void *ptr;
5577 	u64 addr;
5578 	int err;
5579 
5580 	err = map->ops->map_direct_value_addr(map, &addr, off);
5581 	if (err)
5582 		return err;
5583 	ptr = (void *)(long)addr + off;
5584 
5585 	switch (size) {
5586 	case sizeof(u8):
5587 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
5588 		break;
5589 	case sizeof(u16):
5590 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
5591 		break;
5592 	case sizeof(u32):
5593 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
5594 		break;
5595 	case sizeof(u64):
5596 		*val = *(u64 *)ptr;
5597 		break;
5598 	default:
5599 		return -EINVAL;
5600 	}
5601 	return 0;
5602 }
5603 
5604 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5605 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5606 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5607 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
5608 
5609 /*
5610  * Allow list few fields as RCU trusted or full trusted.
5611  * This logic doesn't allow mix tagging and will be removed once GCC supports
5612  * btf_type_tag.
5613  */
5614 
5615 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5616 BTF_TYPE_SAFE_RCU(struct task_struct) {
5617 	const cpumask_t *cpus_ptr;
5618 	struct css_set __rcu *cgroups;
5619 	struct task_struct __rcu *real_parent;
5620 	struct task_struct *group_leader;
5621 };
5622 
5623 BTF_TYPE_SAFE_RCU(struct cgroup) {
5624 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5625 	struct kernfs_node *kn;
5626 };
5627 
5628 BTF_TYPE_SAFE_RCU(struct css_set) {
5629 	struct cgroup *dfl_cgrp;
5630 };
5631 
5632 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
5633 	struct cgroup *cgroup;
5634 };
5635 
5636 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5637 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5638 	struct file __rcu *exe_file;
5639 #ifdef CONFIG_MEMCG
5640 	struct task_struct __rcu *owner;
5641 #endif
5642 };
5643 
5644 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5645  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5646  */
5647 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5648 	struct sock *sk;
5649 };
5650 
5651 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5652 	struct sock *sk;
5653 };
5654 
5655 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5656 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5657 	struct seq_file *seq;
5658 };
5659 
5660 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5661 	struct bpf_iter_meta *meta;
5662 	struct task_struct *task;
5663 };
5664 
5665 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5666 	struct file *file;
5667 };
5668 
5669 BTF_TYPE_SAFE_TRUSTED(struct file) {
5670 	struct inode *f_inode;
5671 };
5672 
5673 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
5674 	struct inode *d_inode;
5675 };
5676 
5677 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
5678 	struct sock *sk;
5679 };
5680 
5681 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
5682 	struct mm_struct *vm_mm;
5683 	struct file *vm_file;
5684 };
5685 
5686 static bool type_is_rcu(struct bpf_verifier_env *env,
5687 			struct bpf_reg_state *reg,
5688 			const char *field_name, u32 btf_id)
5689 {
5690 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5691 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5692 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5693 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
5694 
5695 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5696 }
5697 
5698 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5699 				struct bpf_reg_state *reg,
5700 				const char *field_name, u32 btf_id)
5701 {
5702 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5703 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5704 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5705 
5706 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5707 }
5708 
5709 static bool type_is_trusted(struct bpf_verifier_env *env,
5710 			    struct bpf_reg_state *reg,
5711 			    const char *field_name, u32 btf_id)
5712 {
5713 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5714 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5715 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5716 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5717 
5718 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5719 }
5720 
5721 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
5722 				    struct bpf_reg_state *reg,
5723 				    const char *field_name, u32 btf_id)
5724 {
5725 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
5726 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
5727 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
5728 
5729 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
5730 					  "__safe_trusted_or_null");
5731 }
5732 
5733 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5734 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
5735 				   argno_t argno, int off, int size,
5736 				   enum bpf_access_type atype,
5737 				   int value_regno)
5738 {
5739 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5740 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5741 	const char *field_name = NULL;
5742 	enum bpf_type_flag flag = 0;
5743 	u32 btf_id = 0;
5744 	int ret;
5745 
5746 	if (!env->allow_ptr_leaks) {
5747 		verbose(env,
5748 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5749 			tname);
5750 		return -EPERM;
5751 	}
5752 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5753 		verbose(env,
5754 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5755 			tname);
5756 		return -EINVAL;
5757 	}
5758 
5759 	if (!tnum_is_const(reg->var_off)) {
5760 		char tn_buf[48];
5761 
5762 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5763 		verbose(env,
5764 			"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5765 			reg_arg_name(env, argno), tname, off, tn_buf);
5766 		return -EACCES;
5767 	}
5768 
5769 	off += reg->var_off.value;
5770 
5771 	if (off < 0) {
5772 		verbose(env,
5773 			"%s is ptr_%s invalid negative access: off=%d\n",
5774 			reg_arg_name(env, argno), tname, off);
5775 		return -EACCES;
5776 	}
5777 
5778 	if (reg->type & MEM_USER) {
5779 		verbose(env,
5780 			"%s is ptr_%s access user memory: off=%d\n",
5781 			reg_arg_name(env, argno), tname, off);
5782 		return -EACCES;
5783 	}
5784 
5785 	if (reg->type & MEM_PERCPU) {
5786 		verbose(env,
5787 			"%s is ptr_%s access percpu memory: off=%d\n",
5788 			reg_arg_name(env, argno), tname, off);
5789 		return -EACCES;
5790 	}
5791 
5792 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5793 		if (!btf_is_kernel(reg->btf)) {
5794 			verifier_bug(env, "reg->btf must be kernel btf");
5795 			return -EFAULT;
5796 		}
5797 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5798 		if (ret < 0)
5799 			verbose(env,
5800 				"%s cannot write into ptr_%s at off=%d size=%d\n",
5801 				reg_arg_name(env, argno), tname, off, size);
5802 	} else {
5803 		/* Writes are permitted with default btf_struct_access for
5804 		 * program allocated objects (which always have id > 0),
5805 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5806 		 */
5807 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
5808 			verbose(env, "only read is supported\n");
5809 			return -EACCES;
5810 		}
5811 
5812 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5813 		    !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) {
5814 			verifier_bug(env, "allocated object must have a referenced id");
5815 			return -EFAULT;
5816 		}
5817 
5818 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5819 	}
5820 
5821 	if (ret < 0)
5822 		return ret;
5823 
5824 	if (ret != PTR_TO_BTF_ID) {
5825 		/* just mark; */
5826 
5827 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5828 		/* If this is an untrusted pointer, all pointers formed by walking it
5829 		 * also inherit the untrusted flag.
5830 		 */
5831 		flag = PTR_UNTRUSTED;
5832 
5833 	} else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) {
5834 		/* By default any pointer obtained from walking a trusted pointer is no
5835 		 * longer trusted, unless the field being accessed has explicitly been
5836 		 * marked as inheriting its parent's state of trust (either full or RCU).
5837 		 * For example:
5838 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
5839 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
5840 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5841 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5842 		 *
5843 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
5844 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
5845 		 */
5846 		if (type_is_trusted(env, reg, field_name, btf_id)) {
5847 			flag |= PTR_TRUSTED;
5848 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
5849 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
5850 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5851 			if (type_is_rcu(env, reg, field_name, btf_id)) {
5852 				/* ignore __rcu tag and mark it MEM_RCU */
5853 				flag |= MEM_RCU;
5854 			} else if (flag & MEM_RCU ||
5855 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5856 				/* __rcu tagged pointers can be NULL */
5857 				flag |= MEM_RCU | PTR_MAYBE_NULL;
5858 
5859 				/* We always trust them */
5860 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
5861 				    flag & PTR_UNTRUSTED)
5862 					flag &= ~PTR_UNTRUSTED;
5863 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
5864 				/* keep as-is */
5865 			} else {
5866 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5867 				clear_trusted_flags(&flag);
5868 			}
5869 		} else {
5870 			/*
5871 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
5872 			 * aggressively mark as untrusted otherwise such
5873 			 * pointers will be plain PTR_TO_BTF_ID without flags
5874 			 * and will be allowed to be passed into helpers for
5875 			 * compat reasons.
5876 			 */
5877 			flag = PTR_UNTRUSTED;
5878 		}
5879 	} else {
5880 		/* Old compat. Deprecated */
5881 		clear_trusted_flags(&flag);
5882 	}
5883 
5884 	if (atype == BPF_READ && value_regno >= 0) {
5885 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5886 		if (ret < 0)
5887 			return ret;
5888 	}
5889 
5890 	return 0;
5891 }
5892 
5893 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5894 				   struct bpf_reg_state *regs, struct bpf_reg_state *reg,
5895 				   argno_t argno, int off, int size,
5896 				   enum bpf_access_type atype,
5897 				   int value_regno)
5898 {
5899 	struct bpf_map *map = reg->map_ptr;
5900 	struct bpf_reg_state map_reg;
5901 	enum bpf_type_flag flag = 0;
5902 	const struct btf_type *t;
5903 	const char *tname;
5904 	u32 btf_id;
5905 	int ret;
5906 
5907 	if (!btf_vmlinux) {
5908 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5909 		return -ENOTSUPP;
5910 	}
5911 
5912 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5913 		verbose(env, "map_ptr access not supported for map type %d\n",
5914 			map->map_type);
5915 		return -ENOTSUPP;
5916 	}
5917 
5918 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5919 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5920 
5921 	if (!env->allow_ptr_leaks) {
5922 		verbose(env,
5923 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5924 			tname);
5925 		return -EPERM;
5926 	}
5927 
5928 	if (off < 0) {
5929 		verbose(env, "%s is %s invalid negative access: off=%d\n",
5930 			reg_arg_name(env, argno), tname, off);
5931 		return -EACCES;
5932 	}
5933 
5934 	if (atype != BPF_READ) {
5935 		verbose(env, "only read from %s is supported\n", tname);
5936 		return -EACCES;
5937 	}
5938 
5939 	/* Simulate access to a PTR_TO_BTF_ID */
5940 	memset(&map_reg, 0, sizeof(map_reg));
5941 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
5942 			      btf_vmlinux, *map->ops->map_btf_id, 0);
5943 	if (ret < 0)
5944 		return ret;
5945 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5946 	if (ret < 0)
5947 		return ret;
5948 
5949 	if (value_regno >= 0) {
5950 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5951 		if (ret < 0)
5952 			return ret;
5953 	}
5954 
5955 	return 0;
5956 }
5957 
5958 /* Check that the stack access at the given offset is within bounds. The
5959  * maximum valid offset is -1.
5960  *
5961  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5962  * -state->allocated_stack for reads.
5963  */
5964 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
5965                                           s64 off,
5966                                           struct bpf_func_state *state,
5967                                           enum bpf_access_type t)
5968 {
5969 	int min_valid_off;
5970 
5971 	if (t == BPF_WRITE || env->allow_uninit_stack)
5972 		min_valid_off = -MAX_BPF_STACK;
5973 	else
5974 		min_valid_off = -state->allocated_stack;
5975 
5976 	if (off < min_valid_off || off > -1)
5977 		return -EACCES;
5978 	return 0;
5979 }
5980 
5981 /* Check that the stack access at 'regno + off' falls within the maximum stack
5982  * bounds.
5983  *
5984  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5985  */
5986 static int check_stack_access_within_bounds(
5987 		struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5988 		argno_t argno, int off, int access_size,
5989 		enum bpf_access_type type)
5990 {
5991 	struct bpf_func_state *state = bpf_func(env, reg);
5992 	s64 min_off, max_off;
5993 	int err;
5994 	char *err_extra;
5995 
5996 	if (type == BPF_READ)
5997 		err_extra = " read from";
5998 	else
5999 		err_extra = " write to";
6000 
6001 	if (tnum_is_const(reg->var_off)) {
6002 		min_off = (s64)reg->var_off.value + off;
6003 		max_off = min_off + access_size;
6004 	} else {
6005 		if (reg_smax(reg) >= BPF_MAX_VAR_OFF ||
6006 		    reg_smin(reg) <= -BPF_MAX_VAR_OFF) {
6007 			verbose(env, "invalid unbounded variable-offset%s stack %s\n",
6008 				err_extra, reg_arg_name(env, argno));
6009 			return -EACCES;
6010 		}
6011 		min_off = reg_smin(reg) + off;
6012 		max_off = reg_smax(reg) + off + access_size;
6013 	}
6014 
6015 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6016 	if (!err && max_off > 0)
6017 		err = -EINVAL; /* out of stack access into non-negative offsets */
6018 	if (!err && access_size < 0)
6019 		/* access_size should not be negative (or overflow an int); others checks
6020 		 * along the way should have prevented such an access.
6021 		 */
6022 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6023 
6024 	if (err) {
6025 		if (tnum_is_const(reg->var_off)) {
6026 			verbose(env, "invalid%s stack %s off=%lld size=%d\n",
6027 				err_extra, reg_arg_name(env, argno), min_off, access_size);
6028 		} else {
6029 			char tn_buf[48];
6030 
6031 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6032 			verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n",
6033 				err_extra, reg_arg_name(env, argno), tn_buf, off, access_size);
6034 		}
6035 		return err;
6036 	}
6037 
6038 	/* Note that there is no stack access with offset zero, so the needed stack
6039 	 * size is -min_off, not -min_off+1.
6040 	 */
6041 	return grow_stack_state(env, state, -min_off /* size */);
6042 }
6043 
6044 static bool get_func_retval_range(struct bpf_prog *prog,
6045 				  struct bpf_retval_range *range)
6046 {
6047 	if (prog->type == BPF_PROG_TYPE_LSM &&
6048 		prog->expected_attach_type == BPF_LSM_MAC &&
6049 		!bpf_lsm_get_retval_range(prog, range)) {
6050 		return true;
6051 	}
6052 	return false;
6053 }
6054 
6055 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val)
6056 {
6057 	struct bpf_reg_state fake_reg;
6058 
6059 	if (!val)
6060 		return;
6061 
6062 	fake_reg.type = SCALAR_VALUE;
6063 	__mark_reg_known(&fake_reg, val);
6064 
6065 	scalar32_min_max_add(dst_reg, &fake_reg);
6066 	scalar_min_max_add(dst_reg, &fake_reg);
6067 	dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off);
6068 
6069 	reg_bounds_sync(dst_reg);
6070 }
6071 
6072 /* check whether memory at (regno + off) is accessible for t = (read | write)
6073  * if t==write, value_regno is a register which value is stored into memory
6074  * if t==read, value_regno is a register which will receive the value from memory
6075  * if t==write && value_regno==-1, some unknown value is stored into memory
6076  * if t==read && value_regno==-1, don't care what we read from memory
6077  */
6078 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,
6079 			    int off, int bpf_size, enum bpf_access_type t,
6080 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6081 {
6082 	struct bpf_reg_state *regs = cur_regs(env);
6083 	int size, err = 0;
6084 
6085 	size = bpf_size_to_bytes(bpf_size);
6086 	if (size < 0)
6087 		return size;
6088 
6089 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6090 	if (err)
6091 		return err;
6092 
6093 	if (reg->type == PTR_TO_MAP_KEY) {
6094 		if (t == BPF_WRITE) {
6095 			verbose(env, "write to change key %s not allowed\n",
6096 				reg_arg_name(env, argno));
6097 			return -EACCES;
6098 		}
6099 
6100 		err = check_mem_region_access(env, reg, argno, off, size,
6101 					      reg->map_ptr->key_size, false);
6102 		if (err)
6103 			return err;
6104 		if (value_regno >= 0)
6105 			mark_reg_unknown(env, regs, value_regno);
6106 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6107 		struct btf_field *kptr_field = NULL;
6108 
6109 		if (t == BPF_WRITE && value_regno >= 0 &&
6110 		    is_pointer_value(env, value_regno)) {
6111 			verbose(env, "R%d leaks addr into map\n", value_regno);
6112 			return -EACCES;
6113 		}
6114 		err = check_map_access_type(env, reg, off, size, t);
6115 		if (err)
6116 			return err;
6117 		err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT);
6118 		if (err)
6119 			return err;
6120 		if (tnum_is_const(reg->var_off))
6121 			kptr_field = btf_record_find(reg->map_ptr->record,
6122 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
6123 		if (kptr_field) {
6124 			err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field);
6125 		} else if (t == BPF_READ && value_regno >= 0) {
6126 			struct bpf_map *map = reg->map_ptr;
6127 
6128 			/*
6129 			 * If map is read-only, track its contents as scalars,
6130 			 * unless it is an insn array (see the special case below)
6131 			 */
6132 			if (tnum_is_const(reg->var_off) &&
6133 			    bpf_map_is_rdonly(map) &&
6134 			    map->ops->map_direct_value_addr &&
6135 			    map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
6136 				int map_off = off + reg->var_off.value;
6137 				u64 val = 0;
6138 
6139 				err = bpf_map_direct_read(map, map_off, size,
6140 							  &val, is_ldsx);
6141 				if (err)
6142 					return err;
6143 
6144 				regs[value_regno].type = SCALAR_VALUE;
6145 				__mark_reg_known(&regs[value_regno], val);
6146 			} else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
6147 				if (bpf_size != BPF_DW) {
6148 					verbose(env, "Invalid read of %d bytes from insn_array\n",
6149 						     size);
6150 					return -EACCES;
6151 				}
6152 				regs[value_regno] = *reg;
6153 				add_scalar_to_reg(&regs[value_regno], off);
6154 				regs[value_regno].type = PTR_TO_INSN;
6155 			} else {
6156 				mark_reg_unknown(env, regs, value_regno);
6157 			}
6158 		}
6159 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6160 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6161 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
6162 
6163 		if (type_may_be_null(reg->type)) {
6164 			verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6165 				reg_type_str(env, reg->type));
6166 			return -EACCES;
6167 		}
6168 
6169 		if (t == BPF_WRITE && rdonly_mem) {
6170 			verbose(env, "%s cannot write into %s\n",
6171 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6172 			return -EACCES;
6173 		}
6174 
6175 		if (t == BPF_WRITE && value_regno >= 0 &&
6176 		    is_pointer_value(env, value_regno)) {
6177 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6178 			return -EACCES;
6179 		}
6180 
6181 		/*
6182 		 * Accesses to untrusted PTR_TO_MEM are done through probe
6183 		 * instructions, hence no need to check bounds in that case.
6184 		 */
6185 		if (!rdonly_untrusted)
6186 			err = check_mem_region_access(env, reg, argno, off, size,
6187 						      reg->mem_size, false);
6188 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6189 			mark_reg_unknown(env, regs, value_regno);
6190 	} else if (reg->type == PTR_TO_CTX) {
6191 		struct bpf_insn_access_aux info = {
6192 			.reg_type = SCALAR_VALUE,
6193 			.is_ldsx = is_ldsx,
6194 			.log = &env->log,
6195 		};
6196 		struct bpf_retval_range range;
6197 
6198 		if (t == BPF_WRITE && value_regno >= 0 &&
6199 		    is_pointer_value(env, value_regno)) {
6200 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6201 			return -EACCES;
6202 		}
6203 
6204 		err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info);
6205 		if (!err && t == BPF_READ && value_regno >= 0) {
6206 			/* ctx access returns either a scalar, or a
6207 			 * PTR_TO_PACKET[_META,_END]. In the latter
6208 			 * case, we know the offset is zero.
6209 			 */
6210 			if (info.reg_type == SCALAR_VALUE) {
6211 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
6212 					mark_reg_unknown(env, regs, value_regno);
6213 					err = __mark_reg_s32_range(env, regs, value_regno,
6214 								   range.minval, range.maxval);
6215 					if (err)
6216 						return err;
6217 				} else {
6218 					mark_reg_unknown(env, regs, value_regno);
6219 				}
6220 			} else {
6221 				mark_reg_known_zero(env, regs,
6222 						    value_regno);
6223 				/* A load of ctx field could have different
6224 				 * actual load size with the one encoded in the
6225 				 * insn. When the dst is PTR, it is for sure not
6226 				 * a sub-register.
6227 				 */
6228 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6229 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
6230 					regs[value_regno].btf = info.btf;
6231 					regs[value_regno].btf_id = info.btf_id;
6232 					regs[value_regno].id = info.ref_id;
6233 				}
6234 				if (type_may_be_null(info.reg_type) && !regs[value_regno].id)
6235 					regs[value_regno].id = ++env->id_gen;
6236 			}
6237 			regs[value_regno].type = info.reg_type;
6238 		}
6239 
6240 	} else if (reg->type == PTR_TO_STACK) {
6241 		/* Basic bounds checks. */
6242 		err = check_stack_access_within_bounds(env, reg, argno, off, size, t);
6243 		if (err)
6244 			return err;
6245 
6246 		if (t == BPF_READ)
6247 			err = check_stack_read(env, reg, argno, off, size,
6248 					       value_regno);
6249 		else
6250 			err = check_stack_write(env, reg, off, size,
6251 						value_regno, insn_idx);
6252 	} else if (reg_is_pkt_pointer(reg)) {
6253 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6254 			verbose(env, "cannot write into packet\n");
6255 			return -EACCES;
6256 		}
6257 		if (t == BPF_WRITE && value_regno >= 0 &&
6258 		    is_pointer_value(env, value_regno)) {
6259 			verbose(env, "R%d leaks addr into packet\n",
6260 				value_regno);
6261 			return -EACCES;
6262 		}
6263 		err = check_packet_access(env, reg, argno, off, size, false);
6264 		if (!err && t == BPF_READ && value_regno >= 0)
6265 			mark_reg_unknown(env, regs, value_regno);
6266 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6267 		if (t == BPF_WRITE && value_regno >= 0 &&
6268 		    is_pointer_value(env, value_regno)) {
6269 			verbose(env, "R%d leaks addr into flow keys\n",
6270 				value_regno);
6271 			return -EACCES;
6272 		}
6273 
6274 		err = check_flow_keys_access(env, reg, argno, off, size);
6275 		if (!err && t == BPF_READ && value_regno >= 0)
6276 			mark_reg_unknown(env, regs, value_regno);
6277 	} else if (type_is_sk_pointer(reg->type)) {
6278 		if (t == BPF_WRITE) {
6279 			verbose(env, "%s cannot write into %s\n",
6280 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6281 			return -EACCES;
6282 		}
6283 		err = check_sock_access(env, insn_idx, reg, argno, off, size, t);
6284 		if (!err && value_regno >= 0)
6285 			mark_reg_unknown(env, regs, value_regno);
6286 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6287 		err = check_tp_buffer_access(env, reg, argno, off, size);
6288 		if (!err && t == BPF_READ && value_regno >= 0)
6289 			mark_reg_unknown(env, regs, value_regno);
6290 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6291 		   !type_may_be_null(reg->type)) {
6292 		err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t,
6293 					      value_regno);
6294 	} else if (reg->type == CONST_PTR_TO_MAP) {
6295 		err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t,
6296 					      value_regno);
6297 	} else if (base_type(reg->type) == PTR_TO_BUF &&
6298 		   !type_may_be_null(reg->type)) {
6299 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6300 		u32 *max_access;
6301 
6302 		if (rdonly_mem) {
6303 			if (t == BPF_WRITE) {
6304 				verbose(env, "%s cannot write into %s\n",
6305 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6306 				return -EACCES;
6307 			}
6308 			max_access = &env->prog->aux->max_rdonly_access;
6309 		} else {
6310 			max_access = &env->prog->aux->max_rdwr_access;
6311 		}
6312 
6313 		err = check_buffer_access(env, reg, argno, off, size, false,
6314 					  max_access);
6315 
6316 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6317 			mark_reg_unknown(env, regs, value_regno);
6318 	} else if (reg->type == PTR_TO_ARENA) {
6319 		if (t == BPF_READ && value_regno >= 0)
6320 			mark_reg_unknown(env, regs, value_regno);
6321 	} else {
6322 		verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno),
6323 			reg_type_str(env, reg->type));
6324 		return -EACCES;
6325 	}
6326 
6327 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6328 	    regs[value_regno].type == SCALAR_VALUE) {
6329 		if (!is_ldsx)
6330 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6331 			coerce_reg_to_size(&regs[value_regno], size);
6332 		else
6333 			coerce_reg_to_size_sx(&regs[value_regno], size);
6334 	}
6335 	return err;
6336 }
6337 
6338 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
6339 			     bool allow_trust_mismatch);
6340 
6341 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
6342 			  bool strict_alignment_once, bool is_ldsx,
6343 			  bool allow_trust_mismatch, const char *ctx)
6344 {
6345 	struct bpf_verifier_state *vstate = env->cur_state;
6346 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6347 	struct bpf_reg_state *regs = cur_regs(env);
6348 	enum bpf_reg_type src_reg_type;
6349 	int err;
6350 
6351 	/* Handle stack arg read */
6352 	if (is_stack_arg_ldx(insn)) {
6353 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6354 		if (err)
6355 			return err;
6356 		return check_stack_arg_read(env, state, insn->off, insn->dst_reg);
6357 	}
6358 
6359 	/* check src operand */
6360 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6361 	if (err)
6362 		return err;
6363 
6364 	/* check dst operand */
6365 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6366 	if (err)
6367 		return err;
6368 
6369 	src_reg_type = regs[insn->src_reg].type;
6370 
6371 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
6372 	 * updated by this call.
6373 	 */
6374 	err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off,
6375 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
6376 			       strict_alignment_once, is_ldsx);
6377 	err = err ?: save_aux_ptr_type(env, src_reg_type,
6378 				       allow_trust_mismatch);
6379 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
6380 
6381 	return err;
6382 }
6383 
6384 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
6385 			   bool strict_alignment_once)
6386 {
6387 	struct bpf_verifier_state *vstate = env->cur_state;
6388 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6389 	struct bpf_reg_state *regs = cur_regs(env);
6390 	enum bpf_reg_type dst_reg_type;
6391 	int err;
6392 
6393 	/* Handle stack arg write */
6394 	if (is_stack_arg_stx(insn)) {
6395 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
6396 		if (err)
6397 			return err;
6398 		return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg);
6399 	}
6400 
6401 	/* check src1 operand */
6402 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6403 	if (err)
6404 		return err;
6405 
6406 	/* check src2 operand */
6407 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6408 	if (err)
6409 		return err;
6410 
6411 	dst_reg_type = regs[insn->dst_reg].type;
6412 
6413 	/* Check if (dst_reg + off) is writeable. */
6414 	err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6415 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
6416 			       strict_alignment_once, false);
6417 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
6418 
6419 	return err;
6420 }
6421 
6422 static int check_atomic_rmw(struct bpf_verifier_env *env,
6423 			    struct bpf_insn *insn)
6424 {
6425 	struct bpf_reg_state *dst_reg;
6426 	int load_reg;
6427 	int err;
6428 
6429 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6430 		verbose(env, "invalid atomic operand size\n");
6431 		return -EINVAL;
6432 	}
6433 
6434 	/* check src1 operand */
6435 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6436 	if (err)
6437 		return err;
6438 
6439 	/* check src2 operand */
6440 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6441 	if (err)
6442 		return err;
6443 
6444 	if (insn->imm == BPF_CMPXCHG) {
6445 		/* Check comparison of R0 with memory location */
6446 		const u32 aux_reg = BPF_REG_0;
6447 
6448 		err = check_reg_arg(env, aux_reg, SRC_OP);
6449 		if (err)
6450 			return err;
6451 
6452 		if (is_pointer_value(env, aux_reg)) {
6453 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6454 			return -EACCES;
6455 		}
6456 	}
6457 
6458 	if (is_pointer_value(env, insn->src_reg)) {
6459 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6460 		return -EACCES;
6461 	}
6462 
6463 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6464 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6465 			insn->dst_reg,
6466 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6467 		return -EACCES;
6468 	}
6469 
6470 	if (insn->imm & BPF_FETCH) {
6471 		if (insn->imm == BPF_CMPXCHG)
6472 			load_reg = BPF_REG_0;
6473 		else
6474 			load_reg = insn->src_reg;
6475 
6476 		/* check and record load of old value */
6477 		err = check_reg_arg(env, load_reg, DST_OP);
6478 		if (err)
6479 			return err;
6480 	} else {
6481 		/* This instruction accesses a memory location but doesn't
6482 		 * actually load it into a register.
6483 		 */
6484 		load_reg = -1;
6485 	}
6486 
6487 	dst_reg = cur_regs(env) + insn->dst_reg;
6488 
6489 	/* Check whether we can read the memory, with second call for fetch
6490 	 * case to simulate the register fill.
6491 	 */
6492 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6493 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6494 	if (!err && load_reg >= 0)
6495 		err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg),
6496 				       insn->off, BPF_SIZE(insn->code),
6497 				       BPF_READ, load_reg, true, false);
6498 	if (err)
6499 		return err;
6500 
6501 	if (is_arena_reg(env, insn->dst_reg)) {
6502 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
6503 		if (err)
6504 			return err;
6505 	}
6506 	/* Check whether we can write into the same memory. */
6507 	err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off,
6508 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6509 	if (err)
6510 		return err;
6511 	return 0;
6512 }
6513 
6514 static int check_atomic_load(struct bpf_verifier_env *env,
6515 			     struct bpf_insn *insn)
6516 {
6517 	int err;
6518 
6519 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
6520 	if (err)
6521 		return err;
6522 
6523 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
6524 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
6525 			insn->src_reg,
6526 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
6527 		return -EACCES;
6528 	}
6529 
6530 	return 0;
6531 }
6532 
6533 static int check_atomic_store(struct bpf_verifier_env *env,
6534 			      struct bpf_insn *insn)
6535 {
6536 	int err;
6537 
6538 	err = check_store_reg(env, insn, true);
6539 	if (err)
6540 		return err;
6541 
6542 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
6543 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6544 			insn->dst_reg,
6545 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6546 		return -EACCES;
6547 	}
6548 
6549 	return 0;
6550 }
6551 
6552 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
6553 {
6554 	switch (insn->imm) {
6555 	case BPF_ADD:
6556 	case BPF_ADD | BPF_FETCH:
6557 	case BPF_AND:
6558 	case BPF_AND | BPF_FETCH:
6559 	case BPF_OR:
6560 	case BPF_OR | BPF_FETCH:
6561 	case BPF_XOR:
6562 	case BPF_XOR | BPF_FETCH:
6563 	case BPF_XCHG:
6564 	case BPF_CMPXCHG:
6565 		return check_atomic_rmw(env, insn);
6566 	case BPF_LOAD_ACQ:
6567 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6568 			verbose(env,
6569 				"64-bit load-acquires are only supported on 64-bit arches\n");
6570 			return -EOPNOTSUPP;
6571 		}
6572 		return check_atomic_load(env, insn);
6573 	case BPF_STORE_REL:
6574 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
6575 			verbose(env,
6576 				"64-bit store-releases are only supported on 64-bit arches\n");
6577 			return -EOPNOTSUPP;
6578 		}
6579 		return check_atomic_store(env, insn);
6580 	default:
6581 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
6582 			insn->imm);
6583 		return -EINVAL;
6584 	}
6585 }
6586 
6587 /* When register 'regno' is used to read the stack (either directly or through
6588  * a helper function) make sure that it's within stack boundary and, depending
6589  * on the access type and privileges, that all elements of the stack are
6590  * initialized.
6591  *
6592  * All registers that have been spilled on the stack in the slots within the
6593  * read offsets are marked as read.
6594  */
6595 static int check_stack_range_initialized(
6596 		struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off,
6597 		int access_size, bool zero_size_allowed,
6598 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
6599 {
6600 	struct bpf_func_state *state = bpf_func(env, reg);
6601 	int err, min_off, max_off, i, j, slot, spi;
6602 	/* Some accesses can write anything into the stack, others are
6603 	 * read-only.
6604 	 */
6605 	bool clobber = type == BPF_WRITE;
6606 	/*
6607 	 * Negative access_size signals global subprog/kfunc arg check where
6608 	 * STACK_POISON slots are acceptable. static stack liveness
6609 	 * might have determined that subprog doesn't read them,
6610 	 * but BTF based global subprog validation isn't accurate enough.
6611 	 */
6612 	bool allow_poison = access_size < 0 || clobber;
6613 
6614 	access_size = abs(access_size);
6615 
6616 	if (access_size == 0 && !zero_size_allowed) {
6617 		verbose(env, "invalid zero-sized read\n");
6618 		return -EACCES;
6619 	}
6620 
6621 	err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type);
6622 	if (err)
6623 		return err;
6624 
6625 
6626 	if (tnum_is_const(reg->var_off)) {
6627 		min_off = max_off = reg->var_off.value + off;
6628 	} else {
6629 		/* Variable offset is prohibited for unprivileged mode for
6630 		 * simplicity since it requires corresponding support in
6631 		 * Spectre masking for stack ALU.
6632 		 * See also retrieve_ptr_limit().
6633 		 */
6634 		if (!env->bypass_spec_v1) {
6635 			char tn_buf[48];
6636 
6637 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6638 			verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n",
6639 				reg_arg_name(env, argno), tn_buf);
6640 			return -EACCES;
6641 		}
6642 		/* Only initialized buffer on stack is allowed to be accessed
6643 		 * with variable offset. With uninitialized buffer it's hard to
6644 		 * guarantee that whole memory is marked as initialized on
6645 		 * helper return since specific bounds are unknown what may
6646 		 * cause uninitialized stack leaking.
6647 		 */
6648 		if (meta && meta->raw_mode)
6649 			meta = NULL;
6650 
6651 		min_off = reg_smin(reg) + off;
6652 		max_off = reg_smax(reg) + off;
6653 	}
6654 
6655 	if (meta && meta->raw_mode) {
6656 		/* Ensure we won't be overwriting dynptrs when simulating byte
6657 		 * by byte access in check_helper_call using meta.access_size.
6658 		 * This would be a problem if we have a helper in the future
6659 		 * which takes:
6660 		 *
6661 		 *	helper(uninit_mem, len, dynptr)
6662 		 *
6663 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6664 		 * may end up writing to dynptr itself when touching memory from
6665 		 * arg 1. This can be relaxed on a case by case basis for known
6666 		 * safe cases, but reject due to the possibilitiy of aliasing by
6667 		 * default.
6668 		 */
6669 		for (i = min_off; i < max_off + access_size; i++) {
6670 			int stack_off = -i - 1;
6671 
6672 			spi = bpf_get_spi(i);
6673 			/* raw_mode may write past allocated_stack */
6674 			if (state->allocated_stack <= stack_off)
6675 				continue;
6676 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6677 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6678 				return -EACCES;
6679 			}
6680 		}
6681 		meta->access_size = access_size;
6682 		meta->regno = reg_from_argno(argno);
6683 		return 0;
6684 	}
6685 
6686 	for (i = min_off; i < max_off + access_size; i++) {
6687 		u8 *stype;
6688 
6689 		slot = -i - 1;
6690 		spi = slot / BPF_REG_SIZE;
6691 		if (state->allocated_stack <= slot) {
6692 			verbose(env, "allocated_stack too small\n");
6693 			return -EFAULT;
6694 		}
6695 
6696 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6697 		if (*stype == STACK_MISC)
6698 			goto mark;
6699 		if ((*stype == STACK_ZERO) ||
6700 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6701 			if (clobber) {
6702 				/* helper can write anything into the stack */
6703 				*stype = STACK_MISC;
6704 			}
6705 			goto mark;
6706 		}
6707 
6708 		if (bpf_is_spilled_reg(&state->stack[spi]) &&
6709 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6710 		     env->allow_ptr_leaks)) {
6711 			if (clobber) {
6712 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6713 				for (j = 0; j < BPF_REG_SIZE; j++)
6714 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6715 			}
6716 			goto mark;
6717 		}
6718 
6719 		if (*stype == STACK_POISON) {
6720 			if (allow_poison)
6721 				goto mark;
6722 			verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n",
6723 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6724 		} else if (tnum_is_const(reg->var_off)) {
6725 			verbose(env, "invalid read from stack %s off %d+%d size %d\n",
6726 				reg_arg_name(env, argno), min_off, i - min_off, access_size);
6727 		} else {
6728 			char tn_buf[48];
6729 
6730 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6731 			verbose(env, "invalid read from stack %s var_off %s+%d size %d\n",
6732 				reg_arg_name(env, argno), tn_buf, i - min_off, access_size);
6733 		}
6734 		return -EACCES;
6735 mark:
6736 		;
6737 	}
6738 	return 0;
6739 }
6740 
6741 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
6742 				   int access_size, enum bpf_access_type access_type,
6743 				   bool zero_size_allowed,
6744 				   struct bpf_call_arg_meta *meta)
6745 {
6746 	struct bpf_reg_state *regs = cur_regs(env);
6747 	u32 *max_access;
6748 
6749 	switch (base_type(reg->type)) {
6750 	case PTR_TO_PACKET:
6751 	case PTR_TO_PACKET_META:
6752 		return check_packet_access(env, reg, argno, 0, access_size,
6753 					   zero_size_allowed);
6754 	case PTR_TO_MAP_KEY:
6755 		if (access_type == BPF_WRITE) {
6756 			verbose(env, "%s cannot write into %s\n",
6757 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
6758 			return -EACCES;
6759 		}
6760 		return check_mem_region_access(env, reg, argno, 0, access_size,
6761 					       reg->map_ptr->key_size, false);
6762 	case PTR_TO_MAP_VALUE:
6763 		if (check_map_access_type(env, reg, 0, access_size, access_type))
6764 			return -EACCES;
6765 		return check_map_access(env, reg, argno, 0, access_size,
6766 					zero_size_allowed, ACCESS_HELPER);
6767 	case PTR_TO_MEM:
6768 		if (type_is_rdonly_mem(reg->type)) {
6769 			if (access_type == BPF_WRITE) {
6770 				verbose(env, "%s cannot write into %s\n",
6771 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6772 				return -EACCES;
6773 			}
6774 		}
6775 		return check_mem_region_access(env, reg, argno, 0,
6776 					       access_size, reg->mem_size,
6777 					       zero_size_allowed);
6778 	case PTR_TO_BUF:
6779 		if (type_is_rdonly_mem(reg->type)) {
6780 			if (access_type == BPF_WRITE) {
6781 				verbose(env, "%s cannot write into %s\n",
6782 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
6783 				return -EACCES;
6784 			}
6785 
6786 			max_access = &env->prog->aux->max_rdonly_access;
6787 		} else {
6788 			max_access = &env->prog->aux->max_rdwr_access;
6789 		}
6790 		return check_buffer_access(env, reg, argno, 0,
6791 					   access_size, zero_size_allowed,
6792 					   max_access);
6793 	case PTR_TO_STACK:
6794 		return check_stack_range_initialized(
6795 				env, reg,
6796 				argno, 0, access_size,
6797 				zero_size_allowed, access_type, meta);
6798 	case PTR_TO_BTF_ID:
6799 		return check_ptr_to_btf_access(env, regs, reg, argno, 0,
6800 					       access_size, access_type, -1);
6801 	case PTR_TO_CTX:
6802 		/* Only permit reading or writing syscall context using helper calls. */
6803 		if (is_var_ctx_off_allowed(env->prog)) {
6804 			int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX,
6805 							  zero_size_allowed);
6806 			if (err)
6807 				return err;
6808 			if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size)
6809 				env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size;
6810 			return 0;
6811 		}
6812 		fallthrough;
6813 	default: /* scalar_value or invalid ptr */
6814 		/* Allow zero-byte read from NULL, regardless of pointer type */
6815 		if (zero_size_allowed && access_size == 0 &&
6816 		    bpf_register_is_null(reg))
6817 			return 0;
6818 
6819 		verbose(env, "%s type=%s ", reg_arg_name(env, argno),
6820 			reg_type_str(env, reg->type));
6821 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6822 		return -EACCES;
6823 	}
6824 }
6825 
6826 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
6827  * size.
6828  *
6829  * @mem_reg contains the pointer, @size_reg contains the access size.
6830  */
6831 static int check_mem_size_reg(struct bpf_verifier_env *env,
6832 			      struct bpf_reg_state *mem_reg,
6833 			      struct bpf_reg_state *size_reg, argno_t mem_argno,
6834 			      argno_t size_argno, enum bpf_access_type access_type,
6835 			      bool zero_size_allowed,
6836 			      struct bpf_call_arg_meta *meta)
6837 {
6838 	int err;
6839 
6840 	/* This is used to refine r0 return value bounds for helpers
6841 	 * that enforce this value as an upper bound on return values.
6842 	 * See do_refine_retval_range() for helpers that can refine
6843 	 * the return value. C type of helper is u32 so we pull register
6844 	 * bound from umax_value however, if negative verifier errors
6845 	 * out. Only upper bounds can be learned because retval is an
6846 	 * int type and negative retvals are allowed.
6847 	 */
6848 	meta->msize_max_value = reg_umax(size_reg);
6849 
6850 	/* The register is SCALAR_VALUE; the access check happens using
6851 	 * its boundaries. For unprivileged variable accesses, disable
6852 	 * raw mode so that the program is required to initialize all
6853 	 * the memory that the helper could just partially fill up.
6854 	 */
6855 	if (!tnum_is_const(size_reg->var_off))
6856 		meta = NULL;
6857 
6858 	if (reg_smin(size_reg) < 0) {
6859 		verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n",
6860 			reg_arg_name(env, size_argno));
6861 		return -EACCES;
6862 	}
6863 
6864 	if (reg_umin(size_reg) == 0 && !zero_size_allowed) {
6865 		verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n",
6866 			reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg));
6867 		return -EACCES;
6868 	}
6869 
6870 	if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) {
6871 		verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6872 			reg_arg_name(env, size_argno));
6873 		return -EACCES;
6874 	}
6875 	err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg),
6876 				      access_type, zero_size_allowed, meta);
6877 	if (!err) {
6878 		int regno = reg_from_argno(size_argno);
6879 
6880 		if (regno >= 0)
6881 			err = mark_chain_precision(env, regno);
6882 		else
6883 			err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno));
6884 	}
6885 	return err;
6886 }
6887 
6888 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6889 			 argno_t argno, u32 mem_size)
6890 {
6891 	bool may_be_null = type_may_be_null(reg->type);
6892 	struct bpf_reg_state saved_reg;
6893 	int err;
6894 
6895 	if (bpf_register_is_null(reg))
6896 		return 0;
6897 
6898 	if (mem_size > S32_MAX) {
6899 		verbose(env, "%s memory size %u is too large\n",
6900 			reg_arg_name(env, argno), mem_size);
6901 		return -EACCES;
6902 	}
6903 
6904 	/* Assuming that the register contains a value check if the memory
6905 	 * access is safe. Temporarily save and restore the register's state as
6906 	 * the conversion shouldn't be visible to a caller.
6907 	 */
6908 	if (may_be_null) {
6909 		saved_reg = *reg;
6910 		mark_ptr_not_null_reg(reg);
6911 	}
6912 
6913 	int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size;
6914 
6915 	err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL);
6916 	err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL);
6917 
6918 	if (may_be_null)
6919 		*reg = saved_reg;
6920 
6921 	return err;
6922 }
6923 
6924 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg,
6925 				    struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno)
6926 {
6927 	bool may_be_null = type_may_be_null(mem_reg->type);
6928 	struct bpf_reg_state saved_reg;
6929 	struct bpf_call_arg_meta meta;
6930 	int err;
6931 
6932 	memset(&meta, 0, sizeof(meta));
6933 
6934 	if (may_be_null) {
6935 		saved_reg = *mem_reg;
6936 		mark_ptr_not_null_reg(mem_reg);
6937 	}
6938 
6939 	err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta);
6940 	err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta);
6941 
6942 	if (may_be_null)
6943 		*mem_reg = saved_reg;
6944 
6945 	return err;
6946 }
6947 
6948 enum {
6949 	PROCESS_SPIN_LOCK = (1 << 0),
6950 	PROCESS_RES_LOCK  = (1 << 1),
6951 	PROCESS_LOCK_IRQ  = (1 << 2),
6952 };
6953 
6954 /* Implementation details:
6955  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6956  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6957  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6958  * Two separate bpf_obj_new will also have different reg->id.
6959  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6960  * clears reg->id after value_or_null->value transition, since the verifier only
6961  * cares about the range of access to valid map value pointer and doesn't care
6962  * about actual address of the map element.
6963  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6964  * reg->id > 0 after value_or_null->value transition. By doing so
6965  * two bpf_map_lookups will be considered two different pointers that
6966  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6967  * returned from bpf_obj_new.
6968  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6969  * dead-locks.
6970  * Since only one bpf_spin_lock is allowed the checks are simpler than
6971  * reg_is_refcounted() logic. The verifier needs to remember only
6972  * one spin_lock instead of array of acquired_refs.
6973  * env->cur_state->active_locks remembers which map value element or allocated
6974  * object got locked and clears it after bpf_spin_unlock.
6975  */
6976 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags)
6977 {
6978 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
6979 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
6980 	struct bpf_verifier_state *cur = env->cur_state;
6981 	bool is_const = tnum_is_const(reg->var_off);
6982 	bool is_irq = flags & PROCESS_LOCK_IRQ;
6983 	u64 val = reg->var_off.value;
6984 	struct bpf_map *map = NULL;
6985 	struct btf *btf = NULL;
6986 	struct btf_record *rec;
6987 	u32 spin_lock_off;
6988 	int err;
6989 
6990 	if (!is_const) {
6991 		verbose(env,
6992 			"%s doesn't have constant offset. %s_lock has to be at the constant offset\n",
6993 			reg_arg_name(env, argno), lock_str);
6994 		return -EINVAL;
6995 	}
6996 	if (reg->type == PTR_TO_MAP_VALUE) {
6997 		map = reg->map_ptr;
6998 		if (!map->btf) {
6999 			verbose(env,
7000 				"map '%s' has to have BTF in order to use %s_lock\n",
7001 				map->name, lock_str);
7002 			return -EINVAL;
7003 		}
7004 	} else {
7005 		btf = reg->btf;
7006 	}
7007 
7008 	rec = reg_btf_record(reg);
7009 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
7010 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
7011 			map ? map->name : "kptr", lock_str);
7012 		return -EINVAL;
7013 	}
7014 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
7015 	if (spin_lock_off != val) {
7016 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
7017 			val, lock_str, spin_lock_off);
7018 		return -EINVAL;
7019 	}
7020 	if (is_lock) {
7021 		void *ptr;
7022 		int type;
7023 
7024 		if (map)
7025 			ptr = map;
7026 		else
7027 			ptr = btf;
7028 
7029 		if (!is_res_lock && cur->active_locks) {
7030 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
7031 				verbose(env,
7032 					"Locking two bpf_spin_locks are not allowed\n");
7033 				return -EINVAL;
7034 			}
7035 		} else if (is_res_lock && cur->active_locks) {
7036 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
7037 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
7038 				return -EINVAL;
7039 			}
7040 		}
7041 
7042 		if (is_res_lock && is_irq)
7043 			type = REF_TYPE_RES_LOCK_IRQ;
7044 		else if (is_res_lock)
7045 			type = REF_TYPE_RES_LOCK;
7046 		else
7047 			type = REF_TYPE_LOCK;
7048 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
7049 		if (err < 0) {
7050 			verbose(env, "Failed to acquire lock state\n");
7051 			return err;
7052 		}
7053 	} else {
7054 		void *ptr;
7055 		int type;
7056 
7057 		if (map)
7058 			ptr = map;
7059 		else
7060 			ptr = btf;
7061 
7062 		if (!cur->active_locks) {
7063 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
7064 			return -EINVAL;
7065 		}
7066 
7067 		if (is_res_lock && is_irq)
7068 			type = REF_TYPE_RES_LOCK_IRQ;
7069 		else if (is_res_lock)
7070 			type = REF_TYPE_RES_LOCK;
7071 		else
7072 			type = REF_TYPE_LOCK;
7073 		if (!find_lock_state(cur, type, reg->id, ptr)) {
7074 			verbose(env, "%s_unlock of different lock\n", lock_str);
7075 			return -EINVAL;
7076 		}
7077 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
7078 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
7079 			return -EINVAL;
7080 		}
7081 		if (release_lock_state(cur, type, reg->id, ptr)) {
7082 			verbose(env, "%s_unlock of different lock\n", lock_str);
7083 			return -EINVAL;
7084 		}
7085 
7086 		invalidate_non_owning_refs(env);
7087 	}
7088 	return 0;
7089 }
7090 
7091 /* Check if @regno is a pointer to a specific field in a map value */
7092 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7093 				   enum btf_field_type field_type,
7094 				   struct bpf_map_desc *map_desc)
7095 {
7096 	bool is_const = tnum_is_const(reg->var_off);
7097 	struct bpf_map *map = reg->map_ptr;
7098 	u64 val = reg->var_off.value;
7099 	const char *struct_name = btf_field_type_name(field_type);
7100 	int field_off = -1;
7101 
7102 	if (!is_const) {
7103 		verbose(env,
7104 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
7105 			reg_arg_name(env, argno), struct_name);
7106 		return -EINVAL;
7107 	}
7108 	if (!map->btf) {
7109 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
7110 			struct_name);
7111 		return -EINVAL;
7112 	}
7113 	if (!btf_record_has_field(map->record, field_type)) {
7114 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
7115 		return -EINVAL;
7116 	}
7117 	switch (field_type) {
7118 	case BPF_TIMER:
7119 		field_off = map->record->timer_off;
7120 		break;
7121 	case BPF_TASK_WORK:
7122 		field_off = map->record->task_work_off;
7123 		break;
7124 	case BPF_WORKQUEUE:
7125 		field_off = map->record->wq_off;
7126 		break;
7127 	default:
7128 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
7129 		return -EINVAL;
7130 	}
7131 	if (field_off != val) {
7132 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
7133 			val, struct_name, field_off);
7134 		return -EINVAL;
7135 	}
7136 	if (map_desc->ptr) {
7137 		verifier_bug(env, "Two map pointers in a %s helper", struct_name);
7138 		return -EFAULT;
7139 	}
7140 	map_desc->uid = reg->map_uid;
7141 	map_desc->ptr = map;
7142 	return 0;
7143 }
7144 
7145 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7146 			      struct bpf_map_desc *map)
7147 {
7148 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
7149 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
7150 		return -EOPNOTSUPP;
7151 	}
7152 	return check_map_field_pointer(env, reg, argno, BPF_TIMER, map);
7153 }
7154 
7155 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7156 				struct bpf_call_arg_meta *meta)
7157 {
7158 	return process_timer_func(env, reg, argno, &meta->map);
7159 }
7160 
7161 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7162 			       struct bpf_kfunc_call_arg_meta *meta)
7163 {
7164 	return process_timer_func(env, reg, argno, &meta->map);
7165 }
7166 
7167 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7168 			     struct bpf_call_arg_meta *meta)
7169 {
7170 	struct bpf_reg_state *reg = reg_state(env, regno);
7171 	struct btf_field *kptr_field;
7172 	struct bpf_map *map_ptr;
7173 	struct btf_record *rec;
7174 	u32 kptr_off;
7175 
7176 	if (type_is_ptr_alloc_obj(reg->type)) {
7177 		rec = reg_btf_record(reg);
7178 	} else { /* PTR_TO_MAP_VALUE */
7179 		map_ptr = reg->map_ptr;
7180 		if (!map_ptr->btf) {
7181 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7182 				map_ptr->name);
7183 			return -EINVAL;
7184 		}
7185 		rec = map_ptr->record;
7186 		meta->map.ptr = map_ptr;
7187 	}
7188 
7189 	if (!tnum_is_const(reg->var_off)) {
7190 		verbose(env,
7191 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7192 			regno);
7193 		return -EINVAL;
7194 	}
7195 
7196 	if (!btf_record_has_field(rec, BPF_KPTR)) {
7197 		verbose(env, "R%d has no valid kptr\n", regno);
7198 		return -EINVAL;
7199 	}
7200 
7201 	kptr_off = reg->var_off.value;
7202 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
7203 	if (!kptr_field) {
7204 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7205 		return -EACCES;
7206 	}
7207 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7208 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7209 		return -EACCES;
7210 	}
7211 	meta->kptr_field = kptr_field;
7212 	return 0;
7213 }
7214 
7215 /*
7216  * Validate dynptr arguments for helper, kfunc and subprog.
7217  *
7218  * @dynptr is both input and output. It is populated when the argument is
7219  * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed)
7220  * and consumed when the argument is expecting to be an initialized dynptr.
7221  * @parent_id is used to track the referenced parent object (e.g., file or skb in
7222  * qdisc program) when constructing a dynptr.
7223  *
7224  * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7225  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7226  *
7227  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7228  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7229  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7230  *
7231  * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the
7232  * dynptr points to. At the first level, the verifier will make sure a
7233  * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of
7234  * a dynptr's view (i.e., start and offset) is not tracked as there is not such
7235  * use case. The second level is tracked using the upper bit of bpf_dynptr->size
7236  * and checked dynamically during runtime.
7237  */
7238 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7239 			       argno_t argno, int insn_idx, enum bpf_arg_type arg_type,
7240 			       struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr)
7241 {
7242 	int spi, err = 0;
7243 
7244 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7245 		verbose(env,
7246 			"%s expected pointer to stack or const struct bpf_dynptr\n",
7247 			reg_arg_name(env, argno));
7248 		return -EINVAL;
7249 	}
7250 
7251 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7252 	 *		 constructing a mutable bpf_dynptr object.
7253 	 *
7254 	 *		 Currently, this is only possible with PTR_TO_STACK
7255 	 *		 pointing to a region of at least 16 bytes which doesn't
7256 	 *		 contain an existing bpf_dynptr.
7257 	 *
7258 	 *  OBJ_RELEASE - Points to a initialized bpf_dynptr that will be
7259 	 *		  destroyed.
7260 	 *
7261 	 *  None       - Points to a initialized dynptr that cannot be
7262 	 *		 reinitialized or destroyed. However, the view of the
7263 	 *		 dynptr and the memory it points to may be mutated.
7264 	 */
7265 	if (arg_type & MEM_UNINIT) {
7266 		int i;
7267 
7268 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7269 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7270 			return -EINVAL;
7271 		}
7272 
7273 		/* we write BPF_DW bits (8 bytes) at a time */
7274 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7275 			err = check_mem_access(env, insn_idx, reg, argno,
7276 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7277 			if (err)
7278 				return err;
7279 		}
7280 
7281 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr);
7282 	} else /* OBJ_RELEASE and None case from above */ {
7283 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7284 		if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) {
7285 			verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n");
7286 			return -EINVAL;
7287 		}
7288 
7289 		if (!is_dynptr_reg_valid_init(env, reg)) {
7290 			verbose(env, "Expected an initialized dynptr as %s\n",
7291 				reg_arg_name(env, argno));
7292 			return -EINVAL;
7293 		}
7294 
7295 		/* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */
7296 		if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) {
7297 			verbose(env,
7298 				"Expected a dynptr of type %s as %s\n",
7299 				dynptr_type_str(arg_to_dynptr_type(arg_type)),
7300 				reg_arg_name(env, argno));
7301 			return -EINVAL;
7302 		}
7303 
7304 		if (reg->type != CONST_PTR_TO_DYNPTR) {
7305 			struct bpf_func_state *state = bpf_func(env, reg);
7306 
7307 			spi = dynptr_get_spi(env, reg);
7308 			if (spi < 0)
7309 				return spi;
7310 
7311 			/*
7312 			 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg
7313 			 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call.
7314 			 */
7315 			mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS);
7316 
7317 			reg = &state->stack[spi].spilled_ptr;
7318 		}
7319 
7320 		if (dynptr) {
7321 			dynptr->type = reg->dynptr.type;
7322 			dynptr->id = reg->id;
7323 			dynptr->parent_id = reg->parent_id;
7324 		}
7325 	}
7326 	return err;
7327 }
7328 
7329 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7330 {
7331 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7332 }
7333 
7334 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7335 {
7336 	return meta->kfunc_flags & KF_ITER_NEW;
7337 }
7338 
7339 
7340 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7341 {
7342 	return meta->kfunc_flags & KF_ITER_DESTROY;
7343 }
7344 
7345 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
7346 			      const struct btf_param *arg)
7347 {
7348 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7349 	 * kfunc is iter state pointer
7350 	 */
7351 	if (is_iter_kfunc(meta))
7352 		return arg_idx == 0;
7353 
7354 	/* iter passed as an argument to a generic kfunc */
7355 	return btf_param_match_suffix(meta->btf, arg, "__iter");
7356 }
7357 
7358 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx,
7359 			    struct bpf_kfunc_call_arg_meta *meta)
7360 {
7361 	struct bpf_func_state *state = bpf_func(env, reg);
7362 	const struct btf_type *t;
7363 	u32 arg_idx = arg_idx_from_argno(argno);
7364 	int spi, err, i, nr_slots, btf_id;
7365 
7366 	if (reg->type != PTR_TO_STACK) {
7367 		verbose(env, "%s expected pointer to an iterator on stack\n",
7368 			reg_arg_name(env, argno));
7369 		return -EINVAL;
7370 	}
7371 
7372 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
7373 	 * ensures struct convention, so we wouldn't need to do any BTF
7374 	 * validation here. But given iter state can be passed as a parameter
7375 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
7376 	 * conservative here.
7377 	 */
7378 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx);
7379 	if (btf_id < 0) {
7380 		verbose(env, "expected valid iter pointer as %s\n",
7381 			reg_arg_name(env, argno));
7382 		return -EINVAL;
7383 	}
7384 	t = btf_type_by_id(meta->btf, btf_id);
7385 	nr_slots = t->size / BPF_REG_SIZE;
7386 
7387 	if (is_iter_new_kfunc(meta)) {
7388 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7389 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7390 			verbose(env, "expected uninitialized iter_%s as %s\n",
7391 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7392 			return -EINVAL;
7393 		}
7394 
7395 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7396 			err = check_mem_access(env, insn_idx, reg, argno,
7397 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7398 			if (err)
7399 				return err;
7400 		}
7401 
7402 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7403 		if (err)
7404 			return err;
7405 	} else {
7406 		/* iter_next() or iter_destroy(), as well as any kfunc
7407 		 * accepting iter argument, expect initialized iter state
7408 		 */
7409 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7410 		switch (err) {
7411 		case 0:
7412 			break;
7413 		case -EINVAL:
7414 			verbose(env, "expected an initialized iter_%s as %s\n",
7415 				iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno));
7416 			return err;
7417 		case -EPROTO:
7418 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7419 			return err;
7420 		default:
7421 			return err;
7422 		}
7423 
7424 		spi = iter_get_spi(env, reg, nr_slots);
7425 		if (spi < 0)
7426 			return spi;
7427 
7428 		mark_stack_slots_scratched(env, spi, nr_slots);
7429 
7430 		/* remember meta->iter info for process_iter_next_call() */
7431 		meta->iter.spi = spi;
7432 		meta->iter.frameno = reg->frameno;
7433 		update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr);
7434 
7435 		if (is_iter_destroy_kfunc(meta)) {
7436 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7437 			if (err)
7438 				return err;
7439 		}
7440 	}
7441 
7442 	return 0;
7443 }
7444 
7445 /* Look for a previous loop entry at insn_idx: nearest parent state
7446  * stopped at insn_idx with callsites matching those in cur->frame.
7447  */
7448 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7449 						  struct bpf_verifier_state *cur,
7450 						  int insn_idx)
7451 {
7452 	struct bpf_verifier_state_list *sl;
7453 	struct bpf_verifier_state *st;
7454 	struct list_head *pos, *head;
7455 
7456 	/* Explored states are pushed in stack order, most recent states come first */
7457 	head = bpf_explored_state(env, insn_idx);
7458 	list_for_each(pos, head) {
7459 		sl = container_of(pos, struct bpf_verifier_state_list, node);
7460 		/* If st->branches != 0 state is a part of current DFS verification path,
7461 		 * hence cur & st for a loop.
7462 		 */
7463 		st = &sl->state;
7464 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7465 		    st->dfs_depth < cur->dfs_depth)
7466 			return st;
7467 	}
7468 
7469 	return NULL;
7470 }
7471 
7472 /*
7473  * Check if scalar registers are exact for the purpose of not widening.
7474  * More lenient than regs_exact()
7475  */
7476 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold,
7477 				    const struct bpf_reg_state *rcur)
7478 {
7479 	return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id));
7480 }
7481 
7482 static void maybe_widen_reg(struct bpf_verifier_env *env,
7483 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur)
7484 {
7485 	if (rold->type != SCALAR_VALUE)
7486 		return;
7487 	if (rold->type != rcur->type)
7488 		return;
7489 	if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur))
7490 		return;
7491 	__mark_reg_unknown(env, rcur);
7492 }
7493 
7494 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7495 				   struct bpf_verifier_state *old,
7496 				   struct bpf_verifier_state *cur)
7497 {
7498 	struct bpf_func_state *fold, *fcur;
7499 	int i, fr, num_slots;
7500 
7501 	for (fr = old->curframe; fr >= 0; fr--) {
7502 		fold = old->frame[fr];
7503 		fcur = cur->frame[fr];
7504 
7505 		for (i = 0; i < MAX_BPF_REG; i++)
7506 			maybe_widen_reg(env,
7507 					&fold->regs[i],
7508 					&fcur->regs[i]);
7509 
7510 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
7511 				fcur->allocated_stack / BPF_REG_SIZE);
7512 		for (i = 0; i < num_slots; i++) {
7513 			if (!bpf_is_spilled_reg(&fold->stack[i]) ||
7514 			    !bpf_is_spilled_reg(&fcur->stack[i]))
7515 				continue;
7516 
7517 			maybe_widen_reg(env,
7518 					&fold->stack[i].spilled_ptr,
7519 					&fcur->stack[i].spilled_ptr);
7520 		}
7521 	}
7522 	return 0;
7523 }
7524 
7525 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7526 						 struct bpf_kfunc_call_arg_meta *meta)
7527 {
7528 	int iter_frameno = meta->iter.frameno;
7529 	int iter_spi = meta->iter.spi;
7530 
7531 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7532 }
7533 
7534 /* process_iter_next_call() is called when verifier gets to iterator's next
7535  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7536  * to it as just "iter_next()" in comments below.
7537  *
7538  * BPF verifier relies on a crucial contract for any iter_next()
7539  * implementation: it should *eventually* return NULL, and once that happens
7540  * it should keep returning NULL. That is, once iterator exhausts elements to
7541  * iterate, it should never reset or spuriously return new elements.
7542  *
7543  * With the assumption of such contract, process_iter_next_call() simulates
7544  * a fork in the verifier state to validate loop logic correctness and safety
7545  * without having to simulate infinite amount of iterations.
7546  *
7547  * In current state, we first assume that iter_next() returned NULL and
7548  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7549  * conditions we should not form an infinite loop and should eventually reach
7550  * exit.
7551  *
7552  * Besides that, we also fork current state and enqueue it for later
7553  * verification. In a forked state we keep iterator state as ACTIVE
7554  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7555  * also bump iteration depth to prevent erroneous infinite loop detection
7556  * later on (see iter_active_depths_differ() comment for details). In this
7557  * state we assume that we'll eventually loop back to another iter_next()
7558  * calls (it could be in exactly same location or in some other instruction,
7559  * it doesn't matter, we don't make any unnecessary assumptions about this,
7560  * everything revolves around iterator state in a stack slot, not which
7561  * instruction is calling iter_next()). When that happens, we either will come
7562  * to iter_next() with equivalent state and can conclude that next iteration
7563  * will proceed in exactly the same way as we just verified, so it's safe to
7564  * assume that loop converges. If not, we'll go on another iteration
7565  * simulation with a different input state, until all possible starting states
7566  * are validated or we reach maximum number of instructions limit.
7567  *
7568  * This way, we will either exhaustively discover all possible input states
7569  * that iterator loop can start with and eventually will converge, or we'll
7570  * effectively regress into bounded loop simulation logic and either reach
7571  * maximum number of instructions if loop is not provably convergent, or there
7572  * is some statically known limit on number of iterations (e.g., if there is
7573  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7574  *
7575  * Iteration convergence logic in is_state_visited() relies on exact
7576  * states comparison, which ignores read and precision marks.
7577  * This is necessary because read and precision marks are not finalized
7578  * while in the loop. Exact comparison might preclude convergence for
7579  * simple programs like below:
7580  *
7581  *     i = 0;
7582  *     while(iter_next(&it))
7583  *       i++;
7584  *
7585  * At each iteration step i++ would produce a new distinct state and
7586  * eventually instruction processing limit would be reached.
7587  *
7588  * To avoid such behavior speculatively forget (widen) range for
7589  * imprecise scalar registers, if those registers were not precise at the
7590  * end of the previous iteration and do not match exactly.
7591  *
7592  * This is a conservative heuristic that allows to verify wide range of programs,
7593  * however it precludes verification of programs that conjure an
7594  * imprecise value on the first loop iteration and use it as precise on a second.
7595  * For example, the following safe program would fail to verify:
7596  *
7597  *     struct bpf_num_iter it;
7598  *     int arr[10];
7599  *     int i = 0, a = 0;
7600  *     bpf_iter_num_new(&it, 0, 10);
7601  *     while (bpf_iter_num_next(&it)) {
7602  *       if (a == 0) {
7603  *         a = 1;
7604  *         i = 7; // Because i changed verifier would forget
7605  *                // it's range on second loop entry.
7606  *       } else {
7607  *         arr[i] = 42; // This would fail to verify.
7608  *       }
7609  *     }
7610  *     bpf_iter_num_destroy(&it);
7611  */
7612 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7613 				  struct bpf_kfunc_call_arg_meta *meta)
7614 {
7615 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7616 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7617 	struct bpf_reg_state *cur_iter, *queued_iter;
7618 
7619 	BTF_TYPE_EMIT(struct bpf_iter);
7620 
7621 	cur_iter = get_iter_from_state(cur_st, meta);
7622 
7623 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7624 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7625 		verifier_bug(env, "unexpected iterator state %d (%s)",
7626 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7627 		return -EFAULT;
7628 	}
7629 
7630 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7631 		/* Because iter_next() call is a checkpoint is_state_visitied()
7632 		 * should guarantee parent state with same call sites and insn_idx.
7633 		 */
7634 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7635 		    !same_callsites(cur_st->parent, cur_st)) {
7636 			verifier_bug(env, "bad parent state for iter next call");
7637 			return -EFAULT;
7638 		}
7639 		/* Note cur_st->parent in the call below, it is necessary to skip
7640 		 * checkpoint created for cur_st by is_state_visited()
7641 		 * right at this instruction.
7642 		 */
7643 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7644 		/* branch out active iter state */
7645 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7646 		if (IS_ERR(queued_st))
7647 			return PTR_ERR(queued_st);
7648 
7649 		queued_iter = get_iter_from_state(queued_st, meta);
7650 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7651 		queued_iter->iter.depth++;
7652 		if (prev_st)
7653 			widen_imprecise_scalars(env, prev_st, queued_st);
7654 
7655 		queued_fr = queued_st->frame[queued_st->curframe];
7656 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7657 	}
7658 
7659 	/* switch to DRAINED state, but keep the depth unchanged */
7660 	/* mark current iter state as drained and assume returned NULL */
7661 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7662 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
7663 
7664 	return 0;
7665 }
7666 
7667 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7668 {
7669 	return type == ARG_CONST_SIZE ||
7670 	       type == ARG_CONST_SIZE_OR_ZERO;
7671 }
7672 
7673 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7674 {
7675 	return base_type(type) == ARG_PTR_TO_MEM &&
7676 	       type & MEM_UNINIT;
7677 }
7678 
7679 static bool arg_type_is_release(enum bpf_arg_type type)
7680 {
7681 	return type & OBJ_RELEASE;
7682 }
7683 
7684 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7685 {
7686 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7687 }
7688 
7689 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7690 				 const struct bpf_call_arg_meta *meta,
7691 				 enum bpf_arg_type *arg_type)
7692 {
7693 	if (!meta->map.ptr) {
7694 		/* kernel subsystem misconfigured verifier */
7695 		verifier_bug(env, "invalid map_ptr to access map->type");
7696 		return -EFAULT;
7697 	}
7698 
7699 	switch (meta->map.ptr->map_type) {
7700 	case BPF_MAP_TYPE_SOCKMAP:
7701 	case BPF_MAP_TYPE_SOCKHASH:
7702 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7703 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7704 		} else {
7705 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
7706 			return -EINVAL;
7707 		}
7708 		break;
7709 	case BPF_MAP_TYPE_BLOOM_FILTER:
7710 		if (meta->func_id == BPF_FUNC_map_peek_elem)
7711 			*arg_type = ARG_PTR_TO_MAP_VALUE;
7712 		break;
7713 	default:
7714 		break;
7715 	}
7716 	return 0;
7717 }
7718 
7719 struct bpf_reg_types {
7720 	const enum bpf_reg_type types[10];
7721 	u32 *btf_id;
7722 };
7723 
7724 static const struct bpf_reg_types sock_types = {
7725 	.types = {
7726 		PTR_TO_SOCK_COMMON,
7727 		PTR_TO_SOCKET,
7728 		PTR_TO_TCP_SOCK,
7729 		PTR_TO_XDP_SOCK,
7730 	},
7731 };
7732 
7733 #ifdef CONFIG_NET
7734 static const struct bpf_reg_types btf_id_sock_common_types = {
7735 	.types = {
7736 		PTR_TO_SOCK_COMMON,
7737 		PTR_TO_SOCKET,
7738 		PTR_TO_TCP_SOCK,
7739 		PTR_TO_XDP_SOCK,
7740 		PTR_TO_BTF_ID,
7741 		PTR_TO_BTF_ID | PTR_TRUSTED,
7742 	},
7743 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7744 };
7745 #endif
7746 
7747 static const struct bpf_reg_types mem_types = {
7748 	.types = {
7749 		PTR_TO_STACK,
7750 		PTR_TO_PACKET,
7751 		PTR_TO_PACKET_META,
7752 		PTR_TO_MAP_KEY,
7753 		PTR_TO_MAP_VALUE,
7754 		PTR_TO_MEM,
7755 		PTR_TO_MEM | MEM_RINGBUF,
7756 		PTR_TO_BUF,
7757 		PTR_TO_BTF_ID | PTR_TRUSTED,
7758 		PTR_TO_CTX,
7759 	},
7760 };
7761 
7762 static const struct bpf_reg_types spin_lock_types = {
7763 	.types = {
7764 		PTR_TO_MAP_VALUE,
7765 		PTR_TO_BTF_ID | MEM_ALLOC,
7766 	}
7767 };
7768 
7769 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7770 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7771 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7772 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7773 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7774 static const struct bpf_reg_types btf_ptr_types = {
7775 	.types = {
7776 		PTR_TO_BTF_ID,
7777 		PTR_TO_BTF_ID | PTR_TRUSTED,
7778 		PTR_TO_BTF_ID | MEM_RCU,
7779 	},
7780 };
7781 static const struct bpf_reg_types percpu_btf_ptr_types = {
7782 	.types = {
7783 		PTR_TO_BTF_ID | MEM_PERCPU,
7784 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
7785 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7786 	}
7787 };
7788 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7789 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7790 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7791 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7792 static const struct bpf_reg_types kptr_xchg_dest_types = {
7793 	.types = {
7794 		PTR_TO_MAP_VALUE,
7795 		PTR_TO_BTF_ID | MEM_ALLOC,
7796 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF,
7797 		PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU,
7798 	}
7799 };
7800 static const struct bpf_reg_types dynptr_types = {
7801 	.types = {
7802 		PTR_TO_STACK,
7803 		CONST_PTR_TO_DYNPTR,
7804 	}
7805 };
7806 
7807 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7808 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
7809 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
7810 	[ARG_CONST_SIZE]		= &scalar_types,
7811 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
7812 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
7813 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
7814 	[ARG_PTR_TO_CTX]		= &context_types,
7815 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
7816 #ifdef CONFIG_NET
7817 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
7818 #endif
7819 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
7820 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
7821 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
7822 	[ARG_PTR_TO_MEM]		= &mem_types,
7823 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
7824 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
7825 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
7826 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
7827 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
7828 	[ARG_PTR_TO_TIMER]		= &timer_types,
7829 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
7830 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
7831 };
7832 
7833 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
7834 			  enum bpf_arg_type arg_type,
7835 			  const u32 *arg_btf_id,
7836 			  struct bpf_call_arg_meta *meta)
7837 {
7838 	enum bpf_reg_type expected, type = reg->type;
7839 	const struct bpf_reg_types *compatible;
7840 	int i, j, err;
7841 
7842 	compatible = compatible_reg_types[base_type(arg_type)];
7843 	if (!compatible) {
7844 		verifier_bug(env, "unsupported arg type %d", arg_type);
7845 		return -EFAULT;
7846 	}
7847 
7848 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7849 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7850 	 *
7851 	 * Same for MAYBE_NULL:
7852 	 *
7853 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7854 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7855 	 *
7856 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7857 	 *
7858 	 * Therefore we fold these flags depending on the arg_type before comparison.
7859 	 */
7860 	if (arg_type & MEM_RDONLY)
7861 		type &= ~MEM_RDONLY;
7862 	if (arg_type & PTR_MAYBE_NULL)
7863 		type &= ~PTR_MAYBE_NULL;
7864 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
7865 		type &= ~DYNPTR_TYPE_FLAG_MASK;
7866 
7867 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
7868 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) {
7869 		type &= ~MEM_ALLOC;
7870 		type &= ~MEM_PERCPU;
7871 	}
7872 
7873 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7874 		expected = compatible->types[i];
7875 		if (expected == NOT_INIT)
7876 			break;
7877 
7878 		if (type == expected)
7879 			goto found;
7880 	}
7881 
7882 	verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type));
7883 	for (j = 0; j + 1 < i; j++)
7884 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7885 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7886 	return -EACCES;
7887 
7888 found:
7889 	if (base_type(reg->type) != PTR_TO_BTF_ID)
7890 		return 0;
7891 
7892 	if (compatible == &mem_types) {
7893 		if (!(arg_type & MEM_RDONLY)) {
7894 			verbose(env,
7895 				"%s() may write into memory pointed by %s type=%s\n",
7896 				func_id_name(meta->func_id),
7897 				reg_arg_name(env, argno), reg_type_str(env, reg->type));
7898 			return -EACCES;
7899 		}
7900 		return 0;
7901 	}
7902 
7903 	switch ((int)reg->type) {
7904 	case PTR_TO_BTF_ID:
7905 	case PTR_TO_BTF_ID | PTR_TRUSTED:
7906 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
7907 	case PTR_TO_BTF_ID | MEM_RCU:
7908 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7909 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7910 	{
7911 		/* For bpf_sk_release, it needs to match against first member
7912 		 * 'struct sock_common', hence make an exception for it. This
7913 		 * allows bpf_sk_release to work for multiple socket types.
7914 		 */
7915 		bool strict_type_match = arg_type_is_release(arg_type) &&
7916 					 meta->func_id != BPF_FUNC_sk_release;
7917 
7918 		if (type_may_be_null(reg->type) &&
7919 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7920 			verbose(env, "Possibly NULL pointer passed to helper %s\n",
7921 				reg_arg_name(env, argno));
7922 			return -EACCES;
7923 		}
7924 
7925 		if (!arg_btf_id) {
7926 			if (!compatible->btf_id) {
7927 				verifier_bug(env, "missing arg compatible BTF ID");
7928 				return -EFAULT;
7929 			}
7930 			arg_btf_id = compatible->btf_id;
7931 		}
7932 
7933 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7934 			if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno)))
7935 				return -EACCES;
7936 		} else {
7937 			if (arg_btf_id == BPF_PTR_POISON) {
7938 				verbose(env, "verifier internal error:");
7939 				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
7940 					reg_arg_name(env, argno));
7941 				return -EACCES;
7942 			}
7943 
7944 			err = __check_ptr_off_reg(env, reg, argno, true);
7945 			if (err)
7946 				return err;
7947 
7948 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id,
7949 						  reg->var_off.value, btf_vmlinux, *arg_btf_id,
7950 						  strict_type_match)) {
7951 				verbose(env, "%s is of type %s but %s is expected\n",
7952 					reg_arg_name(env, argno),
7953 					btf_type_name(reg->btf, reg->btf_id),
7954 					btf_type_name(btf_vmlinux, *arg_btf_id));
7955 				return -EACCES;
7956 			}
7957 		}
7958 		break;
7959 	}
7960 	case PTR_TO_BTF_ID | MEM_ALLOC:
7961 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
7962 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7963 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
7964 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7965 		    meta->func_id != BPF_FUNC_kptr_xchg) {
7966 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
7967 			return -EFAULT;
7968 		}
7969 		/* Check if local kptr in src arg matches kptr in dst arg */
7970 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
7971 			int regno = reg_from_argno(argno);
7972 
7973 			if (regno == BPF_REG_2 &&
7974 			    map_kptr_match_type(env, meta->kptr_field, reg, regno))
7975 				return -EACCES;
7976 		}
7977 		break;
7978 	case PTR_TO_BTF_ID | MEM_PERCPU:
7979 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
7980 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7981 		/* Handled by helper specific checks */
7982 		break;
7983 	default:
7984 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
7985 		return -EFAULT;
7986 	}
7987 	return 0;
7988 }
7989 
7990 static struct btf_field *
7991 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7992 {
7993 	struct btf_field *field;
7994 	struct btf_record *rec;
7995 
7996 	rec = reg_btf_record(reg);
7997 	if (!rec)
7998 		return NULL;
7999 
8000 	field = btf_record_find(rec, off, fields);
8001 	if (!field)
8002 		return NULL;
8003 
8004 	return field;
8005 }
8006 
8007 static int __check_func_arg_reg_off(struct bpf_verifier_env *env,
8008 				    const struct bpf_reg_state *reg, argno_t argno,
8009 				    enum bpf_arg_type arg_type,
8010 				    bool btf_id_fixed_off_ok)
8011 {
8012 	u32 type = reg->type;
8013 
8014 	/* When referenced register is passed to release function, its fixed
8015 	 * offset must be 0.
8016 	 *
8017 	 * We will check arg_type_is_release reg has id when storing
8018 	 * meta->release_regno.
8019 	 */
8020 	if (arg_type_is_release(arg_type)) {
8021 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8022 		 * may not directly point to the object being released, but to
8023 		 * dynptr pointing to such object, which might be at some offset
8024 		 * on the stack. In that case, we simply to fallback to the
8025 		 * default handling.
8026 		 */
8027 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8028 			return 0;
8029 
8030 		/* Doing check_ptr_off_reg check for the offset will catch this
8031 		 * because fixed_off_ok is false, but checking here allows us
8032 		 * to give the user a better error message.
8033 		 */
8034 		if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) {
8035 			verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n",
8036 				reg_arg_name(env, argno));
8037 			return -EINVAL;
8038 		}
8039 	}
8040 
8041 	switch (type) {
8042 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8043 	case PTR_TO_STACK:
8044 	case PTR_TO_PACKET:
8045 	case PTR_TO_PACKET_META:
8046 	case PTR_TO_MAP_KEY:
8047 	case PTR_TO_MAP_VALUE:
8048 	case PTR_TO_MEM:
8049 	case PTR_TO_MEM | MEM_RDONLY:
8050 	case PTR_TO_MEM | MEM_RINGBUF:
8051 	case PTR_TO_BUF:
8052 	case PTR_TO_BUF | MEM_RDONLY:
8053 	case PTR_TO_ARENA:
8054 	case SCALAR_VALUE:
8055 		return 0;
8056 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8057 	 * fixed offset.
8058 	 */
8059 	case PTR_TO_BTF_ID:
8060 	case PTR_TO_BTF_ID | MEM_ALLOC:
8061 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8062 	case PTR_TO_BTF_ID | MEM_RCU:
8063 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8064 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8065 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8066 		 * its fixed offset must be 0. In the other cases, fixed offset
8067 		 * can be non-zero unless the caller requires otherwise.
8068 		 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still
8069 		 * need to do checks instead of returning.
8070 		 */
8071 		return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok);
8072 	case PTR_TO_CTX:
8073 		/*
8074 		 * Allow fixed and variable offsets for syscall context, but
8075 		 * only when the argument is passed as memory, not ctx,
8076 		 * otherwise we may get modified ctx in tail called programs and
8077 		 * global subprogs (that may act as extension prog hooks).
8078 		 */
8079 		if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog))
8080 			return 0;
8081 		fallthrough;
8082 	default:
8083 		return __check_ptr_off_reg(env, reg, argno, false);
8084 	}
8085 }
8086 
8087 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8088 				  const struct bpf_reg_state *reg, argno_t argno,
8089 				  enum bpf_arg_type arg_type)
8090 {
8091 	return __check_func_arg_reg_off(env, reg, argno, arg_type, true);
8092 }
8093 
8094 static int check_arg_const_str(struct bpf_verifier_env *env,
8095 			       struct bpf_reg_state *reg, argno_t argno)
8096 {
8097 	struct bpf_map *map = reg->map_ptr;
8098 	int err;
8099 	int map_off;
8100 	u64 map_addr;
8101 	char *str_ptr;
8102 
8103 	if (reg->type != PTR_TO_MAP_VALUE)
8104 		return -EINVAL;
8105 
8106 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
8107 		verbose(env, "%s points to insn_array map which cannot be used as const string\n",
8108 			reg_arg_name(env, argno));
8109 		return -EACCES;
8110 	}
8111 
8112 	if (!bpf_map_is_rdonly(map)) {
8113 		verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno));
8114 		return -EACCES;
8115 	}
8116 
8117 	if (!tnum_is_const(reg->var_off)) {
8118 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
8119 		return -EACCES;
8120 	}
8121 
8122 	if (!map->ops->map_direct_value_addr) {
8123 		verbose(env, "no direct value access support for this map type\n");
8124 		return -EACCES;
8125 	}
8126 
8127 	err = check_map_access(env, reg, argno, 0,
8128 			       map->value_size - reg->var_off.value, false,
8129 			       ACCESS_HELPER);
8130 	if (err)
8131 		return err;
8132 
8133 	map_off = reg->var_off.value;
8134 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8135 	if (err) {
8136 		verbose(env, "direct value access on string failed\n");
8137 		return err;
8138 	}
8139 
8140 	str_ptr = (char *)(long)(map_addr);
8141 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8142 		verbose(env, "string is not zero-terminated\n");
8143 		return -EINVAL;
8144 	}
8145 	return 0;
8146 }
8147 
8148 /* Returns constant key value in `value` if possible, else negative error */
8149 static int get_constant_map_key(struct bpf_verifier_env *env,
8150 				struct bpf_reg_state *key,
8151 				u32 key_size,
8152 				s64 *value)
8153 {
8154 	struct bpf_func_state *state = bpf_func(env, key);
8155 	struct bpf_reg_state *reg;
8156 	int slot, spi, off;
8157 	int spill_size = 0;
8158 	int zero_size = 0;
8159 	int stack_off;
8160 	int i, err;
8161 	u8 *stype;
8162 
8163 	if (!env->bpf_capable)
8164 		return -EOPNOTSUPP;
8165 	if (key->type != PTR_TO_STACK)
8166 		return -EOPNOTSUPP;
8167 	if (!tnum_is_const(key->var_off))
8168 		return -EOPNOTSUPP;
8169 
8170 	stack_off = key->var_off.value;
8171 	slot = -stack_off - 1;
8172 	spi = slot / BPF_REG_SIZE;
8173 	off = slot % BPF_REG_SIZE;
8174 	stype = state->stack[spi].slot_type;
8175 
8176 	/* First handle precisely tracked STACK_ZERO */
8177 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
8178 		zero_size++;
8179 	if (zero_size >= key_size) {
8180 		*value = 0;
8181 		return 0;
8182 	}
8183 
8184 	/* Check that stack contains a scalar spill of expected size */
8185 	if (!bpf_is_spilled_scalar_reg(&state->stack[spi]))
8186 		return -EOPNOTSUPP;
8187 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
8188 		spill_size++;
8189 	if (spill_size != key_size)
8190 		return -EOPNOTSUPP;
8191 
8192 	reg = &state->stack[spi].spilled_ptr;
8193 	if (!tnum_is_const(reg->var_off))
8194 		/* Stack value not statically known */
8195 		return -EOPNOTSUPP;
8196 
8197 	/* We are relying on a constant value. So mark as precise
8198 	 * to prevent pruning on it.
8199 	 */
8200 	bpf_bt_set_frame_slot(&env->bt, key->frameno, spi);
8201 	err = mark_chain_precision_batch(env, env->cur_state);
8202 	if (err < 0)
8203 		return err;
8204 
8205 	*value = reg->var_off.value;
8206 	return 0;
8207 }
8208 
8209 static bool can_elide_value_nullness(const struct bpf_map *map);
8210 
8211 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8212 			  struct bpf_call_arg_meta *meta,
8213 			  const struct bpf_func_proto *fn,
8214 			  int insn_idx)
8215 {
8216 	u32 regno = BPF_REG_1 + arg;
8217 	struct bpf_reg_state *reg = reg_state(env, regno);
8218 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8219 	argno_t argno = argno_from_arg(arg + 1);
8220 	enum bpf_reg_type type = reg->type;
8221 	u32 *arg_btf_id = NULL;
8222 	u32 key_size;
8223 	int err = 0;
8224 
8225 	if (arg_type == ARG_DONTCARE)
8226 		return 0;
8227 
8228 	err = check_reg_arg(env, regno, SRC_OP);
8229 	if (err)
8230 		return err;
8231 
8232 	if (arg_type == ARG_ANYTHING) {
8233 		if (is_pointer_value(env, regno)) {
8234 			verbose(env, "R%d leaks addr into helper function\n",
8235 				regno);
8236 			return -EACCES;
8237 		}
8238 		return 0;
8239 	}
8240 
8241 	if (type_is_pkt_pointer(type) &&
8242 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8243 		verbose(env, "helper access to the packet is not allowed\n");
8244 		return -EACCES;
8245 	}
8246 
8247 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8248 		err = resolve_map_arg_type(env, meta, &arg_type);
8249 		if (err)
8250 			return err;
8251 	}
8252 
8253 	if (bpf_register_is_null(reg) && type_may_be_null(arg_type))
8254 		/* A NULL register has a SCALAR_VALUE type, so skip
8255 		 * type checking.
8256 		 */
8257 		goto skip_type_check;
8258 
8259 	/* arg_btf_id and arg_size are in a union. */
8260 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8261 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8262 		arg_btf_id = fn->arg_btf_id[arg];
8263 
8264 	err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta);
8265 	if (err)
8266 		return err;
8267 
8268 	err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type);
8269 	if (err)
8270 		return err;
8271 
8272 skip_type_check:
8273 	if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) &&
8274 	    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
8275 		verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n",
8276 			func_id_name(meta->func_id), reg_arg_name(env, argno));
8277 		return -EINVAL;
8278 	}
8279 
8280 	if (reg_is_referenced(env, reg))
8281 		update_ref_obj(&meta->ref_obj, reg);
8282 
8283 	switch (base_type(arg_type)) {
8284 	case ARG_CONST_MAP_PTR:
8285 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8286 		if (meta->map.ptr) {
8287 			/* Use map_uid (which is unique id of inner map) to reject:
8288 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8289 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8290 			 * if (inner_map1 && inner_map2) {
8291 			 *     timer = bpf_map_lookup_elem(inner_map1);
8292 			 *     if (timer)
8293 			 *         // mismatch would have been allowed
8294 			 *         bpf_timer_init(timer, inner_map2);
8295 			 * }
8296 			 *
8297 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8298 			 */
8299 			if (meta->map.ptr != reg->map_ptr ||
8300 			    meta->map.uid != reg->map_uid) {
8301 				verbose(env,
8302 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8303 					meta->map.uid, reg->map_uid);
8304 				return -EINVAL;
8305 			}
8306 		}
8307 		meta->map.ptr = reg->map_ptr;
8308 		meta->map.uid = reg->map_uid;
8309 		break;
8310 	case ARG_PTR_TO_MAP_KEY:
8311 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8312 		 * check that [key, key + map->key_size) are within
8313 		 * stack limits and initialized
8314 		 */
8315 		if (!meta->map.ptr) {
8316 			/* in function declaration map_ptr must come before
8317 			 * map_key, so that it's verified and known before
8318 			 * we have to check map_key here. Otherwise it means
8319 			 * that kernel subsystem misconfigured verifier
8320 			 */
8321 			verifier_bug(env, "invalid map_ptr to access map->key");
8322 			return -EFAULT;
8323 		}
8324 		key_size = meta->map.ptr->key_size;
8325 		err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL);
8326 		if (err)
8327 			return err;
8328 		if (can_elide_value_nullness(meta->map.ptr)) {
8329 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
8330 			if (err < 0) {
8331 				meta->const_map_key = -1;
8332 				if (err == -EOPNOTSUPP)
8333 					err = 0;
8334 				else
8335 					return err;
8336 			}
8337 		}
8338 		break;
8339 	case ARG_PTR_TO_MAP_VALUE:
8340 		if (type_may_be_null(arg_type) && bpf_register_is_null(reg))
8341 			return 0;
8342 
8343 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8344 		 * check [value, value + map->value_size) validity
8345 		 */
8346 		if (!meta->map.ptr) {
8347 			/* kernel subsystem misconfigured verifier */
8348 			verifier_bug(env, "invalid map_ptr to access map->value");
8349 			return -EFAULT;
8350 		}
8351 		meta->raw_mode = arg_type & MEM_UNINIT;
8352 		err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size,
8353 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8354 					      false, meta);
8355 		break;
8356 	case ARG_PTR_TO_PERCPU_BTF_ID:
8357 		if (!reg->btf_id) {
8358 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8359 			return -EACCES;
8360 		}
8361 		meta->ret_btf = reg->btf;
8362 		meta->ret_btf_id = reg->btf_id;
8363 		break;
8364 	case ARG_PTR_TO_SPIN_LOCK:
8365 		if (in_rbtree_lock_required_cb(env)) {
8366 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8367 			return -EACCES;
8368 		}
8369 		if (meta->func_id == BPF_FUNC_spin_lock) {
8370 			err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK);
8371 			if (err)
8372 				return err;
8373 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8374 			err = process_spin_lock(env, reg, argno_from_reg(regno), 0);
8375 			if (err)
8376 				return err;
8377 		} else {
8378 			verifier_bug(env, "spin lock arg on unexpected helper");
8379 			return -EFAULT;
8380 		}
8381 		break;
8382 	case ARG_PTR_TO_TIMER:
8383 		err = process_timer_helper(env, reg, argno_from_reg(regno), meta);
8384 		if (err)
8385 			return err;
8386 		break;
8387 	case ARG_PTR_TO_FUNC:
8388 		meta->subprogno = reg->subprogno;
8389 		break;
8390 	case ARG_PTR_TO_MEM:
8391 		/* The access to this pointer is only checked when we hit the
8392 		 * next is_mem_size argument below.
8393 		 */
8394 		meta->raw_mode = arg_type & MEM_UNINIT;
8395 		if (arg_type & MEM_FIXED_SIZE) {
8396 			err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg],
8397 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8398 						      false, meta);
8399 			if (err)
8400 				return err;
8401 			if (arg_type & MEM_ALIGNED)
8402 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8403 		}
8404 		break;
8405 	case ARG_CONST_SIZE:
8406 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1),
8407 					 argno_from_reg(regno),
8408 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8409 					 BPF_WRITE : BPF_READ,
8410 					 false, meta);
8411 		break;
8412 	case ARG_CONST_SIZE_OR_ZERO:
8413 		err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1),
8414 					 argno_from_reg(regno),
8415 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8416 					 BPF_WRITE : BPF_READ,
8417 					 true, meta);
8418 		break;
8419 	case ARG_PTR_TO_DYNPTR:
8420 		err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, &meta->ref_obj,
8421 					  &meta->dynptr);
8422 		if (err)
8423 			return err;
8424 		break;
8425 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8426 		if (!tnum_is_const(reg->var_off)) {
8427 			verbose(env, "R%d is not a known constant'\n",
8428 				regno);
8429 			return -EACCES;
8430 		}
8431 		meta->mem_size = reg->var_off.value;
8432 		err = mark_chain_precision(env, regno);
8433 		if (err)
8434 			return err;
8435 		break;
8436 	case ARG_PTR_TO_CONST_STR:
8437 	{
8438 		err = check_arg_const_str(env, reg, argno_from_reg(regno));
8439 		if (err)
8440 			return err;
8441 		break;
8442 	}
8443 	case ARG_KPTR_XCHG_DEST:
8444 		err = process_kptr_func(env, regno, meta);
8445 		if (err)
8446 			return err;
8447 		break;
8448 	}
8449 
8450 	return err;
8451 }
8452 
8453 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8454 {
8455 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8456 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8457 
8458 	if (func_id != BPF_FUNC_map_update_elem &&
8459 	    func_id != BPF_FUNC_map_delete_elem)
8460 		return false;
8461 
8462 	/* It's not possible to get access to a locked struct sock in these
8463 	 * contexts, so updating is safe.
8464 	 */
8465 	switch (type) {
8466 	case BPF_PROG_TYPE_TRACING:
8467 		if (eatype == BPF_TRACE_ITER)
8468 			return true;
8469 		break;
8470 	case BPF_PROG_TYPE_SOCK_OPS:
8471 		/* map_update allowed only via dedicated helpers with event type checks */
8472 		if (func_id == BPF_FUNC_map_delete_elem)
8473 			return true;
8474 		break;
8475 	case BPF_PROG_TYPE_SOCKET_FILTER:
8476 	case BPF_PROG_TYPE_SCHED_CLS:
8477 	case BPF_PROG_TYPE_SCHED_ACT:
8478 	case BPF_PROG_TYPE_XDP:
8479 	case BPF_PROG_TYPE_SK_REUSEPORT:
8480 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8481 	case BPF_PROG_TYPE_SK_LOOKUP:
8482 		return true;
8483 	default:
8484 		break;
8485 	}
8486 
8487 	verbose(env, "cannot update sockmap in this context\n");
8488 	return false;
8489 }
8490 
8491 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8492 {
8493 	return env->prog->jit_requested &&
8494 	       bpf_jit_supports_subprog_tailcalls();
8495 }
8496 
8497 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8498 					struct bpf_map *map, int func_id)
8499 {
8500 	if (!map)
8501 		return 0;
8502 
8503 	/* We need a two way check, first is from map perspective ... */
8504 	switch (map->map_type) {
8505 	case BPF_MAP_TYPE_PROG_ARRAY:
8506 		if (func_id != BPF_FUNC_tail_call)
8507 			goto error;
8508 		break;
8509 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8510 		if (func_id != BPF_FUNC_perf_event_read &&
8511 		    func_id != BPF_FUNC_perf_event_output &&
8512 		    func_id != BPF_FUNC_skb_output &&
8513 		    func_id != BPF_FUNC_perf_event_read_value &&
8514 		    func_id != BPF_FUNC_xdp_output)
8515 			goto error;
8516 		break;
8517 	case BPF_MAP_TYPE_RINGBUF:
8518 		if (func_id != BPF_FUNC_ringbuf_output &&
8519 		    func_id != BPF_FUNC_ringbuf_reserve &&
8520 		    func_id != BPF_FUNC_ringbuf_query &&
8521 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8522 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8523 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8524 			goto error;
8525 		break;
8526 	case BPF_MAP_TYPE_USER_RINGBUF:
8527 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8528 			goto error;
8529 		break;
8530 	case BPF_MAP_TYPE_STACK_TRACE:
8531 		if (func_id != BPF_FUNC_get_stackid)
8532 			goto error;
8533 		break;
8534 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8535 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8536 		    func_id != BPF_FUNC_current_task_under_cgroup)
8537 			goto error;
8538 		break;
8539 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8540 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8541 		if (func_id != BPF_FUNC_get_local_storage)
8542 			goto error;
8543 		break;
8544 	case BPF_MAP_TYPE_DEVMAP:
8545 	case BPF_MAP_TYPE_DEVMAP_HASH:
8546 		if (func_id != BPF_FUNC_redirect_map &&
8547 		    func_id != BPF_FUNC_map_lookup_elem)
8548 			goto error;
8549 		break;
8550 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8551 	 * appear.
8552 	 */
8553 	case BPF_MAP_TYPE_CPUMAP:
8554 		if (func_id != BPF_FUNC_redirect_map)
8555 			goto error;
8556 		break;
8557 	case BPF_MAP_TYPE_XSKMAP:
8558 		if (func_id != BPF_FUNC_redirect_map &&
8559 		    func_id != BPF_FUNC_map_lookup_elem)
8560 			goto error;
8561 		break;
8562 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8563 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8564 		if (func_id != BPF_FUNC_map_lookup_elem)
8565 			goto error;
8566 		break;
8567 	case BPF_MAP_TYPE_SOCKMAP:
8568 		if (func_id != BPF_FUNC_sk_redirect_map &&
8569 		    func_id != BPF_FUNC_sock_map_update &&
8570 		    func_id != BPF_FUNC_msg_redirect_map &&
8571 		    func_id != BPF_FUNC_sk_select_reuseport &&
8572 		    func_id != BPF_FUNC_map_lookup_elem &&
8573 		    !may_update_sockmap(env, func_id))
8574 			goto error;
8575 		break;
8576 	case BPF_MAP_TYPE_SOCKHASH:
8577 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8578 		    func_id != BPF_FUNC_sock_hash_update &&
8579 		    func_id != BPF_FUNC_msg_redirect_hash &&
8580 		    func_id != BPF_FUNC_sk_select_reuseport &&
8581 		    func_id != BPF_FUNC_map_lookup_elem &&
8582 		    !may_update_sockmap(env, func_id))
8583 			goto error;
8584 		break;
8585 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8586 		if (func_id != BPF_FUNC_sk_select_reuseport)
8587 			goto error;
8588 		break;
8589 	case BPF_MAP_TYPE_QUEUE:
8590 	case BPF_MAP_TYPE_STACK:
8591 		if (func_id != BPF_FUNC_map_peek_elem &&
8592 		    func_id != BPF_FUNC_map_pop_elem &&
8593 		    func_id != BPF_FUNC_map_push_elem)
8594 			goto error;
8595 		break;
8596 	case BPF_MAP_TYPE_SK_STORAGE:
8597 		if (func_id != BPF_FUNC_sk_storage_get &&
8598 		    func_id != BPF_FUNC_sk_storage_delete &&
8599 		    func_id != BPF_FUNC_kptr_xchg)
8600 			goto error;
8601 		break;
8602 	case BPF_MAP_TYPE_INODE_STORAGE:
8603 		if (func_id != BPF_FUNC_inode_storage_get &&
8604 		    func_id != BPF_FUNC_inode_storage_delete &&
8605 		    func_id != BPF_FUNC_kptr_xchg)
8606 			goto error;
8607 		break;
8608 	case BPF_MAP_TYPE_TASK_STORAGE:
8609 		if (func_id != BPF_FUNC_task_storage_get &&
8610 		    func_id != BPF_FUNC_task_storage_delete &&
8611 		    func_id != BPF_FUNC_kptr_xchg)
8612 			goto error;
8613 		break;
8614 	case BPF_MAP_TYPE_CGRP_STORAGE:
8615 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8616 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8617 		    func_id != BPF_FUNC_kptr_xchg)
8618 			goto error;
8619 		break;
8620 	case BPF_MAP_TYPE_BLOOM_FILTER:
8621 		if (func_id != BPF_FUNC_map_peek_elem &&
8622 		    func_id != BPF_FUNC_map_push_elem)
8623 			goto error;
8624 		break;
8625 	case BPF_MAP_TYPE_INSN_ARRAY:
8626 		goto error;
8627 	default:
8628 		break;
8629 	}
8630 
8631 	/* ... and second from the function itself. */
8632 	switch (func_id) {
8633 	case BPF_FUNC_tail_call:
8634 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8635 			goto error;
8636 		if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) {
8637 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
8638 			return -EINVAL;
8639 		}
8640 		break;
8641 	case BPF_FUNC_perf_event_read:
8642 	case BPF_FUNC_perf_event_output:
8643 	case BPF_FUNC_perf_event_read_value:
8644 	case BPF_FUNC_skb_output:
8645 	case BPF_FUNC_xdp_output:
8646 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8647 			goto error;
8648 		break;
8649 	case BPF_FUNC_ringbuf_output:
8650 	case BPF_FUNC_ringbuf_reserve:
8651 	case BPF_FUNC_ringbuf_query:
8652 	case BPF_FUNC_ringbuf_reserve_dynptr:
8653 	case BPF_FUNC_ringbuf_submit_dynptr:
8654 	case BPF_FUNC_ringbuf_discard_dynptr:
8655 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8656 			goto error;
8657 		break;
8658 	case BPF_FUNC_user_ringbuf_drain:
8659 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8660 			goto error;
8661 		break;
8662 	case BPF_FUNC_get_stackid:
8663 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8664 			goto error;
8665 		break;
8666 	case BPF_FUNC_current_task_under_cgroup:
8667 	case BPF_FUNC_skb_under_cgroup:
8668 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8669 			goto error;
8670 		break;
8671 	case BPF_FUNC_redirect_map:
8672 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8673 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8674 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8675 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8676 			goto error;
8677 		break;
8678 	case BPF_FUNC_sk_redirect_map:
8679 	case BPF_FUNC_msg_redirect_map:
8680 	case BPF_FUNC_sock_map_update:
8681 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8682 			goto error;
8683 		break;
8684 	case BPF_FUNC_sk_redirect_hash:
8685 	case BPF_FUNC_msg_redirect_hash:
8686 	case BPF_FUNC_sock_hash_update:
8687 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8688 			goto error;
8689 		break;
8690 	case BPF_FUNC_get_local_storage:
8691 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8692 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8693 			goto error;
8694 		break;
8695 	case BPF_FUNC_sk_select_reuseport:
8696 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8697 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8698 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8699 			goto error;
8700 		break;
8701 	case BPF_FUNC_map_pop_elem:
8702 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8703 		    map->map_type != BPF_MAP_TYPE_STACK)
8704 			goto error;
8705 		break;
8706 	case BPF_FUNC_map_peek_elem:
8707 	case BPF_FUNC_map_push_elem:
8708 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8709 		    map->map_type != BPF_MAP_TYPE_STACK &&
8710 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8711 			goto error;
8712 		break;
8713 	case BPF_FUNC_map_lookup_percpu_elem:
8714 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8715 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8716 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8717 			goto error;
8718 		break;
8719 	case BPF_FUNC_sk_storage_get:
8720 	case BPF_FUNC_sk_storage_delete:
8721 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8722 			goto error;
8723 		break;
8724 	case BPF_FUNC_inode_storage_get:
8725 	case BPF_FUNC_inode_storage_delete:
8726 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8727 			goto error;
8728 		break;
8729 	case BPF_FUNC_task_storage_get:
8730 	case BPF_FUNC_task_storage_delete:
8731 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8732 			goto error;
8733 		break;
8734 	case BPF_FUNC_cgrp_storage_get:
8735 	case BPF_FUNC_cgrp_storage_delete:
8736 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8737 			goto error;
8738 		break;
8739 	default:
8740 		break;
8741 	}
8742 
8743 	return 0;
8744 error:
8745 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
8746 		map->map_type, func_id_name(func_id), func_id);
8747 	return -EINVAL;
8748 }
8749 
8750 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8751 {
8752 	int count = 0;
8753 
8754 	if (arg_type_is_raw_mem(fn->arg1_type))
8755 		count++;
8756 	if (arg_type_is_raw_mem(fn->arg2_type))
8757 		count++;
8758 	if (arg_type_is_raw_mem(fn->arg3_type))
8759 		count++;
8760 	if (arg_type_is_raw_mem(fn->arg4_type))
8761 		count++;
8762 	if (arg_type_is_raw_mem(fn->arg5_type))
8763 		count++;
8764 
8765 	/* We only support one arg being in raw mode at the moment,
8766 	 * which is sufficient for the helper functions we have
8767 	 * right now.
8768 	 */
8769 	return count <= 1;
8770 }
8771 
8772 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8773 {
8774 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8775 	bool has_size = fn->arg_size[arg] != 0;
8776 	bool is_next_size = false;
8777 
8778 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8779 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8780 
8781 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8782 		return is_next_size;
8783 
8784 	return has_size == is_next_size || is_next_size == is_fixed;
8785 }
8786 
8787 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8788 {
8789 	/* bpf_xxx(..., buf, len) call will access 'len'
8790 	 * bytes from memory 'buf'. Both arg types need
8791 	 * to be paired, so make sure there's no buggy
8792 	 * helper function specification.
8793 	 */
8794 	if (arg_type_is_mem_size(fn->arg1_type) ||
8795 	    check_args_pair_invalid(fn, 0) ||
8796 	    check_args_pair_invalid(fn, 1) ||
8797 	    check_args_pair_invalid(fn, 2) ||
8798 	    check_args_pair_invalid(fn, 3) ||
8799 	    check_args_pair_invalid(fn, 4))
8800 		return false;
8801 
8802 	return true;
8803 }
8804 
8805 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8806 {
8807 	int i;
8808 
8809 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8810 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8811 			return !!fn->arg_btf_id[i];
8812 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8813 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
8814 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8815 		    /* arg_btf_id and arg_size are in a union. */
8816 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8817 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8818 			return false;
8819 	}
8820 
8821 	return true;
8822 }
8823 
8824 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn)
8825 {
8826 	int i;
8827 
8828 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8829 		enum bpf_arg_type arg_type = fn->arg_type[i];
8830 
8831 		if (base_type(arg_type) != ARG_PTR_TO_MEM)
8832 			continue;
8833 		if (!(arg_type & (MEM_WRITE | MEM_RDONLY)))
8834 			return false;
8835 	}
8836 
8837 	return true;
8838 }
8839 
8840 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
8841 {
8842 	int i;
8843 
8844 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8845 		enum bpf_arg_type arg_type = fn->arg_type[i];
8846 
8847 		if (arg_type_is_release(arg_type)) {
8848 			if (meta->release_regno)
8849 				return false;
8850 			meta->release_regno = i + 1;
8851 		}
8852 	}
8853 
8854 	return true;
8855 }
8856 
8857 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta)
8858 {
8859 	return check_raw_mode_ok(fn) &&
8860 	       check_arg_pair_ok(fn) &&
8861 	       check_mem_arg_rw_flag_ok(fn) &&
8862 	       check_proto_release_reg(fn, meta) &&
8863 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
8864 }
8865 
8866 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8867  * are now invalid, so turn them into unknown SCALAR_VALUE.
8868  *
8869  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8870  * since these slices point to packet data.
8871  */
8872 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8873 {
8874 	struct bpf_func_state *state;
8875 	struct bpf_reg_state *reg;
8876 
8877 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8878 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8879 			mark_reg_invalid(env, reg);
8880 	}));
8881 }
8882 
8883 enum {
8884 	AT_PKT_END = -1,
8885 	BEYOND_PKT_END = -2,
8886 };
8887 
8888 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8889 {
8890 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8891 	struct bpf_reg_state *reg = &state->regs[regn];
8892 
8893 	if (reg->type != PTR_TO_PACKET)
8894 		/* PTR_TO_PACKET_META is not supported yet */
8895 		return;
8896 
8897 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8898 	 * How far beyond pkt_end it goes is unknown.
8899 	 * if (!range_open) it's the case of pkt >= pkt_end
8900 	 * if (range_open) it's the case of pkt > pkt_end
8901 	 * hence this pointer is at least 1 byte bigger than pkt_end
8902 	 */
8903 	if (range_open)
8904 		reg->range = BEYOND_PKT_END;
8905 	else
8906 		reg->range = AT_PKT_END;
8907 }
8908 
8909 static int release_reference_nomark(struct bpf_verifier_state *state, int id)
8910 {
8911 	int i;
8912 
8913 	for (i = 0; i < state->acquired_refs; i++) {
8914 		if (state->refs[i].type != REF_TYPE_PTR)
8915 			continue;
8916 		if (state->refs[i].id == id) {
8917 			release_reference_state(state, i);
8918 			return 0;
8919 		}
8920 	}
8921 	return -EINVAL;
8922 }
8923 
8924 static int idstack_push(struct bpf_idmap *idmap, u32 id)
8925 {
8926 	int i;
8927 
8928 	if (!id)
8929 		return 0;
8930 
8931 	for (i = 0; i < idmap->cnt; i++)
8932 		if (idmap->map[i].old == id)
8933 			return 0;
8934 
8935 	if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE))
8936 		return -EFAULT;
8937 
8938 	idmap->map[idmap->cnt++].old = id;
8939 	return 0;
8940 }
8941 
8942 static int idstack_pop(struct bpf_idmap *idmap)
8943 {
8944 	if (!idmap->cnt)
8945 		return 0;
8946 
8947 	return idmap->map[--idmap->cnt].old;
8948 }
8949 
8950 /* Release id and objects derived from it iteratively in a DFS manner */
8951 static int release_reference(struct bpf_verifier_env *env, int id)
8952 {
8953 	u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR);
8954 	struct bpf_verifier_state *vstate = env->cur_state;
8955 	struct bpf_idmap *idstack = &env->idmap_scratch;
8956 	struct bpf_stack_state *stack;
8957 	struct bpf_func_state *state;
8958 	struct bpf_reg_state *reg;
8959 	int i, err;
8960 
8961 	idstack->cnt = 0;
8962 	err = idstack_push(idstack, id);
8963 	if (err)
8964 		return err;
8965 
8966 	if (find_reference_state(vstate, id))
8967 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
8968 
8969 	while ((id = idstack_pop(idstack))) {
8970 		/*
8971 		 * Child references are inaccessible after parent is released,
8972 		 * any child references that exist at this point are a leak.
8973 		 */
8974 		for (i = 0; i < vstate->acquired_refs; i++) {
8975 			if (vstate->refs[i].type != REF_TYPE_PTR)
8976 				continue;
8977 			if (vstate->refs[i].parent_id != id)
8978 				continue;
8979 			verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n",
8980 				vstate->refs[i].id, vstate->refs[i].insn_idx);
8981 			return -EINVAL;
8982 		}
8983 
8984 		bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
8985 			if (reg->id != id && reg->parent_id != id)
8986 				continue;
8987 
8988 			/* Free objects derived from the current object */
8989 			if (reg->parent_id == id) {
8990 				err = idstack_push(idstack, reg->id);
8991 				if (err)
8992 					return err;
8993 			}
8994 
8995 			if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL)
8996 				mark_reg_invalid(env, reg);
8997 			else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR)
8998 				invalidate_dynptr(env, stack);
8999 		}));
9000 	}
9001 
9002 	return 0;
9003 }
9004 
9005 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9006 {
9007 	struct bpf_func_state *unused;
9008 	struct bpf_reg_state *reg;
9009 
9010 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9011 		if (type_is_non_owning_ref(reg->type))
9012 			mark_reg_invalid(env, reg);
9013 	}));
9014 }
9015 
9016 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)
9017 {
9018 	struct bpf_stack_state *stack;
9019 	struct bpf_func_state *state;
9020 	struct bpf_reg_state *reg;
9021 	u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
9022 
9023 	bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({
9024 		if (reg->type & MEM_RCU) {
9025 			reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
9026 			reg->type |= PTR_UNTRUSTED;
9027 		}
9028 	}));
9029 }
9030 
9031 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
9032 {
9033 	struct bpf_func_state *state;
9034 	struct bpf_reg_state *reg;
9035 	int err;
9036 
9037 	err = release_reference_nomark(env->cur_state, id);
9038 
9039 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9040 		if (reg->id != id)
9041 			continue;
9042 		if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
9043 			reg->id = 0;
9044 			reg->type &= ~MEM_ALLOC;
9045 			reg->type |= MEM_RCU;
9046 		}
9047 	}));
9048 
9049 	return err;
9050 }
9051 
9052 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9053 				    struct bpf_reg_state *regs)
9054 {
9055 	int i;
9056 
9057 	/* after the call registers r0 - r5 were scratched */
9058 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9059 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
9060 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9061 	}
9062 }
9063 
9064 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env,
9065 					   struct bpf_func_state *state)
9066 {
9067 	int i, nslots = state->out_stack_arg_cnt;
9068 
9069 	for (i = 0; i < nslots; i++)
9070 		bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]);
9071 }
9072 
9073 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9074 				   struct bpf_func_state *caller,
9075 				   struct bpf_func_state *callee,
9076 				   int insn_idx);
9077 
9078 static int set_callee_state(struct bpf_verifier_env *env,
9079 			    struct bpf_func_state *caller,
9080 			    struct bpf_func_state *callee, int insn_idx);
9081 
9082 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9083 			    set_callee_state_fn set_callee_state_cb,
9084 			    struct bpf_verifier_state *state)
9085 {
9086 	struct bpf_func_state *caller, *callee;
9087 	int err;
9088 
9089 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9090 		verbose(env, "the call stack of %d frames is too deep\n",
9091 			state->curframe + 2);
9092 		return -E2BIG;
9093 	}
9094 
9095 	if (state->frame[state->curframe + 1]) {
9096 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
9097 		return -EFAULT;
9098 	}
9099 
9100 	caller = state->frame[state->curframe];
9101 	callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);
9102 	if (!callee)
9103 		return -ENOMEM;
9104 	state->frame[state->curframe + 1] = callee;
9105 
9106 	/* callee cannot access r0, r6 - r9 for reading and has to write
9107 	 * into its own stack before reading from it.
9108 	 * callee can read/write into caller's stack
9109 	 */
9110 	init_func_state(env, callee,
9111 			/* remember the callsite, it will be used by bpf_exit */
9112 			callsite,
9113 			state->curframe + 1 /* frameno within this callchain */,
9114 			subprog /* subprog number within this prog */);
9115 	err = set_callee_state_cb(env, caller, callee, callsite);
9116 	if (err)
9117 		goto err_out;
9118 
9119 	/* only increment it after check_reg_arg() finished */
9120 	state->curframe++;
9121 
9122 	return 0;
9123 
9124 err_out:
9125 	free_func_state(callee);
9126 	state->frame[state->curframe + 1] = NULL;
9127 	return err;
9128 }
9129 
9130 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9131 				    const struct btf *btf,
9132 				    struct bpf_reg_state *regs)
9133 {
9134 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9135 	struct bpf_func_state *caller = cur_func(env);
9136 	struct bpf_verifier_log *log = &env->log;
9137 	struct ref_obj_desc ref_obj = {};
9138 	u32 i;
9139 	int ret, err;
9140 
9141 	ret = btf_prepare_func_args(env, subprog);
9142 	if (ret) {
9143 		if (bpf_in_stack_arg_cnt(sub) > 0) {
9144 			err = check_outgoing_stack_args(env, caller, sub->arg_cnt);
9145 			if (err)
9146 				return err;
9147 		}
9148 		return ret;
9149 	}
9150 
9151 	ret = check_outgoing_stack_args(env, caller, sub->arg_cnt);
9152 	if (ret)
9153 		return ret;
9154 
9155 	/* check that BTF function arguments match actual types that the
9156 	 * verifier sees.
9157 	 */
9158 	for (i = 0; i < sub->arg_cnt; i++) {
9159 		argno_t argno = argno_from_arg(i + 1);
9160 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
9161 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9162 
9163 		if (arg->arg_type == ARG_ANYTHING) {
9164 			if (reg->type != SCALAR_VALUE) {
9165 				bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno));
9166 				return -EINVAL;
9167 			}
9168 		} else if (arg->arg_type & PTR_UNTRUSTED) {
9169 			/*
9170 			 * Anything is allowed for untrusted arguments, as these are
9171 			 * read-only and probe read instructions would protect against
9172 			 * invalid memory access.
9173 			 */
9174 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9175 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX);
9176 			if (ret < 0)
9177 				return ret;
9178 			/* If function expects ctx type in BTF check that caller
9179 			 * is passing PTR_TO_CTX.
9180 			 */
9181 			if (reg->type != PTR_TO_CTX) {
9182 				bpf_log(log, "%s expects pointer to ctx\n",
9183 					reg_arg_name(env, argno));
9184 				return -EINVAL;
9185 			}
9186 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9187 			ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE);
9188 			if (ret < 0)
9189 				return ret;
9190 			if (check_mem_reg(env, reg, argno, arg->mem_size))
9191 				return -EINVAL;
9192 			if (!(arg->arg_type & PTR_MAYBE_NULL) &&
9193 			    (type_may_be_null(reg->type) || bpf_register_is_null(reg))) {
9194 				bpf_log(log, "%s is expected to be non-NULL\n",
9195 					reg_arg_name(env, argno));
9196 				return -EINVAL;
9197 			}
9198 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9199 			/*
9200 			 * Can pass any value and the kernel won't crash, but
9201 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9202 			 * else is a bug in the bpf program. Point it out to
9203 			 * the user at the verification time instead of
9204 			 * run-time debug nightmare.
9205 			 */
9206 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9207 				bpf_log(log, "%s is not a pointer to arena or scalar.\n",
9208 					reg_arg_name(env, argno));
9209 				return -EINVAL;
9210 			}
9211 		} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
9212 			ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR);
9213 			if (ret)
9214 				return ret;
9215 
9216 			ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL);
9217 			if (ret)
9218 				return ret;
9219 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9220 			struct bpf_call_arg_meta meta;
9221 			int err;
9222 
9223 			if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type))
9224 				continue;
9225 
9226 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9227 			err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta);
9228 			err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type);
9229 			if (err)
9230 				return err;
9231 		} else {
9232 			verifier_bug(env, "unrecognized %s type %d",
9233 				     reg_arg_name(env, argno), arg->arg_type);
9234 			return -EFAULT;
9235 		}
9236 	}
9237 
9238 	return 0;
9239 }
9240 
9241 /* Compare BTF of a function call with given bpf_reg_state.
9242  * Returns:
9243  * EFAULT - there is a verifier bug. Abort verification.
9244  * EINVAL - there is a type mismatch or BTF is not available.
9245  * 0 - BTF matches with what bpf_reg_state expects.
9246  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9247  */
9248 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9249 				  struct bpf_reg_state *regs)
9250 {
9251 	struct bpf_prog *prog = env->prog;
9252 	struct btf *btf = prog->aux->btf;
9253 	u32 btf_id;
9254 	int err;
9255 
9256 	if (!prog->aux->func_info)
9257 		return -EINVAL;
9258 
9259 	btf_id = prog->aux->func_info[subprog].type_id;
9260 	if (!btf_id)
9261 		return -EFAULT;
9262 
9263 	if (prog->aux->func_info_aux[subprog].unreliable)
9264 		return -EINVAL;
9265 
9266 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9267 	/* Compiler optimizations can remove arguments from static functions
9268 	 * or mismatched type can be passed into a global function.
9269 	 * In such cases mark the function as unreliable from BTF point of view.
9270 	 */
9271 	if (err)
9272 		prog->aux->func_info_aux[subprog].unreliable = true;
9273 	return err;
9274 }
9275 
9276 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9277 			      int insn_idx, int subprog,
9278 			      set_callee_state_fn set_callee_state_cb)
9279 {
9280 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9281 	struct bpf_func_state *caller, *callee;
9282 	int err;
9283 
9284 	caller = state->frame[state->curframe];
9285 	err = btf_check_subprog_call(env, subprog, caller->regs);
9286 	if (err == -EFAULT)
9287 		return err;
9288 
9289 	/* set_callee_state is used for direct subprog calls, but we are
9290 	 * interested in validating only BPF helpers that can call subprogs as
9291 	 * callbacks
9292 	 */
9293 	env->subprog_info[subprog].is_cb = true;
9294 	if (bpf_pseudo_kfunc_call(insn) &&
9295 	    !is_callback_calling_kfunc(insn->imm)) {
9296 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
9297 			     func_id_name(insn->imm), insn->imm);
9298 		return -EFAULT;
9299 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9300 		   !is_callback_calling_function(insn->imm)) { /* helper */
9301 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
9302 			     func_id_name(insn->imm), insn->imm);
9303 		return -EFAULT;
9304 	}
9305 
9306 	if (bpf_is_async_callback_calling_insn(insn)) {
9307 		struct bpf_verifier_state *async_cb;
9308 
9309 		/* there is no real recursion here. timer and workqueue callbacks are async */
9310 		env->subprog_info[subprog].is_async_cb = true;
9311 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9312 					 insn_idx, subprog,
9313 					 is_async_cb_sleepable(env, insn));
9314 		if (IS_ERR(async_cb))
9315 			return PTR_ERR(async_cb);
9316 		callee = async_cb->frame[0];
9317 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9318 
9319 		/* Convert bpf_timer_set_callback() args into timer callback args */
9320 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9321 		if (err)
9322 			return err;
9323 
9324 		return 0;
9325 	}
9326 
9327 	/* for callback functions enqueue entry to callback and
9328 	 * proceed with next instruction within current frame.
9329 	 */
9330 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9331 	if (IS_ERR(callback_state))
9332 		return PTR_ERR(callback_state);
9333 
9334 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9335 			       callback_state);
9336 	if (err)
9337 		return err;
9338 
9339 	callback_state->callback_unroll_depth++;
9340 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9341 	caller->callback_depth = 0;
9342 	return 0;
9343 }
9344 
9345 static int process_bpf_exit_full(struct bpf_verifier_env *env,
9346 				 bool *do_print_state, bool exception_exit);
9347 
9348 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9349 			   int *insn_idx)
9350 {
9351 	struct bpf_verifier_state *state = env->cur_state;
9352 	struct bpf_subprog_info *caller_info;
9353 	u16 callee_incoming, stack_arg_cnt;
9354 	struct bpf_func_state *caller;
9355 	int err, subprog, target_insn;
9356 
9357 	target_insn = *insn_idx + insn->imm + 1;
9358 	subprog = bpf_find_subprog(env, target_insn);
9359 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
9360 			    target_insn))
9361 		return -EFAULT;
9362 
9363 	caller = state->frame[state->curframe];
9364 	err = btf_check_subprog_call(env, subprog, caller->regs);
9365 	if (err == -EFAULT)
9366 		return err;
9367 	if (bpf_subprog_is_global(env, subprog)) {
9368 		const char *sub_name = subprog_name(env, subprog);
9369 
9370 		if (env->cur_state->active_locks) {
9371 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9372 				     "use static function instead\n");
9373 			return -EINVAL;
9374 		}
9375 
9376 		if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) {
9377 			verbose(env, "sleepable global function %s() called in %s\n",
9378 				sub_name, non_sleepable_context_description(env));
9379 			return -EINVAL;
9380 		}
9381 
9382 		if (err) {
9383 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9384 				subprog, sub_name);
9385 			return err;
9386 		}
9387 
9388 		if (env->log.level & BPF_LOG_LEVEL)
9389 			verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9390 				subprog, sub_name);
9391 		if (env->subprog_info[subprog].changes_pkt_data)
9392 			clear_all_pkt_pointers(env);
9393 		/* mark global subprog for verifying after main prog */
9394 		subprog_aux(env, subprog)->called = true;
9395 		clear_caller_saved_regs(env, caller->regs);
9396 		invalidate_outgoing_stack_args(env, cur_func(env));
9397 
9398 		/* All non-void global functions return a 64-bit SCALAR_VALUE. */
9399 		if (!subprog_returns_void(env, subprog)) {
9400 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
9401 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9402 		}
9403 
9404 		if (env->subprog_info[subprog].might_throw) {
9405 			struct bpf_verifier_state *branch;
9406 
9407 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
9408 			if (IS_ERR(branch)) {
9409 				verbose(env, "failed to push state for global subprog exception path\n");
9410 				return PTR_ERR(branch);
9411 			}
9412 			return process_bpf_exit_full(env, NULL, true);
9413 		}
9414 
9415 		/* continue with next insn after call */
9416 		return 0;
9417 	}
9418 
9419 	/*
9420 	 * Track caller's total stack arg count (incoming + max outgoing).
9421 	 * This is needed so the JIT knows how much stack arg space to allocate.
9422 	 */
9423 	caller_info = &env->subprog_info[caller->subprogno];
9424 	callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]);
9425 	stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming;
9426 	if (stack_arg_cnt > caller_info->stack_arg_cnt)
9427 		caller_info->stack_arg_cnt = stack_arg_cnt;
9428 
9429 	/* for regular function entry setup new frame and continue
9430 	 * from that frame.
9431 	 */
9432 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9433 	if (err)
9434 		return err;
9435 
9436 	clear_caller_saved_regs(env, caller->regs);
9437 
9438 	/* and go analyze first insn of the callee */
9439 	*insn_idx = env->subprog_info[subprog].start - 1;
9440 
9441 	if (env->log.level & BPF_LOG_LEVEL) {
9442 		verbose(env, "caller:\n");
9443 		print_verifier_state(env, state, caller->frameno, true);
9444 		verbose(env, "callee:\n");
9445 		print_verifier_state(env, state, state->curframe, true);
9446 	}
9447 
9448 	return 0;
9449 }
9450 
9451 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9452 				   struct bpf_func_state *caller,
9453 				   struct bpf_func_state *callee)
9454 {
9455 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9456 	 *      void *callback_ctx, u64 flags);
9457 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9458 	 *      void *callback_ctx);
9459 	 */
9460 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9461 
9462 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9463 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9464 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9465 
9466 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9467 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9468 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9469 
9470 	/* pointer to stack or null */
9471 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9472 
9473 	/* unused */
9474 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9475 	return 0;
9476 }
9477 
9478 static int set_callee_state(struct bpf_verifier_env *env,
9479 			    struct bpf_func_state *caller,
9480 			    struct bpf_func_state *callee, int insn_idx)
9481 {
9482 	int i;
9483 
9484 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9485 	 * pointers, which connects us up to the liveness chain
9486 	 */
9487 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9488 		callee->regs[i] = caller->regs[i];
9489 	return 0;
9490 }
9491 
9492 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9493 				       struct bpf_func_state *caller,
9494 				       struct bpf_func_state *callee,
9495 				       int insn_idx)
9496 {
9497 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9498 	struct bpf_map *map;
9499 	int err;
9500 
9501 	/* valid map_ptr and poison value does not matter */
9502 	map = insn_aux->map_ptr_state.map_ptr;
9503 	if (!map->ops->map_set_for_each_callback_args ||
9504 	    !map->ops->map_for_each_callback) {
9505 		verbose(env, "callback function not allowed for map\n");
9506 		return -ENOTSUPP;
9507 	}
9508 
9509 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9510 	if (err)
9511 		return err;
9512 
9513 	callee->in_callback_fn = true;
9514 	callee->callback_ret_range = retval_range(0, 1);
9515 	return 0;
9516 }
9517 
9518 static int set_loop_callback_state(struct bpf_verifier_env *env,
9519 				   struct bpf_func_state *caller,
9520 				   struct bpf_func_state *callee,
9521 				   int insn_idx)
9522 {
9523 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9524 	 *	    u64 flags);
9525 	 * callback_fn(u64 index, void *callback_ctx);
9526 	 */
9527 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9528 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9529 
9530 	/* unused */
9531 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9532 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9533 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9534 
9535 	callee->in_callback_fn = true;
9536 	callee->callback_ret_range = retval_range(0, 1);
9537 	return 0;
9538 }
9539 
9540 static int set_timer_callback_state(struct bpf_verifier_env *env,
9541 				    struct bpf_func_state *caller,
9542 				    struct bpf_func_state *callee,
9543 				    int insn_idx)
9544 {
9545 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9546 
9547 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9548 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9549 	 */
9550 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9551 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9552 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9553 
9554 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9555 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9556 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9557 
9558 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9559 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9560 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9561 
9562 	/* unused */
9563 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9564 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9565 	callee->in_async_callback_fn = true;
9566 	callee->callback_ret_range = retval_range(0, 0);
9567 	return 0;
9568 }
9569 
9570 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9571 				       struct bpf_func_state *caller,
9572 				       struct bpf_func_state *callee,
9573 				       int insn_idx)
9574 {
9575 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9576 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9577 	 * (callback_fn)(struct task_struct *task,
9578 	 *               struct vm_area_struct *vma, void *callback_ctx);
9579 	 */
9580 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9581 
9582 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9583 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9584 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9585 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9586 
9587 	/* pointer to stack or null */
9588 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9589 
9590 	/* unused */
9591 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9592 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9593 	callee->in_callback_fn = true;
9594 	callee->callback_ret_range = retval_range(0, 1);
9595 	return 0;
9596 }
9597 
9598 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9599 					   struct bpf_func_state *caller,
9600 					   struct bpf_func_state *callee,
9601 					   int insn_idx)
9602 {
9603 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9604 	 *			  callback_ctx, u64 flags);
9605 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9606 	 */
9607 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9608 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9609 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9610 
9611 	/* unused */
9612 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9613 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9614 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9615 
9616 	callee->in_callback_fn = true;
9617 	callee->callback_ret_range = retval_range(0, 1);
9618 	return 0;
9619 }
9620 
9621 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9622 					 struct bpf_func_state *caller,
9623 					 struct bpf_func_state *callee,
9624 					 int insn_idx)
9625 {
9626 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9627 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9628 	 *
9629 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9630 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9631 	 * by this point, so look at 'root'
9632 	 */
9633 	struct btf_field *field;
9634 
9635 	field = reg_find_field_offset(&caller->regs[BPF_REG_1],
9636 				      caller->regs[BPF_REG_1].var_off.value,
9637 				      BPF_RB_ROOT);
9638 	if (!field || !field->graph_root.value_btf_id)
9639 		return -EFAULT;
9640 
9641 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9642 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9643 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9644 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9645 
9646 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9647 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9648 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9649 	callee->in_callback_fn = true;
9650 	callee->callback_ret_range = retval_range(0, 1);
9651 	return 0;
9652 }
9653 
9654 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
9655 						 struct bpf_func_state *caller,
9656 						 struct bpf_func_state *callee,
9657 						 int insn_idx)
9658 {
9659 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
9660 
9661 	/*
9662 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9663 	 */
9664 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9665 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9666 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9667 
9668 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9669 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9670 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9671 
9672 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9673 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9674 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9675 
9676 	/* unused */
9677 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9678 	bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9679 	callee->in_async_callback_fn = true;
9680 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
9681 	return 0;
9682 }
9683 
9684 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9685 
9686 /* Are we currently verifying the callback for a rbtree helper that must
9687  * be called with lock held? If so, no need to complain about unreleased
9688  * lock
9689  */
9690 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9691 {
9692 	struct bpf_verifier_state *state = env->cur_state;
9693 	struct bpf_insn *insn = env->prog->insnsi;
9694 	struct bpf_func_state *callee;
9695 	int kfunc_btf_id;
9696 
9697 	if (!state->curframe)
9698 		return false;
9699 
9700 	callee = state->frame[state->curframe];
9701 
9702 	if (!callee->in_callback_fn)
9703 		return false;
9704 
9705 	kfunc_btf_id = insn[callee->callsite].imm;
9706 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9707 }
9708 
9709 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9710 {
9711 	if (range.return_32bit)
9712 		return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval;
9713 	else
9714 		return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval;
9715 }
9716 
9717 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9718 {
9719 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9720 	struct bpf_func_state *caller, *callee;
9721 	struct bpf_reg_state *r0;
9722 	bool in_callback_fn;
9723 	int err;
9724 
9725 	callee = state->frame[state->curframe];
9726 	r0 = &callee->regs[BPF_REG_0];
9727 	if (r0->type == PTR_TO_STACK) {
9728 		/* technically it's ok to return caller's stack pointer
9729 		 * (or caller's caller's pointer) back to the caller,
9730 		 * since these pointers are valid. Only current stack
9731 		 * pointer will be invalid as soon as function exits,
9732 		 * but let's be conservative
9733 		 */
9734 		verbose(env, "cannot return stack pointer to the caller\n");
9735 		return -EINVAL;
9736 	}
9737 
9738 	caller = state->frame[state->curframe - 1];
9739 	if (callee->in_callback_fn) {
9740 		if (r0->type != SCALAR_VALUE) {
9741 			verbose(env, "R0 not a scalar value\n");
9742 			return -EACCES;
9743 		}
9744 
9745 		/* we are going to rely on register's precise value */
9746 		err = mark_chain_precision(env, BPF_REG_0);
9747 		if (err)
9748 			return err;
9749 
9750 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
9751 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9752 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9753 					       "At callback return", "R0");
9754 			return -EINVAL;
9755 		}
9756 		if (!bpf_calls_callback(env, callee->callsite)) {
9757 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
9758 				     *insn_idx, callee->callsite);
9759 			return -EFAULT;
9760 		}
9761 	} else {
9762 		/* return to the caller whatever r0 had in the callee */
9763 		caller->regs[BPF_REG_0] = *r0;
9764 	}
9765 
9766 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9767 	 * there function call logic would reschedule callback visit. If iteration
9768 	 * converges is_state_visited() would prune that visit eventually.
9769 	 */
9770 	in_callback_fn = callee->in_callback_fn;
9771 	if (in_callback_fn)
9772 		*insn_idx = callee->callsite;
9773 	else
9774 		*insn_idx = callee->callsite + 1;
9775 
9776 	if (env->log.level & BPF_LOG_LEVEL) {
9777 		verbose(env, "returning from callee:\n");
9778 		print_verifier_state(env, state, callee->frameno, true);
9779 		verbose(env, "to caller at %d:\n", *insn_idx);
9780 		print_verifier_state(env, state, caller->frameno, true);
9781 	}
9782 	/* clear everything in the callee. In case of exceptional exits using
9783 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9784 	free_func_state(callee);
9785 	state->frame[state->curframe--] = NULL;
9786 	invalidate_outgoing_stack_args(env, caller);
9787 
9788 	/* for callbacks widen imprecise scalars to make programs like below verify:
9789 	 *
9790 	 *   struct ctx { int i; }
9791 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9792 	 *   ...
9793 	 *   struct ctx = { .i = 0; }
9794 	 *   bpf_loop(100, cb, &ctx, 0);
9795 	 *
9796 	 * This is similar to what is done in process_iter_next_call() for open
9797 	 * coded iterators.
9798 	 */
9799 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9800 	if (prev_st) {
9801 		err = widen_imprecise_scalars(env, prev_st, state);
9802 		if (err)
9803 			return err;
9804 	}
9805 	return 0;
9806 }
9807 
9808 static int do_refine_retval_range(struct bpf_verifier_env *env,
9809 				  struct bpf_reg_state *regs, int ret_type,
9810 				  int func_id,
9811 				  struct bpf_call_arg_meta *meta)
9812 {
9813 	struct bpf_retval_range range;
9814 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9815 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9816 
9817 	if (ret_type != RET_INTEGER)
9818 		return 0;
9819 
9820 	switch (func_id) {
9821 	case BPF_FUNC_get_stack:
9822 	case BPF_FUNC_get_task_stack:
9823 	case BPF_FUNC_probe_read_str:
9824 	case BPF_FUNC_probe_read_kernel_str:
9825 	case BPF_FUNC_probe_read_user_str:
9826 		reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value);
9827 		reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value);
9828 		reg_bounds_sync(ret_reg);
9829 		break;
9830 	case BPF_FUNC_get_smp_processor_id:
9831 		reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1);
9832 		reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1);
9833 		reg_bounds_sync(ret_reg);
9834 		break;
9835 	case BPF_FUNC_get_retval:
9836 		/*
9837 		 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for
9838 		 * CGROUP_GETSOCKOPT type.
9839 		 */
9840 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
9841 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
9842 			break;
9843 
9844 		if (prog_type == BPF_PROG_TYPE_LSM &&
9845 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9846 			if (!env->prog->aux->attach_func_proto->type)
9847 				break;
9848 			bpf_lsm_get_retval_range(env->prog, &range);
9849 		} else {
9850 			range.minval = -MAX_ERRNO;
9851 			range.maxval = 0;
9852 		}
9853 
9854 		reg_set_srange64(ret_reg, range.minval, range.maxval);
9855 		reg_set_srange32(ret_reg, range.minval, range.maxval);
9856 		reg_bounds_sync(ret_reg);
9857 		break;
9858 	}
9859 
9860 	return reg_bounds_sanity_check(env, ret_reg, "retval");
9861 }
9862 
9863 static int
9864 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9865 		int func_id, int insn_idx)
9866 {
9867 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9868 	struct bpf_map *map = meta->map.ptr;
9869 
9870 	if (func_id != BPF_FUNC_tail_call &&
9871 	    func_id != BPF_FUNC_map_lookup_elem &&
9872 	    func_id != BPF_FUNC_map_update_elem &&
9873 	    func_id != BPF_FUNC_map_delete_elem &&
9874 	    func_id != BPF_FUNC_map_push_elem &&
9875 	    func_id != BPF_FUNC_map_pop_elem &&
9876 	    func_id != BPF_FUNC_map_peek_elem &&
9877 	    func_id != BPF_FUNC_for_each_map_elem &&
9878 	    func_id != BPF_FUNC_redirect_map &&
9879 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9880 		return 0;
9881 
9882 	if (map == NULL) {
9883 		verifier_bug(env, "expected map for helper call");
9884 		return -EFAULT;
9885 	}
9886 
9887 	/* In case of read-only, some additional restrictions
9888 	 * need to be applied in order to prevent altering the
9889 	 * state of the map from program side.
9890 	 */
9891 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9892 	    (func_id == BPF_FUNC_map_delete_elem ||
9893 	     func_id == BPF_FUNC_map_update_elem ||
9894 	     func_id == BPF_FUNC_map_push_elem ||
9895 	     func_id == BPF_FUNC_map_pop_elem)) {
9896 		verbose(env, "write into map forbidden\n");
9897 		return -EACCES;
9898 	}
9899 
9900 	if (!aux->map_ptr_state.map_ptr)
9901 		bpf_map_ptr_store(aux, meta->map.ptr,
9902 				  !meta->map.ptr->bypass_spec_v1, false);
9903 	else if (aux->map_ptr_state.map_ptr != meta->map.ptr)
9904 		bpf_map_ptr_store(aux, meta->map.ptr,
9905 				  !meta->map.ptr->bypass_spec_v1, true);
9906 	return 0;
9907 }
9908 
9909 static int
9910 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9911 		int func_id, int insn_idx)
9912 {
9913 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9914 	struct bpf_reg_state *reg;
9915 	struct bpf_map *map = meta->map.ptr;
9916 	u64 val, max;
9917 	int err;
9918 
9919 	if (func_id != BPF_FUNC_tail_call)
9920 		return 0;
9921 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9922 		verbose(env, "expected prog array map for tail call");
9923 		return -EINVAL;
9924 	}
9925 
9926 	reg = reg_state(env, BPF_REG_3);
9927 	val = reg->var_off.value;
9928 	max = map->max_entries;
9929 
9930 	if (!(is_reg_const(reg, false) && val < max)) {
9931 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9932 		return 0;
9933 	}
9934 
9935 	err = mark_chain_precision(env, BPF_REG_3);
9936 	if (err)
9937 		return err;
9938 	if (bpf_map_key_unseen(aux))
9939 		bpf_map_key_store(aux, val);
9940 	else if (!bpf_map_key_poisoned(aux) &&
9941 		  bpf_map_key_immediate(aux) != val)
9942 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9943 	return 0;
9944 }
9945 
9946 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9947 {
9948 	struct bpf_verifier_state *state = env->cur_state;
9949 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9950 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
9951 	bool refs_lingering = false;
9952 	int i;
9953 
9954 	if (!exception_exit && cur_func(env)->frameno)
9955 		return 0;
9956 
9957 	for (i = 0; i < state->acquired_refs; i++) {
9958 		if (state->refs[i].type != REF_TYPE_PTR)
9959 			continue;
9960 		/* Allow struct_ops programs to return a referenced kptr back to
9961 		 * kernel. Type checks are performed later in check_return_code.
9962 		 */
9963 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
9964 		    reg->id == state->refs[i].id)
9965 			continue;
9966 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9967 			state->refs[i].id, state->refs[i].insn_idx);
9968 		refs_lingering = true;
9969 	}
9970 	return refs_lingering ? -EINVAL : 0;
9971 }
9972 
9973 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
9974 {
9975 	int err;
9976 
9977 	if (check_lock && env->cur_state->active_locks) {
9978 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
9979 		return -EINVAL;
9980 	}
9981 
9982 	err = check_reference_leak(env, exception_exit);
9983 	if (err) {
9984 		verbose(env, "%s would lead to reference leak\n", prefix);
9985 		return err;
9986 	}
9987 
9988 	if (check_lock && env->cur_state->active_irq_id) {
9989 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
9990 		return -EINVAL;
9991 	}
9992 
9993 	if (check_lock && env->cur_state->active_rcu_locks) {
9994 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
9995 		return -EINVAL;
9996 	}
9997 
9998 	if (check_lock && env->cur_state->active_preempt_locks) {
9999 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
10000 		return -EINVAL;
10001 	}
10002 
10003 	return 0;
10004 }
10005 
10006 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10007 				   struct bpf_reg_state *regs)
10008 {
10009 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10010 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10011 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10012 	struct bpf_bprintf_data data = {};
10013 	int err, fmt_map_off, num_args;
10014 	u64 fmt_addr;
10015 	char *fmt;
10016 
10017 	/* data must be an array of u64 */
10018 	if (data_len_reg->var_off.value % 8)
10019 		return -EINVAL;
10020 	num_args = data_len_reg->var_off.value / 8;
10021 
10022 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10023 	 * and map_direct_value_addr is set.
10024 	 */
10025 	fmt_map_off = fmt_reg->var_off.value;
10026 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10027 						  fmt_map_off);
10028 	if (err) {
10029 		verbose(env, "failed to retrieve map value address\n");
10030 		return -EFAULT;
10031 	}
10032 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10033 
10034 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10035 	 * can focus on validating the format specifiers.
10036 	 */
10037 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10038 	if (err < 0)
10039 		verbose(env, "Invalid format string\n");
10040 
10041 	return err;
10042 }
10043 
10044 static int check_get_func_ip(struct bpf_verifier_env *env)
10045 {
10046 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10047 	int func_id = BPF_FUNC_get_func_ip;
10048 
10049 	if (type == BPF_PROG_TYPE_TRACING) {
10050 		if (!bpf_prog_has_trampoline(env->prog)) {
10051 			verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n",
10052 				func_id_name(func_id), func_id);
10053 			return -ENOTSUPP;
10054 		}
10055 		return 0;
10056 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10057 		return 0;
10058 	}
10059 
10060 	verbose(env, "func %s#%d not supported for program type %d\n",
10061 		func_id_name(func_id), func_id, type);
10062 	return -ENOTSUPP;
10063 }
10064 
10065 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
10066 {
10067 	return &env->insn_aux_data[env->insn_idx];
10068 }
10069 
10070 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10071 {
10072 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_4);
10073 	bool reg_is_null = bpf_register_is_null(reg);
10074 
10075 	if (reg_is_null)
10076 		mark_chain_precision(env, BPF_REG_4);
10077 
10078 	return reg_is_null;
10079 }
10080 
10081 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10082 {
10083 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10084 
10085 	if (!state->initialized) {
10086 		state->initialized = 1;
10087 		state->fit_for_inline = loop_flag_is_zero(env);
10088 		state->callback_subprogno = subprogno;
10089 		return;
10090 	}
10091 
10092 	if (!state->fit_for_inline)
10093 		return;
10094 
10095 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10096 				 state->callback_subprogno == subprogno);
10097 }
10098 
10099 /* Returns whether or not the given map can potentially elide
10100  * lookup return value nullness check. This is possible if the key
10101  * is statically known.
10102  */
10103 static bool can_elide_value_nullness(const struct bpf_map *map)
10104 {
10105 	if (map->map_flags & BPF_F_INNER_MAP)
10106 		return false;
10107 
10108 	switch (map->map_type) {
10109 	case BPF_MAP_TYPE_ARRAY:
10110 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10111 		return true;
10112 	default:
10113 		return false;
10114 	}
10115 }
10116 
10117 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
10118 			 const struct bpf_func_proto **ptr)
10119 {
10120 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10121 		return -ERANGE;
10122 
10123 	if (!env->ops->get_func_proto)
10124 		return -EINVAL;
10125 
10126 	*ptr = env->ops->get_func_proto(func_id, env->prog);
10127 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
10128 }
10129 
10130 /* Check if we're in a sleepable context. */
10131 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
10132 {
10133 	return !env->cur_state->active_rcu_locks &&
10134 	       !env->cur_state->active_preempt_locks &&
10135 	       !env->cur_state->active_locks &&
10136 	       !env->cur_state->active_irq_id &&
10137 	       in_sleepable(env);
10138 }
10139 
10140 static const char *non_sleepable_context_description(struct bpf_verifier_env *env)
10141 {
10142 	if (env->cur_state->active_rcu_locks)
10143 		return "rcu_read_lock region";
10144 	if (env->cur_state->active_preempt_locks)
10145 		return "non-preemptible region";
10146 	if (env->cur_state->active_irq_id)
10147 		return "IRQ-disabled region";
10148 	if (env->cur_state->active_locks)
10149 		return "lock region";
10150 	return "non-sleepable prog";
10151 }
10152 
10153 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
10154 		       bool convert_rcu, bool release_dynptr)
10155 {
10156 	int err = -EINVAL;
10157 
10158 	if (bpf_register_is_null(reg))
10159 		return 0;
10160 
10161 	if (release_dynptr)
10162 		err = unmark_stack_slots_dynptr(env, reg);
10163 	else if (convert_rcu)
10164 		err = ref_convert_alloc_rcu_protected(env, reg->id);
10165 	else if (reg_is_referenced(env, reg))
10166 		err = release_reference(env, reg->id);
10167 
10168 	return err;
10169 }
10170 
10171 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10172 			     int *insn_idx_p)
10173 {
10174 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10175 	bool returns_cpu_specific_alloc_ptr = false;
10176 	const struct bpf_func_proto *fn = NULL;
10177 	enum bpf_return_type ret_type;
10178 	enum bpf_type_flag ret_flag;
10179 	struct bpf_reg_state *regs;
10180 	struct bpf_call_arg_meta meta;
10181 	int insn_idx = *insn_idx_p;
10182 	bool changes_data;
10183 	int i, err, func_id;
10184 
10185 	/* find function prototype */
10186 	func_id = insn->imm;
10187 	err = bpf_get_helper_proto(env, insn->imm, &fn);
10188 	if (err == -ERANGE) {
10189 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10190 		return -EINVAL;
10191 	}
10192 
10193 	if (err) {
10194 		verbose(env, "program of this type cannot use helper %s#%d\n",
10195 			func_id_name(func_id), func_id);
10196 		return err;
10197 	}
10198 
10199 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10200 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10201 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10202 		return -EINVAL;
10203 	}
10204 
10205 	if (fn->allowed && !fn->allowed(env->prog)) {
10206 		verbose(env, "helper call is not allowed in probe\n");
10207 		return -EINVAL;
10208 	}
10209 
10210 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10211 	changes_data = bpf_helper_changes_pkt_data(func_id);
10212 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10213 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
10214 		return -EFAULT;
10215 	}
10216 
10217 	memset(&meta, 0, sizeof(meta));
10218 	meta.pkt_access = fn->pkt_access;
10219 
10220 	err = check_func_proto(fn, &meta);
10221 	if (err) {
10222 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
10223 		return err;
10224 	}
10225 
10226 	if (fn->might_sleep && !in_sleepable_context(env)) {
10227 		verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id,
10228 			non_sleepable_context_description(env));
10229 		return -EINVAL;
10230 	}
10231 
10232 	/* Track non-sleepable context for helpers. */
10233 	if (!in_sleepable_context(env))
10234 		env->insn_aux_data[insn_idx].non_sleepable = true;
10235 
10236 	meta.func_id = func_id;
10237 	/* check args */
10238 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10239 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10240 		if (err)
10241 			return err;
10242 	}
10243 
10244 	err = record_func_map(env, &meta, func_id, insn_idx);
10245 	if (err)
10246 		return err;
10247 
10248 	err = record_func_key(env, &meta, func_id, insn_idx);
10249 	if (err)
10250 		return err;
10251 
10252 	regs = cur_regs(env);
10253 
10254 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10255 	 * is inferred from register state.
10256 	 */
10257 	for (i = 0; i < meta.access_size; i++) {
10258 		err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B,
10259 				       BPF_WRITE, -1, false, false);
10260 		if (err)
10261 			return err;
10262 	}
10263 
10264 	if (meta.release_regno) {
10265 		struct bpf_reg_state *reg = &regs[meta.release_regno];
10266 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
10267 				   (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU);
10268 
10269 		err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id);
10270 		if (err)
10271 			return err;
10272 	}
10273 
10274 	switch (func_id) {
10275 	case BPF_FUNC_tail_call:
10276 		err = check_resource_leak(env, false, true, "tail_call");
10277 		if (err)
10278 			return err;
10279 		break;
10280 	case BPF_FUNC_get_local_storage:
10281 		/* check that flags argument in get_local_storage(map, flags) is 0,
10282 		 * this is required because get_local_storage() can't return an error.
10283 		 */
10284 		if (!bpf_register_is_null(&regs[BPF_REG_2])) {
10285 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10286 			return -EINVAL;
10287 		}
10288 		break;
10289 	case BPF_FUNC_for_each_map_elem:
10290 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10291 					 set_map_elem_callback_state);
10292 		break;
10293 	case BPF_FUNC_timer_set_callback:
10294 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10295 					 set_timer_callback_state);
10296 		break;
10297 	case BPF_FUNC_find_vma:
10298 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10299 					 set_find_vma_callback_state);
10300 		break;
10301 	case BPF_FUNC_snprintf:
10302 		err = check_bpf_snprintf_call(env, regs);
10303 		break;
10304 	case BPF_FUNC_loop:
10305 		update_loop_inline_state(env, meta.subprogno);
10306 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10307 		 * is finished, thus mark it precise.
10308 		 */
10309 		err = mark_chain_precision(env, BPF_REG_1);
10310 		if (err)
10311 			return err;
10312 		if (cur_func(env)->callback_depth < reg_umax(&regs[BPF_REG_1])) {
10313 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10314 						 set_loop_callback_state);
10315 		} else {
10316 			cur_func(env)->callback_depth = 0;
10317 			if (env->log.level & BPF_LOG_LEVEL2)
10318 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10319 					env->cur_state->curframe);
10320 		}
10321 		break;
10322 	case BPF_FUNC_dynptr_from_mem:
10323 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10324 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10325 				reg_type_str(env, regs[BPF_REG_1].type));
10326 			return -EACCES;
10327 		}
10328 		break;
10329 	case BPF_FUNC_set_retval:
10330 	{
10331 		struct bpf_retval_range range = {
10332 			.minval = -MAX_ERRNO,
10333 			.maxval = 0,
10334 			.return_32bit = true
10335 		};
10336 		struct bpf_reg_state *r1 = &regs[BPF_REG_1];
10337 
10338 		if (r1->type != SCALAR_VALUE) {
10339 			verbose(env, "R1 is not a scalar\n");
10340 			return -EINVAL;
10341 		}
10342 
10343 		/* CGROUP_GETSOCKOPT is allowed to return arbitrary value */
10344 		if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT &&
10345 		    env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)
10346 			break;
10347 
10348 		if (prog_type == BPF_PROG_TYPE_LSM &&
10349 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10350 			if (!env->prog->aux->attach_func_proto->type) {
10351 				/* Make sure programs that attach to void
10352 				 * hooks don't try to modify return value.
10353 				 */
10354 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10355 				return -EINVAL;
10356 			}
10357 			bpf_lsm_get_retval_range(env->prog, &range);
10358 		}
10359 
10360 		err = mark_chain_precision(env, BPF_REG_1);
10361 		if (err)
10362 			return err;
10363 
10364 		if (!retval_range_within(range, r1)) {
10365 			verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1");
10366 			return -EINVAL;
10367 		}
10368 
10369 		break;
10370 	}
10371 	case BPF_FUNC_dynptr_write:
10372 	{
10373 		enum bpf_dynptr_type dynptr_type = meta.dynptr.type;
10374 
10375 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10376 			return -EFAULT;
10377 
10378 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
10379 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
10380 			/* this will trigger clear_all_pkt_pointers(), which will
10381 			 * invalidate all dynptr slices associated with the skb
10382 			 */
10383 			changes_data = true;
10384 
10385 		break;
10386 	}
10387 	case BPF_FUNC_per_cpu_ptr:
10388 	case BPF_FUNC_this_cpu_ptr:
10389 	{
10390 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10391 		const struct btf_type *type;
10392 
10393 		if (reg->type & MEM_RCU) {
10394 			type = btf_type_by_id(reg->btf, reg->btf_id);
10395 			if (!type || !btf_type_is_struct(type)) {
10396 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10397 				return -EFAULT;
10398 			}
10399 			returns_cpu_specific_alloc_ptr = true;
10400 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10401 		}
10402 		break;
10403 	}
10404 	case BPF_FUNC_user_ringbuf_drain:
10405 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10406 					 set_user_ringbuf_callback_state);
10407 		break;
10408 	}
10409 
10410 	if (err)
10411 		return err;
10412 
10413 	/* reset caller saved regs */
10414 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10415 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
10416 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10417 	}
10418 	invalidate_outgoing_stack_args(env, cur_func(env));
10419 
10420 	/* helper call returns 64-bit value. */
10421 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10422 
10423 	/* update return register (already marked as written above) */
10424 	ret_type = fn->ret_type;
10425 	ret_flag = type_flag(ret_type);
10426 
10427 	switch (base_type(ret_type)) {
10428 	case RET_INTEGER:
10429 		/* sets type to SCALAR_VALUE */
10430 		mark_reg_unknown(env, regs, BPF_REG_0);
10431 		break;
10432 	case RET_VOID:
10433 		regs[BPF_REG_0].type = NOT_INIT;
10434 		break;
10435 	case RET_PTR_TO_MAP_VALUE:
10436 		/* There is no offset yet applied, variable or fixed */
10437 		mark_reg_known_zero(env, regs, BPF_REG_0);
10438 		/* remember map_ptr, so that check_map_access()
10439 		 * can check 'value_size' boundary of memory access
10440 		 * to map element returned from bpf_map_lookup_elem()
10441 		 */
10442 		if (meta.map.ptr == NULL) {
10443 			verifier_bug(env, "unexpected null map_ptr");
10444 			return -EFAULT;
10445 		}
10446 
10447 		if (func_id == BPF_FUNC_map_lookup_elem &&
10448 		    can_elide_value_nullness(meta.map.ptr) &&
10449 		    meta.const_map_key >= 0 &&
10450 		    meta.const_map_key < meta.map.ptr->max_entries)
10451 			ret_flag &= ~PTR_MAYBE_NULL;
10452 
10453 		regs[BPF_REG_0].map_ptr = meta.map.ptr;
10454 		regs[BPF_REG_0].map_uid = meta.map.uid;
10455 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10456 		if (!type_may_be_null(ret_flag) &&
10457 		    btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
10458 			regs[BPF_REG_0].id = ++env->id_gen;
10459 		}
10460 		break;
10461 	case RET_PTR_TO_SOCKET:
10462 		mark_reg_known_zero(env, regs, BPF_REG_0);
10463 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10464 		break;
10465 	case RET_PTR_TO_SOCK_COMMON:
10466 		mark_reg_known_zero(env, regs, BPF_REG_0);
10467 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10468 		break;
10469 	case RET_PTR_TO_TCP_SOCK:
10470 		mark_reg_known_zero(env, regs, BPF_REG_0);
10471 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10472 		break;
10473 	case RET_PTR_TO_MEM:
10474 		mark_reg_known_zero(env, regs, BPF_REG_0);
10475 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10476 		regs[BPF_REG_0].mem_size = meta.mem_size;
10477 		break;
10478 	case RET_PTR_TO_MEM_OR_BTF_ID:
10479 	{
10480 		const struct btf_type *t;
10481 
10482 		mark_reg_known_zero(env, regs, BPF_REG_0);
10483 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10484 		if (!btf_type_is_struct(t)) {
10485 			u32 tsize;
10486 			const struct btf_type *ret;
10487 			const char *tname;
10488 
10489 			/* resolve the type size of ksym. */
10490 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10491 			if (IS_ERR(ret)) {
10492 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10493 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10494 					tname, PTR_ERR(ret));
10495 				return -EINVAL;
10496 			}
10497 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10498 			regs[BPF_REG_0].mem_size = tsize;
10499 		} else {
10500 			if (returns_cpu_specific_alloc_ptr) {
10501 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10502 			} else {
10503 				/* MEM_RDONLY may be carried from ret_flag, but it
10504 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10505 				 * it will confuse the check of PTR_TO_BTF_ID in
10506 				 * check_mem_access().
10507 				 */
10508 				ret_flag &= ~MEM_RDONLY;
10509 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10510 			}
10511 
10512 			regs[BPF_REG_0].btf = meta.ret_btf;
10513 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10514 		}
10515 		break;
10516 	}
10517 	case RET_PTR_TO_BTF_ID:
10518 	{
10519 		struct btf *ret_btf;
10520 		int ret_btf_id;
10521 
10522 		mark_reg_known_zero(env, regs, BPF_REG_0);
10523 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10524 		if (func_id == BPF_FUNC_kptr_xchg) {
10525 			ret_btf = meta.kptr_field->kptr.btf;
10526 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10527 			if (!btf_is_kernel(ret_btf)) {
10528 				regs[BPF_REG_0].type |= MEM_ALLOC;
10529 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10530 					regs[BPF_REG_0].type |= MEM_PERCPU;
10531 			}
10532 		} else {
10533 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10534 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
10535 					     func_id_name(func_id));
10536 				return -EFAULT;
10537 			}
10538 			ret_btf = btf_vmlinux;
10539 			ret_btf_id = *fn->ret_btf_id;
10540 		}
10541 		if (ret_btf_id == 0) {
10542 			verbose(env, "invalid return type %u of func %s#%d\n",
10543 				base_type(ret_type), func_id_name(func_id),
10544 				func_id);
10545 			return -EINVAL;
10546 		}
10547 		regs[BPF_REG_0].btf = ret_btf;
10548 		regs[BPF_REG_0].btf_id = ret_btf_id;
10549 		break;
10550 	}
10551 	default:
10552 		verbose(env, "unknown return type %u of func %s#%d\n",
10553 			base_type(ret_type), func_id_name(func_id), func_id);
10554 		return -EINVAL;
10555 	}
10556 
10557 	if (type_may_be_null(regs[BPF_REG_0].type))
10558 		regs[BPF_REG_0].id = ++env->id_gen;
10559 
10560 	if (is_ptr_cast_function(func_id) &&
10561 	    find_reference_state(env->cur_state, meta.ref_obj.id)) {
10562 		struct bpf_verifier_state *branch;
10563 		struct bpf_reg_state *r0;
10564 
10565 		err = validate_ref_obj(env, &meta.ref_obj);
10566 		if (err)
10567 			return err;
10568 
10569 		/*
10570 		 * In order for a release of any of the original or cast pointers
10571 		 * to invalidate all other pointers, reuse the same reference id for
10572 		 * the cast result.
10573 		 * This reference id can't be used for nullness propagation,
10574 		 * as cast might return NULL for a non-NULL input.
10575 		 * Hence, explore the NULL case as a separate branch.
10576 		 */
10577 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
10578 		if (IS_ERR(branch))
10579 			return PTR_ERR(branch);
10580 
10581 		r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0];
10582 		__mark_reg_known_zero(r0);
10583 		r0->type = SCALAR_VALUE;
10584 
10585 		regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL;
10586 		regs[BPF_REG_0].id = meta.ref_obj.id;
10587 	} else if (is_acquire_function(func_id, meta.map.ptr)) {
10588 		int id = acquire_reference(env, insn_idx, 0);
10589 
10590 		if (id < 0)
10591 			return id;
10592 
10593 		regs[BPF_REG_0].id = id;
10594 	}
10595 
10596 	if (func_id == BPF_FUNC_dynptr_data)
10597 		regs[BPF_REG_0].parent_id = meta.dynptr.id;
10598 
10599 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10600 	if (err)
10601 		return err;
10602 
10603 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
10604 	if (err)
10605 		return err;
10606 
10607 	if ((func_id == BPF_FUNC_get_stack ||
10608 	     func_id == BPF_FUNC_get_task_stack) &&
10609 	    !env->prog->has_callchain_buf) {
10610 		const char *err_str;
10611 
10612 #ifdef CONFIG_PERF_EVENTS
10613 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10614 		err_str = "cannot get callchain buffer for func %s#%d\n";
10615 #else
10616 		err = -ENOTSUPP;
10617 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10618 #endif
10619 		if (err) {
10620 			verbose(env, err_str, func_id_name(func_id), func_id);
10621 			return err;
10622 		}
10623 
10624 		env->prog->has_callchain_buf = true;
10625 	}
10626 
10627 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10628 		env->prog->call_get_stack = true;
10629 
10630 	if (func_id == BPF_FUNC_get_func_ip) {
10631 		if (check_get_func_ip(env))
10632 			return -ENOTSUPP;
10633 		env->prog->call_get_func_ip = true;
10634 	}
10635 
10636 	if (func_id == BPF_FUNC_tail_call) {
10637 		if (env->cur_state->curframe) {
10638 			struct bpf_verifier_state *branch;
10639 
10640 			mark_reg_scratched(env, BPF_REG_0);
10641 			branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
10642 			if (IS_ERR(branch))
10643 				return PTR_ERR(branch);
10644 			clear_all_pkt_pointers(env);
10645 			mark_reg_unknown(env, regs, BPF_REG_0);
10646 			err = prepare_func_exit(env, &env->insn_idx);
10647 			if (err)
10648 				return err;
10649 			env->insn_idx--;
10650 		} else {
10651 			changes_data = false;
10652 		}
10653 	}
10654 
10655 	if (changes_data)
10656 		clear_all_pkt_pointers(env);
10657 	return 0;
10658 }
10659 
10660 /* mark_btf_func_reg_size() is used when the reg size is determined by
10661  * the BTF func_proto's return value size and argument.
10662  */
10663 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
10664 				     u32 regno, size_t reg_size)
10665 {
10666 	struct bpf_reg_state *reg = &regs[regno];
10667 
10668 	if (regno == BPF_REG_0) {
10669 		/* Function return value */
10670 		reg->subreg_def = reg_size == sizeof(u64) ?
10671 			DEF_NOT_SUBREG : env->insn_idx + 1;
10672 	} else if (reg_size == sizeof(u64)) {
10673 		/* Function argument */
10674 		mark_insn_zext(env, reg);
10675 	}
10676 }
10677 
10678 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10679 				   size_t reg_size)
10680 {
10681 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
10682 }
10683 
10684 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10685 {
10686 	return meta->kfunc_flags & KF_ACQUIRE;
10687 }
10688 
10689 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10690 {
10691 	return meta->kfunc_flags & KF_RELEASE;
10692 }
10693 
10694 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10695 {
10696 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10697 }
10698 
10699 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10700 {
10701 	return meta->kfunc_flags & KF_RCU;
10702 }
10703 
10704 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10705 {
10706 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10707 }
10708 
10709 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10710 				  const struct btf_param *arg,
10711 				  const struct bpf_reg_state *reg)
10712 {
10713 	const struct btf_type *t;
10714 
10715 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10716 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10717 		return false;
10718 
10719 	return btf_param_match_suffix(btf, arg, "__sz");
10720 }
10721 
10722 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10723 					const struct btf_param *arg,
10724 					const struct bpf_reg_state *reg)
10725 {
10726 	const struct btf_type *t;
10727 
10728 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10729 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10730 		return false;
10731 
10732 	return btf_param_match_suffix(btf, arg, "__szk");
10733 }
10734 
10735 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10736 {
10737 	return btf_param_match_suffix(btf, arg, "__k");
10738 }
10739 
10740 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10741 {
10742 	return btf_param_match_suffix(btf, arg, "__ign");
10743 }
10744 
10745 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10746 {
10747 	return btf_param_match_suffix(btf, arg, "__map");
10748 }
10749 
10750 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10751 {
10752 	return btf_param_match_suffix(btf, arg, "__alloc");
10753 }
10754 
10755 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10756 {
10757 	return btf_param_match_suffix(btf, arg, "__uninit");
10758 }
10759 
10760 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10761 {
10762 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10763 }
10764 
10765 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10766 {
10767 	return btf_param_match_suffix(btf, arg, "__nullable");
10768 }
10769 
10770 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg)
10771 {
10772 	return btf_param_match_suffix(btf, arg, "__nonown_allowed");
10773 }
10774 
10775 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10776 {
10777 	return btf_param_match_suffix(btf, arg, "__str");
10778 }
10779 
10780 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
10781 {
10782 	return btf_param_match_suffix(btf, arg, "__irq_flag");
10783 }
10784 
10785 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10786 					  const struct btf_param *arg,
10787 					  const char *name)
10788 {
10789 	int len, target_len = strlen(name);
10790 	const char *param_name;
10791 
10792 	param_name = btf_name_by_offset(btf, arg->name_off);
10793 	if (str_is_empty(param_name))
10794 		return false;
10795 	len = strlen(param_name);
10796 	if (len != target_len)
10797 		return false;
10798 	if (strcmp(param_name, name))
10799 		return false;
10800 
10801 	return true;
10802 }
10803 
10804 enum {
10805 	KF_ARG_DYNPTR_ID,
10806 	KF_ARG_LIST_HEAD_ID,
10807 	KF_ARG_LIST_NODE_ID,
10808 	KF_ARG_RB_ROOT_ID,
10809 	KF_ARG_RB_NODE_ID,
10810 	KF_ARG_WORKQUEUE_ID,
10811 	KF_ARG_RES_SPIN_LOCK_ID,
10812 	KF_ARG_TASK_WORK_ID,
10813 	KF_ARG_PROG_AUX_ID,
10814 	KF_ARG_TIMER_ID
10815 };
10816 
10817 BTF_ID_LIST(kf_arg_btf_ids)
10818 BTF_ID(struct, bpf_dynptr)
10819 BTF_ID(struct, bpf_list_head)
10820 BTF_ID(struct, bpf_list_node)
10821 BTF_ID(struct, bpf_rb_root)
10822 BTF_ID(struct, bpf_rb_node)
10823 BTF_ID(struct, bpf_wq)
10824 BTF_ID(struct, bpf_res_spin_lock)
10825 BTF_ID(struct, bpf_task_work)
10826 BTF_ID(struct, bpf_prog_aux)
10827 BTF_ID(struct, bpf_timer)
10828 
10829 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10830 				    const struct btf_param *arg, int type)
10831 {
10832 	const struct btf_type *t;
10833 	u32 res_id;
10834 
10835 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10836 	if (!t)
10837 		return false;
10838 	if (!btf_type_is_ptr(t))
10839 		return false;
10840 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10841 	if (!t)
10842 		return false;
10843 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10844 }
10845 
10846 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10847 {
10848 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10849 }
10850 
10851 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10852 {
10853 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10854 }
10855 
10856 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10857 {
10858 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10859 }
10860 
10861 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10862 {
10863 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10864 }
10865 
10866 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10867 {
10868 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10869 }
10870 
10871 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg)
10872 {
10873 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID);
10874 }
10875 
10876 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
10877 {
10878 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
10879 }
10880 
10881 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
10882 {
10883 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
10884 }
10885 
10886 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
10887 {
10888 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
10889 }
10890 
10891 static bool is_rbtree_node_type(const struct btf_type *t)
10892 {
10893 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
10894 }
10895 
10896 static bool is_list_node_type(const struct btf_type *t)
10897 {
10898 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
10899 }
10900 
10901 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10902 				  const struct btf_param *arg)
10903 {
10904 	const struct btf_type *t;
10905 
10906 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10907 	if (!t)
10908 		return false;
10909 
10910 	return true;
10911 }
10912 
10913 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg)
10914 {
10915 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID);
10916 }
10917 
10918 /*
10919  * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF:
10920  *   - the _impl prototype with full arg list (meta->func_proto)
10921  *   - the BPF API prototype w/o implicit args (func->type in BTF)
10922  * To determine whether an argument is implicit, we compare its position
10923  * against the number of arguments in the prototype w/o implicit args.
10924  */
10925 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx)
10926 {
10927 	const struct btf_type *func, *func_proto;
10928 	u32 argn;
10929 
10930 	if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS))
10931 		return false;
10932 
10933 	func = btf_type_by_id(meta->btf, meta->func_id);
10934 	func_proto = btf_type_by_id(meta->btf, func->type);
10935 	argn = btf_type_vlen(func_proto);
10936 
10937 	return argn <= arg_idx;
10938 }
10939 
10940 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10941 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10942 					const struct btf *btf,
10943 					const struct btf_type *t, int rec)
10944 {
10945 	const struct btf_type *member_type;
10946 	const struct btf_member *member;
10947 	u32 i;
10948 
10949 	if (!btf_type_is_struct(t))
10950 		return false;
10951 
10952 	for_each_member(i, t, member) {
10953 		const struct btf_array *array;
10954 
10955 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10956 		if (btf_type_is_struct(member_type)) {
10957 			if (rec >= 3) {
10958 				verbose(env, "max struct nesting depth exceeded\n");
10959 				return false;
10960 			}
10961 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10962 				return false;
10963 			continue;
10964 		}
10965 		if (btf_type_is_array(member_type)) {
10966 			array = btf_array(member_type);
10967 			if (!array->nelems)
10968 				return false;
10969 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10970 			if (!btf_type_is_scalar(member_type))
10971 				return false;
10972 			continue;
10973 		}
10974 		if (!btf_type_is_scalar(member_type))
10975 			return false;
10976 	}
10977 	return true;
10978 }
10979 
10980 enum kfunc_ptr_arg_type {
10981 	KF_ARG_PTR_TO_CTX,
10982 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10983 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10984 	KF_ARG_PTR_TO_DYNPTR,
10985 	KF_ARG_PTR_TO_ITER,
10986 	KF_ARG_PTR_TO_LIST_HEAD,
10987 	KF_ARG_PTR_TO_LIST_NODE,
10988 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10989 	KF_ARG_PTR_TO_MEM,
10990 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10991 	KF_ARG_PTR_TO_CALLBACK,
10992 	KF_ARG_PTR_TO_RB_ROOT,
10993 	KF_ARG_PTR_TO_RB_NODE,
10994 	KF_ARG_PTR_TO_NULL,
10995 	KF_ARG_PTR_TO_CONST_STR,
10996 	KF_ARG_PTR_TO_MAP,
10997 	KF_ARG_PTR_TO_TIMER,
10998 	KF_ARG_PTR_TO_WORKQUEUE,
10999 	KF_ARG_PTR_TO_IRQ_FLAG,
11000 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
11001 	KF_ARG_PTR_TO_TASK_WORK,
11002 };
11003 
11004 enum special_kfunc_type {
11005 	KF_bpf_obj_new_impl,
11006 	KF_bpf_obj_new,
11007 	KF_bpf_obj_drop_impl,
11008 	KF_bpf_obj_drop,
11009 	KF_bpf_refcount_acquire_impl,
11010 	KF_bpf_refcount_acquire,
11011 	KF_bpf_list_push_front_impl,
11012 	KF_bpf_list_push_front,
11013 	KF_bpf_list_push_back_impl,
11014 	KF_bpf_list_push_back,
11015 	KF_bpf_list_add,
11016 	KF_bpf_list_pop_front,
11017 	KF_bpf_list_pop_back,
11018 	KF_bpf_list_del,
11019 	KF_bpf_list_front,
11020 	KF_bpf_list_back,
11021 	KF_bpf_list_is_first,
11022 	KF_bpf_list_is_last,
11023 	KF_bpf_list_empty,
11024 	KF_bpf_cast_to_kern_ctx,
11025 	KF_bpf_rdonly_cast,
11026 	KF_bpf_rcu_read_lock,
11027 	KF_bpf_rcu_read_unlock,
11028 	KF_bpf_rbtree_remove,
11029 	KF_bpf_rbtree_add_impl,
11030 	KF_bpf_rbtree_add,
11031 	KF_bpf_rbtree_first,
11032 	KF_bpf_rbtree_root,
11033 	KF_bpf_rbtree_left,
11034 	KF_bpf_rbtree_right,
11035 	KF_bpf_dynptr_from_skb,
11036 	KF_bpf_dynptr_from_xdp,
11037 	KF_bpf_dynptr_from_skb_meta,
11038 	KF_bpf_xdp_pull_data,
11039 	KF_bpf_dynptr_slice,
11040 	KF_bpf_dynptr_slice_rdwr,
11041 	KF_bpf_dynptr_clone,
11042 	KF_bpf_percpu_obj_new_impl,
11043 	KF_bpf_percpu_obj_new,
11044 	KF_bpf_percpu_obj_drop_impl,
11045 	KF_bpf_percpu_obj_drop,
11046 	KF_bpf_throw,
11047 	KF_bpf_wq_set_callback,
11048 	KF_bpf_preempt_disable,
11049 	KF_bpf_preempt_enable,
11050 	KF_bpf_iter_css_task_new,
11051 	KF_bpf_session_cookie,
11052 	KF_bpf_get_kmem_cache,
11053 	KF_bpf_local_irq_save,
11054 	KF_bpf_local_irq_restore,
11055 	KF_bpf_iter_num_new,
11056 	KF_bpf_iter_num_next,
11057 	KF_bpf_iter_num_destroy,
11058 	KF_bpf_set_dentry_xattr,
11059 	KF_bpf_remove_dentry_xattr,
11060 	KF_bpf_res_spin_lock,
11061 	KF_bpf_res_spin_unlock,
11062 	KF_bpf_res_spin_lock_irqsave,
11063 	KF_bpf_res_spin_unlock_irqrestore,
11064 	KF_bpf_dynptr_from_file,
11065 	KF_bpf_dynptr_file_discard,
11066 	KF___bpf_trap,
11067 	KF_bpf_task_work_schedule_signal,
11068 	KF_bpf_task_work_schedule_resume,
11069 	KF_bpf_arena_alloc_pages,
11070 	KF_bpf_arena_free_pages,
11071 	KF_bpf_arena_reserve_pages,
11072 	KF_bpf_session_is_return,
11073 	KF_bpf_stream_vprintk,
11074 	KF_bpf_stream_print_stack,
11075 };
11076 
11077 BTF_ID_LIST(special_kfunc_list)
11078 BTF_ID(func, bpf_obj_new_impl)
11079 BTF_ID(func, bpf_obj_new)
11080 BTF_ID(func, bpf_obj_drop_impl)
11081 BTF_ID(func, bpf_obj_drop)
11082 BTF_ID(func, bpf_refcount_acquire_impl)
11083 BTF_ID(func, bpf_refcount_acquire)
11084 BTF_ID(func, bpf_list_push_front_impl)
11085 BTF_ID(func, bpf_list_push_front)
11086 BTF_ID(func, bpf_list_push_back_impl)
11087 BTF_ID(func, bpf_list_push_back)
11088 BTF_ID(func, bpf_list_add)
11089 BTF_ID(func, bpf_list_pop_front)
11090 BTF_ID(func, bpf_list_pop_back)
11091 BTF_ID(func, bpf_list_del)
11092 BTF_ID(func, bpf_list_front)
11093 BTF_ID(func, bpf_list_back)
11094 BTF_ID(func, bpf_list_is_first)
11095 BTF_ID(func, bpf_list_is_last)
11096 BTF_ID(func, bpf_list_empty)
11097 BTF_ID(func, bpf_cast_to_kern_ctx)
11098 BTF_ID(func, bpf_rdonly_cast)
11099 BTF_ID(func, bpf_rcu_read_lock)
11100 BTF_ID(func, bpf_rcu_read_unlock)
11101 BTF_ID(func, bpf_rbtree_remove)
11102 BTF_ID(func, bpf_rbtree_add_impl)
11103 BTF_ID(func, bpf_rbtree_add)
11104 BTF_ID(func, bpf_rbtree_first)
11105 BTF_ID(func, bpf_rbtree_root)
11106 BTF_ID(func, bpf_rbtree_left)
11107 BTF_ID(func, bpf_rbtree_right)
11108 #ifdef CONFIG_NET
11109 BTF_ID(func, bpf_dynptr_from_skb)
11110 BTF_ID(func, bpf_dynptr_from_xdp)
11111 BTF_ID(func, bpf_dynptr_from_skb_meta)
11112 BTF_ID(func, bpf_xdp_pull_data)
11113 #else
11114 BTF_ID_UNUSED
11115 BTF_ID_UNUSED
11116 BTF_ID_UNUSED
11117 BTF_ID_UNUSED
11118 #endif
11119 BTF_ID(func, bpf_dynptr_slice)
11120 BTF_ID(func, bpf_dynptr_slice_rdwr)
11121 BTF_ID(func, bpf_dynptr_clone)
11122 BTF_ID(func, bpf_percpu_obj_new_impl)
11123 BTF_ID(func, bpf_percpu_obj_new)
11124 BTF_ID(func, bpf_percpu_obj_drop_impl)
11125 BTF_ID(func, bpf_percpu_obj_drop)
11126 BTF_ID(func, bpf_throw)
11127 BTF_ID(func, bpf_wq_set_callback)
11128 BTF_ID(func, bpf_preempt_disable)
11129 BTF_ID(func, bpf_preempt_enable)
11130 #ifdef CONFIG_CGROUPS
11131 BTF_ID(func, bpf_iter_css_task_new)
11132 #else
11133 BTF_ID_UNUSED
11134 #endif
11135 #ifdef CONFIG_BPF_EVENTS
11136 BTF_ID(func, bpf_session_cookie)
11137 #else
11138 BTF_ID_UNUSED
11139 #endif
11140 BTF_ID(func, bpf_get_kmem_cache)
11141 BTF_ID(func, bpf_local_irq_save)
11142 BTF_ID(func, bpf_local_irq_restore)
11143 BTF_ID(func, bpf_iter_num_new)
11144 BTF_ID(func, bpf_iter_num_next)
11145 BTF_ID(func, bpf_iter_num_destroy)
11146 #ifdef CONFIG_BPF_LSM
11147 BTF_ID(func, bpf_set_dentry_xattr)
11148 BTF_ID(func, bpf_remove_dentry_xattr)
11149 #else
11150 BTF_ID_UNUSED
11151 BTF_ID_UNUSED
11152 #endif
11153 BTF_ID(func, bpf_res_spin_lock)
11154 BTF_ID(func, bpf_res_spin_unlock)
11155 BTF_ID(func, bpf_res_spin_lock_irqsave)
11156 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
11157 BTF_ID(func, bpf_dynptr_from_file)
11158 BTF_ID(func, bpf_dynptr_file_discard)
11159 BTF_ID(func, __bpf_trap)
11160 BTF_ID(func, bpf_task_work_schedule_signal)
11161 BTF_ID(func, bpf_task_work_schedule_resume)
11162 BTF_ID(func, bpf_arena_alloc_pages)
11163 BTF_ID(func, bpf_arena_free_pages)
11164 BTF_ID(func, bpf_arena_reserve_pages)
11165 #ifdef CONFIG_BPF_EVENTS
11166 BTF_ID(func, bpf_session_is_return)
11167 #else
11168 BTF_ID_UNUSED
11169 #endif
11170 BTF_ID(func, bpf_stream_vprintk)
11171 BTF_ID(func, bpf_stream_print_stack)
11172 
11173 static bool is_bpf_obj_new_kfunc(u32 func_id)
11174 {
11175 	return func_id == special_kfunc_list[KF_bpf_obj_new] ||
11176 	       func_id == special_kfunc_list[KF_bpf_obj_new_impl];
11177 }
11178 
11179 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id)
11180 {
11181 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] ||
11182 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl];
11183 }
11184 
11185 static bool is_bpf_obj_drop_kfunc(u32 func_id)
11186 {
11187 	return func_id == special_kfunc_list[KF_bpf_obj_drop] ||
11188 	       func_id == special_kfunc_list[KF_bpf_obj_drop_impl];
11189 }
11190 
11191 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id)
11192 {
11193 	return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] ||
11194 	       func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl];
11195 }
11196 
11197 static bool is_bpf_refcount_acquire_kfunc(u32 func_id)
11198 {
11199 	return func_id == special_kfunc_list[KF_bpf_refcount_acquire] ||
11200 	       func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11201 }
11202 
11203 static bool is_bpf_list_push_kfunc(u32 func_id)
11204 {
11205 	return func_id == special_kfunc_list[KF_bpf_list_push_front] ||
11206 	       func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11207 	       func_id == special_kfunc_list[KF_bpf_list_push_back] ||
11208 	       func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11209 	       func_id == special_kfunc_list[KF_bpf_list_add];
11210 }
11211 
11212 static bool is_bpf_rbtree_add_kfunc(u32 func_id)
11213 {
11214 	return func_id == special_kfunc_list[KF_bpf_rbtree_add] ||
11215 	       func_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11216 }
11217 
11218 static bool is_task_work_add_kfunc(u32 func_id)
11219 {
11220 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] ||
11221 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume];
11222 }
11223 
11224 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11225 {
11226 	if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref)
11227 		return false;
11228 
11229 	return meta->kfunc_flags & KF_RET_NULL;
11230 }
11231 
11232 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11233 {
11234 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11235 }
11236 
11237 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11238 {
11239 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11240 }
11241 
11242 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11243 {
11244 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11245 }
11246 
11247 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11248 {
11249 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11250 }
11251 
11252 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
11253 {
11254 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
11255 }
11256 
11257 static enum kfunc_ptr_arg_type
11258 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller,
11259 		       struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta,
11260 		       const struct btf_type *t, const struct btf_type *ref_t,
11261 		       const char *ref_tname, const struct btf_param *args,
11262 		       int arg, int nargs, argno_t argno, struct bpf_reg_state *reg)
11263 {
11264 	bool arg_mem_size = false;
11265 
11266 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
11267 	    meta->func_id == special_kfunc_list[KF_bpf_session_is_return] ||
11268 	    meta->func_id == special_kfunc_list[KF_bpf_session_cookie])
11269 		return KF_ARG_PTR_TO_CTX;
11270 
11271 	if (arg + 1 < nargs &&
11272 	    (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) ||
11273 	     is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1))))
11274 		arg_mem_size = true;
11275 
11276 	/* In this function, we verify the kfunc's BTF as per the argument type,
11277 	 * leaving the rest of the verification with respect to the register
11278 	 * type to our caller. When a set of conditions hold in the BTF type of
11279 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11280 	 */
11281 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg))
11282 		return KF_ARG_PTR_TO_CTX;
11283 
11284 	if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) &&
11285 	    !arg_mem_size)
11286 		return KF_ARG_PTR_TO_NULL;
11287 
11288 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg]))
11289 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11290 
11291 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg]))
11292 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11293 
11294 	if (is_kfunc_arg_dynptr(meta->btf, &args[arg]))
11295 		return KF_ARG_PTR_TO_DYNPTR;
11296 
11297 	if (is_kfunc_arg_iter(meta, arg, &args[arg]))
11298 		return KF_ARG_PTR_TO_ITER;
11299 
11300 	if (is_kfunc_arg_list_head(meta->btf, &args[arg]))
11301 		return KF_ARG_PTR_TO_LIST_HEAD;
11302 
11303 	if (is_kfunc_arg_list_node(meta->btf, &args[arg]))
11304 		return KF_ARG_PTR_TO_LIST_NODE;
11305 
11306 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg]))
11307 		return KF_ARG_PTR_TO_RB_ROOT;
11308 
11309 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg]))
11310 		return KF_ARG_PTR_TO_RB_NODE;
11311 
11312 	if (is_kfunc_arg_const_str(meta->btf, &args[arg]))
11313 		return KF_ARG_PTR_TO_CONST_STR;
11314 
11315 	if (is_kfunc_arg_map(meta->btf, &args[arg]))
11316 		return KF_ARG_PTR_TO_MAP;
11317 
11318 	if (is_kfunc_arg_wq(meta->btf, &args[arg]))
11319 		return KF_ARG_PTR_TO_WORKQUEUE;
11320 
11321 	if (is_kfunc_arg_timer(meta->btf, &args[arg]))
11322 		return KF_ARG_PTR_TO_TIMER;
11323 
11324 	if (is_kfunc_arg_task_work(meta->btf, &args[arg]))
11325 		return KF_ARG_PTR_TO_TASK_WORK;
11326 
11327 	if (is_kfunc_arg_irq_flag(meta->btf, &args[arg]))
11328 		return KF_ARG_PTR_TO_IRQ_FLAG;
11329 
11330 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg]))
11331 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
11332 
11333 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11334 		if (!btf_type_is_struct(ref_t)) {
11335 			verbose(env, "kernel function %s %s pointer type %s %s is not supported\n",
11336 				meta->func_name, reg_arg_name(env, argno),
11337 				btf_type_str(ref_t), ref_tname);
11338 			return -EINVAL;
11339 		}
11340 		return KF_ARG_PTR_TO_BTF_ID;
11341 	}
11342 
11343 	if (is_kfunc_arg_callback(env, meta->btf, &args[arg]))
11344 		return KF_ARG_PTR_TO_CALLBACK;
11345 
11346 	/* This is the catch all argument type of register types supported by
11347 	 * check_helper_mem_access. However, we only allow when argument type is
11348 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11349 	 * arg_mem_size is true, the pointer can be void *.
11350 	 */
11351 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11352 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11353 		verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n",
11354 			reg_arg_name(env, argno),
11355 			btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11356 		return -EINVAL;
11357 	}
11358 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11359 }
11360 
11361 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11362 					struct bpf_reg_state *reg,
11363 					const struct btf_type *ref_t,
11364 					const char *ref_tname, u32 ref_id,
11365 					struct bpf_kfunc_call_arg_meta *meta,
11366 					int arg, argno_t argno)
11367 {
11368 	const struct btf_type *reg_ref_t;
11369 	bool strict_type_match = false;
11370 	const struct btf *reg_btf;
11371 	const char *reg_ref_tname;
11372 	bool taking_projection;
11373 	bool struct_same;
11374 	u32 reg_ref_id;
11375 
11376 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11377 		reg_btf = reg->btf;
11378 		reg_ref_id = reg->btf_id;
11379 	} else {
11380 		reg_btf = btf_vmlinux;
11381 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11382 	}
11383 
11384 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11385 	 * or releasing a reference, or are no-cast aliases. We do _not_
11386 	 * enforce strict matching for kfuncs by default,
11387 	 * as we want to enable BPF programs to pass types that are bitwise
11388 	 * equivalent without forcing them to explicitly cast with something
11389 	 * like bpf_cast_to_kern_ctx().
11390 	 *
11391 	 * For example, say we had a type like the following:
11392 	 *
11393 	 * struct bpf_cpumask {
11394 	 *	cpumask_t cpumask;
11395 	 *	refcount_t usage;
11396 	 * };
11397 	 *
11398 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11399 	 * to a struct cpumask, so it would be safe to pass a struct
11400 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11401 	 *
11402 	 * The philosophy here is similar to how we allow scalars of different
11403 	 * types to be passed to kfuncs as long as the size is the same. The
11404 	 * only difference here is that we're simply allowing
11405 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11406 	 * resolve types.
11407 	 */
11408 	if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) ||
11409 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11410 		strict_type_match = true;
11411 
11412 	WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off));
11413 
11414 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11415 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11416 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value,
11417 					   meta->btf, ref_id, strict_type_match);
11418 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11419 	 * actually use it -- it must cast to the underlying type. So we allow
11420 	 * caller to pass in the underlying type.
11421 	 */
11422 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11423 	if (!taking_projection && !struct_same) {
11424 		verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n",
11425 			meta->func_name, reg_arg_name(env, argno),
11426 			btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno),
11427 			btf_type_str(reg_ref_t), reg_ref_tname);
11428 		return -EINVAL;
11429 	}
11430 	return 0;
11431 }
11432 
11433 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno,
11434 			     struct bpf_kfunc_call_arg_meta *meta)
11435 {
11436 	int err, spi, kfunc_class = IRQ_NATIVE_KFUNC;
11437 	bool irq_save;
11438 
11439 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
11440 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
11441 		irq_save = true;
11442 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
11443 			kfunc_class = IRQ_LOCK_KFUNC;
11444 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
11445 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
11446 		irq_save = false;
11447 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
11448 			kfunc_class = IRQ_LOCK_KFUNC;
11449 	} else {
11450 		verifier_bug(env, "unknown irq flags kfunc");
11451 		return -EFAULT;
11452 	}
11453 
11454 	if (irq_save) {
11455 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
11456 			verbose(env, "expected uninitialized irq flag as %s\n",
11457 				reg_arg_name(env, argno));
11458 			return -EINVAL;
11459 		}
11460 
11461 		err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW,
11462 				       BPF_WRITE, -1, false, false);
11463 		if (err)
11464 			return err;
11465 
11466 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
11467 		if (err)
11468 			return err;
11469 	} else {
11470 		err = is_irq_flag_reg_valid_init(env, reg);
11471 		if (err) {
11472 			verbose(env, "expected an initialized irq flag as %s\n",
11473 				reg_arg_name(env, argno));
11474 			return err;
11475 		}
11476 
11477 		spi = irq_flag_get_spi(env, reg);
11478 		if (spi < 0)
11479 			return spi;
11480 
11481 		mark_stack_slots_scratched(env, spi, 1);
11482 
11483 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
11484 		if (err)
11485 			return err;
11486 	}
11487 	return 0;
11488 }
11489 
11490 
11491 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11492 {
11493 	struct btf_record *rec = reg_btf_record(reg);
11494 
11495 	if (!env->cur_state->active_locks) {
11496 		verifier_bug(env, "%s w/o active lock", __func__);
11497 		return -EFAULT;
11498 	}
11499 
11500 	if (type_flag(reg->type) & NON_OWN_REF) {
11501 		verifier_bug(env, "NON_OWN_REF already set");
11502 		return -EFAULT;
11503 	}
11504 
11505 	reg->type |= NON_OWN_REF;
11506 	if (rec->refcount_off >= 0)
11507 		reg->type |= MEM_RCU;
11508 
11509 	return 0;
11510 }
11511 
11512 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
11513 {
11514 	struct bpf_func_state *unused;
11515 	struct bpf_reg_state *reg;
11516 
11517 	WARN_ON_ONCE(release_reference_nomark(env->cur_state, id));
11518 
11519 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11520 		if (reg->id == id) {
11521 			reg->id = 0;
11522 			ref_set_non_owning(env, reg);
11523 		}
11524 	}));
11525 
11526 	return;
11527 }
11528 
11529 /* Implementation details:
11530  *
11531  * Each register points to some region of memory, which we define as an
11532  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11533  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11534  * allocation. The lock and the data it protects are colocated in the same
11535  * memory region.
11536  *
11537  * Hence, everytime a register holds a pointer value pointing to such
11538  * allocation, the verifier preserves a unique reg->id for it.
11539  *
11540  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11541  * bpf_spin_lock is called.
11542  *
11543  * To enable this, lock state in the verifier captures two values:
11544  *	active_lock.ptr = Register's type specific pointer
11545  *	active_lock.id  = A unique ID for each register pointer value
11546  *
11547  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11548  * supported register types.
11549  *
11550  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11551  * allocated objects is the reg->btf pointer.
11552  *
11553  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11554  * can establish the provenance of the map value statically for each distinct
11555  * lookup into such maps. They always contain a single map value hence unique
11556  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11557  *
11558  * So, in case of global variables, they use array maps with max_entries = 1,
11559  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11560  * into the same map value as max_entries is 1, as described above).
11561  *
11562  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11563  * outer map pointer (in verifier context), but each lookup into an inner map
11564  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11565  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11566  * will get different reg->id assigned to each lookup, hence different
11567  * active_lock.id.
11568  *
11569  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11570  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11571  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11572  */
11573 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11574 {
11575 	struct bpf_reference_state *s;
11576 	void *ptr;
11577 	u32 id;
11578 
11579 	switch ((int)reg->type) {
11580 	case PTR_TO_MAP_VALUE:
11581 		ptr = reg->map_ptr;
11582 		break;
11583 	case PTR_TO_BTF_ID | MEM_ALLOC:
11584 		ptr = reg->btf;
11585 		break;
11586 	default:
11587 		verifier_bug(env, "unknown reg type for lock check");
11588 		return -EFAULT;
11589 	}
11590 	id = reg->id;
11591 
11592 	if (!env->cur_state->active_locks)
11593 		return -EINVAL;
11594 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
11595 	if (!s) {
11596 		verbose(env, "held lock and object are not in the same allocation\n");
11597 		return -EINVAL;
11598 	}
11599 	return 0;
11600 }
11601 
11602 static bool is_bpf_list_api_kfunc(u32 btf_id)
11603 {
11604 	return is_bpf_list_push_kfunc(btf_id) ||
11605 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11606 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
11607 	       btf_id == special_kfunc_list[KF_bpf_list_del] ||
11608 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
11609 	       btf_id == special_kfunc_list[KF_bpf_list_back] ||
11610 	       btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
11611 	       btf_id == special_kfunc_list[KF_bpf_list_is_last] ||
11612 	       btf_id == special_kfunc_list[KF_bpf_list_empty];
11613 }
11614 
11615 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11616 {
11617 	return is_bpf_rbtree_add_kfunc(btf_id) ||
11618 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11619 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
11620 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
11621 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
11622 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
11623 }
11624 
11625 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
11626 {
11627 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
11628 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
11629 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
11630 }
11631 
11632 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11633 {
11634 	return is_bpf_list_api_kfunc(btf_id) ||
11635 	       is_bpf_rbtree_api_kfunc(btf_id) ||
11636 	       is_bpf_refcount_acquire_kfunc(btf_id);
11637 }
11638 
11639 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
11640 {
11641 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
11642 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
11643 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
11644 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
11645 }
11646 
11647 static bool is_bpf_arena_kfunc(u32 btf_id)
11648 {
11649 	return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] ||
11650 	       btf_id == special_kfunc_list[KF_bpf_arena_free_pages] ||
11651 	       btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages];
11652 }
11653 
11654 static bool is_bpf_stream_kfunc(u32 btf_id)
11655 {
11656 	return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] ||
11657 	       btf_id == special_kfunc_list[KF_bpf_stream_print_stack];
11658 }
11659 
11660 static bool kfunc_spin_allowed(u32 btf_id)
11661 {
11662 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
11663 	       is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) ||
11664 	       is_bpf_stream_kfunc(btf_id);
11665 }
11666 
11667 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11668 {
11669 	return is_bpf_rbtree_add_kfunc(btf_id);
11670 }
11671 
11672 static bool is_async_callback_calling_kfunc(u32 btf_id)
11673 {
11674 	return is_bpf_wq_set_callback_kfunc(btf_id) ||
11675 	       is_task_work_add_kfunc(btf_id);
11676 }
11677 
11678 bool bpf_is_throw_kfunc(struct bpf_insn *insn)
11679 {
11680 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11681 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11682 }
11683 
11684 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
11685 {
11686 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
11687 }
11688 
11689 static bool is_callback_calling_kfunc(u32 btf_id)
11690 {
11691 	return is_sync_callback_calling_kfunc(btf_id) ||
11692 	       is_async_callback_calling_kfunc(btf_id);
11693 }
11694 
11695 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11696 {
11697 	return is_bpf_rbtree_api_kfunc(btf_id);
11698 }
11699 
11700 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11701 					  enum btf_field_type head_field_type,
11702 					  u32 kfunc_btf_id)
11703 {
11704 	bool ret;
11705 
11706 	switch (head_field_type) {
11707 	case BPF_LIST_HEAD:
11708 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11709 		break;
11710 	case BPF_RB_ROOT:
11711 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11712 		break;
11713 	default:
11714 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11715 			btf_field_type_name(head_field_type));
11716 		return false;
11717 	}
11718 
11719 	if (!ret)
11720 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11721 			btf_field_type_name(head_field_type));
11722 	return ret;
11723 }
11724 
11725 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11726 					  enum btf_field_type node_field_type,
11727 					  u32 kfunc_btf_id)
11728 {
11729 	bool ret;
11730 
11731 	switch (node_field_type) {
11732 	case BPF_LIST_NODE:
11733 		ret = is_bpf_list_push_kfunc(kfunc_btf_id) ||
11734 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] ||
11735 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] ||
11736 		      kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last];
11737 		break;
11738 	case BPF_RB_NODE:
11739 		ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) ||
11740 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11741 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
11742 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
11743 		break;
11744 	default:
11745 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11746 			btf_field_type_name(node_field_type));
11747 		return false;
11748 	}
11749 
11750 	if (!ret)
11751 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11752 			btf_field_type_name(node_field_type));
11753 	return ret;
11754 }
11755 
11756 static int
11757 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11758 				   struct bpf_reg_state *reg, argno_t argno,
11759 				   struct bpf_kfunc_call_arg_meta *meta,
11760 				   enum btf_field_type head_field_type,
11761 				   struct btf_field **head_field)
11762 {
11763 	const char *head_type_name;
11764 	struct btf_field *field;
11765 	struct btf_record *rec;
11766 	u32 head_off;
11767 
11768 	if (meta->btf != btf_vmlinux) {
11769 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
11770 		return -EFAULT;
11771 	}
11772 
11773 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11774 		return -EFAULT;
11775 
11776 	head_type_name = btf_field_type_name(head_field_type);
11777 	if (!tnum_is_const(reg->var_off)) {
11778 		verbose(env,
11779 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
11780 			reg_arg_name(env, argno), head_type_name);
11781 		return -EINVAL;
11782 	}
11783 
11784 	rec = reg_btf_record(reg);
11785 	head_off = reg->var_off.value;
11786 	field = btf_record_find(rec, head_off, head_field_type);
11787 	if (!field) {
11788 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11789 		return -EINVAL;
11790 	}
11791 
11792 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11793 	if (check_reg_allocation_locked(env, reg)) {
11794 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11795 			rec->spin_lock_off, head_type_name);
11796 		return -EINVAL;
11797 	}
11798 
11799 	if (*head_field) {
11800 		verifier_bug(env, "repeating %s arg", head_type_name);
11801 		return -EFAULT;
11802 	}
11803 	*head_field = field;
11804 	return 0;
11805 }
11806 
11807 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11808 					   struct bpf_reg_state *reg, argno_t argno,
11809 					   struct bpf_kfunc_call_arg_meta *meta)
11810 {
11811 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD,
11812 							  &meta->arg_list_head.field);
11813 }
11814 
11815 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11816 					     struct bpf_reg_state *reg, argno_t argno,
11817 					     struct bpf_kfunc_call_arg_meta *meta)
11818 {
11819 	return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT,
11820 							  &meta->arg_rbtree_root.field);
11821 }
11822 
11823 static int
11824 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11825 				   struct bpf_reg_state *reg, argno_t argno,
11826 				   struct bpf_kfunc_call_arg_meta *meta,
11827 				   enum btf_field_type head_field_type,
11828 				   enum btf_field_type node_field_type,
11829 				   struct btf_field **node_field)
11830 {
11831 	const char *node_type_name;
11832 	const struct btf_type *et, *t;
11833 	struct btf_field *field;
11834 	u32 node_off;
11835 
11836 	if (meta->btf != btf_vmlinux) {
11837 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
11838 		return -EFAULT;
11839 	}
11840 
11841 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11842 		return -EFAULT;
11843 
11844 	node_type_name = btf_field_type_name(node_field_type);
11845 	if (!tnum_is_const(reg->var_off)) {
11846 		verbose(env,
11847 			"%s doesn't have constant offset. %s has to be at the constant offset\n",
11848 			reg_arg_name(env, argno), node_type_name);
11849 		return -EINVAL;
11850 	}
11851 
11852 	node_off = reg->var_off.value;
11853 	field = reg_find_field_offset(reg, node_off, node_field_type);
11854 	if (!field) {
11855 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11856 		return -EINVAL;
11857 	}
11858 
11859 	field = *node_field;
11860 
11861 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11862 	t = btf_type_by_id(reg->btf, reg->btf_id);
11863 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11864 				  field->graph_root.value_btf_id, true)) {
11865 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11866 			"in struct %s, but arg is at offset=%d in struct %s\n",
11867 			btf_field_type_name(head_field_type),
11868 			btf_field_type_name(node_field_type),
11869 			field->graph_root.node_offset,
11870 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11871 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11872 		return -EINVAL;
11873 	}
11874 	meta->arg_btf = reg->btf;
11875 	meta->arg_btf_id = reg->btf_id;
11876 
11877 	if (node_off != field->graph_root.node_offset) {
11878 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11879 			node_off, btf_field_type_name(node_field_type),
11880 			field->graph_root.node_offset,
11881 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11882 		return -EINVAL;
11883 	}
11884 
11885 	return 0;
11886 }
11887 
11888 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11889 					   struct bpf_reg_state *reg, argno_t argno,
11890 					   struct bpf_kfunc_call_arg_meta *meta)
11891 {
11892 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
11893 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11894 						  &meta->arg_list_head.field);
11895 }
11896 
11897 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11898 					     struct bpf_reg_state *reg, argno_t argno,
11899 					     struct bpf_kfunc_call_arg_meta *meta)
11900 {
11901 	return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta,
11902 						  BPF_RB_ROOT, BPF_RB_NODE,
11903 						  &meta->arg_rbtree_root.field);
11904 }
11905 
11906 /*
11907  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11908  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11909  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11910  * them can only be attached to some specific hook points.
11911  */
11912 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11913 {
11914 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11915 
11916 	switch (prog_type) {
11917 	case BPF_PROG_TYPE_LSM:
11918 		return true;
11919 	case BPF_PROG_TYPE_TRACING:
11920 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11921 			return true;
11922 		fallthrough;
11923 	default:
11924 		return in_sleepable(env);
11925 	}
11926 }
11927 
11928 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11929 			    int insn_idx)
11930 {
11931 	const char *func_name = meta->func_name, *ref_tname;
11932 	struct bpf_func_state *caller = cur_func(env);
11933 	struct bpf_reg_state *regs = cur_regs(env);
11934 	const struct btf *btf = meta->btf;
11935 	const struct btf_param *args;
11936 	struct btf_record *rec;
11937 	u32 i, nargs;
11938 	int ret;
11939 
11940 	args = (const struct btf_param *)(meta->func_proto + 1);
11941 	nargs = btf_type_vlen(meta->func_proto);
11942 	if (nargs > MAX_BPF_FUNC_ARGS) {
11943 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11944 			MAX_BPF_FUNC_ARGS);
11945 		return -EINVAL;
11946 	}
11947 	if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) {
11948 		verbose(env, "JIT does not support kfunc %s() with %d args\n",
11949 			func_name, nargs);
11950 		return -ENOTSUPP;
11951 	}
11952 
11953 	ret = check_outgoing_stack_args(env, caller, nargs);
11954 	if (ret)
11955 		return ret;
11956 
11957 	/* Check that BTF function arguments match actual types that the
11958 	 * verifier sees.
11959 	 */
11960 	for (i = 0; i < nargs; i++) {
11961 		struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i);
11962 		const struct btf_type *t, *ref_t, *resolve_ret;
11963 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11964 		argno_t argno = argno_from_arg(i + 1);
11965 		int regno = reg_from_argno(argno);
11966 		bool btf_id_fixed_off_ok = true;
11967 		u32 ref_id, type_size;
11968 		bool is_ret_buf_sz = false;
11969 		int kf_arg_type;
11970 
11971 		if (is_kfunc_arg_prog_aux(btf, &args[i])) {
11972 			/* Reject repeated use bpf_prog_aux */
11973 			if (meta->arg_prog) {
11974 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
11975 				return -EFAULT;
11976 			}
11977 			if (regno < 0) {
11978 				verbose(env, "%s prog->aux cannot be a stack argument\n",
11979 					reg_arg_name(env, argno));
11980 				return -EINVAL;
11981 			}
11982 			meta->arg_prog = true;
11983 			cur_aux(env)->arg_prog = regno;
11984 			continue;
11985 		}
11986 
11987 		if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i))
11988 			continue;
11989 
11990 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11991 
11992 		if (btf_type_is_scalar(t)) {
11993 			if (reg->type != SCALAR_VALUE) {
11994 				verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno));
11995 				return -EINVAL;
11996 			}
11997 
11998 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11999 				if (meta->arg_constant.found) {
12000 					verifier_bug(env, "only one constant argument permitted");
12001 					return -EFAULT;
12002 				}
12003 				if (!tnum_is_const(reg->var_off)) {
12004 					verbose(env, "%s must be a known constant\n",
12005 						reg_arg_name(env, argno));
12006 					return -EINVAL;
12007 				}
12008 				if (regno >= 0)
12009 					ret = mark_chain_precision(env, regno);
12010 				else
12011 					ret = mark_stack_arg_precision(env, i);
12012 				if (ret < 0)
12013 					return ret;
12014 				meta->arg_constant.found = true;
12015 				meta->arg_constant.value = reg->var_off.value;
12016 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
12017 				meta->r0_rdonly = true;
12018 				is_ret_buf_sz = true;
12019 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
12020 				is_ret_buf_sz = true;
12021 			}
12022 
12023 			if (is_ret_buf_sz) {
12024 				if (meta->r0_size) {
12025 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
12026 					return -EINVAL;
12027 				}
12028 
12029 				if (!tnum_is_const(reg->var_off)) {
12030 					verbose(env, "%s is not a const\n",
12031 						reg_arg_name(env, argno));
12032 					return -EINVAL;
12033 				}
12034 
12035 				meta->r0_size = reg->var_off.value;
12036 				if (regno >= 0)
12037 					ret = mark_chain_precision(env, regno);
12038 				else
12039 					ret = mark_stack_arg_precision(env, i);
12040 				if (ret)
12041 					return ret;
12042 			}
12043 			continue;
12044 		}
12045 
12046 		if (!btf_type_is_ptr(t)) {
12047 			verbose(env, "Unrecognized %s type %s\n",
12048 				reg_arg_name(env, argno), btf_type_str(t));
12049 			return -EINVAL;
12050 		}
12051 
12052 		if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) &&
12053 		    !is_kfunc_arg_nullable(meta->btf, &args[i])) {
12054 			verbose(env, "Possibly NULL pointer passed to trusted %s\n",
12055 				reg_arg_name(env, argno));
12056 			return -EACCES;
12057 		}
12058 
12059 		if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) &&
12060 		    !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) {
12061 			verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n",
12062 				func_name, reg_arg_name(env, argno));
12063 			return -EINVAL;
12064 		}
12065 
12066 		if (reg_is_referenced(env, reg))
12067 			update_ref_obj(&meta->ref_obj, reg);
12068 
12069 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12070 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12071 
12072 		kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname,
12073 						     args, i, nargs, argno, reg);
12074 		if (kf_arg_type < 0)
12075 			return kf_arg_type;
12076 
12077 		switch (kf_arg_type) {
12078 		case KF_ARG_PTR_TO_NULL:
12079 			continue;
12080 		case KF_ARG_PTR_TO_MAP:
12081 			if (!reg->map_ptr) {
12082 				verbose(env, "pointer in %s isn't map pointer\n",
12083 					reg_arg_name(env, argno));
12084 				return -EINVAL;
12085 			}
12086 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
12087 					      reg->map_ptr->record->task_work_off >= 0)) {
12088 				/* Use map_uid (which is unique id of inner map) to reject:
12089 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12090 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12091 				 * if (inner_map1 && inner_map2) {
12092 				 *     wq = bpf_map_lookup_elem(inner_map1);
12093 				 *     if (wq)
12094 				 *         // mismatch would have been allowed
12095 				 *         bpf_wq_init(wq, inner_map2);
12096 				 * }
12097 				 *
12098 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
12099 				 */
12100 				if (meta->map.ptr != reg->map_ptr ||
12101 				    meta->map.uid != reg->map_uid) {
12102 					if (reg->map_ptr->record->task_work_off >= 0) {
12103 						verbose(env,
12104 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
12105 							meta->map.uid, reg->map_uid);
12106 						return -EINVAL;
12107 					}
12108 					verbose(env,
12109 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12110 						meta->map.uid, reg->map_uid);
12111 					return -EINVAL;
12112 				}
12113 			}
12114 			meta->map.ptr = reg->map_ptr;
12115 			meta->map.uid = reg->map_uid;
12116 			fallthrough;
12117 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12118 		case KF_ARG_PTR_TO_BTF_ID:
12119 			if (!is_trusted_reg(env, reg)) {
12120 				if (!is_kfunc_rcu(meta)) {
12121 					verbose(env, "%s must be referenced or trusted\n",
12122 						reg_arg_name(env, argno));
12123 					return -EINVAL;
12124 				}
12125 				if (!is_rcu_reg(reg)) {
12126 					verbose(env, "%s must be a rcu pointer\n",
12127 						reg_arg_name(env, argno));
12128 					return -EINVAL;
12129 				}
12130 			}
12131 			fallthrough;
12132 		case KF_ARG_PTR_TO_ITER:
12133 		case KF_ARG_PTR_TO_LIST_HEAD:
12134 		case KF_ARG_PTR_TO_LIST_NODE:
12135 		case KF_ARG_PTR_TO_RB_ROOT:
12136 		case KF_ARG_PTR_TO_RB_NODE:
12137 		case KF_ARG_PTR_TO_MEM:
12138 		case KF_ARG_PTR_TO_MEM_SIZE:
12139 		case KF_ARG_PTR_TO_CALLBACK:
12140 		case KF_ARG_PTR_TO_CONST_STR:
12141 		case KF_ARG_PTR_TO_WORKQUEUE:
12142 		case KF_ARG_PTR_TO_TIMER:
12143 		case KF_ARG_PTR_TO_TASK_WORK:
12144 		case KF_ARG_PTR_TO_IRQ_FLAG:
12145 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
12146 			break;
12147 		case KF_ARG_PTR_TO_DYNPTR:
12148 			arg_type = ARG_PTR_TO_DYNPTR;
12149 			break;
12150 		case KF_ARG_PTR_TO_CTX:
12151 			arg_type = ARG_PTR_TO_CTX;
12152 			break;
12153 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12154 			arg_type = ARG_PTR_TO_BTF_ID;
12155 			btf_id_fixed_off_ok = false;
12156 			break;
12157 		default:
12158 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
12159 			return -EFAULT;
12160 		}
12161 
12162 		if (regno == meta->release_regno)
12163 			arg_type |= OBJ_RELEASE;
12164 		ret = __check_func_arg_reg_off(env, reg, argno, arg_type,
12165 					       btf_id_fixed_off_ok);
12166 		if (ret < 0)
12167 			return ret;
12168 
12169 		switch (kf_arg_type) {
12170 		case KF_ARG_PTR_TO_CTX:
12171 			if (reg->type != PTR_TO_CTX) {
12172 				verbose(env, "%s expected pointer to ctx, but got %s\n",
12173 					reg_arg_name(env, argno), reg_type_str(env, reg->type));
12174 				return -EINVAL;
12175 			}
12176 
12177 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12178 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12179 				if (ret < 0)
12180 					return -EINVAL;
12181 				meta->ret_btf_id  = ret;
12182 			}
12183 			break;
12184 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12185 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12186 				if (!is_bpf_obj_drop_kfunc(meta->func_id)) {
12187 					verbose(env, "%s expected for bpf_obj_drop()\n",
12188 						reg_arg_name(env, argno));
12189 					return -EINVAL;
12190 				}
12191 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12192 				if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) {
12193 					verbose(env, "%s expected for bpf_percpu_obj_drop()\n",
12194 						reg_arg_name(env, argno));
12195 					return -EINVAL;
12196 				}
12197 			} else {
12198 				verbose(env, "%s expected pointer to allocated object\n",
12199 					reg_arg_name(env, argno));
12200 				return -EINVAL;
12201 			}
12202 			if (!reg_is_referenced(env, reg)) {
12203 				verbose(env, "allocated object must be referenced\n");
12204 				return -EINVAL;
12205 			}
12206 			if (meta->btf == btf_vmlinux) {
12207 				meta->arg_btf = reg->btf;
12208 				meta->arg_btf_id = reg->btf_id;
12209 			}
12210 			break;
12211 		case KF_ARG_PTR_TO_DYNPTR:
12212 		{
12213 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12214 
12215 			if (is_kfunc_arg_uninit(btf, &args[i]))
12216 				dynptr_arg_type |= MEM_UNINIT;
12217 
12218 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12219 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
12220 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12221 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12222 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
12223 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
12224 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
12225 				dynptr_arg_type |= DYNPTR_TYPE_FILE;
12226 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
12227 				dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE;
12228 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12229 				   (dynptr_arg_type & MEM_UNINIT)) {
12230 				enum bpf_dynptr_type parent_type = meta->dynptr.type;
12231 
12232 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12233 					verifier_bug(env, "no dynptr type for parent of clone");
12234 					return -EFAULT;
12235 				}
12236 
12237 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12238 			}
12239 
12240 			ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type,
12241 						  &meta->ref_obj, &meta->dynptr);
12242 			if (ret < 0)
12243 				return ret;
12244 			break;
12245 		}
12246 		case KF_ARG_PTR_TO_ITER:
12247 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12248 				if (!check_css_task_iter_allowlist(env)) {
12249 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12250 					return -EINVAL;
12251 				}
12252 			}
12253 			ret = process_iter_arg(env, reg, argno, insn_idx, meta);
12254 			if (ret < 0)
12255 				return ret;
12256 			break;
12257 		case KF_ARG_PTR_TO_LIST_HEAD:
12258 			if (reg->type != PTR_TO_MAP_VALUE &&
12259 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12260 				verbose(env, "%s expected pointer to map value or allocated object\n",
12261 					reg_arg_name(env, argno));
12262 				return -EINVAL;
12263 			}
12264 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12265 			    !reg_is_referenced(env, reg)) {
12266 				verbose(env, "allocated object must be referenced\n");
12267 				return -EINVAL;
12268 			}
12269 			ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta);
12270 			if (ret < 0)
12271 				return ret;
12272 			break;
12273 		case KF_ARG_PTR_TO_RB_ROOT:
12274 			if (reg->type != PTR_TO_MAP_VALUE &&
12275 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12276 				verbose(env, "%s expected pointer to map value or allocated object\n",
12277 					reg_arg_name(env, argno));
12278 				return -EINVAL;
12279 			}
12280 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) &&
12281 			    !reg_is_referenced(env, reg)) {
12282 				verbose(env, "allocated object must be referenced\n");
12283 				return -EINVAL;
12284 			}
12285 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta);
12286 			if (ret < 0)
12287 				return ret;
12288 			break;
12289 		case KF_ARG_PTR_TO_LIST_NODE:
12290 			if (is_kfunc_arg_nonown_allowed(btf, &args[i]) &&
12291 			    type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) {
12292 				/* Allow bpf_list_front/back return value for
12293 				 * __nonown_allowed list-node arguments.
12294 				 */
12295 				goto check_ok;
12296 			}
12297 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12298 				verbose(env, "%s expected pointer to allocated object\n",
12299 					reg_arg_name(env, argno));
12300 				return -EINVAL;
12301 			}
12302 			if (!reg_is_referenced(env, reg)) {
12303 				verbose(env, "allocated object must be referenced\n");
12304 				return -EINVAL;
12305 			}
12306 check_ok:
12307 			ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta);
12308 			if (ret < 0)
12309 				return ret;
12310 			break;
12311 		case KF_ARG_PTR_TO_RB_NODE:
12312 			if (is_bpf_rbtree_add_kfunc(meta->func_id)) {
12313 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12314 					verbose(env, "%s expected pointer to allocated object\n",
12315 						reg_arg_name(env, argno));
12316 					return -EINVAL;
12317 				}
12318 				if (!reg_is_referenced(env, reg)) {
12319 					verbose(env, "allocated object must be referenced\n");
12320 					return -EINVAL;
12321 				}
12322 			} else {
12323 				if (!type_is_non_owning_ref(reg->type) &&
12324 				    !reg_is_referenced(env, reg)) {
12325 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
12326 					return -EINVAL;
12327 				}
12328 				if (in_rbtree_lock_required_cb(env)) {
12329 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
12330 					return -EINVAL;
12331 				}
12332 			}
12333 
12334 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta);
12335 			if (ret < 0)
12336 				return ret;
12337 			break;
12338 		case KF_ARG_PTR_TO_MAP:
12339 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12340 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12341 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12342 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12343 			fallthrough;
12344 		case KF_ARG_PTR_TO_BTF_ID:
12345 			/* Only base_type is checked, further checks are done here */
12346 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12347 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12348 			    !reg2btf_ids[base_type(reg->type)]) {
12349 				verbose(env, "%s is %s ", reg_arg_name(env, argno),
12350 					reg_type_str(env, reg->type));
12351 				verbose(env, "expected %s or socket\n",
12352 					reg_type_str(env, base_type(reg->type) |
12353 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12354 				return -EINVAL;
12355 			}
12356 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno);
12357 			if (ret < 0)
12358 				return ret;
12359 			break;
12360 		case KF_ARG_PTR_TO_MEM:
12361 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12362 			if (IS_ERR(resolve_ret)) {
12363 				verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n",
12364 					reg_arg_name(env, argno), btf_type_str(ref_t),
12365 					ref_tname, PTR_ERR(resolve_ret));
12366 				return -EINVAL;
12367 			}
12368 			ret = check_mem_reg(env, reg, argno, type_size);
12369 			if (ret < 0)
12370 				return ret;
12371 			break;
12372 		case KF_ARG_PTR_TO_MEM_SIZE:
12373 		{
12374 			struct bpf_reg_state *buff_reg = reg;
12375 			const struct btf_param *buff_arg = &args[i];
12376 			struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1);
12377 			const struct btf_param *size_arg = &args[i + 1];
12378 			argno_t next_argno = argno_from_arg(i + 2);
12379 
12380 			if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) {
12381 				ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg,
12382 							       argno, next_argno);
12383 				if (ret < 0) {
12384 					verbose(env, "%s and ", reg_arg_name(env, argno));
12385 					verbose(env, "%s memory, len pair leads to invalid memory access\n",
12386 						reg_arg_name(env, next_argno));
12387 					return ret;
12388 				}
12389 			}
12390 
12391 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12392 				if (meta->arg_constant.found) {
12393 					verifier_bug(env, "only one constant argument permitted");
12394 					return -EFAULT;
12395 				}
12396 				if (!tnum_is_const(size_reg->var_off)) {
12397 					verbose(env, "%s must be a known constant\n",
12398 						reg_arg_name(env, next_argno));
12399 					return -EINVAL;
12400 				}
12401 				meta->arg_constant.found = true;
12402 				meta->arg_constant.value = size_reg->var_off.value;
12403 			}
12404 
12405 			/* Skip next '__sz' or '__szk' argument */
12406 			i++;
12407 			break;
12408 		}
12409 		case KF_ARG_PTR_TO_CALLBACK:
12410 			if (reg->type != PTR_TO_FUNC) {
12411 				verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno));
12412 				return -EINVAL;
12413 			}
12414 			meta->subprogno = reg->subprogno;
12415 			break;
12416 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12417 			if (!type_is_ptr_alloc_obj(reg->type)) {
12418 				verbose(env, "%s is neither owning or non-owning ref\n",
12419 					reg_arg_name(env, argno));
12420 				return -EINVAL;
12421 			}
12422 			if (!type_is_non_owning_ref(reg->type))
12423 				meta->arg_owning_ref = true;
12424 
12425 			rec = reg_btf_record(reg);
12426 			if (!rec) {
12427 				verifier_bug(env, "Couldn't find btf_record");
12428 				return -EFAULT;
12429 			}
12430 
12431 			if (rec->refcount_off < 0) {
12432 				verbose(env, "%s doesn't point to a type with bpf_refcount field\n",
12433 					reg_arg_name(env, argno));
12434 				return -EINVAL;
12435 			}
12436 
12437 			meta->arg_btf = reg->btf;
12438 			meta->arg_btf_id = reg->btf_id;
12439 			break;
12440 		case KF_ARG_PTR_TO_CONST_STR:
12441 			if (reg->type != PTR_TO_MAP_VALUE) {
12442 				verbose(env, "%s doesn't point to a const string\n",
12443 					reg_arg_name(env, argno));
12444 				return -EINVAL;
12445 			}
12446 			ret = check_arg_const_str(env, reg, argno);
12447 			if (ret)
12448 				return ret;
12449 			break;
12450 		case KF_ARG_PTR_TO_WORKQUEUE:
12451 			if (reg->type != PTR_TO_MAP_VALUE) {
12452 				verbose(env, "%s doesn't point to a map value\n",
12453 					reg_arg_name(env, argno));
12454 				return -EINVAL;
12455 			}
12456 			ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map);
12457 			if (ret < 0)
12458 				return ret;
12459 			break;
12460 		case KF_ARG_PTR_TO_TIMER:
12461 			if (reg->type != PTR_TO_MAP_VALUE) {
12462 				verbose(env, "%s doesn't point to a map value\n",
12463 					reg_arg_name(env, argno));
12464 				return -EINVAL;
12465 			}
12466 			ret = process_timer_kfunc(env, reg, argno, meta);
12467 			if (ret < 0)
12468 				return ret;
12469 			break;
12470 		case KF_ARG_PTR_TO_TASK_WORK:
12471 			if (reg->type != PTR_TO_MAP_VALUE) {
12472 				verbose(env, "%s doesn't point to a map value\n",
12473 					reg_arg_name(env, argno));
12474 				return -EINVAL;
12475 			}
12476 			ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map);
12477 			if (ret < 0)
12478 				return ret;
12479 			break;
12480 		case KF_ARG_PTR_TO_IRQ_FLAG:
12481 			if (reg->type != PTR_TO_STACK) {
12482 				verbose(env, "%s doesn't point to an irq flag on stack\n",
12483 					reg_arg_name(env, argno));
12484 				return -EINVAL;
12485 			}
12486 			ret = process_irq_flag(env, reg, argno, meta);
12487 			if (ret < 0)
12488 				return ret;
12489 			break;
12490 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
12491 		{
12492 			int flags = PROCESS_RES_LOCK;
12493 
12494 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12495 				verbose(env, "%s doesn't point to map value or allocated object\n",
12496 					reg_arg_name(env, argno));
12497 				return -EINVAL;
12498 			}
12499 
12500 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
12501 				return -EFAULT;
12502 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12503 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12504 				flags |= PROCESS_SPIN_LOCK;
12505 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12506 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12507 				flags |= PROCESS_LOCK_IRQ;
12508 			ret = process_spin_lock(env, reg, argno, flags);
12509 			if (ret < 0)
12510 				return ret;
12511 			break;
12512 		}
12513 		}
12514 	}
12515 
12516 	return 0;
12517 }
12518 
12519 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env,
12520 			     s32 func_id,
12521 			     s16 offset,
12522 			     struct bpf_kfunc_call_arg_meta *meta)
12523 {
12524 	struct bpf_kfunc_meta kfunc;
12525 	int err;
12526 
12527 	err = fetch_kfunc_meta(env, func_id, offset, &kfunc);
12528 	if (err)
12529 		return err;
12530 
12531 	memset(meta, 0, sizeof(*meta));
12532 	meta->btf = kfunc.btf;
12533 	meta->func_id = kfunc.id;
12534 	meta->func_proto = kfunc.proto;
12535 	meta->func_name = kfunc.name;
12536 
12537 	if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog))
12538 		return -EACCES;
12539 
12540 	meta->kfunc_flags = *kfunc.flags;
12541 
12542 	/* Only support release referenced argument passed by register */
12543 	if (is_kfunc_release(meta))
12544 		meta->release_regno = BPF_REG_1;
12545 
12546 	return 0;
12547 }
12548 
12549 /*
12550  * Determine how many bytes a helper accesses through a stack pointer at
12551  * argument position @arg (0-based, corresponding to R1-R5).
12552  *
12553  * Returns:
12554  *   > 0   known read access size in bytes
12555  *     0   doesn't read anything directly
12556  * S64_MIN unknown
12557  *   < 0   known write access of (-return) bytes
12558  */
12559 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
12560 				  int arg, int insn_idx)
12561 {
12562 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12563 	const struct bpf_func_proto *fn;
12564 	enum bpf_arg_type at;
12565 	s64 size;
12566 
12567 	if (bpf_get_helper_proto(env, insn->imm, &fn) < 0)
12568 		return S64_MIN;
12569 
12570 	at = fn->arg_type[arg];
12571 
12572 	switch (base_type(at)) {
12573 	case ARG_PTR_TO_MAP_KEY:
12574 	case ARG_PTR_TO_MAP_VALUE: {
12575 		bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY;
12576 		u64 val;
12577 		int i, map_reg;
12578 
12579 		for (i = 0; i < arg; i++) {
12580 			if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR)
12581 				break;
12582 		}
12583 		if (i >= arg)
12584 			goto scan_all_maps;
12585 
12586 		map_reg = BPF_REG_1 + i;
12587 
12588 		if (!(aux->const_reg_map_mask & BIT(map_reg)))
12589 			goto scan_all_maps;
12590 
12591 		i = aux->const_reg_vals[map_reg];
12592 		if (i < env->used_map_cnt) {
12593 			size = is_key ? env->used_maps[i]->key_size
12594 				      : env->used_maps[i]->value_size;
12595 			goto out;
12596 		}
12597 scan_all_maps:
12598 		/*
12599 		 * Map pointer is not known at this call site (e.g. different
12600 		 * maps on merged paths).  Conservatively return the largest
12601 		 * key_size or value_size across all maps used by the program.
12602 		 */
12603 		val = 0;
12604 		for (i = 0; i < env->used_map_cnt; i++) {
12605 			struct bpf_map *map = env->used_maps[i];
12606 			u32 sz = is_key ? map->key_size : map->value_size;
12607 
12608 			if (sz > val)
12609 				val = sz;
12610 			if (map->inner_map_meta) {
12611 				sz = is_key ? map->inner_map_meta->key_size
12612 					    : map->inner_map_meta->value_size;
12613 				if (sz > val)
12614 					val = sz;
12615 			}
12616 		}
12617 		if (!val)
12618 			return S64_MIN;
12619 		size = val;
12620 		goto out;
12621 	}
12622 	case ARG_PTR_TO_MEM:
12623 		if (at & MEM_FIXED_SIZE) {
12624 			size = fn->arg_size[arg];
12625 			goto out;
12626 		}
12627 		if (arg + 1 < ARRAY_SIZE(fn->arg_type) &&
12628 		    arg_type_is_mem_size(fn->arg_type[arg + 1])) {
12629 			int size_reg = BPF_REG_1 + arg + 1;
12630 
12631 			if (aux->const_reg_mask & BIT(size_reg)) {
12632 				size = (s64)aux->const_reg_vals[size_reg];
12633 				goto out;
12634 			}
12635 			/*
12636 			 * Size arg is const on each path but differs across merged
12637 			 * paths. MAX_BPF_STACK is a safe upper bound for reads.
12638 			 */
12639 			if (at & MEM_UNINIT)
12640 				return 0;
12641 			return MAX_BPF_STACK;
12642 		}
12643 		return S64_MIN;
12644 	case ARG_PTR_TO_DYNPTR:
12645 		size = BPF_DYNPTR_SIZE;
12646 		break;
12647 	case ARG_PTR_TO_STACK:
12648 		/*
12649 		 * Only used by bpf_calls_callback() helpers. The helper itself
12650 		 * doesn't access stack. The callback subprog does and it's
12651 		 * analyzed separately.
12652 		 */
12653 		return 0;
12654 	default:
12655 		return S64_MIN;
12656 	}
12657 out:
12658 	/*
12659 	 * MEM_UNINIT args are write-only: the helper initializes the
12660 	 * buffer without reading it.
12661 	 */
12662 	if (at & MEM_UNINIT)
12663 		return -size;
12664 	return size;
12665 }
12666 
12667 /*
12668  * Determine how many bytes a kfunc accesses through a stack pointer at
12669  * argument position @arg (0-based, corresponding to R1-R5).
12670  *
12671  * Returns:
12672  *   > 0      known read access size in bytes
12673  *     0      doesn't access memory through that argument (ex: not a pointer)
12674  *   S64_MIN  unknown
12675  *   < 0      known write access of (-return) bytes
12676  */
12677 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,
12678 				 int arg, int insn_idx)
12679 {
12680 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
12681 	struct bpf_kfunc_call_arg_meta meta;
12682 	const struct btf_param *args;
12683 	const struct btf_type *t, *ref_t;
12684 	const struct btf *btf;
12685 	u32 nargs, type_size;
12686 	s64 size;
12687 
12688 	if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0)
12689 		return S64_MIN;
12690 
12691 	btf = meta.btf;
12692 	args = btf_params(meta.func_proto);
12693 	nargs = btf_type_vlen(meta.func_proto);
12694 	if (arg >= nargs)
12695 		return 0;
12696 
12697 	t = btf_type_skip_modifiers(btf, args[arg].type, NULL);
12698 	if (!btf_type_is_ptr(t))
12699 		return 0;
12700 
12701 	/* dynptr: fixed 16-byte on-stack representation */
12702 	if (is_kfunc_arg_dynptr(btf, &args[arg])) {
12703 		size = BPF_DYNPTR_SIZE;
12704 		goto out;
12705 	}
12706 
12707 	/* ptr + __sz/__szk pair: size is in the next register */
12708 	if (arg + 1 < nargs &&
12709 	    (btf_param_match_suffix(btf, &args[arg + 1], "__sz") ||
12710 	     btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) {
12711 		int size_reg = BPF_REG_1 + arg + 1;
12712 
12713 		if (aux->const_reg_mask & BIT(size_reg)) {
12714 			size = (s64)aux->const_reg_vals[size_reg];
12715 			goto out;
12716 		}
12717 		return MAX_BPF_STACK;
12718 	}
12719 
12720 	/* fixed-size pointed-to type: resolve via BTF */
12721 	ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
12722 	if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) {
12723 		size = type_size;
12724 		goto out;
12725 	}
12726 
12727 	return S64_MIN;
12728 out:
12729 	/* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */
12730 	if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW)
12731 		return -size;
12732 	if (is_kfunc_arg_uninit(btf, &args[arg]))
12733 		return -size;
12734 	return size;
12735 }
12736 
12737 /* check special kfuncs and return:
12738  *  1  - not fall-through to 'else' branch, continue verification
12739  *  0  - fall-through to 'else' branch
12740  * < 0 - not fall-through to 'else' branch, return error
12741  */
12742 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
12743 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
12744 			       const struct btf_type *ptr_type, struct btf *desc_btf)
12745 {
12746 	const struct btf_type *ret_t;
12747 	int err = 0;
12748 
12749 	if (meta->btf != btf_vmlinux)
12750 		return 0;
12751 
12752 	if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12753 		struct btf_struct_meta *struct_meta;
12754 		struct btf *ret_btf;
12755 		u32 ret_btf_id;
12756 
12757 		if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set)
12758 			return -ENOMEM;
12759 
12760 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
12761 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12762 			return -EINVAL;
12763 		}
12764 
12765 		ret_btf = env->prog->aux->btf;
12766 		ret_btf_id = meta->arg_constant.value;
12767 
12768 		/* This may be NULL due to user not supplying a BTF */
12769 		if (!ret_btf) {
12770 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12771 			return -EINVAL;
12772 		}
12773 
12774 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12775 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
12776 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12777 			return -EINVAL;
12778 		}
12779 
12780 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12781 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12782 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12783 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12784 				return -EINVAL;
12785 			}
12786 
12787 			if (!bpf_global_percpu_ma_set) {
12788 				mutex_lock(&bpf_percpu_ma_lock);
12789 				if (!bpf_global_percpu_ma_set) {
12790 					/* Charge memory allocated with bpf_global_percpu_ma to
12791 					 * root memcg. The obj_cgroup for root memcg is NULL.
12792 					 */
12793 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12794 					if (!err)
12795 						bpf_global_percpu_ma_set = true;
12796 				}
12797 				mutex_unlock(&bpf_percpu_ma_lock);
12798 				if (err)
12799 					return err;
12800 			}
12801 
12802 			mutex_lock(&bpf_percpu_ma_lock);
12803 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12804 			mutex_unlock(&bpf_percpu_ma_lock);
12805 			if (err)
12806 				return err;
12807 		}
12808 
12809 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12810 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) {
12811 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12812 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12813 				return -EINVAL;
12814 			}
12815 
12816 			if (struct_meta) {
12817 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12818 				return -EINVAL;
12819 			}
12820 		}
12821 
12822 		mark_reg_known_zero(env, regs, BPF_REG_0);
12823 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12824 		regs[BPF_REG_0].btf = ret_btf;
12825 		regs[BPF_REG_0].btf_id = ret_btf_id;
12826 		if (is_bpf_percpu_obj_new_kfunc(meta->func_id))
12827 			regs[BPF_REG_0].type |= MEM_PERCPU;
12828 
12829 		insn_aux->obj_new_size = ret_t->size;
12830 		insn_aux->kptr_struct_meta = struct_meta;
12831 	} else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) {
12832 		mark_reg_known_zero(env, regs, BPF_REG_0);
12833 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12834 		regs[BPF_REG_0].btf = meta->arg_btf;
12835 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
12836 
12837 		insn_aux->kptr_struct_meta =
12838 			btf_find_struct_meta(meta->arg_btf,
12839 					     meta->arg_btf_id);
12840 	} else if (is_list_node_type(ptr_type)) {
12841 		struct btf_field *field = meta->arg_list_head.field;
12842 
12843 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12844 	} else if (is_rbtree_node_type(ptr_type)) {
12845 		struct btf_field *field = meta->arg_rbtree_root.field;
12846 
12847 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12848 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12849 		mark_reg_known_zero(env, regs, BPF_REG_0);
12850 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12851 		regs[BPF_REG_0].btf = desc_btf;
12852 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
12853 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12854 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
12855 		if (!ret_t) {
12856 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
12857 				meta->arg_constant.value);
12858 			return -EINVAL;
12859 		} else if (btf_type_is_struct(ret_t)) {
12860 			mark_reg_known_zero(env, regs, BPF_REG_0);
12861 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12862 			regs[BPF_REG_0].btf = desc_btf;
12863 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
12864 		} else if (btf_type_is_void(ret_t)) {
12865 			mark_reg_known_zero(env, regs, BPF_REG_0);
12866 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
12867 			regs[BPF_REG_0].mem_size = 0;
12868 		} else {
12869 			verbose(env,
12870 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
12871 			return -EINVAL;
12872 		}
12873 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12874 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12875 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type);
12876 
12877 		mark_reg_known_zero(env, regs, BPF_REG_0);
12878 
12879 		if (!meta->arg_constant.found) {
12880 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
12881 			return -EFAULT;
12882 		}
12883 
12884 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
12885 
12886 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12887 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12888 
12889 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12890 			regs[BPF_REG_0].type |= MEM_RDONLY;
12891 		} else {
12892 			/* this will set env->seen_direct_write to true */
12893 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12894 				verbose(env, "the prog does not allow writes to packet data\n");
12895 				return -EINVAL;
12896 			}
12897 		}
12898 
12899 		if (!meta->dynptr.id) {
12900 			verifier_bug(env, "no dynptr id");
12901 			return -EFAULT;
12902 		}
12903 		regs[BPF_REG_0].parent_id = meta->dynptr.id;
12904 	} else {
12905 		return 0;
12906 	}
12907 
12908 	return 1;
12909 }
12910 
12911 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12912 
12913 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12914 			    int *insn_idx_p)
12915 {
12916 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12917 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12918 	struct bpf_reg_state *regs = cur_regs(env);
12919 	const char *func_name, *ptr_type_name;
12920 	const struct btf_type *t, *ptr_type;
12921 	struct bpf_kfunc_call_arg_meta meta;
12922 	struct bpf_insn_aux_data *insn_aux;
12923 	int err, insn_idx = *insn_idx_p;
12924 	const struct btf_param *args;
12925 	u32 i, nargs, ptr_type_id;
12926 	struct btf *desc_btf;
12927 	int id;
12928 
12929 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12930 	if (!insn->imm)
12931 		return 0;
12932 
12933 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
12934 	if (err == -EACCES && meta.func_name)
12935 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
12936 	if (err)
12937 		return err;
12938 	desc_btf = meta.btf;
12939 	func_name = meta.func_name;
12940 	insn_aux = &env->insn_aux_data[insn_idx];
12941 
12942 	insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta);
12943 
12944 	if (!insn->off &&
12945 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
12946 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
12947 		struct bpf_verifier_state *branch;
12948 		struct bpf_reg_state *regs;
12949 
12950 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
12951 		if (IS_ERR(branch)) {
12952 			verbose(env, "failed to push state for failed lock acquisition\n");
12953 			return PTR_ERR(branch);
12954 		}
12955 
12956 		regs = branch->frame[branch->curframe]->regs;
12957 
12958 		/* Clear r0-r5 registers in forked state */
12959 		for (i = 0; i < CALLER_SAVED_REGS; i++)
12960 			bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
12961 
12962 		mark_reg_unknown(env, regs, BPF_REG_0);
12963 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
12964 		if (err) {
12965 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
12966 			return err;
12967 		}
12968 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
12969 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
12970 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
12971 		return -EFAULT;
12972 	}
12973 
12974 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12975 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12976 		return -EACCES;
12977 	}
12978 
12979 	sleepable = bpf_is_kfunc_sleepable(&meta);
12980 	if (sleepable && !in_sleepable(env)) {
12981 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12982 		return -EACCES;
12983 	}
12984 
12985 	/* Track non-sleepable context for kfuncs, same as for helpers. */
12986 	if (!in_sleepable_context(env))
12987 		insn_aux->non_sleepable = true;
12988 
12989 	/* Check the arguments */
12990 	err = check_kfunc_args(env, &meta, insn_idx);
12991 	if (err < 0)
12992 		return err;
12993 
12994 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
12995 	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) ||
12996 	     /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */
12997 	     (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER
12998 	      && !env->prog->sleepable))) {
12999 		struct btf_struct_meta *struct_meta;
13000 
13001 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13002 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
13003 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
13004 				func_name);
13005 			return -EINVAL;
13006 		}
13007 	}
13008 
13009 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
13010 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13011 					 set_rbtree_add_callback_state);
13012 		if (err) {
13013 			verbose(env, "kfunc %s#%d failed callback verification\n",
13014 				func_name, meta.func_id);
13015 			return err;
13016 		}
13017 	}
13018 
13019 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13020 		meta.r0_size = sizeof(u64);
13021 		meta.r0_rdonly = false;
13022 	}
13023 
13024 	if (is_bpf_wq_set_callback_kfunc(meta.func_id)) {
13025 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13026 					 set_timer_callback_state);
13027 		if (err) {
13028 			verbose(env, "kfunc %s#%d failed callback verification\n",
13029 				func_name, meta.func_id);
13030 			return err;
13031 		}
13032 	}
13033 
13034 	if (is_task_work_add_kfunc(meta.func_id)) {
13035 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13036 					 set_task_work_schedule_callback_state);
13037 		if (err) {
13038 			verbose(env, "kfunc %s#%d failed callback verification\n",
13039 				func_name, meta.func_id);
13040 			return err;
13041 		}
13042 	}
13043 
13044 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13045 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13046 
13047 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13048 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13049 
13050 	if (rcu_lock) {
13051 		env->cur_state->active_rcu_locks++;
13052 	} else if (rcu_unlock) {
13053 		if (env->cur_state->active_rcu_locks == 0) {
13054 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13055 			return -EINVAL;
13056 		}
13057 		if (--env->cur_state->active_rcu_locks == 0)
13058 			invalidate_rcu_protected_refs(env);
13059 	} else if (preempt_disable) {
13060 		env->cur_state->active_preempt_locks++;
13061 	} else if (preempt_enable) {
13062 		if (env->cur_state->active_preempt_locks == 0) {
13063 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13064 			return -EINVAL;
13065 		}
13066 		env->cur_state->active_preempt_locks--;
13067 	}
13068 
13069 	if (sleepable && !in_sleepable_context(env)) {
13070 		verbose(env, "kernel func %s is sleepable within %s\n",
13071 			func_name, non_sleepable_context_description(env));
13072 		return -EACCES;
13073 	}
13074 
13075 	if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13076 		verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13077 		return -EACCES;
13078 	}
13079 
13080 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13081 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13082 		return -EACCES;
13083 	}
13084 
13085 	/* In case of release function, we get register number of refcounted
13086 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13087 	 */
13088 	if (meta.release_regno) {
13089 		err = release_reg(env, &regs[meta.release_regno], false, !!meta.dynptr.id);
13090 		if (err)
13091 			return err;
13092 	}
13093 
13094 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
13095 		id = regs[BPF_REG_2].id;
13096 		insn_aux->insert_off = regs[BPF_REG_2].var_off.value;
13097 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13098 		ref_convert_owning_non_owning(env, id);
13099 	}
13100 
13101 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13102 		if (!bpf_jit_supports_exceptions()) {
13103 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13104 				func_name, meta.func_id);
13105 			return -ENOTSUPP;
13106 		}
13107 		env->seen_exception = true;
13108 
13109 		/* In the case of the default callback, the cookie value passed
13110 		 * to bpf_throw becomes the return value of the program.
13111 		 */
13112 		if (!env->exception_callback_subprog) {
13113 			err = check_return_code(env, BPF_REG_1, "R1");
13114 			if (err < 0)
13115 				return err;
13116 		}
13117 	}
13118 
13119 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
13120 		u32 regno = caller_saved[i];
13121 
13122 		bpf_mark_reg_not_init(env, &regs[regno]);
13123 		regs[regno].subreg_def = DEF_NOT_SUBREG;
13124 	}
13125 	invalidate_outgoing_stack_args(env, cur_func(env));
13126 
13127 	/* Check return type */
13128 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13129 
13130 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13131 		if (meta.btf != btf_vmlinux ||
13132 		    (!is_bpf_obj_new_kfunc(meta.func_id) &&
13133 		     !is_bpf_percpu_obj_new_kfunc(meta.func_id) &&
13134 		     !is_bpf_refcount_acquire_kfunc(meta.func_id))) {
13135 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13136 			return -EINVAL;
13137 		}
13138 	}
13139 
13140 	if (btf_type_is_scalar(t)) {
13141 		mark_reg_unknown(env, regs, BPF_REG_0);
13142 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13143 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
13144 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
13145 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13146 	} else if (btf_type_is_ptr(t)) {
13147 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13148 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
13149 		if (err) {
13150 			if (err < 0)
13151 				return err;
13152 		} else if (btf_type_is_void(ptr_type)) {
13153 			/* kfunc returning 'void *' is equivalent to returning scalar */
13154 			mark_reg_unknown(env, regs, BPF_REG_0);
13155 		} else if (!__btf_type_is_struct(ptr_type)) {
13156 			if (!meta.r0_size) {
13157 				__u32 sz;
13158 
13159 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13160 					meta.r0_size = sz;
13161 					meta.r0_rdonly = true;
13162 				}
13163 			}
13164 			if (!meta.r0_size) {
13165 				ptr_type_name = btf_name_by_offset(desc_btf,
13166 								   ptr_type->name_off);
13167 				verbose(env,
13168 					"kernel function %s returns pointer type %s %s is not supported\n",
13169 					func_name,
13170 					btf_type_str(ptr_type),
13171 					ptr_type_name);
13172 				return -EINVAL;
13173 			}
13174 
13175 			mark_reg_known_zero(env, regs, BPF_REG_0);
13176 			regs[BPF_REG_0].type = PTR_TO_MEM;
13177 			regs[BPF_REG_0].mem_size = meta.r0_size;
13178 
13179 			if (meta.r0_rdonly)
13180 				regs[BPF_REG_0].type |= MEM_RDONLY;
13181 
13182 			/* Ensures we don't access the memory after a release_reference() */
13183 			if (meta.ref_obj.id) {
13184 				err = validate_ref_obj(env, &meta.ref_obj);
13185 				if (err)
13186 					return err;
13187 				regs[BPF_REG_0].parent_id = meta.ref_obj.id;
13188 			}
13189 
13190 			if (is_kfunc_rcu_protected(&meta))
13191 				regs[BPF_REG_0].type |= MEM_RCU;
13192 		} else {
13193 			enum bpf_reg_type type = PTR_TO_BTF_ID;
13194 
13195 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
13196 				type |= PTR_UNTRUSTED;
13197 			else if (is_kfunc_rcu_protected(&meta) ||
13198 				 (bpf_is_iter_next_kfunc(&meta) &&
13199 				  (get_iter_from_state(env->cur_state, &meta)
13200 					   ->type & MEM_RCU))) {
13201 				/*
13202 				 * If the iterator's constructor (the _new
13203 				 * function e.g., bpf_iter_task_new) has been
13204 				 * annotated with BPF kfunc flag
13205 				 * KF_RCU_PROTECTED and was called within a RCU
13206 				 * read-side critical section, also propagate
13207 				 * the MEM_RCU flag to the pointer returned from
13208 				 * the iterator's next function (e.g.,
13209 				 * bpf_iter_task_next).
13210 				 */
13211 				type |= MEM_RCU;
13212 			} else {
13213 				/*
13214 				 * Any PTR_TO_BTF_ID that is returned from a BPF
13215 				 * kfunc should by default be treated as
13216 				 * implicitly trusted.
13217 				 */
13218 				type |= PTR_TRUSTED;
13219 			}
13220 
13221 			mark_reg_known_zero(env, regs, BPF_REG_0);
13222 			regs[BPF_REG_0].btf = desc_btf;
13223 			regs[BPF_REG_0].type = type;
13224 			regs[BPF_REG_0].btf_id = ptr_type_id;
13225 		}
13226 
13227 		if (is_kfunc_ret_null(&meta)) {
13228 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
13229 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
13230 			regs[BPF_REG_0].id = ++env->id_gen;
13231 		}
13232 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
13233 		if (is_kfunc_acquire(&meta)) {
13234 			id = acquire_reference(env, insn_idx, 0);
13235 			if (id < 0)
13236 				return id;
13237 			regs[BPF_REG_0].id = id;
13238 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
13239 			ref_set_non_owning(env, &regs[BPF_REG_0]);
13240 		}
13241 
13242 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
13243 			regs[BPF_REG_0].id = ++env->id_gen;
13244 	} else if (btf_type_is_void(t)) {
13245 		if (meta.btf == btf_vmlinux) {
13246 			if (is_bpf_obj_drop_kfunc(meta.func_id) ||
13247 			    is_bpf_percpu_obj_drop_kfunc(meta.func_id)) {
13248 				insn_aux->kptr_struct_meta =
13249 					btf_find_struct_meta(meta.arg_btf,
13250 							     meta.arg_btf_id);
13251 			}
13252 		}
13253 	}
13254 
13255 	if (bpf_is_kfunc_pkt_changing(&meta))
13256 		clear_all_pkt_pointers(env);
13257 
13258 	nargs = btf_type_vlen(meta.func_proto);
13259 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13260 		struct bpf_func_state *caller = cur_func(env);
13261 		struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno];
13262 		u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS;
13263 		u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt;
13264 
13265 		if (stack_arg_cnt > caller_info->stack_arg_cnt)
13266 			caller_info->stack_arg_cnt = stack_arg_cnt;
13267 	}
13268 
13269 	args = (const struct btf_param *)(meta.func_proto + 1);
13270 	for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) {
13271 		u32 regno = i + 1;
13272 
13273 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
13274 		if (btf_type_is_ptr(t))
13275 			mark_btf_func_reg_size(env, regno, sizeof(void *));
13276 		else
13277 			/* scalar. ensured by check_kfunc_args() */
13278 			mark_btf_func_reg_size(env, regno, t->size);
13279 	}
13280 
13281 	if (bpf_is_iter_next_kfunc(&meta)) {
13282 		err = process_iter_next_call(env, insn_idx, &meta);
13283 		if (err)
13284 			return err;
13285 	}
13286 
13287 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
13288 		env->prog->call_session_cookie = true;
13289 
13290 	if (bpf_is_throw_kfunc(insn))
13291 		return process_bpf_exit_full(env, NULL, true);
13292 
13293 	return 0;
13294 }
13295 
13296 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env,
13297 					 const struct bpf_reg_state *reg,
13298 					 enum bpf_reg_type type)
13299 {
13300 	bool known = tnum_is_const(reg->var_off);
13301 	s64 val = reg->var_off.value;
13302 	s64 smin = reg_smin(reg);
13303 
13304 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13305 		verbose(env, "math between %s pointer and %lld is not allowed\n",
13306 			reg_type_str(env, type), val);
13307 		return false;
13308 	}
13309 
13310 	if (smin == S64_MIN) {
13311 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
13312 			reg_type_str(env, type));
13313 		return false;
13314 	}
13315 
13316 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13317 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
13318 			smin, reg_type_str(env, type));
13319 		return false;
13320 	}
13321 
13322 	return true;
13323 }
13324 
13325 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env,
13326 				      const struct bpf_reg_state *reg,
13327 				      enum bpf_reg_type type)
13328 {
13329 	bool known = tnum_is_const(reg->var_off);
13330 	s64 val = reg->var_off.value;
13331 	s64 smin = reg_smin(reg);
13332 
13333 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
13334 		verbose(env, "%s pointer offset %lld is not allowed\n",
13335 			reg_type_str(env, type), val);
13336 		return false;
13337 	}
13338 
13339 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
13340 		verbose(env, "%s pointer offset %lld is not allowed\n",
13341 			reg_type_str(env, type), smin);
13342 		return false;
13343 	}
13344 
13345 	return true;
13346 }
13347 
13348 enum {
13349 	REASON_BOUNDS	= -1,
13350 	REASON_TYPE	= -2,
13351 	REASON_PATHS	= -3,
13352 	REASON_LIMIT	= -4,
13353 	REASON_STACK	= -5,
13354 };
13355 
13356 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
13357 			      u32 *alu_limit, bool mask_to_left)
13358 {
13359 	u32 max = 0, ptr_limit = 0;
13360 
13361 	switch (ptr_reg->type) {
13362 	case PTR_TO_STACK:
13363 		/* Offset 0 is out-of-bounds, but acceptable start for the
13364 		 * left direction, see BPF_REG_FP. Also, unknown scalar
13365 		 * offset where we would need to deal with min/max bounds is
13366 		 * currently prohibited for unprivileged.
13367 		 */
13368 		max = MAX_BPF_STACK + mask_to_left;
13369 		ptr_limit = -ptr_reg->var_off.value;
13370 		break;
13371 	case PTR_TO_MAP_VALUE:
13372 		max = ptr_reg->map_ptr->value_size;
13373 		ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg);
13374 		break;
13375 	default:
13376 		return REASON_TYPE;
13377 	}
13378 
13379 	if (ptr_limit >= max)
13380 		return REASON_LIMIT;
13381 	*alu_limit = ptr_limit;
13382 	return 0;
13383 }
13384 
13385 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
13386 				    const struct bpf_insn *insn)
13387 {
13388 	return env->bypass_spec_v1 ||
13389 		BPF_SRC(insn->code) == BPF_K ||
13390 		cur_aux(env)->nospec;
13391 }
13392 
13393 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
13394 				       u32 alu_state, u32 alu_limit)
13395 {
13396 	/* If we arrived here from different branches with different
13397 	 * state or limits to sanitize, then this won't work.
13398 	 */
13399 	if (aux->alu_state &&
13400 	    (aux->alu_state != alu_state ||
13401 	     aux->alu_limit != alu_limit))
13402 		return REASON_PATHS;
13403 
13404 	/* Corresponding fixup done in do_misc_fixups(). */
13405 	aux->alu_state = alu_state;
13406 	aux->alu_limit = alu_limit;
13407 	return 0;
13408 }
13409 
13410 static int sanitize_val_alu(struct bpf_verifier_env *env,
13411 			    struct bpf_insn *insn)
13412 {
13413 	struct bpf_insn_aux_data *aux = cur_aux(env);
13414 
13415 	if (can_skip_alu_sanitation(env, insn))
13416 		return 0;
13417 
13418 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13419 }
13420 
13421 static bool sanitize_needed(u8 opcode)
13422 {
13423 	return opcode == BPF_ADD || opcode == BPF_SUB;
13424 }
13425 
13426 struct bpf_sanitize_info {
13427 	struct bpf_insn_aux_data aux;
13428 	bool mask_to_left;
13429 };
13430 
13431 static int sanitize_speculative_path(struct bpf_verifier_env *env,
13432 				     const struct bpf_insn *insn,
13433 				     u32 next_idx, u32 curr_idx)
13434 {
13435 	struct bpf_verifier_state *branch;
13436 	struct bpf_reg_state *regs;
13437 
13438 	branch = push_stack(env, next_idx, curr_idx, true);
13439 	if (!IS_ERR(branch) && insn) {
13440 		regs = branch->frame[branch->curframe]->regs;
13441 		if (BPF_SRC(insn->code) == BPF_K) {
13442 			mark_reg_unknown(env, regs, insn->dst_reg);
13443 		} else if (BPF_SRC(insn->code) == BPF_X) {
13444 			mark_reg_unknown(env, regs, insn->dst_reg);
13445 			mark_reg_unknown(env, regs, insn->src_reg);
13446 		}
13447 	}
13448 	return PTR_ERR_OR_ZERO(branch);
13449 }
13450 
13451 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13452 			    struct bpf_insn *insn,
13453 			    const struct bpf_reg_state *ptr_reg,
13454 			    const struct bpf_reg_state *off_reg,
13455 			    struct bpf_reg_state *dst_reg,
13456 			    struct bpf_sanitize_info *info,
13457 			    const bool commit_window)
13458 {
13459 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13460 	struct bpf_verifier_state *vstate = env->cur_state;
13461 	bool off_is_imm = tnum_is_const(off_reg->var_off);
13462 	bool off_is_neg = reg_smin(off_reg) < 0;
13463 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
13464 	u8 opcode = BPF_OP(insn->code);
13465 	u32 alu_state, alu_limit;
13466 	struct bpf_reg_state tmp;
13467 	int err;
13468 
13469 	if (can_skip_alu_sanitation(env, insn))
13470 		return 0;
13471 
13472 	/* We already marked aux for masking from non-speculative
13473 	 * paths, thus we got here in the first place. We only care
13474 	 * to explore bad access from here.
13475 	 */
13476 	if (vstate->speculative)
13477 		goto do_sim;
13478 
13479 	if (!commit_window) {
13480 		if (!tnum_is_const(off_reg->var_off) &&
13481 		    (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0))
13482 			return REASON_BOUNDS;
13483 
13484 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
13485 				     (opcode == BPF_SUB && !off_is_neg);
13486 	}
13487 
13488 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13489 	if (err < 0)
13490 		return err;
13491 
13492 	if (commit_window) {
13493 		/* In commit phase we narrow the masking window based on
13494 		 * the observed pointer move after the simulated operation.
13495 		 */
13496 		alu_state = info->aux.alu_state;
13497 		alu_limit = abs(info->aux.alu_limit - alu_limit);
13498 	} else {
13499 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13500 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13501 		alu_state |= ptr_is_dst_reg ?
13502 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13503 
13504 		/* Limit pruning on unknown scalars to enable deep search for
13505 		 * potential masking differences from other program paths.
13506 		 */
13507 		if (!off_is_imm)
13508 			env->explore_alu_limits = true;
13509 	}
13510 
13511 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13512 	if (err < 0)
13513 		return err;
13514 do_sim:
13515 	/* If we're in commit phase, we're done here given we already
13516 	 * pushed the truncated dst_reg into the speculative verification
13517 	 * stack.
13518 	 *
13519 	 * Also, when register is a known constant, we rewrite register-based
13520 	 * operation to immediate-based, and thus do not need masking (and as
13521 	 * a consequence, do not need to simulate the zero-truncation either).
13522 	 */
13523 	if (commit_window || off_is_imm)
13524 		return 0;
13525 
13526 	/* Simulate and find potential out-of-bounds access under
13527 	 * speculative execution from truncation as a result of
13528 	 * masking when off was not within expected range. If off
13529 	 * sits in dst, then we temporarily need to move ptr there
13530 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13531 	 * for cases where we use K-based arithmetic in one direction
13532 	 * and truncated reg-based in the other in order to explore
13533 	 * bad access.
13534 	 */
13535 	if (!ptr_is_dst_reg) {
13536 		tmp = *dst_reg;
13537 		*dst_reg = *ptr_reg;
13538 	}
13539 	err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
13540 	if (err < 0)
13541 		return REASON_STACK;
13542 	if (!ptr_is_dst_reg)
13543 		*dst_reg = tmp;
13544 	return 0;
13545 }
13546 
13547 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13548 {
13549 	struct bpf_verifier_state *vstate = env->cur_state;
13550 
13551 	/* If we simulate paths under speculation, we don't update the
13552 	 * insn as 'seen' such that when we verify unreachable paths in
13553 	 * the non-speculative domain, sanitize_dead_code() can still
13554 	 * rewrite/sanitize them.
13555 	 */
13556 	if (!vstate->speculative)
13557 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13558 }
13559 
13560 static int sanitize_err(struct bpf_verifier_env *env,
13561 			const struct bpf_insn *insn, int reason,
13562 			const struct bpf_reg_state *off_reg,
13563 			const struct bpf_reg_state *dst_reg)
13564 {
13565 	static const char *err = "pointer arithmetic with it prohibited for !root";
13566 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13567 	u32 dst = insn->dst_reg, src = insn->src_reg;
13568 
13569 	switch (reason) {
13570 	case REASON_BOUNDS:
13571 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13572 			off_reg == dst_reg ? dst : src, err);
13573 		break;
13574 	case REASON_TYPE:
13575 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13576 			off_reg == dst_reg ? src : dst, err);
13577 		break;
13578 	case REASON_PATHS:
13579 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13580 			dst, op, err);
13581 		break;
13582 	case REASON_LIMIT:
13583 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13584 			dst, op, err);
13585 		break;
13586 	case REASON_STACK:
13587 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13588 			dst, err);
13589 		return -ENOMEM;
13590 	default:
13591 		verifier_bug(env, "unknown reason (%d)", reason);
13592 		break;
13593 	}
13594 
13595 	return -EACCES;
13596 }
13597 
13598 /* check that stack access falls within stack limits and that 'reg' doesn't
13599  * have a variable offset.
13600  *
13601  * Variable offset is prohibited for unprivileged mode for simplicity since it
13602  * requires corresponding support in Spectre masking for stack ALU.  See also
13603  * retrieve_ptr_limit().
13604  */
13605 static int check_stack_access_for_ptr_arithmetic(
13606 				struct bpf_verifier_env *env,
13607 				int regno,
13608 				const struct bpf_reg_state *reg,
13609 				int off)
13610 {
13611 	if (!tnum_is_const(reg->var_off)) {
13612 		char tn_buf[48];
13613 
13614 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13615 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13616 			regno, tn_buf, off);
13617 		return -EACCES;
13618 	}
13619 
13620 	if (off >= 0 || off < -MAX_BPF_STACK) {
13621 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13622 			"prohibited for !root; off=%d\n", regno, off);
13623 		return -EACCES;
13624 	}
13625 
13626 	return 0;
13627 }
13628 
13629 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13630 				 const struct bpf_insn *insn,
13631 				 struct bpf_reg_state *dst_reg)
13632 {
13633 	u32 dst = insn->dst_reg;
13634 
13635 	/* For unprivileged we require that resulting offset must be in bounds
13636 	 * in order to be able to sanitize access later on.
13637 	 */
13638 	if (env->bypass_spec_v1)
13639 		return 0;
13640 
13641 	switch (dst_reg->type) {
13642 	case PTR_TO_STACK:
13643 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13644 							  dst_reg->var_off.value))
13645 			return -EACCES;
13646 		break;
13647 	case PTR_TO_MAP_VALUE:
13648 		if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) {
13649 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13650 				"prohibited for !root\n", dst);
13651 			return -EACCES;
13652 		}
13653 		break;
13654 	default:
13655 		return -EOPNOTSUPP;
13656 	}
13657 
13658 	return 0;
13659 }
13660 
13661 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13662  * Caller should also handle BPF_MOV case separately.
13663  * If we return -EACCES, caller may want to try again treating pointer as a
13664  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13665  */
13666 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13667 				   struct bpf_insn *insn,
13668 				   const struct bpf_reg_state *ptr_reg,
13669 				   const struct bpf_reg_state *off_reg)
13670 {
13671 	struct bpf_verifier_state *vstate = env->cur_state;
13672 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13673 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13674 	bool known = tnum_is_const(off_reg->var_off);
13675 	s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg);
13676 	u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg);
13677 	struct bpf_sanitize_info info = {};
13678 	u8 opcode = BPF_OP(insn->code);
13679 	u32 dst = insn->dst_reg;
13680 	int ret, bounds_ret;
13681 
13682 	dst_reg = &regs[dst];
13683 
13684 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13685 	    smin_val > smax_val || umin_val > umax_val) {
13686 		/* Taint dst register if offset had invalid bounds derived from
13687 		 * e.g. dead branches.
13688 		 */
13689 		__mark_reg_unknown(env, dst_reg);
13690 		return 0;
13691 	}
13692 
13693 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13694 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13695 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13696 			__mark_reg_unknown(env, dst_reg);
13697 			return 0;
13698 		}
13699 
13700 		verbose(env,
13701 			"R%d 32-bit pointer arithmetic prohibited\n",
13702 			dst);
13703 		return -EACCES;
13704 	}
13705 
13706 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13707 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13708 			dst, reg_type_str(env, ptr_reg->type));
13709 		return -EACCES;
13710 	}
13711 
13712 	/*
13713 	 * Accesses to untrusted PTR_TO_MEM are done through probe
13714 	 * instructions, hence no need to track offsets.
13715 	 */
13716 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
13717 		return 0;
13718 
13719 	switch (base_type(ptr_reg->type)) {
13720 	case PTR_TO_CTX:
13721 	case PTR_TO_MAP_VALUE:
13722 	case PTR_TO_MAP_KEY:
13723 	case PTR_TO_STACK:
13724 	case PTR_TO_PACKET_META:
13725 	case PTR_TO_PACKET:
13726 	case PTR_TO_TP_BUFFER:
13727 	case PTR_TO_BTF_ID:
13728 	case PTR_TO_MEM:
13729 	case PTR_TO_BUF:
13730 	case PTR_TO_FUNC:
13731 	case CONST_PTR_TO_DYNPTR:
13732 		break;
13733 	case PTR_TO_FLOW_KEYS:
13734 		if (known)
13735 			break;
13736 		fallthrough;
13737 	case CONST_PTR_TO_MAP:
13738 		/* smin_val represents the known value */
13739 		if (known && smin_val == 0 && opcode == BPF_ADD)
13740 			break;
13741 		fallthrough;
13742 	default:
13743 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13744 			dst, reg_type_str(env, ptr_reg->type));
13745 		return -EACCES;
13746 	}
13747 
13748 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13749 	 * The id may be overwritten later if we create a new variable offset.
13750 	 */
13751 	dst_reg->type = ptr_reg->type;
13752 	dst_reg->id = ptr_reg->id;
13753 
13754 	if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) ||
13755 	    !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type))
13756 		return -EINVAL;
13757 
13758 	/* pointer types do not carry 32-bit bounds at the moment. */
13759 	__mark_reg32_unbounded(dst_reg);
13760 
13761 	if (sanitize_needed(opcode)) {
13762 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13763 				       &info, false);
13764 		if (ret < 0)
13765 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13766 	}
13767 
13768 	switch (opcode) {
13769 	case BPF_ADD:
13770 		/*
13771 		 * dst_reg gets the pointer type and since some positive
13772 		 * integer value was added to the pointer, give it a new 'id'
13773 		 * if it's a PTR_TO_PACKET.
13774 		 * this creates a new 'base' pointer, off_reg (variable) gets
13775 		 * added into the variable offset, and we copy the fixed offset
13776 		 * from ptr_reg.
13777 		 */
13778 		dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
13779 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13780 		dst_reg->raw = ptr_reg->raw;
13781 		if (reg_is_pkt_pointer(ptr_reg)) {
13782 			if (!known)
13783 				dst_reg->id = ++env->id_gen;
13784 			/*
13785 			 * Clear range for unknown addends since we can't know
13786 			 * where the pkt pointer ended up. Also clear AT_PKT_END /
13787 			 * BEYOND_PKT_END from prior comparison as any pointer
13788 			 * arithmetic invalidates them.
13789 			 */
13790 			if (!known || dst_reg->range < 0)
13791 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13792 		}
13793 		break;
13794 	case BPF_SUB:
13795 		if (dst_reg == off_reg) {
13796 			/* scalar -= pointer.  Creates an unknown scalar */
13797 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13798 				dst);
13799 			return -EACCES;
13800 		}
13801 		/* We don't allow subtraction from FP, because (according to
13802 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13803 		 * be able to deal with it.
13804 		 */
13805 		if (ptr_reg->type == PTR_TO_STACK) {
13806 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13807 				dst);
13808 			return -EACCES;
13809 		}
13810 		dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64));
13811 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13812 		dst_reg->raw = ptr_reg->raw;
13813 		if (reg_is_pkt_pointer(ptr_reg)) {
13814 			if (!known)
13815 				dst_reg->id = ++env->id_gen;
13816 			/*
13817 			 * Clear range if the subtrahend may be negative since
13818 			 * pkt pointer could move past its bounds. A positive
13819 			 * subtrahend moves it backwards keeping positive range
13820 			 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from
13821 			 * prior comparison as arithmetic invalidates them.
13822 			 */
13823 			if ((!known && smin_val < 0) || dst_reg->range < 0)
13824 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13825 		}
13826 		break;
13827 	case BPF_AND:
13828 	case BPF_OR:
13829 	case BPF_XOR:
13830 		/* bitwise ops on pointers are troublesome, prohibit. */
13831 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13832 			dst, bpf_alu_string[opcode >> 4]);
13833 		return -EACCES;
13834 	default:
13835 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13836 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13837 			dst, bpf_alu_string[opcode >> 4]);
13838 		return -EACCES;
13839 	}
13840 
13841 	if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type))
13842 		return -EINVAL;
13843 	reg_bounds_sync(dst_reg);
13844 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
13845 	if (bounds_ret == -EACCES)
13846 		return bounds_ret;
13847 	if (sanitize_needed(opcode)) {
13848 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13849 				       &info, true);
13850 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
13851 				    && !env->cur_state->speculative
13852 				    && bounds_ret
13853 				    && !ret,
13854 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
13855 			return -EFAULT;
13856 		}
13857 		if (ret < 0)
13858 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13859 	}
13860 
13861 	return 0;
13862 }
13863 
13864 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13865 				 struct bpf_reg_state *src_reg)
13866 {
13867 	dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32);
13868 }
13869 
13870 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13871 			       struct bpf_reg_state *src_reg)
13872 {
13873 	dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64);
13874 }
13875 
13876 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13877 				 struct bpf_reg_state *src_reg)
13878 {
13879 	dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32));
13880 }
13881 
13882 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13883 			       struct bpf_reg_state *src_reg)
13884 {
13885 	dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64));
13886 }
13887 
13888 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13889 				 struct bpf_reg_state *src_reg)
13890 {
13891 	s32 smin = reg_s32_min(dst_reg);
13892 	s32 smax = reg_s32_max(dst_reg);
13893 	u32 umin = reg_u32_min(dst_reg);
13894 	u32 umax = reg_u32_max(dst_reg);
13895 	s32 tmp_prod[4];
13896 
13897 	if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) ||
13898 	    check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) {
13899 		/* Overflow possible, we know nothing */
13900 		umin = 0;
13901 		umax = U32_MAX;
13902 	}
13903 	if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) ||
13904 	    check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) ||
13905 	    check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) ||
13906 	    check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) {
13907 		/* Overflow possible, we know nothing */
13908 		smin = S32_MIN;
13909 		smax = S32_MAX;
13910 	} else {
13911 		smin = min_array(tmp_prod, 4);
13912 		smax = max_array(tmp_prod, 4);
13913 	}
13914 
13915 	dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax),
13916 					cnum32_from_srange(smin, smax));
13917 }
13918 
13919 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13920 			       struct bpf_reg_state *src_reg)
13921 {
13922 	s64 smin = reg_smin(dst_reg);
13923 	s64 smax = reg_smax(dst_reg);
13924 	u64 umin = reg_umin(dst_reg);
13925 	u64 umax = reg_umax(dst_reg);
13926 	s64 tmp_prod[4];
13927 
13928 	if (check_mul_overflow(umax, reg_umax(src_reg), &umax) ||
13929 	    check_mul_overflow(umin, reg_umin(src_reg), &umin)) {
13930 		/* Overflow possible, we know nothing */
13931 		umin = 0;
13932 		umax = U64_MAX;
13933 	}
13934 	if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) ||
13935 	    check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) ||
13936 	    check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) ||
13937 	    check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) {
13938 		/* Overflow possible, we know nothing */
13939 		smin = S64_MIN;
13940 		smax = S64_MAX;
13941 	} else {
13942 		smin = min_array(tmp_prod, 4);
13943 		smax = max_array(tmp_prod, 4);
13944 	}
13945 
13946 	dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax),
13947 					cnum64_from_srange(smin, smax));
13948 }
13949 
13950 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg,
13951 				  struct bpf_reg_state *src_reg)
13952 {
13953 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
13954 
13955 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val,
13956 			 reg_u32_max(dst_reg) / src_val);
13957 
13958 	/* Reset other ranges/tnum to unbounded/unknown. */
13959 	reset_reg64_and_tnum(dst_reg);
13960 }
13961 
13962 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg,
13963 				struct bpf_reg_state *src_reg)
13964 {
13965 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
13966 
13967 	reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val),
13968 			 div64_u64(reg_umax(dst_reg), src_val));
13969 
13970 	/* Reset other ranges/tnum to unbounded/unknown. */
13971 	reset_reg32_and_tnum(dst_reg);
13972 }
13973 
13974 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg,
13975 				  struct bpf_reg_state *src_reg)
13976 {
13977 	s32 smin = reg_s32_min(dst_reg);
13978 	s32 smax = reg_s32_max(dst_reg);
13979 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
13980 	s32 res1, res2;
13981 
13982 	/* BPF div specification: S32_MIN / -1 = S32_MIN */
13983 	if (smin == S32_MIN && src_val == -1) {
13984 		/*
13985 		 * If the dividend range contains more than just S32_MIN,
13986 		 * we cannot precisely track the result, so it becomes unbounded.
13987 		 * e.g., [S32_MIN, S32_MIN+10]/(-1),
13988 		 *     = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)]
13989 		 *     = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX]
13990 		 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN.
13991 		 */
13992 		if (smax != S32_MIN) {
13993 			smin = S32_MIN;
13994 			smax = S32_MAX;
13995 		}
13996 		goto reset;
13997 	}
13998 
13999 	res1 = smin / src_val;
14000 	res2 = smax / src_val;
14001 	smin = min(res1, res2);
14002 	smax = max(res1, res2);
14003 
14004 reset:
14005 	reg_set_srange32(dst_reg, smin, smax);
14006 	/* Reset other ranges/tnum to unbounded/unknown. */
14007 	reset_reg64_and_tnum(dst_reg);
14008 }
14009 
14010 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg,
14011 				struct bpf_reg_state *src_reg)
14012 {
14013 	s64 smin = reg_smin(dst_reg);
14014 	s64 smax = reg_smax(dst_reg);
14015 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
14016 	s64 res1, res2;
14017 
14018 	/* BPF div specification: S64_MIN / -1 = S64_MIN */
14019 	if (smin == S64_MIN && src_val == -1) {
14020 		/*
14021 		 * If the dividend range contains more than just S64_MIN,
14022 		 * we cannot precisely track the result, so it becomes unbounded.
14023 		 * e.g., [S64_MIN, S64_MIN+10]/(-1),
14024 		 *     = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)]
14025 		 *     = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX]
14026 		 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN.
14027 		 */
14028 		if (smax != S64_MIN) {
14029 			smin = S64_MIN;
14030 			smax = S64_MAX;
14031 		}
14032 		goto reset;
14033 	}
14034 
14035 	res1 = div64_s64(smin, src_val);
14036 	res2 = div64_s64(smax, src_val);
14037 	smin = min(res1, res2);
14038 	smax = max(res1, res2);
14039 
14040 reset:
14041 	reg_set_srange64(dst_reg, smin, smax);
14042 	/* Reset other ranges/tnum to unbounded/unknown. */
14043 	reset_reg32_and_tnum(dst_reg);
14044 }
14045 
14046 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg,
14047 				  struct bpf_reg_state *src_reg)
14048 {
14049 	u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */
14050 	u32 res_max = src_val - 1;
14051 
14052 	/*
14053 	 * If dst_umax <= res_max, the result remains unchanged.
14054 	 * e.g., [2, 5] % 10 = [2, 5].
14055 	 */
14056 	if (reg_u32_max(dst_reg) <= res_max)
14057 		return;
14058 
14059 	reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max));
14060 
14061 	/* Reset other ranges/tnum to unbounded/unknown. */
14062 	reset_reg64_and_tnum(dst_reg);
14063 }
14064 
14065 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg,
14066 				struct bpf_reg_state *src_reg)
14067 {
14068 	u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */
14069 	u64 res_max = src_val - 1;
14070 
14071 	/*
14072 	 * If dst_umax <= res_max, the result remains unchanged.
14073 	 * e.g., [2, 5] % 10 = [2, 5].
14074 	 */
14075 	if (reg_umax(dst_reg) <= res_max)
14076 		return;
14077 
14078 	reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max));
14079 
14080 	/* Reset other ranges/tnum to unbounded/unknown. */
14081 	reset_reg32_and_tnum(dst_reg);
14082 }
14083 
14084 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg,
14085 				  struct bpf_reg_state *src_reg)
14086 {
14087 	s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */
14088 
14089 	/*
14090 	 * Safe absolute value calculation:
14091 	 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648.
14092 	 * Here use unsigned integer to avoid overflow.
14093 	 */
14094 	u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val;
14095 
14096 	/*
14097 	 * Calculate the maximum possible absolute value of the result.
14098 	 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives
14099 	 * 2147483647 (S32_MAX), which fits perfectly in s32.
14100 	 */
14101 	s32 res_max_abs = src_abs - 1;
14102 
14103 	/*
14104 	 * If the dividend is already within the result range,
14105 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
14106 	 */
14107 	if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs)
14108 		return;
14109 
14110 	/* General case: result has the same sign as the dividend. */
14111 	if (reg_s32_min(dst_reg) >= 0) {
14112 		reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs));
14113 	} else if (reg_s32_max(dst_reg) <= 0) {
14114 		reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0);
14115 	} else {
14116 		reg_set_srange32(dst_reg, -res_max_abs, res_max_abs);
14117 	}
14118 
14119 	/* Reset other ranges/tnum to unbounded/unknown. */
14120 	reset_reg64_and_tnum(dst_reg);
14121 }
14122 
14123 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg,
14124 				struct bpf_reg_state *src_reg)
14125 {
14126 	s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */
14127 
14128 	/*
14129 	 * Safe absolute value calculation:
14130 	 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63.
14131 	 * Here use unsigned integer to avoid overflow.
14132 	 */
14133 	u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val;
14134 
14135 	/*
14136 	 * Calculate the maximum possible absolute value of the result.
14137 	 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives
14138 	 * 2^63 - 1 (S64_MAX), which fits perfectly in s64.
14139 	 */
14140 	s64 res_max_abs = src_abs - 1;
14141 
14142 	/*
14143 	 * If the dividend is already within the result range,
14144 	 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5].
14145 	 */
14146 	if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs)
14147 		return;
14148 
14149 	/* General case: result has the same sign as the dividend. */
14150 	if (reg_smin(dst_reg) >= 0) {
14151 		reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs));
14152 	} else if (reg_smax(dst_reg) <= 0) {
14153 		reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0);
14154 	} else {
14155 		reg_set_srange64(dst_reg, -res_max_abs, res_max_abs);
14156 	}
14157 
14158 	/* Reset other ranges/tnum to unbounded/unknown. */
14159 	reset_reg32_and_tnum(dst_reg);
14160 }
14161 
14162 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14163 				 struct bpf_reg_state *src_reg)
14164 {
14165 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14166 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14167 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14168 	u32 umax_val = reg_u32_max(src_reg);
14169 
14170 	if (src_known && dst_known) {
14171 		__mark_reg32_known(dst_reg, var32_off.value);
14172 		return;
14173 	}
14174 
14175 	/* We get our minimum from the var_off, since that's inherently
14176 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14177 	 */
14178 	reg_set_urange32(dst_reg,
14179 			 var32_off.value,
14180 			 min(reg_u32_max(dst_reg), umax_val));
14181 }
14182 
14183 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14184 			       struct bpf_reg_state *src_reg)
14185 {
14186 	bool src_known = tnum_is_const(src_reg->var_off);
14187 	bool dst_known = tnum_is_const(dst_reg->var_off);
14188 	u64 umax_val = reg_umax(src_reg);
14189 
14190 	if (src_known && dst_known) {
14191 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14192 		return;
14193 	}
14194 
14195 	/* We get our minimum from the var_off, since that's inherently
14196 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14197 	 */
14198 	reg_set_urange64(dst_reg,
14199 			 dst_reg->var_off.value,
14200 			 min(reg_umax(dst_reg), umax_val));
14201 
14202 	/* We may learn something more from the var_off */
14203 	__update_reg_bounds(dst_reg);
14204 }
14205 
14206 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14207 				struct bpf_reg_state *src_reg)
14208 {
14209 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14210 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14211 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14212 	u32 umin_val = reg_u32_min(src_reg);
14213 
14214 	if (src_known && dst_known) {
14215 		__mark_reg32_known(dst_reg, var32_off.value);
14216 		return;
14217 	}
14218 
14219 	/* We get our maximum from the var_off, and our minimum is the
14220 	 * maximum of the operands' minima
14221 	 */
14222 	reg_set_urange32(dst_reg,
14223 			 max(reg_u32_min(dst_reg), umin_val),
14224 			 var32_off.value | var32_off.mask);
14225 }
14226 
14227 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14228 			      struct bpf_reg_state *src_reg)
14229 {
14230 	bool src_known = tnum_is_const(src_reg->var_off);
14231 	bool dst_known = tnum_is_const(dst_reg->var_off);
14232 	u64 umin_val = reg_umin(src_reg);
14233 
14234 	if (src_known && dst_known) {
14235 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14236 		return;
14237 	}
14238 
14239 	/* We get our maximum from the var_off, and our minimum is the
14240 	 * maximum of the operands' minima
14241 	 */
14242 	reg_set_urange64(dst_reg,
14243 			 max(reg_umin(dst_reg), umin_val),
14244 			 dst_reg->var_off.value | dst_reg->var_off.mask);
14245 
14246 	/* We may learn something more from the var_off */
14247 	__update_reg_bounds(dst_reg);
14248 }
14249 
14250 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
14251 				 struct bpf_reg_state *src_reg)
14252 {
14253 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14254 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14255 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14256 
14257 	if (src_known && dst_known) {
14258 		__mark_reg32_known(dst_reg, var32_off.value);
14259 		return;
14260 	}
14261 
14262 	/* We get both minimum and maximum from the var32_off. */
14263 	reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask);
14264 }
14265 
14266 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
14267 			       struct bpf_reg_state *src_reg)
14268 {
14269 	bool src_known = tnum_is_const(src_reg->var_off);
14270 	bool dst_known = tnum_is_const(dst_reg->var_off);
14271 
14272 	if (src_known && dst_known) {
14273 		/* dst_reg->var_off.value has been updated earlier */
14274 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14275 		return;
14276 	}
14277 
14278 	/* We get both minimum and maximum from the var_off. */
14279 	reg_set_urange64(dst_reg,
14280 			 dst_reg->var_off.value,
14281 			 dst_reg->var_off.value | dst_reg->var_off.mask);
14282 }
14283 
14284 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14285 				   u64 umin_val, u64 umax_val)
14286 {
14287 	/* If we might shift our top bit out, then we know nothing */
14288 	if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val))
14289 		reg_set_urange32(dst_reg, 0, U32_MAX);
14290 	else
14291 		/* We lose all sign bit information (except what we can pick
14292 		 * up from var_off)
14293 		 */
14294 		reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val,
14295 				 reg_u32_max(dst_reg) << umax_val);
14296 }
14297 
14298 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
14299 				 struct bpf_reg_state *src_reg)
14300 {
14301 	u32 umax_val = reg_u32_max(src_reg);
14302 	u32 umin_val = reg_u32_min(src_reg);
14303 	/* u32 alu operation will zext upper bits */
14304 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14305 
14306 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14307 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
14308 	/* Not required but being careful mark reg64 bounds as unknown so
14309 	 * that we are forced to pick them up from tnum and zext later and
14310 	 * if some path skips this step we are still safe.
14311 	 */
14312 	__mark_reg64_unbounded(dst_reg);
14313 	__update_reg32_bounds(dst_reg);
14314 }
14315 
14316 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
14317 				   u64 umin_val, u64 umax_val)
14318 {
14319 	struct cnum64 u, s;
14320 
14321 	/* Special case <<32 because it is a common compiler pattern to sign
14322 	 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct
14323 	 * because s32 bounds don't flip sign when shifting to the left by
14324 	 * 32bits.
14325 	 */
14326 	if (umin_val == 32 && umax_val == 32)
14327 		s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32,
14328 				       (s64)reg_s32_max(dst_reg) << 32);
14329 	else
14330 		s = CNUM64_UNBOUNDED;
14331 
14332 	/* If we might shift our top bit out, then we know nothing */
14333 	if (reg_umax(dst_reg) > 1ULL << (63 - umax_val))
14334 		u = CNUM64_UNBOUNDED;
14335 	else
14336 		u = cnum64_from_urange(reg_umin(dst_reg) << umin_val,
14337 				       reg_umax(dst_reg) << umax_val);
14338 
14339 	dst_reg->r64 = cnum64_intersect(u, s);
14340 }
14341 
14342 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
14343 			       struct bpf_reg_state *src_reg)
14344 {
14345 	u64 umax_val = reg_umax(src_reg);
14346 	u64 umin_val = reg_umin(src_reg);
14347 
14348 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
14349 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
14350 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
14351 
14352 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
14353 	/* We may learn something more from the var_off */
14354 	__update_reg_bounds(dst_reg);
14355 }
14356 
14357 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
14358 				 struct bpf_reg_state *src_reg)
14359 {
14360 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
14361 	u32 umax_val = reg_u32_max(src_reg);
14362 	u32 umin_val = reg_u32_min(src_reg);
14363 
14364 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14365 	 * be negative, then either:
14366 	 * 1) src_reg might be zero, so the sign bit of the result is
14367 	 *    unknown, so we lose our signed bounds
14368 	 * 2) it's known negative, thus the unsigned bounds capture the
14369 	 *    signed bounds
14370 	 * 3) the signed bounds cross zero, so they tell us nothing
14371 	 *    about the result
14372 	 * If the value in dst_reg is known nonnegative, then again the
14373 	 * unsigned bounds capture the signed bounds.
14374 	 * Thus, in all cases it suffices to blow away our signed bounds
14375 	 * and rely on inferring new ones from the unsigned bounds and
14376 	 * var_off of the result.
14377 	 */
14378 
14379 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
14380 	reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val,
14381 			 reg_u32_max(dst_reg) >> umin_val);
14382 
14383 	__mark_reg64_unbounded(dst_reg);
14384 	__update_reg32_bounds(dst_reg);
14385 }
14386 
14387 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
14388 			       struct bpf_reg_state *src_reg)
14389 {
14390 	u64 umax_val = reg_umax(src_reg);
14391 	u64 umin_val = reg_umin(src_reg);
14392 
14393 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
14394 	 * be negative, then either:
14395 	 * 1) src_reg might be zero, so the sign bit of the result is
14396 	 *    unknown, so we lose our signed bounds
14397 	 * 2) it's known negative, thus the unsigned bounds capture the
14398 	 *    signed bounds
14399 	 * 3) the signed bounds cross zero, so they tell us nothing
14400 	 *    about the result
14401 	 * If the value in dst_reg is known nonnegative, then again the
14402 	 * unsigned bounds capture the signed bounds.
14403 	 * Thus, in all cases it suffices to blow away our signed bounds
14404 	 * and rely on inferring new ones from the unsigned bounds and
14405 	 * var_off of the result.
14406 	 */
14407 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
14408 	reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val,
14409 			 reg_umax(dst_reg) >> umin_val);
14410 
14411 	/* Its not easy to operate on alu32 bounds here because it depends
14412 	 * on bits being shifted in. Take easy way out and mark unbounded
14413 	 * so we can recalculate later from tnum.
14414 	 */
14415 	__mark_reg32_unbounded(dst_reg);
14416 	__update_reg_bounds(dst_reg);
14417 }
14418 
14419 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
14420 				  struct bpf_reg_state *src_reg)
14421 {
14422 	u64 umin_val = reg_u32_min(src_reg);
14423 
14424 	/* Upon reaching here, src_known is true and
14425 	 * umax_val is equal to umin_val.
14426 	 * Blow away the dst_reg umin_value/umax_value and rely on
14427 	 * dst_reg var_off to refine the result.
14428 	 */
14429 	reg_set_srange32(dst_reg,
14430 			 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val),
14431 			 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val));
14432 
14433 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
14434 
14435 	__mark_reg64_unbounded(dst_reg);
14436 	__update_reg32_bounds(dst_reg);
14437 }
14438 
14439 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14440 				struct bpf_reg_state *src_reg)
14441 {
14442 	u64 umin_val = reg_umin(src_reg);
14443 
14444 	/* Upon reaching here, src_known is true and umax_val is equal
14445 	 * to umin_val.
14446 	 */
14447 	reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val,
14448 			 reg_smax(dst_reg) >> umin_val);
14449 
14450 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14451 
14452 	/* Its not easy to operate on alu32 bounds here because it depends
14453 	 * on bits being shifted in from upper 32-bits. Take easy way out
14454 	 * and mark unbounded so we can recalculate later from tnum.
14455 	 */
14456 	__mark_reg32_unbounded(dst_reg);
14457 	__update_reg_bounds(dst_reg);
14458 }
14459 
14460 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn)
14461 {
14462 	/*
14463 	 * Byte swap operation - update var_off using tnum_bswap.
14464 	 * Three cases:
14465 	 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE)
14466 	 *    unconditional swap
14467 	 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE)
14468 	 *    swap on big-endian, truncation or no-op on little-endian
14469 	 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE)
14470 	 *    swap on little-endian, truncation or no-op on big-endian
14471 	 */
14472 
14473 	bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64;
14474 	bool to_le = BPF_SRC(insn->code) == BPF_TO_LE;
14475 	bool is_big_endian;
14476 #ifdef CONFIG_CPU_BIG_ENDIAN
14477 	is_big_endian = true;
14478 #else
14479 	is_big_endian = false;
14480 #endif
14481 	/* Apply bswap if alu64 or switch between big-endian and little-endian machines */
14482 	bool need_bswap = alu64 || (to_le == is_big_endian);
14483 
14484 	/*
14485 	 * If the register is mutated, manually reset its scalar ID to break
14486 	 * any existing ties and avoid incorrect bounds propagation.
14487 	 */
14488 	if (need_bswap || insn->imm == 16 || insn->imm == 32)
14489 		clear_scalar_id(dst_reg);
14490 
14491 	if (need_bswap) {
14492 		if (insn->imm == 16)
14493 			dst_reg->var_off = tnum_bswap16(dst_reg->var_off);
14494 		else if (insn->imm == 32)
14495 			dst_reg->var_off = tnum_bswap32(dst_reg->var_off);
14496 		else if (insn->imm == 64)
14497 			dst_reg->var_off = tnum_bswap64(dst_reg->var_off);
14498 		/*
14499 		 * Byteswap scrambles the range, so we must reset bounds.
14500 		 * Bounds will be re-derived from the new tnum later.
14501 		 */
14502 		__mark_reg_unbounded(dst_reg);
14503 	}
14504 	/* For bswap16/32, truncate dst register to match the swapped size */
14505 	if (insn->imm == 16 || insn->imm == 32)
14506 		coerce_reg_to_size(dst_reg, insn->imm / 8);
14507 }
14508 
14509 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14510 					     const struct bpf_reg_state *src_reg)
14511 {
14512 	bool src_is_const = false;
14513 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14514 
14515 	if (insn_bitness == 32) {
14516 		if (tnum_subreg_is_const(src_reg->var_off)
14517 		    && reg_s32_min(src_reg) == reg_s32_max(src_reg)
14518 		    && reg_u32_min(src_reg) == reg_u32_max(src_reg))
14519 			src_is_const = true;
14520 	} else {
14521 		if (tnum_is_const(src_reg->var_off)
14522 		    && reg_smin(src_reg) == reg_smax(src_reg)
14523 		    && reg_umin(src_reg) == reg_umax(src_reg))
14524 			src_is_const = true;
14525 	}
14526 
14527 	switch (BPF_OP(insn->code)) {
14528 	case BPF_ADD:
14529 	case BPF_SUB:
14530 	case BPF_NEG:
14531 	case BPF_AND:
14532 	case BPF_XOR:
14533 	case BPF_OR:
14534 	case BPF_MUL:
14535 	case BPF_END:
14536 		return true;
14537 
14538 	/*
14539 	 * Division and modulo operators range is only safe to compute when the
14540 	 * divisor is a constant.
14541 	 */
14542 	case BPF_DIV:
14543 	case BPF_MOD:
14544 		return src_is_const;
14545 
14546 	/* Shift operators range is only computable if shift dimension operand
14547 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
14548 	 * includes shifts by a negative number.
14549 	 */
14550 	case BPF_LSH:
14551 	case BPF_RSH:
14552 	case BPF_ARSH:
14553 		return (src_is_const && reg_umax(src_reg) < insn_bitness);
14554 	default:
14555 		return false;
14556 	}
14557 }
14558 
14559 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn,
14560 			      struct bpf_reg_state *dst_reg)
14561 {
14562 	struct bpf_verifier_state *branch;
14563 	struct bpf_reg_state *regs;
14564 	bool alu32;
14565 
14566 	if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0)
14567 		alu32 = false;
14568 	else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0)
14569 		alu32 = true;
14570 	else
14571 		return 0;
14572 
14573 	branch = push_stack(env, env->insn_idx, env->insn_idx, false);
14574 	if (IS_ERR(branch))
14575 		return PTR_ERR(branch);
14576 
14577 	regs = branch->frame[branch->curframe]->regs;
14578 	if (alu32) {
14579 		__mark_reg32_known(&regs[insn->dst_reg], 0);
14580 		__mark_reg32_known(dst_reg, -1ull);
14581 	} else {
14582 		__mark_reg_known(&regs[insn->dst_reg], 0);
14583 		__mark_reg_known(dst_reg, -1ull);
14584 	}
14585 	return 0;
14586 }
14587 
14588 /* WARNING: This function does calculations on 64-bit values, but the actual
14589  * execution may occur on 32-bit values. Therefore, things like bitshifts
14590  * need extra checks in the 32-bit case.
14591  */
14592 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14593 				      struct bpf_insn *insn,
14594 				      struct bpf_reg_state *dst_reg,
14595 				      struct bpf_reg_state src_reg)
14596 {
14597 	u8 opcode = BPF_OP(insn->code);
14598 	s16 off = insn->off;
14599 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14600 	int ret;
14601 
14602 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14603 		__mark_reg_unknown(env, dst_reg);
14604 		return 0;
14605 	}
14606 
14607 	if (sanitize_needed(opcode)) {
14608 		ret = sanitize_val_alu(env, insn);
14609 		if (ret < 0)
14610 			return sanitize_err(env, insn, ret, NULL, NULL);
14611 	}
14612 
14613 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14614 	 * There are two classes of instructions: The first class we track both
14615 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
14616 	 * greatest amount of precision when alu operations are mixed with jmp32
14617 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14618 	 * and BPF_OR. This is possible because these ops have fairly easy to
14619 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14620 	 * See alu32 verifier tests for examples. The second class of
14621 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14622 	 * with regards to tracking sign/unsigned bounds because the bits may
14623 	 * cross subreg boundaries in the alu64 case. When this happens we mark
14624 	 * the reg unbounded in the subreg bound space and use the resulting
14625 	 * tnum to calculate an approximation of the sign/unsigned bounds.
14626 	 */
14627 	switch (opcode) {
14628 	case BPF_ADD:
14629 		scalar32_min_max_add(dst_reg, &src_reg);
14630 		scalar_min_max_add(dst_reg, &src_reg);
14631 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14632 		break;
14633 	case BPF_SUB:
14634 		scalar32_min_max_sub(dst_reg, &src_reg);
14635 		scalar_min_max_sub(dst_reg, &src_reg);
14636 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14637 		break;
14638 	case BPF_NEG:
14639 		env->fake_reg[0] = *dst_reg;
14640 		__mark_reg_known(dst_reg, 0);
14641 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
14642 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
14643 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
14644 		break;
14645 	case BPF_MUL:
14646 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14647 		scalar32_min_max_mul(dst_reg, &src_reg);
14648 		scalar_min_max_mul(dst_reg, &src_reg);
14649 		break;
14650 	case BPF_DIV:
14651 		/* BPF div specification: x / 0 = 0 */
14652 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) {
14653 			___mark_reg_known(dst_reg, 0);
14654 			break;
14655 		}
14656 		if (alu32)
14657 			if (off == 1)
14658 				scalar32_min_max_sdiv(dst_reg, &src_reg);
14659 			else
14660 				scalar32_min_max_udiv(dst_reg, &src_reg);
14661 		else
14662 			if (off == 1)
14663 				scalar_min_max_sdiv(dst_reg, &src_reg);
14664 			else
14665 				scalar_min_max_udiv(dst_reg, &src_reg);
14666 		break;
14667 	case BPF_MOD:
14668 		/* BPF mod specification: x % 0 = x */
14669 		if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0))
14670 			break;
14671 		if (alu32)
14672 			if (off == 1)
14673 				scalar32_min_max_smod(dst_reg, &src_reg);
14674 			else
14675 				scalar32_min_max_umod(dst_reg, &src_reg);
14676 		else
14677 			if (off == 1)
14678 				scalar_min_max_smod(dst_reg, &src_reg);
14679 			else
14680 				scalar_min_max_umod(dst_reg, &src_reg);
14681 		break;
14682 	case BPF_AND:
14683 		if (tnum_is_const(src_reg.var_off)) {
14684 			ret = maybe_fork_scalars(env, insn, dst_reg);
14685 			if (ret)
14686 				return ret;
14687 		}
14688 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14689 		scalar32_min_max_and(dst_reg, &src_reg);
14690 		scalar_min_max_and(dst_reg, &src_reg);
14691 		break;
14692 	case BPF_OR:
14693 		if (tnum_is_const(src_reg.var_off)) {
14694 			ret = maybe_fork_scalars(env, insn, dst_reg);
14695 			if (ret)
14696 				return ret;
14697 		}
14698 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14699 		scalar32_min_max_or(dst_reg, &src_reg);
14700 		scalar_min_max_or(dst_reg, &src_reg);
14701 		break;
14702 	case BPF_XOR:
14703 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14704 		scalar32_min_max_xor(dst_reg, &src_reg);
14705 		scalar_min_max_xor(dst_reg, &src_reg);
14706 		break;
14707 	case BPF_LSH:
14708 		if (alu32)
14709 			scalar32_min_max_lsh(dst_reg, &src_reg);
14710 		else
14711 			scalar_min_max_lsh(dst_reg, &src_reg);
14712 		break;
14713 	case BPF_RSH:
14714 		if (alu32)
14715 			scalar32_min_max_rsh(dst_reg, &src_reg);
14716 		else
14717 			scalar_min_max_rsh(dst_reg, &src_reg);
14718 		break;
14719 	case BPF_ARSH:
14720 		if (alu32)
14721 			scalar32_min_max_arsh(dst_reg, &src_reg);
14722 		else
14723 			scalar_min_max_arsh(dst_reg, &src_reg);
14724 		break;
14725 	case BPF_END:
14726 		scalar_byte_swap(dst_reg, insn);
14727 		break;
14728 	default:
14729 		break;
14730 	}
14731 
14732 	/*
14733 	 * ALU32 ops are zero extended into 64bit register.
14734 	 *
14735 	 * BPF_END is already handled inside the helper (truncation),
14736 	 * so skip zext here to avoid unexpected zero extension.
14737 	 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40
14738 	 * This is a 64bit byte swap operation with alu32==true,
14739 	 * but we should not zero extend the result.
14740 	 */
14741 	if (alu32 && opcode != BPF_END)
14742 		zext_32_to_64(dst_reg);
14743 	reg_bounds_sync(dst_reg);
14744 	return 0;
14745 }
14746 
14747 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14748  * and var_off.
14749  */
14750 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14751 				   struct bpf_insn *insn)
14752 {
14753 	struct bpf_verifier_state *vstate = env->cur_state;
14754 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14755 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14756 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14757 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14758 	u8 opcode = BPF_OP(insn->code);
14759 	int err;
14760 
14761 	dst_reg = &regs[insn->dst_reg];
14762 	if (BPF_SRC(insn->code) == BPF_X)
14763 		src_reg = &regs[insn->src_reg];
14764 	else
14765 		src_reg = NULL;
14766 
14767 	/* Case where at least one operand is an arena. */
14768 	if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) {
14769 		struct bpf_insn_aux_data *aux = cur_aux(env);
14770 
14771 		if (dst_reg->type != PTR_TO_ARENA)
14772 			*dst_reg = *src_reg;
14773 
14774 		dst_reg->subreg_def = env->insn_idx + 1;
14775 
14776 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14777 			/*
14778 			 * 32-bit operations zero upper bits automatically.
14779 			 * 64-bit operations need to be converted to 32.
14780 			 */
14781 			aux->needs_zext = true;
14782 
14783 		/* Any arithmetic operations are allowed on arena pointers */
14784 		return 0;
14785 	}
14786 
14787 	if (dst_reg->type != SCALAR_VALUE)
14788 		ptr_reg = dst_reg;
14789 
14790 	if (BPF_SRC(insn->code) == BPF_X) {
14791 		if (src_reg->type != SCALAR_VALUE) {
14792 			if (dst_reg->type != SCALAR_VALUE) {
14793 				/* Combining two pointers by any ALU op yields
14794 				 * an arbitrary scalar. Disallow all math except
14795 				 * pointer subtraction
14796 				 */
14797 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14798 					mark_reg_unknown(env, regs, insn->dst_reg);
14799 					return 0;
14800 				}
14801 				verbose(env, "R%d pointer %s pointer prohibited\n",
14802 					insn->dst_reg,
14803 					bpf_alu_string[opcode >> 4]);
14804 				return -EACCES;
14805 			} else {
14806 				/* scalar += pointer
14807 				 * This is legal, but we have to reverse our
14808 				 * src/dest handling in computing the range
14809 				 */
14810 				err = mark_chain_precision(env, insn->dst_reg);
14811 				if (err)
14812 					return err;
14813 				return adjust_ptr_min_max_vals(env, insn,
14814 							       src_reg, dst_reg);
14815 			}
14816 		} else if (ptr_reg) {
14817 			/* pointer += scalar */
14818 			err = mark_chain_precision(env, insn->src_reg);
14819 			if (err)
14820 				return err;
14821 			return adjust_ptr_min_max_vals(env, insn,
14822 						       dst_reg, src_reg);
14823 		} else if (dst_reg->precise) {
14824 			/* if dst_reg is precise, src_reg should be precise as well */
14825 			err = mark_chain_precision(env, insn->src_reg);
14826 			if (err)
14827 				return err;
14828 		}
14829 	} else {
14830 		/* Pretend the src is a reg with a known value, since we only
14831 		 * need to be able to read from this state.
14832 		 */
14833 		off_reg.type = SCALAR_VALUE;
14834 		__mark_reg_known(&off_reg, insn->imm);
14835 		src_reg = &off_reg;
14836 		if (ptr_reg) /* pointer += K */
14837 			return adjust_ptr_min_max_vals(env, insn,
14838 						       ptr_reg, src_reg);
14839 	}
14840 
14841 	/* Got here implies adding two SCALAR_VALUEs */
14842 	if (WARN_ON_ONCE(ptr_reg)) {
14843 		print_verifier_state(env, vstate, vstate->curframe, true);
14844 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14845 		return -EFAULT;
14846 	}
14847 	if (WARN_ON(!src_reg)) {
14848 		print_verifier_state(env, vstate, vstate->curframe, true);
14849 		verbose(env, "verifier internal error: no src_reg\n");
14850 		return -EFAULT;
14851 	}
14852 	/*
14853 	 * For alu32 linked register tracking, we need to check dst_reg's
14854 	 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(),
14855 	 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX.
14856 	 */
14857 	u64 dst_umax = reg_umax(dst_reg);
14858 
14859 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14860 	if (err)
14861 		return err;
14862 	/*
14863 	 * Compilers can generate the code
14864 	 * r1 = r2
14865 	 * r1 += 0x1
14866 	 * if r2 < 1000 goto ...
14867 	 * use r1 in memory access
14868 	 * So remember constant delta between r2 and r1 and update r1 after
14869 	 * 'if' condition.
14870 	 */
14871 	if (env->bpf_capable &&
14872 	    (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) &&
14873 	    dst_reg->id && is_reg_const(src_reg, alu32) &&
14874 	    !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) {
14875 		u64 val = reg_const_value(src_reg, alu32);
14876 		s32 off;
14877 
14878 		if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX))
14879 			goto clear_id;
14880 
14881 		if (alu32 && (dst_umax > U32_MAX))
14882 			goto clear_id;
14883 
14884 		off = (s32)val;
14885 
14886 		if (BPF_OP(insn->code) == BPF_SUB) {
14887 			/* Negating S32_MIN would overflow */
14888 			if (off == S32_MIN)
14889 				goto clear_id;
14890 			off = -off;
14891 		}
14892 
14893 		if (dst_reg->id & BPF_ADD_CONST) {
14894 			/*
14895 			 * If the register already went through rX += val
14896 			 * we cannot accumulate another val into rx->off.
14897 			 */
14898 clear_id:
14899 			clear_scalar_id(dst_reg);
14900 		} else {
14901 			if (alu32)
14902 				dst_reg->id |= BPF_ADD_CONST32;
14903 			else
14904 				dst_reg->id |= BPF_ADD_CONST64;
14905 			dst_reg->delta = off;
14906 		}
14907 	} else {
14908 		/*
14909 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14910 		 * incorrectly propagated into other registers by sync_linked_regs()
14911 		 */
14912 		clear_scalar_id(dst_reg);
14913 	}
14914 	return 0;
14915 }
14916 
14917 /* check validity of 32-bit and 64-bit arithmetic operations */
14918 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14919 {
14920 	struct bpf_reg_state *regs = cur_regs(env);
14921 	u8 opcode = BPF_OP(insn->code);
14922 	int err;
14923 
14924 	if (opcode == BPF_END || opcode == BPF_NEG) {
14925 		/* check src operand */
14926 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14927 		if (err)
14928 			return err;
14929 
14930 		if (is_pointer_value(env, insn->dst_reg)) {
14931 			verbose(env, "R%d pointer arithmetic prohibited\n",
14932 				insn->dst_reg);
14933 			return -EACCES;
14934 		}
14935 
14936 		/* check dest operand */
14937 		if (regs[insn->dst_reg].type == SCALAR_VALUE) {
14938 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14939 			err = err ?: adjust_scalar_min_max_vals(env, insn,
14940 							 &regs[insn->dst_reg],
14941 							 regs[insn->dst_reg]);
14942 		} else {
14943 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
14944 		}
14945 		if (err)
14946 			return err;
14947 
14948 	} else if (opcode == BPF_MOV) {
14949 
14950 		if (BPF_SRC(insn->code) == BPF_X) {
14951 			if (insn->off == BPF_ADDR_SPACE_CAST) {
14952 				if (!env->prog->aux->arena) {
14953 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14954 					return -EINVAL;
14955 				}
14956 			}
14957 
14958 			/* check src operand */
14959 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14960 			if (err)
14961 				return err;
14962 		}
14963 
14964 		/* check dest operand, mark as required later */
14965 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14966 		if (err)
14967 			return err;
14968 
14969 		if (BPF_SRC(insn->code) == BPF_X) {
14970 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14971 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14972 
14973 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14974 				if (insn->imm) {
14975 					/* off == BPF_ADDR_SPACE_CAST */
14976 					mark_reg_unknown(env, regs, insn->dst_reg);
14977 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14978 						dst_reg->type = PTR_TO_ARENA;
14979 						/* PTR_TO_ARENA is 32-bit */
14980 						dst_reg->subreg_def = env->insn_idx + 1;
14981 					}
14982 				} else if (insn->off == 0) {
14983 					/* case: R1 = R2
14984 					 * copy register state to dest reg
14985 					 */
14986 					assign_scalar_id_before_mov(env, src_reg);
14987 					*dst_reg = *src_reg;
14988 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14989 				} else {
14990 					/* case: R1 = (s8, s16 s32)R2 */
14991 					if (is_pointer_value(env, insn->src_reg)) {
14992 						verbose(env,
14993 							"R%d sign-extension part of pointer\n",
14994 							insn->src_reg);
14995 						return -EACCES;
14996 					} else if (src_reg->type == SCALAR_VALUE) {
14997 						bool no_sext;
14998 
14999 						no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
15000 						if (no_sext)
15001 							assign_scalar_id_before_mov(env, src_reg);
15002 						*dst_reg = *src_reg;
15003 						if (!no_sext)
15004 							clear_scalar_id(dst_reg);
15005 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15006 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15007 					} else {
15008 						mark_reg_unknown(env, regs, insn->dst_reg);
15009 					}
15010 				}
15011 			} else {
15012 				/* R1 = (u32) R2 */
15013 				if (is_pointer_value(env, insn->src_reg)) {
15014 					verbose(env,
15015 						"R%d partial copy of pointer\n",
15016 						insn->src_reg);
15017 					return -EACCES;
15018 				} else if (src_reg->type == SCALAR_VALUE) {
15019 					if (insn->off == 0) {
15020 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15021 
15022 						if (is_src_reg_u32)
15023 							assign_scalar_id_before_mov(env, src_reg);
15024 						*dst_reg = *src_reg;
15025 						/* Make sure ID is cleared if src_reg is not in u32
15026 						 * range otherwise dst_reg min/max could be incorrectly
15027 						 * propagated into src_reg by sync_linked_regs()
15028 						 */
15029 						if (!is_src_reg_u32)
15030 							clear_scalar_id(dst_reg);
15031 						dst_reg->subreg_def = env->insn_idx + 1;
15032 					} else {
15033 						/* case: W1 = (s8, s16)W2 */
15034 						bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1));
15035 
15036 						if (no_sext)
15037 							assign_scalar_id_before_mov(env, src_reg);
15038 						*dst_reg = *src_reg;
15039 						if (!no_sext)
15040 							clear_scalar_id(dst_reg);
15041 						dst_reg->subreg_def = env->insn_idx + 1;
15042 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15043 					}
15044 				} else {
15045 					mark_reg_unknown(env, regs,
15046 							 insn->dst_reg);
15047 				}
15048 				zext_32_to_64(dst_reg);
15049 				reg_bounds_sync(dst_reg);
15050 			}
15051 		} else {
15052 			/* case: R = imm
15053 			 * remember the value we stored into this reg
15054 			 */
15055 			/* clear any state __mark_reg_known doesn't set */
15056 			mark_reg_unknown(env, regs, insn->dst_reg);
15057 			regs[insn->dst_reg].type = SCALAR_VALUE;
15058 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15059 				__mark_reg_known(regs + insn->dst_reg,
15060 						 insn->imm);
15061 			} else {
15062 				__mark_reg_known(regs + insn->dst_reg,
15063 						 (u32)insn->imm);
15064 			}
15065 		}
15066 
15067 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15068 
15069 		if (BPF_SRC(insn->code) == BPF_X) {
15070 			/* check src1 operand */
15071 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15072 			if (err)
15073 				return err;
15074 		}
15075 
15076 		/* check src2 operand */
15077 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15078 		if (err)
15079 			return err;
15080 
15081 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15082 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15083 			verbose(env, "div by zero\n");
15084 			return -EINVAL;
15085 		}
15086 
15087 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15088 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15089 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15090 
15091 			if (insn->imm < 0 || insn->imm >= size) {
15092 				verbose(env, "invalid shift %d\n", insn->imm);
15093 				return -EINVAL;
15094 			}
15095 		}
15096 
15097 		/* check dest operand */
15098 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15099 		err = err ?: adjust_reg_min_max_vals(env, insn);
15100 		if (err)
15101 			return err;
15102 	}
15103 
15104 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15105 }
15106 
15107 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15108 				   struct bpf_reg_state *dst_reg,
15109 				   enum bpf_reg_type type,
15110 				   bool range_right_open)
15111 {
15112 	struct bpf_func_state *state;
15113 	struct bpf_reg_state *reg;
15114 	int new_range;
15115 
15116 	if (reg_umax(dst_reg) == 0 && range_right_open)
15117 		/* This doesn't give us any range */
15118 		return;
15119 
15120 	if (reg_umax(dst_reg) > MAX_PACKET_OFF)
15121 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15122 		 * than pkt_end, but that's because it's also less than pkt.
15123 		 */
15124 		return;
15125 
15126 	new_range = reg_umax(dst_reg);
15127 	if (range_right_open)
15128 		new_range++;
15129 
15130 	/* Examples for register markings:
15131 	 *
15132 	 * pkt_data in dst register:
15133 	 *
15134 	 *   r2 = r3;
15135 	 *   r2 += 8;
15136 	 *   if (r2 > pkt_end) goto <handle exception>
15137 	 *   <access okay>
15138 	 *
15139 	 *   r2 = r3;
15140 	 *   r2 += 8;
15141 	 *   if (r2 < pkt_end) goto <access okay>
15142 	 *   <handle exception>
15143 	 *
15144 	 *   Where:
15145 	 *     r2 == dst_reg, pkt_end == src_reg
15146 	 *     r2=pkt(id=n,off=8,r=0)
15147 	 *     r3=pkt(id=n,off=0,r=0)
15148 	 *
15149 	 * pkt_data in src register:
15150 	 *
15151 	 *   r2 = r3;
15152 	 *   r2 += 8;
15153 	 *   if (pkt_end >= r2) goto <access okay>
15154 	 *   <handle exception>
15155 	 *
15156 	 *   r2 = r3;
15157 	 *   r2 += 8;
15158 	 *   if (pkt_end <= r2) goto <handle exception>
15159 	 *   <access okay>
15160 	 *
15161 	 *   Where:
15162 	 *     pkt_end == dst_reg, r2 == src_reg
15163 	 *     r2=pkt(id=n,off=8,r=0)
15164 	 *     r3=pkt(id=n,off=0,r=0)
15165 	 *
15166 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15167 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15168 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15169 	 * the check.
15170 	 */
15171 
15172 	/* If our ids match, then we must have the same max_value.  And we
15173 	 * don't care about the other reg's fixed offset, since if it's too big
15174 	 * the range won't allow anything.
15175 	 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16.
15176 	 */
15177 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15178 		if (reg->type == type && reg->id == dst_reg->id)
15179 			/* keep the maximum range already checked */
15180 			reg->range = max(reg->range, new_range);
15181 	}));
15182 }
15183 
15184 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15185 				u8 opcode, bool is_jmp32);
15186 static u8 rev_opcode(u8 opcode);
15187 
15188 /*
15189  * Learn more information about live branches by simulating refinement on both branches.
15190  * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
15191  * that branch is dead.
15192  */
15193 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
15194 {
15195 	/* Fallthrough (FALSE) branch */
15196 	regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32);
15197 	reg_bounds_sync(&env->false_reg1);
15198 	reg_bounds_sync(&env->false_reg2);
15199 	/*
15200 	 * If there is a range bounds violation in *any* of the abstract values in either
15201 	 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only
15202 	 * TRUE branch will be taken.
15203 	 */
15204 	if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2))
15205 		return 1;
15206 
15207 	/* Jump (TRUE) branch */
15208 	regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32);
15209 	reg_bounds_sync(&env->true_reg1);
15210 	reg_bounds_sync(&env->true_reg2);
15211 	/*
15212 	 * If there is a range bounds violation in *any* of the abstract values in either
15213 	 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead.
15214 	 * Only FALSE branch will be taken.
15215 	 */
15216 	if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2))
15217 		return 0;
15218 
15219 	/* Both branches are possible, we can't determine which one will be taken. */
15220 	return -1;
15221 }
15222 
15223 /*
15224  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15225  */
15226 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
15227 				  struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
15228 {
15229 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15230 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15231 	u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1);
15232 	u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1);
15233 	s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1);
15234 	s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1);
15235 	u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2);
15236 	u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2);
15237 	s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2);
15238 	s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2);
15239 
15240 	if (reg1 == reg2) {
15241 		switch (opcode) {
15242 		case BPF_JGE:
15243 		case BPF_JLE:
15244 		case BPF_JSGE:
15245 		case BPF_JSLE:
15246 		case BPF_JEQ:
15247 			return 1;
15248 		case BPF_JGT:
15249 		case BPF_JLT:
15250 		case BPF_JSGT:
15251 		case BPF_JSLT:
15252 		case BPF_JNE:
15253 			return 0;
15254 		case BPF_JSET:
15255 			if (tnum_is_const(t1))
15256 				return t1.value != 0;
15257 			else
15258 				return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
15259 		default:
15260 			return -1;
15261 		}
15262 	}
15263 
15264 	switch (opcode) {
15265 	case BPF_JEQ:
15266 		/* constants, umin/umax and smin/smax checks would be
15267 		 * redundant in this case because they all should match
15268 		 */
15269 		if (tnum_is_const(t1) && tnum_is_const(t2))
15270 			return t1.value == t2.value;
15271 		if (!tnum_overlap(t1, t2))
15272 			return 0;
15273 		/* non-overlapping ranges */
15274 		if (umin1 > umax2 || umax1 < umin2)
15275 			return 0;
15276 		if (smin1 > smax2 || smax1 < smin2)
15277 			return 0;
15278 		if (!is_jmp32) {
15279 			/* if 64-bit ranges are inconclusive, see if we can
15280 			 * utilize 32-bit subrange knowledge to eliminate
15281 			 * branches that can't be taken a priori
15282 			 */
15283 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
15284 			    reg_u32_max(reg1) < reg_u32_min(reg2))
15285 				return 0;
15286 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
15287 			    reg_s32_max(reg1) < reg_s32_min(reg2))
15288 				return 0;
15289 		}
15290 		break;
15291 	case BPF_JNE:
15292 		/* constants, umin/umax and smin/smax checks would be
15293 		 * redundant in this case because they all should match
15294 		 */
15295 		if (tnum_is_const(t1) && tnum_is_const(t2))
15296 			return t1.value != t2.value;
15297 		if (!tnum_overlap(t1, t2))
15298 			return 1;
15299 		/* non-overlapping ranges */
15300 		if (umin1 > umax2 || umax1 < umin2)
15301 			return 1;
15302 		if (smin1 > smax2 || smax1 < smin2)
15303 			return 1;
15304 		if (!is_jmp32) {
15305 			/* if 64-bit ranges are inconclusive, see if we can
15306 			 * utilize 32-bit subrange knowledge to eliminate
15307 			 * branches that can't be taken a priori
15308 			 */
15309 			if (reg_u32_min(reg1) > reg_u32_max(reg2) ||
15310 			    reg_u32_max(reg1) < reg_u32_min(reg2))
15311 				return 1;
15312 			if (reg_s32_min(reg1) > reg_s32_max(reg2) ||
15313 			    reg_s32_max(reg1) < reg_s32_min(reg2))
15314 				return 1;
15315 		}
15316 		break;
15317 	case BPF_JSET:
15318 		if (!is_reg_const(reg2, is_jmp32)) {
15319 			swap(reg1, reg2);
15320 			swap(t1, t2);
15321 		}
15322 		if (!is_reg_const(reg2, is_jmp32))
15323 			return -1;
15324 		if ((~t1.mask & t1.value) & t2.value)
15325 			return 1;
15326 		if (!((t1.mask | t1.value) & t2.value))
15327 			return 0;
15328 		break;
15329 	case BPF_JGT:
15330 		if (umin1 > umax2)
15331 			return 1;
15332 		else if (umax1 <= umin2)
15333 			return 0;
15334 		break;
15335 	case BPF_JSGT:
15336 		if (smin1 > smax2)
15337 			return 1;
15338 		else if (smax1 <= smin2)
15339 			return 0;
15340 		break;
15341 	case BPF_JLT:
15342 		if (umax1 < umin2)
15343 			return 1;
15344 		else if (umin1 >= umax2)
15345 			return 0;
15346 		break;
15347 	case BPF_JSLT:
15348 		if (smax1 < smin2)
15349 			return 1;
15350 		else if (smin1 >= smax2)
15351 			return 0;
15352 		break;
15353 	case BPF_JGE:
15354 		if (umin1 >= umax2)
15355 			return 1;
15356 		else if (umax1 < umin2)
15357 			return 0;
15358 		break;
15359 	case BPF_JSGE:
15360 		if (smin1 >= smax2)
15361 			return 1;
15362 		else if (smax1 < smin2)
15363 			return 0;
15364 		break;
15365 	case BPF_JLE:
15366 		if (umax1 <= umin2)
15367 			return 1;
15368 		else if (umin1 > umax2)
15369 			return 0;
15370 		break;
15371 	case BPF_JSLE:
15372 		if (smax1 <= smin2)
15373 			return 1;
15374 		else if (smin1 > smax2)
15375 			return 0;
15376 		break;
15377 	}
15378 
15379 	return simulate_both_branches_taken(env, opcode, is_jmp32);
15380 }
15381 
15382 static int flip_opcode(u32 opcode)
15383 {
15384 	/* How can we transform "a <op> b" into "b <op> a"? */
15385 	static const u8 opcode_flip[16] = {
15386 		/* these stay the same */
15387 		[BPF_JEQ  >> 4] = BPF_JEQ,
15388 		[BPF_JNE  >> 4] = BPF_JNE,
15389 		[BPF_JSET >> 4] = BPF_JSET,
15390 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
15391 		[BPF_JGE  >> 4] = BPF_JLE,
15392 		[BPF_JGT  >> 4] = BPF_JLT,
15393 		[BPF_JLE  >> 4] = BPF_JGE,
15394 		[BPF_JLT  >> 4] = BPF_JGT,
15395 		[BPF_JSGE >> 4] = BPF_JSLE,
15396 		[BPF_JSGT >> 4] = BPF_JSLT,
15397 		[BPF_JSLE >> 4] = BPF_JSGE,
15398 		[BPF_JSLT >> 4] = BPF_JSGT
15399 	};
15400 	return opcode_flip[opcode >> 4];
15401 }
15402 
15403 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
15404 				   struct bpf_reg_state *src_reg,
15405 				   u8 opcode)
15406 {
15407 	struct bpf_reg_state *pkt;
15408 
15409 	if (src_reg->type == PTR_TO_PACKET_END) {
15410 		pkt = dst_reg;
15411 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
15412 		pkt = src_reg;
15413 		opcode = flip_opcode(opcode);
15414 	} else {
15415 		return -1;
15416 	}
15417 
15418 	if (pkt->range >= 0)
15419 		return -1;
15420 
15421 	switch (opcode) {
15422 	case BPF_JLE:
15423 		/* pkt <= pkt_end */
15424 		fallthrough;
15425 	case BPF_JGT:
15426 		/* pkt > pkt_end */
15427 		if (pkt->range == BEYOND_PKT_END)
15428 			/* pkt has at last one extra byte beyond pkt_end */
15429 			return opcode == BPF_JGT;
15430 		break;
15431 	case BPF_JLT:
15432 		/* pkt < pkt_end */
15433 		fallthrough;
15434 	case BPF_JGE:
15435 		/* pkt >= pkt_end */
15436 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
15437 			return opcode == BPF_JGE;
15438 		break;
15439 	}
15440 	return -1;
15441 }
15442 
15443 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
15444  * and return:
15445  *  1 - branch will be taken and "goto target" will be executed
15446  *  0 - branch will not be taken and fall-through to next insn
15447  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
15448  *      range [0,10]
15449  */
15450 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1,
15451 			   struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32)
15452 {
15453 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
15454 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
15455 
15456 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
15457 		u64 val;
15458 
15459 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
15460 		if (!is_reg_const(reg2, is_jmp32)) {
15461 			opcode = flip_opcode(opcode);
15462 			swap(reg1, reg2);
15463 		}
15464 		/* and ensure that reg2 is a constant */
15465 		if (!is_reg_const(reg2, is_jmp32))
15466 			return -1;
15467 
15468 		if (!reg_not_null(env, reg1))
15469 			return -1;
15470 
15471 		/* If pointer is valid tests against zero will fail so we can
15472 		 * use this to direct branch taken.
15473 		 */
15474 		val = reg_const_value(reg2, is_jmp32);
15475 		if (val != 0)
15476 			return -1;
15477 
15478 		switch (opcode) {
15479 		case BPF_JEQ:
15480 			return 0;
15481 		case BPF_JNE:
15482 			return 1;
15483 		default:
15484 			return -1;
15485 		}
15486 	}
15487 
15488 	/* now deal with two scalars, but not necessarily constants */
15489 	return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32);
15490 }
15491 
15492 /* Opcode that corresponds to a *false* branch condition.
15493  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
15494  */
15495 static u8 rev_opcode(u8 opcode)
15496 {
15497 	switch (opcode) {
15498 	case BPF_JEQ:		return BPF_JNE;
15499 	case BPF_JNE:		return BPF_JEQ;
15500 	/* JSET doesn't have it's reverse opcode in BPF, so add
15501 	 * BPF_X flag to denote the reverse of that operation
15502 	 */
15503 	case BPF_JSET:		return BPF_JSET | BPF_X;
15504 	case BPF_JSET | BPF_X:	return BPF_JSET;
15505 	case BPF_JGE:		return BPF_JLT;
15506 	case BPF_JGT:		return BPF_JLE;
15507 	case BPF_JLE:		return BPF_JGT;
15508 	case BPF_JLT:		return BPF_JGE;
15509 	case BPF_JSGE:		return BPF_JSLT;
15510 	case BPF_JSGT:		return BPF_JSLE;
15511 	case BPF_JSLE:		return BPF_JSGT;
15512 	case BPF_JSLT:		return BPF_JSGE;
15513 	default:		return 0;
15514 	}
15515 }
15516 
15517 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
15518 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15519 				u8 opcode, bool is_jmp32)
15520 {
15521 	struct tnum t;
15522 	u64 val;
15523 
15524 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
15525 	switch (opcode) {
15526 	case BPF_JGE:
15527 	case BPF_JGT:
15528 	case BPF_JSGE:
15529 	case BPF_JSGT:
15530 		opcode = flip_opcode(opcode);
15531 		swap(reg1, reg2);
15532 		break;
15533 	default:
15534 		break;
15535 	}
15536 
15537 	switch (opcode) {
15538 	case BPF_JEQ:
15539 		if (is_jmp32) {
15540 			reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32);
15541 			reg2->r32 = reg1->r32;
15542 
15543 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
15544 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15545 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
15546 		} else {
15547 			reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64);
15548 			reg2->r64 = reg1->r64;
15549 
15550 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
15551 			reg2->var_off = reg1->var_off;
15552 		}
15553 		break;
15554 	case BPF_JNE:
15555 		if (!is_reg_const(reg2, is_jmp32))
15556 			swap(reg1, reg2);
15557 		if (!is_reg_const(reg2, is_jmp32))
15558 			break;
15559 
15560 		/* try to recompute the bound of reg1 if reg2 is a const and
15561 		 * is exactly the edge of reg1.
15562 		 */
15563 		val = reg_const_value(reg2, is_jmp32);
15564 		if (is_jmp32) {
15565 			/* Complement of the range [val, val] as cnum32. */
15566 			cnum32_intersect_with(&reg1->r32, (struct cnum32){ val + 1, U32_MAX - 1 });
15567 		} else {
15568 			/* Complement of the range [val, val] as cnum64. */
15569 			cnum64_intersect_with(&reg1->r64, (struct cnum64){ val + 1, U64_MAX - 1 });
15570 		}
15571 		break;
15572 	case BPF_JSET:
15573 		if (!is_reg_const(reg2, is_jmp32))
15574 			swap(reg1, reg2);
15575 		if (!is_reg_const(reg2, is_jmp32))
15576 			break;
15577 		val = reg_const_value(reg2, is_jmp32);
15578 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
15579 		 * requires single bit to learn something useful. E.g., if we
15580 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
15581 		 * are actually set? We can learn something definite only if
15582 		 * it's a single-bit value to begin with.
15583 		 *
15584 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
15585 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
15586 		 * bit 1 is set, which we can readily use in adjustments.
15587 		 */
15588 		if (!is_power_of_2(val))
15589 			break;
15590 		if (is_jmp32) {
15591 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
15592 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15593 		} else {
15594 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15595 		}
15596 		break;
15597 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15598 		if (!is_reg_const(reg2, is_jmp32))
15599 			swap(reg1, reg2);
15600 		if (!is_reg_const(reg2, is_jmp32))
15601 			break;
15602 		val = reg_const_value(reg2, is_jmp32);
15603 		/* Forget the ranges before narrowing tnums, to avoid invariant
15604 		 * violations if we're on a dead branch.
15605 		 */
15606 		__mark_reg_unbounded(reg1);
15607 		if (is_jmp32) {
15608 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15609 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15610 		} else {
15611 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15612 		}
15613 		break;
15614 	case BPF_JLE:
15615 		if (is_jmp32) {
15616 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2));
15617 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1), U32_MAX);
15618 		} else {
15619 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2));
15620 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1), U64_MAX);
15621 		}
15622 		break;
15623 	case BPF_JLT:
15624 		if (is_jmp32) {
15625 			cnum32_intersect_with_urange(&reg1->r32, 0, reg_u32_max(reg2) - 1);
15626 			cnum32_intersect_with_urange(&reg2->r32, reg_u32_min(reg1) + 1, U32_MAX);
15627 		} else {
15628 			cnum64_intersect_with_urange(&reg1->r64, 0, reg_umax(reg2) - 1);
15629 			cnum64_intersect_with_urange(&reg2->r64, reg_umin(reg1) + 1, U64_MAX);
15630 		}
15631 		break;
15632 	case BPF_JSLE:
15633 		if (is_jmp32) {
15634 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2));
15635 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1), S32_MAX);
15636 		} else {
15637 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2));
15638 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1), S64_MAX);
15639 		}
15640 		break;
15641 	case BPF_JSLT:
15642 		if (is_jmp32) {
15643 			cnum32_intersect_with_srange(&reg1->r32, S32_MIN, reg_s32_max(reg2) - 1);
15644 			cnum32_intersect_with_srange(&reg2->r32, reg_s32_min(reg1) + 1, S32_MAX);
15645 		} else {
15646 			cnum64_intersect_with_srange(&reg1->r64, S64_MIN, reg_smax(reg2) - 1);
15647 			cnum64_intersect_with_srange(&reg2->r64, reg_smin(reg1) + 1, S64_MAX);
15648 		}
15649 		break;
15650 	default:
15651 		return;
15652 	}
15653 }
15654 
15655 /* Check for invariant violations on the registers for both branches of a condition */
15656 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env)
15657 {
15658 	int err;
15659 
15660 	err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1");
15661 	err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2");
15662 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1");
15663 	err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2");
15664 	return err;
15665 }
15666 
15667 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15668 				 struct bpf_reg_state *reg, u32 id,
15669 				 bool is_null)
15670 {
15671 	if (type_may_be_null(reg->type) && reg->id == id &&
15672 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15673 		/* Old offset should have been known-zero, because we don't
15674 		 * allow pointer arithmetic on pointers that might be NULL.
15675 		 * If we see this happening, don't convert the register.
15676 		 *
15677 		 * But in some cases, some helpers that return local kptrs
15678 		 * advance offset for the returned pointer. In those cases,
15679 		 * it is fine to expect to see reg->var_off.
15680 		 */
15681 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15682 		    WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0)))
15683 			return;
15684 		if (is_null) {
15685 			/* We don't need id from this point
15686 			 * onwards anymore, thus we should better reset it,
15687 			 * so that state pruning has chances to take effect.
15688 			 */
15689 			__mark_reg_known_zero(reg);
15690 			reg->type = SCALAR_VALUE;
15691 
15692 			return;
15693 		}
15694 
15695 		mark_ptr_not_null_reg(reg);
15696 
15697 		/*
15698 		 * reg->id is preserved for object relationship tracking
15699 		 * and spin_lock lock state tracking
15700 		 */
15701 	}
15702 }
15703 
15704 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15705  * be folded together at some point.
15706  */
15707 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15708 				  bool is_null)
15709 {
15710 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15711 	struct bpf_reg_state *regs = state->regs, *reg;
15712 	u32 id = regs[regno].id;
15713 
15714 	if (is_null && find_reference_state(vstate, id))
15715 		/* regs[regno] is in the " == NULL" branch.
15716 		 * No one could have freed the reference state before
15717 		 * doing the NULL check.
15718 		 */
15719 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
15720 
15721 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15722 		mark_ptr_or_null_reg(state, reg, id, is_null);
15723 	}));
15724 }
15725 
15726 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15727 				   struct bpf_reg_state *dst_reg,
15728 				   struct bpf_reg_state *src_reg,
15729 				   struct bpf_verifier_state *this_branch,
15730 				   struct bpf_verifier_state *other_branch)
15731 {
15732 	if (BPF_SRC(insn->code) != BPF_X)
15733 		return false;
15734 
15735 	/* Pointers are always 64-bit. */
15736 	if (BPF_CLASS(insn->code) == BPF_JMP32)
15737 		return false;
15738 
15739 	switch (BPF_OP(insn->code)) {
15740 	case BPF_JGT:
15741 		if ((dst_reg->type == PTR_TO_PACKET &&
15742 		     src_reg->type == PTR_TO_PACKET_END) ||
15743 		    (dst_reg->type == PTR_TO_PACKET_META &&
15744 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15745 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15746 			find_good_pkt_pointers(this_branch, dst_reg,
15747 					       dst_reg->type, false);
15748 			mark_pkt_end(other_branch, insn->dst_reg, true);
15749 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15750 			    src_reg->type == PTR_TO_PACKET) ||
15751 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15752 			    src_reg->type == PTR_TO_PACKET_META)) {
15753 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15754 			find_good_pkt_pointers(other_branch, src_reg,
15755 					       src_reg->type, true);
15756 			mark_pkt_end(this_branch, insn->src_reg, false);
15757 		} else {
15758 			return false;
15759 		}
15760 		break;
15761 	case BPF_JLT:
15762 		if ((dst_reg->type == PTR_TO_PACKET &&
15763 		     src_reg->type == PTR_TO_PACKET_END) ||
15764 		    (dst_reg->type == PTR_TO_PACKET_META &&
15765 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15766 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15767 			find_good_pkt_pointers(other_branch, dst_reg,
15768 					       dst_reg->type, true);
15769 			mark_pkt_end(this_branch, insn->dst_reg, false);
15770 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15771 			    src_reg->type == PTR_TO_PACKET) ||
15772 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15773 			    src_reg->type == PTR_TO_PACKET_META)) {
15774 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15775 			find_good_pkt_pointers(this_branch, src_reg,
15776 					       src_reg->type, false);
15777 			mark_pkt_end(other_branch, insn->src_reg, true);
15778 		} else {
15779 			return false;
15780 		}
15781 		break;
15782 	case BPF_JGE:
15783 		if ((dst_reg->type == PTR_TO_PACKET &&
15784 		     src_reg->type == PTR_TO_PACKET_END) ||
15785 		    (dst_reg->type == PTR_TO_PACKET_META &&
15786 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15787 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15788 			find_good_pkt_pointers(this_branch, dst_reg,
15789 					       dst_reg->type, true);
15790 			mark_pkt_end(other_branch, insn->dst_reg, false);
15791 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15792 			    src_reg->type == PTR_TO_PACKET) ||
15793 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15794 			    src_reg->type == PTR_TO_PACKET_META)) {
15795 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15796 			find_good_pkt_pointers(other_branch, src_reg,
15797 					       src_reg->type, false);
15798 			mark_pkt_end(this_branch, insn->src_reg, true);
15799 		} else {
15800 			return false;
15801 		}
15802 		break;
15803 	case BPF_JLE:
15804 		if ((dst_reg->type == PTR_TO_PACKET &&
15805 		     src_reg->type == PTR_TO_PACKET_END) ||
15806 		    (dst_reg->type == PTR_TO_PACKET_META &&
15807 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15808 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15809 			find_good_pkt_pointers(other_branch, dst_reg,
15810 					       dst_reg->type, false);
15811 			mark_pkt_end(this_branch, insn->dst_reg, true);
15812 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15813 			    src_reg->type == PTR_TO_PACKET) ||
15814 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15815 			    src_reg->type == PTR_TO_PACKET_META)) {
15816 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15817 			find_good_pkt_pointers(this_branch, src_reg,
15818 					       src_reg->type, true);
15819 			mark_pkt_end(other_branch, insn->src_reg, false);
15820 		} else {
15821 			return false;
15822 		}
15823 		break;
15824 	default:
15825 		return false;
15826 	}
15827 
15828 	return true;
15829 }
15830 
15831 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15832 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15833 {
15834 	struct linked_reg *e;
15835 
15836 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15837 		return;
15838 
15839 	e = linked_regs_push(reg_set);
15840 	if (e) {
15841 		e->frameno = frameno;
15842 		e->is_reg = is_reg;
15843 		e->regno = spi_or_reg;
15844 	} else {
15845 		clear_scalar_id(reg);
15846 	}
15847 }
15848 
15849 /* For all R being scalar registers or spilled scalar registers
15850  * in verifier state, save R in linked_regs if R->id == id.
15851  * If there are too many Rs sharing same id, reset id for leftover Rs.
15852  */
15853 static void collect_linked_regs(struct bpf_verifier_env *env,
15854 				struct bpf_verifier_state *vstate,
15855 				u32 id,
15856 				struct linked_regs *linked_regs)
15857 {
15858 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
15859 	struct bpf_func_state *func;
15860 	struct bpf_reg_state *reg;
15861 	u16 live_regs;
15862 	int i, j;
15863 
15864 	id = id & ~BPF_ADD_CONST;
15865 	for (i = vstate->curframe; i >= 0; i--) {
15866 		live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before;
15867 		func = vstate->frame[i];
15868 		for (j = 0; j < BPF_REG_FP; j++) {
15869 			if (!(live_regs & BIT(j)))
15870 				continue;
15871 			reg = &func->regs[j];
15872 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
15873 		}
15874 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15875 			if (!bpf_is_spilled_reg(&func->stack[j]))
15876 				continue;
15877 			reg = &func->stack[j].spilled_ptr;
15878 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
15879 		}
15880 	}
15881 }
15882 
15883 /* For all R in linked_regs, copy known_reg range into R
15884  * if R->id == known_reg->id.
15885  */
15886 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate,
15887 			     struct bpf_reg_state *known_reg, struct linked_regs *linked_regs)
15888 {
15889 	struct bpf_reg_state fake_reg;
15890 	struct bpf_reg_state *reg;
15891 	struct linked_reg *e;
15892 	int i;
15893 
15894 	for (i = 0; i < linked_regs->cnt; ++i) {
15895 		e = &linked_regs->entries[i];
15896 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15897 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15898 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15899 			continue;
15900 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15901 			continue;
15902 		/*
15903 		 * Skip mixed 32/64-bit links: the delta relationship doesn't
15904 		 * hold across different ALU widths.
15905 		 */
15906 		if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST)
15907 			continue;
15908 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15909 		    reg->delta == known_reg->delta) {
15910 			s32 saved_subreg_def = reg->subreg_def;
15911 
15912 			*reg = *known_reg;
15913 			reg->subreg_def = saved_subreg_def;
15914 		} else {
15915 			s32 saved_subreg_def = reg->subreg_def;
15916 			s32 saved_off = reg->delta;
15917 			u32 saved_id = reg->id;
15918 
15919 			fake_reg.type = SCALAR_VALUE;
15920 			__mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta);
15921 
15922 			/* reg = known_reg; reg += delta */
15923 			*reg = *known_reg;
15924 			/*
15925 			 * Must preserve off, id and subreg_def flag,
15926 			 * otherwise another sync_linked_regs() will be incorrect.
15927 			 */
15928 			reg->delta = saved_off;
15929 			reg->id = saved_id;
15930 			reg->subreg_def = saved_subreg_def;
15931 
15932 			scalar32_min_max_add(reg, &fake_reg);
15933 			scalar_min_max_add(reg, &fake_reg);
15934 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15935 			if ((reg->id | known_reg->id) & BPF_ADD_CONST32)
15936 				zext_32_to_64(reg);
15937 			reg_bounds_sync(reg);
15938 		}
15939 		if (e->is_reg)
15940 			mark_reg_scratched(env, e->regno);
15941 		else
15942 			mark_stack_slot_scratched(env, e->spi);
15943 	}
15944 }
15945 
15946 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15947 			     struct bpf_insn *insn, int *insn_idx)
15948 {
15949 	struct bpf_verifier_state *this_branch = env->cur_state;
15950 	struct bpf_verifier_state *other_branch;
15951 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15952 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15953 	struct bpf_reg_state *eq_branch_regs;
15954 	struct linked_regs linked_regs = {};
15955 	u8 opcode = BPF_OP(insn->code);
15956 	int insn_flags = 0;
15957 	bool is_jmp32;
15958 	int pred = -1;
15959 	int err;
15960 
15961 	/* Only conditional jumps are expected to reach here. */
15962 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15963 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15964 		return -EINVAL;
15965 	}
15966 
15967 	if (opcode == BPF_JCOND) {
15968 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15969 		int idx = *insn_idx;
15970 
15971 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15972 
15973 		/* branch out 'fallthrough' insn as a new state to explore */
15974 		queued_st = push_stack(env, idx + 1, idx, false);
15975 		if (IS_ERR(queued_st))
15976 			return PTR_ERR(queued_st);
15977 
15978 		queued_st->may_goto_depth++;
15979 		if (prev_st)
15980 			widen_imprecise_scalars(env, prev_st, queued_st);
15981 		*insn_idx += insn->off;
15982 		return 0;
15983 	}
15984 
15985 	/* check src2 operand */
15986 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15987 	if (err)
15988 		return err;
15989 
15990 	dst_reg = &regs[insn->dst_reg];
15991 	if (BPF_SRC(insn->code) == BPF_X) {
15992 		/* check src1 operand */
15993 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15994 		if (err)
15995 			return err;
15996 
15997 		src_reg = &regs[insn->src_reg];
15998 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15999 		    is_pointer_value(env, insn->src_reg)) {
16000 			verbose(env, "R%d pointer comparison prohibited\n",
16001 				insn->src_reg);
16002 			return -EACCES;
16003 		}
16004 
16005 		if (src_reg->type == PTR_TO_STACK)
16006 			insn_flags |= INSN_F_SRC_REG_STACK;
16007 		if (dst_reg->type == PTR_TO_STACK)
16008 			insn_flags |= INSN_F_DST_REG_STACK;
16009 	} else {
16010 		src_reg = &env->fake_reg[0];
16011 		memset(src_reg, 0, sizeof(*src_reg));
16012 		src_reg->type = SCALAR_VALUE;
16013 		__mark_reg_known(src_reg, insn->imm);
16014 
16015 		if (dst_reg->type == PTR_TO_STACK)
16016 			insn_flags |= INSN_F_DST_REG_STACK;
16017 	}
16018 
16019 	if (insn_flags) {
16020 		err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0);
16021 		if (err)
16022 			return err;
16023 	}
16024 
16025 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16026 	env->false_reg1 = *dst_reg;
16027 	env->false_reg2 = *src_reg;
16028 	env->true_reg1 = *dst_reg;
16029 	env->true_reg2 = *src_reg;
16030 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
16031 	if (pred >= 0) {
16032 		/* If we get here with a dst_reg pointer type it is because
16033 		 * above is_branch_taken() special cased the 0 comparison.
16034 		 */
16035 		if (!__is_pointer_value(false, dst_reg))
16036 			err = mark_chain_precision(env, insn->dst_reg);
16037 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16038 		    !__is_pointer_value(false, src_reg))
16039 			err = mark_chain_precision(env, insn->src_reg);
16040 		if (err)
16041 			return err;
16042 	}
16043 
16044 	if (pred == 1) {
16045 		/* Only follow the goto, ignore fall-through. If needed, push
16046 		 * the fall-through branch for simulation under speculative
16047 		 * execution.
16048 		 */
16049 		if (!env->bypass_spec_v1) {
16050 			err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
16051 			if (err < 0)
16052 				return err;
16053 		}
16054 		if (env->log.level & BPF_LOG_LEVEL)
16055 			print_insn_state(env, this_branch, this_branch->curframe);
16056 		*insn_idx += insn->off;
16057 		return 0;
16058 	} else if (pred == 0) {
16059 		/* Only follow the fall-through branch, since that's where the
16060 		 * program will go. If needed, push the goto branch for
16061 		 * simulation under speculative execution.
16062 		 */
16063 		if (!env->bypass_spec_v1) {
16064 			err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
16065 							*insn_idx);
16066 			if (err < 0)
16067 				return err;
16068 		}
16069 		if (env->log.level & BPF_LOG_LEVEL)
16070 			print_insn_state(env, this_branch, this_branch->curframe);
16071 		return 0;
16072 	}
16073 
16074 	/* Push scalar registers sharing same ID to jump history,
16075 	 * do this before creating 'other_branch', so that both
16076 	 * 'this_branch' and 'other_branch' share this history
16077 	 * if parent state is created.
16078 	 */
16079 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16080 		collect_linked_regs(env, this_branch, src_reg->id, &linked_regs);
16081 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16082 		collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs);
16083 	if (linked_regs.cnt > 1) {
16084 		err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs));
16085 		if (err)
16086 			return err;
16087 	}
16088 
16089 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
16090 	if (IS_ERR(other_branch))
16091 		return PTR_ERR(other_branch);
16092 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16093 
16094 	err = regs_bounds_sanity_check_branches(env);
16095 	if (err)
16096 		return err;
16097 
16098 	*dst_reg = env->false_reg1;
16099 	*src_reg = env->false_reg2;
16100 	other_branch_regs[insn->dst_reg] = env->true_reg1;
16101 	if (BPF_SRC(insn->code) == BPF_X)
16102 		other_branch_regs[insn->src_reg] = env->true_reg2;
16103 
16104 	if (BPF_SRC(insn->code) == BPF_X &&
16105 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16106 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16107 		sync_linked_regs(env, this_branch, src_reg, &linked_regs);
16108 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg],
16109 				 &linked_regs);
16110 	}
16111 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16112 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16113 		sync_linked_regs(env, this_branch, dst_reg, &linked_regs);
16114 		sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg],
16115 				 &linked_regs);
16116 	}
16117 
16118 	/* if one pointer register is compared to another pointer
16119 	 * register check if PTR_MAYBE_NULL could be lifted.
16120 	 * E.g. register A - maybe null
16121 	 *      register B - not null
16122 	 * for JNE A, B, ... - A is not null in the false branch;
16123 	 * for JEQ A, B, ... - A is not null in the true branch.
16124 	 *
16125 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16126 	 * not need to be null checked by the BPF program, i.e.,
16127 	 * could be null even without PTR_MAYBE_NULL marking, so
16128 	 * only propagate nullness when neither reg is that type.
16129 	 */
16130 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16131 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16132 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16133 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16134 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16135 		eq_branch_regs = NULL;
16136 		switch (opcode) {
16137 		case BPF_JEQ:
16138 			eq_branch_regs = other_branch_regs;
16139 			break;
16140 		case BPF_JNE:
16141 			eq_branch_regs = regs;
16142 			break;
16143 		default:
16144 			/* do nothing */
16145 			break;
16146 		}
16147 		if (eq_branch_regs) {
16148 			if (type_may_be_null(src_reg->type))
16149 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16150 			else
16151 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16152 		}
16153 	}
16154 
16155 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16156 	 * Also does the same detection for a register whose the value is
16157 	 * known to be 0.
16158 	 * NOTE: these optimizations below are related with pointer comparison
16159 	 *       which will never be JMP32.
16160 	 */
16161 	if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16162 	    type_may_be_null(dst_reg->type) &&
16163 	    ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) ||
16164 	     (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) {
16165 		/* Mark all identical registers in each branch as either
16166 		 * safe or unknown depending R == 0 or R != 0 conditional.
16167 		 */
16168 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16169 				      opcode == BPF_JNE);
16170 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16171 				      opcode == BPF_JEQ);
16172 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16173 					   this_branch, other_branch) &&
16174 		   is_pointer_value(env, insn->dst_reg)) {
16175 		verbose(env, "R%d pointer comparison prohibited\n",
16176 			insn->dst_reg);
16177 		return -EACCES;
16178 	}
16179 	if (env->log.level & BPF_LOG_LEVEL)
16180 		print_insn_state(env, this_branch, this_branch->curframe);
16181 	return 0;
16182 }
16183 
16184 /* verify BPF_LD_IMM64 instruction */
16185 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16186 {
16187 	struct bpf_insn_aux_data *aux = cur_aux(env);
16188 	struct bpf_reg_state *regs = cur_regs(env);
16189 	struct bpf_reg_state *dst_reg;
16190 	struct bpf_map *map;
16191 	int err;
16192 
16193 	if (BPF_SIZE(insn->code) != BPF_DW) {
16194 		verbose(env, "invalid BPF_LD_IMM insn\n");
16195 		return -EINVAL;
16196 	}
16197 
16198 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16199 	if (err)
16200 		return err;
16201 
16202 	dst_reg = &regs[insn->dst_reg];
16203 	if (insn->src_reg == 0) {
16204 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16205 
16206 		dst_reg->type = SCALAR_VALUE;
16207 		__mark_reg_known(&regs[insn->dst_reg], imm);
16208 		return 0;
16209 	}
16210 
16211 	/* All special src_reg cases are listed below. From this point onwards
16212 	 * we either succeed and assign a corresponding dst_reg->type after
16213 	 * zeroing the offset, or fail and reject the program.
16214 	 */
16215 	mark_reg_known_zero(env, regs, insn->dst_reg);
16216 
16217 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16218 		dst_reg->type = aux->btf_var.reg_type;
16219 		switch (base_type(dst_reg->type)) {
16220 		case PTR_TO_MEM:
16221 			dst_reg->mem_size = aux->btf_var.mem_size;
16222 			break;
16223 		case PTR_TO_BTF_ID:
16224 			dst_reg->btf = aux->btf_var.btf;
16225 			dst_reg->btf_id = aux->btf_var.btf_id;
16226 			break;
16227 		default:
16228 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16229 			return -EFAULT;
16230 		}
16231 		return 0;
16232 	}
16233 
16234 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16235 		struct bpf_prog_aux *aux = env->prog->aux;
16236 		u32 subprogno = bpf_find_subprog(env,
16237 						 env->insn_idx + insn->imm + 1);
16238 
16239 		if (!aux->func_info) {
16240 			verbose(env, "missing btf func_info\n");
16241 			return -EINVAL;
16242 		}
16243 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16244 			verbose(env, "callback function not static\n");
16245 			return -EINVAL;
16246 		}
16247 
16248 		dst_reg->type = PTR_TO_FUNC;
16249 		dst_reg->subprogno = subprogno;
16250 		return 0;
16251 	}
16252 
16253 	map = env->used_maps[aux->map_index];
16254 
16255 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16256 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16257 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16258 			__mark_reg_unknown(env, dst_reg);
16259 			dst_reg->map_ptr = map;
16260 			return 0;
16261 		}
16262 		__mark_reg_known(dst_reg, aux->map_off);
16263 		dst_reg->type = PTR_TO_MAP_VALUE;
16264 		dst_reg->map_ptr = map;
16265 		WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
16266 			     map->max_entries != 1);
16267 		/* We want reg->id to be same (0) as map_value is not distinct */
16268 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16269 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16270 		dst_reg->type = CONST_PTR_TO_MAP;
16271 		dst_reg->map_ptr = map;
16272 	} else {
16273 		verifier_bug(env, "unexpected src reg value for ldimm64");
16274 		return -EFAULT;
16275 	}
16276 
16277 	return 0;
16278 }
16279 
16280 static bool may_access_skb(enum bpf_prog_type type)
16281 {
16282 	switch (type) {
16283 	case BPF_PROG_TYPE_SOCKET_FILTER:
16284 	case BPF_PROG_TYPE_SCHED_CLS:
16285 	case BPF_PROG_TYPE_SCHED_ACT:
16286 		return true;
16287 	default:
16288 		return false;
16289 	}
16290 }
16291 
16292 /* verify safety of LD_ABS|LD_IND instructions:
16293  * - they can only appear in the programs where ctx == skb
16294  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16295  *   preserve R6-R9, and store return value into R0
16296  *
16297  * Implicit input:
16298  *   ctx == skb == R6 == CTX
16299  *
16300  * Explicit input:
16301  *   SRC == any register
16302  *   IMM == 32-bit immediate
16303  *
16304  * Output:
16305  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16306  */
16307 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16308 {
16309 	struct bpf_reg_state *regs = cur_regs(env);
16310 	static const int ctx_reg = BPF_REG_6;
16311 	u8 mode = BPF_MODE(insn->code);
16312 	int i, err;
16313 
16314 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16315 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16316 		return -EINVAL;
16317 	}
16318 
16319 	if (!env->ops->gen_ld_abs) {
16320 		verifier_bug(env, "gen_ld_abs is null");
16321 		return -EFAULT;
16322 	}
16323 
16324 	/* check whether implicit source operand (register R6) is readable */
16325 	err = check_reg_arg(env, ctx_reg, SRC_OP);
16326 	if (err)
16327 		return err;
16328 
16329 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
16330 	 * gen_ld_abs() may terminate the program at runtime, leading to
16331 	 * reference leak.
16332 	 */
16333 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
16334 	if (err)
16335 		return err;
16336 
16337 	if (regs[ctx_reg].type != PTR_TO_CTX) {
16338 		verbose(env,
16339 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
16340 		return -EINVAL;
16341 	}
16342 
16343 	if (mode == BPF_IND) {
16344 		/* check explicit source operand */
16345 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16346 		if (err)
16347 			return err;
16348 	}
16349 
16350 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
16351 	if (err < 0)
16352 		return err;
16353 
16354 	/* reset caller saved regs to unreadable */
16355 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
16356 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
16357 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
16358 	}
16359 
16360 	/* mark destination R0 register as readable, since it contains
16361 	 * the value fetched from the packet.
16362 	 * Already marked as written above.
16363 	 */
16364 	mark_reg_unknown(env, regs, BPF_REG_0);
16365 	/* ld_abs load up to 32-bit skb data. */
16366 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
16367 	/*
16368 	 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0
16369 	 * which must be explored by the verifier when in a subprog.
16370 	 */
16371 	if (env->cur_state->curframe) {
16372 		struct bpf_verifier_state *branch;
16373 
16374 		mark_reg_scratched(env, BPF_REG_0);
16375 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
16376 		if (IS_ERR(branch))
16377 			return PTR_ERR(branch);
16378 		mark_reg_known_zero(env, regs, BPF_REG_0);
16379 		err = prepare_func_exit(env, &env->insn_idx);
16380 		if (err)
16381 			return err;
16382 		env->insn_idx--;
16383 	}
16384 	return 0;
16385 }
16386 
16387 
16388 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range)
16389 {
16390 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16391 
16392 	/* Default return value range. */
16393 	*range = retval_range(0, 1);
16394 
16395 	switch (prog_type) {
16396 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
16397 		switch (env->prog->expected_attach_type) {
16398 		case BPF_CGROUP_UDP4_RECVMSG:
16399 		case BPF_CGROUP_UDP6_RECVMSG:
16400 		case BPF_CGROUP_UNIX_RECVMSG:
16401 		case BPF_CGROUP_INET4_GETPEERNAME:
16402 		case BPF_CGROUP_INET6_GETPEERNAME:
16403 		case BPF_CGROUP_UNIX_GETPEERNAME:
16404 		case BPF_CGROUP_INET4_GETSOCKNAME:
16405 		case BPF_CGROUP_INET6_GETSOCKNAME:
16406 		case BPF_CGROUP_UNIX_GETSOCKNAME:
16407 			*range = retval_range(1, 1);
16408 			break;
16409 		case BPF_CGROUP_INET4_BIND:
16410 		case BPF_CGROUP_INET6_BIND:
16411 			*range = retval_range(0, 3);
16412 			break;
16413 		default:
16414 			break;
16415 		}
16416 		break;
16417 	case BPF_PROG_TYPE_CGROUP_SKB:
16418 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)
16419 			*range = retval_range(0, 3);
16420 		break;
16421 	case BPF_PROG_TYPE_CGROUP_SOCK:
16422 	case BPF_PROG_TYPE_SOCK_OPS:
16423 	case BPF_PROG_TYPE_CGROUP_DEVICE:
16424 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
16425 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
16426 		break;
16427 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
16428 		if (!env->prog->aux->attach_btf_id)
16429 			return false;
16430 		*range = retval_range(0, 0);
16431 		break;
16432 	case BPF_PROG_TYPE_TRACING:
16433 		switch (env->prog->expected_attach_type) {
16434 		case BPF_TRACE_FENTRY:
16435 		case BPF_TRACE_FEXIT:
16436 		case BPF_TRACE_FSESSION:
16437 		case BPF_TRACE_FENTRY_MULTI:
16438 		case BPF_TRACE_FEXIT_MULTI:
16439 		case BPF_TRACE_FSESSION_MULTI:
16440 			*range = retval_range(0, 0);
16441 			break;
16442 		case BPF_TRACE_RAW_TP:
16443 		case BPF_MODIFY_RETURN:
16444 			return false;
16445 		case BPF_TRACE_ITER:
16446 		default:
16447 			break;
16448 		}
16449 		break;
16450 	case BPF_PROG_TYPE_KPROBE:
16451 		switch (env->prog->expected_attach_type) {
16452 		case BPF_TRACE_KPROBE_SESSION:
16453 		case BPF_TRACE_UPROBE_SESSION:
16454 			break;
16455 		default:
16456 			return false;
16457 		}
16458 		break;
16459 	case BPF_PROG_TYPE_SK_LOOKUP:
16460 		*range = retval_range(SK_DROP, SK_PASS);
16461 		break;
16462 
16463 	case BPF_PROG_TYPE_LSM:
16464 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
16465 			/* no range found, any return value is allowed */
16466 			if (!get_func_retval_range(env->prog, range))
16467 				return false;
16468 			/* no restricted range, any return value is allowed */
16469 			if (range->minval == S32_MIN && range->maxval == S32_MAX)
16470 				return false;
16471 			range->return_32bit = true;
16472 		} else if (!env->prog->aux->attach_func_proto->type) {
16473 			/* Make sure programs that attach to void
16474 			 * hooks don't try to modify return value.
16475 			 */
16476 			*range = retval_range(1, 1);
16477 		}
16478 		break;
16479 
16480 	case BPF_PROG_TYPE_NETFILTER:
16481 		*range = retval_range(NF_DROP, NF_ACCEPT);
16482 		break;
16483 	case BPF_PROG_TYPE_STRUCT_OPS:
16484 		*range = retval_range(0, 0);
16485 		break;
16486 	case BPF_PROG_TYPE_EXT:
16487 		/* freplace program can return anything as its return value
16488 		 * depends on the to-be-replaced kernel func or bpf program.
16489 		 */
16490 	default:
16491 		return false;
16492 	}
16493 
16494 	/* Continue calculating. */
16495 
16496 	return true;
16497 }
16498 
16499 static bool program_returns_void(struct bpf_verifier_env *env)
16500 {
16501 	const struct bpf_prog *prog = env->prog;
16502 	enum bpf_prog_type prog_type = prog->type;
16503 
16504 	switch (prog_type) {
16505 	case BPF_PROG_TYPE_LSM:
16506 		/* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */
16507 		if (prog->expected_attach_type != BPF_LSM_CGROUP &&
16508 		    !prog->aux->attach_func_proto->type)
16509 			return true;
16510 		break;
16511 	case BPF_PROG_TYPE_STRUCT_OPS:
16512 		if (!prog->aux->attach_func_proto->type)
16513 			return true;
16514 		break;
16515 	case BPF_PROG_TYPE_EXT:
16516 		/*
16517 		 * If the actual program is an extension, let it
16518 		 * return void - attaching will succeed only if the
16519 		 * program being replaced also returns void, and since
16520 		 * it has passed verification its actual type doesn't matter.
16521 		 */
16522 		if (subprog_returns_void(env, 0))
16523 			return true;
16524 		break;
16525 	default:
16526 		break;
16527 	}
16528 	return false;
16529 }
16530 
16531 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
16532 {
16533 	const char *exit_ctx = "At program exit";
16534 	struct tnum enforce_attach_type_range = tnum_unknown;
16535 	const struct bpf_prog *prog = env->prog;
16536 	struct bpf_reg_state *reg = reg_state(env, regno);
16537 	struct bpf_retval_range range = retval_range(0, 1);
16538 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
16539 	struct bpf_func_state *frame = env->cur_state->frame[0];
16540 	const struct btf_type *reg_type, *ret_type = NULL;
16541 	int err;
16542 
16543 	/* LSM and struct_ops func-ptr's return type could be "void" */
16544 	if (!frame->in_async_callback_fn && program_returns_void(env))
16545 		return 0;
16546 
16547 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) {
16548 		/* Allow a struct_ops program to return a referenced kptr if it
16549 		 * matches the operator's return type and is in its unmodified
16550 		 * form. A scalar zero (i.e., a null pointer) is also allowed.
16551 		 */
16552 		reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
16553 		ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
16554 						prog->aux->attach_func_proto->type,
16555 						NULL);
16556 		if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg))
16557 			return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false);
16558 	}
16559 
16560 	/* eBPF calling convention is such that R0 is used
16561 	 * to return the value from eBPF program.
16562 	 * Make sure that it's readable at this time
16563 	 * of bpf_exit, which means that program wrote
16564 	 * something into it earlier
16565 	 */
16566 	err = check_reg_arg(env, regno, SRC_OP);
16567 	if (err)
16568 		return err;
16569 
16570 	if (is_pointer_value(env, regno)) {
16571 		verbose(env, "R%d leaks addr as return value\n", regno);
16572 		return -EACCES;
16573 	}
16574 
16575 	if (frame->in_async_callback_fn) {
16576 		exit_ctx = "At async callback return";
16577 		range = frame->callback_ret_range;
16578 		goto enforce_retval;
16579 	}
16580 
16581 	if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
16582 		return 0;
16583 
16584 	if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS))
16585 		enforce_attach_type_range = tnum_range(2, 3);
16586 
16587 	if (!return_retval_range(env, &range))
16588 		return 0;
16589 
16590 enforce_retval:
16591 	if (reg->type != SCALAR_VALUE) {
16592 		verbose(env, "%s the register R%d is not a known value (%s)\n",
16593 			exit_ctx, regno, reg_type_str(env, reg->type));
16594 		return -EINVAL;
16595 	}
16596 
16597 	err = mark_chain_precision(env, regno);
16598 	if (err)
16599 		return err;
16600 
16601 	if (!retval_range_within(range, reg)) {
16602 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
16603 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
16604 		    prog_type == BPF_PROG_TYPE_LSM &&
16605 		    !prog->aux->attach_func_proto->type)
16606 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
16607 		return -EINVAL;
16608 	}
16609 
16610 	if (!tnum_is_unknown(enforce_attach_type_range) &&
16611 	    tnum_in(enforce_attach_type_range, reg->var_off))
16612 		env->prog->enforce_expected_attach_type = 1;
16613 	return 0;
16614 }
16615 
16616 static int check_global_subprog_return_code(struct bpf_verifier_env *env)
16617 {
16618 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
16619 	struct bpf_func_state *cur_frame = cur_func(env);
16620 	int err;
16621 
16622 	if (subprog_returns_void(env, cur_frame->subprogno))
16623 		return 0;
16624 
16625 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
16626 	if (err)
16627 		return err;
16628 
16629 	/* Pointers to arena are safe to pass between subprograms. */
16630 	if (is_arena_reg(env, BPF_REG_0))
16631 		return 0;
16632 
16633 	if (is_pointer_value(env, BPF_REG_0)) {
16634 		verbose(env, "R%d leaks addr as return value\n", BPF_REG_0);
16635 		return -EACCES;
16636 	}
16637 
16638 	if (reg->type != SCALAR_VALUE) {
16639 		verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
16640 			reg_type_str(env, reg->type));
16641 		return -EINVAL;
16642 	}
16643 
16644 	return 0;
16645 }
16646 
16647 /* Bitmask with 1s for all caller saved registers */
16648 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16649 
16650 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16651  * replacement patch is presumed to follow bpf_fastcall contract
16652  * (see mark_fastcall_pattern_for_call() below).
16653  */
16654 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16655 {
16656 	switch (imm) {
16657 #ifdef CONFIG_X86_64
16658 	case BPF_FUNC_get_smp_processor_id:
16659 #ifdef CONFIG_SMP
16660 	case BPF_FUNC_get_current_task_btf:
16661 	case BPF_FUNC_get_current_task:
16662 #endif
16663 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16664 #endif
16665 	default:
16666 		return false;
16667 	}
16668 }
16669 
16670 /* If @call is a kfunc or helper call, fills @cs and returns true,
16671  * otherwise returns false.
16672  */
16673 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
16674 			  struct bpf_call_summary *cs)
16675 {
16676 	struct bpf_kfunc_call_arg_meta meta;
16677 	const struct bpf_func_proto *fn;
16678 	int i;
16679 
16680 	if (bpf_helper_call(call)) {
16681 
16682 		if (bpf_get_helper_proto(env, call->imm, &fn) < 0)
16683 			/* error would be reported later */
16684 			return false;
16685 		cs->fastcall = fn->allow_fastcall &&
16686 			       (bpf_verifier_inlines_helper_call(env, call->imm) ||
16687 				bpf_jit_inlines_helper_call(call->imm));
16688 		cs->is_void = fn->ret_type == RET_VOID;
16689 		cs->num_params = 0;
16690 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
16691 			if (fn->arg_type[i] == ARG_DONTCARE)
16692 				break;
16693 			cs->num_params++;
16694 		}
16695 		return true;
16696 	}
16697 
16698 	if (bpf_pseudo_kfunc_call(call)) {
16699 		int err;
16700 
16701 		err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta);
16702 		if (err < 0)
16703 			/* error would be reported later */
16704 			return false;
16705 		cs->num_params = btf_type_vlen(meta.func_proto);
16706 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
16707 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
16708 		return true;
16709 	}
16710 
16711 	return false;
16712 }
16713 
16714 /* LLVM define a bpf_fastcall function attribute.
16715  * This attribute means that function scratches only some of
16716  * the caller saved registers defined by ABI.
16717  * For BPF the set of such registers could be defined as follows:
16718  * - R0 is scratched only if function is non-void;
16719  * - R1-R5 are scratched only if corresponding parameter type is defined
16720  *   in the function prototype.
16721  *
16722  * The contract between kernel and clang allows to simultaneously use
16723  * such functions and maintain backwards compatibility with old
16724  * kernels that don't understand bpf_fastcall calls:
16725  *
16726  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16727  *   registers are not scratched by the call;
16728  *
16729  * - as a post-processing step, clang visits each bpf_fastcall call and adds
16730  *   spill/fill for every live r0-r5;
16731  *
16732  * - stack offsets used for the spill/fill are allocated as lowest
16733  *   stack offsets in whole function and are not used for any other
16734  *   purposes;
16735  *
16736  * - when kernel loads a program, it looks for such patterns
16737  *   (bpf_fastcall function surrounded by spills/fills) and checks if
16738  *   spill/fill stack offsets are used exclusively in fastcall patterns;
16739  *
16740  * - if so, and if verifier or current JIT inlines the call to the
16741  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16742  *   spill/fill pairs;
16743  *
16744  * - when old kernel loads a program, presence of spill/fill pairs
16745  *   keeps BPF program valid, albeit slightly less efficient.
16746  *
16747  * For example:
16748  *
16749  *   r1 = 1;
16750  *   r2 = 2;
16751  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16752  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
16753  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16754  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
16755  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
16756  *   r0 = r1;                            exit;
16757  *   r0 += r2;
16758  *   exit;
16759  *
16760  * The purpose of mark_fastcall_pattern_for_call is to:
16761  * - look for such patterns;
16762  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16763  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16764  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16765  *   at which bpf_fastcall spill/fill stack slots start;
16766  * - update env->subprog_info[*]->keep_fastcall_stack.
16767  *
16768  * The .fastcall_pattern and .fastcall_stack_off are used by
16769  * check_fastcall_stack_contract() to check if every stack access to
16770  * fastcall spill/fill stack slot originates from spill/fill
16771  * instructions, members of fastcall patterns.
16772  *
16773  * If such condition holds true for a subprogram, fastcall patterns could
16774  * be rewritten by remove_fastcall_spills_fills().
16775  * Otherwise bpf_fastcall patterns are not changed in the subprogram
16776  * (code, presumably, generated by an older clang version).
16777  *
16778  * For example, it is *not* safe to remove spill/fill below:
16779  *
16780  *   r1 = 1;
16781  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
16782  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
16783  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
16784  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
16785  *   r0 += r1;                           exit;
16786  *   exit;
16787  */
16788 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16789 					   struct bpf_subprog_info *subprog,
16790 					   int insn_idx, s16 lowest_off)
16791 {
16792 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16793 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16794 	u32 clobbered_regs_mask;
16795 	struct bpf_call_summary cs;
16796 	u32 expected_regs_mask;
16797 	s16 off;
16798 	int i;
16799 
16800 	if (!bpf_get_call_summary(env, call, &cs))
16801 		return;
16802 
16803 	/* A bitmask specifying which caller saved registers are clobbered
16804 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
16805 	 * bpf_fastcall contract:
16806 	 * - includes R0 if function is non-void;
16807 	 * - includes R1-R5 if corresponding parameter has is described
16808 	 *   in the function prototype.
16809 	 */
16810 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
16811 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16812 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16813 
16814 	/* match pairs of form:
16815 	 *
16816 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
16817 	 * ...
16818 	 * call %[to_be_inlined]
16819 	 * ...
16820 	 * rX = *(u64 *)(r10 - Y)
16821 	 */
16822 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16823 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16824 			break;
16825 		stx = &insns[insn_idx - i];
16826 		ldx = &insns[insn_idx + i];
16827 		/* must be a stack spill/fill pair */
16828 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16829 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16830 		    stx->dst_reg != BPF_REG_10 ||
16831 		    ldx->src_reg != BPF_REG_10)
16832 			break;
16833 		/* must be a spill/fill for the same reg */
16834 		if (stx->src_reg != ldx->dst_reg)
16835 			break;
16836 		/* must be one of the previously unseen registers */
16837 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16838 			break;
16839 		/* must be a spill/fill for the same expected offset,
16840 		 * no need to check offset alignment, BPF_DW stack access
16841 		 * is always 8-byte aligned.
16842 		 */
16843 		if (stx->off != off || ldx->off != off)
16844 			break;
16845 		expected_regs_mask &= ~BIT(stx->src_reg);
16846 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16847 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16848 	}
16849 	if (i == 1)
16850 		return;
16851 
16852 	/* Conditionally set 'fastcall_spills_num' to allow forward
16853 	 * compatibility when more helper functions are marked as
16854 	 * bpf_fastcall at compile time than current kernel supports, e.g:
16855 	 *
16856 	 *   1: *(u64 *)(r10 - 8) = r1
16857 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
16858 	 *   3: r1 = *(u64 *)(r10 - 8)
16859 	 *   4: *(u64 *)(r10 - 8) = r1
16860 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
16861 	 *   6: r1 = *(u64 *)(r10 - 8)
16862 	 *
16863 	 * There is no need to block bpf_fastcall rewrite for such program.
16864 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16865 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16866 	 * does not remove spill/fill pair {4,6}.
16867 	 */
16868 	if (cs.fastcall)
16869 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16870 	else
16871 		subprog->keep_fastcall_stack = 1;
16872 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16873 }
16874 
16875 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16876 {
16877 	struct bpf_subprog_info *subprog = env->subprog_info;
16878 	struct bpf_insn *insn;
16879 	s16 lowest_off;
16880 	int s, i;
16881 
16882 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16883 		/* find lowest stack spill offset used in this subprog */
16884 		lowest_off = 0;
16885 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16886 			insn = env->prog->insnsi + i;
16887 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16888 			    insn->dst_reg != BPF_REG_10)
16889 				continue;
16890 			lowest_off = min(lowest_off, insn->off);
16891 		}
16892 		/* use this offset to find fastcall patterns */
16893 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16894 			insn = env->prog->insnsi + i;
16895 			if (insn->code != (BPF_JMP | BPF_CALL))
16896 				continue;
16897 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16898 		}
16899 	}
16900 	return 0;
16901 }
16902 
16903 static void adjust_btf_func(struct bpf_verifier_env *env)
16904 {
16905 	struct bpf_prog_aux *aux = env->prog->aux;
16906 	int i;
16907 
16908 	if (!aux->func_info)
16909 		return;
16910 
16911 	/* func_info is not available for hidden subprogs */
16912 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16913 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16914 }
16915 
16916 /* Find id in idset and increment its count, or add new entry */
16917 static void idset_cnt_inc(struct bpf_idset *idset, u32 id)
16918 {
16919 	u32 i;
16920 
16921 	for (i = 0; i < idset->num_ids; i++) {
16922 		if (idset->entries[i].id == id) {
16923 			idset->entries[i].cnt++;
16924 			return;
16925 		}
16926 	}
16927 	/* New id */
16928 	if (idset->num_ids < BPF_ID_MAP_SIZE) {
16929 		idset->entries[idset->num_ids].id = id;
16930 		idset->entries[idset->num_ids].cnt = 1;
16931 		idset->num_ids++;
16932 	}
16933 }
16934 
16935 /* Find id in idset and return its count, or 0 if not found */
16936 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id)
16937 {
16938 	u32 i;
16939 
16940 	for (i = 0; i < idset->num_ids; i++) {
16941 		if (idset->entries[i].id == id)
16942 			return idset->entries[i].cnt;
16943 	}
16944 	return 0;
16945 }
16946 
16947 /*
16948  * Clear singular scalar ids in a state.
16949  * A register with a non-zero id is called singular if no other register shares
16950  * the same base id. Such registers can be treated as independent (id=0).
16951  */
16952 void bpf_clear_singular_ids(struct bpf_verifier_env *env,
16953 			    struct bpf_verifier_state *st)
16954 {
16955 	struct bpf_idset *idset = &env->idset_scratch;
16956 	struct bpf_func_state *func;
16957 	struct bpf_reg_state *reg;
16958 
16959 	idset->num_ids = 0;
16960 
16961 	bpf_for_each_reg_in_vstate(st, func, reg, ({
16962 		if (reg->type != SCALAR_VALUE)
16963 			continue;
16964 		if (!reg->id)
16965 			continue;
16966 		idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST);
16967 	}));
16968 
16969 	bpf_for_each_reg_in_vstate(st, func, reg, ({
16970 		if (reg->type != SCALAR_VALUE)
16971 			continue;
16972 		if (!reg->id)
16973 			continue;
16974 		if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1)
16975 			clear_scalar_id(reg);
16976 	}));
16977 }
16978 
16979 /* Return true if it's OK to have the same insn return a different type. */
16980 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16981 {
16982 	switch (base_type(type)) {
16983 	case PTR_TO_CTX:
16984 	case PTR_TO_SOCKET:
16985 	case PTR_TO_SOCK_COMMON:
16986 	case PTR_TO_TCP_SOCK:
16987 	case PTR_TO_XDP_SOCK:
16988 	case PTR_TO_BTF_ID:
16989 	case PTR_TO_ARENA:
16990 		return false;
16991 	default:
16992 		return true;
16993 	}
16994 }
16995 
16996 /* If an instruction was previously used with particular pointer types, then we
16997  * need to be careful to avoid cases such as the below, where it may be ok
16998  * for one branch accessing the pointer, but not ok for the other branch:
16999  *
17000  * R1 = sock_ptr
17001  * goto X;
17002  * ...
17003  * R1 = some_other_valid_ptr;
17004  * goto X;
17005  * ...
17006  * R2 = *(u32 *)(R1 + 0);
17007  */
17008 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17009 {
17010 	return src != prev && (!reg_type_mismatch_ok(src) ||
17011 			       !reg_type_mismatch_ok(prev));
17012 }
17013 
17014 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
17015 {
17016 	switch (base_type(type)) {
17017 	case PTR_TO_MEM:
17018 	case PTR_TO_BTF_ID:
17019 		return true;
17020 	default:
17021 		return false;
17022 	}
17023 }
17024 
17025 static bool is_ptr_to_mem(enum bpf_reg_type type)
17026 {
17027 	return base_type(type) == PTR_TO_MEM;
17028 }
17029 
17030 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17031 			     bool allow_trust_mismatch)
17032 {
17033 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17034 	enum bpf_reg_type merged_type;
17035 
17036 	if (*prev_type == NOT_INIT) {
17037 		/* Saw a valid insn
17038 		 * dst_reg = *(u32 *)(src_reg + off)
17039 		 * save type to validate intersecting paths
17040 		 */
17041 		*prev_type = type;
17042 	} else if (reg_type_mismatch(type, *prev_type)) {
17043 		/* Abuser program is trying to use the same insn
17044 		 * dst_reg = *(u32*) (src_reg + off)
17045 		 * with different pointer types:
17046 		 * src_reg == ctx in one branch and
17047 		 * src_reg == stack|map in some other branch.
17048 		 * Reject it.
17049 		 */
17050 		if (allow_trust_mismatch &&
17051 		    is_ptr_to_mem_or_btf_id(type) &&
17052 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
17053 			/*
17054 			 * Have to support a use case when one path through
17055 			 * the program yields TRUSTED pointer while another
17056 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17057 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17058 			 * Same behavior of MEM_RDONLY flag.
17059 			 */
17060 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
17061 				merged_type = PTR_TO_MEM;
17062 			else
17063 				merged_type = PTR_TO_BTF_ID;
17064 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
17065 				merged_type |= PTR_UNTRUSTED;
17066 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
17067 				merged_type |= MEM_RDONLY;
17068 			*prev_type = merged_type;
17069 		} else {
17070 			verbose(env, "same insn cannot be used with different pointers\n");
17071 			return -EINVAL;
17072 		}
17073 	}
17074 
17075 	return 0;
17076 }
17077 
17078 enum {
17079 	PROCESS_BPF_EXIT = 1,
17080 	INSN_IDX_UPDATED = 2,
17081 };
17082 
17083 static int process_bpf_exit_full(struct bpf_verifier_env *env,
17084 				 bool *do_print_state,
17085 				 bool exception_exit)
17086 {
17087 	struct bpf_func_state *cur_frame = cur_func(env);
17088 
17089 	/* We must do check_reference_leak here before
17090 	 * prepare_func_exit to handle the case when
17091 	 * state->curframe > 0, it may be a callback function,
17092 	 * for which reference_state must match caller reference
17093 	 * state when it exits.
17094 	 */
17095 	int err = check_resource_leak(env, exception_exit,
17096 				      exception_exit || !env->cur_state->curframe,
17097 				      exception_exit ? "bpf_throw" :
17098 				      "BPF_EXIT instruction in main prog");
17099 	if (err)
17100 		return err;
17101 
17102 	/* The side effect of the prepare_func_exit which is
17103 	 * being skipped is that it frees bpf_func_state.
17104 	 * Typically, process_bpf_exit will only be hit with
17105 	 * outermost exit. copy_verifier_state in pop_stack will
17106 	 * handle freeing of any extra bpf_func_state left over
17107 	 * from not processing all nested function exits. We
17108 	 * also skip return code checks as they are not needed
17109 	 * for exceptional exits.
17110 	 */
17111 	if (exception_exit)
17112 		return PROCESS_BPF_EXIT;
17113 
17114 	if (env->cur_state->curframe) {
17115 		/* exit from nested function */
17116 		err = prepare_func_exit(env, &env->insn_idx);
17117 		if (err)
17118 			return err;
17119 		*do_print_state = true;
17120 		return INSN_IDX_UPDATED;
17121 	}
17122 
17123 	/*
17124 	 * Return from a regular global subprogram differs from return
17125 	 * from the main program or async/exception callback.
17126 	 * Main program exit implies return code restrictions
17127 	 * that depend on program type.
17128 	 * Exit from exception callback is equivalent to main program exit.
17129 	 * Exit from async callback implies return code restrictions
17130 	 * that depend on async scheduling mechanism.
17131 	 */
17132 	if (cur_frame->subprogno &&
17133 	    !cur_frame->in_async_callback_fn &&
17134 	    !cur_frame->in_exception_callback_fn)
17135 		err = check_global_subprog_return_code(env);
17136 	else
17137 		err = check_return_code(env, BPF_REG_0, "R0");
17138 	if (err)
17139 		return err;
17140 	return PROCESS_BPF_EXIT;
17141 }
17142 
17143 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
17144 				       int regno,
17145 				       struct bpf_map *map,
17146 				       u32 *pmin_index, u32 *pmax_index)
17147 {
17148 	struct bpf_reg_state *reg = reg_state(env, regno);
17149 	u64 min_index = reg_umin(reg);
17150 	u64 max_index = reg_umax(reg);
17151 	const u32 size = 8;
17152 
17153 	if (min_index > (u64) U32_MAX * size) {
17154 		verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg));
17155 		return -ERANGE;
17156 	}
17157 	if (max_index > (u64) U32_MAX * size) {
17158 		verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg));
17159 		return -ERANGE;
17160 	}
17161 
17162 	min_index /= size;
17163 	max_index /= size;
17164 
17165 	if (max_index >= map->max_entries) {
17166 		verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
17167 			     regno, min_index, max_index, map->max_entries);
17168 		return -EINVAL;
17169 	}
17170 
17171 	*pmin_index = min_index;
17172 	*pmax_index = max_index;
17173 	return 0;
17174 }
17175 
17176 /* gotox *dst_reg */
17177 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
17178 {
17179 	struct bpf_verifier_state *other_branch;
17180 	struct bpf_reg_state *dst_reg;
17181 	struct bpf_map *map;
17182 	u32 min_index, max_index;
17183 	int err = 0;
17184 	int n;
17185 	int i;
17186 
17187 	dst_reg = reg_state(env, insn->dst_reg);
17188 	if (dst_reg->type != PTR_TO_INSN) {
17189 		verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
17190 			     insn->dst_reg, reg_type_str(env, dst_reg->type));
17191 		return -EINVAL;
17192 	}
17193 
17194 	map = dst_reg->map_ptr;
17195 	if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
17196 		return -EFAULT;
17197 
17198 	if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
17199 			    "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
17200 		return -EFAULT;
17201 
17202 	err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
17203 	if (err)
17204 		return err;
17205 
17206 	/* Ensure that the buffer is large enough */
17207 	if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
17208 		env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf,
17209 						        max_index - min_index + 1);
17210 		if (!env->gotox_tmp_buf)
17211 			return -ENOMEM;
17212 	}
17213 
17214 	n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
17215 	if (n < 0)
17216 		return n;
17217 	if (n == 0) {
17218 		verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
17219 			     insn->dst_reg, map->id);
17220 		return -EINVAL;
17221 	}
17222 
17223 	for (i = 0; i < n - 1; i++) {
17224 		mark_indirect_target(env, env->gotox_tmp_buf->items[i]);
17225 		other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
17226 					  env->insn_idx, env->cur_state->speculative);
17227 		if (IS_ERR(other_branch))
17228 			return PTR_ERR(other_branch);
17229 	}
17230 	env->insn_idx = env->gotox_tmp_buf->items[n-1];
17231 	mark_indirect_target(env, env->insn_idx);
17232 	return INSN_IDX_UPDATED;
17233 }
17234 
17235 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
17236 {
17237 	int err;
17238 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
17239 	u8 class = BPF_CLASS(insn->code);
17240 
17241 	switch (class) {
17242 	case BPF_ALU:
17243 	case BPF_ALU64:
17244 		return check_alu_op(env, insn);
17245 
17246 	case BPF_LDX:
17247 		return check_load_mem(env, insn, false,
17248 				      BPF_MODE(insn->code) == BPF_MEMSX,
17249 				      true, "ldx");
17250 
17251 	case BPF_STX:
17252 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
17253 			return check_atomic(env, insn);
17254 		return check_store_reg(env, insn, false);
17255 
17256 	case BPF_ST: {
17257 		/* Handle stack arg write (store immediate) */
17258 		if (is_stack_arg_st(insn)) {
17259 			struct bpf_verifier_state *vstate = env->cur_state;
17260 			struct bpf_func_state *state = vstate->frame[vstate->curframe];
17261 
17262 			return check_stack_arg_write(env, state, insn->off, NULL);
17263 		}
17264 
17265 		enum bpf_reg_type dst_reg_type;
17266 
17267 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17268 		if (err)
17269 			return err;
17270 
17271 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
17272 
17273 		err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg),
17274 				       insn->off, BPF_SIZE(insn->code),
17275 				       BPF_WRITE, -1, false, false);
17276 		if (err)
17277 			return err;
17278 
17279 		return save_aux_ptr_type(env, dst_reg_type, false);
17280 	}
17281 	case BPF_JMP:
17282 	case BPF_JMP32: {
17283 		u8 opcode = BPF_OP(insn->code);
17284 
17285 		env->jmps_processed++;
17286 		if (opcode == BPF_CALL) {
17287 			if (env->cur_state->active_locks) {
17288 				if ((insn->src_reg == BPF_REG_0 &&
17289 				     insn->imm != BPF_FUNC_spin_unlock &&
17290 				     insn->imm != BPF_FUNC_kptr_xchg) ||
17291 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17292 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
17293 					verbose(env,
17294 						"function calls are not allowed while holding a lock\n");
17295 					return -EINVAL;
17296 				}
17297 			}
17298 			mark_reg_scratched(env, BPF_REG_0);
17299 			if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno]))
17300 				cur_func(env)->no_stack_arg_load = true;
17301 			if (insn->src_reg == BPF_PSEUDO_CALL)
17302 				return check_func_call(env, insn, &env->insn_idx);
17303 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17304 				return check_kfunc_call(env, insn, &env->insn_idx);
17305 			return check_helper_call(env, insn, &env->insn_idx);
17306 		} else if (opcode == BPF_JA) {
17307 			if (BPF_SRC(insn->code) == BPF_X)
17308 				return check_indirect_jump(env, insn);
17309 
17310 			if (class == BPF_JMP)
17311 				env->insn_idx += insn->off + 1;
17312 			else
17313 				env->insn_idx += insn->imm + 1;
17314 			return INSN_IDX_UPDATED;
17315 		} else if (opcode == BPF_EXIT) {
17316 			return process_bpf_exit_full(env, do_print_state, false);
17317 		}
17318 		return check_cond_jmp_op(env, insn, &env->insn_idx);
17319 	}
17320 	case BPF_LD: {
17321 		u8 mode = BPF_MODE(insn->code);
17322 
17323 		if (mode == BPF_ABS || mode == BPF_IND)
17324 			return check_ld_abs(env, insn);
17325 
17326 		if (mode == BPF_IMM) {
17327 			err = check_ld_imm(env, insn);
17328 			if (err)
17329 				return err;
17330 
17331 			env->insn_idx++;
17332 			sanitize_mark_insn_seen(env);
17333 		}
17334 		return 0;
17335 	}
17336 	}
17337 	/* all class values are handled above. silence compiler warning */
17338 	return -EFAULT;
17339 }
17340 
17341 static int do_check(struct bpf_verifier_env *env)
17342 {
17343 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17344 	struct bpf_verifier_state *state = env->cur_state;
17345 	struct bpf_insn *insns = env->prog->insnsi;
17346 	int insn_cnt = env->prog->len;
17347 	bool do_print_state = false;
17348 	int prev_insn_idx = -1;
17349 
17350 	for (;;) {
17351 		struct bpf_insn *insn;
17352 		struct bpf_insn_aux_data *insn_aux;
17353 		int err;
17354 
17355 		/* reset current history entry on each new instruction */
17356 		env->cur_hist_ent = NULL;
17357 
17358 		env->prev_insn_idx = prev_insn_idx;
17359 		if (env->insn_idx >= insn_cnt) {
17360 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17361 				env->insn_idx, insn_cnt);
17362 			return -EFAULT;
17363 		}
17364 
17365 		insn = &insns[env->insn_idx];
17366 		insn_aux = &env->insn_aux_data[env->insn_idx];
17367 
17368 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17369 			verbose(env,
17370 				"BPF program is too large. Processed %d insn\n",
17371 				env->insn_processed);
17372 			return -E2BIG;
17373 		}
17374 
17375 		state->last_insn_idx = env->prev_insn_idx;
17376 		state->insn_idx = env->insn_idx;
17377 
17378 		if (bpf_is_prune_point(env, env->insn_idx)) {
17379 			err = bpf_is_state_visited(env, env->insn_idx);
17380 			if (err < 0)
17381 				return err;
17382 			if (err == 1) {
17383 				/* found equivalent state, can prune the search */
17384 				if (env->log.level & BPF_LOG_LEVEL) {
17385 					if (do_print_state)
17386 						verbose(env, "\nfrom %d to %d%s: safe\n",
17387 							env->prev_insn_idx, env->insn_idx,
17388 							env->cur_state->speculative ?
17389 							" (speculative execution)" : "");
17390 					else
17391 						verbose(env, "%d: safe\n", env->insn_idx);
17392 				}
17393 				goto process_bpf_exit;
17394 			}
17395 		}
17396 
17397 		if (bpf_is_jmp_point(env, env->insn_idx)) {
17398 			err = bpf_push_jmp_history(env, state, 0, 0, 0, 0);
17399 			if (err)
17400 				return err;
17401 		}
17402 
17403 		if (signal_pending(current))
17404 			return -EAGAIN;
17405 
17406 		if (need_resched())
17407 			cond_resched();
17408 
17409 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17410 			verbose(env, "\nfrom %d to %d%s:",
17411 				env->prev_insn_idx, env->insn_idx,
17412 				env->cur_state->speculative ?
17413 				" (speculative execution)" : "");
17414 			print_verifier_state(env, state, state->curframe, true);
17415 			do_print_state = false;
17416 		}
17417 
17418 		if (env->log.level & BPF_LOG_LEVEL) {
17419 			if (verifier_state_scratched(env))
17420 				print_insn_state(env, state, state->curframe);
17421 
17422 			verbose_linfo(env, env->insn_idx, "; ");
17423 			env->prev_log_pos = env->log.end_pos;
17424 			verbose(env, "%d: ", env->insn_idx);
17425 			bpf_verbose_insn(env, insn);
17426 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17427 			env->prev_log_pos = env->log.end_pos;
17428 		}
17429 
17430 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17431 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17432 							   env->prev_insn_idx);
17433 			if (err)
17434 				return err;
17435 		}
17436 
17437 		sanitize_mark_insn_seen(env);
17438 		prev_insn_idx = env->insn_idx;
17439 
17440 		/* Sanity check: precomputed constants must match verifier state */
17441 		if (!state->speculative && insn_aux->const_reg_mask) {
17442 			struct bpf_reg_state *regs = cur_regs(env);
17443 			u16 mask = insn_aux->const_reg_mask;
17444 
17445 			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
17446 				u32 cval = insn_aux->const_reg_vals[r];
17447 
17448 				if (!(mask & BIT(r)))
17449 					continue;
17450 				if (regs[r].type != SCALAR_VALUE)
17451 					continue;
17452 				if (!tnum_is_const(regs[r].var_off))
17453 					continue;
17454 				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
17455 						    env, "const R%d: %u != %llu",
17456 						    r, cval, regs[r].var_off.value))
17457 					return -EFAULT;
17458 			}
17459 		}
17460 
17461 		/* Reduce verification complexity by stopping speculative path
17462 		 * verification when a nospec is encountered.
17463 		 */
17464 		if (state->speculative && insn_aux->nospec)
17465 			goto process_bpf_exit;
17466 
17467 		err = do_check_insn(env, &do_print_state);
17468 		if (error_recoverable_with_nospec(err) && state->speculative) {
17469 			/* Prevent this speculative path from ever reaching the
17470 			 * insn that would have been unsafe to execute.
17471 			 */
17472 			insn_aux->nospec = true;
17473 			/* If it was an ADD/SUB insn, potentially remove any
17474 			 * markings for alu sanitization.
17475 			 */
17476 			insn_aux->alu_state = 0;
17477 			goto process_bpf_exit;
17478 		} else if (err < 0) {
17479 			return err;
17480 		} else if (err == PROCESS_BPF_EXIT) {
17481 			goto process_bpf_exit;
17482 		} else if (err == INSN_IDX_UPDATED) {
17483 		} else if (err == 0) {
17484 			env->insn_idx++;
17485 		}
17486 
17487 		if (state->speculative && insn_aux->nospec_result) {
17488 			/* If we are on a path that performed a jump-op, this
17489 			 * may skip a nospec patched-in after the jump. This can
17490 			 * currently never happen because nospec_result is only
17491 			 * used for the write-ops
17492 			 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper
17493 			 * calls. These must never skip the following insn
17494 			 * (i.e., bpf_insn_successors()'s opcode_info.can_jump
17495 			 * is false). Still, add a warning to document this in
17496 			 * case nospec_result is used elsewhere in the future.
17497 			 *
17498 			 * All non-branch instructions have a single
17499 			 * fall-through edge. For these, nospec_result should
17500 			 * already work.
17501 			 */
17502 			if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP ||
17503 					     BPF_CLASS(insn->code) == BPF_JMP32) &&
17504 					    BPF_OP(insn->code) != BPF_CALL, env,
17505 					    "speculation barrier after jump instruction may not have the desired effect"))
17506 				return -EFAULT;
17507 process_bpf_exit:
17508 			mark_verifier_state_scratched(env);
17509 			err = bpf_update_branch_counts(env, env->cur_state);
17510 			if (err)
17511 				return err;
17512 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
17513 					pop_log);
17514 			if (err < 0) {
17515 				if (err != -ENOENT)
17516 					return err;
17517 				break;
17518 			} else {
17519 				do_print_state = true;
17520 				continue;
17521 			}
17522 		}
17523 	}
17524 
17525 	return 0;
17526 }
17527 
17528 static int find_btf_percpu_datasec(struct btf *btf)
17529 {
17530 	const struct btf_type *t;
17531 	const char *tname;
17532 	int i, n;
17533 
17534 	/*
17535 	 * Both vmlinux and module each have their own ".data..percpu"
17536 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17537 	 * types to look at only module's own BTF types.
17538 	 */
17539 	n = btf_nr_types(btf);
17540 	for (i = btf_named_start_id(btf, true); i < n; i++) {
17541 		t = btf_type_by_id(btf, i);
17542 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17543 			continue;
17544 
17545 		tname = btf_name_by_offset(btf, t->name_off);
17546 		if (!strcmp(tname, ".data..percpu"))
17547 			return i;
17548 	}
17549 
17550 	return -ENOENT;
17551 }
17552 
17553 /*
17554  * Add btf to the env->used_btfs array. If needed, refcount the
17555  * corresponding kernel module. To simplify caller's logic
17556  * in case of error or if btf was added before the function
17557  * decreases the btf refcount.
17558  */
17559 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
17560 {
17561 	struct btf_mod_pair *btf_mod;
17562 	int ret = 0;
17563 	int i;
17564 
17565 	/* check whether we recorded this BTF (and maybe module) already */
17566 	for (i = 0; i < env->used_btf_cnt; i++)
17567 		if (env->used_btfs[i].btf == btf)
17568 			goto ret_put;
17569 
17570 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17571 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
17572 			MAX_USED_BTFS);
17573 		ret = -E2BIG;
17574 		goto ret_put;
17575 	}
17576 
17577 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17578 	btf_mod->btf = btf;
17579 	btf_mod->module = NULL;
17580 
17581 	/* if we reference variables from kernel module, bump its refcount */
17582 	if (btf_is_module(btf)) {
17583 		btf_mod->module = btf_try_get_module(btf);
17584 		if (!btf_mod->module) {
17585 			ret = -ENXIO;
17586 			goto ret_put;
17587 		}
17588 	}
17589 
17590 	env->used_btf_cnt++;
17591 	return 0;
17592 
17593 ret_put:
17594 	/* Either error or this BTF was already added */
17595 	btf_put(btf);
17596 	return ret;
17597 }
17598 
17599 /* replace pseudo btf_id with kernel symbol address */
17600 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
17601 				 struct bpf_insn *insn,
17602 				 struct bpf_insn_aux_data *aux,
17603 				 struct btf *btf)
17604 {
17605 	const struct btf_var_secinfo *vsi;
17606 	const struct btf_type *datasec;
17607 	const struct btf_type *t;
17608 	const char *sym_name;
17609 	bool percpu = false;
17610 	u32 type, id = insn->imm;
17611 	s32 datasec_id;
17612 	u64 addr;
17613 	int i;
17614 
17615 	t = btf_type_by_id(btf, id);
17616 	if (!t) {
17617 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17618 		return -ENOENT;
17619 	}
17620 
17621 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17622 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17623 		return -EINVAL;
17624 	}
17625 
17626 	sym_name = btf_name_by_offset(btf, t->name_off);
17627 	addr = kallsyms_lookup_name(sym_name);
17628 	if (!addr) {
17629 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17630 			sym_name);
17631 		return -ENOENT;
17632 	}
17633 	insn[0].imm = (u32)addr;
17634 	insn[1].imm = addr >> 32;
17635 
17636 	if (btf_type_is_func(t)) {
17637 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17638 		aux->btf_var.mem_size = 0;
17639 		return 0;
17640 	}
17641 
17642 	datasec_id = find_btf_percpu_datasec(btf);
17643 	if (datasec_id > 0) {
17644 		datasec = btf_type_by_id(btf, datasec_id);
17645 		for_each_vsi(i, datasec, vsi) {
17646 			if (vsi->type == id) {
17647 				percpu = true;
17648 				break;
17649 			}
17650 		}
17651 	}
17652 
17653 	type = t->type;
17654 	t = btf_type_skip_modifiers(btf, type, NULL);
17655 	if (percpu) {
17656 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17657 		aux->btf_var.btf = btf;
17658 		aux->btf_var.btf_id = type;
17659 	} else if (!btf_type_is_struct(t)) {
17660 		const struct btf_type *ret;
17661 		const char *tname;
17662 		u32 tsize;
17663 
17664 		/* resolve the type size of ksym. */
17665 		ret = btf_resolve_size(btf, t, &tsize);
17666 		if (IS_ERR(ret)) {
17667 			tname = btf_name_by_offset(btf, t->name_off);
17668 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17669 				tname, PTR_ERR(ret));
17670 			return -EINVAL;
17671 		}
17672 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17673 		aux->btf_var.mem_size = tsize;
17674 	} else {
17675 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17676 		aux->btf_var.btf = btf;
17677 		aux->btf_var.btf_id = type;
17678 	}
17679 
17680 	return 0;
17681 }
17682 
17683 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17684 			       struct bpf_insn *insn,
17685 			       struct bpf_insn_aux_data *aux)
17686 {
17687 	struct btf *btf;
17688 	int btf_fd;
17689 	int err;
17690 
17691 	btf_fd = insn[1].imm;
17692 	if (btf_fd) {
17693 		btf = btf_get_by_fd(btf_fd);
17694 		if (IS_ERR(btf)) {
17695 			verbose(env, "invalid module BTF object FD specified.\n");
17696 			return -EINVAL;
17697 		}
17698 	} else {
17699 		if (!btf_vmlinux) {
17700 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17701 			return -EINVAL;
17702 		}
17703 		btf_get(btf_vmlinux);
17704 		btf = btf_vmlinux;
17705 	}
17706 
17707 	err = __check_pseudo_btf_id(env, insn, aux, btf);
17708 	if (err) {
17709 		btf_put(btf);
17710 		return err;
17711 	}
17712 
17713 	return __add_used_btf(env, btf);
17714 }
17715 
17716 static bool is_tracing_prog_type(enum bpf_prog_type type)
17717 {
17718 	switch (type) {
17719 	case BPF_PROG_TYPE_KPROBE:
17720 	case BPF_PROG_TYPE_TRACEPOINT:
17721 	case BPF_PROG_TYPE_PERF_EVENT:
17722 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17723 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17724 		return true;
17725 	default:
17726 		return false;
17727 	}
17728 }
17729 
17730 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17731 {
17732 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17733 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17734 }
17735 
17736 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17737 					struct bpf_map *map,
17738 					struct bpf_prog *prog)
17739 
17740 {
17741 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17742 
17743 	if (map->excl_prog_sha &&
17744 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
17745 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
17746 		return -EACCES;
17747 	}
17748 
17749 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17750 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17751 		if (is_tracing_prog_type(prog_type)) {
17752 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17753 			return -EINVAL;
17754 		}
17755 	}
17756 
17757 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
17758 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17759 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17760 			return -EINVAL;
17761 		}
17762 
17763 		if (is_tracing_prog_type(prog_type)) {
17764 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17765 			return -EINVAL;
17766 		}
17767 	}
17768 
17769 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17770 	    !bpf_offload_prog_map_match(prog, map)) {
17771 		verbose(env, "offload device mismatch between prog and map\n");
17772 		return -EINVAL;
17773 	}
17774 
17775 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17776 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17777 		return -EINVAL;
17778 	}
17779 
17780 	if (prog->sleepable)
17781 		switch (map->map_type) {
17782 		case BPF_MAP_TYPE_HASH:
17783 		case BPF_MAP_TYPE_RHASH:
17784 		case BPF_MAP_TYPE_LRU_HASH:
17785 		case BPF_MAP_TYPE_ARRAY:
17786 		case BPF_MAP_TYPE_PERCPU_HASH:
17787 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17788 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17789 		case BPF_MAP_TYPE_LPM_TRIE:
17790 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17791 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17792 		case BPF_MAP_TYPE_RINGBUF:
17793 		case BPF_MAP_TYPE_USER_RINGBUF:
17794 		case BPF_MAP_TYPE_INODE_STORAGE:
17795 		case BPF_MAP_TYPE_SK_STORAGE:
17796 		case BPF_MAP_TYPE_TASK_STORAGE:
17797 		case BPF_MAP_TYPE_CGRP_STORAGE:
17798 		case BPF_MAP_TYPE_QUEUE:
17799 		case BPF_MAP_TYPE_STACK:
17800 		case BPF_MAP_TYPE_ARENA:
17801 		case BPF_MAP_TYPE_INSN_ARRAY:
17802 		case BPF_MAP_TYPE_PROG_ARRAY:
17803 			break;
17804 		default:
17805 			verbose(env,
17806 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17807 			return -EINVAL;
17808 		}
17809 
17810 	if (bpf_map_is_cgroup_storage(map) &&
17811 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17812 		verbose(env, "only one cgroup storage of each type is allowed\n");
17813 		return -EBUSY;
17814 	}
17815 
17816 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
17817 		if (env->prog->aux->arena) {
17818 			verbose(env, "Only one arena per program\n");
17819 			return -EBUSY;
17820 		}
17821 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
17822 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
17823 			return -EPERM;
17824 		}
17825 		if (!env->prog->jit_requested) {
17826 			verbose(env, "JIT is required to use arena\n");
17827 			return -EOPNOTSUPP;
17828 		}
17829 		if (!bpf_jit_supports_arena()) {
17830 			verbose(env, "JIT doesn't support arena\n");
17831 			return -EOPNOTSUPP;
17832 		}
17833 		env->prog->aux->arena = (void *)map;
17834 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
17835 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
17836 			return -EINVAL;
17837 		}
17838 	}
17839 
17840 	return 0;
17841 }
17842 
17843 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
17844 {
17845 	int i, err;
17846 
17847 	/* check whether we recorded this map already */
17848 	for (i = 0; i < env->used_map_cnt; i++)
17849 		if (env->used_maps[i] == map)
17850 			return i;
17851 
17852 	if (env->used_map_cnt >= MAX_USED_MAPS) {
17853 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
17854 			MAX_USED_MAPS);
17855 		return -E2BIG;
17856 	}
17857 
17858 	err = check_map_prog_compatibility(env, map, env->prog);
17859 	if (err)
17860 		return err;
17861 
17862 	if (env->prog->sleepable)
17863 		atomic64_inc(&map->sleepable_refcnt);
17864 
17865 	/* hold the map. If the program is rejected by verifier,
17866 	 * the map will be released by release_maps() or it
17867 	 * will be used by the valid program until it's unloaded
17868 	 * and all maps are released in bpf_free_used_maps()
17869 	 */
17870 	bpf_map_inc(map);
17871 
17872 	env->used_maps[env->used_map_cnt++] = map;
17873 
17874 	if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
17875 		err = bpf_insn_array_init(map, env->prog);
17876 		if (err) {
17877 			verbose(env, "Failed to properly initialize insn array\n");
17878 			return err;
17879 		}
17880 		env->insn_array_maps[env->insn_array_map_cnt++] = map;
17881 	}
17882 
17883 	return env->used_map_cnt - 1;
17884 }
17885 
17886 /* Add map behind fd to used maps list, if it's not already there, and return
17887  * its index.
17888  * Returns <0 on error, or >= 0 index, on success.
17889  */
17890 static int add_used_map(struct bpf_verifier_env *env, int fd)
17891 {
17892 	struct bpf_map *map;
17893 	CLASS(fd, f)(fd);
17894 
17895 	map = __bpf_map_get(f);
17896 	if (IS_ERR(map)) {
17897 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17898 		return PTR_ERR(map);
17899 	}
17900 
17901 	return __add_used_map(env, map);
17902 }
17903 
17904 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
17905 {
17906 	u8 class = BPF_CLASS(insn->code);
17907 	u8 opcode = BPF_OP(insn->code);
17908 
17909 	switch (opcode) {
17910 	case BPF_NEG:
17911 		if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 ||
17912 		    insn->off != 0 || insn->imm != 0) {
17913 			verbose(env, "BPF_NEG uses reserved fields\n");
17914 			return -EINVAL;
17915 		}
17916 		return 0;
17917 	case BPF_END:
17918 		if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
17919 		    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
17920 		    (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) {
17921 			verbose(env, "BPF_END uses reserved fields\n");
17922 			return -EINVAL;
17923 		}
17924 		return 0;
17925 	case BPF_MOV:
17926 		if (BPF_SRC(insn->code) == BPF_X) {
17927 			if (class == BPF_ALU) {
17928 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
17929 				    insn->imm) {
17930 					verbose(env, "BPF_MOV uses reserved fields\n");
17931 					return -EINVAL;
17932 				}
17933 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
17934 				if (insn->imm != 1 && insn->imm != 1u << 16) {
17935 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
17936 					return -EINVAL;
17937 				}
17938 			} else if ((insn->off != 0 && insn->off != 8 &&
17939 				    insn->off != 16 && insn->off != 32) || insn->imm) {
17940 				verbose(env, "BPF_MOV uses reserved fields\n");
17941 				return -EINVAL;
17942 			}
17943 		} else if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
17944 			verbose(env, "BPF_MOV uses reserved fields\n");
17945 			return -EINVAL;
17946 		}
17947 		return 0;
17948 	case BPF_ADD:
17949 	case BPF_SUB:
17950 	case BPF_AND:
17951 	case BPF_OR:
17952 	case BPF_XOR:
17953 	case BPF_LSH:
17954 	case BPF_RSH:
17955 	case BPF_ARSH:
17956 	case BPF_MUL:
17957 	case BPF_DIV:
17958 	case BPF_MOD:
17959 		if (BPF_SRC(insn->code) == BPF_X) {
17960 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
17961 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
17962 				verbose(env, "BPF_ALU uses reserved fields\n");
17963 				return -EINVAL;
17964 			}
17965 		} else if (insn->src_reg != BPF_REG_0 ||
17966 			   (insn->off != 0 && insn->off != 1) ||
17967 			   (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
17968 			verbose(env, "BPF_ALU uses reserved fields\n");
17969 			return -EINVAL;
17970 		}
17971 		return 0;
17972 	default:
17973 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17974 		return -EINVAL;
17975 	}
17976 }
17977 
17978 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
17979 {
17980 	u8 class = BPF_CLASS(insn->code);
17981 	u8 opcode = BPF_OP(insn->code);
17982 
17983 	switch (opcode) {
17984 	case BPF_CALL:
17985 		if (BPF_SRC(insn->code) != BPF_K ||
17986 		    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) ||
17987 		    (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL &&
17988 		     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17989 		    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
17990 			verbose(env, "BPF_CALL uses reserved fields\n");
17991 			return -EINVAL;
17992 		}
17993 		return 0;
17994 	case BPF_JA:
17995 		if (BPF_SRC(insn->code) == BPF_X) {
17996 			if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) {
17997 				verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
17998 				return -EINVAL;
17999 			}
18000 		} else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
18001 			   (class == BPF_JMP && insn->imm != 0) ||
18002 			   (class == BPF_JMP32 && insn->off != 0)) {
18003 			verbose(env, "BPF_JA uses reserved fields\n");
18004 			return -EINVAL;
18005 		}
18006 		return 0;
18007 	case BPF_EXIT:
18008 		if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 ||
18009 		    insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 ||
18010 		    class == BPF_JMP32) {
18011 			verbose(env, "BPF_EXIT uses reserved fields\n");
18012 			return -EINVAL;
18013 		}
18014 		return 0;
18015 	case BPF_JCOND:
18016 		if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO ||
18017 		    insn->dst_reg || insn->imm) {
18018 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
18019 			return -EINVAL;
18020 		}
18021 		return 0;
18022 	default:
18023 		if (BPF_SRC(insn->code) == BPF_X) {
18024 			if (insn->imm != 0) {
18025 				verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
18026 				return -EINVAL;
18027 			}
18028 		} else if (insn->src_reg != BPF_REG_0) {
18029 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
18030 			return -EINVAL;
18031 		}
18032 		return 0;
18033 	}
18034 }
18035 
18036 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn)
18037 {
18038 	switch (BPF_CLASS(insn->code)) {
18039 	case BPF_ALU:
18040 	case BPF_ALU64:
18041 		return check_alu_fields(env, insn);
18042 	case BPF_LDX:
18043 		if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18044 		    insn->imm != 0) {
18045 			verbose(env, "BPF_LDX uses reserved fields\n");
18046 			return -EINVAL;
18047 		}
18048 		return 0;
18049 	case BPF_STX:
18050 		if (BPF_MODE(insn->code) == BPF_ATOMIC)
18051 			return 0;
18052 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18053 			verbose(env, "BPF_STX uses reserved fields\n");
18054 			return -EINVAL;
18055 		}
18056 		return 0;
18057 	case BPF_ST:
18058 		if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) {
18059 			verbose(env, "BPF_ST uses reserved fields\n");
18060 			return -EINVAL;
18061 		}
18062 		return 0;
18063 	case BPF_JMP:
18064 	case BPF_JMP32:
18065 		return check_jmp_fields(env, insn);
18066 	case BPF_LD: {
18067 		u8 mode = BPF_MODE(insn->code);
18068 
18069 		if (mode == BPF_ABS || mode == BPF_IND) {
18070 			if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
18071 			    BPF_SIZE(insn->code) == BPF_DW ||
18072 			    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
18073 				verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
18074 				return -EINVAL;
18075 			}
18076 		} else if (mode != BPF_IMM) {
18077 			verbose(env, "invalid BPF_LD mode\n");
18078 			return -EINVAL;
18079 		}
18080 		return 0;
18081 	}
18082 	default:
18083 		verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code));
18084 		return -EINVAL;
18085 	}
18086 }
18087 
18088 /*
18089  * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions:
18090  *
18091  * 1. if it accesses map FD, replace it with actual map pointer.
18092  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18093  *
18094  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18095  */
18096 static int check_and_resolve_insns(struct bpf_verifier_env *env)
18097 {
18098 	struct bpf_insn *insn = env->prog->insnsi;
18099 	int insn_cnt = env->prog->len;
18100 	int i, err;
18101 
18102 	err = bpf_prog_calc_tag(env->prog);
18103 	if (err)
18104 		return err;
18105 
18106 	for (i = 0; i < insn_cnt; i++, insn++) {
18107 		if (insn->dst_reg >= MAX_BPF_REG &&
18108 		    !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) {
18109 			verbose(env, "R%d is invalid\n", insn->dst_reg);
18110 			return -EINVAL;
18111 		}
18112 		if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) {
18113 			verbose(env, "R%d is invalid\n", insn->src_reg);
18114 			return -EINVAL;
18115 		}
18116 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18117 			struct bpf_insn_aux_data *aux;
18118 			struct bpf_map *map;
18119 			int map_idx;
18120 			u64 addr;
18121 			u32 fd;
18122 
18123 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18124 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18125 			    insn[1].off != 0) {
18126 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18127 				return -EINVAL;
18128 			}
18129 
18130 			if (insn[0].off != 0) {
18131 				verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
18132 				return -EINVAL;
18133 			}
18134 
18135 			if (insn[0].src_reg == 0)
18136 				/* valid generic load 64-bit imm */
18137 				goto next_insn;
18138 
18139 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18140 				aux = &env->insn_aux_data[i];
18141 				err = check_pseudo_btf_id(env, insn, aux);
18142 				if (err)
18143 					return err;
18144 				goto next_insn;
18145 			}
18146 
18147 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18148 				aux = &env->insn_aux_data[i];
18149 				aux->ptr_type = PTR_TO_FUNC;
18150 				goto next_insn;
18151 			}
18152 
18153 			/* In final convert_pseudo_ld_imm64() step, this is
18154 			 * converted into regular 64-bit imm load insn.
18155 			 */
18156 			switch (insn[0].src_reg) {
18157 			case BPF_PSEUDO_MAP_VALUE:
18158 			case BPF_PSEUDO_MAP_IDX_VALUE:
18159 				break;
18160 			case BPF_PSEUDO_MAP_FD:
18161 			case BPF_PSEUDO_MAP_IDX:
18162 				if (insn[1].imm == 0)
18163 					break;
18164 				fallthrough;
18165 			default:
18166 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18167 				return -EINVAL;
18168 			}
18169 
18170 			switch (insn[0].src_reg) {
18171 			case BPF_PSEUDO_MAP_IDX_VALUE:
18172 			case BPF_PSEUDO_MAP_IDX:
18173 				if (bpfptr_is_null(env->fd_array)) {
18174 					verbose(env, "fd_idx without fd_array is invalid\n");
18175 					return -EPROTO;
18176 				}
18177 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18178 							    insn[0].imm * sizeof(fd),
18179 							    sizeof(fd)))
18180 					return -EFAULT;
18181 				break;
18182 			default:
18183 				fd = insn[0].imm;
18184 				break;
18185 			}
18186 
18187 			map_idx = add_used_map(env, fd);
18188 			if (map_idx < 0)
18189 				return map_idx;
18190 			map = env->used_maps[map_idx];
18191 
18192 			aux = &env->insn_aux_data[i];
18193 			aux->map_index = map_idx;
18194 
18195 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18196 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18197 				addr = (unsigned long)map;
18198 			} else {
18199 				u32 off = insn[1].imm;
18200 
18201 				if (!map->ops->map_direct_value_addr) {
18202 					verbose(env, "no direct value access support for this map type\n");
18203 					return -EINVAL;
18204 				}
18205 
18206 				err = map->ops->map_direct_value_addr(map, &addr, off);
18207 				if (err) {
18208 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18209 						map->value_size, off);
18210 					return err;
18211 				}
18212 
18213 				aux->map_off = off;
18214 				addr += off;
18215 			}
18216 
18217 			insn[0].imm = (u32)addr;
18218 			insn[1].imm = addr >> 32;
18219 
18220 next_insn:
18221 			insn++;
18222 			i++;
18223 			continue;
18224 		}
18225 
18226 		/* Basic sanity check before we invest more work here. */
18227 		if (!bpf_opcode_in_insntable(insn->code)) {
18228 			verbose(env, "unknown opcode %02x\n", insn->code);
18229 			return -EINVAL;
18230 		}
18231 
18232 		err = check_insn_fields(env, insn);
18233 		if (err)
18234 			return err;
18235 	}
18236 
18237 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18238 	 * 'struct bpf_map *' into a register instead of user map_fd.
18239 	 * These pointers will be used later by verifier to validate map access.
18240 	 */
18241 	return 0;
18242 }
18243 
18244 /* drop refcnt of maps used by the rejected program */
18245 static void release_maps(struct bpf_verifier_env *env)
18246 {
18247 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18248 			     env->used_map_cnt);
18249 }
18250 
18251 /* drop refcnt of maps used by the rejected program */
18252 static void release_btfs(struct bpf_verifier_env *env)
18253 {
18254 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
18255 }
18256 
18257 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18258 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18259 {
18260 	struct bpf_insn *insn = env->prog->insnsi;
18261 	int insn_cnt = env->prog->len;
18262 	int i;
18263 
18264 	for (i = 0; i < insn_cnt; i++, insn++) {
18265 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18266 			continue;
18267 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18268 			continue;
18269 		insn->src_reg = 0;
18270 	}
18271 }
18272 
18273 static void release_insn_arrays(struct bpf_verifier_env *env)
18274 {
18275 	int i;
18276 
18277 	for (i = 0; i < env->insn_array_map_cnt; i++)
18278 		bpf_insn_array_release(env->insn_array_maps[i]);
18279 }
18280 
18281 
18282 
18283 /* The verifier does more data flow analysis than llvm and will not
18284  * explore branches that are dead at run time. Malicious programs can
18285  * have dead code too. Therefore replace all dead at-run-time code
18286  * with 'ja -1'.
18287  *
18288  * Just nops are not optimal, e.g. if they would sit at the end of the
18289  * program and through another bug we would manage to jump there, then
18290  * we'd execute beyond program memory otherwise. Returning exception
18291  * code also wouldn't work since we can have subprogs where the dead
18292  * code could be located.
18293  */
18294 static void sanitize_dead_code(struct bpf_verifier_env *env)
18295 {
18296 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18297 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18298 	struct bpf_insn *insn = env->prog->insnsi;
18299 	const int insn_cnt = env->prog->len;
18300 	int i;
18301 
18302 	for (i = 0; i < insn_cnt; i++) {
18303 		if (aux_data[i].seen)
18304 			continue;
18305 		memcpy(insn + i, &trap, sizeof(trap));
18306 		aux_data[i].zext_dst = false;
18307 	}
18308 }
18309 
18310 
18311 
18312 static void free_states(struct bpf_verifier_env *env)
18313 {
18314 	struct bpf_verifier_state_list *sl;
18315 	struct list_head *head, *pos, *tmp;
18316 	struct bpf_scc_info *info;
18317 	int i, j;
18318 
18319 	bpf_free_verifier_state(env->cur_state, true);
18320 	env->cur_state = NULL;
18321 	while (!pop_stack(env, NULL, NULL, false));
18322 
18323 	list_for_each_safe(pos, tmp, &env->free_list) {
18324 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18325 		bpf_free_verifier_state(&sl->state, false);
18326 		kfree(sl);
18327 	}
18328 	INIT_LIST_HEAD(&env->free_list);
18329 
18330 	for (i = 0; i < env->scc_cnt; ++i) {
18331 		info = env->scc_info[i];
18332 		if (!info)
18333 			continue;
18334 		for (j = 0; j < info->num_visits; j++)
18335 			bpf_free_backedges(&info->visits[j]);
18336 		kvfree(info);
18337 		env->scc_info[i] = NULL;
18338 	}
18339 
18340 	if (!env->explored_states)
18341 		return;
18342 
18343 	for (i = 0; i < state_htab_size(env); i++) {
18344 		head = &env->explored_states[i];
18345 
18346 		list_for_each_safe(pos, tmp, head) {
18347 			sl = container_of(pos, struct bpf_verifier_state_list, node);
18348 			bpf_free_verifier_state(&sl->state, false);
18349 			kfree(sl);
18350 		}
18351 		INIT_LIST_HEAD(&env->explored_states[i]);
18352 	}
18353 }
18354 
18355 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18356 {
18357 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18358 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
18359 	struct bpf_prog_aux *aux = env->prog->aux;
18360 	struct bpf_verifier_state *state;
18361 	struct bpf_reg_state *regs;
18362 	int ret, i;
18363 
18364 	env->prev_linfo = NULL;
18365 	env->pass_cnt++;
18366 
18367 	state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT);
18368 	if (!state)
18369 		return -ENOMEM;
18370 	state->curframe = 0;
18371 	state->speculative = false;
18372 	state->branches = 1;
18373 	state->in_sleepable = env->prog->sleepable;
18374 	state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);
18375 	if (!state->frame[0]) {
18376 		kfree(state);
18377 		return -ENOMEM;
18378 	}
18379 	env->cur_state = state;
18380 	init_func_state(env, state->frame[0],
18381 			BPF_MAIN_FUNC /* callsite */,
18382 			0 /* frameno */,
18383 			subprog);
18384 	state->first_insn_idx = env->subprog_info[subprog].start;
18385 	state->last_insn_idx = -1;
18386 
18387 	regs = state->frame[state->curframe]->regs;
18388 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18389 		const char *sub_name = subprog_name(env, subprog);
18390 		struct bpf_subprog_arg_info *arg;
18391 		struct bpf_reg_state *reg;
18392 
18393 		if (env->log.level & BPF_LOG_LEVEL)
18394 			verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
18395 		ret = btf_prepare_func_args(env, subprog);
18396 		if (ret)
18397 			goto out;
18398 
18399 		if (subprog_is_exc_cb(env, subprog)) {
18400 			state->frame[0]->in_exception_callback_fn = true;
18401 
18402 			/*
18403 			 * Global functions are scalar or void, make sure
18404 			 * we return a scalar.
18405 			 */
18406 			if (subprog_returns_void(env, subprog)) {
18407 				verbose(env, "exception cb cannot return void\n");
18408 				ret = -EINVAL;
18409 				goto out;
18410 			}
18411 
18412 			/* Also ensure the callback only has a single scalar argument. */
18413 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
18414 				verbose(env, "exception cb only supports single integer argument\n");
18415 				ret = -EINVAL;
18416 				goto out;
18417 			}
18418 		}
18419 		for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) {
18420 			arg = &sub->args[i - BPF_REG_1];
18421 			reg = &regs[i];
18422 
18423 			if (arg->arg_type == ARG_PTR_TO_CTX) {
18424 				reg->type = PTR_TO_CTX;
18425 				mark_reg_known_zero(env, regs, i);
18426 			} else if (arg->arg_type == ARG_ANYTHING) {
18427 				reg->type = SCALAR_VALUE;
18428 				mark_reg_unknown(env, regs, i);
18429 			} else if (arg->arg_type == ARG_PTR_TO_DYNPTR) {
18430 				/* assume unspecial LOCAL dynptr type */
18431 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0);
18432 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
18433 				reg->type = PTR_TO_MEM;
18434 				reg->type |= arg->arg_type &
18435 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
18436 				mark_reg_known_zero(env, regs, i);
18437 				reg->mem_size = arg->mem_size;
18438 				if (arg->arg_type & PTR_MAYBE_NULL)
18439 					reg->id = ++env->id_gen;
18440 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
18441 				reg->type = PTR_TO_BTF_ID;
18442 				if (arg->arg_type & PTR_MAYBE_NULL)
18443 					reg->type |= PTR_MAYBE_NULL;
18444 				if (arg->arg_type & PTR_UNTRUSTED)
18445 					reg->type |= PTR_UNTRUSTED;
18446 				if (arg->arg_type & PTR_TRUSTED)
18447 					reg->type |= PTR_TRUSTED;
18448 				mark_reg_known_zero(env, regs, i);
18449 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
18450 				reg->btf_id = arg->btf_id;
18451 				reg->id = ++env->id_gen;
18452 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
18453 				/* caller can pass either PTR_TO_ARENA or SCALAR */
18454 				mark_reg_unknown(env, regs, i);
18455 			} else {
18456 				verifier_bug(env, "unhandled arg#%d type %d",
18457 					     i - BPF_REG_1 + 1, arg->arg_type);
18458 				ret = -EFAULT;
18459 				goto out;
18460 			}
18461 		}
18462 		if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) {
18463 			verbose(env, "freplace programs with >%d args not supported yet\n",
18464 				MAX_BPF_FUNC_REG_ARGS);
18465 			ret = -EINVAL;
18466 			goto out;
18467 		}
18468 	} else {
18469 		/* if main BPF program has associated BTF info, validate that
18470 		 * it's matching expected signature, and otherwise mark BTF
18471 		 * info for main program as unreliable
18472 		 */
18473 		if (env->prog->aux->func_info_aux) {
18474 			ret = btf_prepare_func_args(env, 0);
18475 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) {
18476 				env->prog->aux->func_info_aux[0].unreliable = true;
18477 				sub->arg_cnt = 1;
18478 				sub->stack_arg_cnt = 0;
18479 			}
18480 		}
18481 
18482 		/* 1st arg to a function */
18483 		regs[BPF_REG_1].type = PTR_TO_CTX;
18484 		mark_reg_known_zero(env, regs, BPF_REG_1);
18485 	}
18486 
18487 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
18488 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
18489 		for (i = 0; i < aux->ctx_arg_info_size; i++) {
18490 			ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0;
18491 			if (ret < 0)
18492 				goto out;
18493 
18494 			aux->ctx_arg_info[i].ref_id = ret;
18495 		}
18496 	}
18497 
18498 	ret = do_check(env);
18499 out:
18500 	if (!ret && pop_log)
18501 		bpf_vlog_reset(&env->log, 0);
18502 	free_states(env);
18503 	return ret;
18504 }
18505 
18506 /* Lazily verify all global functions based on their BTF, if they are called
18507  * from main BPF program or any of subprograms transitively.
18508  * BPF global subprogs called from dead code are not validated.
18509  * All callable global functions must pass verification.
18510  * Otherwise the whole program is rejected.
18511  * Consider:
18512  * int bar(int);
18513  * int foo(int f)
18514  * {
18515  *    return bar(f);
18516  * }
18517  * int bar(int b)
18518  * {
18519  *    ...
18520  * }
18521  * foo() will be verified first for R1=any_scalar_value. During verification it
18522  * will be assumed that bar() already verified successfully and call to bar()
18523  * from foo() will be checked for type match only. Later bar() will be verified
18524  * independently to check that it's safe for R1=any_scalar_value.
18525  */
18526 static int do_check_subprogs(struct bpf_verifier_env *env)
18527 {
18528 	struct bpf_prog_aux *aux = env->prog->aux;
18529 	struct bpf_func_info_aux *sub_aux;
18530 	int i, ret, new_cnt;
18531 	u32 insn_processed;
18532 
18533 	if (!aux->func_info)
18534 		return 0;
18535 
18536 	/* exception callback is presumed to be always called */
18537 	if (env->exception_callback_subprog)
18538 		subprog_aux(env, env->exception_callback_subprog)->called = true;
18539 
18540 again:
18541 	new_cnt = 0;
18542 	for (i = 1; i < env->subprog_cnt; i++) {
18543 		if (!bpf_subprog_is_global(env, i))
18544 			continue;
18545 
18546 		insn_processed = env->insn_processed;
18547 
18548 		sub_aux = subprog_aux(env, i);
18549 		if (!sub_aux->called || sub_aux->verified)
18550 			continue;
18551 
18552 		env->insn_idx = env->subprog_info[i].start;
18553 		WARN_ON_ONCE(env->insn_idx == 0);
18554 		ret = do_check_common(env, i);
18555 		env->subprog_info[i].insn_processed = env->insn_processed - insn_processed;
18556 		if (ret) {
18557 			return ret;
18558 		} else if (env->log.level & BPF_LOG_LEVEL) {
18559 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
18560 				i, subprog_name(env, i));
18561 		}
18562 
18563 		/* We verified new global subprog, it might have called some
18564 		 * more global subprogs that we haven't verified yet, so we
18565 		 * need to do another pass over subprogs to verify those.
18566 		 */
18567 		sub_aux->verified = true;
18568 		new_cnt++;
18569 	}
18570 
18571 	/* We can't loop forever as we verify at least one global subprog on
18572 	 * each pass.
18573 	 */
18574 	if (new_cnt)
18575 		goto again;
18576 
18577 	return 0;
18578 }
18579 
18580 static int do_check_main(struct bpf_verifier_env *env)
18581 {
18582 	u32 insn_processed = env->insn_processed;
18583 	int ret;
18584 
18585 	env->insn_idx = 0;
18586 	ret = do_check_common(env, 0);
18587 	env->subprog_info[0].insn_processed = env->insn_processed - insn_processed;
18588 	if (!ret)
18589 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18590 	return ret;
18591 }
18592 
18593 
18594 static void print_verification_stats(struct bpf_verifier_env *env)
18595 {
18596 	/* Skip over hidden subprogs which are not verified. */
18597 	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18598 
18599 	if (env->log.level & BPF_LOG_STATS) {
18600 		verbose(env, "verification time %lld usec\n",
18601 			div_u64(env->verification_time, 1000));
18602 		verbose(env, "stack depth %d", env->subprog_info[0].stack_depth);
18603 		for (i = 1; i < subprog_cnt; i++)
18604 			verbose(env, "+%d", env->subprog_info[i].stack_depth);
18605 		verbose(env, " max %d\n", env->max_stack_depth);
18606 		verbose(env, "insns processed %d", env->subprog_info[0].insn_processed);
18607 		for (i = 1; i < subprog_cnt; i++)
18608 			if (bpf_subprog_is_global(env, i))
18609 				verbose(env, "+%d", env->subprog_info[i].insn_processed);
18610 		verbose(env, "\n");
18611 	}
18612 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18613 		"total_states %d peak_states %d mark_read %d\n",
18614 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18615 		env->max_states_per_insn, env->total_states,
18616 		env->peak_states, env->longest_mark_read_walk);
18617 }
18618 
18619 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
18620 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
18621 {
18622 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
18623 	prog->aux->ctx_arg_info_size = cnt;
18624 
18625 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
18626 }
18627 
18628 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18629 {
18630 	const struct btf_type *t, *func_proto;
18631 	const struct bpf_struct_ops_desc *st_ops_desc;
18632 	const struct bpf_struct_ops *st_ops;
18633 	const struct btf_member *member;
18634 	struct bpf_prog *prog = env->prog;
18635 	bool has_refcounted_arg = false;
18636 	u32 btf_id, member_idx, member_off;
18637 	struct btf *btf;
18638 	const char *mname;
18639 	int i, err;
18640 
18641 	if (!prog->gpl_compatible) {
18642 		verbose(env, "struct ops programs must have a GPL compatible license\n");
18643 		return -EINVAL;
18644 	}
18645 
18646 	if (!prog->aux->attach_btf_id)
18647 		return -ENOTSUPP;
18648 
18649 	btf = prog->aux->attach_btf;
18650 	if (btf_is_module(btf)) {
18651 		/* Make sure st_ops is valid through the lifetime of env */
18652 		env->attach_btf_mod = btf_try_get_module(btf);
18653 		if (!env->attach_btf_mod) {
18654 			verbose(env, "struct_ops module %s is not found\n",
18655 				btf_get_name(btf));
18656 			return -ENOTSUPP;
18657 		}
18658 	}
18659 
18660 	btf_id = prog->aux->attach_btf_id;
18661 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
18662 	if (!st_ops_desc) {
18663 		verbose(env, "attach_btf_id %u is not a supported struct\n",
18664 			btf_id);
18665 		return -ENOTSUPP;
18666 	}
18667 	st_ops = st_ops_desc->st_ops;
18668 
18669 	t = st_ops_desc->type;
18670 	member_idx = prog->expected_attach_type;
18671 	if (member_idx >= btf_type_vlen(t)) {
18672 		verbose(env, "attach to invalid member idx %u of struct %s\n",
18673 			member_idx, st_ops->name);
18674 		return -EINVAL;
18675 	}
18676 
18677 	member = &btf_type_member(t)[member_idx];
18678 	mname = btf_name_by_offset(btf, member->name_off);
18679 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
18680 					       NULL);
18681 	if (!func_proto) {
18682 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18683 			mname, member_idx, st_ops->name);
18684 		return -EINVAL;
18685 	}
18686 
18687 	member_off = __btf_member_bit_offset(t, member) / 8;
18688 	err = bpf_struct_ops_supported(st_ops, member_off);
18689 	if (err) {
18690 		verbose(env, "attach to unsupported member %s of struct %s\n",
18691 			mname, st_ops->name);
18692 		return err;
18693 	}
18694 
18695 	if (st_ops->check_member) {
18696 		err = st_ops->check_member(t, member, prog);
18697 
18698 		if (err) {
18699 			verbose(env, "attach to unsupported member %s of struct %s\n",
18700 				mname, st_ops->name);
18701 			return err;
18702 		}
18703 	}
18704 
18705 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
18706 		verbose(env, "Private stack not supported by jit\n");
18707 		return -EACCES;
18708 	}
18709 
18710 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
18711 		if (st_ops_desc->arg_info[member_idx].info[i].refcounted) {
18712 			has_refcounted_arg = true;
18713 			break;
18714 		}
18715 	}
18716 
18717 	/* Tail call is not allowed for programs with refcounted arguments since we
18718 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
18719 	 */
18720 	for (i = 0; i < env->subprog_cnt; i++) {
18721 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
18722 			verbose(env, "program with __ref argument cannot tail call\n");
18723 			return -EINVAL;
18724 		}
18725 	}
18726 
18727 	prog->aux->st_ops = st_ops;
18728 	prog->aux->attach_st_ops_member_off = member_off;
18729 
18730 	prog->aux->attach_func_proto = func_proto;
18731 	prog->aux->attach_func_name = mname;
18732 	env->ops = st_ops->verifier_ops;
18733 
18734 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
18735 					  st_ops_desc->arg_info[member_idx].cnt);
18736 }
18737 #define SECURITY_PREFIX "security_"
18738 
18739 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
18740 
18741 /* list of non-sleepable functions that are otherwise on
18742  * ALLOW_ERROR_INJECTION list
18743  */
18744 BTF_SET_START(btf_non_sleepable_error_inject)
18745 /* Three functions below can be called from sleepable and non-sleepable context.
18746  * Assume non-sleepable from bpf safety point of view.
18747  */
18748 BTF_ID(func, __filemap_add_folio)
18749 #ifdef CONFIG_FAIL_PAGE_ALLOC
18750 BTF_ID(func, should_fail_alloc_page)
18751 #endif
18752 #ifdef CONFIG_FAILSLAB
18753 BTF_ID(func, should_failslab)
18754 #endif
18755 BTF_SET_END(btf_non_sleepable_error_inject)
18756 
18757 static int check_non_sleepable_error_inject(u32 btf_id)
18758 {
18759 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18760 }
18761 
18762 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
18763 {
18764 	/* fentry/fexit/fmod_ret progs can be sleepable if they are
18765 	 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18766 	 */
18767 	if (!check_non_sleepable_error_inject(btf_id) &&
18768 	    within_error_injection_list(addr))
18769 		return 0;
18770 
18771 	return -EINVAL;
18772 }
18773 
18774 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18775 {
18776 	if (within_error_injection_list(addr) ||
18777 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18778 		return 0;
18779 
18780 	return -EINVAL;
18781 }
18782 
18783 #else
18784 
18785 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code
18786  * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name()
18787  * but that just compares two concrete function names.
18788  */
18789 static bool has_arch_syscall_prefix(const char *func_name)
18790 {
18791 #if defined(__x86_64__)
18792 	return !strncmp(func_name, "__x64_", 6);
18793 #elif defined(__i386__)
18794 	return !strncmp(func_name, "__ia32_", 7);
18795 #elif defined(__s390x__)
18796 	return !strncmp(func_name, "__s390x_", 8);
18797 #elif defined(__aarch64__)
18798 	return !strncmp(func_name, "__arm64_", 8);
18799 #elif defined(__riscv)
18800 	return !strncmp(func_name, "__riscv_", 8);
18801 #elif defined(__powerpc__) || defined(__powerpc64__)
18802 	return !strncmp(func_name, "sys_", 4);
18803 #elif defined(__loongarch__)
18804 	return !strncmp(func_name, "sys_", 4);
18805 #else
18806 	return false;
18807 #endif
18808 }
18809 
18810 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */
18811 
18812 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name)
18813 {
18814 	if (has_arch_syscall_prefix(func_name))
18815 		return 0;
18816 
18817 	return -EINVAL;
18818 }
18819 
18820 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18821 {
18822 	if (has_arch_syscall_prefix(func_name) ||
18823 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18824 		return 0;
18825 
18826 	return -EINVAL;
18827 }
18828 
18829 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */
18830 
18831 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id)
18832 {
18833 	return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id;
18834 }
18835 
18836 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog,
18837 				  const struct btf *btf)
18838 {
18839 	const struct btf_type *t;
18840 	const char *tname;
18841 
18842 	switch (prog->type) {
18843 	case BPF_PROG_TYPE_TRACING:
18844 		t = btf_type_by_id(btf, btf_id);
18845 		if (!t)
18846 			return -EINVAL;
18847 		tname = btf_name_by_offset(btf, t->name_off);
18848 		if (!tname)
18849 			return -EINVAL;
18850 
18851 		/*
18852 		 * *.multi sleepable programs will pass initial sleepable check,
18853 		 * the actual attached btf ids are checked later during the link
18854 		 * attachment.
18855 		 */
18856 		if (is_tracing_multi_id(prog, btf_id))
18857 			return 0;
18858 		if (!check_attach_sleepable(btf_id, addr, tname))
18859 			return 0;
18860 		/*
18861 		 * fentry/fexit/fmod_ret progs can also be sleepable if they are
18862 		 * in the fmodret id set with the KF_SLEEPABLE flag.
18863 		 */
18864 		else {
18865 			u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog);
18866 
18867 			if (flags && (*flags & KF_SLEEPABLE))
18868 				return 0;
18869 		}
18870 		break;
18871 	case BPF_PROG_TYPE_LSM:
18872 		/*
18873 		 * LSM progs check that they are attached to bpf_lsm_*() funcs.
18874 		 * Only some of them are sleepable.
18875 		 */
18876 		if (bpf_lsm_is_sleepable_hook(btf_id))
18877 			return 0;
18878 		break;
18879 	default:
18880 		break;
18881 	}
18882 	return -EINVAL;
18883 }
18884 
18885 /*
18886  * Resolve the prototype describing a trace target's real ABI. A
18887  * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public
18888  * prototype, so use the _impl prototype; other targets use their own.
18889  */
18890 static const struct btf_type *
18891 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id)
18892 {
18893 	const struct btf_type *func;
18894 	struct module *mod = NULL;
18895 	const char *name;
18896 	int implicit;
18897 
18898 	func = btf_type_by_id(btf, func_id);
18899 	if (!func || !btf_type_is_func(func))
18900 		return NULL;
18901 	name = btf_name_by_offset(btf, func->name_off);
18902 
18903 	/*
18904 	 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is
18905 	 * stable only once it is live; hold a module ref across the read to
18906 	 * exclude a concurrent module load.
18907 	 */
18908 	if (btf_is_module(btf)) {
18909 		mod = btf_try_get_module(btf);
18910 		if (!mod)
18911 			return NULL;
18912 	}
18913 	implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS);
18914 	module_put(mod);
18915 
18916 	if (implicit == -EINVAL) {
18917 		bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name);
18918 		return NULL;
18919 	}
18920 	if (implicit > 0)
18921 		return find_kfunc_impl_proto(log, btf, name);
18922 
18923 	return btf_type_by_id(btf, func->type);
18924 }
18925 
18926 int bpf_check_attach_target(struct bpf_verifier_log *log,
18927 			    const struct bpf_prog *prog,
18928 			    const struct bpf_prog *tgt_prog,
18929 			    u32 btf_id,
18930 			    struct bpf_attach_target_info *tgt_info)
18931 {
18932 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18933 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
18934 	char trace_symbol[KSYM_SYMBOL_LEN];
18935 	const char prefix[] = "btf_trace_";
18936 	struct bpf_raw_event_map *btp;
18937 	int ret = 0, subprog = -1, i;
18938 	const struct btf_type *t;
18939 	bool conservative = true;
18940 	const char *tname, *fname;
18941 	struct btf *btf;
18942 	long addr = 0;
18943 	struct module *mod = NULL;
18944 
18945 	if (!btf_id) {
18946 		bpf_log(log, "Tracing programs must provide btf_id\n");
18947 		return -EINVAL;
18948 	}
18949 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18950 	if (!btf) {
18951 		bpf_log(log,
18952 			"Tracing program can only be attached to another program annotated with BTF\n");
18953 		return -EINVAL;
18954 	}
18955 	t = btf_type_by_id(btf, btf_id);
18956 	if (!t) {
18957 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18958 		return -EINVAL;
18959 	}
18960 	tname = btf_name_by_offset(btf, t->name_off);
18961 	if (!tname) {
18962 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18963 		return -EINVAL;
18964 	}
18965 	if (tgt_prog) {
18966 		struct bpf_prog_aux *aux = tgt_prog->aux;
18967 		bool tgt_changes_pkt_data;
18968 		bool tgt_might_sleep;
18969 
18970 		if (bpf_prog_is_dev_bound(prog->aux) &&
18971 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18972 			bpf_log(log, "Target program bound device mismatch");
18973 			return -EINVAL;
18974 		}
18975 
18976 		for (i = 0; i < aux->func_info_cnt; i++)
18977 			if (aux->func_info[i].type_id == btf_id) {
18978 				subprog = i;
18979 				break;
18980 			}
18981 		if (subprog == -1) {
18982 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
18983 			return -EINVAL;
18984 		}
18985 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
18986 			bpf_log(log,
18987 				"%s programs cannot attach to exception callback\n",
18988 				prog_extension ? "Extension" : "Tracing");
18989 			return -EINVAL;
18990 		}
18991 		conservative = aux->func_info_aux[subprog].unreliable;
18992 		if (prog_extension) {
18993 			if (conservative) {
18994 				bpf_log(log,
18995 					"Cannot replace static functions\n");
18996 				return -EINVAL;
18997 			}
18998 			if (!prog->jit_requested) {
18999 				bpf_log(log,
19000 					"Extension programs should be JITed\n");
19001 				return -EINVAL;
19002 			}
19003 			tgt_changes_pkt_data = aux->func
19004 					       ? aux->func[subprog]->aux->changes_pkt_data
19005 					       : aux->changes_pkt_data;
19006 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
19007 				bpf_log(log,
19008 					"Extension program changes packet data, while original does not\n");
19009 				return -EINVAL;
19010 			}
19011 
19012 			tgt_might_sleep = aux->func
19013 					  ? aux->func[subprog]->aux->might_sleep
19014 					  : aux->might_sleep;
19015 			if (prog->aux->might_sleep && !tgt_might_sleep) {
19016 				bpf_log(log,
19017 					"Extension program may sleep, while original does not\n");
19018 				return -EINVAL;
19019 			}
19020 		}
19021 		if (!tgt_prog->jited) {
19022 			bpf_log(log, "Can attach to only JITed progs\n");
19023 			return -EINVAL;
19024 		}
19025 		if (prog_tracing) {
19026 			if (aux->attach_tracing_prog) {
19027 				/*
19028 				 * Target program is an fentry/fexit which is already attached
19029 				 * to another tracing program. More levels of nesting
19030 				 * attachment are not allowed.
19031 				 */
19032 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
19033 				return -EINVAL;
19034 			}
19035 		} else if (tgt_prog->type == prog->type) {
19036 			/*
19037 			 * To avoid potential call chain cycles, prevent attaching of a
19038 			 * program extension to another extension. It's ok to attach
19039 			 * fentry/fexit to extension program.
19040 			 */
19041 			bpf_log(log, "Cannot recursively attach\n");
19042 			return -EINVAL;
19043 		}
19044 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19045 		    prog_extension &&
19046 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19047 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT ||
19048 		     tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI ||
19049 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
19050 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION ||
19051 		     tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19052 			/* Program extensions can extend all program types
19053 			 * except fentry/fexit. The reason is the following.
19054 			 * The fentry/fexit programs are used for performance
19055 			 * analysis, stats and can be attached to any program
19056 			 * type. When extension program is replacing XDP function
19057 			 * it is necessary to allow performance analysis of all
19058 			 * functions. Both original XDP program and its program
19059 			 * extension. Hence attaching fentry/fexit to
19060 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
19061 			 * fentry/fexit was allowed it would be possible to create
19062 			 * long call chain fentry->extension->fentry->extension
19063 			 * beyond reasonable stack size. Hence extending fentry
19064 			 * is not allowed.
19065 			 */
19066 			bpf_log(log, "Cannot extend fentry/fexit/fsession\n");
19067 			return -EINVAL;
19068 		}
19069 	} else {
19070 		if (prog_extension) {
19071 			bpf_log(log, "Cannot replace kernel functions\n");
19072 			return -EINVAL;
19073 		}
19074 	}
19075 
19076 	switch (prog->expected_attach_type) {
19077 	case BPF_TRACE_RAW_TP:
19078 		if (tgt_prog) {
19079 			bpf_log(log,
19080 				"Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n");
19081 			return -EINVAL;
19082 		}
19083 		if (!btf_type_is_typedef(t)) {
19084 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19085 				btf_id);
19086 			return -EINVAL;
19087 		}
19088 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19089 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19090 				btf_id, tname);
19091 			return -EINVAL;
19092 		}
19093 		tname += sizeof(prefix) - 1;
19094 
19095 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
19096 		 * names. Thus using bpf_raw_event_map to get argument names.
19097 		 */
19098 		btp = bpf_get_raw_tracepoint(tname);
19099 		if (!btp)
19100 			return -EINVAL;
19101 		if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) {
19102 			bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n",
19103 				tname);
19104 			bpf_put_raw_tracepoint(btp);
19105 			return -EINVAL;
19106 		}
19107 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
19108 					trace_symbol);
19109 		bpf_put_raw_tracepoint(btp);
19110 
19111 		if (fname)
19112 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
19113 
19114 		if (!fname || ret < 0) {
19115 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
19116 				prefix, tname);
19117 			t = btf_type_by_id(btf, t->type);
19118 			if (!btf_type_is_ptr(t))
19119 				/* should never happen in valid vmlinux build */
19120 				return -EINVAL;
19121 		} else {
19122 			t = btf_type_by_id(btf, ret);
19123 			if (!btf_type_is_func(t))
19124 				/* should never happen in valid vmlinux build */
19125 				return -EINVAL;
19126 		}
19127 
19128 		t = btf_type_by_id(btf, t->type);
19129 		if (!btf_type_is_func_proto(t))
19130 			/* should never happen in valid vmlinux build */
19131 			return -EINVAL;
19132 
19133 		break;
19134 	case BPF_TRACE_ITER:
19135 		if (!btf_type_is_func(t)) {
19136 			bpf_log(log, "attach_btf_id %u is not a function\n",
19137 				btf_id);
19138 			return -EINVAL;
19139 		}
19140 		t = btf_type_by_id(btf, t->type);
19141 		if (!btf_type_is_func_proto(t))
19142 			return -EINVAL;
19143 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19144 		if (ret)
19145 			return ret;
19146 		break;
19147 	default:
19148 		if (!prog_extension)
19149 			return -EINVAL;
19150 		fallthrough;
19151 	case BPF_MODIFY_RETURN:
19152 	case BPF_LSM_MAC:
19153 	case BPF_LSM_CGROUP:
19154 	case BPF_TRACE_FENTRY:
19155 	case BPF_TRACE_FEXIT:
19156 	case BPF_TRACE_FSESSION:
19157 	case BPF_TRACE_FSESSION_MULTI:
19158 	case BPF_TRACE_FENTRY_MULTI:
19159 	case BPF_TRACE_FEXIT_MULTI:
19160 		if ((prog->expected_attach_type == BPF_TRACE_FSESSION ||
19161 		    prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
19162 		    !bpf_jit_supports_fsession()) {
19163 			bpf_log(log, "JIT does not support fsession\n");
19164 			return -EOPNOTSUPP;
19165 		}
19166 		if (!btf_type_is_func(t)) {
19167 			bpf_log(log, "attach_btf_id %u is not a function\n",
19168 				btf_id);
19169 			return -EINVAL;
19170 		}
19171 		if (prog_extension &&
19172 		    btf_check_type_match(log, prog, btf, t))
19173 			return -EINVAL;
19174 		t = btf_attach_func_proto(log, btf, btf_id);
19175 		if (!t || !btf_type_is_func_proto(t))
19176 			return -EINVAL;
19177 
19178 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19179 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19180 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19181 			return -EINVAL;
19182 
19183 		if (tgt_prog && conservative)
19184 			t = NULL;
19185 
19186 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19187 		if (ret < 0)
19188 			return ret;
19189 
19190 		/*
19191 		 * *.multi programs don't need an address during program
19192 		 * verification, we just take the module ref if needed.
19193 		 */
19194 		if (is_tracing_multi_id(prog, btf_id)) {
19195 			if (btf_is_module(btf)) {
19196 				mod = btf_try_get_module(btf);
19197 				if (!mod)
19198 					return -ENOENT;
19199 			}
19200 			addr = 0;
19201 		} else if (tgt_prog) {
19202 			if (subprog == 0)
19203 				addr = (long) tgt_prog->bpf_func;
19204 			else
19205 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19206 		} else {
19207 			if (btf_is_module(btf)) {
19208 				mod = btf_try_get_module(btf);
19209 				if (mod)
19210 					addr = find_kallsyms_symbol_value(mod, tname);
19211 				else
19212 					addr = 0;
19213 			} else {
19214 				addr = kallsyms_lookup_name(tname);
19215 			}
19216 			if (!addr) {
19217 				module_put(mod);
19218 				bpf_log(log,
19219 					"The address of function %s cannot be found\n",
19220 					tname);
19221 				return -ENOENT;
19222 			}
19223 		}
19224 
19225 		if (prog->sleepable) {
19226 			ret = btf_id_allow_sleepable(btf_id, addr, prog, btf);
19227 			if (ret) {
19228 				module_put(mod);
19229 				bpf_log(log, "%s is not sleepable\n", tname);
19230 				return ret;
19231 			}
19232 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19233 			if (tgt_prog) {
19234 				module_put(mod);
19235 				bpf_log(log, "can't modify return codes of BPF programs\n");
19236 				return -EINVAL;
19237 			}
19238 			ret = -EINVAL;
19239 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19240 			    !check_attach_modify_return(addr, tname))
19241 				ret = 0;
19242 			if (ret) {
19243 				module_put(mod);
19244 				bpf_log(log, "%s() is not modifiable\n", tname);
19245 				return ret;
19246 			}
19247 		}
19248 
19249 		break;
19250 	}
19251 	tgt_info->tgt_addr = addr;
19252 	tgt_info->tgt_name = tname;
19253 	tgt_info->tgt_type = t;
19254 	tgt_info->tgt_mod = mod;
19255 	return 0;
19256 }
19257 
19258 BTF_SET_START(btf_id_deny)
19259 BTF_ID_UNUSED
19260 #ifdef CONFIG_SMP
19261 BTF_ID(func, ___migrate_enable)
19262 BTF_ID(func, migrate_disable)
19263 BTF_ID(func, migrate_enable)
19264 #endif
19265 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19266 BTF_ID(func, rcu_read_unlock_strict)
19267 #endif
19268 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19269 BTF_ID(func, preempt_count_add)
19270 BTF_ID(func, preempt_count_sub)
19271 #endif
19272 #ifdef CONFIG_PREEMPT_RCU
19273 BTF_ID(func, __rcu_read_lock)
19274 BTF_ID(func, __rcu_read_unlock)
19275 #endif
19276 BTF_SET_END(btf_id_deny)
19277 
19278 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
19279  * Currently, we must manually list all __noreturn functions here. Once a more
19280  * robust solution is implemented, this workaround can be removed.
19281  */
19282 BTF_SET_START(noreturn_deny)
19283 #ifdef CONFIG_IA32_EMULATION
19284 BTF_ID(func, __ia32_sys_exit)
19285 BTF_ID(func, __ia32_sys_exit_group)
19286 #endif
19287 #ifdef CONFIG_KUNIT
19288 BTF_ID(func, __kunit_abort)
19289 BTF_ID(func, kunit_try_catch_throw)
19290 #endif
19291 #ifdef CONFIG_MODULES
19292 BTF_ID(func, __module_put_and_kthread_exit)
19293 #endif
19294 #ifdef CONFIG_X86_64
19295 BTF_ID(func, __x64_sys_exit)
19296 BTF_ID(func, __x64_sys_exit_group)
19297 #endif
19298 BTF_ID(func, do_exit)
19299 BTF_ID(func, do_group_exit)
19300 BTF_ID(func, kthread_complete_and_exit)
19301 BTF_ID(func, make_task_dead)
19302 BTF_SET_END(noreturn_deny)
19303 
19304 static bool can_be_sleepable(struct bpf_prog *prog)
19305 {
19306 	if (prog->type == BPF_PROG_TYPE_TRACING) {
19307 		switch (prog->expected_attach_type) {
19308 		case BPF_TRACE_FENTRY:
19309 		case BPF_TRACE_FEXIT:
19310 		case BPF_MODIFY_RETURN:
19311 		case BPF_TRACE_ITER:
19312 		case BPF_TRACE_FSESSION:
19313 		case BPF_TRACE_RAW_TP:
19314 		case BPF_TRACE_FENTRY_MULTI:
19315 		case BPF_TRACE_FEXIT_MULTI:
19316 		case BPF_TRACE_FSESSION_MULTI:
19317 			return true;
19318 		default:
19319 			return false;
19320 		}
19321 	}
19322 	if (prog->type == BPF_PROG_TYPE_LSM)
19323 		return prog->expected_attach_type != BPF_LSM_CGROUP;
19324 
19325 	return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19326 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
19327 	       prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
19328 	       prog->type == BPF_PROG_TYPE_TRACEPOINT;
19329 }
19330 
19331 static int check_attach_btf_id(struct bpf_verifier_env *env)
19332 {
19333 	struct bpf_prog *prog = env->prog;
19334 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19335 	struct bpf_attach_target_info tgt_info = {};
19336 	u32 btf_id = prog->aux->attach_btf_id;
19337 	struct bpf_trampoline *tr;
19338 	int ret;
19339 	u64 key;
19340 
19341 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19342 		if (prog->sleepable)
19343 			/* attach_btf_id checked to be zero already */
19344 			return 0;
19345 		verbose(env, "Syscall programs can only be sleepable\n");
19346 		return -EINVAL;
19347 	}
19348 
19349 	if (prog->sleepable && !can_be_sleepable(prog)) {
19350 		verbose(env, "Program of this type cannot be sleepable\n");
19351 		return -EINVAL;
19352 	}
19353 
19354 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19355 		return check_struct_ops_btf_id(env);
19356 
19357 	if (prog->type != BPF_PROG_TYPE_TRACING &&
19358 	    prog->type != BPF_PROG_TYPE_LSM &&
19359 	    prog->type != BPF_PROG_TYPE_EXT)
19360 		return 0;
19361 
19362 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19363 	if (ret)
19364 		return ret;
19365 
19366 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19367 		/* to make freplace equivalent to their targets, they need to
19368 		 * inherit env->ops and expected_attach_type for the rest of the
19369 		 * verification
19370 		 */
19371 		env->ops = bpf_verifier_ops[tgt_prog->type];
19372 		prog->expected_attach_type = tgt_prog->expected_attach_type;
19373 	}
19374 
19375 	/* store info about the attachment target that will be used later */
19376 	prog->aux->attach_func_proto = tgt_info.tgt_type;
19377 	prog->aux->attach_func_name = tgt_info.tgt_name;
19378 	prog->aux->mod = tgt_info.tgt_mod;
19379 
19380 	if (tgt_prog) {
19381 		prog->aux->saved_dst_prog_type = tgt_prog->type;
19382 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19383 	}
19384 
19385 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19386 		prog->aux->attach_btf_trace = true;
19387 		return 0;
19388 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19389 		return bpf_iter_prog_supported(prog);
19390 	}
19391 
19392 	if (prog->type == BPF_PROG_TYPE_LSM) {
19393 		ret = bpf_lsm_verify_prog(&env->log, prog);
19394 		if (ret < 0)
19395 			return ret;
19396 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
19397 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
19398 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
19399 			tgt_info.tgt_name);
19400 		return -EINVAL;
19401 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
19402 		   prog->expected_attach_type == BPF_TRACE_FSESSION ||
19403 		   prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI ||
19404 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
19405 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
19406 		verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n",
19407 			tgt_info.tgt_name);
19408 		return -EINVAL;
19409 	}
19410 
19411 	/*
19412 	 * We don't get trampoline for tracing_multi programs at this point,
19413 	 * it's done when tracing_multi link is created.
19414 	 */
19415 	if (prog->type == BPF_PROG_TYPE_TRACING &&
19416 	    is_tracing_multi(prog->expected_attach_type))
19417 		return 0;
19418 
19419 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19420 	tr = bpf_trampoline_get(key, &tgt_info);
19421 	if (!tr)
19422 		return -ENOMEM;
19423 
19424 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
19425 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
19426 
19427 	prog->aux->dst_trampoline = tr;
19428 	return 0;
19429 }
19430 
19431 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
19432 				  struct bpf_attach_target_info *tgt_info)
19433 {
19434 	const struct btf_type *t;
19435 	unsigned long addr;
19436 	const char *tname;
19437 	int err;
19438 
19439 	if (!btf_id || !btf)
19440 		return -EINVAL;
19441 
19442 	/* Check noreturn attachment. */
19443 	if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI ||
19444 	     prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) &&
19445 	     btf_id_set_contains(&noreturn_deny, btf_id))
19446 		return -EINVAL;
19447 	/* Check denied attachment. */
19448 	if (btf_id_set_contains(&btf_id_deny, btf_id))
19449 		return -EINVAL;
19450 
19451 	/* Check and get function target data. */
19452 	t = btf_type_by_id(btf, btf_id);
19453 	if (!t)
19454 		return -EINVAL;
19455 	tname = btf_name_by_offset(btf, t->name_off);
19456 	if (!tname)
19457 		return -EINVAL;
19458 	t = btf_attach_func_proto(NULL, btf, btf_id);
19459 	if (!t || !btf_type_is_func_proto(t))
19460 		return -EINVAL;
19461 	err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel);
19462 	if (err < 0)
19463 		return err;
19464 	if (btf_is_module(btf)) {
19465 		/* The bpf program already holds reference to module. */
19466 		if (WARN_ON_ONCE(!prog->aux->mod))
19467 			return -EINVAL;
19468 		addr = find_kallsyms_symbol_value(prog->aux->mod, tname);
19469 	} else {
19470 		addr = kallsyms_lookup_name(tname);
19471 	}
19472 	if (!addr || !ftrace_location(addr))
19473 		return -ENOENT;
19474 
19475 	/* Check sleepable program attachment. */
19476 	if (prog->sleepable) {
19477 		err = btf_id_allow_sleepable(btf_id, addr, prog, btf);
19478 		if (err)
19479 			return err;
19480 	}
19481 	tgt_info->tgt_addr = addr;
19482 	return 0;
19483 }
19484 
19485 struct btf *bpf_get_btf_vmlinux(void)
19486 {
19487 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19488 		mutex_lock(&bpf_verifier_lock);
19489 		if (!btf_vmlinux)
19490 			btf_vmlinux = btf_parse_vmlinux();
19491 		mutex_unlock(&bpf_verifier_lock);
19492 	}
19493 	return btf_vmlinux;
19494 }
19495 
19496 /*
19497  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
19498  * this case expect that every file descriptor in the array is either a map or
19499  * a BTF. Everything else is considered to be trash.
19500  */
19501 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
19502 {
19503 	struct bpf_map *map;
19504 	struct btf *btf;
19505 	CLASS(fd, f)(fd);
19506 	int err;
19507 
19508 	map = __bpf_map_get(f);
19509 	if (!IS_ERR(map)) {
19510 		err = __add_used_map(env, map);
19511 		if (err < 0)
19512 			return err;
19513 		return 0;
19514 	}
19515 
19516 	btf = __btf_get_by_fd(f);
19517 	if (!IS_ERR(btf)) {
19518 		btf_get(btf);
19519 		return __add_used_btf(env, btf);
19520 	}
19521 
19522 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
19523 	return PTR_ERR(map);
19524 }
19525 
19526 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
19527 {
19528 	size_t size = sizeof(int);
19529 	int ret;
19530 	int fd;
19531 	u32 i;
19532 
19533 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19534 
19535 	/*
19536 	 * The only difference between old (no fd_array_cnt is given) and new
19537 	 * APIs is that in the latter case the fd_array is expected to be
19538 	 * continuous and is scanned for map fds right away
19539 	 */
19540 	if (!attr->fd_array_cnt)
19541 		return 0;
19542 
19543 	/* Check for integer overflow */
19544 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
19545 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
19546 		return -EINVAL;
19547 	}
19548 
19549 	for (i = 0; i < attr->fd_array_cnt; i++) {
19550 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
19551 			return -EFAULT;
19552 
19553 		ret = add_fd_from_fd_array(env, fd);
19554 		if (ret)
19555 			return ret;
19556 	}
19557 
19558 	return 0;
19559 }
19560 
19561 /* replace a generic kfunc with a specialized version if necessary */
19562 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
19563 {
19564 	struct bpf_prog *prog = env->prog;
19565 	bool seen_direct_write;
19566 	void *xdp_kfunc;
19567 	bool is_rdonly;
19568 	u32 func_id = desc->func_id;
19569 	u16 offset = desc->offset;
19570 	unsigned long addr = desc->addr;
19571 
19572 	if (offset) /* return if module BTF is used */
19573 		return 0;
19574 
19575 	if (bpf_dev_bound_kfunc_id(func_id)) {
19576 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19577 		if (xdp_kfunc)
19578 			addr = (unsigned long)xdp_kfunc;
19579 		/* fallback to default kfunc when not supported by netdev */
19580 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19581 		seen_direct_write = env->seen_direct_write;
19582 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19583 
19584 		if (is_rdonly)
19585 			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19586 
19587 		/* restore env->seen_direct_write to its original value, since
19588 		 * may_access_direct_pkt_data mutates it
19589 		 */
19590 		env->seen_direct_write = seen_direct_write;
19591 	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
19592 		if (bpf_lsm_has_d_inode_locked(prog))
19593 			addr = (unsigned long)bpf_set_dentry_xattr_locked;
19594 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
19595 		if (bpf_lsm_has_d_inode_locked(prog))
19596 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
19597 	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
19598 		if (!env->insn_aux_data[insn_idx].non_sleepable)
19599 			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
19600 	} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {
19601 		if (env->insn_aux_data[insn_idx].non_sleepable)
19602 			addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;
19603 	} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {
19604 		if (env->insn_aux_data[insn_idx].non_sleepable)
19605 			addr = (unsigned long)bpf_arena_free_pages_non_sleepable;
19606 	}
19607 	desc->addr = addr;
19608 	return 0;
19609 }
19610 
19611 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19612 					    u16 struct_meta_reg,
19613 					    u16 node_offset_reg,
19614 					    struct bpf_insn *insn,
19615 					    struct bpf_insn *insn_buf,
19616 					    int *cnt)
19617 {
19618 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19619 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19620 
19621 	insn_buf[0] = addr[0];
19622 	insn_buf[1] = addr[1];
19623 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19624 	insn_buf[3] = *insn;
19625 	*cnt = 4;
19626 }
19627 
19628 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19629 		     struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19630 {
19631 	struct bpf_kfunc_desc *desc;
19632 	int err;
19633 
19634 	if (!insn->imm) {
19635 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19636 		return -EINVAL;
19637 	}
19638 
19639 	*cnt = 0;
19640 
19641 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19642 	 * __bpf_call_base, unless the JIT needs to call functions that are
19643 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19644 	 */
19645 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19646 	if (!desc) {
19647 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
19648 			     insn->imm);
19649 		return -EFAULT;
19650 	}
19651 
19652 	err = specialize_kfunc(env, desc, insn_idx);
19653 	if (err)
19654 		return err;
19655 
19656 	if (!bpf_jit_supports_far_kfunc_call())
19657 		insn->imm = BPF_CALL_IMM(desc->addr);
19658 
19659 	if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) {
19660 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19661 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19662 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19663 
19664 		if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) {
19665 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
19666 				     insn_idx);
19667 			return -EFAULT;
19668 		}
19669 
19670 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19671 		insn_buf[1] = addr[0];
19672 		insn_buf[2] = addr[1];
19673 		insn_buf[3] = *insn;
19674 		*cnt = 4;
19675 	} else if (is_bpf_obj_drop_kfunc(desc->func_id) ||
19676 		   is_bpf_percpu_obj_drop_kfunc(desc->func_id) ||
19677 		   is_bpf_refcount_acquire_kfunc(desc->func_id)) {
19678 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19679 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19680 
19681 		if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) {
19682 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
19683 				     insn_idx);
19684 			return -EFAULT;
19685 		}
19686 
19687 		if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) {
19688 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
19689 				     insn_idx);
19690 			return -EFAULT;
19691 		}
19692 
19693 		insn_buf[0] = addr[0];
19694 		insn_buf[1] = addr[1];
19695 		insn_buf[2] = *insn;
19696 		*cnt = 3;
19697 	} else if (is_bpf_list_push_kfunc(desc->func_id) ||
19698 		   is_bpf_rbtree_add_kfunc(desc->func_id)) {
19699 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19700 		int struct_meta_reg = BPF_REG_3;
19701 		int node_offset_reg = BPF_REG_4;
19702 
19703 		/* list_add/rbtree_add have an extra arg (prev/less),
19704 		 * so args-to-fixup are in diff regs.
19705 		 */
19706 		if (desc->func_id == special_kfunc_list[KF_bpf_list_add] ||
19707 		    is_bpf_rbtree_add_kfunc(desc->func_id)) {
19708 			struct_meta_reg = BPF_REG_4;
19709 			node_offset_reg = BPF_REG_5;
19710 		}
19711 
19712 		if (!kptr_struct_meta) {
19713 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
19714 				     insn_idx);
19715 			return -EFAULT;
19716 		}
19717 
19718 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19719 						node_offset_reg, insn, insn_buf, cnt);
19720 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19721 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19722 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19723 		*cnt = 1;
19724 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] &&
19725 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
19726 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19727 
19728 		/*
19729 		 * inline the bpf_session_is_return() for fsession:
19730 		 *   bool bpf_session_is_return(void *ctx)
19731 		 *   {
19732 		 *       return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1;
19733 		 *   }
19734 		 */
19735 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19736 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT);
19737 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1);
19738 		*cnt = 3;
19739 	} else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] &&
19740 		   (env->prog->expected_attach_type == BPF_TRACE_FSESSION ||
19741 		    env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) {
19742 		/*
19743 		 * inline bpf_session_cookie() for fsession:
19744 		 *   __u64 *bpf_session_cookie(void *ctx)
19745 		 *   {
19746 		 *       u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF;
19747 		 *       return &((u64 *)ctx)[-off];
19748 		 *   }
19749 		 */
19750 		insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19751 		insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT);
19752 		insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
19753 		insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19754 		insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1);
19755 		insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0);
19756 		*cnt = 6;
19757 	}
19758 
19759 	if (env->insn_aux_data[insn_idx].arg_prog) {
19760 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
19761 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
19762 		int idx = *cnt;
19763 
19764 		insn_buf[idx++] = ld_addrs[0];
19765 		insn_buf[idx++] = ld_addrs[1];
19766 		insn_buf[idx++] = *insn;
19767 		*cnt = idx;
19768 	}
19769 	return 0;
19770 }
19771 
19772 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
19773 	      struct bpf_log_attr *attr_log)
19774 {
19775 	u64 start_time = ktime_get_ns();
19776 	struct bpf_verifier_env *env;
19777 	int i, len, ret = -EINVAL, err;
19778 	bool is_priv;
19779 
19780 	BTF_TYPE_EMIT(enum bpf_features);
19781 
19782 	/* no program is valid */
19783 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19784 		return -EINVAL;
19785 
19786 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
19787 	 * allocate/free it every time bpf_check() is called
19788 	 */
19789 	env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT);
19790 	if (!env)
19791 		return -ENOMEM;
19792 
19793 	env->bt.env = env;
19794 
19795 	len = (*prog)->len;
19796 	env->insn_aux_data =
19797 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19798 	ret = -ENOMEM;
19799 	if (!env->insn_aux_data)
19800 		goto err_free_env;
19801 	for (i = 0; i < len; i++)
19802 		env->insn_aux_data[i].orig_idx = i;
19803 	env->succ = bpf_iarray_realloc(NULL, 2);
19804 	if (!env->succ)
19805 		goto err_free_env;
19806 	env->prog = *prog;
19807 	env->ops = bpf_verifier_ops[env->prog->type];
19808 
19809 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
19810 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
19811 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
19812 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
19813 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
19814 
19815 	bpf_get_btf_vmlinux();
19816 
19817 	/* grab the mutex to protect few globals used by verifier */
19818 	if (!is_priv)
19819 		mutex_lock(&bpf_verifier_lock);
19820 
19821 	/* user could have requested verbose verifier output
19822 	 * and supplied buffer to store the verification trace
19823 	 */
19824 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
19825 	if (ret)
19826 		goto err_unlock;
19827 
19828 	ret = process_fd_array(env, attr, uattr);
19829 	if (ret)
19830 		goto skip_full_check;
19831 
19832 	mark_verifier_state_clean(env);
19833 
19834 	if (IS_ERR(btf_vmlinux)) {
19835 		/* Either gcc or pahole or kernel are broken. */
19836 		verbose(env, "in-kernel BTF is malformed\n");
19837 		ret = PTR_ERR(btf_vmlinux);
19838 		goto skip_full_check;
19839 	}
19840 
19841 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19842 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19843 		env->strict_alignment = true;
19844 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19845 		env->strict_alignment = false;
19846 
19847 	if (is_priv)
19848 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19849 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
19850 
19851 	env->explored_states = kvzalloc_objs(struct list_head,
19852 					     state_htab_size(env),
19853 					     GFP_KERNEL_ACCOUNT);
19854 	ret = -ENOMEM;
19855 	if (!env->explored_states)
19856 		goto skip_full_check;
19857 
19858 	for (i = 0; i < state_htab_size(env); i++)
19859 		INIT_LIST_HEAD(&env->explored_states[i]);
19860 	INIT_LIST_HEAD(&env->free_list);
19861 
19862 	ret = bpf_check_btf_info_early(env, attr, uattr);
19863 	if (ret < 0)
19864 		goto skip_full_check;
19865 
19866 	ret = add_subprog_and_kfunc(env);
19867 	if (ret < 0)
19868 		goto skip_full_check;
19869 
19870 	ret = check_subprogs(env);
19871 	if (ret < 0)
19872 		goto skip_full_check;
19873 
19874 	ret = bpf_check_btf_info(env, attr, uattr);
19875 	if (ret < 0)
19876 		goto skip_full_check;
19877 
19878 	ret = check_and_resolve_insns(env);
19879 	if (ret < 0)
19880 		goto skip_full_check;
19881 
19882 	if (bpf_prog_is_offloaded(env->prog->aux)) {
19883 		ret = bpf_prog_offload_verifier_prep(env->prog);
19884 		if (ret)
19885 			goto skip_full_check;
19886 	}
19887 
19888 	ret = bpf_check_cfg(env);
19889 	if (ret < 0)
19890 		goto skip_full_check;
19891 
19892 	ret = bpf_compute_postorder(env);
19893 	if (ret < 0)
19894 		goto skip_full_check;
19895 
19896 	ret = bpf_stack_liveness_init(env);
19897 	if (ret)
19898 		goto skip_full_check;
19899 
19900 	ret = check_attach_btf_id(env);
19901 	if (ret)
19902 		goto skip_full_check;
19903 
19904 	ret = bpf_compute_const_regs(env);
19905 	if (ret < 0)
19906 		goto skip_full_check;
19907 
19908 	ret = bpf_prune_dead_branches(env);
19909 	if (ret < 0)
19910 		goto skip_full_check;
19911 
19912 	ret = sort_subprogs_topo(env);
19913 	if (ret < 0)
19914 		goto skip_full_check;
19915 
19916 	ret = bpf_compute_scc(env);
19917 	if (ret < 0)
19918 		goto skip_full_check;
19919 
19920 	ret = bpf_compute_live_registers(env);
19921 	if (ret < 0)
19922 		goto skip_full_check;
19923 
19924 	ret = mark_fastcall_patterns(env);
19925 	if (ret < 0)
19926 		goto skip_full_check;
19927 
19928 	ret = do_check_main(env);
19929 	ret = ret ?: do_check_subprogs(env);
19930 
19931 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19932 		ret = bpf_prog_offload_finalize(env);
19933 
19934 skip_full_check:
19935 	kvfree(env->explored_states);
19936 
19937 	/* might decrease stack depth, keep it before passes that
19938 	 * allocate additional slots.
19939 	 */
19940 	if (ret == 0)
19941 		ret = bpf_remove_fastcall_spills_fills(env);
19942 
19943 	if (ret == 0)
19944 		ret = check_max_stack_depth(env);
19945 
19946 	/* instruction rewrites happen after this point */
19947 	if (ret == 0)
19948 		ret = bpf_optimize_bpf_loop(env);
19949 
19950 	if (is_priv) {
19951 		if (ret == 0)
19952 			bpf_opt_hard_wire_dead_code_branches(env);
19953 		if (ret == 0)
19954 			ret = bpf_opt_remove_dead_code(env);
19955 		if (ret == 0)
19956 			ret = bpf_opt_remove_nops(env);
19957 	} else {
19958 		if (ret == 0)
19959 			sanitize_dead_code(env);
19960 	}
19961 
19962 	if (ret == 0)
19963 		/* program is valid, convert *(u32*)(ctx + off) accesses */
19964 		ret = bpf_convert_ctx_accesses(env);
19965 
19966 	if (ret == 0)
19967 		ret = bpf_do_misc_fixups(env);
19968 
19969 	/* do 32-bit optimization after insn patching has done so those patched
19970 	 * insns could be handled correctly.
19971 	 */
19972 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19973 		ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr);
19974 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19975 								     : false;
19976 	}
19977 
19978 	if (ret == 0)
19979 		ret = bpf_fixup_call_args(env);
19980 
19981 	env->verification_time = ktime_get_ns() - start_time;
19982 	print_verification_stats(env);
19983 	env->prog->aux->verified_insns = env->insn_processed;
19984 
19985 	/* preserve original error even if log finalization is successful */
19986 	err = bpf_log_attr_finalize(attr_log, &env->log);
19987 	if (err)
19988 		ret = err;
19989 
19990 	if (ret)
19991 		goto err_release_maps;
19992 
19993 	if (env->used_map_cnt) {
19994 		/* if program passed verifier, update used_maps in bpf_prog_info */
19995 		env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0],
19996 							 env->used_map_cnt,
19997 							 GFP_KERNEL_ACCOUNT);
19998 
19999 		if (!env->prog->aux->used_maps) {
20000 			ret = -ENOMEM;
20001 			goto err_release_maps;
20002 		}
20003 
20004 		memcpy(env->prog->aux->used_maps, env->used_maps,
20005 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20006 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20007 	}
20008 	if (env->used_btf_cnt) {
20009 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20010 		env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0],
20011 							 env->used_btf_cnt,
20012 							 GFP_KERNEL_ACCOUNT);
20013 		if (!env->prog->aux->used_btfs) {
20014 			ret = -ENOMEM;
20015 			goto err_release_maps;
20016 		}
20017 
20018 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20019 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20020 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20021 	}
20022 	if (env->used_map_cnt || env->used_btf_cnt) {
20023 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20024 		 * bpf_ld_imm64 instructions
20025 		 */
20026 		convert_pseudo_ld_imm64(env);
20027 	}
20028 
20029 	adjust_btf_func(env);
20030 
20031 	/* extension progs temporarily inherit the attach_type of their targets
20032 	   for verification purposes, so set it back to zero before returning
20033 	 */
20034 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20035 		env->prog->expected_attach_type = 0;
20036 
20037 	env->prog = __bpf_prog_select_runtime(env, env->prog, &ret);
20038 
20039 err_release_maps:
20040 	if (ret)
20041 		release_insn_arrays(env);
20042 	if (!env->prog->aux->used_maps)
20043 		/* if we didn't copy map pointers into bpf_prog_info, release
20044 		 * them now. Otherwise free_used_maps() will release them.
20045 		 */
20046 		release_maps(env);
20047 	if (!env->prog->aux->used_btfs)
20048 		release_btfs(env);
20049 
20050 	*prog = env->prog;
20051 
20052 	module_put(env->attach_btf_mod);
20053 err_unlock:
20054 	if (!is_priv)
20055 		mutex_unlock(&bpf_verifier_lock);
20056 	bpf_clear_insn_aux_data(env, 0, env->prog->len);
20057 err_free_env:
20058 	bpf_stack_liveness_free(env);
20059 	kvfree(env->cfg.insn_postorder);
20060 	kvfree(env->scc_info);
20061 	kvfree(env->succ);
20062 	kvfree(env->gotox_tmp_buf);
20063 	vfree(env->insn_aux_data);
20064 	kvfree(env);
20065 	return ret;
20066 }
20067