xref: /openbmc/linux/kernel/bpf/verifier.c (revision 0e6774ec)
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 <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 	if (type_may_be_null(flag))
2543 		regs[regno].id = ++env->id_gen;
2544 }
2545 
2546 #define DEF_NOT_SUBREG	(0)
2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 			   struct bpf_func_state *state)
2549 {
2550 	struct bpf_reg_state *regs = state->regs;
2551 	int i;
2552 
2553 	for (i = 0; i < MAX_BPF_REG; i++) {
2554 		mark_reg_not_init(env, regs, i);
2555 		regs[i].live = REG_LIVE_NONE;
2556 		regs[i].parent = NULL;
2557 		regs[i].subreg_def = DEF_NOT_SUBREG;
2558 	}
2559 
2560 	/* frame pointer */
2561 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2562 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2563 	regs[BPF_REG_FP].frameno = state->frameno;
2564 }
2565 
2566 #define BPF_MAIN_FUNC (-1)
2567 static void init_func_state(struct bpf_verifier_env *env,
2568 			    struct bpf_func_state *state,
2569 			    int callsite, int frameno, int subprogno)
2570 {
2571 	state->callsite = callsite;
2572 	state->frameno = frameno;
2573 	state->subprogno = subprogno;
2574 	state->callback_ret_range = tnum_range(0, 0);
2575 	init_reg_state(env, state);
2576 	mark_verifier_state_scratched(env);
2577 }
2578 
2579 /* Similar to push_stack(), but for async callbacks */
2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581 						int insn_idx, int prev_insn_idx,
2582 						int subprog)
2583 {
2584 	struct bpf_verifier_stack_elem *elem;
2585 	struct bpf_func_state *frame;
2586 
2587 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588 	if (!elem)
2589 		goto err;
2590 
2591 	elem->insn_idx = insn_idx;
2592 	elem->prev_insn_idx = prev_insn_idx;
2593 	elem->next = env->head;
2594 	elem->log_pos = env->log.end_pos;
2595 	env->head = elem;
2596 	env->stack_size++;
2597 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598 		verbose(env,
2599 			"The sequence of %d jumps is too complex for async cb.\n",
2600 			env->stack_size);
2601 		goto err;
2602 	}
2603 	/* Unlike push_stack() do not copy_verifier_state().
2604 	 * The caller state doesn't matter.
2605 	 * This is async callback. It starts in a fresh stack.
2606 	 * Initialize it similar to do_check_common().
2607 	 */
2608 	elem->st.branches = 1;
2609 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610 	if (!frame)
2611 		goto err;
2612 	init_func_state(env, frame,
2613 			BPF_MAIN_FUNC /* callsite */,
2614 			0 /* frameno within this callchain */,
2615 			subprog /* subprog number within this prog */);
2616 	elem->st.frame[0] = frame;
2617 	return &elem->st;
2618 err:
2619 	free_verifier_state(env->cur_state, true);
2620 	env->cur_state = NULL;
2621 	/* pop all elements and return */
2622 	while (!pop_stack(env, NULL, NULL, false));
2623 	return NULL;
2624 }
2625 
2626 
2627 enum reg_arg_type {
2628 	SRC_OP,		/* register is used as source operand */
2629 	DST_OP,		/* register is used as destination operand */
2630 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2631 };
2632 
2633 static int cmp_subprogs(const void *a, const void *b)
2634 {
2635 	return ((struct bpf_subprog_info *)a)->start -
2636 	       ((struct bpf_subprog_info *)b)->start;
2637 }
2638 
2639 static int find_subprog(struct bpf_verifier_env *env, int off)
2640 {
2641 	struct bpf_subprog_info *p;
2642 
2643 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2644 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2645 	if (!p)
2646 		return -ENOENT;
2647 	return p - env->subprog_info;
2648 
2649 }
2650 
2651 static int add_subprog(struct bpf_verifier_env *env, int off)
2652 {
2653 	int insn_cnt = env->prog->len;
2654 	int ret;
2655 
2656 	if (off >= insn_cnt || off < 0) {
2657 		verbose(env, "call to invalid destination\n");
2658 		return -EINVAL;
2659 	}
2660 	ret = find_subprog(env, off);
2661 	if (ret >= 0)
2662 		return ret;
2663 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2664 		verbose(env, "too many subprograms\n");
2665 		return -E2BIG;
2666 	}
2667 	/* determine subprog starts. The end is one before the next starts */
2668 	env->subprog_info[env->subprog_cnt++].start = off;
2669 	sort(env->subprog_info, env->subprog_cnt,
2670 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2671 	return env->subprog_cnt - 1;
2672 }
2673 
2674 #define MAX_KFUNC_DESCS 256
2675 #define MAX_KFUNC_BTFS	256
2676 
2677 struct bpf_kfunc_desc {
2678 	struct btf_func_model func_model;
2679 	u32 func_id;
2680 	s32 imm;
2681 	u16 offset;
2682 	unsigned long addr;
2683 };
2684 
2685 struct bpf_kfunc_btf {
2686 	struct btf *btf;
2687 	struct module *module;
2688 	u16 offset;
2689 };
2690 
2691 struct bpf_kfunc_desc_tab {
2692 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2693 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2694 	 * available, therefore at the end of verification do_misc_fixups()
2695 	 * sorts this by imm and offset.
2696 	 */
2697 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2698 	u32 nr_descs;
2699 };
2700 
2701 struct bpf_kfunc_btf_tab {
2702 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2703 	u32 nr_descs;
2704 };
2705 
2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2707 {
2708 	const struct bpf_kfunc_desc *d0 = a;
2709 	const struct bpf_kfunc_desc *d1 = b;
2710 
2711 	/* func_id is not greater than BTF_MAX_TYPE */
2712 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2713 }
2714 
2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2716 {
2717 	const struct bpf_kfunc_btf *d0 = a;
2718 	const struct bpf_kfunc_btf *d1 = b;
2719 
2720 	return d0->offset - d1->offset;
2721 }
2722 
2723 static const struct bpf_kfunc_desc *
2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2725 {
2726 	struct bpf_kfunc_desc desc = {
2727 		.func_id = func_id,
2728 		.offset = offset,
2729 	};
2730 	struct bpf_kfunc_desc_tab *tab;
2731 
2732 	tab = prog->aux->kfunc_tab;
2733 	return bsearch(&desc, tab->descs, tab->nr_descs,
2734 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2735 }
2736 
2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2738 		       u16 btf_fd_idx, u8 **func_addr)
2739 {
2740 	const struct bpf_kfunc_desc *desc;
2741 
2742 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2743 	if (!desc)
2744 		return -EFAULT;
2745 
2746 	*func_addr = (u8 *)desc->addr;
2747 	return 0;
2748 }
2749 
2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2751 					 s16 offset)
2752 {
2753 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2754 	struct bpf_kfunc_btf_tab *tab;
2755 	struct bpf_kfunc_btf *b;
2756 	struct module *mod;
2757 	struct btf *btf;
2758 	int btf_fd;
2759 
2760 	tab = env->prog->aux->kfunc_btf_tab;
2761 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2762 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2763 	if (!b) {
2764 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2765 			verbose(env, "too many different module BTFs\n");
2766 			return ERR_PTR(-E2BIG);
2767 		}
2768 
2769 		if (bpfptr_is_null(env->fd_array)) {
2770 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2771 			return ERR_PTR(-EPROTO);
2772 		}
2773 
2774 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2775 					    offset * sizeof(btf_fd),
2776 					    sizeof(btf_fd)))
2777 			return ERR_PTR(-EFAULT);
2778 
2779 		btf = btf_get_by_fd(btf_fd);
2780 		if (IS_ERR(btf)) {
2781 			verbose(env, "invalid module BTF fd specified\n");
2782 			return btf;
2783 		}
2784 
2785 		if (!btf_is_module(btf)) {
2786 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2787 			btf_put(btf);
2788 			return ERR_PTR(-EINVAL);
2789 		}
2790 
2791 		mod = btf_try_get_module(btf);
2792 		if (!mod) {
2793 			btf_put(btf);
2794 			return ERR_PTR(-ENXIO);
2795 		}
2796 
2797 		b = &tab->descs[tab->nr_descs++];
2798 		b->btf = btf;
2799 		b->module = mod;
2800 		b->offset = offset;
2801 
2802 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2803 		     kfunc_btf_cmp_by_off, NULL);
2804 	}
2805 	return b->btf;
2806 }
2807 
2808 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2809 {
2810 	if (!tab)
2811 		return;
2812 
2813 	while (tab->nr_descs--) {
2814 		module_put(tab->descs[tab->nr_descs].module);
2815 		btf_put(tab->descs[tab->nr_descs].btf);
2816 	}
2817 	kfree(tab);
2818 }
2819 
2820 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2821 {
2822 	if (offset) {
2823 		if (offset < 0) {
2824 			/* In the future, this can be allowed to increase limit
2825 			 * of fd index into fd_array, interpreted as u16.
2826 			 */
2827 			verbose(env, "negative offset disallowed for kernel module function call\n");
2828 			return ERR_PTR(-EINVAL);
2829 		}
2830 
2831 		return __find_kfunc_desc_btf(env, offset);
2832 	}
2833 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2834 }
2835 
2836 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2837 {
2838 	const struct btf_type *func, *func_proto;
2839 	struct bpf_kfunc_btf_tab *btf_tab;
2840 	struct bpf_kfunc_desc_tab *tab;
2841 	struct bpf_prog_aux *prog_aux;
2842 	struct bpf_kfunc_desc *desc;
2843 	const char *func_name;
2844 	struct btf *desc_btf;
2845 	unsigned long call_imm;
2846 	unsigned long addr;
2847 	int err;
2848 
2849 	prog_aux = env->prog->aux;
2850 	tab = prog_aux->kfunc_tab;
2851 	btf_tab = prog_aux->kfunc_btf_tab;
2852 	if (!tab) {
2853 		if (!btf_vmlinux) {
2854 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2855 			return -ENOTSUPP;
2856 		}
2857 
2858 		if (!env->prog->jit_requested) {
2859 			verbose(env, "JIT is required for calling kernel function\n");
2860 			return -ENOTSUPP;
2861 		}
2862 
2863 		if (!bpf_jit_supports_kfunc_call()) {
2864 			verbose(env, "JIT does not support calling kernel function\n");
2865 			return -ENOTSUPP;
2866 		}
2867 
2868 		if (!env->prog->gpl_compatible) {
2869 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2870 			return -EINVAL;
2871 		}
2872 
2873 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2874 		if (!tab)
2875 			return -ENOMEM;
2876 		prog_aux->kfunc_tab = tab;
2877 	}
2878 
2879 	/* func_id == 0 is always invalid, but instead of returning an error, be
2880 	 * conservative and wait until the code elimination pass before returning
2881 	 * error, so that invalid calls that get pruned out can be in BPF programs
2882 	 * loaded from userspace.  It is also required that offset be untouched
2883 	 * for such calls.
2884 	 */
2885 	if (!func_id && !offset)
2886 		return 0;
2887 
2888 	if (!btf_tab && offset) {
2889 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2890 		if (!btf_tab)
2891 			return -ENOMEM;
2892 		prog_aux->kfunc_btf_tab = btf_tab;
2893 	}
2894 
2895 	desc_btf = find_kfunc_desc_btf(env, offset);
2896 	if (IS_ERR(desc_btf)) {
2897 		verbose(env, "failed to find BTF for kernel function\n");
2898 		return PTR_ERR(desc_btf);
2899 	}
2900 
2901 	if (find_kfunc_desc(env->prog, func_id, offset))
2902 		return 0;
2903 
2904 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2905 		verbose(env, "too many different kernel function calls\n");
2906 		return -E2BIG;
2907 	}
2908 
2909 	func = btf_type_by_id(desc_btf, func_id);
2910 	if (!func || !btf_type_is_func(func)) {
2911 		verbose(env, "kernel btf_id %u is not a function\n",
2912 			func_id);
2913 		return -EINVAL;
2914 	}
2915 	func_proto = btf_type_by_id(desc_btf, func->type);
2916 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2917 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2918 			func_id);
2919 		return -EINVAL;
2920 	}
2921 
2922 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2923 	addr = kallsyms_lookup_name(func_name);
2924 	if (!addr) {
2925 		verbose(env, "cannot find address for kernel function %s\n",
2926 			func_name);
2927 		return -EINVAL;
2928 	}
2929 	specialize_kfunc(env, func_id, offset, &addr);
2930 
2931 	if (bpf_jit_supports_far_kfunc_call()) {
2932 		call_imm = func_id;
2933 	} else {
2934 		call_imm = BPF_CALL_IMM(addr);
2935 		/* Check whether the relative offset overflows desc->imm */
2936 		if ((unsigned long)(s32)call_imm != call_imm) {
2937 			verbose(env, "address of kernel function %s is out of range\n",
2938 				func_name);
2939 			return -EINVAL;
2940 		}
2941 	}
2942 
2943 	if (bpf_dev_bound_kfunc_id(func_id)) {
2944 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2945 		if (err)
2946 			return err;
2947 	}
2948 
2949 	desc = &tab->descs[tab->nr_descs++];
2950 	desc->func_id = func_id;
2951 	desc->imm = call_imm;
2952 	desc->offset = offset;
2953 	desc->addr = addr;
2954 	err = btf_distill_func_proto(&env->log, desc_btf,
2955 				     func_proto, func_name,
2956 				     &desc->func_model);
2957 	if (!err)
2958 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2959 		     kfunc_desc_cmp_by_id_off, NULL);
2960 	return err;
2961 }
2962 
2963 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2964 {
2965 	const struct bpf_kfunc_desc *d0 = a;
2966 	const struct bpf_kfunc_desc *d1 = b;
2967 
2968 	if (d0->imm != d1->imm)
2969 		return d0->imm < d1->imm ? -1 : 1;
2970 	if (d0->offset != d1->offset)
2971 		return d0->offset < d1->offset ? -1 : 1;
2972 	return 0;
2973 }
2974 
2975 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2976 {
2977 	struct bpf_kfunc_desc_tab *tab;
2978 
2979 	tab = prog->aux->kfunc_tab;
2980 	if (!tab)
2981 		return;
2982 
2983 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2984 	     kfunc_desc_cmp_by_imm_off, NULL);
2985 }
2986 
2987 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2988 {
2989 	return !!prog->aux->kfunc_tab;
2990 }
2991 
2992 const struct btf_func_model *
2993 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2994 			 const struct bpf_insn *insn)
2995 {
2996 	const struct bpf_kfunc_desc desc = {
2997 		.imm = insn->imm,
2998 		.offset = insn->off,
2999 	};
3000 	const struct bpf_kfunc_desc *res;
3001 	struct bpf_kfunc_desc_tab *tab;
3002 
3003 	tab = prog->aux->kfunc_tab;
3004 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3005 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3006 
3007 	return res ? &res->func_model : NULL;
3008 }
3009 
3010 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3011 {
3012 	struct bpf_subprog_info *subprog = env->subprog_info;
3013 	struct bpf_insn *insn = env->prog->insnsi;
3014 	int i, ret, insn_cnt = env->prog->len;
3015 
3016 	/* Add entry function. */
3017 	ret = add_subprog(env, 0);
3018 	if (ret)
3019 		return ret;
3020 
3021 	for (i = 0; i < insn_cnt; i++, insn++) {
3022 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3023 		    !bpf_pseudo_kfunc_call(insn))
3024 			continue;
3025 
3026 		if (!env->bpf_capable) {
3027 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3028 			return -EPERM;
3029 		}
3030 
3031 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3032 			ret = add_subprog(env, i + insn->imm + 1);
3033 		else
3034 			ret = add_kfunc_call(env, insn->imm, insn->off);
3035 
3036 		if (ret < 0)
3037 			return ret;
3038 	}
3039 
3040 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3041 	 * logic. 'subprog_cnt' should not be increased.
3042 	 */
3043 	subprog[env->subprog_cnt].start = insn_cnt;
3044 
3045 	if (env->log.level & BPF_LOG_LEVEL2)
3046 		for (i = 0; i < env->subprog_cnt; i++)
3047 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3048 
3049 	return 0;
3050 }
3051 
3052 static int check_subprogs(struct bpf_verifier_env *env)
3053 {
3054 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3055 	struct bpf_subprog_info *subprog = env->subprog_info;
3056 	struct bpf_insn *insn = env->prog->insnsi;
3057 	int insn_cnt = env->prog->len;
3058 
3059 	/* now check that all jumps are within the same subprog */
3060 	subprog_start = subprog[cur_subprog].start;
3061 	subprog_end = subprog[cur_subprog + 1].start;
3062 	for (i = 0; i < insn_cnt; i++) {
3063 		u8 code = insn[i].code;
3064 
3065 		if (code == (BPF_JMP | BPF_CALL) &&
3066 		    insn[i].src_reg == 0 &&
3067 		    insn[i].imm == BPF_FUNC_tail_call) {
3068 			subprog[cur_subprog].has_tail_call = true;
3069 			subprog[cur_subprog].tail_call_reachable = true;
3070 		}
3071 		if (BPF_CLASS(code) == BPF_LD &&
3072 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3073 			subprog[cur_subprog].has_ld_abs = true;
3074 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3075 			goto next;
3076 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3077 			goto next;
3078 		if (code == (BPF_JMP32 | BPF_JA))
3079 			off = i + insn[i].imm + 1;
3080 		else
3081 			off = i + insn[i].off + 1;
3082 		if (off < subprog_start || off >= subprog_end) {
3083 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3084 			return -EINVAL;
3085 		}
3086 next:
3087 		if (i == subprog_end - 1) {
3088 			/* to avoid fall-through from one subprog into another
3089 			 * the last insn of the subprog should be either exit
3090 			 * or unconditional jump back
3091 			 */
3092 			if (code != (BPF_JMP | BPF_EXIT) &&
3093 			    code != (BPF_JMP32 | BPF_JA) &&
3094 			    code != (BPF_JMP | BPF_JA)) {
3095 				verbose(env, "last insn is not an exit or jmp\n");
3096 				return -EINVAL;
3097 			}
3098 			subprog_start = subprog_end;
3099 			cur_subprog++;
3100 			if (cur_subprog < env->subprog_cnt)
3101 				subprog_end = subprog[cur_subprog + 1].start;
3102 		}
3103 	}
3104 	return 0;
3105 }
3106 
3107 /* Parentage chain of this register (or stack slot) should take care of all
3108  * issues like callee-saved registers, stack slot allocation time, etc.
3109  */
3110 static int mark_reg_read(struct bpf_verifier_env *env,
3111 			 const struct bpf_reg_state *state,
3112 			 struct bpf_reg_state *parent, u8 flag)
3113 {
3114 	bool writes = parent == state->parent; /* Observe write marks */
3115 	int cnt = 0;
3116 
3117 	while (parent) {
3118 		/* if read wasn't screened by an earlier write ... */
3119 		if (writes && state->live & REG_LIVE_WRITTEN)
3120 			break;
3121 		if (parent->live & REG_LIVE_DONE) {
3122 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3123 				reg_type_str(env, parent->type),
3124 				parent->var_off.value, parent->off);
3125 			return -EFAULT;
3126 		}
3127 		/* The first condition is more likely to be true than the
3128 		 * second, checked it first.
3129 		 */
3130 		if ((parent->live & REG_LIVE_READ) == flag ||
3131 		    parent->live & REG_LIVE_READ64)
3132 			/* The parentage chain never changes and
3133 			 * this parent was already marked as LIVE_READ.
3134 			 * There is no need to keep walking the chain again and
3135 			 * keep re-marking all parents as LIVE_READ.
3136 			 * This case happens when the same register is read
3137 			 * multiple times without writes into it in-between.
3138 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3139 			 * then no need to set the weak REG_LIVE_READ32.
3140 			 */
3141 			break;
3142 		/* ... then we depend on parent's value */
3143 		parent->live |= flag;
3144 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3145 		if (flag == REG_LIVE_READ64)
3146 			parent->live &= ~REG_LIVE_READ32;
3147 		state = parent;
3148 		parent = state->parent;
3149 		writes = true;
3150 		cnt++;
3151 	}
3152 
3153 	if (env->longest_mark_read_walk < cnt)
3154 		env->longest_mark_read_walk = cnt;
3155 	return 0;
3156 }
3157 
3158 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3159 {
3160 	struct bpf_func_state *state = func(env, reg);
3161 	int spi, ret;
3162 
3163 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3164 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3165 	 * check_kfunc_call.
3166 	 */
3167 	if (reg->type == CONST_PTR_TO_DYNPTR)
3168 		return 0;
3169 	spi = dynptr_get_spi(env, reg);
3170 	if (spi < 0)
3171 		return spi;
3172 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3173 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3174 	 * read.
3175 	 */
3176 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3177 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3178 	if (ret)
3179 		return ret;
3180 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3181 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3182 }
3183 
3184 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3185 			  int spi, int nr_slots)
3186 {
3187 	struct bpf_func_state *state = func(env, reg);
3188 	int err, i;
3189 
3190 	for (i = 0; i < nr_slots; i++) {
3191 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3192 
3193 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3194 		if (err)
3195 			return err;
3196 
3197 		mark_stack_slot_scratched(env, spi - i);
3198 	}
3199 
3200 	return 0;
3201 }
3202 
3203 /* This function is supposed to be used by the following 32-bit optimization
3204  * code only. It returns TRUE if the source or destination register operates
3205  * on 64-bit, otherwise return FALSE.
3206  */
3207 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3208 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3209 {
3210 	u8 code, class, op;
3211 
3212 	code = insn->code;
3213 	class = BPF_CLASS(code);
3214 	op = BPF_OP(code);
3215 	if (class == BPF_JMP) {
3216 		/* BPF_EXIT for "main" will reach here. Return TRUE
3217 		 * conservatively.
3218 		 */
3219 		if (op == BPF_EXIT)
3220 			return true;
3221 		if (op == BPF_CALL) {
3222 			/* BPF to BPF call will reach here because of marking
3223 			 * caller saved clobber with DST_OP_NO_MARK for which we
3224 			 * don't care the register def because they are anyway
3225 			 * marked as NOT_INIT already.
3226 			 */
3227 			if (insn->src_reg == BPF_PSEUDO_CALL)
3228 				return false;
3229 			/* Helper call will reach here because of arg type
3230 			 * check, conservatively return TRUE.
3231 			 */
3232 			if (t == SRC_OP)
3233 				return true;
3234 
3235 			return false;
3236 		}
3237 	}
3238 
3239 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3240 		return false;
3241 
3242 	if (class == BPF_ALU64 || class == BPF_JMP ||
3243 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3244 		return true;
3245 
3246 	if (class == BPF_ALU || class == BPF_JMP32)
3247 		return false;
3248 
3249 	if (class == BPF_LDX) {
3250 		if (t != SRC_OP)
3251 			return BPF_SIZE(code) == BPF_DW;
3252 		/* LDX source must be ptr. */
3253 		return true;
3254 	}
3255 
3256 	if (class == BPF_STX) {
3257 		/* BPF_STX (including atomic variants) has multiple source
3258 		 * operands, one of which is a ptr. Check whether the caller is
3259 		 * asking about it.
3260 		 */
3261 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3262 			return true;
3263 		return BPF_SIZE(code) == BPF_DW;
3264 	}
3265 
3266 	if (class == BPF_LD) {
3267 		u8 mode = BPF_MODE(code);
3268 
3269 		/* LD_IMM64 */
3270 		if (mode == BPF_IMM)
3271 			return true;
3272 
3273 		/* Both LD_IND and LD_ABS return 32-bit data. */
3274 		if (t != SRC_OP)
3275 			return  false;
3276 
3277 		/* Implicit ctx ptr. */
3278 		if (regno == BPF_REG_6)
3279 			return true;
3280 
3281 		/* Explicit source could be any width. */
3282 		return true;
3283 	}
3284 
3285 	if (class == BPF_ST)
3286 		/* The only source register for BPF_ST is a ptr. */
3287 		return true;
3288 
3289 	/* Conservatively return true at default. */
3290 	return true;
3291 }
3292 
3293 /* Return the regno defined by the insn, or -1. */
3294 static int insn_def_regno(const struct bpf_insn *insn)
3295 {
3296 	switch (BPF_CLASS(insn->code)) {
3297 	case BPF_JMP:
3298 	case BPF_JMP32:
3299 	case BPF_ST:
3300 		return -1;
3301 	case BPF_STX:
3302 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3303 		    (insn->imm & BPF_FETCH)) {
3304 			if (insn->imm == BPF_CMPXCHG)
3305 				return BPF_REG_0;
3306 			else
3307 				return insn->src_reg;
3308 		} else {
3309 			return -1;
3310 		}
3311 	default:
3312 		return insn->dst_reg;
3313 	}
3314 }
3315 
3316 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3317 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3318 {
3319 	int dst_reg = insn_def_regno(insn);
3320 
3321 	if (dst_reg == -1)
3322 		return false;
3323 
3324 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3325 }
3326 
3327 static void mark_insn_zext(struct bpf_verifier_env *env,
3328 			   struct bpf_reg_state *reg)
3329 {
3330 	s32 def_idx = reg->subreg_def;
3331 
3332 	if (def_idx == DEF_NOT_SUBREG)
3333 		return;
3334 
3335 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3336 	/* The dst will be zero extended, so won't be sub-register anymore. */
3337 	reg->subreg_def = DEF_NOT_SUBREG;
3338 }
3339 
3340 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3341 			   enum reg_arg_type t)
3342 {
3343 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3344 	struct bpf_reg_state *reg;
3345 	bool rw64;
3346 
3347 	if (regno >= MAX_BPF_REG) {
3348 		verbose(env, "R%d is invalid\n", regno);
3349 		return -EINVAL;
3350 	}
3351 
3352 	mark_reg_scratched(env, regno);
3353 
3354 	reg = &regs[regno];
3355 	rw64 = is_reg64(env, insn, regno, reg, t);
3356 	if (t == SRC_OP) {
3357 		/* check whether register used as source operand can be read */
3358 		if (reg->type == NOT_INIT) {
3359 			verbose(env, "R%d !read_ok\n", regno);
3360 			return -EACCES;
3361 		}
3362 		/* We don't need to worry about FP liveness because it's read-only */
3363 		if (regno == BPF_REG_FP)
3364 			return 0;
3365 
3366 		if (rw64)
3367 			mark_insn_zext(env, reg);
3368 
3369 		return mark_reg_read(env, reg, reg->parent,
3370 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3371 	} else {
3372 		/* check whether register used as dest operand can be written to */
3373 		if (regno == BPF_REG_FP) {
3374 			verbose(env, "frame pointer is read only\n");
3375 			return -EACCES;
3376 		}
3377 		reg->live |= REG_LIVE_WRITTEN;
3378 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3379 		if (t == DST_OP)
3380 			mark_reg_unknown(env, regs, regno);
3381 	}
3382 	return 0;
3383 }
3384 
3385 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3386 			 enum reg_arg_type t)
3387 {
3388 	struct bpf_verifier_state *vstate = env->cur_state;
3389 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3390 
3391 	return __check_reg_arg(env, state->regs, regno, t);
3392 }
3393 
3394 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3395 {
3396 	env->insn_aux_data[idx].jmp_point = true;
3397 }
3398 
3399 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3400 {
3401 	return env->insn_aux_data[insn_idx].jmp_point;
3402 }
3403 
3404 /* for any branch, call, exit record the history of jmps in the given state */
3405 static int push_jmp_history(struct bpf_verifier_env *env,
3406 			    struct bpf_verifier_state *cur)
3407 {
3408 	u32 cnt = cur->jmp_history_cnt;
3409 	struct bpf_idx_pair *p;
3410 	size_t alloc_size;
3411 
3412 	if (!is_jmp_point(env, env->insn_idx))
3413 		return 0;
3414 
3415 	cnt++;
3416 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3417 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3418 	if (!p)
3419 		return -ENOMEM;
3420 	p[cnt - 1].idx = env->insn_idx;
3421 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3422 	cur->jmp_history = p;
3423 	cur->jmp_history_cnt = cnt;
3424 	return 0;
3425 }
3426 
3427 /* Backtrack one insn at a time. If idx is not at the top of recorded
3428  * history then previous instruction came from straight line execution.
3429  * Return -ENOENT if we exhausted all instructions within given state.
3430  *
3431  * It's legal to have a bit of a looping with the same starting and ending
3432  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3433  * instruction index is the same as state's first_idx doesn't mean we are
3434  * done. If there is still some jump history left, we should keep going. We
3435  * need to take into account that we might have a jump history between given
3436  * state's parent and itself, due to checkpointing. In this case, we'll have
3437  * history entry recording a jump from last instruction of parent state and
3438  * first instruction of given state.
3439  */
3440 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3441 			     u32 *history)
3442 {
3443 	u32 cnt = *history;
3444 
3445 	if (i == st->first_insn_idx) {
3446 		if (cnt == 0)
3447 			return -ENOENT;
3448 		if (cnt == 1 && st->jmp_history[0].idx == i)
3449 			return -ENOENT;
3450 	}
3451 
3452 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3453 		i = st->jmp_history[cnt - 1].prev_idx;
3454 		(*history)--;
3455 	} else {
3456 		i--;
3457 	}
3458 	return i;
3459 }
3460 
3461 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3462 {
3463 	const struct btf_type *func;
3464 	struct btf *desc_btf;
3465 
3466 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3467 		return NULL;
3468 
3469 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3470 	if (IS_ERR(desc_btf))
3471 		return "<error>";
3472 
3473 	func = btf_type_by_id(desc_btf, insn->imm);
3474 	return btf_name_by_offset(desc_btf, func->name_off);
3475 }
3476 
3477 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3478 {
3479 	bt->frame = frame;
3480 }
3481 
3482 static inline void bt_reset(struct backtrack_state *bt)
3483 {
3484 	struct bpf_verifier_env *env = bt->env;
3485 
3486 	memset(bt, 0, sizeof(*bt));
3487 	bt->env = env;
3488 }
3489 
3490 static inline u32 bt_empty(struct backtrack_state *bt)
3491 {
3492 	u64 mask = 0;
3493 	int i;
3494 
3495 	for (i = 0; i <= bt->frame; i++)
3496 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3497 
3498 	return mask == 0;
3499 }
3500 
3501 static inline int bt_subprog_enter(struct backtrack_state *bt)
3502 {
3503 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3504 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3505 		WARN_ONCE(1, "verifier backtracking bug");
3506 		return -EFAULT;
3507 	}
3508 	bt->frame++;
3509 	return 0;
3510 }
3511 
3512 static inline int bt_subprog_exit(struct backtrack_state *bt)
3513 {
3514 	if (bt->frame == 0) {
3515 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3516 		WARN_ONCE(1, "verifier backtracking bug");
3517 		return -EFAULT;
3518 	}
3519 	bt->frame--;
3520 	return 0;
3521 }
3522 
3523 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3524 {
3525 	bt->reg_masks[frame] |= 1 << reg;
3526 }
3527 
3528 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3529 {
3530 	bt->reg_masks[frame] &= ~(1 << reg);
3531 }
3532 
3533 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3534 {
3535 	bt_set_frame_reg(bt, bt->frame, reg);
3536 }
3537 
3538 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3539 {
3540 	bt_clear_frame_reg(bt, bt->frame, reg);
3541 }
3542 
3543 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3544 {
3545 	bt->stack_masks[frame] |= 1ull << slot;
3546 }
3547 
3548 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3549 {
3550 	bt->stack_masks[frame] &= ~(1ull << slot);
3551 }
3552 
3553 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3554 {
3555 	bt_set_frame_slot(bt, bt->frame, slot);
3556 }
3557 
3558 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3559 {
3560 	bt_clear_frame_slot(bt, bt->frame, slot);
3561 }
3562 
3563 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3564 {
3565 	return bt->reg_masks[frame];
3566 }
3567 
3568 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3569 {
3570 	return bt->reg_masks[bt->frame];
3571 }
3572 
3573 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3574 {
3575 	return bt->stack_masks[frame];
3576 }
3577 
3578 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3579 {
3580 	return bt->stack_masks[bt->frame];
3581 }
3582 
3583 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3584 {
3585 	return bt->reg_masks[bt->frame] & (1 << reg);
3586 }
3587 
3588 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3589 {
3590 	return bt->stack_masks[bt->frame] & (1ull << slot);
3591 }
3592 
3593 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3594 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3595 {
3596 	DECLARE_BITMAP(mask, 64);
3597 	bool first = true;
3598 	int i, n;
3599 
3600 	buf[0] = '\0';
3601 
3602 	bitmap_from_u64(mask, reg_mask);
3603 	for_each_set_bit(i, mask, 32) {
3604 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3605 		first = false;
3606 		buf += n;
3607 		buf_sz -= n;
3608 		if (buf_sz < 0)
3609 			break;
3610 	}
3611 }
3612 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3613 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3614 {
3615 	DECLARE_BITMAP(mask, 64);
3616 	bool first = true;
3617 	int i, n;
3618 
3619 	buf[0] = '\0';
3620 
3621 	bitmap_from_u64(mask, stack_mask);
3622 	for_each_set_bit(i, mask, 64) {
3623 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3624 		first = false;
3625 		buf += n;
3626 		buf_sz -= n;
3627 		if (buf_sz < 0)
3628 			break;
3629 	}
3630 }
3631 
3632 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3633 
3634 /* For given verifier state backtrack_insn() is called from the last insn to
3635  * the first insn. Its purpose is to compute a bitmask of registers and
3636  * stack slots that needs precision in the parent verifier state.
3637  *
3638  * @idx is an index of the instruction we are currently processing;
3639  * @subseq_idx is an index of the subsequent instruction that:
3640  *   - *would be* executed next, if jump history is viewed in forward order;
3641  *   - *was* processed previously during backtracking.
3642  */
3643 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3644 			  struct backtrack_state *bt)
3645 {
3646 	const struct bpf_insn_cbs cbs = {
3647 		.cb_call	= disasm_kfunc_name,
3648 		.cb_print	= verbose,
3649 		.private_data	= env,
3650 	};
3651 	struct bpf_insn *insn = env->prog->insnsi + idx;
3652 	u8 class = BPF_CLASS(insn->code);
3653 	u8 opcode = BPF_OP(insn->code);
3654 	u8 mode = BPF_MODE(insn->code);
3655 	u32 dreg = insn->dst_reg;
3656 	u32 sreg = insn->src_reg;
3657 	u32 spi, i;
3658 
3659 	if (insn->code == 0)
3660 		return 0;
3661 	if (env->log.level & BPF_LOG_LEVEL2) {
3662 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3663 		verbose(env, "mark_precise: frame%d: regs=%s ",
3664 			bt->frame, env->tmp_str_buf);
3665 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3666 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3667 		verbose(env, "%d: ", idx);
3668 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3669 	}
3670 
3671 	if (class == BPF_ALU || class == BPF_ALU64) {
3672 		if (!bt_is_reg_set(bt, dreg))
3673 			return 0;
3674 		if (opcode == BPF_END || opcode == BPF_NEG) {
3675 			/* sreg is reserved and unused
3676 			 * dreg still need precision before this insn
3677 			 */
3678 			return 0;
3679 		} else if (opcode == BPF_MOV) {
3680 			if (BPF_SRC(insn->code) == BPF_X) {
3681 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3682 				 * dreg needs precision after this insn
3683 				 * sreg needs precision before this insn
3684 				 */
3685 				bt_clear_reg(bt, dreg);
3686 				if (sreg != BPF_REG_FP)
3687 					bt_set_reg(bt, sreg);
3688 			} else {
3689 				/* dreg = K
3690 				 * dreg needs precision after this insn.
3691 				 * Corresponding register is already marked
3692 				 * as precise=true in this verifier state.
3693 				 * No further markings in parent are necessary
3694 				 */
3695 				bt_clear_reg(bt, dreg);
3696 			}
3697 		} else {
3698 			if (BPF_SRC(insn->code) == BPF_X) {
3699 				/* dreg += sreg
3700 				 * both dreg and sreg need precision
3701 				 * before this insn
3702 				 */
3703 				if (sreg != BPF_REG_FP)
3704 					bt_set_reg(bt, sreg);
3705 			} /* else dreg += K
3706 			   * dreg still needs precision before this insn
3707 			   */
3708 		}
3709 	} else if (class == BPF_LDX) {
3710 		if (!bt_is_reg_set(bt, dreg))
3711 			return 0;
3712 		bt_clear_reg(bt, dreg);
3713 
3714 		/* scalars can only be spilled into stack w/o losing precision.
3715 		 * Load from any other memory can be zero extended.
3716 		 * The desire to keep that precision is already indicated
3717 		 * by 'precise' mark in corresponding register of this state.
3718 		 * No further tracking necessary.
3719 		 */
3720 		if (insn->src_reg != BPF_REG_FP)
3721 			return 0;
3722 
3723 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3724 		 * that [fp - off] slot contains scalar that needs to be
3725 		 * tracked with precision
3726 		 */
3727 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3728 		if (spi >= 64) {
3729 			verbose(env, "BUG spi %d\n", spi);
3730 			WARN_ONCE(1, "verifier backtracking bug");
3731 			return -EFAULT;
3732 		}
3733 		bt_set_slot(bt, spi);
3734 	} else if (class == BPF_STX || class == BPF_ST) {
3735 		if (bt_is_reg_set(bt, dreg))
3736 			/* stx & st shouldn't be using _scalar_ dst_reg
3737 			 * to access memory. It means backtracking
3738 			 * encountered a case of pointer subtraction.
3739 			 */
3740 			return -ENOTSUPP;
3741 		/* scalars can only be spilled into stack */
3742 		if (insn->dst_reg != BPF_REG_FP)
3743 			return 0;
3744 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3745 		if (spi >= 64) {
3746 			verbose(env, "BUG spi %d\n", spi);
3747 			WARN_ONCE(1, "verifier backtracking bug");
3748 			return -EFAULT;
3749 		}
3750 		if (!bt_is_slot_set(bt, spi))
3751 			return 0;
3752 		bt_clear_slot(bt, spi);
3753 		if (class == BPF_STX)
3754 			bt_set_reg(bt, sreg);
3755 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3756 		if (bpf_pseudo_call(insn)) {
3757 			int subprog_insn_idx, subprog;
3758 
3759 			subprog_insn_idx = idx + insn->imm + 1;
3760 			subprog = find_subprog(env, subprog_insn_idx);
3761 			if (subprog < 0)
3762 				return -EFAULT;
3763 
3764 			if (subprog_is_global(env, subprog)) {
3765 				/* check that jump history doesn't have any
3766 				 * extra instructions from subprog; the next
3767 				 * instruction after call to global subprog
3768 				 * should be literally next instruction in
3769 				 * caller program
3770 				 */
3771 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3772 				/* r1-r5 are invalidated after subprog call,
3773 				 * so for global func call it shouldn't be set
3774 				 * anymore
3775 				 */
3776 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3777 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3778 					WARN_ONCE(1, "verifier backtracking bug");
3779 					return -EFAULT;
3780 				}
3781 				/* global subprog always sets R0 */
3782 				bt_clear_reg(bt, BPF_REG_0);
3783 				return 0;
3784 			} else {
3785 				/* static subprog call instruction, which
3786 				 * means that we are exiting current subprog,
3787 				 * so only r1-r5 could be still requested as
3788 				 * precise, r0 and r6-r10 or any stack slot in
3789 				 * the current frame should be zero by now
3790 				 */
3791 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3792 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3793 					WARN_ONCE(1, "verifier backtracking bug");
3794 					return -EFAULT;
3795 				}
3796 				/* we don't track register spills perfectly,
3797 				 * so fallback to force-precise instead of failing */
3798 				if (bt_stack_mask(bt) != 0)
3799 					return -ENOTSUPP;
3800 				/* propagate r1-r5 to the caller */
3801 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3802 					if (bt_is_reg_set(bt, i)) {
3803 						bt_clear_reg(bt, i);
3804 						bt_set_frame_reg(bt, bt->frame - 1, i);
3805 					}
3806 				}
3807 				if (bt_subprog_exit(bt))
3808 					return -EFAULT;
3809 				return 0;
3810 			}
3811 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3812 			/* exit from callback subprog to callback-calling helper or
3813 			 * kfunc call. Use idx/subseq_idx check to discern it from
3814 			 * straight line code backtracking.
3815 			 * Unlike the subprog call handling above, we shouldn't
3816 			 * propagate precision of r1-r5 (if any requested), as they are
3817 			 * not actually arguments passed directly to callback subprogs
3818 			 */
3819 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3820 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3821 				WARN_ONCE(1, "verifier backtracking bug");
3822 				return -EFAULT;
3823 			}
3824 			if (bt_stack_mask(bt) != 0)
3825 				return -ENOTSUPP;
3826 			/* clear r1-r5 in callback subprog's mask */
3827 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3828 				bt_clear_reg(bt, i);
3829 			if (bt_subprog_exit(bt))
3830 				return -EFAULT;
3831 			return 0;
3832 		} else if (opcode == BPF_CALL) {
3833 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3834 			 * catch this error later. Make backtracking conservative
3835 			 * with ENOTSUPP.
3836 			 */
3837 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3838 				return -ENOTSUPP;
3839 			/* regular helper call sets R0 */
3840 			bt_clear_reg(bt, BPF_REG_0);
3841 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3842 				/* if backtracing was looking for registers R1-R5
3843 				 * they should have been found already.
3844 				 */
3845 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3846 				WARN_ONCE(1, "verifier backtracking bug");
3847 				return -EFAULT;
3848 			}
3849 		} else if (opcode == BPF_EXIT) {
3850 			bool r0_precise;
3851 
3852 			/* Backtracking to a nested function call, 'idx' is a part of
3853 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3854 			 * In case of a regular function call, instructions giving
3855 			 * precision to registers R1-R5 should have been found already.
3856 			 * In case of a callback, it is ok to have R1-R5 marked for
3857 			 * backtracking, as these registers are set by the function
3858 			 * invoking callback.
3859 			 */
3860 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3861 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3862 					bt_clear_reg(bt, i);
3863 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3864 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3865 				WARN_ONCE(1, "verifier backtracking bug");
3866 				return -EFAULT;
3867 			}
3868 
3869 			/* BPF_EXIT in subprog or callback always returns
3870 			 * right after the call instruction, so by checking
3871 			 * whether the instruction at subseq_idx-1 is subprog
3872 			 * call or not we can distinguish actual exit from
3873 			 * *subprog* from exit from *callback*. In the former
3874 			 * case, we need to propagate r0 precision, if
3875 			 * necessary. In the former we never do that.
3876 			 */
3877 			r0_precise = subseq_idx - 1 >= 0 &&
3878 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3879 				     bt_is_reg_set(bt, BPF_REG_0);
3880 
3881 			bt_clear_reg(bt, BPF_REG_0);
3882 			if (bt_subprog_enter(bt))
3883 				return -EFAULT;
3884 
3885 			if (r0_precise)
3886 				bt_set_reg(bt, BPF_REG_0);
3887 			/* r6-r9 and stack slots will stay set in caller frame
3888 			 * bitmasks until we return back from callee(s)
3889 			 */
3890 			return 0;
3891 		} else if (BPF_SRC(insn->code) == BPF_X) {
3892 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3893 				return 0;
3894 			/* dreg <cond> sreg
3895 			 * Both dreg and sreg need precision before
3896 			 * this insn. If only sreg was marked precise
3897 			 * before it would be equally necessary to
3898 			 * propagate it to dreg.
3899 			 */
3900 			bt_set_reg(bt, dreg);
3901 			bt_set_reg(bt, sreg);
3902 			 /* else dreg <cond> K
3903 			  * Only dreg still needs precision before
3904 			  * this insn, so for the K-based conditional
3905 			  * there is nothing new to be marked.
3906 			  */
3907 		}
3908 	} else if (class == BPF_LD) {
3909 		if (!bt_is_reg_set(bt, dreg))
3910 			return 0;
3911 		bt_clear_reg(bt, dreg);
3912 		/* It's ld_imm64 or ld_abs or ld_ind.
3913 		 * For ld_imm64 no further tracking of precision
3914 		 * into parent is necessary
3915 		 */
3916 		if (mode == BPF_IND || mode == BPF_ABS)
3917 			/* to be analyzed */
3918 			return -ENOTSUPP;
3919 	}
3920 	return 0;
3921 }
3922 
3923 /* the scalar precision tracking algorithm:
3924  * . at the start all registers have precise=false.
3925  * . scalar ranges are tracked as normal through alu and jmp insns.
3926  * . once precise value of the scalar register is used in:
3927  *   .  ptr + scalar alu
3928  *   . if (scalar cond K|scalar)
3929  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3930  *   backtrack through the verifier states and mark all registers and
3931  *   stack slots with spilled constants that these scalar regisers
3932  *   should be precise.
3933  * . during state pruning two registers (or spilled stack slots)
3934  *   are equivalent if both are not precise.
3935  *
3936  * Note the verifier cannot simply walk register parentage chain,
3937  * since many different registers and stack slots could have been
3938  * used to compute single precise scalar.
3939  *
3940  * The approach of starting with precise=true for all registers and then
3941  * backtrack to mark a register as not precise when the verifier detects
3942  * that program doesn't care about specific value (e.g., when helper
3943  * takes register as ARG_ANYTHING parameter) is not safe.
3944  *
3945  * It's ok to walk single parentage chain of the verifier states.
3946  * It's possible that this backtracking will go all the way till 1st insn.
3947  * All other branches will be explored for needing precision later.
3948  *
3949  * The backtracking needs to deal with cases like:
3950  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3951  * r9 -= r8
3952  * r5 = r9
3953  * if r5 > 0x79f goto pc+7
3954  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3955  * r5 += 1
3956  * ...
3957  * call bpf_perf_event_output#25
3958  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3959  *
3960  * and this case:
3961  * r6 = 1
3962  * call foo // uses callee's r6 inside to compute r0
3963  * r0 += r6
3964  * if r0 == 0 goto
3965  *
3966  * to track above reg_mask/stack_mask needs to be independent for each frame.
3967  *
3968  * Also if parent's curframe > frame where backtracking started,
3969  * the verifier need to mark registers in both frames, otherwise callees
3970  * may incorrectly prune callers. This is similar to
3971  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3972  *
3973  * For now backtracking falls back into conservative marking.
3974  */
3975 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3976 				     struct bpf_verifier_state *st)
3977 {
3978 	struct bpf_func_state *func;
3979 	struct bpf_reg_state *reg;
3980 	int i, j;
3981 
3982 	if (env->log.level & BPF_LOG_LEVEL2) {
3983 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3984 			st->curframe);
3985 	}
3986 
3987 	/* big hammer: mark all scalars precise in this path.
3988 	 * pop_stack may still get !precise scalars.
3989 	 * We also skip current state and go straight to first parent state,
3990 	 * because precision markings in current non-checkpointed state are
3991 	 * not needed. See why in the comment in __mark_chain_precision below.
3992 	 */
3993 	for (st = st->parent; st; st = st->parent) {
3994 		for (i = 0; i <= st->curframe; i++) {
3995 			func = st->frame[i];
3996 			for (j = 0; j < BPF_REG_FP; j++) {
3997 				reg = &func->regs[j];
3998 				if (reg->type != SCALAR_VALUE || reg->precise)
3999 					continue;
4000 				reg->precise = true;
4001 				if (env->log.level & BPF_LOG_LEVEL2) {
4002 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4003 						i, j);
4004 				}
4005 			}
4006 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4007 				if (!is_spilled_reg(&func->stack[j]))
4008 					continue;
4009 				reg = &func->stack[j].spilled_ptr;
4010 				if (reg->type != SCALAR_VALUE || reg->precise)
4011 					continue;
4012 				reg->precise = true;
4013 				if (env->log.level & BPF_LOG_LEVEL2) {
4014 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4015 						i, -(j + 1) * 8);
4016 				}
4017 			}
4018 		}
4019 	}
4020 }
4021 
4022 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4023 {
4024 	struct bpf_func_state *func;
4025 	struct bpf_reg_state *reg;
4026 	int i, j;
4027 
4028 	for (i = 0; i <= st->curframe; i++) {
4029 		func = st->frame[i];
4030 		for (j = 0; j < BPF_REG_FP; j++) {
4031 			reg = &func->regs[j];
4032 			if (reg->type != SCALAR_VALUE)
4033 				continue;
4034 			reg->precise = false;
4035 		}
4036 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4037 			if (!is_spilled_reg(&func->stack[j]))
4038 				continue;
4039 			reg = &func->stack[j].spilled_ptr;
4040 			if (reg->type != SCALAR_VALUE)
4041 				continue;
4042 			reg->precise = false;
4043 		}
4044 	}
4045 }
4046 
4047 static bool idset_contains(struct bpf_idset *s, u32 id)
4048 {
4049 	u32 i;
4050 
4051 	for (i = 0; i < s->count; ++i)
4052 		if (s->ids[i] == id)
4053 			return true;
4054 
4055 	return false;
4056 }
4057 
4058 static int idset_push(struct bpf_idset *s, u32 id)
4059 {
4060 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4061 		return -EFAULT;
4062 	s->ids[s->count++] = id;
4063 	return 0;
4064 }
4065 
4066 static void idset_reset(struct bpf_idset *s)
4067 {
4068 	s->count = 0;
4069 }
4070 
4071 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4072  * Mark all registers with these IDs as precise.
4073  */
4074 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4075 {
4076 	struct bpf_idset *precise_ids = &env->idset_scratch;
4077 	struct backtrack_state *bt = &env->bt;
4078 	struct bpf_func_state *func;
4079 	struct bpf_reg_state *reg;
4080 	DECLARE_BITMAP(mask, 64);
4081 	int i, fr;
4082 
4083 	idset_reset(precise_ids);
4084 
4085 	for (fr = bt->frame; fr >= 0; fr--) {
4086 		func = st->frame[fr];
4087 
4088 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4089 		for_each_set_bit(i, mask, 32) {
4090 			reg = &func->regs[i];
4091 			if (!reg->id || reg->type != SCALAR_VALUE)
4092 				continue;
4093 			if (idset_push(precise_ids, reg->id))
4094 				return -EFAULT;
4095 		}
4096 
4097 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4098 		for_each_set_bit(i, mask, 64) {
4099 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4100 				break;
4101 			if (!is_spilled_scalar_reg(&func->stack[i]))
4102 				continue;
4103 			reg = &func->stack[i].spilled_ptr;
4104 			if (!reg->id)
4105 				continue;
4106 			if (idset_push(precise_ids, reg->id))
4107 				return -EFAULT;
4108 		}
4109 	}
4110 
4111 	for (fr = 0; fr <= st->curframe; ++fr) {
4112 		func = st->frame[fr];
4113 
4114 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4115 			reg = &func->regs[i];
4116 			if (!reg->id)
4117 				continue;
4118 			if (!idset_contains(precise_ids, reg->id))
4119 				continue;
4120 			bt_set_frame_reg(bt, fr, i);
4121 		}
4122 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4123 			if (!is_spilled_scalar_reg(&func->stack[i]))
4124 				continue;
4125 			reg = &func->stack[i].spilled_ptr;
4126 			if (!reg->id)
4127 				continue;
4128 			if (!idset_contains(precise_ids, reg->id))
4129 				continue;
4130 			bt_set_frame_slot(bt, fr, i);
4131 		}
4132 	}
4133 
4134 	return 0;
4135 }
4136 
4137 /*
4138  * __mark_chain_precision() backtracks BPF program instruction sequence and
4139  * chain of verifier states making sure that register *regno* (if regno >= 0)
4140  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4141  * SCALARS, as well as any other registers and slots that contribute to
4142  * a tracked state of given registers/stack slots, depending on specific BPF
4143  * assembly instructions (see backtrack_insns() for exact instruction handling
4144  * logic). This backtracking relies on recorded jmp_history and is able to
4145  * traverse entire chain of parent states. This process ends only when all the
4146  * necessary registers/slots and their transitive dependencies are marked as
4147  * precise.
4148  *
4149  * One important and subtle aspect is that precise marks *do not matter* in
4150  * the currently verified state (current state). It is important to understand
4151  * why this is the case.
4152  *
4153  * First, note that current state is the state that is not yet "checkpointed",
4154  * i.e., it is not yet put into env->explored_states, and it has no children
4155  * states as well. It's ephemeral, and can end up either a) being discarded if
4156  * compatible explored state is found at some point or BPF_EXIT instruction is
4157  * reached or b) checkpointed and put into env->explored_states, branching out
4158  * into one or more children states.
4159  *
4160  * In the former case, precise markings in current state are completely
4161  * ignored by state comparison code (see regsafe() for details). Only
4162  * checkpointed ("old") state precise markings are important, and if old
4163  * state's register/slot is precise, regsafe() assumes current state's
4164  * register/slot as precise and checks value ranges exactly and precisely. If
4165  * states turn out to be compatible, current state's necessary precise
4166  * markings and any required parent states' precise markings are enforced
4167  * after the fact with propagate_precision() logic, after the fact. But it's
4168  * important to realize that in this case, even after marking current state
4169  * registers/slots as precise, we immediately discard current state. So what
4170  * actually matters is any of the precise markings propagated into current
4171  * state's parent states, which are always checkpointed (due to b) case above).
4172  * As such, for scenario a) it doesn't matter if current state has precise
4173  * markings set or not.
4174  *
4175  * Now, for the scenario b), checkpointing and forking into child(ren)
4176  * state(s). Note that before current state gets to checkpointing step, any
4177  * processed instruction always assumes precise SCALAR register/slot
4178  * knowledge: if precise value or range is useful to prune jump branch, BPF
4179  * verifier takes this opportunity enthusiastically. Similarly, when
4180  * register's value is used to calculate offset or memory address, exact
4181  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4182  * what we mentioned above about state comparison ignoring precise markings
4183  * during state comparison, BPF verifier ignores and also assumes precise
4184  * markings *at will* during instruction verification process. But as verifier
4185  * assumes precision, it also propagates any precision dependencies across
4186  * parent states, which are not yet finalized, so can be further restricted
4187  * based on new knowledge gained from restrictions enforced by their children
4188  * states. This is so that once those parent states are finalized, i.e., when
4189  * they have no more active children state, state comparison logic in
4190  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4191  * required for correctness.
4192  *
4193  * To build a bit more intuition, note also that once a state is checkpointed,
4194  * the path we took to get to that state is not important. This is crucial
4195  * property for state pruning. When state is checkpointed and finalized at
4196  * some instruction index, it can be correctly and safely used to "short
4197  * circuit" any *compatible* state that reaches exactly the same instruction
4198  * index. I.e., if we jumped to that instruction from a completely different
4199  * code path than original finalized state was derived from, it doesn't
4200  * matter, current state can be discarded because from that instruction
4201  * forward having a compatible state will ensure we will safely reach the
4202  * exit. States describe preconditions for further exploration, but completely
4203  * forget the history of how we got here.
4204  *
4205  * This also means that even if we needed precise SCALAR range to get to
4206  * finalized state, but from that point forward *that same* SCALAR register is
4207  * never used in a precise context (i.e., it's precise value is not needed for
4208  * correctness), it's correct and safe to mark such register as "imprecise"
4209  * (i.e., precise marking set to false). This is what we rely on when we do
4210  * not set precise marking in current state. If no child state requires
4211  * precision for any given SCALAR register, it's safe to dictate that it can
4212  * be imprecise. If any child state does require this register to be precise,
4213  * we'll mark it precise later retroactively during precise markings
4214  * propagation from child state to parent states.
4215  *
4216  * Skipping precise marking setting in current state is a mild version of
4217  * relying on the above observation. But we can utilize this property even
4218  * more aggressively by proactively forgetting any precise marking in the
4219  * current state (which we inherited from the parent state), right before we
4220  * checkpoint it and branch off into new child state. This is done by
4221  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4222  * finalized states which help in short circuiting more future states.
4223  */
4224 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4225 {
4226 	struct backtrack_state *bt = &env->bt;
4227 	struct bpf_verifier_state *st = env->cur_state;
4228 	int first_idx = st->first_insn_idx;
4229 	int last_idx = env->insn_idx;
4230 	int subseq_idx = -1;
4231 	struct bpf_func_state *func;
4232 	struct bpf_reg_state *reg;
4233 	bool skip_first = true;
4234 	int i, fr, err;
4235 
4236 	if (!env->bpf_capable)
4237 		return 0;
4238 
4239 	/* set frame number from which we are starting to backtrack */
4240 	bt_init(bt, env->cur_state->curframe);
4241 
4242 	/* Do sanity checks against current state of register and/or stack
4243 	 * slot, but don't set precise flag in current state, as precision
4244 	 * tracking in the current state is unnecessary.
4245 	 */
4246 	func = st->frame[bt->frame];
4247 	if (regno >= 0) {
4248 		reg = &func->regs[regno];
4249 		if (reg->type != SCALAR_VALUE) {
4250 			WARN_ONCE(1, "backtracing misuse");
4251 			return -EFAULT;
4252 		}
4253 		bt_set_reg(bt, regno);
4254 	}
4255 
4256 	if (bt_empty(bt))
4257 		return 0;
4258 
4259 	for (;;) {
4260 		DECLARE_BITMAP(mask, 64);
4261 		u32 history = st->jmp_history_cnt;
4262 
4263 		if (env->log.level & BPF_LOG_LEVEL2) {
4264 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4265 				bt->frame, last_idx, first_idx, subseq_idx);
4266 		}
4267 
4268 		/* If some register with scalar ID is marked as precise,
4269 		 * make sure that all registers sharing this ID are also precise.
4270 		 * This is needed to estimate effect of find_equal_scalars().
4271 		 * Do this at the last instruction of each state,
4272 		 * bpf_reg_state::id fields are valid for these instructions.
4273 		 *
4274 		 * Allows to track precision in situation like below:
4275 		 *
4276 		 *     r2 = unknown value
4277 		 *     ...
4278 		 *   --- state #0 ---
4279 		 *     ...
4280 		 *     r1 = r2                 // r1 and r2 now share the same ID
4281 		 *     ...
4282 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4283 		 *     ...
4284 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4285 		 *     ...
4286 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4287 		 *     r3 = r10
4288 		 *     r3 += r1                // need to mark both r1 and r2
4289 		 */
4290 		if (mark_precise_scalar_ids(env, st))
4291 			return -EFAULT;
4292 
4293 		if (last_idx < 0) {
4294 			/* we are at the entry into subprog, which
4295 			 * is expected for global funcs, but only if
4296 			 * requested precise registers are R1-R5
4297 			 * (which are global func's input arguments)
4298 			 */
4299 			if (st->curframe == 0 &&
4300 			    st->frame[0]->subprogno > 0 &&
4301 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4302 			    bt_stack_mask(bt) == 0 &&
4303 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4304 				bitmap_from_u64(mask, bt_reg_mask(bt));
4305 				for_each_set_bit(i, mask, 32) {
4306 					reg = &st->frame[0]->regs[i];
4307 					bt_clear_reg(bt, i);
4308 					if (reg->type == SCALAR_VALUE)
4309 						reg->precise = true;
4310 				}
4311 				return 0;
4312 			}
4313 
4314 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4315 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4316 			WARN_ONCE(1, "verifier backtracking bug");
4317 			return -EFAULT;
4318 		}
4319 
4320 		for (i = last_idx;;) {
4321 			if (skip_first) {
4322 				err = 0;
4323 				skip_first = false;
4324 			} else {
4325 				err = backtrack_insn(env, i, subseq_idx, bt);
4326 			}
4327 			if (err == -ENOTSUPP) {
4328 				mark_all_scalars_precise(env, env->cur_state);
4329 				bt_reset(bt);
4330 				return 0;
4331 			} else if (err) {
4332 				return err;
4333 			}
4334 			if (bt_empty(bt))
4335 				/* Found assignment(s) into tracked register in this state.
4336 				 * Since this state is already marked, just return.
4337 				 * Nothing to be tracked further in the parent state.
4338 				 */
4339 				return 0;
4340 			subseq_idx = i;
4341 			i = get_prev_insn_idx(st, i, &history);
4342 			if (i == -ENOENT)
4343 				break;
4344 			if (i >= env->prog->len) {
4345 				/* This can happen if backtracking reached insn 0
4346 				 * and there are still reg_mask or stack_mask
4347 				 * to backtrack.
4348 				 * It means the backtracking missed the spot where
4349 				 * particular register was initialized with a constant.
4350 				 */
4351 				verbose(env, "BUG backtracking idx %d\n", i);
4352 				WARN_ONCE(1, "verifier backtracking bug");
4353 				return -EFAULT;
4354 			}
4355 		}
4356 		st = st->parent;
4357 		if (!st)
4358 			break;
4359 
4360 		for (fr = bt->frame; fr >= 0; fr--) {
4361 			func = st->frame[fr];
4362 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4363 			for_each_set_bit(i, mask, 32) {
4364 				reg = &func->regs[i];
4365 				if (reg->type != SCALAR_VALUE) {
4366 					bt_clear_frame_reg(bt, fr, i);
4367 					continue;
4368 				}
4369 				if (reg->precise)
4370 					bt_clear_frame_reg(bt, fr, i);
4371 				else
4372 					reg->precise = true;
4373 			}
4374 
4375 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4376 			for_each_set_bit(i, mask, 64) {
4377 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4378 					/* the sequence of instructions:
4379 					 * 2: (bf) r3 = r10
4380 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4381 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4382 					 * doesn't contain jmps. It's backtracked
4383 					 * as a single block.
4384 					 * During backtracking insn 3 is not recognized as
4385 					 * stack access, so at the end of backtracking
4386 					 * stack slot fp-8 is still marked in stack_mask.
4387 					 * However the parent state may not have accessed
4388 					 * fp-8 and it's "unallocated" stack space.
4389 					 * In such case fallback to conservative.
4390 					 */
4391 					mark_all_scalars_precise(env, env->cur_state);
4392 					bt_reset(bt);
4393 					return 0;
4394 				}
4395 
4396 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4397 					bt_clear_frame_slot(bt, fr, i);
4398 					continue;
4399 				}
4400 				reg = &func->stack[i].spilled_ptr;
4401 				if (reg->precise)
4402 					bt_clear_frame_slot(bt, fr, i);
4403 				else
4404 					reg->precise = true;
4405 			}
4406 			if (env->log.level & BPF_LOG_LEVEL2) {
4407 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4408 					     bt_frame_reg_mask(bt, fr));
4409 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4410 					fr, env->tmp_str_buf);
4411 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4412 					       bt_frame_stack_mask(bt, fr));
4413 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4414 				print_verifier_state(env, func, true);
4415 			}
4416 		}
4417 
4418 		if (bt_empty(bt))
4419 			return 0;
4420 
4421 		subseq_idx = first_idx;
4422 		last_idx = st->last_insn_idx;
4423 		first_idx = st->first_insn_idx;
4424 	}
4425 
4426 	/* if we still have requested precise regs or slots, we missed
4427 	 * something (e.g., stack access through non-r10 register), so
4428 	 * fallback to marking all precise
4429 	 */
4430 	if (!bt_empty(bt)) {
4431 		mark_all_scalars_precise(env, env->cur_state);
4432 		bt_reset(bt);
4433 	}
4434 
4435 	return 0;
4436 }
4437 
4438 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4439 {
4440 	return __mark_chain_precision(env, regno);
4441 }
4442 
4443 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4444  * desired reg and stack masks across all relevant frames
4445  */
4446 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4447 {
4448 	return __mark_chain_precision(env, -1);
4449 }
4450 
4451 static bool is_spillable_regtype(enum bpf_reg_type type)
4452 {
4453 	switch (base_type(type)) {
4454 	case PTR_TO_MAP_VALUE:
4455 	case PTR_TO_STACK:
4456 	case PTR_TO_CTX:
4457 	case PTR_TO_PACKET:
4458 	case PTR_TO_PACKET_META:
4459 	case PTR_TO_PACKET_END:
4460 	case PTR_TO_FLOW_KEYS:
4461 	case CONST_PTR_TO_MAP:
4462 	case PTR_TO_SOCKET:
4463 	case PTR_TO_SOCK_COMMON:
4464 	case PTR_TO_TCP_SOCK:
4465 	case PTR_TO_XDP_SOCK:
4466 	case PTR_TO_BTF_ID:
4467 	case PTR_TO_BUF:
4468 	case PTR_TO_MEM:
4469 	case PTR_TO_FUNC:
4470 	case PTR_TO_MAP_KEY:
4471 		return true;
4472 	default:
4473 		return false;
4474 	}
4475 }
4476 
4477 /* Does this register contain a constant zero? */
4478 static bool register_is_null(struct bpf_reg_state *reg)
4479 {
4480 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4481 }
4482 
4483 static bool register_is_const(struct bpf_reg_state *reg)
4484 {
4485 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4486 }
4487 
4488 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4489 {
4490 	return tnum_is_unknown(reg->var_off) &&
4491 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4492 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4493 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4494 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4495 }
4496 
4497 static bool register_is_bounded(struct bpf_reg_state *reg)
4498 {
4499 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4500 }
4501 
4502 static bool __is_pointer_value(bool allow_ptr_leaks,
4503 			       const struct bpf_reg_state *reg)
4504 {
4505 	if (allow_ptr_leaks)
4506 		return false;
4507 
4508 	return reg->type != SCALAR_VALUE;
4509 }
4510 
4511 /* Copy src state preserving dst->parent and dst->live fields */
4512 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4513 {
4514 	struct bpf_reg_state *parent = dst->parent;
4515 	enum bpf_reg_liveness live = dst->live;
4516 
4517 	*dst = *src;
4518 	dst->parent = parent;
4519 	dst->live = live;
4520 }
4521 
4522 static void save_register_state(struct bpf_func_state *state,
4523 				int spi, struct bpf_reg_state *reg,
4524 				int size)
4525 {
4526 	int i;
4527 
4528 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4529 	if (size == BPF_REG_SIZE)
4530 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4531 
4532 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4533 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4534 
4535 	/* size < 8 bytes spill */
4536 	for (; i; i--)
4537 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4538 }
4539 
4540 static bool is_bpf_st_mem(struct bpf_insn *insn)
4541 {
4542 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4543 }
4544 
4545 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4546  * stack boundary and alignment are checked in check_mem_access()
4547  */
4548 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4549 				       /* stack frame we're writing to */
4550 				       struct bpf_func_state *state,
4551 				       int off, int size, int value_regno,
4552 				       int insn_idx)
4553 {
4554 	struct bpf_func_state *cur; /* state of the current function */
4555 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4556 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4557 	struct bpf_reg_state *reg = NULL;
4558 	u32 dst_reg = insn->dst_reg;
4559 
4560 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4561 	 * so it's aligned access and [off, off + size) are within stack limits
4562 	 */
4563 	if (!env->allow_ptr_leaks &&
4564 	    is_spilled_reg(&state->stack[spi]) &&
4565 	    size != BPF_REG_SIZE) {
4566 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4567 		return -EACCES;
4568 	}
4569 
4570 	cur = env->cur_state->frame[env->cur_state->curframe];
4571 	if (value_regno >= 0)
4572 		reg = &cur->regs[value_regno];
4573 	if (!env->bypass_spec_v4) {
4574 		bool sanitize = reg && is_spillable_regtype(reg->type);
4575 
4576 		for (i = 0; i < size; i++) {
4577 			u8 type = state->stack[spi].slot_type[i];
4578 
4579 			if (type != STACK_MISC && type != STACK_ZERO) {
4580 				sanitize = true;
4581 				break;
4582 			}
4583 		}
4584 
4585 		if (sanitize)
4586 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4587 	}
4588 
4589 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4590 	if (err)
4591 		return err;
4592 
4593 	mark_stack_slot_scratched(env, spi);
4594 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4595 	    !register_is_null(reg) && env->bpf_capable) {
4596 		if (dst_reg != BPF_REG_FP) {
4597 			/* The backtracking logic can only recognize explicit
4598 			 * stack slot address like [fp - 8]. Other spill of
4599 			 * scalar via different register has to be conservative.
4600 			 * Backtrack from here and mark all registers as precise
4601 			 * that contributed into 'reg' being a constant.
4602 			 */
4603 			err = mark_chain_precision(env, value_regno);
4604 			if (err)
4605 				return err;
4606 		}
4607 		save_register_state(state, spi, reg, size);
4608 		/* Break the relation on a narrowing spill. */
4609 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4610 			state->stack[spi].spilled_ptr.id = 0;
4611 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4612 		   insn->imm != 0 && env->bpf_capable) {
4613 		struct bpf_reg_state fake_reg = {};
4614 
4615 		__mark_reg_known(&fake_reg, insn->imm);
4616 		fake_reg.type = SCALAR_VALUE;
4617 		save_register_state(state, spi, &fake_reg, size);
4618 	} else if (reg && is_spillable_regtype(reg->type)) {
4619 		/* register containing pointer is being spilled into stack */
4620 		if (size != BPF_REG_SIZE) {
4621 			verbose_linfo(env, insn_idx, "; ");
4622 			verbose(env, "invalid size of register spill\n");
4623 			return -EACCES;
4624 		}
4625 		if (state != cur && reg->type == PTR_TO_STACK) {
4626 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4627 			return -EINVAL;
4628 		}
4629 		save_register_state(state, spi, reg, size);
4630 	} else {
4631 		u8 type = STACK_MISC;
4632 
4633 		/* regular write of data into stack destroys any spilled ptr */
4634 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4635 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4636 		if (is_stack_slot_special(&state->stack[spi]))
4637 			for (i = 0; i < BPF_REG_SIZE; i++)
4638 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4639 
4640 		/* only mark the slot as written if all 8 bytes were written
4641 		 * otherwise read propagation may incorrectly stop too soon
4642 		 * when stack slots are partially written.
4643 		 * This heuristic means that read propagation will be
4644 		 * conservative, since it will add reg_live_read marks
4645 		 * to stack slots all the way to first state when programs
4646 		 * writes+reads less than 8 bytes
4647 		 */
4648 		if (size == BPF_REG_SIZE)
4649 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4650 
4651 		/* when we zero initialize stack slots mark them as such */
4652 		if ((reg && register_is_null(reg)) ||
4653 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4654 			/* backtracking doesn't work for STACK_ZERO yet. */
4655 			err = mark_chain_precision(env, value_regno);
4656 			if (err)
4657 				return err;
4658 			type = STACK_ZERO;
4659 		}
4660 
4661 		/* Mark slots affected by this stack write. */
4662 		for (i = 0; i < size; i++)
4663 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4664 				type;
4665 	}
4666 	return 0;
4667 }
4668 
4669 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4670  * known to contain a variable offset.
4671  * This function checks whether the write is permitted and conservatively
4672  * tracks the effects of the write, considering that each stack slot in the
4673  * dynamic range is potentially written to.
4674  *
4675  * 'off' includes 'regno->off'.
4676  * 'value_regno' can be -1, meaning that an unknown value is being written to
4677  * the stack.
4678  *
4679  * Spilled pointers in range are not marked as written because we don't know
4680  * what's going to be actually written. This means that read propagation for
4681  * future reads cannot be terminated by this write.
4682  *
4683  * For privileged programs, uninitialized stack slots are considered
4684  * initialized by this write (even though we don't know exactly what offsets
4685  * are going to be written to). The idea is that we don't want the verifier to
4686  * reject future reads that access slots written to through variable offsets.
4687  */
4688 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4689 				     /* func where register points to */
4690 				     struct bpf_func_state *state,
4691 				     int ptr_regno, int off, int size,
4692 				     int value_regno, int insn_idx)
4693 {
4694 	struct bpf_func_state *cur; /* state of the current function */
4695 	int min_off, max_off;
4696 	int i, err;
4697 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4698 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4699 	bool writing_zero = false;
4700 	/* set if the fact that we're writing a zero is used to let any
4701 	 * stack slots remain STACK_ZERO
4702 	 */
4703 	bool zero_used = false;
4704 
4705 	cur = env->cur_state->frame[env->cur_state->curframe];
4706 	ptr_reg = &cur->regs[ptr_regno];
4707 	min_off = ptr_reg->smin_value + off;
4708 	max_off = ptr_reg->smax_value + off + size;
4709 	if (value_regno >= 0)
4710 		value_reg = &cur->regs[value_regno];
4711 	if ((value_reg && register_is_null(value_reg)) ||
4712 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4713 		writing_zero = true;
4714 
4715 	for (i = min_off; i < max_off; i++) {
4716 		int spi;
4717 
4718 		spi = __get_spi(i);
4719 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4720 		if (err)
4721 			return err;
4722 	}
4723 
4724 	/* Variable offset writes destroy any spilled pointers in range. */
4725 	for (i = min_off; i < max_off; i++) {
4726 		u8 new_type, *stype;
4727 		int slot, spi;
4728 
4729 		slot = -i - 1;
4730 		spi = slot / BPF_REG_SIZE;
4731 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4732 		mark_stack_slot_scratched(env, spi);
4733 
4734 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4735 			/* Reject the write if range we may write to has not
4736 			 * been initialized beforehand. If we didn't reject
4737 			 * here, the ptr status would be erased below (even
4738 			 * though not all slots are actually overwritten),
4739 			 * possibly opening the door to leaks.
4740 			 *
4741 			 * We do however catch STACK_INVALID case below, and
4742 			 * only allow reading possibly uninitialized memory
4743 			 * later for CAP_PERFMON, as the write may not happen to
4744 			 * that slot.
4745 			 */
4746 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4747 				insn_idx, i);
4748 			return -EINVAL;
4749 		}
4750 
4751 		/* Erase all spilled pointers. */
4752 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4753 
4754 		/* Update the slot type. */
4755 		new_type = STACK_MISC;
4756 		if (writing_zero && *stype == STACK_ZERO) {
4757 			new_type = STACK_ZERO;
4758 			zero_used = true;
4759 		}
4760 		/* If the slot is STACK_INVALID, we check whether it's OK to
4761 		 * pretend that it will be initialized by this write. The slot
4762 		 * might not actually be written to, and so if we mark it as
4763 		 * initialized future reads might leak uninitialized memory.
4764 		 * For privileged programs, we will accept such reads to slots
4765 		 * that may or may not be written because, if we're reject
4766 		 * them, the error would be too confusing.
4767 		 */
4768 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4769 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4770 					insn_idx, i);
4771 			return -EINVAL;
4772 		}
4773 		*stype = new_type;
4774 	}
4775 	if (zero_used) {
4776 		/* backtracking doesn't work for STACK_ZERO yet. */
4777 		err = mark_chain_precision(env, value_regno);
4778 		if (err)
4779 			return err;
4780 	}
4781 	return 0;
4782 }
4783 
4784 /* When register 'dst_regno' is assigned some values from stack[min_off,
4785  * max_off), we set the register's type according to the types of the
4786  * respective stack slots. If all the stack values are known to be zeros, then
4787  * so is the destination reg. Otherwise, the register is considered to be
4788  * SCALAR. This function does not deal with register filling; the caller must
4789  * ensure that all spilled registers in the stack range have been marked as
4790  * read.
4791  */
4792 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4793 				/* func where src register points to */
4794 				struct bpf_func_state *ptr_state,
4795 				int min_off, int max_off, int dst_regno)
4796 {
4797 	struct bpf_verifier_state *vstate = env->cur_state;
4798 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4799 	int i, slot, spi;
4800 	u8 *stype;
4801 	int zeros = 0;
4802 
4803 	for (i = min_off; i < max_off; i++) {
4804 		slot = -i - 1;
4805 		spi = slot / BPF_REG_SIZE;
4806 		mark_stack_slot_scratched(env, spi);
4807 		stype = ptr_state->stack[spi].slot_type;
4808 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4809 			break;
4810 		zeros++;
4811 	}
4812 	if (zeros == max_off - min_off) {
4813 		/* any access_size read into register is zero extended,
4814 		 * so the whole register == const_zero
4815 		 */
4816 		__mark_reg_const_zero(&state->regs[dst_regno]);
4817 		/* backtracking doesn't support STACK_ZERO yet,
4818 		 * so mark it precise here, so that later
4819 		 * backtracking can stop here.
4820 		 * Backtracking may not need this if this register
4821 		 * doesn't participate in pointer adjustment.
4822 		 * Forward propagation of precise flag is not
4823 		 * necessary either. This mark is only to stop
4824 		 * backtracking. Any register that contributed
4825 		 * to const 0 was marked precise before spill.
4826 		 */
4827 		state->regs[dst_regno].precise = true;
4828 	} else {
4829 		/* have read misc data from the stack */
4830 		mark_reg_unknown(env, state->regs, dst_regno);
4831 	}
4832 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4833 }
4834 
4835 /* Read the stack at 'off' and put the results into the register indicated by
4836  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4837  * spilled reg.
4838  *
4839  * 'dst_regno' can be -1, meaning that the read value is not going to a
4840  * register.
4841  *
4842  * The access is assumed to be within the current stack bounds.
4843  */
4844 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4845 				      /* func where src register points to */
4846 				      struct bpf_func_state *reg_state,
4847 				      int off, int size, int dst_regno)
4848 {
4849 	struct bpf_verifier_state *vstate = env->cur_state;
4850 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4851 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4852 	struct bpf_reg_state *reg;
4853 	u8 *stype, type;
4854 
4855 	stype = reg_state->stack[spi].slot_type;
4856 	reg = &reg_state->stack[spi].spilled_ptr;
4857 
4858 	mark_stack_slot_scratched(env, spi);
4859 
4860 	if (is_spilled_reg(&reg_state->stack[spi])) {
4861 		u8 spill_size = 1;
4862 
4863 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4864 			spill_size++;
4865 
4866 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4867 			if (reg->type != SCALAR_VALUE) {
4868 				verbose_linfo(env, env->insn_idx, "; ");
4869 				verbose(env, "invalid size of register fill\n");
4870 				return -EACCES;
4871 			}
4872 
4873 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4874 			if (dst_regno < 0)
4875 				return 0;
4876 
4877 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4878 				/* The earlier check_reg_arg() has decided the
4879 				 * subreg_def for this insn.  Save it first.
4880 				 */
4881 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4882 
4883 				copy_register_state(&state->regs[dst_regno], reg);
4884 				state->regs[dst_regno].subreg_def = subreg_def;
4885 			} else {
4886 				for (i = 0; i < size; i++) {
4887 					type = stype[(slot - i) % BPF_REG_SIZE];
4888 					if (type == STACK_SPILL)
4889 						continue;
4890 					if (type == STACK_MISC)
4891 						continue;
4892 					if (type == STACK_INVALID && env->allow_uninit_stack)
4893 						continue;
4894 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4895 						off, i, size);
4896 					return -EACCES;
4897 				}
4898 				mark_reg_unknown(env, state->regs, dst_regno);
4899 			}
4900 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4901 			return 0;
4902 		}
4903 
4904 		if (dst_regno >= 0) {
4905 			/* restore register state from stack */
4906 			copy_register_state(&state->regs[dst_regno], reg);
4907 			/* mark reg as written since spilled pointer state likely
4908 			 * has its liveness marks cleared by is_state_visited()
4909 			 * which resets stack/reg liveness for state transitions
4910 			 */
4911 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4912 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4913 			/* If dst_regno==-1, the caller is asking us whether
4914 			 * it is acceptable to use this value as a SCALAR_VALUE
4915 			 * (e.g. for XADD).
4916 			 * We must not allow unprivileged callers to do that
4917 			 * with spilled pointers.
4918 			 */
4919 			verbose(env, "leaking pointer from stack off %d\n",
4920 				off);
4921 			return -EACCES;
4922 		}
4923 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4924 	} else {
4925 		for (i = 0; i < size; i++) {
4926 			type = stype[(slot - i) % BPF_REG_SIZE];
4927 			if (type == STACK_MISC)
4928 				continue;
4929 			if (type == STACK_ZERO)
4930 				continue;
4931 			if (type == STACK_INVALID && env->allow_uninit_stack)
4932 				continue;
4933 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4934 				off, i, size);
4935 			return -EACCES;
4936 		}
4937 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4938 		if (dst_regno >= 0)
4939 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4940 	}
4941 	return 0;
4942 }
4943 
4944 enum bpf_access_src {
4945 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4946 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4947 };
4948 
4949 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4950 					 int regno, int off, int access_size,
4951 					 bool zero_size_allowed,
4952 					 enum bpf_access_src type,
4953 					 struct bpf_call_arg_meta *meta);
4954 
4955 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4956 {
4957 	return cur_regs(env) + regno;
4958 }
4959 
4960 /* Read the stack at 'ptr_regno + off' and put the result into the register
4961  * 'dst_regno'.
4962  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4963  * but not its variable offset.
4964  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4965  *
4966  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4967  * filling registers (i.e. reads of spilled register cannot be detected when
4968  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4969  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4970  * offset; for a fixed offset check_stack_read_fixed_off should be used
4971  * instead.
4972  */
4973 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4974 				    int ptr_regno, int off, int size, int dst_regno)
4975 {
4976 	/* The state of the source register. */
4977 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4978 	struct bpf_func_state *ptr_state = func(env, reg);
4979 	int err;
4980 	int min_off, max_off;
4981 
4982 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4983 	 */
4984 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4985 					    false, ACCESS_DIRECT, NULL);
4986 	if (err)
4987 		return err;
4988 
4989 	min_off = reg->smin_value + off;
4990 	max_off = reg->smax_value + off;
4991 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4992 	return 0;
4993 }
4994 
4995 /* check_stack_read dispatches to check_stack_read_fixed_off or
4996  * check_stack_read_var_off.
4997  *
4998  * The caller must ensure that the offset falls within the allocated stack
4999  * bounds.
5000  *
5001  * 'dst_regno' is a register which will receive the value from the stack. It
5002  * can be -1, meaning that the read value is not going to a register.
5003  */
5004 static int check_stack_read(struct bpf_verifier_env *env,
5005 			    int ptr_regno, int off, int size,
5006 			    int dst_regno)
5007 {
5008 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5009 	struct bpf_func_state *state = func(env, reg);
5010 	int err;
5011 	/* Some accesses are only permitted with a static offset. */
5012 	bool var_off = !tnum_is_const(reg->var_off);
5013 
5014 	/* The offset is required to be static when reads don't go to a
5015 	 * register, in order to not leak pointers (see
5016 	 * check_stack_read_fixed_off).
5017 	 */
5018 	if (dst_regno < 0 && var_off) {
5019 		char tn_buf[48];
5020 
5021 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5022 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5023 			tn_buf, off, size);
5024 		return -EACCES;
5025 	}
5026 	/* Variable offset is prohibited for unprivileged mode for simplicity
5027 	 * since it requires corresponding support in Spectre masking for stack
5028 	 * ALU. See also retrieve_ptr_limit(). The check in
5029 	 * check_stack_access_for_ptr_arithmetic() called by
5030 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5031 	 * with variable offsets, therefore no check is required here. Further,
5032 	 * just checking it here would be insufficient as speculative stack
5033 	 * writes could still lead to unsafe speculative behaviour.
5034 	 */
5035 	if (!var_off) {
5036 		off += reg->var_off.value;
5037 		err = check_stack_read_fixed_off(env, state, off, size,
5038 						 dst_regno);
5039 	} else {
5040 		/* Variable offset stack reads need more conservative handling
5041 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5042 		 * branch.
5043 		 */
5044 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5045 					       dst_regno);
5046 	}
5047 	return err;
5048 }
5049 
5050 
5051 /* check_stack_write dispatches to check_stack_write_fixed_off or
5052  * check_stack_write_var_off.
5053  *
5054  * 'ptr_regno' is the register used as a pointer into the stack.
5055  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5056  * 'value_regno' is the register whose value we're writing to the stack. It can
5057  * be -1, meaning that we're not writing from a register.
5058  *
5059  * The caller must ensure that the offset falls within the maximum stack size.
5060  */
5061 static int check_stack_write(struct bpf_verifier_env *env,
5062 			     int ptr_regno, int off, int size,
5063 			     int value_regno, int insn_idx)
5064 {
5065 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5066 	struct bpf_func_state *state = func(env, reg);
5067 	int err;
5068 
5069 	if (tnum_is_const(reg->var_off)) {
5070 		off += reg->var_off.value;
5071 		err = check_stack_write_fixed_off(env, state, off, size,
5072 						  value_regno, insn_idx);
5073 	} else {
5074 		/* Variable offset stack reads need more conservative handling
5075 		 * than fixed offset ones.
5076 		 */
5077 		err = check_stack_write_var_off(env, state,
5078 						ptr_regno, off, size,
5079 						value_regno, insn_idx);
5080 	}
5081 	return err;
5082 }
5083 
5084 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5085 				 int off, int size, enum bpf_access_type type)
5086 {
5087 	struct bpf_reg_state *regs = cur_regs(env);
5088 	struct bpf_map *map = regs[regno].map_ptr;
5089 	u32 cap = bpf_map_flags_to_cap(map);
5090 
5091 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5092 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5093 			map->value_size, off, size);
5094 		return -EACCES;
5095 	}
5096 
5097 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5098 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5099 			map->value_size, off, size);
5100 		return -EACCES;
5101 	}
5102 
5103 	return 0;
5104 }
5105 
5106 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5107 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5108 			      int off, int size, u32 mem_size,
5109 			      bool zero_size_allowed)
5110 {
5111 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5112 	struct bpf_reg_state *reg;
5113 
5114 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5115 		return 0;
5116 
5117 	reg = &cur_regs(env)[regno];
5118 	switch (reg->type) {
5119 	case PTR_TO_MAP_KEY:
5120 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5121 			mem_size, off, size);
5122 		break;
5123 	case PTR_TO_MAP_VALUE:
5124 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5125 			mem_size, off, size);
5126 		break;
5127 	case PTR_TO_PACKET:
5128 	case PTR_TO_PACKET_META:
5129 	case PTR_TO_PACKET_END:
5130 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5131 			off, size, regno, reg->id, off, mem_size);
5132 		break;
5133 	case PTR_TO_MEM:
5134 	default:
5135 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5136 			mem_size, off, size);
5137 	}
5138 
5139 	return -EACCES;
5140 }
5141 
5142 /* check read/write into a memory region with possible variable offset */
5143 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5144 				   int off, int size, u32 mem_size,
5145 				   bool zero_size_allowed)
5146 {
5147 	struct bpf_verifier_state *vstate = env->cur_state;
5148 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5149 	struct bpf_reg_state *reg = &state->regs[regno];
5150 	int err;
5151 
5152 	/* We may have adjusted the register pointing to memory region, so we
5153 	 * need to try adding each of min_value and max_value to off
5154 	 * to make sure our theoretical access will be safe.
5155 	 *
5156 	 * The minimum value is only important with signed
5157 	 * comparisons where we can't assume the floor of a
5158 	 * value is 0.  If we are using signed variables for our
5159 	 * index'es we need to make sure that whatever we use
5160 	 * will have a set floor within our range.
5161 	 */
5162 	if (reg->smin_value < 0 &&
5163 	    (reg->smin_value == S64_MIN ||
5164 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5165 	      reg->smin_value + off < 0)) {
5166 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5167 			regno);
5168 		return -EACCES;
5169 	}
5170 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5171 				 mem_size, zero_size_allowed);
5172 	if (err) {
5173 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5174 			regno);
5175 		return err;
5176 	}
5177 
5178 	/* If we haven't set a max value then we need to bail since we can't be
5179 	 * sure we won't do bad things.
5180 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5181 	 */
5182 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5183 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5184 			regno);
5185 		return -EACCES;
5186 	}
5187 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5188 				 mem_size, zero_size_allowed);
5189 	if (err) {
5190 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5191 			regno);
5192 		return err;
5193 	}
5194 
5195 	return 0;
5196 }
5197 
5198 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5199 			       const struct bpf_reg_state *reg, int regno,
5200 			       bool fixed_off_ok)
5201 {
5202 	/* Access to this pointer-typed register or passing it to a helper
5203 	 * is only allowed in its original, unmodified form.
5204 	 */
5205 
5206 	if (reg->off < 0) {
5207 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5208 			reg_type_str(env, reg->type), regno, reg->off);
5209 		return -EACCES;
5210 	}
5211 
5212 	if (!fixed_off_ok && reg->off) {
5213 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5214 			reg_type_str(env, reg->type), regno, reg->off);
5215 		return -EACCES;
5216 	}
5217 
5218 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5219 		char tn_buf[48];
5220 
5221 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5222 		verbose(env, "variable %s access var_off=%s disallowed\n",
5223 			reg_type_str(env, reg->type), tn_buf);
5224 		return -EACCES;
5225 	}
5226 
5227 	return 0;
5228 }
5229 
5230 int check_ptr_off_reg(struct bpf_verifier_env *env,
5231 		      const struct bpf_reg_state *reg, int regno)
5232 {
5233 	return __check_ptr_off_reg(env, reg, regno, false);
5234 }
5235 
5236 static int map_kptr_match_type(struct bpf_verifier_env *env,
5237 			       struct btf_field *kptr_field,
5238 			       struct bpf_reg_state *reg, u32 regno)
5239 {
5240 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5241 	int perm_flags;
5242 	const char *reg_name = "";
5243 
5244 	if (btf_is_kernel(reg->btf)) {
5245 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5246 
5247 		/* Only unreferenced case accepts untrusted pointers */
5248 		if (kptr_field->type == BPF_KPTR_UNREF)
5249 			perm_flags |= PTR_UNTRUSTED;
5250 	} else {
5251 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5252 	}
5253 
5254 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5255 		goto bad_type;
5256 
5257 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5258 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5259 
5260 	/* For ref_ptr case, release function check should ensure we get one
5261 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5262 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5263 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5264 	 * reg->off and reg->ref_obj_id are not needed here.
5265 	 */
5266 	if (__check_ptr_off_reg(env, reg, regno, true))
5267 		return -EACCES;
5268 
5269 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5270 	 * we also need to take into account the reg->off.
5271 	 *
5272 	 * We want to support cases like:
5273 	 *
5274 	 * struct foo {
5275 	 *         struct bar br;
5276 	 *         struct baz bz;
5277 	 * };
5278 	 *
5279 	 * struct foo *v;
5280 	 * v = func();	      // PTR_TO_BTF_ID
5281 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5282 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5283 	 *                    // first member type of struct after comparison fails
5284 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5285 	 *                    // to match type
5286 	 *
5287 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5288 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5289 	 * the struct to match type against first member of struct, i.e. reject
5290 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5291 	 * strict mode to true for type match.
5292 	 */
5293 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5294 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5295 				  kptr_field->type == BPF_KPTR_REF))
5296 		goto bad_type;
5297 	return 0;
5298 bad_type:
5299 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5300 		reg_type_str(env, reg->type), reg_name);
5301 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5302 	if (kptr_field->type == BPF_KPTR_UNREF)
5303 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5304 			targ_name);
5305 	else
5306 		verbose(env, "\n");
5307 	return -EINVAL;
5308 }
5309 
5310 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5311  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5312  */
5313 static bool in_rcu_cs(struct bpf_verifier_env *env)
5314 {
5315 	return env->cur_state->active_rcu_lock ||
5316 	       env->cur_state->active_lock.ptr ||
5317 	       !env->prog->aux->sleepable;
5318 }
5319 
5320 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5321 BTF_SET_START(rcu_protected_types)
5322 BTF_ID(struct, prog_test_ref_kfunc)
5323 BTF_ID(struct, cgroup)
5324 BTF_ID(struct, bpf_cpumask)
5325 BTF_ID(struct, task_struct)
5326 BTF_SET_END(rcu_protected_types)
5327 
5328 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5329 {
5330 	if (!btf_is_kernel(btf))
5331 		return false;
5332 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5333 }
5334 
5335 static bool rcu_safe_kptr(const struct btf_field *field)
5336 {
5337 	const struct btf_field_kptr *kptr = &field->kptr;
5338 
5339 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5340 }
5341 
5342 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5343 				 int value_regno, int insn_idx,
5344 				 struct btf_field *kptr_field)
5345 {
5346 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5347 	int class = BPF_CLASS(insn->code);
5348 	struct bpf_reg_state *val_reg;
5349 
5350 	/* Things we already checked for in check_map_access and caller:
5351 	 *  - Reject cases where variable offset may touch kptr
5352 	 *  - size of access (must be BPF_DW)
5353 	 *  - tnum_is_const(reg->var_off)
5354 	 *  - kptr_field->offset == off + reg->var_off.value
5355 	 */
5356 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5357 	if (BPF_MODE(insn->code) != BPF_MEM) {
5358 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5359 		return -EACCES;
5360 	}
5361 
5362 	/* We only allow loading referenced kptr, since it will be marked as
5363 	 * untrusted, similar to unreferenced kptr.
5364 	 */
5365 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5366 		verbose(env, "store to referenced kptr disallowed\n");
5367 		return -EACCES;
5368 	}
5369 
5370 	if (class == BPF_LDX) {
5371 		val_reg = reg_state(env, value_regno);
5372 		/* We can simply mark the value_regno receiving the pointer
5373 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5374 		 */
5375 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5376 				kptr_field->kptr.btf_id,
5377 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5378 				PTR_MAYBE_NULL | MEM_RCU :
5379 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5380 	} else if (class == BPF_STX) {
5381 		val_reg = reg_state(env, value_regno);
5382 		if (!register_is_null(val_reg) &&
5383 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5384 			return -EACCES;
5385 	} else if (class == BPF_ST) {
5386 		if (insn->imm) {
5387 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5388 				kptr_field->offset);
5389 			return -EACCES;
5390 		}
5391 	} else {
5392 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5393 		return -EACCES;
5394 	}
5395 	return 0;
5396 }
5397 
5398 /* check read/write into a map element with possible variable offset */
5399 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5400 			    int off, int size, bool zero_size_allowed,
5401 			    enum bpf_access_src src)
5402 {
5403 	struct bpf_verifier_state *vstate = env->cur_state;
5404 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5405 	struct bpf_reg_state *reg = &state->regs[regno];
5406 	struct bpf_map *map = reg->map_ptr;
5407 	struct btf_record *rec;
5408 	int err, i;
5409 
5410 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5411 				      zero_size_allowed);
5412 	if (err)
5413 		return err;
5414 
5415 	if (IS_ERR_OR_NULL(map->record))
5416 		return 0;
5417 	rec = map->record;
5418 	for (i = 0; i < rec->cnt; i++) {
5419 		struct btf_field *field = &rec->fields[i];
5420 		u32 p = field->offset;
5421 
5422 		/* If any part of a field  can be touched by load/store, reject
5423 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5424 		 * it is sufficient to check x1 < y2 && y1 < x2.
5425 		 */
5426 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5427 		    p < reg->umax_value + off + size) {
5428 			switch (field->type) {
5429 			case BPF_KPTR_UNREF:
5430 			case BPF_KPTR_REF:
5431 				if (src != ACCESS_DIRECT) {
5432 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5433 					return -EACCES;
5434 				}
5435 				if (!tnum_is_const(reg->var_off)) {
5436 					verbose(env, "kptr access cannot have variable offset\n");
5437 					return -EACCES;
5438 				}
5439 				if (p != off + reg->var_off.value) {
5440 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5441 						p, off + reg->var_off.value);
5442 					return -EACCES;
5443 				}
5444 				if (size != bpf_size_to_bytes(BPF_DW)) {
5445 					verbose(env, "kptr access size must be BPF_DW\n");
5446 					return -EACCES;
5447 				}
5448 				break;
5449 			default:
5450 				verbose(env, "%s cannot be accessed directly by load/store\n",
5451 					btf_field_type_name(field->type));
5452 				return -EACCES;
5453 			}
5454 		}
5455 	}
5456 	return 0;
5457 }
5458 
5459 #define MAX_PACKET_OFF 0xffff
5460 
5461 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5462 				       const struct bpf_call_arg_meta *meta,
5463 				       enum bpf_access_type t)
5464 {
5465 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5466 
5467 	switch (prog_type) {
5468 	/* Program types only with direct read access go here! */
5469 	case BPF_PROG_TYPE_LWT_IN:
5470 	case BPF_PROG_TYPE_LWT_OUT:
5471 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5472 	case BPF_PROG_TYPE_SK_REUSEPORT:
5473 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5474 	case BPF_PROG_TYPE_CGROUP_SKB:
5475 		if (t == BPF_WRITE)
5476 			return false;
5477 		fallthrough;
5478 
5479 	/* Program types with direct read + write access go here! */
5480 	case BPF_PROG_TYPE_SCHED_CLS:
5481 	case BPF_PROG_TYPE_SCHED_ACT:
5482 	case BPF_PROG_TYPE_XDP:
5483 	case BPF_PROG_TYPE_LWT_XMIT:
5484 	case BPF_PROG_TYPE_SK_SKB:
5485 	case BPF_PROG_TYPE_SK_MSG:
5486 		if (meta)
5487 			return meta->pkt_access;
5488 
5489 		env->seen_direct_write = true;
5490 		return true;
5491 
5492 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5493 		if (t == BPF_WRITE)
5494 			env->seen_direct_write = true;
5495 
5496 		return true;
5497 
5498 	default:
5499 		return false;
5500 	}
5501 }
5502 
5503 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5504 			       int size, bool zero_size_allowed)
5505 {
5506 	struct bpf_reg_state *regs = cur_regs(env);
5507 	struct bpf_reg_state *reg = &regs[regno];
5508 	int err;
5509 
5510 	/* We may have added a variable offset to the packet pointer; but any
5511 	 * reg->range we have comes after that.  We are only checking the fixed
5512 	 * offset.
5513 	 */
5514 
5515 	/* We don't allow negative numbers, because we aren't tracking enough
5516 	 * detail to prove they're safe.
5517 	 */
5518 	if (reg->smin_value < 0) {
5519 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5520 			regno);
5521 		return -EACCES;
5522 	}
5523 
5524 	err = reg->range < 0 ? -EINVAL :
5525 	      __check_mem_access(env, regno, off, size, reg->range,
5526 				 zero_size_allowed);
5527 	if (err) {
5528 		verbose(env, "R%d offset is outside of the packet\n", regno);
5529 		return err;
5530 	}
5531 
5532 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5533 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5534 	 * otherwise find_good_pkt_pointers would have refused to set range info
5535 	 * that __check_mem_access would have rejected this pkt access.
5536 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5537 	 */
5538 	env->prog->aux->max_pkt_offset =
5539 		max_t(u32, env->prog->aux->max_pkt_offset,
5540 		      off + reg->umax_value + size - 1);
5541 
5542 	return err;
5543 }
5544 
5545 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5546 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5547 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5548 			    struct btf **btf, u32 *btf_id)
5549 {
5550 	struct bpf_insn_access_aux info = {
5551 		.reg_type = *reg_type,
5552 		.log = &env->log,
5553 	};
5554 
5555 	if (env->ops->is_valid_access &&
5556 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5557 		/* A non zero info.ctx_field_size indicates that this field is a
5558 		 * candidate for later verifier transformation to load the whole
5559 		 * field and then apply a mask when accessed with a narrower
5560 		 * access than actual ctx access size. A zero info.ctx_field_size
5561 		 * will only allow for whole field access and rejects any other
5562 		 * type of narrower access.
5563 		 */
5564 		*reg_type = info.reg_type;
5565 
5566 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5567 			*btf = info.btf;
5568 			*btf_id = info.btf_id;
5569 		} else {
5570 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5571 		}
5572 		/* remember the offset of last byte accessed in ctx */
5573 		if (env->prog->aux->max_ctx_offset < off + size)
5574 			env->prog->aux->max_ctx_offset = off + size;
5575 		return 0;
5576 	}
5577 
5578 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5579 	return -EACCES;
5580 }
5581 
5582 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5583 				  int size)
5584 {
5585 	if (size < 0 || off < 0 ||
5586 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5587 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5588 			off, size);
5589 		return -EACCES;
5590 	}
5591 	return 0;
5592 }
5593 
5594 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5595 			     u32 regno, int off, int size,
5596 			     enum bpf_access_type t)
5597 {
5598 	struct bpf_reg_state *regs = cur_regs(env);
5599 	struct bpf_reg_state *reg = &regs[regno];
5600 	struct bpf_insn_access_aux info = {};
5601 	bool valid;
5602 
5603 	if (reg->smin_value < 0) {
5604 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5605 			regno);
5606 		return -EACCES;
5607 	}
5608 
5609 	switch (reg->type) {
5610 	case PTR_TO_SOCK_COMMON:
5611 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5612 		break;
5613 	case PTR_TO_SOCKET:
5614 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5615 		break;
5616 	case PTR_TO_TCP_SOCK:
5617 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5618 		break;
5619 	case PTR_TO_XDP_SOCK:
5620 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5621 		break;
5622 	default:
5623 		valid = false;
5624 	}
5625 
5626 
5627 	if (valid) {
5628 		env->insn_aux_data[insn_idx].ctx_field_size =
5629 			info.ctx_field_size;
5630 		return 0;
5631 	}
5632 
5633 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5634 		regno, reg_type_str(env, reg->type), off, size);
5635 
5636 	return -EACCES;
5637 }
5638 
5639 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5640 {
5641 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5642 }
5643 
5644 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5645 {
5646 	const struct bpf_reg_state *reg = reg_state(env, regno);
5647 
5648 	return reg->type == PTR_TO_CTX;
5649 }
5650 
5651 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5652 {
5653 	const struct bpf_reg_state *reg = reg_state(env, regno);
5654 
5655 	return type_is_sk_pointer(reg->type);
5656 }
5657 
5658 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5659 {
5660 	const struct bpf_reg_state *reg = reg_state(env, regno);
5661 
5662 	return type_is_pkt_pointer(reg->type);
5663 }
5664 
5665 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5666 {
5667 	const struct bpf_reg_state *reg = reg_state(env, regno);
5668 
5669 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5670 	return reg->type == PTR_TO_FLOW_KEYS;
5671 }
5672 
5673 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5674 #ifdef CONFIG_NET
5675 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5676 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5677 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5678 #endif
5679 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5680 };
5681 
5682 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5683 {
5684 	/* A referenced register is always trusted. */
5685 	if (reg->ref_obj_id)
5686 		return true;
5687 
5688 	/* Types listed in the reg2btf_ids are always trusted */
5689 	if (reg2btf_ids[base_type(reg->type)] &&
5690 	    !bpf_type_has_unsafe_modifiers(reg->type))
5691 		return true;
5692 
5693 	/* If a register is not referenced, it is trusted if it has the
5694 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5695 	 * other type modifiers may be safe, but we elect to take an opt-in
5696 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5697 	 * not.
5698 	 *
5699 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5700 	 * for whether a register is trusted.
5701 	 */
5702 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5703 	       !bpf_type_has_unsafe_modifiers(reg->type);
5704 }
5705 
5706 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5707 {
5708 	return reg->type & MEM_RCU;
5709 }
5710 
5711 static void clear_trusted_flags(enum bpf_type_flag *flag)
5712 {
5713 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5714 }
5715 
5716 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5717 				   const struct bpf_reg_state *reg,
5718 				   int off, int size, bool strict)
5719 {
5720 	struct tnum reg_off;
5721 	int ip_align;
5722 
5723 	/* Byte size accesses are always allowed. */
5724 	if (!strict || size == 1)
5725 		return 0;
5726 
5727 	/* For platforms that do not have a Kconfig enabling
5728 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5729 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5730 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5731 	 * to this code only in strict mode where we want to emulate
5732 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5733 	 * unconditional IP align value of '2'.
5734 	 */
5735 	ip_align = 2;
5736 
5737 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5738 	if (!tnum_is_aligned(reg_off, size)) {
5739 		char tn_buf[48];
5740 
5741 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5742 		verbose(env,
5743 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5744 			ip_align, tn_buf, reg->off, off, size);
5745 		return -EACCES;
5746 	}
5747 
5748 	return 0;
5749 }
5750 
5751 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5752 				       const struct bpf_reg_state *reg,
5753 				       const char *pointer_desc,
5754 				       int off, int size, bool strict)
5755 {
5756 	struct tnum reg_off;
5757 
5758 	/* Byte size accesses are always allowed. */
5759 	if (!strict || size == 1)
5760 		return 0;
5761 
5762 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5763 	if (!tnum_is_aligned(reg_off, size)) {
5764 		char tn_buf[48];
5765 
5766 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5767 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5768 			pointer_desc, tn_buf, reg->off, off, size);
5769 		return -EACCES;
5770 	}
5771 
5772 	return 0;
5773 }
5774 
5775 static int check_ptr_alignment(struct bpf_verifier_env *env,
5776 			       const struct bpf_reg_state *reg, int off,
5777 			       int size, bool strict_alignment_once)
5778 {
5779 	bool strict = env->strict_alignment || strict_alignment_once;
5780 	const char *pointer_desc = "";
5781 
5782 	switch (reg->type) {
5783 	case PTR_TO_PACKET:
5784 	case PTR_TO_PACKET_META:
5785 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5786 		 * right in front, treat it the very same way.
5787 		 */
5788 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5789 	case PTR_TO_FLOW_KEYS:
5790 		pointer_desc = "flow keys ";
5791 		break;
5792 	case PTR_TO_MAP_KEY:
5793 		pointer_desc = "key ";
5794 		break;
5795 	case PTR_TO_MAP_VALUE:
5796 		pointer_desc = "value ";
5797 		break;
5798 	case PTR_TO_CTX:
5799 		pointer_desc = "context ";
5800 		break;
5801 	case PTR_TO_STACK:
5802 		pointer_desc = "stack ";
5803 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5804 		 * and check_stack_read_fixed_off() relies on stack accesses being
5805 		 * aligned.
5806 		 */
5807 		strict = true;
5808 		break;
5809 	case PTR_TO_SOCKET:
5810 		pointer_desc = "sock ";
5811 		break;
5812 	case PTR_TO_SOCK_COMMON:
5813 		pointer_desc = "sock_common ";
5814 		break;
5815 	case PTR_TO_TCP_SOCK:
5816 		pointer_desc = "tcp_sock ";
5817 		break;
5818 	case PTR_TO_XDP_SOCK:
5819 		pointer_desc = "xdp_sock ";
5820 		break;
5821 	default:
5822 		break;
5823 	}
5824 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5825 					   strict);
5826 }
5827 
5828 /* starting from main bpf function walk all instructions of the function
5829  * and recursively walk all callees that given function can call.
5830  * Ignore jump and exit insns.
5831  * Since recursion is prevented by check_cfg() this algorithm
5832  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5833  */
5834 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5835 {
5836 	struct bpf_subprog_info *subprog = env->subprog_info;
5837 	struct bpf_insn *insn = env->prog->insnsi;
5838 	int depth = 0, frame = 0, i, subprog_end;
5839 	bool tail_call_reachable = false;
5840 	int ret_insn[MAX_CALL_FRAMES];
5841 	int ret_prog[MAX_CALL_FRAMES];
5842 	int j;
5843 
5844 	i = subprog[idx].start;
5845 process_func:
5846 	/* protect against potential stack overflow that might happen when
5847 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5848 	 * depth for such case down to 256 so that the worst case scenario
5849 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5850 	 * 8k).
5851 	 *
5852 	 * To get the idea what might happen, see an example:
5853 	 * func1 -> sub rsp, 128
5854 	 *  subfunc1 -> sub rsp, 256
5855 	 *  tailcall1 -> add rsp, 256
5856 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5857 	 *   subfunc2 -> sub rsp, 64
5858 	 *   subfunc22 -> sub rsp, 128
5859 	 *   tailcall2 -> add rsp, 128
5860 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5861 	 *
5862 	 * tailcall will unwind the current stack frame but it will not get rid
5863 	 * of caller's stack as shown on the example above.
5864 	 */
5865 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5866 		verbose(env,
5867 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5868 			depth);
5869 		return -EACCES;
5870 	}
5871 	/* round up to 32-bytes, since this is granularity
5872 	 * of interpreter stack size
5873 	 */
5874 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5875 	if (depth > MAX_BPF_STACK) {
5876 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5877 			frame + 1, depth);
5878 		return -EACCES;
5879 	}
5880 continue_func:
5881 	subprog_end = subprog[idx + 1].start;
5882 	for (; i < subprog_end; i++) {
5883 		int next_insn, sidx;
5884 
5885 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5886 			continue;
5887 		/* remember insn and function to return to */
5888 		ret_insn[frame] = i + 1;
5889 		ret_prog[frame] = idx;
5890 
5891 		/* find the callee */
5892 		next_insn = i + insn[i].imm + 1;
5893 		sidx = find_subprog(env, next_insn);
5894 		if (sidx < 0) {
5895 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5896 				  next_insn);
5897 			return -EFAULT;
5898 		}
5899 		if (subprog[sidx].is_async_cb) {
5900 			if (subprog[sidx].has_tail_call) {
5901 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5902 				return -EFAULT;
5903 			}
5904 			/* async callbacks don't increase bpf prog stack size unless called directly */
5905 			if (!bpf_pseudo_call(insn + i))
5906 				continue;
5907 		}
5908 		i = next_insn;
5909 		idx = sidx;
5910 
5911 		if (subprog[idx].has_tail_call)
5912 			tail_call_reachable = true;
5913 
5914 		frame++;
5915 		if (frame >= MAX_CALL_FRAMES) {
5916 			verbose(env, "the call stack of %d frames is too deep !\n",
5917 				frame);
5918 			return -E2BIG;
5919 		}
5920 		goto process_func;
5921 	}
5922 	/* if tail call got detected across bpf2bpf calls then mark each of the
5923 	 * currently present subprog frames as tail call reachable subprogs;
5924 	 * this info will be utilized by JIT so that we will be preserving the
5925 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5926 	 */
5927 	if (tail_call_reachable)
5928 		for (j = 0; j < frame; j++)
5929 			subprog[ret_prog[j]].tail_call_reachable = true;
5930 	if (subprog[0].tail_call_reachable)
5931 		env->prog->aux->tail_call_reachable = true;
5932 
5933 	/* end of for() loop means the last insn of the 'subprog'
5934 	 * was reached. Doesn't matter whether it was JA or EXIT
5935 	 */
5936 	if (frame == 0)
5937 		return 0;
5938 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5939 	frame--;
5940 	i = ret_insn[frame];
5941 	idx = ret_prog[frame];
5942 	goto continue_func;
5943 }
5944 
5945 static int check_max_stack_depth(struct bpf_verifier_env *env)
5946 {
5947 	struct bpf_subprog_info *si = env->subprog_info;
5948 	int ret;
5949 
5950 	for (int i = 0; i < env->subprog_cnt; i++) {
5951 		if (!i || si[i].is_async_cb) {
5952 			ret = check_max_stack_depth_subprog(env, i);
5953 			if (ret < 0)
5954 				return ret;
5955 		}
5956 		continue;
5957 	}
5958 	return 0;
5959 }
5960 
5961 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5962 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5963 				  const struct bpf_insn *insn, int idx)
5964 {
5965 	int start = idx + insn->imm + 1, subprog;
5966 
5967 	subprog = find_subprog(env, start);
5968 	if (subprog < 0) {
5969 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5970 			  start);
5971 		return -EFAULT;
5972 	}
5973 	return env->subprog_info[subprog].stack_depth;
5974 }
5975 #endif
5976 
5977 static int __check_buffer_access(struct bpf_verifier_env *env,
5978 				 const char *buf_info,
5979 				 const struct bpf_reg_state *reg,
5980 				 int regno, int off, int size)
5981 {
5982 	if (off < 0) {
5983 		verbose(env,
5984 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5985 			regno, buf_info, off, size);
5986 		return -EACCES;
5987 	}
5988 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5989 		char tn_buf[48];
5990 
5991 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5992 		verbose(env,
5993 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5994 			regno, off, tn_buf);
5995 		return -EACCES;
5996 	}
5997 
5998 	return 0;
5999 }
6000 
6001 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6002 				  const struct bpf_reg_state *reg,
6003 				  int regno, int off, int size)
6004 {
6005 	int err;
6006 
6007 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6008 	if (err)
6009 		return err;
6010 
6011 	if (off + size > env->prog->aux->max_tp_access)
6012 		env->prog->aux->max_tp_access = off + size;
6013 
6014 	return 0;
6015 }
6016 
6017 static int check_buffer_access(struct bpf_verifier_env *env,
6018 			       const struct bpf_reg_state *reg,
6019 			       int regno, int off, int size,
6020 			       bool zero_size_allowed,
6021 			       u32 *max_access)
6022 {
6023 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6024 	int err;
6025 
6026 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6027 	if (err)
6028 		return err;
6029 
6030 	if (off + size > *max_access)
6031 		*max_access = off + size;
6032 
6033 	return 0;
6034 }
6035 
6036 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6037 static void zext_32_to_64(struct bpf_reg_state *reg)
6038 {
6039 	reg->var_off = tnum_subreg(reg->var_off);
6040 	__reg_assign_32_into_64(reg);
6041 }
6042 
6043 /* truncate register to smaller size (in bytes)
6044  * must be called with size < BPF_REG_SIZE
6045  */
6046 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6047 {
6048 	u64 mask;
6049 
6050 	/* clear high bits in bit representation */
6051 	reg->var_off = tnum_cast(reg->var_off, size);
6052 
6053 	/* fix arithmetic bounds */
6054 	mask = ((u64)1 << (size * 8)) - 1;
6055 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6056 		reg->umin_value &= mask;
6057 		reg->umax_value &= mask;
6058 	} else {
6059 		reg->umin_value = 0;
6060 		reg->umax_value = mask;
6061 	}
6062 	reg->smin_value = reg->umin_value;
6063 	reg->smax_value = reg->umax_value;
6064 
6065 	/* If size is smaller than 32bit register the 32bit register
6066 	 * values are also truncated so we push 64-bit bounds into
6067 	 * 32-bit bounds. Above were truncated < 32-bits already.
6068 	 */
6069 	if (size >= 4)
6070 		return;
6071 	__reg_combine_64_into_32(reg);
6072 }
6073 
6074 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6075 {
6076 	if (size == 1) {
6077 		reg->smin_value = reg->s32_min_value = S8_MIN;
6078 		reg->smax_value = reg->s32_max_value = S8_MAX;
6079 	} else if (size == 2) {
6080 		reg->smin_value = reg->s32_min_value = S16_MIN;
6081 		reg->smax_value = reg->s32_max_value = S16_MAX;
6082 	} else {
6083 		/* size == 4 */
6084 		reg->smin_value = reg->s32_min_value = S32_MIN;
6085 		reg->smax_value = reg->s32_max_value = S32_MAX;
6086 	}
6087 	reg->umin_value = reg->u32_min_value = 0;
6088 	reg->umax_value = U64_MAX;
6089 	reg->u32_max_value = U32_MAX;
6090 	reg->var_off = tnum_unknown;
6091 }
6092 
6093 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6094 {
6095 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6096 	u64 top_smax_value, top_smin_value;
6097 	u64 num_bits = size * 8;
6098 
6099 	if (tnum_is_const(reg->var_off)) {
6100 		u64_cval = reg->var_off.value;
6101 		if (size == 1)
6102 			reg->var_off = tnum_const((s8)u64_cval);
6103 		else if (size == 2)
6104 			reg->var_off = tnum_const((s16)u64_cval);
6105 		else
6106 			/* size == 4 */
6107 			reg->var_off = tnum_const((s32)u64_cval);
6108 
6109 		u64_cval = reg->var_off.value;
6110 		reg->smax_value = reg->smin_value = u64_cval;
6111 		reg->umax_value = reg->umin_value = u64_cval;
6112 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6113 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6114 		return;
6115 	}
6116 
6117 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6118 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6119 
6120 	if (top_smax_value != top_smin_value)
6121 		goto out;
6122 
6123 	/* find the s64_min and s64_min after sign extension */
6124 	if (size == 1) {
6125 		init_s64_max = (s8)reg->smax_value;
6126 		init_s64_min = (s8)reg->smin_value;
6127 	} else if (size == 2) {
6128 		init_s64_max = (s16)reg->smax_value;
6129 		init_s64_min = (s16)reg->smin_value;
6130 	} else {
6131 		init_s64_max = (s32)reg->smax_value;
6132 		init_s64_min = (s32)reg->smin_value;
6133 	}
6134 
6135 	s64_max = max(init_s64_max, init_s64_min);
6136 	s64_min = min(init_s64_max, init_s64_min);
6137 
6138 	/* both of s64_max/s64_min positive or negative */
6139 	if ((s64_max >= 0) == (s64_min >= 0)) {
6140 		reg->smin_value = reg->s32_min_value = s64_min;
6141 		reg->smax_value = reg->s32_max_value = s64_max;
6142 		reg->umin_value = reg->u32_min_value = s64_min;
6143 		reg->umax_value = reg->u32_max_value = s64_max;
6144 		reg->var_off = tnum_range(s64_min, s64_max);
6145 		return;
6146 	}
6147 
6148 out:
6149 	set_sext64_default_val(reg, size);
6150 }
6151 
6152 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6153 {
6154 	if (size == 1) {
6155 		reg->s32_min_value = S8_MIN;
6156 		reg->s32_max_value = S8_MAX;
6157 	} else {
6158 		/* size == 2 */
6159 		reg->s32_min_value = S16_MIN;
6160 		reg->s32_max_value = S16_MAX;
6161 	}
6162 	reg->u32_min_value = 0;
6163 	reg->u32_max_value = U32_MAX;
6164 	reg->var_off = tnum_subreg(tnum_unknown);
6165 }
6166 
6167 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6168 {
6169 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6170 	u32 top_smax_value, top_smin_value;
6171 	u32 num_bits = size * 8;
6172 
6173 	if (tnum_is_const(reg->var_off)) {
6174 		u32_val = reg->var_off.value;
6175 		if (size == 1)
6176 			reg->var_off = tnum_const((s8)u32_val);
6177 		else
6178 			reg->var_off = tnum_const((s16)u32_val);
6179 
6180 		u32_val = reg->var_off.value;
6181 		reg->s32_min_value = reg->s32_max_value = u32_val;
6182 		reg->u32_min_value = reg->u32_max_value = u32_val;
6183 		return;
6184 	}
6185 
6186 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6187 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6188 
6189 	if (top_smax_value != top_smin_value)
6190 		goto out;
6191 
6192 	/* find the s32_min and s32_min after sign extension */
6193 	if (size == 1) {
6194 		init_s32_max = (s8)reg->s32_max_value;
6195 		init_s32_min = (s8)reg->s32_min_value;
6196 	} else {
6197 		/* size == 2 */
6198 		init_s32_max = (s16)reg->s32_max_value;
6199 		init_s32_min = (s16)reg->s32_min_value;
6200 	}
6201 	s32_max = max(init_s32_max, init_s32_min);
6202 	s32_min = min(init_s32_max, init_s32_min);
6203 
6204 	if ((s32_min >= 0) == (s32_max >= 0)) {
6205 		reg->s32_min_value = s32_min;
6206 		reg->s32_max_value = s32_max;
6207 		reg->u32_min_value = (u32)s32_min;
6208 		reg->u32_max_value = (u32)s32_max;
6209 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6210 		return;
6211 	}
6212 
6213 out:
6214 	set_sext32_default_val(reg, size);
6215 }
6216 
6217 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6218 {
6219 	/* A map is considered read-only if the following condition are true:
6220 	 *
6221 	 * 1) BPF program side cannot change any of the map content. The
6222 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6223 	 *    and was set at map creation time.
6224 	 * 2) The map value(s) have been initialized from user space by a
6225 	 *    loader and then "frozen", such that no new map update/delete
6226 	 *    operations from syscall side are possible for the rest of
6227 	 *    the map's lifetime from that point onwards.
6228 	 * 3) Any parallel/pending map update/delete operations from syscall
6229 	 *    side have been completed. Only after that point, it's safe to
6230 	 *    assume that map value(s) are immutable.
6231 	 */
6232 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6233 	       READ_ONCE(map->frozen) &&
6234 	       !bpf_map_write_active(map);
6235 }
6236 
6237 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6238 			       bool is_ldsx)
6239 {
6240 	void *ptr;
6241 	u64 addr;
6242 	int err;
6243 
6244 	err = map->ops->map_direct_value_addr(map, &addr, off);
6245 	if (err)
6246 		return err;
6247 	ptr = (void *)(long)addr + off;
6248 
6249 	switch (size) {
6250 	case sizeof(u8):
6251 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6252 		break;
6253 	case sizeof(u16):
6254 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6255 		break;
6256 	case sizeof(u32):
6257 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6258 		break;
6259 	case sizeof(u64):
6260 		*val = *(u64 *)ptr;
6261 		break;
6262 	default:
6263 		return -EINVAL;
6264 	}
6265 	return 0;
6266 }
6267 
6268 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6269 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6270 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6271 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6272 
6273 /*
6274  * Allow list few fields as RCU trusted or full trusted.
6275  * This logic doesn't allow mix tagging and will be removed once GCC supports
6276  * btf_type_tag.
6277  */
6278 
6279 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6280 BTF_TYPE_SAFE_RCU(struct task_struct) {
6281 	const cpumask_t *cpus_ptr;
6282 	struct css_set __rcu *cgroups;
6283 	struct task_struct __rcu *real_parent;
6284 	struct task_struct *group_leader;
6285 };
6286 
6287 BTF_TYPE_SAFE_RCU(struct cgroup) {
6288 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6289 	struct kernfs_node *kn;
6290 };
6291 
6292 BTF_TYPE_SAFE_RCU(struct css_set) {
6293 	struct cgroup *dfl_cgrp;
6294 };
6295 
6296 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6297 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6298 	struct file __rcu *exe_file;
6299 };
6300 
6301 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6302  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6303  */
6304 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6305 	struct sock *sk;
6306 };
6307 
6308 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6309 	struct sock *sk;
6310 };
6311 
6312 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6313 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6314 	struct seq_file *seq;
6315 };
6316 
6317 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6318 	struct bpf_iter_meta *meta;
6319 	struct task_struct *task;
6320 };
6321 
6322 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6323 	struct file *file;
6324 };
6325 
6326 BTF_TYPE_SAFE_TRUSTED(struct file) {
6327 	struct inode *f_inode;
6328 };
6329 
6330 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6331 	/* no negative dentry-s in places where bpf can see it */
6332 	struct inode *d_inode;
6333 };
6334 
6335 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6336 	struct sock *sk;
6337 };
6338 
6339 static bool type_is_rcu(struct bpf_verifier_env *env,
6340 			struct bpf_reg_state *reg,
6341 			const char *field_name, u32 btf_id)
6342 {
6343 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6344 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6345 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6346 
6347 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6348 }
6349 
6350 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6351 				struct bpf_reg_state *reg,
6352 				const char *field_name, u32 btf_id)
6353 {
6354 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6355 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6356 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6357 
6358 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6359 }
6360 
6361 static bool type_is_trusted(struct bpf_verifier_env *env,
6362 			    struct bpf_reg_state *reg,
6363 			    const char *field_name, u32 btf_id)
6364 {
6365 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6366 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6367 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6368 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6369 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6370 
6371 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6372 }
6373 
6374 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6375 				    struct bpf_reg_state *reg,
6376 				    const char *field_name, u32 btf_id)
6377 {
6378 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6379 
6380 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6381 					  "__safe_trusted_or_null");
6382 }
6383 
6384 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6385 				   struct bpf_reg_state *regs,
6386 				   int regno, int off, int size,
6387 				   enum bpf_access_type atype,
6388 				   int value_regno)
6389 {
6390 	struct bpf_reg_state *reg = regs + regno;
6391 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6392 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6393 	const char *field_name = NULL;
6394 	enum bpf_type_flag flag = 0;
6395 	u32 btf_id = 0;
6396 	int ret;
6397 
6398 	if (!env->allow_ptr_leaks) {
6399 		verbose(env,
6400 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6401 			tname);
6402 		return -EPERM;
6403 	}
6404 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6405 		verbose(env,
6406 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6407 			tname);
6408 		return -EINVAL;
6409 	}
6410 	if (off < 0) {
6411 		verbose(env,
6412 			"R%d is ptr_%s invalid negative access: off=%d\n",
6413 			regno, tname, off);
6414 		return -EACCES;
6415 	}
6416 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6417 		char tn_buf[48];
6418 
6419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6420 		verbose(env,
6421 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6422 			regno, tname, off, tn_buf);
6423 		return -EACCES;
6424 	}
6425 
6426 	if (reg->type & MEM_USER) {
6427 		verbose(env,
6428 			"R%d is ptr_%s access user memory: off=%d\n",
6429 			regno, tname, off);
6430 		return -EACCES;
6431 	}
6432 
6433 	if (reg->type & MEM_PERCPU) {
6434 		verbose(env,
6435 			"R%d is ptr_%s access percpu memory: off=%d\n",
6436 			regno, tname, off);
6437 		return -EACCES;
6438 	}
6439 
6440 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6441 		if (!btf_is_kernel(reg->btf)) {
6442 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6443 			return -EFAULT;
6444 		}
6445 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6446 	} else {
6447 		/* Writes are permitted with default btf_struct_access for
6448 		 * program allocated objects (which always have ref_obj_id > 0),
6449 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6450 		 */
6451 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6452 			verbose(env, "only read is supported\n");
6453 			return -EACCES;
6454 		}
6455 
6456 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6457 		    !reg->ref_obj_id) {
6458 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6459 			return -EFAULT;
6460 		}
6461 
6462 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6463 	}
6464 
6465 	if (ret < 0)
6466 		return ret;
6467 
6468 	if (ret != PTR_TO_BTF_ID) {
6469 		/* just mark; */
6470 
6471 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6472 		/* If this is an untrusted pointer, all pointers formed by walking it
6473 		 * also inherit the untrusted flag.
6474 		 */
6475 		flag = PTR_UNTRUSTED;
6476 
6477 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6478 		/* By default any pointer obtained from walking a trusted pointer is no
6479 		 * longer trusted, unless the field being accessed has explicitly been
6480 		 * marked as inheriting its parent's state of trust (either full or RCU).
6481 		 * For example:
6482 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6483 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6484 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6485 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6486 		 *
6487 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6488 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6489 		 */
6490 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6491 			flag |= PTR_TRUSTED;
6492 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6493 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6494 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6495 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6496 				/* ignore __rcu tag and mark it MEM_RCU */
6497 				flag |= MEM_RCU;
6498 			} else if (flag & MEM_RCU ||
6499 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6500 				/* __rcu tagged pointers can be NULL */
6501 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6502 
6503 				/* We always trust them */
6504 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6505 				    flag & PTR_UNTRUSTED)
6506 					flag &= ~PTR_UNTRUSTED;
6507 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6508 				/* keep as-is */
6509 			} else {
6510 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6511 				clear_trusted_flags(&flag);
6512 			}
6513 		} else {
6514 			/*
6515 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6516 			 * aggressively mark as untrusted otherwise such
6517 			 * pointers will be plain PTR_TO_BTF_ID without flags
6518 			 * and will be allowed to be passed into helpers for
6519 			 * compat reasons.
6520 			 */
6521 			flag = PTR_UNTRUSTED;
6522 		}
6523 	} else {
6524 		/* Old compat. Deprecated */
6525 		clear_trusted_flags(&flag);
6526 	}
6527 
6528 	if (atype == BPF_READ && value_regno >= 0)
6529 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6530 
6531 	return 0;
6532 }
6533 
6534 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6535 				   struct bpf_reg_state *regs,
6536 				   int regno, int off, int size,
6537 				   enum bpf_access_type atype,
6538 				   int value_regno)
6539 {
6540 	struct bpf_reg_state *reg = regs + regno;
6541 	struct bpf_map *map = reg->map_ptr;
6542 	struct bpf_reg_state map_reg;
6543 	enum bpf_type_flag flag = 0;
6544 	const struct btf_type *t;
6545 	const char *tname;
6546 	u32 btf_id;
6547 	int ret;
6548 
6549 	if (!btf_vmlinux) {
6550 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6551 		return -ENOTSUPP;
6552 	}
6553 
6554 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6555 		verbose(env, "map_ptr access not supported for map type %d\n",
6556 			map->map_type);
6557 		return -ENOTSUPP;
6558 	}
6559 
6560 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6561 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6562 
6563 	if (!env->allow_ptr_leaks) {
6564 		verbose(env,
6565 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6566 			tname);
6567 		return -EPERM;
6568 	}
6569 
6570 	if (off < 0) {
6571 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6572 			regno, tname, off);
6573 		return -EACCES;
6574 	}
6575 
6576 	if (atype != BPF_READ) {
6577 		verbose(env, "only read from %s is supported\n", tname);
6578 		return -EACCES;
6579 	}
6580 
6581 	/* Simulate access to a PTR_TO_BTF_ID */
6582 	memset(&map_reg, 0, sizeof(map_reg));
6583 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6584 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6585 	if (ret < 0)
6586 		return ret;
6587 
6588 	if (value_regno >= 0)
6589 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6590 
6591 	return 0;
6592 }
6593 
6594 /* Check that the stack access at the given offset is within bounds. The
6595  * maximum valid offset is -1.
6596  *
6597  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6598  * -state->allocated_stack for reads.
6599  */
6600 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6601                                           s64 off,
6602                                           struct bpf_func_state *state,
6603                                           enum bpf_access_type t)
6604 {
6605 	int min_valid_off;
6606 
6607 	if (t == BPF_WRITE || env->allow_uninit_stack)
6608 		min_valid_off = -MAX_BPF_STACK;
6609 	else
6610 		min_valid_off = -state->allocated_stack;
6611 
6612 	if (off < min_valid_off || off > -1)
6613 		return -EACCES;
6614 	return 0;
6615 }
6616 
6617 /* Check that the stack access at 'regno + off' falls within the maximum stack
6618  * bounds.
6619  *
6620  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6621  */
6622 static int check_stack_access_within_bounds(
6623 		struct bpf_verifier_env *env,
6624 		int regno, int off, int access_size,
6625 		enum bpf_access_src src, enum bpf_access_type type)
6626 {
6627 	struct bpf_reg_state *regs = cur_regs(env);
6628 	struct bpf_reg_state *reg = regs + regno;
6629 	struct bpf_func_state *state = func(env, reg);
6630 	s64 min_off, max_off;
6631 	int err;
6632 	char *err_extra;
6633 
6634 	if (src == ACCESS_HELPER)
6635 		/* We don't know if helpers are reading or writing (or both). */
6636 		err_extra = " indirect access to";
6637 	else if (type == BPF_READ)
6638 		err_extra = " read from";
6639 	else
6640 		err_extra = " write to";
6641 
6642 	if (tnum_is_const(reg->var_off)) {
6643 		min_off = (s64)reg->var_off.value + off;
6644 		max_off = min_off + access_size;
6645 	} else {
6646 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6647 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6648 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6649 				err_extra, regno);
6650 			return -EACCES;
6651 		}
6652 		min_off = reg->smin_value + off;
6653 		max_off = reg->smax_value + off + access_size;
6654 	}
6655 
6656 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6657 	if (!err && max_off > 0)
6658 		err = -EINVAL; /* out of stack access into non-negative offsets */
6659 	if (!err && access_size < 0)
6660 		/* access_size should not be negative (or overflow an int); others checks
6661 		 * along the way should have prevented such an access.
6662 		 */
6663 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6664 
6665 	if (err) {
6666 		if (tnum_is_const(reg->var_off)) {
6667 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6668 				err_extra, regno, off, access_size);
6669 		} else {
6670 			char tn_buf[48];
6671 
6672 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6673 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6674 				err_extra, regno, tn_buf, access_size);
6675 		}
6676 		return err;
6677 	}
6678 
6679 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6680 }
6681 
6682 /* check whether memory at (regno + off) is accessible for t = (read | write)
6683  * if t==write, value_regno is a register which value is stored into memory
6684  * if t==read, value_regno is a register which will receive the value from memory
6685  * if t==write && value_regno==-1, some unknown value is stored into memory
6686  * if t==read && value_regno==-1, don't care what we read from memory
6687  */
6688 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6689 			    int off, int bpf_size, enum bpf_access_type t,
6690 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6691 {
6692 	struct bpf_reg_state *regs = cur_regs(env);
6693 	struct bpf_reg_state *reg = regs + regno;
6694 	int size, err = 0;
6695 
6696 	size = bpf_size_to_bytes(bpf_size);
6697 	if (size < 0)
6698 		return size;
6699 
6700 	/* alignment checks will add in reg->off themselves */
6701 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6702 	if (err)
6703 		return err;
6704 
6705 	/* for access checks, reg->off is just part of off */
6706 	off += reg->off;
6707 
6708 	if (reg->type == PTR_TO_MAP_KEY) {
6709 		if (t == BPF_WRITE) {
6710 			verbose(env, "write to change key R%d not allowed\n", regno);
6711 			return -EACCES;
6712 		}
6713 
6714 		err = check_mem_region_access(env, regno, off, size,
6715 					      reg->map_ptr->key_size, false);
6716 		if (err)
6717 			return err;
6718 		if (value_regno >= 0)
6719 			mark_reg_unknown(env, regs, value_regno);
6720 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6721 		struct btf_field *kptr_field = NULL;
6722 
6723 		if (t == BPF_WRITE && value_regno >= 0 &&
6724 		    is_pointer_value(env, value_regno)) {
6725 			verbose(env, "R%d leaks addr into map\n", value_regno);
6726 			return -EACCES;
6727 		}
6728 		err = check_map_access_type(env, regno, off, size, t);
6729 		if (err)
6730 			return err;
6731 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6732 		if (err)
6733 			return err;
6734 		if (tnum_is_const(reg->var_off))
6735 			kptr_field = btf_record_find(reg->map_ptr->record,
6736 						     off + reg->var_off.value, BPF_KPTR);
6737 		if (kptr_field) {
6738 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6739 		} else if (t == BPF_READ && value_regno >= 0) {
6740 			struct bpf_map *map = reg->map_ptr;
6741 
6742 			/* if map is read-only, track its contents as scalars */
6743 			if (tnum_is_const(reg->var_off) &&
6744 			    bpf_map_is_rdonly(map) &&
6745 			    map->ops->map_direct_value_addr) {
6746 				int map_off = off + reg->var_off.value;
6747 				u64 val = 0;
6748 
6749 				err = bpf_map_direct_read(map, map_off, size,
6750 							  &val, is_ldsx);
6751 				if (err)
6752 					return err;
6753 
6754 				regs[value_regno].type = SCALAR_VALUE;
6755 				__mark_reg_known(&regs[value_regno], val);
6756 			} else {
6757 				mark_reg_unknown(env, regs, value_regno);
6758 			}
6759 		}
6760 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6761 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6762 
6763 		if (type_may_be_null(reg->type)) {
6764 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6765 				reg_type_str(env, reg->type));
6766 			return -EACCES;
6767 		}
6768 
6769 		if (t == BPF_WRITE && rdonly_mem) {
6770 			verbose(env, "R%d cannot write into %s\n",
6771 				regno, reg_type_str(env, reg->type));
6772 			return -EACCES;
6773 		}
6774 
6775 		if (t == BPF_WRITE && value_regno >= 0 &&
6776 		    is_pointer_value(env, value_regno)) {
6777 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6778 			return -EACCES;
6779 		}
6780 
6781 		err = check_mem_region_access(env, regno, off, size,
6782 					      reg->mem_size, false);
6783 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6784 			mark_reg_unknown(env, regs, value_regno);
6785 	} else if (reg->type == PTR_TO_CTX) {
6786 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6787 		struct btf *btf = NULL;
6788 		u32 btf_id = 0;
6789 
6790 		if (t == BPF_WRITE && value_regno >= 0 &&
6791 		    is_pointer_value(env, value_regno)) {
6792 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6793 			return -EACCES;
6794 		}
6795 
6796 		err = check_ptr_off_reg(env, reg, regno);
6797 		if (err < 0)
6798 			return err;
6799 
6800 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6801 				       &btf_id);
6802 		if (err)
6803 			verbose_linfo(env, insn_idx, "; ");
6804 		if (!err && t == BPF_READ && value_regno >= 0) {
6805 			/* ctx access returns either a scalar, or a
6806 			 * PTR_TO_PACKET[_META,_END]. In the latter
6807 			 * case, we know the offset is zero.
6808 			 */
6809 			if (reg_type == SCALAR_VALUE) {
6810 				mark_reg_unknown(env, regs, value_regno);
6811 			} else {
6812 				mark_reg_known_zero(env, regs,
6813 						    value_regno);
6814 				if (type_may_be_null(reg_type))
6815 					regs[value_regno].id = ++env->id_gen;
6816 				/* A load of ctx field could have different
6817 				 * actual load size with the one encoded in the
6818 				 * insn. When the dst is PTR, it is for sure not
6819 				 * a sub-register.
6820 				 */
6821 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6822 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6823 					regs[value_regno].btf = btf;
6824 					regs[value_regno].btf_id = btf_id;
6825 				}
6826 			}
6827 			regs[value_regno].type = reg_type;
6828 		}
6829 
6830 	} else if (reg->type == PTR_TO_STACK) {
6831 		/* Basic bounds checks. */
6832 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6833 		if (err)
6834 			return err;
6835 
6836 		if (t == BPF_READ)
6837 			err = check_stack_read(env, regno, off, size,
6838 					       value_regno);
6839 		else
6840 			err = check_stack_write(env, regno, off, size,
6841 						value_regno, insn_idx);
6842 	} else if (reg_is_pkt_pointer(reg)) {
6843 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6844 			verbose(env, "cannot write into packet\n");
6845 			return -EACCES;
6846 		}
6847 		if (t == BPF_WRITE && value_regno >= 0 &&
6848 		    is_pointer_value(env, value_regno)) {
6849 			verbose(env, "R%d leaks addr into packet\n",
6850 				value_regno);
6851 			return -EACCES;
6852 		}
6853 		err = check_packet_access(env, regno, off, size, false);
6854 		if (!err && t == BPF_READ && value_regno >= 0)
6855 			mark_reg_unknown(env, regs, value_regno);
6856 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6857 		if (t == BPF_WRITE && value_regno >= 0 &&
6858 		    is_pointer_value(env, value_regno)) {
6859 			verbose(env, "R%d leaks addr into flow keys\n",
6860 				value_regno);
6861 			return -EACCES;
6862 		}
6863 
6864 		err = check_flow_keys_access(env, off, size);
6865 		if (!err && t == BPF_READ && value_regno >= 0)
6866 			mark_reg_unknown(env, regs, value_regno);
6867 	} else if (type_is_sk_pointer(reg->type)) {
6868 		if (t == BPF_WRITE) {
6869 			verbose(env, "R%d cannot write into %s\n",
6870 				regno, reg_type_str(env, reg->type));
6871 			return -EACCES;
6872 		}
6873 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6874 		if (!err && value_regno >= 0)
6875 			mark_reg_unknown(env, regs, value_regno);
6876 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6877 		err = check_tp_buffer_access(env, reg, regno, off, size);
6878 		if (!err && t == BPF_READ && value_regno >= 0)
6879 			mark_reg_unknown(env, regs, value_regno);
6880 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6881 		   !type_may_be_null(reg->type)) {
6882 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6883 					      value_regno);
6884 	} else if (reg->type == CONST_PTR_TO_MAP) {
6885 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6886 					      value_regno);
6887 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6888 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6889 		u32 *max_access;
6890 
6891 		if (rdonly_mem) {
6892 			if (t == BPF_WRITE) {
6893 				verbose(env, "R%d cannot write into %s\n",
6894 					regno, reg_type_str(env, reg->type));
6895 				return -EACCES;
6896 			}
6897 			max_access = &env->prog->aux->max_rdonly_access;
6898 		} else {
6899 			max_access = &env->prog->aux->max_rdwr_access;
6900 		}
6901 
6902 		err = check_buffer_access(env, reg, regno, off, size, false,
6903 					  max_access);
6904 
6905 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6906 			mark_reg_unknown(env, regs, value_regno);
6907 	} else {
6908 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6909 			reg_type_str(env, reg->type));
6910 		return -EACCES;
6911 	}
6912 
6913 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6914 	    regs[value_regno].type == SCALAR_VALUE) {
6915 		if (!is_ldsx)
6916 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6917 			coerce_reg_to_size(&regs[value_regno], size);
6918 		else
6919 			coerce_reg_to_size_sx(&regs[value_regno], size);
6920 	}
6921 	return err;
6922 }
6923 
6924 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6925 {
6926 	int load_reg;
6927 	int err;
6928 
6929 	switch (insn->imm) {
6930 	case BPF_ADD:
6931 	case BPF_ADD | BPF_FETCH:
6932 	case BPF_AND:
6933 	case BPF_AND | BPF_FETCH:
6934 	case BPF_OR:
6935 	case BPF_OR | BPF_FETCH:
6936 	case BPF_XOR:
6937 	case BPF_XOR | BPF_FETCH:
6938 	case BPF_XCHG:
6939 	case BPF_CMPXCHG:
6940 		break;
6941 	default:
6942 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6943 		return -EINVAL;
6944 	}
6945 
6946 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6947 		verbose(env, "invalid atomic operand size\n");
6948 		return -EINVAL;
6949 	}
6950 
6951 	/* check src1 operand */
6952 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6953 	if (err)
6954 		return err;
6955 
6956 	/* check src2 operand */
6957 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6958 	if (err)
6959 		return err;
6960 
6961 	if (insn->imm == BPF_CMPXCHG) {
6962 		/* Check comparison of R0 with memory location */
6963 		const u32 aux_reg = BPF_REG_0;
6964 
6965 		err = check_reg_arg(env, aux_reg, SRC_OP);
6966 		if (err)
6967 			return err;
6968 
6969 		if (is_pointer_value(env, aux_reg)) {
6970 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6971 			return -EACCES;
6972 		}
6973 	}
6974 
6975 	if (is_pointer_value(env, insn->src_reg)) {
6976 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6977 		return -EACCES;
6978 	}
6979 
6980 	if (is_ctx_reg(env, insn->dst_reg) ||
6981 	    is_pkt_reg(env, insn->dst_reg) ||
6982 	    is_flow_key_reg(env, insn->dst_reg) ||
6983 	    is_sk_reg(env, insn->dst_reg)) {
6984 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6985 			insn->dst_reg,
6986 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6987 		return -EACCES;
6988 	}
6989 
6990 	if (insn->imm & BPF_FETCH) {
6991 		if (insn->imm == BPF_CMPXCHG)
6992 			load_reg = BPF_REG_0;
6993 		else
6994 			load_reg = insn->src_reg;
6995 
6996 		/* check and record load of old value */
6997 		err = check_reg_arg(env, load_reg, DST_OP);
6998 		if (err)
6999 			return err;
7000 	} else {
7001 		/* This instruction accesses a memory location but doesn't
7002 		 * actually load it into a register.
7003 		 */
7004 		load_reg = -1;
7005 	}
7006 
7007 	/* Check whether we can read the memory, with second call for fetch
7008 	 * case to simulate the register fill.
7009 	 */
7010 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7011 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7012 	if (!err && load_reg >= 0)
7013 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7014 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7015 				       true, false);
7016 	if (err)
7017 		return err;
7018 
7019 	/* Check whether we can write into the same memory. */
7020 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7021 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7022 	if (err)
7023 		return err;
7024 
7025 	return 0;
7026 }
7027 
7028 /* When register 'regno' is used to read the stack (either directly or through
7029  * a helper function) make sure that it's within stack boundary and, depending
7030  * on the access type and privileges, that all elements of the stack are
7031  * initialized.
7032  *
7033  * 'off' includes 'regno->off', but not its dynamic part (if any).
7034  *
7035  * All registers that have been spilled on the stack in the slots within the
7036  * read offsets are marked as read.
7037  */
7038 static int check_stack_range_initialized(
7039 		struct bpf_verifier_env *env, int regno, int off,
7040 		int access_size, bool zero_size_allowed,
7041 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7042 {
7043 	struct bpf_reg_state *reg = reg_state(env, regno);
7044 	struct bpf_func_state *state = func(env, reg);
7045 	int err, min_off, max_off, i, j, slot, spi;
7046 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7047 	enum bpf_access_type bounds_check_type;
7048 	/* Some accesses can write anything into the stack, others are
7049 	 * read-only.
7050 	 */
7051 	bool clobber = false;
7052 
7053 	if (access_size == 0 && !zero_size_allowed) {
7054 		verbose(env, "invalid zero-sized read\n");
7055 		return -EACCES;
7056 	}
7057 
7058 	if (type == ACCESS_HELPER) {
7059 		/* The bounds checks for writes are more permissive than for
7060 		 * reads. However, if raw_mode is not set, we'll do extra
7061 		 * checks below.
7062 		 */
7063 		bounds_check_type = BPF_WRITE;
7064 		clobber = true;
7065 	} else {
7066 		bounds_check_type = BPF_READ;
7067 	}
7068 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7069 					       type, bounds_check_type);
7070 	if (err)
7071 		return err;
7072 
7073 
7074 	if (tnum_is_const(reg->var_off)) {
7075 		min_off = max_off = reg->var_off.value + off;
7076 	} else {
7077 		/* Variable offset is prohibited for unprivileged mode for
7078 		 * simplicity since it requires corresponding support in
7079 		 * Spectre masking for stack ALU.
7080 		 * See also retrieve_ptr_limit().
7081 		 */
7082 		if (!env->bypass_spec_v1) {
7083 			char tn_buf[48];
7084 
7085 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7086 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7087 				regno, err_extra, tn_buf);
7088 			return -EACCES;
7089 		}
7090 		/* Only initialized buffer on stack is allowed to be accessed
7091 		 * with variable offset. With uninitialized buffer it's hard to
7092 		 * guarantee that whole memory is marked as initialized on
7093 		 * helper return since specific bounds are unknown what may
7094 		 * cause uninitialized stack leaking.
7095 		 */
7096 		if (meta && meta->raw_mode)
7097 			meta = NULL;
7098 
7099 		min_off = reg->smin_value + off;
7100 		max_off = reg->smax_value + off;
7101 	}
7102 
7103 	if (meta && meta->raw_mode) {
7104 		/* Ensure we won't be overwriting dynptrs when simulating byte
7105 		 * by byte access in check_helper_call using meta.access_size.
7106 		 * This would be a problem if we have a helper in the future
7107 		 * which takes:
7108 		 *
7109 		 *	helper(uninit_mem, len, dynptr)
7110 		 *
7111 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7112 		 * may end up writing to dynptr itself when touching memory from
7113 		 * arg 1. This can be relaxed on a case by case basis for known
7114 		 * safe cases, but reject due to the possibilitiy of aliasing by
7115 		 * default.
7116 		 */
7117 		for (i = min_off; i < max_off + access_size; i++) {
7118 			int stack_off = -i - 1;
7119 
7120 			spi = __get_spi(i);
7121 			/* raw_mode may write past allocated_stack */
7122 			if (state->allocated_stack <= stack_off)
7123 				continue;
7124 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7125 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7126 				return -EACCES;
7127 			}
7128 		}
7129 		meta->access_size = access_size;
7130 		meta->regno = regno;
7131 		return 0;
7132 	}
7133 
7134 	for (i = min_off; i < max_off + access_size; i++) {
7135 		u8 *stype;
7136 
7137 		slot = -i - 1;
7138 		spi = slot / BPF_REG_SIZE;
7139 		if (state->allocated_stack <= slot) {
7140 			verbose(env, "verifier bug: allocated_stack too small");
7141 			return -EFAULT;
7142 		}
7143 
7144 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7145 		if (*stype == STACK_MISC)
7146 			goto mark;
7147 		if ((*stype == STACK_ZERO) ||
7148 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7149 			if (clobber) {
7150 				/* helper can write anything into the stack */
7151 				*stype = STACK_MISC;
7152 			}
7153 			goto mark;
7154 		}
7155 
7156 		if (is_spilled_reg(&state->stack[spi]) &&
7157 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7158 		     env->allow_ptr_leaks)) {
7159 			if (clobber) {
7160 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7161 				for (j = 0; j < BPF_REG_SIZE; j++)
7162 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7163 			}
7164 			goto mark;
7165 		}
7166 
7167 		if (tnum_is_const(reg->var_off)) {
7168 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7169 				err_extra, regno, min_off, i - min_off, access_size);
7170 		} else {
7171 			char tn_buf[48];
7172 
7173 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7174 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7175 				err_extra, regno, tn_buf, i - min_off, access_size);
7176 		}
7177 		return -EACCES;
7178 mark:
7179 		/* reading any byte out of 8-byte 'spill_slot' will cause
7180 		 * the whole slot to be marked as 'read'
7181 		 */
7182 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7183 			      state->stack[spi].spilled_ptr.parent,
7184 			      REG_LIVE_READ64);
7185 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7186 		 * be sure that whether stack slot is written to or not. Hence,
7187 		 * we must still conservatively propagate reads upwards even if
7188 		 * helper may write to the entire memory range.
7189 		 */
7190 	}
7191 	return 0;
7192 }
7193 
7194 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7195 				   int access_size, bool zero_size_allowed,
7196 				   struct bpf_call_arg_meta *meta)
7197 {
7198 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7199 	u32 *max_access;
7200 
7201 	switch (base_type(reg->type)) {
7202 	case PTR_TO_PACKET:
7203 	case PTR_TO_PACKET_META:
7204 		return check_packet_access(env, regno, reg->off, access_size,
7205 					   zero_size_allowed);
7206 	case PTR_TO_MAP_KEY:
7207 		if (meta && meta->raw_mode) {
7208 			verbose(env, "R%d cannot write into %s\n", regno,
7209 				reg_type_str(env, reg->type));
7210 			return -EACCES;
7211 		}
7212 		return check_mem_region_access(env, regno, reg->off, access_size,
7213 					       reg->map_ptr->key_size, false);
7214 	case PTR_TO_MAP_VALUE:
7215 		if (check_map_access_type(env, regno, reg->off, access_size,
7216 					  meta && meta->raw_mode ? BPF_WRITE :
7217 					  BPF_READ))
7218 			return -EACCES;
7219 		return check_map_access(env, regno, reg->off, access_size,
7220 					zero_size_allowed, ACCESS_HELPER);
7221 	case PTR_TO_MEM:
7222 		if (type_is_rdonly_mem(reg->type)) {
7223 			if (meta && meta->raw_mode) {
7224 				verbose(env, "R%d cannot write into %s\n", regno,
7225 					reg_type_str(env, reg->type));
7226 				return -EACCES;
7227 			}
7228 		}
7229 		return check_mem_region_access(env, regno, reg->off,
7230 					       access_size, reg->mem_size,
7231 					       zero_size_allowed);
7232 	case PTR_TO_BUF:
7233 		if (type_is_rdonly_mem(reg->type)) {
7234 			if (meta && meta->raw_mode) {
7235 				verbose(env, "R%d cannot write into %s\n", regno,
7236 					reg_type_str(env, reg->type));
7237 				return -EACCES;
7238 			}
7239 
7240 			max_access = &env->prog->aux->max_rdonly_access;
7241 		} else {
7242 			max_access = &env->prog->aux->max_rdwr_access;
7243 		}
7244 		return check_buffer_access(env, reg, regno, reg->off,
7245 					   access_size, zero_size_allowed,
7246 					   max_access);
7247 	case PTR_TO_STACK:
7248 		return check_stack_range_initialized(
7249 				env,
7250 				regno, reg->off, access_size,
7251 				zero_size_allowed, ACCESS_HELPER, meta);
7252 	case PTR_TO_BTF_ID:
7253 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7254 					       access_size, BPF_READ, -1);
7255 	case PTR_TO_CTX:
7256 		/* in case the function doesn't know how to access the context,
7257 		 * (because we are in a program of type SYSCALL for example), we
7258 		 * can not statically check its size.
7259 		 * Dynamically check it now.
7260 		 */
7261 		if (!env->ops->convert_ctx_access) {
7262 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7263 			int offset = access_size - 1;
7264 
7265 			/* Allow zero-byte read from PTR_TO_CTX */
7266 			if (access_size == 0)
7267 				return zero_size_allowed ? 0 : -EACCES;
7268 
7269 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7270 						atype, -1, false, false);
7271 		}
7272 
7273 		fallthrough;
7274 	default: /* scalar_value or invalid ptr */
7275 		/* Allow zero-byte read from NULL, regardless of pointer type */
7276 		if (zero_size_allowed && access_size == 0 &&
7277 		    register_is_null(reg))
7278 			return 0;
7279 
7280 		verbose(env, "R%d type=%s ", regno,
7281 			reg_type_str(env, reg->type));
7282 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7283 		return -EACCES;
7284 	}
7285 }
7286 
7287 static int check_mem_size_reg(struct bpf_verifier_env *env,
7288 			      struct bpf_reg_state *reg, u32 regno,
7289 			      bool zero_size_allowed,
7290 			      struct bpf_call_arg_meta *meta)
7291 {
7292 	int err;
7293 
7294 	/* This is used to refine r0 return value bounds for helpers
7295 	 * that enforce this value as an upper bound on return values.
7296 	 * See do_refine_retval_range() for helpers that can refine
7297 	 * the return value. C type of helper is u32 so we pull register
7298 	 * bound from umax_value however, if negative verifier errors
7299 	 * out. Only upper bounds can be learned because retval is an
7300 	 * int type and negative retvals are allowed.
7301 	 */
7302 	meta->msize_max_value = reg->umax_value;
7303 
7304 	/* The register is SCALAR_VALUE; the access check
7305 	 * happens using its boundaries.
7306 	 */
7307 	if (!tnum_is_const(reg->var_off))
7308 		/* For unprivileged variable accesses, disable raw
7309 		 * mode so that the program is required to
7310 		 * initialize all the memory that the helper could
7311 		 * just partially fill up.
7312 		 */
7313 		meta = NULL;
7314 
7315 	if (reg->smin_value < 0) {
7316 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7317 			regno);
7318 		return -EACCES;
7319 	}
7320 
7321 	if (reg->umin_value == 0) {
7322 		err = check_helper_mem_access(env, regno - 1, 0,
7323 					      zero_size_allowed,
7324 					      meta);
7325 		if (err)
7326 			return err;
7327 	}
7328 
7329 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7330 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7331 			regno);
7332 		return -EACCES;
7333 	}
7334 	err = check_helper_mem_access(env, regno - 1,
7335 				      reg->umax_value,
7336 				      zero_size_allowed, meta);
7337 	if (!err)
7338 		err = mark_chain_precision(env, regno);
7339 	return err;
7340 }
7341 
7342 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7343 		   u32 regno, u32 mem_size)
7344 {
7345 	bool may_be_null = type_may_be_null(reg->type);
7346 	struct bpf_reg_state saved_reg;
7347 	struct bpf_call_arg_meta meta;
7348 	int err;
7349 
7350 	if (register_is_null(reg))
7351 		return 0;
7352 
7353 	memset(&meta, 0, sizeof(meta));
7354 	/* Assuming that the register contains a value check if the memory
7355 	 * access is safe. Temporarily save and restore the register's state as
7356 	 * the conversion shouldn't be visible to a caller.
7357 	 */
7358 	if (may_be_null) {
7359 		saved_reg = *reg;
7360 		mark_ptr_not_null_reg(reg);
7361 	}
7362 
7363 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7364 	/* Check access for BPF_WRITE */
7365 	meta.raw_mode = true;
7366 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7367 
7368 	if (may_be_null)
7369 		*reg = saved_reg;
7370 
7371 	return err;
7372 }
7373 
7374 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7375 				    u32 regno)
7376 {
7377 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7378 	bool may_be_null = type_may_be_null(mem_reg->type);
7379 	struct bpf_reg_state saved_reg;
7380 	struct bpf_call_arg_meta meta;
7381 	int err;
7382 
7383 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7384 
7385 	memset(&meta, 0, sizeof(meta));
7386 
7387 	if (may_be_null) {
7388 		saved_reg = *mem_reg;
7389 		mark_ptr_not_null_reg(mem_reg);
7390 	}
7391 
7392 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7393 	/* Check access for BPF_WRITE */
7394 	meta.raw_mode = true;
7395 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7396 
7397 	if (may_be_null)
7398 		*mem_reg = saved_reg;
7399 	return err;
7400 }
7401 
7402 /* Implementation details:
7403  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7404  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7405  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7406  * Two separate bpf_obj_new will also have different reg->id.
7407  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7408  * clears reg->id after value_or_null->value transition, since the verifier only
7409  * cares about the range of access to valid map value pointer and doesn't care
7410  * about actual address of the map element.
7411  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7412  * reg->id > 0 after value_or_null->value transition. By doing so
7413  * two bpf_map_lookups will be considered two different pointers that
7414  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7415  * returned from bpf_obj_new.
7416  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7417  * dead-locks.
7418  * Since only one bpf_spin_lock is allowed the checks are simpler than
7419  * reg_is_refcounted() logic. The verifier needs to remember only
7420  * one spin_lock instead of array of acquired_refs.
7421  * cur_state->active_lock remembers which map value element or allocated
7422  * object got locked and clears it after bpf_spin_unlock.
7423  */
7424 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7425 			     bool is_lock)
7426 {
7427 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7428 	struct bpf_verifier_state *cur = env->cur_state;
7429 	bool is_const = tnum_is_const(reg->var_off);
7430 	u64 val = reg->var_off.value;
7431 	struct bpf_map *map = NULL;
7432 	struct btf *btf = NULL;
7433 	struct btf_record *rec;
7434 
7435 	if (!is_const) {
7436 		verbose(env,
7437 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7438 			regno);
7439 		return -EINVAL;
7440 	}
7441 	if (reg->type == PTR_TO_MAP_VALUE) {
7442 		map = reg->map_ptr;
7443 		if (!map->btf) {
7444 			verbose(env,
7445 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7446 				map->name);
7447 			return -EINVAL;
7448 		}
7449 	} else {
7450 		btf = reg->btf;
7451 	}
7452 
7453 	rec = reg_btf_record(reg);
7454 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7455 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7456 			map ? map->name : "kptr");
7457 		return -EINVAL;
7458 	}
7459 	if (rec->spin_lock_off != val + reg->off) {
7460 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7461 			val + reg->off, rec->spin_lock_off);
7462 		return -EINVAL;
7463 	}
7464 	if (is_lock) {
7465 		if (cur->active_lock.ptr) {
7466 			verbose(env,
7467 				"Locking two bpf_spin_locks are not allowed\n");
7468 			return -EINVAL;
7469 		}
7470 		if (map)
7471 			cur->active_lock.ptr = map;
7472 		else
7473 			cur->active_lock.ptr = btf;
7474 		cur->active_lock.id = reg->id;
7475 	} else {
7476 		void *ptr;
7477 
7478 		if (map)
7479 			ptr = map;
7480 		else
7481 			ptr = btf;
7482 
7483 		if (!cur->active_lock.ptr) {
7484 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7485 			return -EINVAL;
7486 		}
7487 		if (cur->active_lock.ptr != ptr ||
7488 		    cur->active_lock.id != reg->id) {
7489 			verbose(env, "bpf_spin_unlock of different lock\n");
7490 			return -EINVAL;
7491 		}
7492 
7493 		invalidate_non_owning_refs(env);
7494 
7495 		cur->active_lock.ptr = NULL;
7496 		cur->active_lock.id = 0;
7497 	}
7498 	return 0;
7499 }
7500 
7501 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7502 			      struct bpf_call_arg_meta *meta)
7503 {
7504 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7505 	bool is_const = tnum_is_const(reg->var_off);
7506 	struct bpf_map *map = reg->map_ptr;
7507 	u64 val = reg->var_off.value;
7508 
7509 	if (!is_const) {
7510 		verbose(env,
7511 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7512 			regno);
7513 		return -EINVAL;
7514 	}
7515 	if (!map->btf) {
7516 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7517 			map->name);
7518 		return -EINVAL;
7519 	}
7520 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7521 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7522 		return -EINVAL;
7523 	}
7524 	if (map->record->timer_off != val + reg->off) {
7525 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7526 			val + reg->off, map->record->timer_off);
7527 		return -EINVAL;
7528 	}
7529 	if (meta->map_ptr) {
7530 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7531 		return -EFAULT;
7532 	}
7533 	meta->map_uid = reg->map_uid;
7534 	meta->map_ptr = map;
7535 	return 0;
7536 }
7537 
7538 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7539 			     struct bpf_call_arg_meta *meta)
7540 {
7541 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7542 	struct bpf_map *map_ptr = reg->map_ptr;
7543 	struct btf_field *kptr_field;
7544 	u32 kptr_off;
7545 
7546 	if (!tnum_is_const(reg->var_off)) {
7547 		verbose(env,
7548 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7549 			regno);
7550 		return -EINVAL;
7551 	}
7552 	if (!map_ptr->btf) {
7553 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7554 			map_ptr->name);
7555 		return -EINVAL;
7556 	}
7557 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7558 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7559 		return -EINVAL;
7560 	}
7561 
7562 	meta->map_ptr = map_ptr;
7563 	kptr_off = reg->off + reg->var_off.value;
7564 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7565 	if (!kptr_field) {
7566 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7567 		return -EACCES;
7568 	}
7569 	if (kptr_field->type != BPF_KPTR_REF) {
7570 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7571 		return -EACCES;
7572 	}
7573 	meta->kptr_field = kptr_field;
7574 	return 0;
7575 }
7576 
7577 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7578  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7579  *
7580  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7581  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7582  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7583  *
7584  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7585  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7586  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7587  * mutate the view of the dynptr and also possibly destroy it. In the latter
7588  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7589  * memory that dynptr points to.
7590  *
7591  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7592  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7593  * readonly dynptr view yet, hence only the first case is tracked and checked.
7594  *
7595  * This is consistent with how C applies the const modifier to a struct object,
7596  * where the pointer itself inside bpf_dynptr becomes const but not what it
7597  * points to.
7598  *
7599  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7600  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7601  */
7602 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7603 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7604 {
7605 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7606 	int err;
7607 
7608 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7609 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7610 	 */
7611 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7612 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7613 		return -EFAULT;
7614 	}
7615 
7616 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7617 	 *		 constructing a mutable bpf_dynptr object.
7618 	 *
7619 	 *		 Currently, this is only possible with PTR_TO_STACK
7620 	 *		 pointing to a region of at least 16 bytes which doesn't
7621 	 *		 contain an existing bpf_dynptr.
7622 	 *
7623 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7624 	 *		 mutated or destroyed. However, the memory it points to
7625 	 *		 may be mutated.
7626 	 *
7627 	 *  None       - Points to a initialized dynptr that can be mutated and
7628 	 *		 destroyed, including mutation of the memory it points
7629 	 *		 to.
7630 	 */
7631 	if (arg_type & MEM_UNINIT) {
7632 		int i;
7633 
7634 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7635 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7636 			return -EINVAL;
7637 		}
7638 
7639 		/* we write BPF_DW bits (8 bytes) at a time */
7640 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7641 			err = check_mem_access(env, insn_idx, regno,
7642 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7643 			if (err)
7644 				return err;
7645 		}
7646 
7647 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7648 	} else /* MEM_RDONLY and None case from above */ {
7649 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7650 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7651 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7652 			return -EINVAL;
7653 		}
7654 
7655 		if (!is_dynptr_reg_valid_init(env, reg)) {
7656 			verbose(env,
7657 				"Expected an initialized dynptr as arg #%d\n",
7658 				regno);
7659 			return -EINVAL;
7660 		}
7661 
7662 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7663 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7664 			verbose(env,
7665 				"Expected a dynptr of type %s as arg #%d\n",
7666 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7667 			return -EINVAL;
7668 		}
7669 
7670 		err = mark_dynptr_read(env, reg);
7671 	}
7672 	return err;
7673 }
7674 
7675 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7676 {
7677 	struct bpf_func_state *state = func(env, reg);
7678 
7679 	return state->stack[spi].spilled_ptr.ref_obj_id;
7680 }
7681 
7682 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7683 {
7684 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7685 }
7686 
7687 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7688 {
7689 	return meta->kfunc_flags & KF_ITER_NEW;
7690 }
7691 
7692 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7693 {
7694 	return meta->kfunc_flags & KF_ITER_NEXT;
7695 }
7696 
7697 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7698 {
7699 	return meta->kfunc_flags & KF_ITER_DESTROY;
7700 }
7701 
7702 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7703 {
7704 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7705 	 * kfunc is iter state pointer
7706 	 */
7707 	return arg == 0 && is_iter_kfunc(meta);
7708 }
7709 
7710 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7711 			    struct bpf_kfunc_call_arg_meta *meta)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7714 	const struct btf_type *t;
7715 	const struct btf_param *arg;
7716 	int spi, err, i, nr_slots;
7717 	u32 btf_id;
7718 
7719 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7720 	arg = &btf_params(meta->func_proto)[0];
7721 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7722 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7723 	nr_slots = t->size / BPF_REG_SIZE;
7724 
7725 	if (is_iter_new_kfunc(meta)) {
7726 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7727 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7728 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7729 				iter_type_str(meta->btf, btf_id), regno);
7730 			return -EINVAL;
7731 		}
7732 
7733 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7734 			err = check_mem_access(env, insn_idx, regno,
7735 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7736 			if (err)
7737 				return err;
7738 		}
7739 
7740 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7741 		if (err)
7742 			return err;
7743 	} else {
7744 		/* iter_next() or iter_destroy() expect initialized iter state*/
7745 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7746 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7747 				iter_type_str(meta->btf, btf_id), regno);
7748 			return -EINVAL;
7749 		}
7750 
7751 		spi = iter_get_spi(env, reg, nr_slots);
7752 		if (spi < 0)
7753 			return spi;
7754 
7755 		err = mark_iter_read(env, reg, spi, nr_slots);
7756 		if (err)
7757 			return err;
7758 
7759 		/* remember meta->iter info for process_iter_next_call() */
7760 		meta->iter.spi = spi;
7761 		meta->iter.frameno = reg->frameno;
7762 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7763 
7764 		if (is_iter_destroy_kfunc(meta)) {
7765 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7766 			if (err)
7767 				return err;
7768 		}
7769 	}
7770 
7771 	return 0;
7772 }
7773 
7774 /* Look for a previous loop entry at insn_idx: nearest parent state
7775  * stopped at insn_idx with callsites matching those in cur->frame.
7776  */
7777 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7778 						  struct bpf_verifier_state *cur,
7779 						  int insn_idx)
7780 {
7781 	struct bpf_verifier_state_list *sl;
7782 	struct bpf_verifier_state *st;
7783 
7784 	/* Explored states are pushed in stack order, most recent states come first */
7785 	sl = *explored_state(env, insn_idx);
7786 	for (; sl; sl = sl->next) {
7787 		/* If st->branches != 0 state is a part of current DFS verification path,
7788 		 * hence cur & st for a loop.
7789 		 */
7790 		st = &sl->state;
7791 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7792 		    st->dfs_depth < cur->dfs_depth)
7793 			return st;
7794 	}
7795 
7796 	return NULL;
7797 }
7798 
7799 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7800 static bool regs_exact(const struct bpf_reg_state *rold,
7801 		       const struct bpf_reg_state *rcur,
7802 		       struct bpf_idmap *idmap);
7803 
7804 static void maybe_widen_reg(struct bpf_verifier_env *env,
7805 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7806 			    struct bpf_idmap *idmap)
7807 {
7808 	if (rold->type != SCALAR_VALUE)
7809 		return;
7810 	if (rold->type != rcur->type)
7811 		return;
7812 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7813 		return;
7814 	__mark_reg_unknown(env, rcur);
7815 }
7816 
7817 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7818 				   struct bpf_verifier_state *old,
7819 				   struct bpf_verifier_state *cur)
7820 {
7821 	struct bpf_func_state *fold, *fcur;
7822 	int i, fr;
7823 
7824 	reset_idmap_scratch(env);
7825 	for (fr = old->curframe; fr >= 0; fr--) {
7826 		fold = old->frame[fr];
7827 		fcur = cur->frame[fr];
7828 
7829 		for (i = 0; i < MAX_BPF_REG; i++)
7830 			maybe_widen_reg(env,
7831 					&fold->regs[i],
7832 					&fcur->regs[i],
7833 					&env->idmap_scratch);
7834 
7835 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7836 			if (!is_spilled_reg(&fold->stack[i]) ||
7837 			    !is_spilled_reg(&fcur->stack[i]))
7838 				continue;
7839 
7840 			maybe_widen_reg(env,
7841 					&fold->stack[i].spilled_ptr,
7842 					&fcur->stack[i].spilled_ptr,
7843 					&env->idmap_scratch);
7844 		}
7845 	}
7846 	return 0;
7847 }
7848 
7849 /* process_iter_next_call() is called when verifier gets to iterator's next
7850  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7851  * to it as just "iter_next()" in comments below.
7852  *
7853  * BPF verifier relies on a crucial contract for any iter_next()
7854  * implementation: it should *eventually* return NULL, and once that happens
7855  * it should keep returning NULL. That is, once iterator exhausts elements to
7856  * iterate, it should never reset or spuriously return new elements.
7857  *
7858  * With the assumption of such contract, process_iter_next_call() simulates
7859  * a fork in the verifier state to validate loop logic correctness and safety
7860  * without having to simulate infinite amount of iterations.
7861  *
7862  * In current state, we first assume that iter_next() returned NULL and
7863  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7864  * conditions we should not form an infinite loop and should eventually reach
7865  * exit.
7866  *
7867  * Besides that, we also fork current state and enqueue it for later
7868  * verification. In a forked state we keep iterator state as ACTIVE
7869  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7870  * also bump iteration depth to prevent erroneous infinite loop detection
7871  * later on (see iter_active_depths_differ() comment for details). In this
7872  * state we assume that we'll eventually loop back to another iter_next()
7873  * calls (it could be in exactly same location or in some other instruction,
7874  * it doesn't matter, we don't make any unnecessary assumptions about this,
7875  * everything revolves around iterator state in a stack slot, not which
7876  * instruction is calling iter_next()). When that happens, we either will come
7877  * to iter_next() with equivalent state and can conclude that next iteration
7878  * will proceed in exactly the same way as we just verified, so it's safe to
7879  * assume that loop converges. If not, we'll go on another iteration
7880  * simulation with a different input state, until all possible starting states
7881  * are validated or we reach maximum number of instructions limit.
7882  *
7883  * This way, we will either exhaustively discover all possible input states
7884  * that iterator loop can start with and eventually will converge, or we'll
7885  * effectively regress into bounded loop simulation logic and either reach
7886  * maximum number of instructions if loop is not provably convergent, or there
7887  * is some statically known limit on number of iterations (e.g., if there is
7888  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7889  *
7890  * Iteration convergence logic in is_state_visited() relies on exact
7891  * states comparison, which ignores read and precision marks.
7892  * This is necessary because read and precision marks are not finalized
7893  * while in the loop. Exact comparison might preclude convergence for
7894  * simple programs like below:
7895  *
7896  *     i = 0;
7897  *     while(iter_next(&it))
7898  *       i++;
7899  *
7900  * At each iteration step i++ would produce a new distinct state and
7901  * eventually instruction processing limit would be reached.
7902  *
7903  * To avoid such behavior speculatively forget (widen) range for
7904  * imprecise scalar registers, if those registers were not precise at the
7905  * end of the previous iteration and do not match exactly.
7906  *
7907  * This is a conservative heuristic that allows to verify wide range of programs,
7908  * however it precludes verification of programs that conjure an
7909  * imprecise value on the first loop iteration and use it as precise on a second.
7910  * For example, the following safe program would fail to verify:
7911  *
7912  *     struct bpf_num_iter it;
7913  *     int arr[10];
7914  *     int i = 0, a = 0;
7915  *     bpf_iter_num_new(&it, 0, 10);
7916  *     while (bpf_iter_num_next(&it)) {
7917  *       if (a == 0) {
7918  *         a = 1;
7919  *         i = 7; // Because i changed verifier would forget
7920  *                // it's range on second loop entry.
7921  *       } else {
7922  *         arr[i] = 42; // This would fail to verify.
7923  *       }
7924  *     }
7925  *     bpf_iter_num_destroy(&it);
7926  */
7927 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7928 				  struct bpf_kfunc_call_arg_meta *meta)
7929 {
7930 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7931 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7932 	struct bpf_reg_state *cur_iter, *queued_iter;
7933 	int iter_frameno = meta->iter.frameno;
7934 	int iter_spi = meta->iter.spi;
7935 
7936 	BTF_TYPE_EMIT(struct bpf_iter);
7937 
7938 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7939 
7940 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7941 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7942 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7943 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7944 		return -EFAULT;
7945 	}
7946 
7947 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7948 		/* Because iter_next() call is a checkpoint is_state_visitied()
7949 		 * should guarantee parent state with same call sites and insn_idx.
7950 		 */
7951 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7952 		    !same_callsites(cur_st->parent, cur_st)) {
7953 			verbose(env, "bug: bad parent state for iter next call");
7954 			return -EFAULT;
7955 		}
7956 		/* Note cur_st->parent in the call below, it is necessary to skip
7957 		 * checkpoint created for cur_st by is_state_visited()
7958 		 * right at this instruction.
7959 		 */
7960 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7961 		/* branch out active iter state */
7962 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7963 		if (!queued_st)
7964 			return -ENOMEM;
7965 
7966 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7967 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7968 		queued_iter->iter.depth++;
7969 		if (prev_st)
7970 			widen_imprecise_scalars(env, prev_st, queued_st);
7971 
7972 		queued_fr = queued_st->frame[queued_st->curframe];
7973 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7974 	}
7975 
7976 	/* switch to DRAINED state, but keep the depth unchanged */
7977 	/* mark current iter state as drained and assume returned NULL */
7978 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7979 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7980 
7981 	return 0;
7982 }
7983 
7984 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7985 {
7986 	return type == ARG_CONST_SIZE ||
7987 	       type == ARG_CONST_SIZE_OR_ZERO;
7988 }
7989 
7990 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7991 {
7992 	return base_type(type) == ARG_PTR_TO_MEM &&
7993 	       type & MEM_UNINIT;
7994 }
7995 
7996 static bool arg_type_is_release(enum bpf_arg_type type)
7997 {
7998 	return type & OBJ_RELEASE;
7999 }
8000 
8001 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8002 {
8003 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8004 }
8005 
8006 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8007 				 const struct bpf_call_arg_meta *meta,
8008 				 enum bpf_arg_type *arg_type)
8009 {
8010 	if (!meta->map_ptr) {
8011 		/* kernel subsystem misconfigured verifier */
8012 		verbose(env, "invalid map_ptr to access map->type\n");
8013 		return -EACCES;
8014 	}
8015 
8016 	switch (meta->map_ptr->map_type) {
8017 	case BPF_MAP_TYPE_SOCKMAP:
8018 	case BPF_MAP_TYPE_SOCKHASH:
8019 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8020 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8021 		} else {
8022 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8023 			return -EINVAL;
8024 		}
8025 		break;
8026 	case BPF_MAP_TYPE_BLOOM_FILTER:
8027 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8028 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8029 		break;
8030 	default:
8031 		break;
8032 	}
8033 	return 0;
8034 }
8035 
8036 struct bpf_reg_types {
8037 	const enum bpf_reg_type types[10];
8038 	u32 *btf_id;
8039 };
8040 
8041 static const struct bpf_reg_types sock_types = {
8042 	.types = {
8043 		PTR_TO_SOCK_COMMON,
8044 		PTR_TO_SOCKET,
8045 		PTR_TO_TCP_SOCK,
8046 		PTR_TO_XDP_SOCK,
8047 	},
8048 };
8049 
8050 #ifdef CONFIG_NET
8051 static const struct bpf_reg_types btf_id_sock_common_types = {
8052 	.types = {
8053 		PTR_TO_SOCK_COMMON,
8054 		PTR_TO_SOCKET,
8055 		PTR_TO_TCP_SOCK,
8056 		PTR_TO_XDP_SOCK,
8057 		PTR_TO_BTF_ID,
8058 		PTR_TO_BTF_ID | PTR_TRUSTED,
8059 	},
8060 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8061 };
8062 #endif
8063 
8064 static const struct bpf_reg_types mem_types = {
8065 	.types = {
8066 		PTR_TO_STACK,
8067 		PTR_TO_PACKET,
8068 		PTR_TO_PACKET_META,
8069 		PTR_TO_MAP_KEY,
8070 		PTR_TO_MAP_VALUE,
8071 		PTR_TO_MEM,
8072 		PTR_TO_MEM | MEM_RINGBUF,
8073 		PTR_TO_BUF,
8074 		PTR_TO_BTF_ID | PTR_TRUSTED,
8075 	},
8076 };
8077 
8078 static const struct bpf_reg_types spin_lock_types = {
8079 	.types = {
8080 		PTR_TO_MAP_VALUE,
8081 		PTR_TO_BTF_ID | MEM_ALLOC,
8082 	}
8083 };
8084 
8085 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8086 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8087 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8088 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8089 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8090 static const struct bpf_reg_types btf_ptr_types = {
8091 	.types = {
8092 		PTR_TO_BTF_ID,
8093 		PTR_TO_BTF_ID | PTR_TRUSTED,
8094 		PTR_TO_BTF_ID | MEM_RCU,
8095 	},
8096 };
8097 static const struct bpf_reg_types percpu_btf_ptr_types = {
8098 	.types = {
8099 		PTR_TO_BTF_ID | MEM_PERCPU,
8100 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8101 	}
8102 };
8103 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8104 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8105 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8106 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8107 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8108 static const struct bpf_reg_types dynptr_types = {
8109 	.types = {
8110 		PTR_TO_STACK,
8111 		CONST_PTR_TO_DYNPTR,
8112 	}
8113 };
8114 
8115 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8116 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8117 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8118 	[ARG_CONST_SIZE]		= &scalar_types,
8119 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8120 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8121 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8122 	[ARG_PTR_TO_CTX]		= &context_types,
8123 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8124 #ifdef CONFIG_NET
8125 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8126 #endif
8127 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8128 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8129 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8130 	[ARG_PTR_TO_MEM]		= &mem_types,
8131 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8132 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8133 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8134 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8135 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8136 	[ARG_PTR_TO_TIMER]		= &timer_types,
8137 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8138 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8139 };
8140 
8141 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8142 			  enum bpf_arg_type arg_type,
8143 			  const u32 *arg_btf_id,
8144 			  struct bpf_call_arg_meta *meta)
8145 {
8146 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8147 	enum bpf_reg_type expected, type = reg->type;
8148 	const struct bpf_reg_types *compatible;
8149 	int i, j;
8150 
8151 	compatible = compatible_reg_types[base_type(arg_type)];
8152 	if (!compatible) {
8153 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8154 		return -EFAULT;
8155 	}
8156 
8157 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8158 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8159 	 *
8160 	 * Same for MAYBE_NULL:
8161 	 *
8162 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8163 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8164 	 *
8165 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8166 	 *
8167 	 * Therefore we fold these flags depending on the arg_type before comparison.
8168 	 */
8169 	if (arg_type & MEM_RDONLY)
8170 		type &= ~MEM_RDONLY;
8171 	if (arg_type & PTR_MAYBE_NULL)
8172 		type &= ~PTR_MAYBE_NULL;
8173 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8174 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8175 
8176 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8177 		type &= ~MEM_ALLOC;
8178 
8179 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8180 		expected = compatible->types[i];
8181 		if (expected == NOT_INIT)
8182 			break;
8183 
8184 		if (type == expected)
8185 			goto found;
8186 	}
8187 
8188 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8189 	for (j = 0; j + 1 < i; j++)
8190 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8191 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8192 	return -EACCES;
8193 
8194 found:
8195 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8196 		return 0;
8197 
8198 	if (compatible == &mem_types) {
8199 		if (!(arg_type & MEM_RDONLY)) {
8200 			verbose(env,
8201 				"%s() may write into memory pointed by R%d type=%s\n",
8202 				func_id_name(meta->func_id),
8203 				regno, reg_type_str(env, reg->type));
8204 			return -EACCES;
8205 		}
8206 		return 0;
8207 	}
8208 
8209 	switch ((int)reg->type) {
8210 	case PTR_TO_BTF_ID:
8211 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8212 	case PTR_TO_BTF_ID | MEM_RCU:
8213 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8214 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8215 	{
8216 		/* For bpf_sk_release, it needs to match against first member
8217 		 * 'struct sock_common', hence make an exception for it. This
8218 		 * allows bpf_sk_release to work for multiple socket types.
8219 		 */
8220 		bool strict_type_match = arg_type_is_release(arg_type) &&
8221 					 meta->func_id != BPF_FUNC_sk_release;
8222 
8223 		if (type_may_be_null(reg->type) &&
8224 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8225 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8226 			return -EACCES;
8227 		}
8228 
8229 		if (!arg_btf_id) {
8230 			if (!compatible->btf_id) {
8231 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8232 				return -EFAULT;
8233 			}
8234 			arg_btf_id = compatible->btf_id;
8235 		}
8236 
8237 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8238 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8239 				return -EACCES;
8240 		} else {
8241 			if (arg_btf_id == BPF_PTR_POISON) {
8242 				verbose(env, "verifier internal error:");
8243 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8244 					regno);
8245 				return -EACCES;
8246 			}
8247 
8248 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8249 						  btf_vmlinux, *arg_btf_id,
8250 						  strict_type_match)) {
8251 				verbose(env, "R%d is of type %s but %s is expected\n",
8252 					regno, btf_type_name(reg->btf, reg->btf_id),
8253 					btf_type_name(btf_vmlinux, *arg_btf_id));
8254 				return -EACCES;
8255 			}
8256 		}
8257 		break;
8258 	}
8259 	case PTR_TO_BTF_ID | MEM_ALLOC:
8260 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8261 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8262 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8263 			return -EFAULT;
8264 		}
8265 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8266 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8267 				return -EACCES;
8268 		}
8269 		break;
8270 	case PTR_TO_BTF_ID | MEM_PERCPU:
8271 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8272 		/* Handled by helper specific checks */
8273 		break;
8274 	default:
8275 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8276 		return -EFAULT;
8277 	}
8278 	return 0;
8279 }
8280 
8281 static struct btf_field *
8282 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8283 {
8284 	struct btf_field *field;
8285 	struct btf_record *rec;
8286 
8287 	rec = reg_btf_record(reg);
8288 	if (!rec)
8289 		return NULL;
8290 
8291 	field = btf_record_find(rec, off, fields);
8292 	if (!field)
8293 		return NULL;
8294 
8295 	return field;
8296 }
8297 
8298 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8299 			   const struct bpf_reg_state *reg, int regno,
8300 			   enum bpf_arg_type arg_type)
8301 {
8302 	u32 type = reg->type;
8303 
8304 	/* When referenced register is passed to release function, its fixed
8305 	 * offset must be 0.
8306 	 *
8307 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8308 	 * meta->release_regno.
8309 	 */
8310 	if (arg_type_is_release(arg_type)) {
8311 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8312 		 * may not directly point to the object being released, but to
8313 		 * dynptr pointing to such object, which might be at some offset
8314 		 * on the stack. In that case, we simply to fallback to the
8315 		 * default handling.
8316 		 */
8317 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8318 			return 0;
8319 
8320 		/* Doing check_ptr_off_reg check for the offset will catch this
8321 		 * because fixed_off_ok is false, but checking here allows us
8322 		 * to give the user a better error message.
8323 		 */
8324 		if (reg->off) {
8325 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8326 				regno);
8327 			return -EINVAL;
8328 		}
8329 		return __check_ptr_off_reg(env, reg, regno, false);
8330 	}
8331 
8332 	switch (type) {
8333 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8334 	case PTR_TO_STACK:
8335 	case PTR_TO_PACKET:
8336 	case PTR_TO_PACKET_META:
8337 	case PTR_TO_MAP_KEY:
8338 	case PTR_TO_MAP_VALUE:
8339 	case PTR_TO_MEM:
8340 	case PTR_TO_MEM | MEM_RDONLY:
8341 	case PTR_TO_MEM | MEM_RINGBUF:
8342 	case PTR_TO_BUF:
8343 	case PTR_TO_BUF | MEM_RDONLY:
8344 	case SCALAR_VALUE:
8345 		return 0;
8346 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8347 	 * fixed offset.
8348 	 */
8349 	case PTR_TO_BTF_ID:
8350 	case PTR_TO_BTF_ID | MEM_ALLOC:
8351 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8352 	case PTR_TO_BTF_ID | MEM_RCU:
8353 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8354 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8355 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8356 		 * its fixed offset must be 0. In the other cases, fixed offset
8357 		 * can be non-zero. This was already checked above. So pass
8358 		 * fixed_off_ok as true to allow fixed offset for all other
8359 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8360 		 * still need to do checks instead of returning.
8361 		 */
8362 		return __check_ptr_off_reg(env, reg, regno, true);
8363 	default:
8364 		return __check_ptr_off_reg(env, reg, regno, false);
8365 	}
8366 }
8367 
8368 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8369 						const struct bpf_func_proto *fn,
8370 						struct bpf_reg_state *regs)
8371 {
8372 	struct bpf_reg_state *state = NULL;
8373 	int i;
8374 
8375 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8376 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8377 			if (state) {
8378 				verbose(env, "verifier internal error: multiple dynptr args\n");
8379 				return NULL;
8380 			}
8381 			state = &regs[BPF_REG_1 + i];
8382 		}
8383 
8384 	if (!state)
8385 		verbose(env, "verifier internal error: no dynptr arg found\n");
8386 
8387 	return state;
8388 }
8389 
8390 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8391 {
8392 	struct bpf_func_state *state = func(env, reg);
8393 	int spi;
8394 
8395 	if (reg->type == CONST_PTR_TO_DYNPTR)
8396 		return reg->id;
8397 	spi = dynptr_get_spi(env, reg);
8398 	if (spi < 0)
8399 		return spi;
8400 	return state->stack[spi].spilled_ptr.id;
8401 }
8402 
8403 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8404 {
8405 	struct bpf_func_state *state = func(env, reg);
8406 	int spi;
8407 
8408 	if (reg->type == CONST_PTR_TO_DYNPTR)
8409 		return reg->ref_obj_id;
8410 	spi = dynptr_get_spi(env, reg);
8411 	if (spi < 0)
8412 		return spi;
8413 	return state->stack[spi].spilled_ptr.ref_obj_id;
8414 }
8415 
8416 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8417 					    struct bpf_reg_state *reg)
8418 {
8419 	struct bpf_func_state *state = func(env, reg);
8420 	int spi;
8421 
8422 	if (reg->type == CONST_PTR_TO_DYNPTR)
8423 		return reg->dynptr.type;
8424 
8425 	spi = __get_spi(reg->off);
8426 	if (spi < 0) {
8427 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8428 		return BPF_DYNPTR_TYPE_INVALID;
8429 	}
8430 
8431 	return state->stack[spi].spilled_ptr.dynptr.type;
8432 }
8433 
8434 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8435 			  struct bpf_call_arg_meta *meta,
8436 			  const struct bpf_func_proto *fn,
8437 			  int insn_idx)
8438 {
8439 	u32 regno = BPF_REG_1 + arg;
8440 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8441 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8442 	enum bpf_reg_type type = reg->type;
8443 	u32 *arg_btf_id = NULL;
8444 	int err = 0;
8445 
8446 	if (arg_type == ARG_DONTCARE)
8447 		return 0;
8448 
8449 	err = check_reg_arg(env, regno, SRC_OP);
8450 	if (err)
8451 		return err;
8452 
8453 	if (arg_type == ARG_ANYTHING) {
8454 		if (is_pointer_value(env, regno)) {
8455 			verbose(env, "R%d leaks addr into helper function\n",
8456 				regno);
8457 			return -EACCES;
8458 		}
8459 		return 0;
8460 	}
8461 
8462 	if (type_is_pkt_pointer(type) &&
8463 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8464 		verbose(env, "helper access to the packet is not allowed\n");
8465 		return -EACCES;
8466 	}
8467 
8468 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8469 		err = resolve_map_arg_type(env, meta, &arg_type);
8470 		if (err)
8471 			return err;
8472 	}
8473 
8474 	if (register_is_null(reg) && type_may_be_null(arg_type))
8475 		/* A NULL register has a SCALAR_VALUE type, so skip
8476 		 * type checking.
8477 		 */
8478 		goto skip_type_check;
8479 
8480 	/* arg_btf_id and arg_size are in a union. */
8481 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8482 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8483 		arg_btf_id = fn->arg_btf_id[arg];
8484 
8485 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8486 	if (err)
8487 		return err;
8488 
8489 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8490 	if (err)
8491 		return err;
8492 
8493 skip_type_check:
8494 	if (arg_type_is_release(arg_type)) {
8495 		if (arg_type_is_dynptr(arg_type)) {
8496 			struct bpf_func_state *state = func(env, reg);
8497 			int spi;
8498 
8499 			/* Only dynptr created on stack can be released, thus
8500 			 * the get_spi and stack state checks for spilled_ptr
8501 			 * should only be done before process_dynptr_func for
8502 			 * PTR_TO_STACK.
8503 			 */
8504 			if (reg->type == PTR_TO_STACK) {
8505 				spi = dynptr_get_spi(env, reg);
8506 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8507 					verbose(env, "arg %d is an unacquired reference\n", regno);
8508 					return -EINVAL;
8509 				}
8510 			} else {
8511 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8512 				return -EINVAL;
8513 			}
8514 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8515 			verbose(env, "R%d must be referenced when passed to release function\n",
8516 				regno);
8517 			return -EINVAL;
8518 		}
8519 		if (meta->release_regno) {
8520 			verbose(env, "verifier internal error: more than one release argument\n");
8521 			return -EFAULT;
8522 		}
8523 		meta->release_regno = regno;
8524 	}
8525 
8526 	if (reg->ref_obj_id) {
8527 		if (meta->ref_obj_id) {
8528 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8529 				regno, reg->ref_obj_id,
8530 				meta->ref_obj_id);
8531 			return -EFAULT;
8532 		}
8533 		meta->ref_obj_id = reg->ref_obj_id;
8534 	}
8535 
8536 	switch (base_type(arg_type)) {
8537 	case ARG_CONST_MAP_PTR:
8538 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8539 		if (meta->map_ptr) {
8540 			/* Use map_uid (which is unique id of inner map) to reject:
8541 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8542 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8543 			 * if (inner_map1 && inner_map2) {
8544 			 *     timer = bpf_map_lookup_elem(inner_map1);
8545 			 *     if (timer)
8546 			 *         // mismatch would have been allowed
8547 			 *         bpf_timer_init(timer, inner_map2);
8548 			 * }
8549 			 *
8550 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8551 			 */
8552 			if (meta->map_ptr != reg->map_ptr ||
8553 			    meta->map_uid != reg->map_uid) {
8554 				verbose(env,
8555 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8556 					meta->map_uid, reg->map_uid);
8557 				return -EINVAL;
8558 			}
8559 		}
8560 		meta->map_ptr = reg->map_ptr;
8561 		meta->map_uid = reg->map_uid;
8562 		break;
8563 	case ARG_PTR_TO_MAP_KEY:
8564 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8565 		 * check that [key, key + map->key_size) are within
8566 		 * stack limits and initialized
8567 		 */
8568 		if (!meta->map_ptr) {
8569 			/* in function declaration map_ptr must come before
8570 			 * map_key, so that it's verified and known before
8571 			 * we have to check map_key here. Otherwise it means
8572 			 * that kernel subsystem misconfigured verifier
8573 			 */
8574 			verbose(env, "invalid map_ptr to access map->key\n");
8575 			return -EACCES;
8576 		}
8577 		err = check_helper_mem_access(env, regno,
8578 					      meta->map_ptr->key_size, false,
8579 					      NULL);
8580 		break;
8581 	case ARG_PTR_TO_MAP_VALUE:
8582 		if (type_may_be_null(arg_type) && register_is_null(reg))
8583 			return 0;
8584 
8585 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8586 		 * check [value, value + map->value_size) validity
8587 		 */
8588 		if (!meta->map_ptr) {
8589 			/* kernel subsystem misconfigured verifier */
8590 			verbose(env, "invalid map_ptr to access map->value\n");
8591 			return -EACCES;
8592 		}
8593 		meta->raw_mode = arg_type & MEM_UNINIT;
8594 		err = check_helper_mem_access(env, regno,
8595 					      meta->map_ptr->value_size, false,
8596 					      meta);
8597 		break;
8598 	case ARG_PTR_TO_PERCPU_BTF_ID:
8599 		if (!reg->btf_id) {
8600 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8601 			return -EACCES;
8602 		}
8603 		meta->ret_btf = reg->btf;
8604 		meta->ret_btf_id = reg->btf_id;
8605 		break;
8606 	case ARG_PTR_TO_SPIN_LOCK:
8607 		if (in_rbtree_lock_required_cb(env)) {
8608 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8609 			return -EACCES;
8610 		}
8611 		if (meta->func_id == BPF_FUNC_spin_lock) {
8612 			err = process_spin_lock(env, regno, true);
8613 			if (err)
8614 				return err;
8615 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8616 			err = process_spin_lock(env, regno, false);
8617 			if (err)
8618 				return err;
8619 		} else {
8620 			verbose(env, "verifier internal error\n");
8621 			return -EFAULT;
8622 		}
8623 		break;
8624 	case ARG_PTR_TO_TIMER:
8625 		err = process_timer_func(env, regno, meta);
8626 		if (err)
8627 			return err;
8628 		break;
8629 	case ARG_PTR_TO_FUNC:
8630 		meta->subprogno = reg->subprogno;
8631 		break;
8632 	case ARG_PTR_TO_MEM:
8633 		/* The access to this pointer is only checked when we hit the
8634 		 * next is_mem_size argument below.
8635 		 */
8636 		meta->raw_mode = arg_type & MEM_UNINIT;
8637 		if (arg_type & MEM_FIXED_SIZE) {
8638 			err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
8639 			if (err)
8640 				return err;
8641 			if (arg_type & MEM_ALIGNED)
8642 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8643 		}
8644 		break;
8645 	case ARG_CONST_SIZE:
8646 		err = check_mem_size_reg(env, reg, regno, false, meta);
8647 		break;
8648 	case ARG_CONST_SIZE_OR_ZERO:
8649 		err = check_mem_size_reg(env, reg, regno, true, meta);
8650 		break;
8651 	case ARG_PTR_TO_DYNPTR:
8652 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8653 		if (err)
8654 			return err;
8655 		break;
8656 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8657 		if (!tnum_is_const(reg->var_off)) {
8658 			verbose(env, "R%d is not a known constant'\n",
8659 				regno);
8660 			return -EACCES;
8661 		}
8662 		meta->mem_size = reg->var_off.value;
8663 		err = mark_chain_precision(env, regno);
8664 		if (err)
8665 			return err;
8666 		break;
8667 	case ARG_PTR_TO_CONST_STR:
8668 	{
8669 		struct bpf_map *map = reg->map_ptr;
8670 		int map_off;
8671 		u64 map_addr;
8672 		char *str_ptr;
8673 
8674 		if (!bpf_map_is_rdonly(map)) {
8675 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8676 			return -EACCES;
8677 		}
8678 
8679 		if (!tnum_is_const(reg->var_off)) {
8680 			verbose(env, "R%d is not a constant address'\n", regno);
8681 			return -EACCES;
8682 		}
8683 
8684 		if (!map->ops->map_direct_value_addr) {
8685 			verbose(env, "no direct value access support for this map type\n");
8686 			return -EACCES;
8687 		}
8688 
8689 		err = check_map_access(env, regno, reg->off,
8690 				       map->value_size - reg->off, false,
8691 				       ACCESS_HELPER);
8692 		if (err)
8693 			return err;
8694 
8695 		map_off = reg->off + reg->var_off.value;
8696 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8697 		if (err) {
8698 			verbose(env, "direct value access on string failed\n");
8699 			return err;
8700 		}
8701 
8702 		str_ptr = (char *)(long)(map_addr);
8703 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8704 			verbose(env, "string is not zero-terminated\n");
8705 			return -EINVAL;
8706 		}
8707 		break;
8708 	}
8709 	case ARG_PTR_TO_KPTR:
8710 		err = process_kptr_func(env, regno, meta);
8711 		if (err)
8712 			return err;
8713 		break;
8714 	}
8715 
8716 	return err;
8717 }
8718 
8719 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8720 {
8721 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8722 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8723 
8724 	if (func_id != BPF_FUNC_map_update_elem &&
8725 	    func_id != BPF_FUNC_map_delete_elem)
8726 		return false;
8727 
8728 	/* It's not possible to get access to a locked struct sock in these
8729 	 * contexts, so updating is safe.
8730 	 */
8731 	switch (type) {
8732 	case BPF_PROG_TYPE_TRACING:
8733 		if (eatype == BPF_TRACE_ITER)
8734 			return true;
8735 		break;
8736 	case BPF_PROG_TYPE_SOCK_OPS:
8737 		/* map_update allowed only via dedicated helpers with event type checks */
8738 		if (func_id == BPF_FUNC_map_delete_elem)
8739 			return true;
8740 		break;
8741 	case BPF_PROG_TYPE_SOCKET_FILTER:
8742 	case BPF_PROG_TYPE_SCHED_CLS:
8743 	case BPF_PROG_TYPE_SCHED_ACT:
8744 	case BPF_PROG_TYPE_XDP:
8745 	case BPF_PROG_TYPE_SK_REUSEPORT:
8746 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8747 	case BPF_PROG_TYPE_SK_LOOKUP:
8748 		return true;
8749 	default:
8750 		break;
8751 	}
8752 
8753 	verbose(env, "cannot update sockmap in this context\n");
8754 	return false;
8755 }
8756 
8757 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8758 {
8759 	return env->prog->jit_requested &&
8760 	       bpf_jit_supports_subprog_tailcalls();
8761 }
8762 
8763 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8764 					struct bpf_map *map, int func_id)
8765 {
8766 	if (!map)
8767 		return 0;
8768 
8769 	/* We need a two way check, first is from map perspective ... */
8770 	switch (map->map_type) {
8771 	case BPF_MAP_TYPE_PROG_ARRAY:
8772 		if (func_id != BPF_FUNC_tail_call)
8773 			goto error;
8774 		break;
8775 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8776 		if (func_id != BPF_FUNC_perf_event_read &&
8777 		    func_id != BPF_FUNC_perf_event_output &&
8778 		    func_id != BPF_FUNC_skb_output &&
8779 		    func_id != BPF_FUNC_perf_event_read_value &&
8780 		    func_id != BPF_FUNC_xdp_output)
8781 			goto error;
8782 		break;
8783 	case BPF_MAP_TYPE_RINGBUF:
8784 		if (func_id != BPF_FUNC_ringbuf_output &&
8785 		    func_id != BPF_FUNC_ringbuf_reserve &&
8786 		    func_id != BPF_FUNC_ringbuf_query &&
8787 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8788 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8789 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8790 			goto error;
8791 		break;
8792 	case BPF_MAP_TYPE_USER_RINGBUF:
8793 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8794 			goto error;
8795 		break;
8796 	case BPF_MAP_TYPE_STACK_TRACE:
8797 		if (func_id != BPF_FUNC_get_stackid)
8798 			goto error;
8799 		break;
8800 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8801 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8802 		    func_id != BPF_FUNC_current_task_under_cgroup)
8803 			goto error;
8804 		break;
8805 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8806 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8807 		if (func_id != BPF_FUNC_get_local_storage)
8808 			goto error;
8809 		break;
8810 	case BPF_MAP_TYPE_DEVMAP:
8811 	case BPF_MAP_TYPE_DEVMAP_HASH:
8812 		if (func_id != BPF_FUNC_redirect_map &&
8813 		    func_id != BPF_FUNC_map_lookup_elem)
8814 			goto error;
8815 		break;
8816 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8817 	 * appear.
8818 	 */
8819 	case BPF_MAP_TYPE_CPUMAP:
8820 		if (func_id != BPF_FUNC_redirect_map)
8821 			goto error;
8822 		break;
8823 	case BPF_MAP_TYPE_XSKMAP:
8824 		if (func_id != BPF_FUNC_redirect_map &&
8825 		    func_id != BPF_FUNC_map_lookup_elem)
8826 			goto error;
8827 		break;
8828 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8829 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8830 		if (func_id != BPF_FUNC_map_lookup_elem)
8831 			goto error;
8832 		break;
8833 	case BPF_MAP_TYPE_SOCKMAP:
8834 		if (func_id != BPF_FUNC_sk_redirect_map &&
8835 		    func_id != BPF_FUNC_sock_map_update &&
8836 		    func_id != BPF_FUNC_msg_redirect_map &&
8837 		    func_id != BPF_FUNC_sk_select_reuseport &&
8838 		    func_id != BPF_FUNC_map_lookup_elem &&
8839 		    !may_update_sockmap(env, func_id))
8840 			goto error;
8841 		break;
8842 	case BPF_MAP_TYPE_SOCKHASH:
8843 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8844 		    func_id != BPF_FUNC_sock_hash_update &&
8845 		    func_id != BPF_FUNC_msg_redirect_hash &&
8846 		    func_id != BPF_FUNC_sk_select_reuseport &&
8847 		    func_id != BPF_FUNC_map_lookup_elem &&
8848 		    !may_update_sockmap(env, func_id))
8849 			goto error;
8850 		break;
8851 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8852 		if (func_id != BPF_FUNC_sk_select_reuseport)
8853 			goto error;
8854 		break;
8855 	case BPF_MAP_TYPE_QUEUE:
8856 	case BPF_MAP_TYPE_STACK:
8857 		if (func_id != BPF_FUNC_map_peek_elem &&
8858 		    func_id != BPF_FUNC_map_pop_elem &&
8859 		    func_id != BPF_FUNC_map_push_elem)
8860 			goto error;
8861 		break;
8862 	case BPF_MAP_TYPE_SK_STORAGE:
8863 		if (func_id != BPF_FUNC_sk_storage_get &&
8864 		    func_id != BPF_FUNC_sk_storage_delete &&
8865 		    func_id != BPF_FUNC_kptr_xchg)
8866 			goto error;
8867 		break;
8868 	case BPF_MAP_TYPE_INODE_STORAGE:
8869 		if (func_id != BPF_FUNC_inode_storage_get &&
8870 		    func_id != BPF_FUNC_inode_storage_delete &&
8871 		    func_id != BPF_FUNC_kptr_xchg)
8872 			goto error;
8873 		break;
8874 	case BPF_MAP_TYPE_TASK_STORAGE:
8875 		if (func_id != BPF_FUNC_task_storage_get &&
8876 		    func_id != BPF_FUNC_task_storage_delete &&
8877 		    func_id != BPF_FUNC_kptr_xchg)
8878 			goto error;
8879 		break;
8880 	case BPF_MAP_TYPE_CGRP_STORAGE:
8881 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8882 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8883 		    func_id != BPF_FUNC_kptr_xchg)
8884 			goto error;
8885 		break;
8886 	case BPF_MAP_TYPE_BLOOM_FILTER:
8887 		if (func_id != BPF_FUNC_map_peek_elem &&
8888 		    func_id != BPF_FUNC_map_push_elem)
8889 			goto error;
8890 		break;
8891 	default:
8892 		break;
8893 	}
8894 
8895 	/* ... and second from the function itself. */
8896 	switch (func_id) {
8897 	case BPF_FUNC_tail_call:
8898 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8899 			goto error;
8900 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8901 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8902 			return -EINVAL;
8903 		}
8904 		break;
8905 	case BPF_FUNC_perf_event_read:
8906 	case BPF_FUNC_perf_event_output:
8907 	case BPF_FUNC_perf_event_read_value:
8908 	case BPF_FUNC_skb_output:
8909 	case BPF_FUNC_xdp_output:
8910 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8911 			goto error;
8912 		break;
8913 	case BPF_FUNC_ringbuf_output:
8914 	case BPF_FUNC_ringbuf_reserve:
8915 	case BPF_FUNC_ringbuf_query:
8916 	case BPF_FUNC_ringbuf_reserve_dynptr:
8917 	case BPF_FUNC_ringbuf_submit_dynptr:
8918 	case BPF_FUNC_ringbuf_discard_dynptr:
8919 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8920 			goto error;
8921 		break;
8922 	case BPF_FUNC_user_ringbuf_drain:
8923 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8924 			goto error;
8925 		break;
8926 	case BPF_FUNC_get_stackid:
8927 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8928 			goto error;
8929 		break;
8930 	case BPF_FUNC_current_task_under_cgroup:
8931 	case BPF_FUNC_skb_under_cgroup:
8932 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8933 			goto error;
8934 		break;
8935 	case BPF_FUNC_redirect_map:
8936 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8937 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8938 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8939 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8940 			goto error;
8941 		break;
8942 	case BPF_FUNC_sk_redirect_map:
8943 	case BPF_FUNC_msg_redirect_map:
8944 	case BPF_FUNC_sock_map_update:
8945 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8946 			goto error;
8947 		break;
8948 	case BPF_FUNC_sk_redirect_hash:
8949 	case BPF_FUNC_msg_redirect_hash:
8950 	case BPF_FUNC_sock_hash_update:
8951 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8952 			goto error;
8953 		break;
8954 	case BPF_FUNC_get_local_storage:
8955 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8956 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8957 			goto error;
8958 		break;
8959 	case BPF_FUNC_sk_select_reuseport:
8960 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8961 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8962 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8963 			goto error;
8964 		break;
8965 	case BPF_FUNC_map_pop_elem:
8966 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8967 		    map->map_type != BPF_MAP_TYPE_STACK)
8968 			goto error;
8969 		break;
8970 	case BPF_FUNC_map_peek_elem:
8971 	case BPF_FUNC_map_push_elem:
8972 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8973 		    map->map_type != BPF_MAP_TYPE_STACK &&
8974 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8975 			goto error;
8976 		break;
8977 	case BPF_FUNC_map_lookup_percpu_elem:
8978 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8979 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8980 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8981 			goto error;
8982 		break;
8983 	case BPF_FUNC_sk_storage_get:
8984 	case BPF_FUNC_sk_storage_delete:
8985 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8986 			goto error;
8987 		break;
8988 	case BPF_FUNC_inode_storage_get:
8989 	case BPF_FUNC_inode_storage_delete:
8990 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8991 			goto error;
8992 		break;
8993 	case BPF_FUNC_task_storage_get:
8994 	case BPF_FUNC_task_storage_delete:
8995 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8996 			goto error;
8997 		break;
8998 	case BPF_FUNC_cgrp_storage_get:
8999 	case BPF_FUNC_cgrp_storage_delete:
9000 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9001 			goto error;
9002 		break;
9003 	default:
9004 		break;
9005 	}
9006 
9007 	return 0;
9008 error:
9009 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9010 		map->map_type, func_id_name(func_id), func_id);
9011 	return -EINVAL;
9012 }
9013 
9014 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9015 {
9016 	int count = 0;
9017 
9018 	if (arg_type_is_raw_mem(fn->arg1_type))
9019 		count++;
9020 	if (arg_type_is_raw_mem(fn->arg2_type))
9021 		count++;
9022 	if (arg_type_is_raw_mem(fn->arg3_type))
9023 		count++;
9024 	if (arg_type_is_raw_mem(fn->arg4_type))
9025 		count++;
9026 	if (arg_type_is_raw_mem(fn->arg5_type))
9027 		count++;
9028 
9029 	/* We only support one arg being in raw mode at the moment,
9030 	 * which is sufficient for the helper functions we have
9031 	 * right now.
9032 	 */
9033 	return count <= 1;
9034 }
9035 
9036 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9037 {
9038 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9039 	bool has_size = fn->arg_size[arg] != 0;
9040 	bool is_next_size = false;
9041 
9042 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9043 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9044 
9045 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9046 		return is_next_size;
9047 
9048 	return has_size == is_next_size || is_next_size == is_fixed;
9049 }
9050 
9051 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9052 {
9053 	/* bpf_xxx(..., buf, len) call will access 'len'
9054 	 * bytes from memory 'buf'. Both arg types need
9055 	 * to be paired, so make sure there's no buggy
9056 	 * helper function specification.
9057 	 */
9058 	if (arg_type_is_mem_size(fn->arg1_type) ||
9059 	    check_args_pair_invalid(fn, 0) ||
9060 	    check_args_pair_invalid(fn, 1) ||
9061 	    check_args_pair_invalid(fn, 2) ||
9062 	    check_args_pair_invalid(fn, 3) ||
9063 	    check_args_pair_invalid(fn, 4))
9064 		return false;
9065 
9066 	return true;
9067 }
9068 
9069 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9070 {
9071 	int i;
9072 
9073 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9074 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9075 			return !!fn->arg_btf_id[i];
9076 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9077 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9078 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9079 		    /* arg_btf_id and arg_size are in a union. */
9080 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9081 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9082 			return false;
9083 	}
9084 
9085 	return true;
9086 }
9087 
9088 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9089 {
9090 	return check_raw_mode_ok(fn) &&
9091 	       check_arg_pair_ok(fn) &&
9092 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9093 }
9094 
9095 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9096  * are now invalid, so turn them into unknown SCALAR_VALUE.
9097  *
9098  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9099  * since these slices point to packet data.
9100  */
9101 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9102 {
9103 	struct bpf_func_state *state;
9104 	struct bpf_reg_state *reg;
9105 
9106 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9107 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9108 			mark_reg_invalid(env, reg);
9109 	}));
9110 }
9111 
9112 enum {
9113 	AT_PKT_END = -1,
9114 	BEYOND_PKT_END = -2,
9115 };
9116 
9117 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9118 {
9119 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9120 	struct bpf_reg_state *reg = &state->regs[regn];
9121 
9122 	if (reg->type != PTR_TO_PACKET)
9123 		/* PTR_TO_PACKET_META is not supported yet */
9124 		return;
9125 
9126 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9127 	 * How far beyond pkt_end it goes is unknown.
9128 	 * if (!range_open) it's the case of pkt >= pkt_end
9129 	 * if (range_open) it's the case of pkt > pkt_end
9130 	 * hence this pointer is at least 1 byte bigger than pkt_end
9131 	 */
9132 	if (range_open)
9133 		reg->range = BEYOND_PKT_END;
9134 	else
9135 		reg->range = AT_PKT_END;
9136 }
9137 
9138 /* The pointer with the specified id has released its reference to kernel
9139  * resources. Identify all copies of the same pointer and clear the reference.
9140  */
9141 static int release_reference(struct bpf_verifier_env *env,
9142 			     int ref_obj_id)
9143 {
9144 	struct bpf_func_state *state;
9145 	struct bpf_reg_state *reg;
9146 	int err;
9147 
9148 	err = release_reference_state(cur_func(env), ref_obj_id);
9149 	if (err)
9150 		return err;
9151 
9152 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9153 		if (reg->ref_obj_id == ref_obj_id)
9154 			mark_reg_invalid(env, reg);
9155 	}));
9156 
9157 	return 0;
9158 }
9159 
9160 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9161 {
9162 	struct bpf_func_state *unused;
9163 	struct bpf_reg_state *reg;
9164 
9165 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9166 		if (type_is_non_owning_ref(reg->type))
9167 			mark_reg_invalid(env, reg);
9168 	}));
9169 }
9170 
9171 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9172 				    struct bpf_reg_state *regs)
9173 {
9174 	int i;
9175 
9176 	/* after the call registers r0 - r5 were scratched */
9177 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9178 		mark_reg_not_init(env, regs, caller_saved[i]);
9179 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9180 	}
9181 }
9182 
9183 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9184 				   struct bpf_func_state *caller,
9185 				   struct bpf_func_state *callee,
9186 				   int insn_idx);
9187 
9188 static int set_callee_state(struct bpf_verifier_env *env,
9189 			    struct bpf_func_state *caller,
9190 			    struct bpf_func_state *callee, int insn_idx);
9191 
9192 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9193 			    set_callee_state_fn set_callee_state_cb,
9194 			    struct bpf_verifier_state *state)
9195 {
9196 	struct bpf_func_state *caller, *callee;
9197 	int err;
9198 
9199 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9200 		verbose(env, "the call stack of %d frames is too deep\n",
9201 			state->curframe + 2);
9202 		return -E2BIG;
9203 	}
9204 
9205 	if (state->frame[state->curframe + 1]) {
9206 		verbose(env, "verifier bug. Frame %d already allocated\n",
9207 			state->curframe + 1);
9208 		return -EFAULT;
9209 	}
9210 
9211 	caller = state->frame[state->curframe];
9212 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9213 	if (!callee)
9214 		return -ENOMEM;
9215 	state->frame[state->curframe + 1] = callee;
9216 
9217 	/* callee cannot access r0, r6 - r9 for reading and has to write
9218 	 * into its own stack before reading from it.
9219 	 * callee can read/write into caller's stack
9220 	 */
9221 	init_func_state(env, callee,
9222 			/* remember the callsite, it will be used by bpf_exit */
9223 			callsite,
9224 			state->curframe + 1 /* frameno within this callchain */,
9225 			subprog /* subprog number within this prog */);
9226 	/* Transfer references to the callee */
9227 	err = copy_reference_state(callee, caller);
9228 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9229 	if (err)
9230 		goto err_out;
9231 
9232 	/* only increment it after check_reg_arg() finished */
9233 	state->curframe++;
9234 
9235 	return 0;
9236 
9237 err_out:
9238 	free_func_state(callee);
9239 	state->frame[state->curframe + 1] = NULL;
9240 	return err;
9241 }
9242 
9243 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9244 			      int insn_idx, int subprog,
9245 			      set_callee_state_fn set_callee_state_cb)
9246 {
9247 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9248 	struct bpf_func_state *caller, *callee;
9249 	int err;
9250 
9251 	caller = state->frame[state->curframe];
9252 	err = btf_check_subprog_call(env, subprog, caller->regs);
9253 	if (err == -EFAULT)
9254 		return err;
9255 
9256 	/* set_callee_state is used for direct subprog calls, but we are
9257 	 * interested in validating only BPF helpers that can call subprogs as
9258 	 * callbacks
9259 	 */
9260 	if (bpf_pseudo_kfunc_call(insn) &&
9261 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9262 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9263 			func_id_name(insn->imm), insn->imm);
9264 		return -EFAULT;
9265 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9266 		   !is_callback_calling_function(insn->imm)) { /* helper */
9267 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9268 			func_id_name(insn->imm), insn->imm);
9269 		return -EFAULT;
9270 	}
9271 
9272 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9273 	    insn->src_reg == 0 &&
9274 	    insn->imm == BPF_FUNC_timer_set_callback) {
9275 		struct bpf_verifier_state *async_cb;
9276 
9277 		/* there is no real recursion here. timer callbacks are async */
9278 		env->subprog_info[subprog].is_async_cb = true;
9279 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9280 					 insn_idx, subprog);
9281 		if (!async_cb)
9282 			return -EFAULT;
9283 		callee = async_cb->frame[0];
9284 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9285 
9286 		/* Convert bpf_timer_set_callback() args into timer callback args */
9287 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9288 		if (err)
9289 			return err;
9290 
9291 		return 0;
9292 	}
9293 
9294 	/* for callback functions enqueue entry to callback and
9295 	 * proceed with next instruction within current frame.
9296 	 */
9297 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9298 	if (!callback_state)
9299 		return -ENOMEM;
9300 
9301 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9302 			       callback_state);
9303 	if (err)
9304 		return err;
9305 
9306 	callback_state->callback_unroll_depth++;
9307 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9308 	caller->callback_depth = 0;
9309 	return 0;
9310 }
9311 
9312 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9313 			   int *insn_idx)
9314 {
9315 	struct bpf_verifier_state *state = env->cur_state;
9316 	struct bpf_func_state *caller;
9317 	int err, subprog, target_insn;
9318 
9319 	target_insn = *insn_idx + insn->imm + 1;
9320 	subprog = find_subprog(env, target_insn);
9321 	if (subprog < 0) {
9322 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9323 		return -EFAULT;
9324 	}
9325 
9326 	caller = state->frame[state->curframe];
9327 	err = btf_check_subprog_call(env, subprog, caller->regs);
9328 	if (err == -EFAULT)
9329 		return err;
9330 	if (subprog_is_global(env, subprog)) {
9331 		if (err) {
9332 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9333 			return err;
9334 		}
9335 
9336 		if (env->log.level & BPF_LOG_LEVEL)
9337 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9338 		clear_caller_saved_regs(env, caller->regs);
9339 
9340 		/* All global functions return a 64-bit SCALAR_VALUE */
9341 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9342 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9343 
9344 		/* continue with next insn after call */
9345 		return 0;
9346 	}
9347 
9348 	/* for regular function entry setup new frame and continue
9349 	 * from that frame.
9350 	 */
9351 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9352 	if (err)
9353 		return err;
9354 
9355 	clear_caller_saved_regs(env, caller->regs);
9356 
9357 	/* and go analyze first insn of the callee */
9358 	*insn_idx = env->subprog_info[subprog].start - 1;
9359 
9360 	if (env->log.level & BPF_LOG_LEVEL) {
9361 		verbose(env, "caller:\n");
9362 		print_verifier_state(env, caller, true);
9363 		verbose(env, "callee:\n");
9364 		print_verifier_state(env, state->frame[state->curframe], true);
9365 	}
9366 
9367 	return 0;
9368 }
9369 
9370 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9371 				   struct bpf_func_state *caller,
9372 				   struct bpf_func_state *callee)
9373 {
9374 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9375 	 *      void *callback_ctx, u64 flags);
9376 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9377 	 *      void *callback_ctx);
9378 	 */
9379 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9380 
9381 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9382 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9383 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9384 
9385 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9386 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9387 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9388 
9389 	/* pointer to stack or null */
9390 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9391 
9392 	/* unused */
9393 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9394 	return 0;
9395 }
9396 
9397 static int set_callee_state(struct bpf_verifier_env *env,
9398 			    struct bpf_func_state *caller,
9399 			    struct bpf_func_state *callee, int insn_idx)
9400 {
9401 	int i;
9402 
9403 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9404 	 * pointers, which connects us up to the liveness chain
9405 	 */
9406 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9407 		callee->regs[i] = caller->regs[i];
9408 	return 0;
9409 }
9410 
9411 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9412 				       struct bpf_func_state *caller,
9413 				       struct bpf_func_state *callee,
9414 				       int insn_idx)
9415 {
9416 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9417 	struct bpf_map *map;
9418 	int err;
9419 
9420 	if (bpf_map_ptr_poisoned(insn_aux)) {
9421 		verbose(env, "tail_call abusing map_ptr\n");
9422 		return -EINVAL;
9423 	}
9424 
9425 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9426 	if (!map->ops->map_set_for_each_callback_args ||
9427 	    !map->ops->map_for_each_callback) {
9428 		verbose(env, "callback function not allowed for map\n");
9429 		return -ENOTSUPP;
9430 	}
9431 
9432 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9433 	if (err)
9434 		return err;
9435 
9436 	callee->in_callback_fn = true;
9437 	callee->callback_ret_range = tnum_range(0, 1);
9438 	return 0;
9439 }
9440 
9441 static int set_loop_callback_state(struct bpf_verifier_env *env,
9442 				   struct bpf_func_state *caller,
9443 				   struct bpf_func_state *callee,
9444 				   int insn_idx)
9445 {
9446 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9447 	 *	    u64 flags);
9448 	 * callback_fn(u32 index, void *callback_ctx);
9449 	 */
9450 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9451 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9452 
9453 	/* unused */
9454 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9455 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9456 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9457 
9458 	callee->in_callback_fn = true;
9459 	callee->callback_ret_range = tnum_range(0, 1);
9460 	return 0;
9461 }
9462 
9463 static int set_timer_callback_state(struct bpf_verifier_env *env,
9464 				    struct bpf_func_state *caller,
9465 				    struct bpf_func_state *callee,
9466 				    int insn_idx)
9467 {
9468 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9469 
9470 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9471 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9472 	 */
9473 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9474 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9475 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9476 
9477 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9478 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9479 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9480 
9481 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9482 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9483 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9484 
9485 	/* unused */
9486 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9487 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9488 	callee->in_async_callback_fn = true;
9489 	callee->callback_ret_range = tnum_range(0, 1);
9490 	return 0;
9491 }
9492 
9493 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9494 				       struct bpf_func_state *caller,
9495 				       struct bpf_func_state *callee,
9496 				       int insn_idx)
9497 {
9498 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9499 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9500 	 * (callback_fn)(struct task_struct *task,
9501 	 *               struct vm_area_struct *vma, void *callback_ctx);
9502 	 */
9503 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9504 
9505 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9506 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9507 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9508 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9509 
9510 	/* pointer to stack or null */
9511 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9512 
9513 	/* unused */
9514 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9515 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9516 	callee->in_callback_fn = true;
9517 	callee->callback_ret_range = tnum_range(0, 1);
9518 	return 0;
9519 }
9520 
9521 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9522 					   struct bpf_func_state *caller,
9523 					   struct bpf_func_state *callee,
9524 					   int insn_idx)
9525 {
9526 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9527 	 *			  callback_ctx, u64 flags);
9528 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9529 	 */
9530 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9531 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9532 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9533 
9534 	/* unused */
9535 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9536 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9537 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9538 
9539 	callee->in_callback_fn = true;
9540 	callee->callback_ret_range = tnum_range(0, 1);
9541 	return 0;
9542 }
9543 
9544 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9545 					 struct bpf_func_state *caller,
9546 					 struct bpf_func_state *callee,
9547 					 int insn_idx)
9548 {
9549 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9550 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9551 	 *
9552 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9553 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9554 	 * by this point, so look at 'root'
9555 	 */
9556 	struct btf_field *field;
9557 
9558 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9559 				      BPF_RB_ROOT);
9560 	if (!field || !field->graph_root.value_btf_id)
9561 		return -EFAULT;
9562 
9563 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9564 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9565 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9566 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9567 
9568 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9569 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9570 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9571 	callee->in_callback_fn = true;
9572 	callee->callback_ret_range = tnum_range(0, 1);
9573 	return 0;
9574 }
9575 
9576 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9577 
9578 /* Are we currently verifying the callback for a rbtree helper that must
9579  * be called with lock held? If so, no need to complain about unreleased
9580  * lock
9581  */
9582 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9583 {
9584 	struct bpf_verifier_state *state = env->cur_state;
9585 	struct bpf_insn *insn = env->prog->insnsi;
9586 	struct bpf_func_state *callee;
9587 	int kfunc_btf_id;
9588 
9589 	if (!state->curframe)
9590 		return false;
9591 
9592 	callee = state->frame[state->curframe];
9593 
9594 	if (!callee->in_callback_fn)
9595 		return false;
9596 
9597 	kfunc_btf_id = insn[callee->callsite].imm;
9598 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9599 }
9600 
9601 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9602 {
9603 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9604 	struct bpf_func_state *caller, *callee;
9605 	struct bpf_reg_state *r0;
9606 	bool in_callback_fn;
9607 	int err;
9608 
9609 	callee = state->frame[state->curframe];
9610 	r0 = &callee->regs[BPF_REG_0];
9611 	if (r0->type == PTR_TO_STACK) {
9612 		/* technically it's ok to return caller's stack pointer
9613 		 * (or caller's caller's pointer) back to the caller,
9614 		 * since these pointers are valid. Only current stack
9615 		 * pointer will be invalid as soon as function exits,
9616 		 * but let's be conservative
9617 		 */
9618 		verbose(env, "cannot return stack pointer to the caller\n");
9619 		return -EINVAL;
9620 	}
9621 
9622 	caller = state->frame[state->curframe - 1];
9623 	if (callee->in_callback_fn) {
9624 		/* enforce R0 return value range [0, 1]. */
9625 		struct tnum range = callee->callback_ret_range;
9626 
9627 		if (r0->type != SCALAR_VALUE) {
9628 			verbose(env, "R0 not a scalar value\n");
9629 			return -EACCES;
9630 		}
9631 
9632 		/* we are going to rely on register's precise value */
9633 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9634 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9635 		if (err)
9636 			return err;
9637 
9638 		if (!tnum_in(range, r0->var_off)) {
9639 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9640 			return -EINVAL;
9641 		}
9642 		if (!calls_callback(env, callee->callsite)) {
9643 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9644 				*insn_idx, callee->callsite);
9645 			return -EFAULT;
9646 		}
9647 	} else {
9648 		/* return to the caller whatever r0 had in the callee */
9649 		caller->regs[BPF_REG_0] = *r0;
9650 	}
9651 
9652 	/* callback_fn frame should have released its own additions to parent's
9653 	 * reference state at this point, or check_reference_leak would
9654 	 * complain, hence it must be the same as the caller. There is no need
9655 	 * to copy it back.
9656 	 */
9657 	if (!callee->in_callback_fn) {
9658 		/* Transfer references to the caller */
9659 		err = copy_reference_state(caller, callee);
9660 		if (err)
9661 			return err;
9662 	}
9663 
9664 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9665 	 * there function call logic would reschedule callback visit. If iteration
9666 	 * converges is_state_visited() would prune that visit eventually.
9667 	 */
9668 	in_callback_fn = callee->in_callback_fn;
9669 	if (in_callback_fn)
9670 		*insn_idx = callee->callsite;
9671 	else
9672 		*insn_idx = callee->callsite + 1;
9673 
9674 	if (env->log.level & BPF_LOG_LEVEL) {
9675 		verbose(env, "returning from callee:\n");
9676 		print_verifier_state(env, callee, true);
9677 		verbose(env, "to caller at %d:\n", *insn_idx);
9678 		print_verifier_state(env, caller, true);
9679 	}
9680 	/* clear everything in the callee */
9681 	free_func_state(callee);
9682 	state->frame[state->curframe--] = NULL;
9683 
9684 	/* for callbacks widen imprecise scalars to make programs like below verify:
9685 	 *
9686 	 *   struct ctx { int i; }
9687 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9688 	 *   ...
9689 	 *   struct ctx = { .i = 0; }
9690 	 *   bpf_loop(100, cb, &ctx, 0);
9691 	 *
9692 	 * This is similar to what is done in process_iter_next_call() for open
9693 	 * coded iterators.
9694 	 */
9695 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9696 	if (prev_st) {
9697 		err = widen_imprecise_scalars(env, prev_st, state);
9698 		if (err)
9699 			return err;
9700 	}
9701 	return 0;
9702 }
9703 
9704 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9705 				   int func_id,
9706 				   struct bpf_call_arg_meta *meta)
9707 {
9708 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9709 
9710 	if (ret_type != RET_INTEGER)
9711 		return;
9712 
9713 	switch (func_id) {
9714 	case BPF_FUNC_get_stack:
9715 	case BPF_FUNC_get_task_stack:
9716 	case BPF_FUNC_probe_read_str:
9717 	case BPF_FUNC_probe_read_kernel_str:
9718 	case BPF_FUNC_probe_read_user_str:
9719 		ret_reg->smax_value = meta->msize_max_value;
9720 		ret_reg->s32_max_value = meta->msize_max_value;
9721 		ret_reg->smin_value = -MAX_ERRNO;
9722 		ret_reg->s32_min_value = -MAX_ERRNO;
9723 		reg_bounds_sync(ret_reg);
9724 		break;
9725 	case BPF_FUNC_get_smp_processor_id:
9726 		ret_reg->umax_value = nr_cpu_ids - 1;
9727 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9728 		ret_reg->smax_value = nr_cpu_ids - 1;
9729 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9730 		ret_reg->umin_value = 0;
9731 		ret_reg->u32_min_value = 0;
9732 		ret_reg->smin_value = 0;
9733 		ret_reg->s32_min_value = 0;
9734 		reg_bounds_sync(ret_reg);
9735 		break;
9736 	}
9737 }
9738 
9739 static int
9740 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9741 		int func_id, int insn_idx)
9742 {
9743 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9744 	struct bpf_map *map = meta->map_ptr;
9745 
9746 	if (func_id != BPF_FUNC_tail_call &&
9747 	    func_id != BPF_FUNC_map_lookup_elem &&
9748 	    func_id != BPF_FUNC_map_update_elem &&
9749 	    func_id != BPF_FUNC_map_delete_elem &&
9750 	    func_id != BPF_FUNC_map_push_elem &&
9751 	    func_id != BPF_FUNC_map_pop_elem &&
9752 	    func_id != BPF_FUNC_map_peek_elem &&
9753 	    func_id != BPF_FUNC_for_each_map_elem &&
9754 	    func_id != BPF_FUNC_redirect_map &&
9755 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9756 		return 0;
9757 
9758 	if (map == NULL) {
9759 		verbose(env, "kernel subsystem misconfigured verifier\n");
9760 		return -EINVAL;
9761 	}
9762 
9763 	/* In case of read-only, some additional restrictions
9764 	 * need to be applied in order to prevent altering the
9765 	 * state of the map from program side.
9766 	 */
9767 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9768 	    (func_id == BPF_FUNC_map_delete_elem ||
9769 	     func_id == BPF_FUNC_map_update_elem ||
9770 	     func_id == BPF_FUNC_map_push_elem ||
9771 	     func_id == BPF_FUNC_map_pop_elem)) {
9772 		verbose(env, "write into map forbidden\n");
9773 		return -EACCES;
9774 	}
9775 
9776 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9777 		bpf_map_ptr_store(aux, meta->map_ptr,
9778 				  !meta->map_ptr->bypass_spec_v1);
9779 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9780 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9781 				  !meta->map_ptr->bypass_spec_v1);
9782 	return 0;
9783 }
9784 
9785 static int
9786 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9787 		int func_id, int insn_idx)
9788 {
9789 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9790 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9791 	struct bpf_map *map = meta->map_ptr;
9792 	u64 val, max;
9793 	int err;
9794 
9795 	if (func_id != BPF_FUNC_tail_call)
9796 		return 0;
9797 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9798 		verbose(env, "kernel subsystem misconfigured verifier\n");
9799 		return -EINVAL;
9800 	}
9801 
9802 	reg = &regs[BPF_REG_3];
9803 	val = reg->var_off.value;
9804 	max = map->max_entries;
9805 
9806 	if (!(register_is_const(reg) && val < max)) {
9807 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9808 		return 0;
9809 	}
9810 
9811 	err = mark_chain_precision(env, BPF_REG_3);
9812 	if (err)
9813 		return err;
9814 	if (bpf_map_key_unseen(aux))
9815 		bpf_map_key_store(aux, val);
9816 	else if (!bpf_map_key_poisoned(aux) &&
9817 		  bpf_map_key_immediate(aux) != val)
9818 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9819 	return 0;
9820 }
9821 
9822 static int check_reference_leak(struct bpf_verifier_env *env)
9823 {
9824 	struct bpf_func_state *state = cur_func(env);
9825 	bool refs_lingering = false;
9826 	int i;
9827 
9828 	if (state->frameno && !state->in_callback_fn)
9829 		return 0;
9830 
9831 	for (i = 0; i < state->acquired_refs; i++) {
9832 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9833 			continue;
9834 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9835 			state->refs[i].id, state->refs[i].insn_idx);
9836 		refs_lingering = true;
9837 	}
9838 	return refs_lingering ? -EINVAL : 0;
9839 }
9840 
9841 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9842 				   struct bpf_reg_state *regs)
9843 {
9844 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9845 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9846 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9847 	struct bpf_bprintf_data data = {};
9848 	int err, fmt_map_off, num_args;
9849 	u64 fmt_addr;
9850 	char *fmt;
9851 
9852 	/* data must be an array of u64 */
9853 	if (data_len_reg->var_off.value % 8)
9854 		return -EINVAL;
9855 	num_args = data_len_reg->var_off.value / 8;
9856 
9857 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9858 	 * and map_direct_value_addr is set.
9859 	 */
9860 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9861 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9862 						  fmt_map_off);
9863 	if (err) {
9864 		verbose(env, "verifier bug\n");
9865 		return -EFAULT;
9866 	}
9867 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9868 
9869 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9870 	 * can focus on validating the format specifiers.
9871 	 */
9872 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9873 	if (err < 0)
9874 		verbose(env, "Invalid format string\n");
9875 
9876 	return err;
9877 }
9878 
9879 static int check_get_func_ip(struct bpf_verifier_env *env)
9880 {
9881 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9882 	int func_id = BPF_FUNC_get_func_ip;
9883 
9884 	if (type == BPF_PROG_TYPE_TRACING) {
9885 		if (!bpf_prog_has_trampoline(env->prog)) {
9886 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9887 				func_id_name(func_id), func_id);
9888 			return -ENOTSUPP;
9889 		}
9890 		return 0;
9891 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9892 		return 0;
9893 	}
9894 
9895 	verbose(env, "func %s#%d not supported for program type %d\n",
9896 		func_id_name(func_id), func_id, type);
9897 	return -ENOTSUPP;
9898 }
9899 
9900 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9901 {
9902 	return &env->insn_aux_data[env->insn_idx];
9903 }
9904 
9905 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9906 {
9907 	struct bpf_reg_state *regs = cur_regs(env);
9908 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9909 	bool reg_is_null = register_is_null(reg);
9910 
9911 	if (reg_is_null)
9912 		mark_chain_precision(env, BPF_REG_4);
9913 
9914 	return reg_is_null;
9915 }
9916 
9917 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9918 {
9919 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9920 
9921 	if (!state->initialized) {
9922 		state->initialized = 1;
9923 		state->fit_for_inline = loop_flag_is_zero(env);
9924 		state->callback_subprogno = subprogno;
9925 		return;
9926 	}
9927 
9928 	if (!state->fit_for_inline)
9929 		return;
9930 
9931 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9932 				 state->callback_subprogno == subprogno);
9933 }
9934 
9935 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9936 			     int *insn_idx_p)
9937 {
9938 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9939 	const struct bpf_func_proto *fn = NULL;
9940 	enum bpf_return_type ret_type;
9941 	enum bpf_type_flag ret_flag;
9942 	struct bpf_reg_state *regs;
9943 	struct bpf_call_arg_meta meta;
9944 	int insn_idx = *insn_idx_p;
9945 	bool changes_data;
9946 	int i, err, func_id;
9947 
9948 	/* find function prototype */
9949 	func_id = insn->imm;
9950 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9951 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9952 			func_id);
9953 		return -EINVAL;
9954 	}
9955 
9956 	if (env->ops->get_func_proto)
9957 		fn = env->ops->get_func_proto(func_id, env->prog);
9958 	if (!fn) {
9959 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9960 			func_id);
9961 		return -EINVAL;
9962 	}
9963 
9964 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9965 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9966 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9967 		return -EINVAL;
9968 	}
9969 
9970 	if (fn->allowed && !fn->allowed(env->prog)) {
9971 		verbose(env, "helper call is not allowed in probe\n");
9972 		return -EINVAL;
9973 	}
9974 
9975 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9976 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9977 		return -EINVAL;
9978 	}
9979 
9980 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9981 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9982 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9983 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9984 			func_id_name(func_id), func_id);
9985 		return -EINVAL;
9986 	}
9987 
9988 	memset(&meta, 0, sizeof(meta));
9989 	meta.pkt_access = fn->pkt_access;
9990 
9991 	err = check_func_proto(fn, func_id);
9992 	if (err) {
9993 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9994 			func_id_name(func_id), func_id);
9995 		return err;
9996 	}
9997 
9998 	if (env->cur_state->active_rcu_lock) {
9999 		if (fn->might_sleep) {
10000 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10001 				func_id_name(func_id), func_id);
10002 			return -EINVAL;
10003 		}
10004 
10005 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10006 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10007 	}
10008 
10009 	meta.func_id = func_id;
10010 	/* check args */
10011 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10012 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10013 		if (err)
10014 			return err;
10015 	}
10016 
10017 	err = record_func_map(env, &meta, func_id, insn_idx);
10018 	if (err)
10019 		return err;
10020 
10021 	err = record_func_key(env, &meta, func_id, insn_idx);
10022 	if (err)
10023 		return err;
10024 
10025 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10026 	 * is inferred from register state.
10027 	 */
10028 	for (i = 0; i < meta.access_size; i++) {
10029 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10030 				       BPF_WRITE, -1, false, false);
10031 		if (err)
10032 			return err;
10033 	}
10034 
10035 	regs = cur_regs(env);
10036 
10037 	if (meta.release_regno) {
10038 		err = -EINVAL;
10039 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10040 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10041 		 * is safe to do directly.
10042 		 */
10043 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10044 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10045 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10046 				return -EFAULT;
10047 			}
10048 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10049 		} else if (meta.ref_obj_id) {
10050 			err = release_reference(env, meta.ref_obj_id);
10051 		} else if (register_is_null(&regs[meta.release_regno])) {
10052 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10053 			 * released is NULL, which must be > R0.
10054 			 */
10055 			err = 0;
10056 		}
10057 		if (err) {
10058 			verbose(env, "func %s#%d reference has not been acquired before\n",
10059 				func_id_name(func_id), func_id);
10060 			return err;
10061 		}
10062 	}
10063 
10064 	switch (func_id) {
10065 	case BPF_FUNC_tail_call:
10066 		err = check_reference_leak(env);
10067 		if (err) {
10068 			verbose(env, "tail_call would lead to reference leak\n");
10069 			return err;
10070 		}
10071 		break;
10072 	case BPF_FUNC_get_local_storage:
10073 		/* check that flags argument in get_local_storage(map, flags) is 0,
10074 		 * this is required because get_local_storage() can't return an error.
10075 		 */
10076 		if (!register_is_null(&regs[BPF_REG_2])) {
10077 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10078 			return -EINVAL;
10079 		}
10080 		break;
10081 	case BPF_FUNC_for_each_map_elem:
10082 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10083 					 set_map_elem_callback_state);
10084 		break;
10085 	case BPF_FUNC_timer_set_callback:
10086 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10087 					 set_timer_callback_state);
10088 		break;
10089 	case BPF_FUNC_find_vma:
10090 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10091 					 set_find_vma_callback_state);
10092 		break;
10093 	case BPF_FUNC_snprintf:
10094 		err = check_bpf_snprintf_call(env, regs);
10095 		break;
10096 	case BPF_FUNC_loop:
10097 		update_loop_inline_state(env, meta.subprogno);
10098 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10099 		 * is finished, thus mark it precise.
10100 		 */
10101 		err = mark_chain_precision(env, BPF_REG_1);
10102 		if (err)
10103 			return err;
10104 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10105 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10106 						 set_loop_callback_state);
10107 		} else {
10108 			cur_func(env)->callback_depth = 0;
10109 			if (env->log.level & BPF_LOG_LEVEL2)
10110 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10111 					env->cur_state->curframe);
10112 		}
10113 		break;
10114 	case BPF_FUNC_dynptr_from_mem:
10115 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10116 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10117 				reg_type_str(env, regs[BPF_REG_1].type));
10118 			return -EACCES;
10119 		}
10120 		break;
10121 	case BPF_FUNC_set_retval:
10122 		if (prog_type == BPF_PROG_TYPE_LSM &&
10123 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10124 			if (!env->prog->aux->attach_func_proto->type) {
10125 				/* Make sure programs that attach to void
10126 				 * hooks don't try to modify return value.
10127 				 */
10128 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10129 				return -EINVAL;
10130 			}
10131 		}
10132 		break;
10133 	case BPF_FUNC_dynptr_data:
10134 	{
10135 		struct bpf_reg_state *reg;
10136 		int id, ref_obj_id;
10137 
10138 		reg = get_dynptr_arg_reg(env, fn, regs);
10139 		if (!reg)
10140 			return -EFAULT;
10141 
10142 
10143 		if (meta.dynptr_id) {
10144 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10145 			return -EFAULT;
10146 		}
10147 		if (meta.ref_obj_id) {
10148 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10149 			return -EFAULT;
10150 		}
10151 
10152 		id = dynptr_id(env, reg);
10153 		if (id < 0) {
10154 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10155 			return id;
10156 		}
10157 
10158 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10159 		if (ref_obj_id < 0) {
10160 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10161 			return ref_obj_id;
10162 		}
10163 
10164 		meta.dynptr_id = id;
10165 		meta.ref_obj_id = ref_obj_id;
10166 
10167 		break;
10168 	}
10169 	case BPF_FUNC_dynptr_write:
10170 	{
10171 		enum bpf_dynptr_type dynptr_type;
10172 		struct bpf_reg_state *reg;
10173 
10174 		reg = get_dynptr_arg_reg(env, fn, regs);
10175 		if (!reg)
10176 			return -EFAULT;
10177 
10178 		dynptr_type = dynptr_get_type(env, reg);
10179 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10180 			return -EFAULT;
10181 
10182 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10183 			/* this will trigger clear_all_pkt_pointers(), which will
10184 			 * invalidate all dynptr slices associated with the skb
10185 			 */
10186 			changes_data = true;
10187 
10188 		break;
10189 	}
10190 	case BPF_FUNC_user_ringbuf_drain:
10191 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10192 					 set_user_ringbuf_callback_state);
10193 		break;
10194 	}
10195 
10196 	if (err)
10197 		return err;
10198 
10199 	/* reset caller saved regs */
10200 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10201 		mark_reg_not_init(env, regs, caller_saved[i]);
10202 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10203 	}
10204 
10205 	/* helper call returns 64-bit value. */
10206 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10207 
10208 	/* update return register (already marked as written above) */
10209 	ret_type = fn->ret_type;
10210 	ret_flag = type_flag(ret_type);
10211 
10212 	switch (base_type(ret_type)) {
10213 	case RET_INTEGER:
10214 		/* sets type to SCALAR_VALUE */
10215 		mark_reg_unknown(env, regs, BPF_REG_0);
10216 		break;
10217 	case RET_VOID:
10218 		regs[BPF_REG_0].type = NOT_INIT;
10219 		break;
10220 	case RET_PTR_TO_MAP_VALUE:
10221 		/* There is no offset yet applied, variable or fixed */
10222 		mark_reg_known_zero(env, regs, BPF_REG_0);
10223 		/* remember map_ptr, so that check_map_access()
10224 		 * can check 'value_size' boundary of memory access
10225 		 * to map element returned from bpf_map_lookup_elem()
10226 		 */
10227 		if (meta.map_ptr == NULL) {
10228 			verbose(env,
10229 				"kernel subsystem misconfigured verifier\n");
10230 			return -EINVAL;
10231 		}
10232 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10233 		regs[BPF_REG_0].map_uid = meta.map_uid;
10234 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10235 		if (!type_may_be_null(ret_type) &&
10236 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10237 			regs[BPF_REG_0].id = ++env->id_gen;
10238 		}
10239 		break;
10240 	case RET_PTR_TO_SOCKET:
10241 		mark_reg_known_zero(env, regs, BPF_REG_0);
10242 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10243 		break;
10244 	case RET_PTR_TO_SOCK_COMMON:
10245 		mark_reg_known_zero(env, regs, BPF_REG_0);
10246 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10247 		break;
10248 	case RET_PTR_TO_TCP_SOCK:
10249 		mark_reg_known_zero(env, regs, BPF_REG_0);
10250 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10251 		break;
10252 	case RET_PTR_TO_MEM:
10253 		mark_reg_known_zero(env, regs, BPF_REG_0);
10254 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10255 		regs[BPF_REG_0].mem_size = meta.mem_size;
10256 		break;
10257 	case RET_PTR_TO_MEM_OR_BTF_ID:
10258 	{
10259 		const struct btf_type *t;
10260 
10261 		mark_reg_known_zero(env, regs, BPF_REG_0);
10262 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10263 		if (!btf_type_is_struct(t)) {
10264 			u32 tsize;
10265 			const struct btf_type *ret;
10266 			const char *tname;
10267 
10268 			/* resolve the type size of ksym. */
10269 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10270 			if (IS_ERR(ret)) {
10271 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10272 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10273 					tname, PTR_ERR(ret));
10274 				return -EINVAL;
10275 			}
10276 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10277 			regs[BPF_REG_0].mem_size = tsize;
10278 		} else {
10279 			/* MEM_RDONLY may be carried from ret_flag, but it
10280 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10281 			 * it will confuse the check of PTR_TO_BTF_ID in
10282 			 * check_mem_access().
10283 			 */
10284 			ret_flag &= ~MEM_RDONLY;
10285 
10286 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10287 			regs[BPF_REG_0].btf = meta.ret_btf;
10288 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10289 		}
10290 		break;
10291 	}
10292 	case RET_PTR_TO_BTF_ID:
10293 	{
10294 		struct btf *ret_btf;
10295 		int ret_btf_id;
10296 
10297 		mark_reg_known_zero(env, regs, BPF_REG_0);
10298 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10299 		if (func_id == BPF_FUNC_kptr_xchg) {
10300 			ret_btf = meta.kptr_field->kptr.btf;
10301 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10302 			if (!btf_is_kernel(ret_btf))
10303 				regs[BPF_REG_0].type |= MEM_ALLOC;
10304 		} else {
10305 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10306 				verbose(env, "verifier internal error:");
10307 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10308 					func_id_name(func_id));
10309 				return -EINVAL;
10310 			}
10311 			ret_btf = btf_vmlinux;
10312 			ret_btf_id = *fn->ret_btf_id;
10313 		}
10314 		if (ret_btf_id == 0) {
10315 			verbose(env, "invalid return type %u of func %s#%d\n",
10316 				base_type(ret_type), func_id_name(func_id),
10317 				func_id);
10318 			return -EINVAL;
10319 		}
10320 		regs[BPF_REG_0].btf = ret_btf;
10321 		regs[BPF_REG_0].btf_id = ret_btf_id;
10322 		break;
10323 	}
10324 	default:
10325 		verbose(env, "unknown return type %u of func %s#%d\n",
10326 			base_type(ret_type), func_id_name(func_id), func_id);
10327 		return -EINVAL;
10328 	}
10329 
10330 	if (type_may_be_null(regs[BPF_REG_0].type))
10331 		regs[BPF_REG_0].id = ++env->id_gen;
10332 
10333 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10334 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10335 			func_id_name(func_id), func_id);
10336 		return -EFAULT;
10337 	}
10338 
10339 	if (is_dynptr_ref_function(func_id))
10340 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10341 
10342 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10343 		/* For release_reference() */
10344 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10345 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10346 		int id = acquire_reference_state(env, insn_idx);
10347 
10348 		if (id < 0)
10349 			return id;
10350 		/* For mark_ptr_or_null_reg() */
10351 		regs[BPF_REG_0].id = id;
10352 		/* For release_reference() */
10353 		regs[BPF_REG_0].ref_obj_id = id;
10354 	}
10355 
10356 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10357 
10358 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10359 	if (err)
10360 		return err;
10361 
10362 	if ((func_id == BPF_FUNC_get_stack ||
10363 	     func_id == BPF_FUNC_get_task_stack) &&
10364 	    !env->prog->has_callchain_buf) {
10365 		const char *err_str;
10366 
10367 #ifdef CONFIG_PERF_EVENTS
10368 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10369 		err_str = "cannot get callchain buffer for func %s#%d\n";
10370 #else
10371 		err = -ENOTSUPP;
10372 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10373 #endif
10374 		if (err) {
10375 			verbose(env, err_str, func_id_name(func_id), func_id);
10376 			return err;
10377 		}
10378 
10379 		env->prog->has_callchain_buf = true;
10380 	}
10381 
10382 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10383 		env->prog->call_get_stack = true;
10384 
10385 	if (func_id == BPF_FUNC_get_func_ip) {
10386 		if (check_get_func_ip(env))
10387 			return -ENOTSUPP;
10388 		env->prog->call_get_func_ip = true;
10389 	}
10390 
10391 	if (changes_data)
10392 		clear_all_pkt_pointers(env);
10393 	return 0;
10394 }
10395 
10396 /* mark_btf_func_reg_size() is used when the reg size is determined by
10397  * the BTF func_proto's return value size and argument.
10398  */
10399 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10400 				   size_t reg_size)
10401 {
10402 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10403 
10404 	if (regno == BPF_REG_0) {
10405 		/* Function return value */
10406 		reg->live |= REG_LIVE_WRITTEN;
10407 		reg->subreg_def = reg_size == sizeof(u64) ?
10408 			DEF_NOT_SUBREG : env->insn_idx + 1;
10409 	} else {
10410 		/* Function argument */
10411 		if (reg_size == sizeof(u64)) {
10412 			mark_insn_zext(env, reg);
10413 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10414 		} else {
10415 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10416 		}
10417 	}
10418 }
10419 
10420 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10421 {
10422 	return meta->kfunc_flags & KF_ACQUIRE;
10423 }
10424 
10425 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10426 {
10427 	return meta->kfunc_flags & KF_RELEASE;
10428 }
10429 
10430 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10431 {
10432 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10433 }
10434 
10435 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10436 {
10437 	return meta->kfunc_flags & KF_SLEEPABLE;
10438 }
10439 
10440 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10441 {
10442 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10443 }
10444 
10445 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10446 {
10447 	return meta->kfunc_flags & KF_RCU;
10448 }
10449 
10450 static bool __kfunc_param_match_suffix(const struct btf *btf,
10451 				       const struct btf_param *arg,
10452 				       const char *suffix)
10453 {
10454 	int suffix_len = strlen(suffix), len;
10455 	const char *param_name;
10456 
10457 	/* In the future, this can be ported to use BTF tagging */
10458 	param_name = btf_name_by_offset(btf, arg->name_off);
10459 	if (str_is_empty(param_name))
10460 		return false;
10461 	len = strlen(param_name);
10462 	if (len < suffix_len)
10463 		return false;
10464 	param_name += len - suffix_len;
10465 	return !strncmp(param_name, suffix, suffix_len);
10466 }
10467 
10468 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10469 				  const struct btf_param *arg,
10470 				  const struct bpf_reg_state *reg)
10471 {
10472 	const struct btf_type *t;
10473 
10474 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10475 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10476 		return false;
10477 
10478 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10479 }
10480 
10481 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10482 					const struct btf_param *arg,
10483 					const struct bpf_reg_state *reg)
10484 {
10485 	const struct btf_type *t;
10486 
10487 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10488 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10489 		return false;
10490 
10491 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10492 }
10493 
10494 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10495 {
10496 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10497 }
10498 
10499 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10500 {
10501 	return __kfunc_param_match_suffix(btf, arg, "__k");
10502 }
10503 
10504 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10505 {
10506 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10507 }
10508 
10509 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10510 {
10511 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10512 }
10513 
10514 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10515 {
10516 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10517 }
10518 
10519 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10520 {
10521 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10522 }
10523 
10524 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10525 					  const struct btf_param *arg,
10526 					  const char *name)
10527 {
10528 	int len, target_len = strlen(name);
10529 	const char *param_name;
10530 
10531 	param_name = btf_name_by_offset(btf, arg->name_off);
10532 	if (str_is_empty(param_name))
10533 		return false;
10534 	len = strlen(param_name);
10535 	if (len != target_len)
10536 		return false;
10537 	if (strcmp(param_name, name))
10538 		return false;
10539 
10540 	return true;
10541 }
10542 
10543 enum {
10544 	KF_ARG_DYNPTR_ID,
10545 	KF_ARG_LIST_HEAD_ID,
10546 	KF_ARG_LIST_NODE_ID,
10547 	KF_ARG_RB_ROOT_ID,
10548 	KF_ARG_RB_NODE_ID,
10549 };
10550 
10551 BTF_ID_LIST(kf_arg_btf_ids)
10552 BTF_ID(struct, bpf_dynptr_kern)
10553 BTF_ID(struct, bpf_list_head)
10554 BTF_ID(struct, bpf_list_node)
10555 BTF_ID(struct, bpf_rb_root)
10556 BTF_ID(struct, bpf_rb_node)
10557 
10558 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10559 				    const struct btf_param *arg, int type)
10560 {
10561 	const struct btf_type *t;
10562 	u32 res_id;
10563 
10564 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10565 	if (!t)
10566 		return false;
10567 	if (!btf_type_is_ptr(t))
10568 		return false;
10569 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10570 	if (!t)
10571 		return false;
10572 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10573 }
10574 
10575 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10576 {
10577 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10578 }
10579 
10580 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10581 {
10582 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10583 }
10584 
10585 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10586 {
10587 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10588 }
10589 
10590 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10591 {
10592 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10593 }
10594 
10595 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10596 {
10597 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10598 }
10599 
10600 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10601 				  const struct btf_param *arg)
10602 {
10603 	const struct btf_type *t;
10604 
10605 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10606 	if (!t)
10607 		return false;
10608 
10609 	return true;
10610 }
10611 
10612 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10613 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10614 					const struct btf *btf,
10615 					const struct btf_type *t, int rec)
10616 {
10617 	const struct btf_type *member_type;
10618 	const struct btf_member *member;
10619 	u32 i;
10620 
10621 	if (!btf_type_is_struct(t))
10622 		return false;
10623 
10624 	for_each_member(i, t, member) {
10625 		const struct btf_array *array;
10626 
10627 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10628 		if (btf_type_is_struct(member_type)) {
10629 			if (rec >= 3) {
10630 				verbose(env, "max struct nesting depth exceeded\n");
10631 				return false;
10632 			}
10633 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10634 				return false;
10635 			continue;
10636 		}
10637 		if (btf_type_is_array(member_type)) {
10638 			array = btf_array(member_type);
10639 			if (!array->nelems)
10640 				return false;
10641 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10642 			if (!btf_type_is_scalar(member_type))
10643 				return false;
10644 			continue;
10645 		}
10646 		if (!btf_type_is_scalar(member_type))
10647 			return false;
10648 	}
10649 	return true;
10650 }
10651 
10652 enum kfunc_ptr_arg_type {
10653 	KF_ARG_PTR_TO_CTX,
10654 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10655 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10656 	KF_ARG_PTR_TO_DYNPTR,
10657 	KF_ARG_PTR_TO_ITER,
10658 	KF_ARG_PTR_TO_LIST_HEAD,
10659 	KF_ARG_PTR_TO_LIST_NODE,
10660 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10661 	KF_ARG_PTR_TO_MEM,
10662 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10663 	KF_ARG_PTR_TO_CALLBACK,
10664 	KF_ARG_PTR_TO_RB_ROOT,
10665 	KF_ARG_PTR_TO_RB_NODE,
10666 };
10667 
10668 enum special_kfunc_type {
10669 	KF_bpf_obj_new_impl,
10670 	KF_bpf_obj_drop_impl,
10671 	KF_bpf_refcount_acquire_impl,
10672 	KF_bpf_list_push_front_impl,
10673 	KF_bpf_list_push_back_impl,
10674 	KF_bpf_list_pop_front,
10675 	KF_bpf_list_pop_back,
10676 	KF_bpf_cast_to_kern_ctx,
10677 	KF_bpf_rdonly_cast,
10678 	KF_bpf_rcu_read_lock,
10679 	KF_bpf_rcu_read_unlock,
10680 	KF_bpf_rbtree_remove,
10681 	KF_bpf_rbtree_add_impl,
10682 	KF_bpf_rbtree_first,
10683 	KF_bpf_dynptr_from_skb,
10684 	KF_bpf_dynptr_from_xdp,
10685 	KF_bpf_dynptr_slice,
10686 	KF_bpf_dynptr_slice_rdwr,
10687 	KF_bpf_dynptr_clone,
10688 };
10689 
10690 BTF_SET_START(special_kfunc_set)
10691 BTF_ID(func, bpf_obj_new_impl)
10692 BTF_ID(func, bpf_obj_drop_impl)
10693 BTF_ID(func, bpf_refcount_acquire_impl)
10694 BTF_ID(func, bpf_list_push_front_impl)
10695 BTF_ID(func, bpf_list_push_back_impl)
10696 BTF_ID(func, bpf_list_pop_front)
10697 BTF_ID(func, bpf_list_pop_back)
10698 BTF_ID(func, bpf_cast_to_kern_ctx)
10699 BTF_ID(func, bpf_rdonly_cast)
10700 BTF_ID(func, bpf_rbtree_remove)
10701 BTF_ID(func, bpf_rbtree_add_impl)
10702 BTF_ID(func, bpf_rbtree_first)
10703 BTF_ID(func, bpf_dynptr_from_skb)
10704 BTF_ID(func, bpf_dynptr_from_xdp)
10705 BTF_ID(func, bpf_dynptr_slice)
10706 BTF_ID(func, bpf_dynptr_slice_rdwr)
10707 BTF_ID(func, bpf_dynptr_clone)
10708 BTF_SET_END(special_kfunc_set)
10709 
10710 BTF_ID_LIST(special_kfunc_list)
10711 BTF_ID(func, bpf_obj_new_impl)
10712 BTF_ID(func, bpf_obj_drop_impl)
10713 BTF_ID(func, bpf_refcount_acquire_impl)
10714 BTF_ID(func, bpf_list_push_front_impl)
10715 BTF_ID(func, bpf_list_push_back_impl)
10716 BTF_ID(func, bpf_list_pop_front)
10717 BTF_ID(func, bpf_list_pop_back)
10718 BTF_ID(func, bpf_cast_to_kern_ctx)
10719 BTF_ID(func, bpf_rdonly_cast)
10720 BTF_ID(func, bpf_rcu_read_lock)
10721 BTF_ID(func, bpf_rcu_read_unlock)
10722 BTF_ID(func, bpf_rbtree_remove)
10723 BTF_ID(func, bpf_rbtree_add_impl)
10724 BTF_ID(func, bpf_rbtree_first)
10725 BTF_ID(func, bpf_dynptr_from_skb)
10726 BTF_ID(func, bpf_dynptr_from_xdp)
10727 BTF_ID(func, bpf_dynptr_slice)
10728 BTF_ID(func, bpf_dynptr_slice_rdwr)
10729 BTF_ID(func, bpf_dynptr_clone)
10730 
10731 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10732 {
10733 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10734 	    meta->arg_owning_ref) {
10735 		return false;
10736 	}
10737 
10738 	return meta->kfunc_flags & KF_RET_NULL;
10739 }
10740 
10741 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10742 {
10743 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10744 }
10745 
10746 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10747 {
10748 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10749 }
10750 
10751 static enum kfunc_ptr_arg_type
10752 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10753 		       struct bpf_kfunc_call_arg_meta *meta,
10754 		       const struct btf_type *t, const struct btf_type *ref_t,
10755 		       const char *ref_tname, const struct btf_param *args,
10756 		       int argno, int nargs)
10757 {
10758 	u32 regno = argno + 1;
10759 	struct bpf_reg_state *regs = cur_regs(env);
10760 	struct bpf_reg_state *reg = &regs[regno];
10761 	bool arg_mem_size = false;
10762 
10763 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10764 		return KF_ARG_PTR_TO_CTX;
10765 
10766 	/* In this function, we verify the kfunc's BTF as per the argument type,
10767 	 * leaving the rest of the verification with respect to the register
10768 	 * type to our caller. When a set of conditions hold in the BTF type of
10769 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10770 	 */
10771 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10772 		return KF_ARG_PTR_TO_CTX;
10773 
10774 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10775 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10776 
10777 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10778 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10779 
10780 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10781 		return KF_ARG_PTR_TO_DYNPTR;
10782 
10783 	if (is_kfunc_arg_iter(meta, argno))
10784 		return KF_ARG_PTR_TO_ITER;
10785 
10786 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10787 		return KF_ARG_PTR_TO_LIST_HEAD;
10788 
10789 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10790 		return KF_ARG_PTR_TO_LIST_NODE;
10791 
10792 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10793 		return KF_ARG_PTR_TO_RB_ROOT;
10794 
10795 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10796 		return KF_ARG_PTR_TO_RB_NODE;
10797 
10798 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10799 		if (!btf_type_is_struct(ref_t)) {
10800 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10801 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10802 			return -EINVAL;
10803 		}
10804 		return KF_ARG_PTR_TO_BTF_ID;
10805 	}
10806 
10807 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10808 		return KF_ARG_PTR_TO_CALLBACK;
10809 
10810 
10811 	if (argno + 1 < nargs &&
10812 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10813 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10814 		arg_mem_size = true;
10815 
10816 	/* This is the catch all argument type of register types supported by
10817 	 * check_helper_mem_access. However, we only allow when argument type is
10818 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10819 	 * arg_mem_size is true, the pointer can be void *.
10820 	 */
10821 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10822 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10823 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10824 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10825 		return -EINVAL;
10826 	}
10827 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10828 }
10829 
10830 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10831 					struct bpf_reg_state *reg,
10832 					const struct btf_type *ref_t,
10833 					const char *ref_tname, u32 ref_id,
10834 					struct bpf_kfunc_call_arg_meta *meta,
10835 					int argno)
10836 {
10837 	const struct btf_type *reg_ref_t;
10838 	bool strict_type_match = false;
10839 	const struct btf *reg_btf;
10840 	const char *reg_ref_tname;
10841 	u32 reg_ref_id;
10842 
10843 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10844 		reg_btf = reg->btf;
10845 		reg_ref_id = reg->btf_id;
10846 	} else {
10847 		reg_btf = btf_vmlinux;
10848 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10849 	}
10850 
10851 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10852 	 * or releasing a reference, or are no-cast aliases. We do _not_
10853 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10854 	 * as we want to enable BPF programs to pass types that are bitwise
10855 	 * equivalent without forcing them to explicitly cast with something
10856 	 * like bpf_cast_to_kern_ctx().
10857 	 *
10858 	 * For example, say we had a type like the following:
10859 	 *
10860 	 * struct bpf_cpumask {
10861 	 *	cpumask_t cpumask;
10862 	 *	refcount_t usage;
10863 	 * };
10864 	 *
10865 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10866 	 * to a struct cpumask, so it would be safe to pass a struct
10867 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10868 	 *
10869 	 * The philosophy here is similar to how we allow scalars of different
10870 	 * types to be passed to kfuncs as long as the size is the same. The
10871 	 * only difference here is that we're simply allowing
10872 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10873 	 * resolve types.
10874 	 */
10875 	if (is_kfunc_acquire(meta) ||
10876 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10877 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10878 		strict_type_match = true;
10879 
10880 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10881 
10882 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10883 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10884 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10885 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10886 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10887 			btf_type_str(reg_ref_t), reg_ref_tname);
10888 		return -EINVAL;
10889 	}
10890 	return 0;
10891 }
10892 
10893 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10894 {
10895 	struct bpf_verifier_state *state = env->cur_state;
10896 	struct btf_record *rec = reg_btf_record(reg);
10897 
10898 	if (!state->active_lock.ptr) {
10899 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10900 		return -EFAULT;
10901 	}
10902 
10903 	if (type_flag(reg->type) & NON_OWN_REF) {
10904 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10905 		return -EFAULT;
10906 	}
10907 
10908 	reg->type |= NON_OWN_REF;
10909 	if (rec->refcount_off >= 0)
10910 		reg->type |= MEM_RCU;
10911 
10912 	return 0;
10913 }
10914 
10915 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10916 {
10917 	struct bpf_func_state *state, *unused;
10918 	struct bpf_reg_state *reg;
10919 	int i;
10920 
10921 	state = cur_func(env);
10922 
10923 	if (!ref_obj_id) {
10924 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10925 			     "owning -> non-owning conversion\n");
10926 		return -EFAULT;
10927 	}
10928 
10929 	for (i = 0; i < state->acquired_refs; i++) {
10930 		if (state->refs[i].id != ref_obj_id)
10931 			continue;
10932 
10933 		/* Clear ref_obj_id here so release_reference doesn't clobber
10934 		 * the whole reg
10935 		 */
10936 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10937 			if (reg->ref_obj_id == ref_obj_id) {
10938 				reg->ref_obj_id = 0;
10939 				ref_set_non_owning(env, reg);
10940 			}
10941 		}));
10942 		return 0;
10943 	}
10944 
10945 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10946 	return -EFAULT;
10947 }
10948 
10949 /* Implementation details:
10950  *
10951  * Each register points to some region of memory, which we define as an
10952  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10953  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10954  * allocation. The lock and the data it protects are colocated in the same
10955  * memory region.
10956  *
10957  * Hence, everytime a register holds a pointer value pointing to such
10958  * allocation, the verifier preserves a unique reg->id for it.
10959  *
10960  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10961  * bpf_spin_lock is called.
10962  *
10963  * To enable this, lock state in the verifier captures two values:
10964  *	active_lock.ptr = Register's type specific pointer
10965  *	active_lock.id  = A unique ID for each register pointer value
10966  *
10967  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10968  * supported register types.
10969  *
10970  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10971  * allocated objects is the reg->btf pointer.
10972  *
10973  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10974  * can establish the provenance of the map value statically for each distinct
10975  * lookup into such maps. They always contain a single map value hence unique
10976  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10977  *
10978  * So, in case of global variables, they use array maps with max_entries = 1,
10979  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10980  * into the same map value as max_entries is 1, as described above).
10981  *
10982  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10983  * outer map pointer (in verifier context), but each lookup into an inner map
10984  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10985  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10986  * will get different reg->id assigned to each lookup, hence different
10987  * active_lock.id.
10988  *
10989  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10990  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10991  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10992  */
10993 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10994 {
10995 	void *ptr;
10996 	u32 id;
10997 
10998 	switch ((int)reg->type) {
10999 	case PTR_TO_MAP_VALUE:
11000 		ptr = reg->map_ptr;
11001 		break;
11002 	case PTR_TO_BTF_ID | MEM_ALLOC:
11003 		ptr = reg->btf;
11004 		break;
11005 	default:
11006 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11007 		return -EFAULT;
11008 	}
11009 	id = reg->id;
11010 
11011 	if (!env->cur_state->active_lock.ptr)
11012 		return -EINVAL;
11013 	if (env->cur_state->active_lock.ptr != ptr ||
11014 	    env->cur_state->active_lock.id != id) {
11015 		verbose(env, "held lock and object are not in the same allocation\n");
11016 		return -EINVAL;
11017 	}
11018 	return 0;
11019 }
11020 
11021 static bool is_bpf_list_api_kfunc(u32 btf_id)
11022 {
11023 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11024 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11025 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11026 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11027 }
11028 
11029 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11030 {
11031 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11032 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11033 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11034 }
11035 
11036 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11037 {
11038 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11039 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11040 }
11041 
11042 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11043 {
11044 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11045 }
11046 
11047 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11048 {
11049 	return is_bpf_rbtree_api_kfunc(btf_id);
11050 }
11051 
11052 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11053 					  enum btf_field_type head_field_type,
11054 					  u32 kfunc_btf_id)
11055 {
11056 	bool ret;
11057 
11058 	switch (head_field_type) {
11059 	case BPF_LIST_HEAD:
11060 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11061 		break;
11062 	case BPF_RB_ROOT:
11063 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11064 		break;
11065 	default:
11066 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11067 			btf_field_type_name(head_field_type));
11068 		return false;
11069 	}
11070 
11071 	if (!ret)
11072 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11073 			btf_field_type_name(head_field_type));
11074 	return ret;
11075 }
11076 
11077 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11078 					  enum btf_field_type node_field_type,
11079 					  u32 kfunc_btf_id)
11080 {
11081 	bool ret;
11082 
11083 	switch (node_field_type) {
11084 	case BPF_LIST_NODE:
11085 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11086 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11087 		break;
11088 	case BPF_RB_NODE:
11089 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11090 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11091 		break;
11092 	default:
11093 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11094 			btf_field_type_name(node_field_type));
11095 		return false;
11096 	}
11097 
11098 	if (!ret)
11099 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11100 			btf_field_type_name(node_field_type));
11101 	return ret;
11102 }
11103 
11104 static int
11105 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11106 				   struct bpf_reg_state *reg, u32 regno,
11107 				   struct bpf_kfunc_call_arg_meta *meta,
11108 				   enum btf_field_type head_field_type,
11109 				   struct btf_field **head_field)
11110 {
11111 	const char *head_type_name;
11112 	struct btf_field *field;
11113 	struct btf_record *rec;
11114 	u32 head_off;
11115 
11116 	if (meta->btf != btf_vmlinux) {
11117 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11118 		return -EFAULT;
11119 	}
11120 
11121 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11122 		return -EFAULT;
11123 
11124 	head_type_name = btf_field_type_name(head_field_type);
11125 	if (!tnum_is_const(reg->var_off)) {
11126 		verbose(env,
11127 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11128 			regno, head_type_name);
11129 		return -EINVAL;
11130 	}
11131 
11132 	rec = reg_btf_record(reg);
11133 	head_off = reg->off + reg->var_off.value;
11134 	field = btf_record_find(rec, head_off, head_field_type);
11135 	if (!field) {
11136 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11137 		return -EINVAL;
11138 	}
11139 
11140 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11141 	if (check_reg_allocation_locked(env, reg)) {
11142 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11143 			rec->spin_lock_off, head_type_name);
11144 		return -EINVAL;
11145 	}
11146 
11147 	if (*head_field) {
11148 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11149 		return -EFAULT;
11150 	}
11151 	*head_field = field;
11152 	return 0;
11153 }
11154 
11155 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11156 					   struct bpf_reg_state *reg, u32 regno,
11157 					   struct bpf_kfunc_call_arg_meta *meta)
11158 {
11159 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11160 							  &meta->arg_list_head.field);
11161 }
11162 
11163 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11164 					     struct bpf_reg_state *reg, u32 regno,
11165 					     struct bpf_kfunc_call_arg_meta *meta)
11166 {
11167 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11168 							  &meta->arg_rbtree_root.field);
11169 }
11170 
11171 static int
11172 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11173 				   struct bpf_reg_state *reg, u32 regno,
11174 				   struct bpf_kfunc_call_arg_meta *meta,
11175 				   enum btf_field_type head_field_type,
11176 				   enum btf_field_type node_field_type,
11177 				   struct btf_field **node_field)
11178 {
11179 	const char *node_type_name;
11180 	const struct btf_type *et, *t;
11181 	struct btf_field *field;
11182 	u32 node_off;
11183 
11184 	if (meta->btf != btf_vmlinux) {
11185 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11186 		return -EFAULT;
11187 	}
11188 
11189 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11190 		return -EFAULT;
11191 
11192 	node_type_name = btf_field_type_name(node_field_type);
11193 	if (!tnum_is_const(reg->var_off)) {
11194 		verbose(env,
11195 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11196 			regno, node_type_name);
11197 		return -EINVAL;
11198 	}
11199 
11200 	node_off = reg->off + reg->var_off.value;
11201 	field = reg_find_field_offset(reg, node_off, node_field_type);
11202 	if (!field || field->offset != node_off) {
11203 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11204 		return -EINVAL;
11205 	}
11206 
11207 	field = *node_field;
11208 
11209 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11210 	t = btf_type_by_id(reg->btf, reg->btf_id);
11211 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11212 				  field->graph_root.value_btf_id, true)) {
11213 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11214 			"in struct %s, but arg is at offset=%d in struct %s\n",
11215 			btf_field_type_name(head_field_type),
11216 			btf_field_type_name(node_field_type),
11217 			field->graph_root.node_offset,
11218 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11219 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11220 		return -EINVAL;
11221 	}
11222 	meta->arg_btf = reg->btf;
11223 	meta->arg_btf_id = reg->btf_id;
11224 
11225 	if (node_off != field->graph_root.node_offset) {
11226 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11227 			node_off, btf_field_type_name(node_field_type),
11228 			field->graph_root.node_offset,
11229 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11230 		return -EINVAL;
11231 	}
11232 
11233 	return 0;
11234 }
11235 
11236 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11237 					   struct bpf_reg_state *reg, u32 regno,
11238 					   struct bpf_kfunc_call_arg_meta *meta)
11239 {
11240 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11241 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11242 						  &meta->arg_list_head.field);
11243 }
11244 
11245 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11246 					     struct bpf_reg_state *reg, u32 regno,
11247 					     struct bpf_kfunc_call_arg_meta *meta)
11248 {
11249 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11250 						  BPF_RB_ROOT, BPF_RB_NODE,
11251 						  &meta->arg_rbtree_root.field);
11252 }
11253 
11254 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11255 			    int insn_idx)
11256 {
11257 	const char *func_name = meta->func_name, *ref_tname;
11258 	const struct btf *btf = meta->btf;
11259 	const struct btf_param *args;
11260 	struct btf_record *rec;
11261 	u32 i, nargs;
11262 	int ret;
11263 
11264 	args = (const struct btf_param *)(meta->func_proto + 1);
11265 	nargs = btf_type_vlen(meta->func_proto);
11266 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11267 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11268 			MAX_BPF_FUNC_REG_ARGS);
11269 		return -EINVAL;
11270 	}
11271 
11272 	/* Check that BTF function arguments match actual types that the
11273 	 * verifier sees.
11274 	 */
11275 	for (i = 0; i < nargs; i++) {
11276 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11277 		const struct btf_type *t, *ref_t, *resolve_ret;
11278 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11279 		u32 regno = i + 1, ref_id, type_size;
11280 		bool is_ret_buf_sz = false;
11281 		int kf_arg_type;
11282 
11283 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11284 
11285 		if (is_kfunc_arg_ignore(btf, &args[i]))
11286 			continue;
11287 
11288 		if (btf_type_is_scalar(t)) {
11289 			if (reg->type != SCALAR_VALUE) {
11290 				verbose(env, "R%d is not a scalar\n", regno);
11291 				return -EINVAL;
11292 			}
11293 
11294 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11295 				if (meta->arg_constant.found) {
11296 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11297 					return -EFAULT;
11298 				}
11299 				if (!tnum_is_const(reg->var_off)) {
11300 					verbose(env, "R%d must be a known constant\n", regno);
11301 					return -EINVAL;
11302 				}
11303 				ret = mark_chain_precision(env, regno);
11304 				if (ret < 0)
11305 					return ret;
11306 				meta->arg_constant.found = true;
11307 				meta->arg_constant.value = reg->var_off.value;
11308 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11309 				meta->r0_rdonly = true;
11310 				is_ret_buf_sz = true;
11311 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11312 				is_ret_buf_sz = true;
11313 			}
11314 
11315 			if (is_ret_buf_sz) {
11316 				if (meta->r0_size) {
11317 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11318 					return -EINVAL;
11319 				}
11320 
11321 				if (!tnum_is_const(reg->var_off)) {
11322 					verbose(env, "R%d is not a const\n", regno);
11323 					return -EINVAL;
11324 				}
11325 
11326 				meta->r0_size = reg->var_off.value;
11327 				ret = mark_chain_precision(env, regno);
11328 				if (ret)
11329 					return ret;
11330 			}
11331 			continue;
11332 		}
11333 
11334 		if (!btf_type_is_ptr(t)) {
11335 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11336 			return -EINVAL;
11337 		}
11338 
11339 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11340 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11341 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11342 			return -EACCES;
11343 		}
11344 
11345 		if (reg->ref_obj_id) {
11346 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11347 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11348 					regno, reg->ref_obj_id,
11349 					meta->ref_obj_id);
11350 				return -EFAULT;
11351 			}
11352 			meta->ref_obj_id = reg->ref_obj_id;
11353 			if (is_kfunc_release(meta))
11354 				meta->release_regno = regno;
11355 		}
11356 
11357 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11358 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11359 
11360 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11361 		if (kf_arg_type < 0)
11362 			return kf_arg_type;
11363 
11364 		switch (kf_arg_type) {
11365 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11366 		case KF_ARG_PTR_TO_BTF_ID:
11367 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11368 				break;
11369 
11370 			if (!is_trusted_reg(reg)) {
11371 				if (!is_kfunc_rcu(meta)) {
11372 					verbose(env, "R%d must be referenced or trusted\n", regno);
11373 					return -EINVAL;
11374 				}
11375 				if (!is_rcu_reg(reg)) {
11376 					verbose(env, "R%d must be a rcu pointer\n", regno);
11377 					return -EINVAL;
11378 				}
11379 			}
11380 
11381 			fallthrough;
11382 		case KF_ARG_PTR_TO_CTX:
11383 			/* Trusted arguments have the same offset checks as release arguments */
11384 			arg_type |= OBJ_RELEASE;
11385 			break;
11386 		case KF_ARG_PTR_TO_DYNPTR:
11387 		case KF_ARG_PTR_TO_ITER:
11388 		case KF_ARG_PTR_TO_LIST_HEAD:
11389 		case KF_ARG_PTR_TO_LIST_NODE:
11390 		case KF_ARG_PTR_TO_RB_ROOT:
11391 		case KF_ARG_PTR_TO_RB_NODE:
11392 		case KF_ARG_PTR_TO_MEM:
11393 		case KF_ARG_PTR_TO_MEM_SIZE:
11394 		case KF_ARG_PTR_TO_CALLBACK:
11395 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11396 			/* Trusted by default */
11397 			break;
11398 		default:
11399 			WARN_ON_ONCE(1);
11400 			return -EFAULT;
11401 		}
11402 
11403 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11404 			arg_type |= OBJ_RELEASE;
11405 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11406 		if (ret < 0)
11407 			return ret;
11408 
11409 		switch (kf_arg_type) {
11410 		case KF_ARG_PTR_TO_CTX:
11411 			if (reg->type != PTR_TO_CTX) {
11412 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11413 				return -EINVAL;
11414 			}
11415 
11416 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11417 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11418 				if (ret < 0)
11419 					return -EINVAL;
11420 				meta->ret_btf_id  = ret;
11421 			}
11422 			break;
11423 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11424 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11425 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11426 				return -EINVAL;
11427 			}
11428 			if (!reg->ref_obj_id) {
11429 				verbose(env, "allocated object must be referenced\n");
11430 				return -EINVAL;
11431 			}
11432 			if (meta->btf == btf_vmlinux &&
11433 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11434 				meta->arg_btf = reg->btf;
11435 				meta->arg_btf_id = reg->btf_id;
11436 			}
11437 			break;
11438 		case KF_ARG_PTR_TO_DYNPTR:
11439 		{
11440 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11441 			int clone_ref_obj_id = 0;
11442 
11443 			if (reg->type != PTR_TO_STACK &&
11444 			    reg->type != CONST_PTR_TO_DYNPTR) {
11445 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11446 				return -EINVAL;
11447 			}
11448 
11449 			if (reg->type == CONST_PTR_TO_DYNPTR)
11450 				dynptr_arg_type |= MEM_RDONLY;
11451 
11452 			if (is_kfunc_arg_uninit(btf, &args[i]))
11453 				dynptr_arg_type |= MEM_UNINIT;
11454 
11455 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11456 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11457 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11458 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11459 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11460 				   (dynptr_arg_type & MEM_UNINIT)) {
11461 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11462 
11463 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11464 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11465 					return -EFAULT;
11466 				}
11467 
11468 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11469 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11470 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11471 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11472 					return -EFAULT;
11473 				}
11474 			}
11475 
11476 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11477 			if (ret < 0)
11478 				return ret;
11479 
11480 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11481 				int id = dynptr_id(env, reg);
11482 
11483 				if (id < 0) {
11484 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11485 					return id;
11486 				}
11487 				meta->initialized_dynptr.id = id;
11488 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11489 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11490 			}
11491 
11492 			break;
11493 		}
11494 		case KF_ARG_PTR_TO_ITER:
11495 			ret = process_iter_arg(env, regno, insn_idx, meta);
11496 			if (ret < 0)
11497 				return ret;
11498 			break;
11499 		case KF_ARG_PTR_TO_LIST_HEAD:
11500 			if (reg->type != PTR_TO_MAP_VALUE &&
11501 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11502 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11503 				return -EINVAL;
11504 			}
11505 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11506 				verbose(env, "allocated object must be referenced\n");
11507 				return -EINVAL;
11508 			}
11509 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11510 			if (ret < 0)
11511 				return ret;
11512 			break;
11513 		case KF_ARG_PTR_TO_RB_ROOT:
11514 			if (reg->type != PTR_TO_MAP_VALUE &&
11515 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11516 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11517 				return -EINVAL;
11518 			}
11519 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11520 				verbose(env, "allocated object must be referenced\n");
11521 				return -EINVAL;
11522 			}
11523 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11524 			if (ret < 0)
11525 				return ret;
11526 			break;
11527 		case KF_ARG_PTR_TO_LIST_NODE:
11528 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11529 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11530 				return -EINVAL;
11531 			}
11532 			if (!reg->ref_obj_id) {
11533 				verbose(env, "allocated object must be referenced\n");
11534 				return -EINVAL;
11535 			}
11536 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11537 			if (ret < 0)
11538 				return ret;
11539 			break;
11540 		case KF_ARG_PTR_TO_RB_NODE:
11541 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11542 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11543 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11544 					return -EINVAL;
11545 				}
11546 				if (in_rbtree_lock_required_cb(env)) {
11547 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11548 					return -EINVAL;
11549 				}
11550 			} else {
11551 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11552 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11553 					return -EINVAL;
11554 				}
11555 				if (!reg->ref_obj_id) {
11556 					verbose(env, "allocated object must be referenced\n");
11557 					return -EINVAL;
11558 				}
11559 			}
11560 
11561 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11562 			if (ret < 0)
11563 				return ret;
11564 			break;
11565 		case KF_ARG_PTR_TO_BTF_ID:
11566 			/* Only base_type is checked, further checks are done here */
11567 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11568 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11569 			    !reg2btf_ids[base_type(reg->type)]) {
11570 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11571 				verbose(env, "expected %s or socket\n",
11572 					reg_type_str(env, base_type(reg->type) |
11573 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11574 				return -EINVAL;
11575 			}
11576 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11577 			if (ret < 0)
11578 				return ret;
11579 			break;
11580 		case KF_ARG_PTR_TO_MEM:
11581 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11582 			if (IS_ERR(resolve_ret)) {
11583 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11584 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11585 				return -EINVAL;
11586 			}
11587 			ret = check_mem_reg(env, reg, regno, type_size);
11588 			if (ret < 0)
11589 				return ret;
11590 			break;
11591 		case KF_ARG_PTR_TO_MEM_SIZE:
11592 		{
11593 			struct bpf_reg_state *buff_reg = &regs[regno];
11594 			const struct btf_param *buff_arg = &args[i];
11595 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11596 			const struct btf_param *size_arg = &args[i + 1];
11597 
11598 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11599 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11600 				if (ret < 0) {
11601 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11602 					return ret;
11603 				}
11604 			}
11605 
11606 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11607 				if (meta->arg_constant.found) {
11608 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11609 					return -EFAULT;
11610 				}
11611 				if (!tnum_is_const(size_reg->var_off)) {
11612 					verbose(env, "R%d must be a known constant\n", regno + 1);
11613 					return -EINVAL;
11614 				}
11615 				meta->arg_constant.found = true;
11616 				meta->arg_constant.value = size_reg->var_off.value;
11617 			}
11618 
11619 			/* Skip next '__sz' or '__szk' argument */
11620 			i++;
11621 			break;
11622 		}
11623 		case KF_ARG_PTR_TO_CALLBACK:
11624 			if (reg->type != PTR_TO_FUNC) {
11625 				verbose(env, "arg%d expected pointer to func\n", i);
11626 				return -EINVAL;
11627 			}
11628 			meta->subprogno = reg->subprogno;
11629 			break;
11630 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11631 			if (!type_is_ptr_alloc_obj(reg->type)) {
11632 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11633 				return -EINVAL;
11634 			}
11635 			if (!type_is_non_owning_ref(reg->type))
11636 				meta->arg_owning_ref = true;
11637 
11638 			rec = reg_btf_record(reg);
11639 			if (!rec) {
11640 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11641 				return -EFAULT;
11642 			}
11643 
11644 			if (rec->refcount_off < 0) {
11645 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11646 				return -EINVAL;
11647 			}
11648 
11649 			meta->arg_btf = reg->btf;
11650 			meta->arg_btf_id = reg->btf_id;
11651 			break;
11652 		}
11653 	}
11654 
11655 	if (is_kfunc_release(meta) && !meta->release_regno) {
11656 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11657 			func_name);
11658 		return -EINVAL;
11659 	}
11660 
11661 	return 0;
11662 }
11663 
11664 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11665 			    struct bpf_insn *insn,
11666 			    struct bpf_kfunc_call_arg_meta *meta,
11667 			    const char **kfunc_name)
11668 {
11669 	const struct btf_type *func, *func_proto;
11670 	u32 func_id, *kfunc_flags;
11671 	const char *func_name;
11672 	struct btf *desc_btf;
11673 
11674 	if (kfunc_name)
11675 		*kfunc_name = NULL;
11676 
11677 	if (!insn->imm)
11678 		return -EINVAL;
11679 
11680 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11681 	if (IS_ERR(desc_btf))
11682 		return PTR_ERR(desc_btf);
11683 
11684 	func_id = insn->imm;
11685 	func = btf_type_by_id(desc_btf, func_id);
11686 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11687 	if (kfunc_name)
11688 		*kfunc_name = func_name;
11689 	func_proto = btf_type_by_id(desc_btf, func->type);
11690 
11691 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11692 	if (!kfunc_flags) {
11693 		return -EACCES;
11694 	}
11695 
11696 	memset(meta, 0, sizeof(*meta));
11697 	meta->btf = desc_btf;
11698 	meta->func_id = func_id;
11699 	meta->kfunc_flags = *kfunc_flags;
11700 	meta->func_proto = func_proto;
11701 	meta->func_name = func_name;
11702 
11703 	return 0;
11704 }
11705 
11706 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11707 			    int *insn_idx_p)
11708 {
11709 	const struct btf_type *t, *ptr_type;
11710 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11711 	struct bpf_reg_state *regs = cur_regs(env);
11712 	const char *func_name, *ptr_type_name;
11713 	bool sleepable, rcu_lock, rcu_unlock;
11714 	struct bpf_kfunc_call_arg_meta meta;
11715 	struct bpf_insn_aux_data *insn_aux;
11716 	int err, insn_idx = *insn_idx_p;
11717 	const struct btf_param *args;
11718 	const struct btf_type *ret_t;
11719 	struct btf *desc_btf;
11720 
11721 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11722 	if (!insn->imm)
11723 		return 0;
11724 
11725 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11726 	if (err == -EACCES && func_name)
11727 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11728 	if (err)
11729 		return err;
11730 	desc_btf = meta.btf;
11731 	insn_aux = &env->insn_aux_data[insn_idx];
11732 
11733 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11734 
11735 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11736 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11737 		return -EACCES;
11738 	}
11739 
11740 	sleepable = is_kfunc_sleepable(&meta);
11741 	if (sleepable && !env->prog->aux->sleepable) {
11742 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11743 		return -EACCES;
11744 	}
11745 
11746 	/* Check the arguments */
11747 	err = check_kfunc_args(env, &meta, insn_idx);
11748 	if (err < 0)
11749 		return err;
11750 
11751 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11752 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11753 					 set_rbtree_add_callback_state);
11754 		if (err) {
11755 			verbose(env, "kfunc %s#%d failed callback verification\n",
11756 				func_name, meta.func_id);
11757 			return err;
11758 		}
11759 	}
11760 
11761 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11762 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11763 
11764 	if (env->cur_state->active_rcu_lock) {
11765 		struct bpf_func_state *state;
11766 		struct bpf_reg_state *reg;
11767 
11768 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11769 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11770 			return -EACCES;
11771 		}
11772 
11773 		if (rcu_lock) {
11774 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11775 			return -EINVAL;
11776 		} else if (rcu_unlock) {
11777 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11778 				if (reg->type & MEM_RCU) {
11779 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11780 					reg->type |= PTR_UNTRUSTED;
11781 				}
11782 			}));
11783 			env->cur_state->active_rcu_lock = false;
11784 		} else if (sleepable) {
11785 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11786 			return -EACCES;
11787 		}
11788 	} else if (rcu_lock) {
11789 		env->cur_state->active_rcu_lock = true;
11790 	} else if (rcu_unlock) {
11791 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11792 		return -EINVAL;
11793 	}
11794 
11795 	/* In case of release function, we get register number of refcounted
11796 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11797 	 */
11798 	if (meta.release_regno) {
11799 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11800 		if (err) {
11801 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11802 				func_name, meta.func_id);
11803 			return err;
11804 		}
11805 	}
11806 
11807 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11808 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11809 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11810 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11811 		insn_aux->insert_off = regs[BPF_REG_2].off;
11812 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11813 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11814 		if (err) {
11815 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11816 				func_name, meta.func_id);
11817 			return err;
11818 		}
11819 
11820 		err = release_reference(env, release_ref_obj_id);
11821 		if (err) {
11822 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11823 				func_name, meta.func_id);
11824 			return err;
11825 		}
11826 	}
11827 
11828 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11829 		mark_reg_not_init(env, regs, caller_saved[i]);
11830 
11831 	/* Check return type */
11832 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11833 
11834 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11835 		/* Only exception is bpf_obj_new_impl */
11836 		if (meta.btf != btf_vmlinux ||
11837 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11838 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11839 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11840 			return -EINVAL;
11841 		}
11842 	}
11843 
11844 	if (btf_type_is_scalar(t)) {
11845 		mark_reg_unknown(env, regs, BPF_REG_0);
11846 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11847 	} else if (btf_type_is_ptr(t)) {
11848 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11849 
11850 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11851 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11852 				struct btf *ret_btf;
11853 				u32 ret_btf_id;
11854 
11855 				if (unlikely(!bpf_global_ma_set))
11856 					return -ENOMEM;
11857 
11858 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11859 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11860 					return -EINVAL;
11861 				}
11862 
11863 				ret_btf = env->prog->aux->btf;
11864 				ret_btf_id = meta.arg_constant.value;
11865 
11866 				/* This may be NULL due to user not supplying a BTF */
11867 				if (!ret_btf) {
11868 					verbose(env, "bpf_obj_new requires prog BTF\n");
11869 					return -EINVAL;
11870 				}
11871 
11872 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11873 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11874 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11875 					return -EINVAL;
11876 				}
11877 
11878 				mark_reg_known_zero(env, regs, BPF_REG_0);
11879 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11880 				regs[BPF_REG_0].btf = ret_btf;
11881 				regs[BPF_REG_0].btf_id = ret_btf_id;
11882 
11883 				insn_aux->obj_new_size = ret_t->size;
11884 				insn_aux->kptr_struct_meta =
11885 					btf_find_struct_meta(ret_btf, ret_btf_id);
11886 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11887 				mark_reg_known_zero(env, regs, BPF_REG_0);
11888 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11889 				regs[BPF_REG_0].btf = meta.arg_btf;
11890 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11891 
11892 				insn_aux->kptr_struct_meta =
11893 					btf_find_struct_meta(meta.arg_btf,
11894 							     meta.arg_btf_id);
11895 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11896 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11897 				struct btf_field *field = meta.arg_list_head.field;
11898 
11899 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11900 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11901 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11902 				struct btf_field *field = meta.arg_rbtree_root.field;
11903 
11904 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11905 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11906 				mark_reg_known_zero(env, regs, BPF_REG_0);
11907 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11908 				regs[BPF_REG_0].btf = desc_btf;
11909 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11910 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11911 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11912 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11913 					verbose(env,
11914 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11915 					return -EINVAL;
11916 				}
11917 
11918 				mark_reg_known_zero(env, regs, BPF_REG_0);
11919 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11920 				regs[BPF_REG_0].btf = desc_btf;
11921 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11922 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11923 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11924 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11925 
11926 				mark_reg_known_zero(env, regs, BPF_REG_0);
11927 
11928 				if (!meta.arg_constant.found) {
11929 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11930 					return -EFAULT;
11931 				}
11932 
11933 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11934 
11935 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11936 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11937 
11938 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11939 					regs[BPF_REG_0].type |= MEM_RDONLY;
11940 				} else {
11941 					/* this will set env->seen_direct_write to true */
11942 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11943 						verbose(env, "the prog does not allow writes to packet data\n");
11944 						return -EINVAL;
11945 					}
11946 				}
11947 
11948 				if (!meta.initialized_dynptr.id) {
11949 					verbose(env, "verifier internal error: no dynptr id\n");
11950 					return -EFAULT;
11951 				}
11952 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11953 
11954 				/* we don't need to set BPF_REG_0's ref obj id
11955 				 * because packet slices are not refcounted (see
11956 				 * dynptr_type_refcounted)
11957 				 */
11958 			} else {
11959 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11960 					meta.func_name);
11961 				return -EFAULT;
11962 			}
11963 		} else if (!__btf_type_is_struct(ptr_type)) {
11964 			if (!meta.r0_size) {
11965 				__u32 sz;
11966 
11967 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11968 					meta.r0_size = sz;
11969 					meta.r0_rdonly = true;
11970 				}
11971 			}
11972 			if (!meta.r0_size) {
11973 				ptr_type_name = btf_name_by_offset(desc_btf,
11974 								   ptr_type->name_off);
11975 				verbose(env,
11976 					"kernel function %s returns pointer type %s %s is not supported\n",
11977 					func_name,
11978 					btf_type_str(ptr_type),
11979 					ptr_type_name);
11980 				return -EINVAL;
11981 			}
11982 
11983 			mark_reg_known_zero(env, regs, BPF_REG_0);
11984 			regs[BPF_REG_0].type = PTR_TO_MEM;
11985 			regs[BPF_REG_0].mem_size = meta.r0_size;
11986 
11987 			if (meta.r0_rdonly)
11988 				regs[BPF_REG_0].type |= MEM_RDONLY;
11989 
11990 			/* Ensures we don't access the memory after a release_reference() */
11991 			if (meta.ref_obj_id)
11992 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11993 		} else {
11994 			mark_reg_known_zero(env, regs, BPF_REG_0);
11995 			regs[BPF_REG_0].btf = desc_btf;
11996 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11997 			regs[BPF_REG_0].btf_id = ptr_type_id;
11998 		}
11999 
12000 		if (is_kfunc_ret_null(&meta)) {
12001 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12002 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12003 			regs[BPF_REG_0].id = ++env->id_gen;
12004 		}
12005 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12006 		if (is_kfunc_acquire(&meta)) {
12007 			int id = acquire_reference_state(env, insn_idx);
12008 
12009 			if (id < 0)
12010 				return id;
12011 			if (is_kfunc_ret_null(&meta))
12012 				regs[BPF_REG_0].id = id;
12013 			regs[BPF_REG_0].ref_obj_id = id;
12014 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12015 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12016 		}
12017 
12018 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12019 			regs[BPF_REG_0].id = ++env->id_gen;
12020 	} else if (btf_type_is_void(t)) {
12021 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12022 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12023 				insn_aux->kptr_struct_meta =
12024 					btf_find_struct_meta(meta.arg_btf,
12025 							     meta.arg_btf_id);
12026 			}
12027 		}
12028 	}
12029 
12030 	nargs = btf_type_vlen(meta.func_proto);
12031 	args = (const struct btf_param *)(meta.func_proto + 1);
12032 	for (i = 0; i < nargs; i++) {
12033 		u32 regno = i + 1;
12034 
12035 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12036 		if (btf_type_is_ptr(t))
12037 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12038 		else
12039 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12040 			mark_btf_func_reg_size(env, regno, t->size);
12041 	}
12042 
12043 	if (is_iter_next_kfunc(&meta)) {
12044 		err = process_iter_next_call(env, insn_idx, &meta);
12045 		if (err)
12046 			return err;
12047 	}
12048 
12049 	return 0;
12050 }
12051 
12052 static bool signed_add_overflows(s64 a, s64 b)
12053 {
12054 	/* Do the add in u64, where overflow is well-defined */
12055 	s64 res = (s64)((u64)a + (u64)b);
12056 
12057 	if (b < 0)
12058 		return res > a;
12059 	return res < a;
12060 }
12061 
12062 static bool signed_add32_overflows(s32 a, s32 b)
12063 {
12064 	/* Do the add in u32, where overflow is well-defined */
12065 	s32 res = (s32)((u32)a + (u32)b);
12066 
12067 	if (b < 0)
12068 		return res > a;
12069 	return res < a;
12070 }
12071 
12072 static bool signed_sub_overflows(s64 a, s64 b)
12073 {
12074 	/* Do the sub in u64, where overflow is well-defined */
12075 	s64 res = (s64)((u64)a - (u64)b);
12076 
12077 	if (b < 0)
12078 		return res < a;
12079 	return res > a;
12080 }
12081 
12082 static bool signed_sub32_overflows(s32 a, s32 b)
12083 {
12084 	/* Do the sub in u32, where overflow is well-defined */
12085 	s32 res = (s32)((u32)a - (u32)b);
12086 
12087 	if (b < 0)
12088 		return res < a;
12089 	return res > a;
12090 }
12091 
12092 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12093 				  const struct bpf_reg_state *reg,
12094 				  enum bpf_reg_type type)
12095 {
12096 	bool known = tnum_is_const(reg->var_off);
12097 	s64 val = reg->var_off.value;
12098 	s64 smin = reg->smin_value;
12099 
12100 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12101 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12102 			reg_type_str(env, type), val);
12103 		return false;
12104 	}
12105 
12106 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12107 		verbose(env, "%s pointer offset %d is not allowed\n",
12108 			reg_type_str(env, type), reg->off);
12109 		return false;
12110 	}
12111 
12112 	if (smin == S64_MIN) {
12113 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12114 			reg_type_str(env, type));
12115 		return false;
12116 	}
12117 
12118 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12119 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12120 			smin, reg_type_str(env, type));
12121 		return false;
12122 	}
12123 
12124 	return true;
12125 }
12126 
12127 enum {
12128 	REASON_BOUNDS	= -1,
12129 	REASON_TYPE	= -2,
12130 	REASON_PATHS	= -3,
12131 	REASON_LIMIT	= -4,
12132 	REASON_STACK	= -5,
12133 };
12134 
12135 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12136 			      u32 *alu_limit, bool mask_to_left)
12137 {
12138 	u32 max = 0, ptr_limit = 0;
12139 
12140 	switch (ptr_reg->type) {
12141 	case PTR_TO_STACK:
12142 		/* Offset 0 is out-of-bounds, but acceptable start for the
12143 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12144 		 * offset where we would need to deal with min/max bounds is
12145 		 * currently prohibited for unprivileged.
12146 		 */
12147 		max = MAX_BPF_STACK + mask_to_left;
12148 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12149 		break;
12150 	case PTR_TO_MAP_VALUE:
12151 		max = ptr_reg->map_ptr->value_size;
12152 		ptr_limit = (mask_to_left ?
12153 			     ptr_reg->smin_value :
12154 			     ptr_reg->umax_value) + ptr_reg->off;
12155 		break;
12156 	default:
12157 		return REASON_TYPE;
12158 	}
12159 
12160 	if (ptr_limit >= max)
12161 		return REASON_LIMIT;
12162 	*alu_limit = ptr_limit;
12163 	return 0;
12164 }
12165 
12166 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12167 				    const struct bpf_insn *insn)
12168 {
12169 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12170 }
12171 
12172 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12173 				       u32 alu_state, u32 alu_limit)
12174 {
12175 	/* If we arrived here from different branches with different
12176 	 * state or limits to sanitize, then this won't work.
12177 	 */
12178 	if (aux->alu_state &&
12179 	    (aux->alu_state != alu_state ||
12180 	     aux->alu_limit != alu_limit))
12181 		return REASON_PATHS;
12182 
12183 	/* Corresponding fixup done in do_misc_fixups(). */
12184 	aux->alu_state = alu_state;
12185 	aux->alu_limit = alu_limit;
12186 	return 0;
12187 }
12188 
12189 static int sanitize_val_alu(struct bpf_verifier_env *env,
12190 			    struct bpf_insn *insn)
12191 {
12192 	struct bpf_insn_aux_data *aux = cur_aux(env);
12193 
12194 	if (can_skip_alu_sanitation(env, insn))
12195 		return 0;
12196 
12197 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12198 }
12199 
12200 static bool sanitize_needed(u8 opcode)
12201 {
12202 	return opcode == BPF_ADD || opcode == BPF_SUB;
12203 }
12204 
12205 struct bpf_sanitize_info {
12206 	struct bpf_insn_aux_data aux;
12207 	bool mask_to_left;
12208 };
12209 
12210 static struct bpf_verifier_state *
12211 sanitize_speculative_path(struct bpf_verifier_env *env,
12212 			  const struct bpf_insn *insn,
12213 			  u32 next_idx, u32 curr_idx)
12214 {
12215 	struct bpf_verifier_state *branch;
12216 	struct bpf_reg_state *regs;
12217 
12218 	branch = push_stack(env, next_idx, curr_idx, true);
12219 	if (branch && insn) {
12220 		regs = branch->frame[branch->curframe]->regs;
12221 		if (BPF_SRC(insn->code) == BPF_K) {
12222 			mark_reg_unknown(env, regs, insn->dst_reg);
12223 		} else if (BPF_SRC(insn->code) == BPF_X) {
12224 			mark_reg_unknown(env, regs, insn->dst_reg);
12225 			mark_reg_unknown(env, regs, insn->src_reg);
12226 		}
12227 	}
12228 	return branch;
12229 }
12230 
12231 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12232 			    struct bpf_insn *insn,
12233 			    const struct bpf_reg_state *ptr_reg,
12234 			    const struct bpf_reg_state *off_reg,
12235 			    struct bpf_reg_state *dst_reg,
12236 			    struct bpf_sanitize_info *info,
12237 			    const bool commit_window)
12238 {
12239 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12240 	struct bpf_verifier_state *vstate = env->cur_state;
12241 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12242 	bool off_is_neg = off_reg->smin_value < 0;
12243 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12244 	u8 opcode = BPF_OP(insn->code);
12245 	u32 alu_state, alu_limit;
12246 	struct bpf_reg_state tmp;
12247 	bool ret;
12248 	int err;
12249 
12250 	if (can_skip_alu_sanitation(env, insn))
12251 		return 0;
12252 
12253 	/* We already marked aux for masking from non-speculative
12254 	 * paths, thus we got here in the first place. We only care
12255 	 * to explore bad access from here.
12256 	 */
12257 	if (vstate->speculative)
12258 		goto do_sim;
12259 
12260 	if (!commit_window) {
12261 		if (!tnum_is_const(off_reg->var_off) &&
12262 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12263 			return REASON_BOUNDS;
12264 
12265 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12266 				     (opcode == BPF_SUB && !off_is_neg);
12267 	}
12268 
12269 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12270 	if (err < 0)
12271 		return err;
12272 
12273 	if (commit_window) {
12274 		/* In commit phase we narrow the masking window based on
12275 		 * the observed pointer move after the simulated operation.
12276 		 */
12277 		alu_state = info->aux.alu_state;
12278 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12279 	} else {
12280 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12281 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12282 		alu_state |= ptr_is_dst_reg ?
12283 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12284 
12285 		/* Limit pruning on unknown scalars to enable deep search for
12286 		 * potential masking differences from other program paths.
12287 		 */
12288 		if (!off_is_imm)
12289 			env->explore_alu_limits = true;
12290 	}
12291 
12292 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12293 	if (err < 0)
12294 		return err;
12295 do_sim:
12296 	/* If we're in commit phase, we're done here given we already
12297 	 * pushed the truncated dst_reg into the speculative verification
12298 	 * stack.
12299 	 *
12300 	 * Also, when register is a known constant, we rewrite register-based
12301 	 * operation to immediate-based, and thus do not need masking (and as
12302 	 * a consequence, do not need to simulate the zero-truncation either).
12303 	 */
12304 	if (commit_window || off_is_imm)
12305 		return 0;
12306 
12307 	/* Simulate and find potential out-of-bounds access under
12308 	 * speculative execution from truncation as a result of
12309 	 * masking when off was not within expected range. If off
12310 	 * sits in dst, then we temporarily need to move ptr there
12311 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12312 	 * for cases where we use K-based arithmetic in one direction
12313 	 * and truncated reg-based in the other in order to explore
12314 	 * bad access.
12315 	 */
12316 	if (!ptr_is_dst_reg) {
12317 		tmp = *dst_reg;
12318 		copy_register_state(dst_reg, ptr_reg);
12319 	}
12320 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12321 					env->insn_idx);
12322 	if (!ptr_is_dst_reg && ret)
12323 		*dst_reg = tmp;
12324 	return !ret ? REASON_STACK : 0;
12325 }
12326 
12327 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12328 {
12329 	struct bpf_verifier_state *vstate = env->cur_state;
12330 
12331 	/* If we simulate paths under speculation, we don't update the
12332 	 * insn as 'seen' such that when we verify unreachable paths in
12333 	 * the non-speculative domain, sanitize_dead_code() can still
12334 	 * rewrite/sanitize them.
12335 	 */
12336 	if (!vstate->speculative)
12337 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12338 }
12339 
12340 static int sanitize_err(struct bpf_verifier_env *env,
12341 			const struct bpf_insn *insn, int reason,
12342 			const struct bpf_reg_state *off_reg,
12343 			const struct bpf_reg_state *dst_reg)
12344 {
12345 	static const char *err = "pointer arithmetic with it prohibited for !root";
12346 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12347 	u32 dst = insn->dst_reg, src = insn->src_reg;
12348 
12349 	switch (reason) {
12350 	case REASON_BOUNDS:
12351 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12352 			off_reg == dst_reg ? dst : src, err);
12353 		break;
12354 	case REASON_TYPE:
12355 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12356 			off_reg == dst_reg ? src : dst, err);
12357 		break;
12358 	case REASON_PATHS:
12359 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12360 			dst, op, err);
12361 		break;
12362 	case REASON_LIMIT:
12363 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12364 			dst, op, err);
12365 		break;
12366 	case REASON_STACK:
12367 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12368 			dst, err);
12369 		break;
12370 	default:
12371 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12372 			reason);
12373 		break;
12374 	}
12375 
12376 	return -EACCES;
12377 }
12378 
12379 /* check that stack access falls within stack limits and that 'reg' doesn't
12380  * have a variable offset.
12381  *
12382  * Variable offset is prohibited for unprivileged mode for simplicity since it
12383  * requires corresponding support in Spectre masking for stack ALU.  See also
12384  * retrieve_ptr_limit().
12385  *
12386  *
12387  * 'off' includes 'reg->off'.
12388  */
12389 static int check_stack_access_for_ptr_arithmetic(
12390 				struct bpf_verifier_env *env,
12391 				int regno,
12392 				const struct bpf_reg_state *reg,
12393 				int off)
12394 {
12395 	if (!tnum_is_const(reg->var_off)) {
12396 		char tn_buf[48];
12397 
12398 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12399 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12400 			regno, tn_buf, off);
12401 		return -EACCES;
12402 	}
12403 
12404 	if (off >= 0 || off < -MAX_BPF_STACK) {
12405 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12406 			"prohibited for !root; off=%d\n", regno, off);
12407 		return -EACCES;
12408 	}
12409 
12410 	return 0;
12411 }
12412 
12413 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12414 				 const struct bpf_insn *insn,
12415 				 const struct bpf_reg_state *dst_reg)
12416 {
12417 	u32 dst = insn->dst_reg;
12418 
12419 	/* For unprivileged we require that resulting offset must be in bounds
12420 	 * in order to be able to sanitize access later on.
12421 	 */
12422 	if (env->bypass_spec_v1)
12423 		return 0;
12424 
12425 	switch (dst_reg->type) {
12426 	case PTR_TO_STACK:
12427 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12428 					dst_reg->off + dst_reg->var_off.value))
12429 			return -EACCES;
12430 		break;
12431 	case PTR_TO_MAP_VALUE:
12432 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12433 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12434 				"prohibited for !root\n", dst);
12435 			return -EACCES;
12436 		}
12437 		break;
12438 	default:
12439 		break;
12440 	}
12441 
12442 	return 0;
12443 }
12444 
12445 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12446  * Caller should also handle BPF_MOV case separately.
12447  * If we return -EACCES, caller may want to try again treating pointer as a
12448  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12449  */
12450 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12451 				   struct bpf_insn *insn,
12452 				   const struct bpf_reg_state *ptr_reg,
12453 				   const struct bpf_reg_state *off_reg)
12454 {
12455 	struct bpf_verifier_state *vstate = env->cur_state;
12456 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12457 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12458 	bool known = tnum_is_const(off_reg->var_off);
12459 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12460 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12461 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12462 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12463 	struct bpf_sanitize_info info = {};
12464 	u8 opcode = BPF_OP(insn->code);
12465 	u32 dst = insn->dst_reg;
12466 	int ret;
12467 
12468 	dst_reg = &regs[dst];
12469 
12470 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12471 	    smin_val > smax_val || umin_val > umax_val) {
12472 		/* Taint dst register if offset had invalid bounds derived from
12473 		 * e.g. dead branches.
12474 		 */
12475 		__mark_reg_unknown(env, dst_reg);
12476 		return 0;
12477 	}
12478 
12479 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12480 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12481 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12482 			__mark_reg_unknown(env, dst_reg);
12483 			return 0;
12484 		}
12485 
12486 		verbose(env,
12487 			"R%d 32-bit pointer arithmetic prohibited\n",
12488 			dst);
12489 		return -EACCES;
12490 	}
12491 
12492 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12493 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12494 			dst, reg_type_str(env, ptr_reg->type));
12495 		return -EACCES;
12496 	}
12497 
12498 	switch (base_type(ptr_reg->type)) {
12499 	case PTR_TO_FLOW_KEYS:
12500 		if (known)
12501 			break;
12502 		fallthrough;
12503 	case CONST_PTR_TO_MAP:
12504 		/* smin_val represents the known value */
12505 		if (known && smin_val == 0 && opcode == BPF_ADD)
12506 			break;
12507 		fallthrough;
12508 	case PTR_TO_PACKET_END:
12509 	case PTR_TO_SOCKET:
12510 	case PTR_TO_SOCK_COMMON:
12511 	case PTR_TO_TCP_SOCK:
12512 	case PTR_TO_XDP_SOCK:
12513 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12514 			dst, reg_type_str(env, ptr_reg->type));
12515 		return -EACCES;
12516 	default:
12517 		break;
12518 	}
12519 
12520 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12521 	 * The id may be overwritten later if we create a new variable offset.
12522 	 */
12523 	dst_reg->type = ptr_reg->type;
12524 	dst_reg->id = ptr_reg->id;
12525 
12526 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12527 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12528 		return -EINVAL;
12529 
12530 	/* pointer types do not carry 32-bit bounds at the moment. */
12531 	__mark_reg32_unbounded(dst_reg);
12532 
12533 	if (sanitize_needed(opcode)) {
12534 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12535 				       &info, false);
12536 		if (ret < 0)
12537 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12538 	}
12539 
12540 	switch (opcode) {
12541 	case BPF_ADD:
12542 		/* We can take a fixed offset as long as it doesn't overflow
12543 		 * the s32 'off' field
12544 		 */
12545 		if (known && (ptr_reg->off + smin_val ==
12546 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12547 			/* pointer += K.  Accumulate it into fixed offset */
12548 			dst_reg->smin_value = smin_ptr;
12549 			dst_reg->smax_value = smax_ptr;
12550 			dst_reg->umin_value = umin_ptr;
12551 			dst_reg->umax_value = umax_ptr;
12552 			dst_reg->var_off = ptr_reg->var_off;
12553 			dst_reg->off = ptr_reg->off + smin_val;
12554 			dst_reg->raw = ptr_reg->raw;
12555 			break;
12556 		}
12557 		/* A new variable offset is created.  Note that off_reg->off
12558 		 * == 0, since it's a scalar.
12559 		 * dst_reg gets the pointer type and since some positive
12560 		 * integer value was added to the pointer, give it a new 'id'
12561 		 * if it's a PTR_TO_PACKET.
12562 		 * this creates a new 'base' pointer, off_reg (variable) gets
12563 		 * added into the variable offset, and we copy the fixed offset
12564 		 * from ptr_reg.
12565 		 */
12566 		if (signed_add_overflows(smin_ptr, smin_val) ||
12567 		    signed_add_overflows(smax_ptr, smax_val)) {
12568 			dst_reg->smin_value = S64_MIN;
12569 			dst_reg->smax_value = S64_MAX;
12570 		} else {
12571 			dst_reg->smin_value = smin_ptr + smin_val;
12572 			dst_reg->smax_value = smax_ptr + smax_val;
12573 		}
12574 		if (umin_ptr + umin_val < umin_ptr ||
12575 		    umax_ptr + umax_val < umax_ptr) {
12576 			dst_reg->umin_value = 0;
12577 			dst_reg->umax_value = U64_MAX;
12578 		} else {
12579 			dst_reg->umin_value = umin_ptr + umin_val;
12580 			dst_reg->umax_value = umax_ptr + umax_val;
12581 		}
12582 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12583 		dst_reg->off = ptr_reg->off;
12584 		dst_reg->raw = ptr_reg->raw;
12585 		if (reg_is_pkt_pointer(ptr_reg)) {
12586 			dst_reg->id = ++env->id_gen;
12587 			/* something was added to pkt_ptr, set range to zero */
12588 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12589 		}
12590 		break;
12591 	case BPF_SUB:
12592 		if (dst_reg == off_reg) {
12593 			/* scalar -= pointer.  Creates an unknown scalar */
12594 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12595 				dst);
12596 			return -EACCES;
12597 		}
12598 		/* We don't allow subtraction from FP, because (according to
12599 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12600 		 * be able to deal with it.
12601 		 */
12602 		if (ptr_reg->type == PTR_TO_STACK) {
12603 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12604 				dst);
12605 			return -EACCES;
12606 		}
12607 		if (known && (ptr_reg->off - smin_val ==
12608 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12609 			/* pointer -= K.  Subtract it from fixed offset */
12610 			dst_reg->smin_value = smin_ptr;
12611 			dst_reg->smax_value = smax_ptr;
12612 			dst_reg->umin_value = umin_ptr;
12613 			dst_reg->umax_value = umax_ptr;
12614 			dst_reg->var_off = ptr_reg->var_off;
12615 			dst_reg->id = ptr_reg->id;
12616 			dst_reg->off = ptr_reg->off - smin_val;
12617 			dst_reg->raw = ptr_reg->raw;
12618 			break;
12619 		}
12620 		/* A new variable offset is created.  If the subtrahend is known
12621 		 * nonnegative, then any reg->range we had before is still good.
12622 		 */
12623 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12624 		    signed_sub_overflows(smax_ptr, smin_val)) {
12625 			/* Overflow possible, we know nothing */
12626 			dst_reg->smin_value = S64_MIN;
12627 			dst_reg->smax_value = S64_MAX;
12628 		} else {
12629 			dst_reg->smin_value = smin_ptr - smax_val;
12630 			dst_reg->smax_value = smax_ptr - smin_val;
12631 		}
12632 		if (umin_ptr < umax_val) {
12633 			/* Overflow possible, we know nothing */
12634 			dst_reg->umin_value = 0;
12635 			dst_reg->umax_value = U64_MAX;
12636 		} else {
12637 			/* Cannot overflow (as long as bounds are consistent) */
12638 			dst_reg->umin_value = umin_ptr - umax_val;
12639 			dst_reg->umax_value = umax_ptr - umin_val;
12640 		}
12641 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12642 		dst_reg->off = ptr_reg->off;
12643 		dst_reg->raw = ptr_reg->raw;
12644 		if (reg_is_pkt_pointer(ptr_reg)) {
12645 			dst_reg->id = ++env->id_gen;
12646 			/* something was added to pkt_ptr, set range to zero */
12647 			if (smin_val < 0)
12648 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12649 		}
12650 		break;
12651 	case BPF_AND:
12652 	case BPF_OR:
12653 	case BPF_XOR:
12654 		/* bitwise ops on pointers are troublesome, prohibit. */
12655 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12656 			dst, bpf_alu_string[opcode >> 4]);
12657 		return -EACCES;
12658 	default:
12659 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12660 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12661 			dst, bpf_alu_string[opcode >> 4]);
12662 		return -EACCES;
12663 	}
12664 
12665 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12666 		return -EINVAL;
12667 	reg_bounds_sync(dst_reg);
12668 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12669 		return -EACCES;
12670 	if (sanitize_needed(opcode)) {
12671 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12672 				       &info, true);
12673 		if (ret < 0)
12674 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12675 	}
12676 
12677 	return 0;
12678 }
12679 
12680 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12681 				 struct bpf_reg_state *src_reg)
12682 {
12683 	s32 smin_val = src_reg->s32_min_value;
12684 	s32 smax_val = src_reg->s32_max_value;
12685 	u32 umin_val = src_reg->u32_min_value;
12686 	u32 umax_val = src_reg->u32_max_value;
12687 
12688 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12689 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12690 		dst_reg->s32_min_value = S32_MIN;
12691 		dst_reg->s32_max_value = S32_MAX;
12692 	} else {
12693 		dst_reg->s32_min_value += smin_val;
12694 		dst_reg->s32_max_value += smax_val;
12695 	}
12696 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12697 	    dst_reg->u32_max_value + umax_val < umax_val) {
12698 		dst_reg->u32_min_value = 0;
12699 		dst_reg->u32_max_value = U32_MAX;
12700 	} else {
12701 		dst_reg->u32_min_value += umin_val;
12702 		dst_reg->u32_max_value += umax_val;
12703 	}
12704 }
12705 
12706 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12707 			       struct bpf_reg_state *src_reg)
12708 {
12709 	s64 smin_val = src_reg->smin_value;
12710 	s64 smax_val = src_reg->smax_value;
12711 	u64 umin_val = src_reg->umin_value;
12712 	u64 umax_val = src_reg->umax_value;
12713 
12714 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12715 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12716 		dst_reg->smin_value = S64_MIN;
12717 		dst_reg->smax_value = S64_MAX;
12718 	} else {
12719 		dst_reg->smin_value += smin_val;
12720 		dst_reg->smax_value += smax_val;
12721 	}
12722 	if (dst_reg->umin_value + umin_val < umin_val ||
12723 	    dst_reg->umax_value + umax_val < umax_val) {
12724 		dst_reg->umin_value = 0;
12725 		dst_reg->umax_value = U64_MAX;
12726 	} else {
12727 		dst_reg->umin_value += umin_val;
12728 		dst_reg->umax_value += umax_val;
12729 	}
12730 }
12731 
12732 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12733 				 struct bpf_reg_state *src_reg)
12734 {
12735 	s32 smin_val = src_reg->s32_min_value;
12736 	s32 smax_val = src_reg->s32_max_value;
12737 	u32 umin_val = src_reg->u32_min_value;
12738 	u32 umax_val = src_reg->u32_max_value;
12739 
12740 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12741 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12742 		/* Overflow possible, we know nothing */
12743 		dst_reg->s32_min_value = S32_MIN;
12744 		dst_reg->s32_max_value = S32_MAX;
12745 	} else {
12746 		dst_reg->s32_min_value -= smax_val;
12747 		dst_reg->s32_max_value -= smin_val;
12748 	}
12749 	if (dst_reg->u32_min_value < umax_val) {
12750 		/* Overflow possible, we know nothing */
12751 		dst_reg->u32_min_value = 0;
12752 		dst_reg->u32_max_value = U32_MAX;
12753 	} else {
12754 		/* Cannot overflow (as long as bounds are consistent) */
12755 		dst_reg->u32_min_value -= umax_val;
12756 		dst_reg->u32_max_value -= umin_val;
12757 	}
12758 }
12759 
12760 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12761 			       struct bpf_reg_state *src_reg)
12762 {
12763 	s64 smin_val = src_reg->smin_value;
12764 	s64 smax_val = src_reg->smax_value;
12765 	u64 umin_val = src_reg->umin_value;
12766 	u64 umax_val = src_reg->umax_value;
12767 
12768 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12769 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12770 		/* Overflow possible, we know nothing */
12771 		dst_reg->smin_value = S64_MIN;
12772 		dst_reg->smax_value = S64_MAX;
12773 	} else {
12774 		dst_reg->smin_value -= smax_val;
12775 		dst_reg->smax_value -= smin_val;
12776 	}
12777 	if (dst_reg->umin_value < umax_val) {
12778 		/* Overflow possible, we know nothing */
12779 		dst_reg->umin_value = 0;
12780 		dst_reg->umax_value = U64_MAX;
12781 	} else {
12782 		/* Cannot overflow (as long as bounds are consistent) */
12783 		dst_reg->umin_value -= umax_val;
12784 		dst_reg->umax_value -= umin_val;
12785 	}
12786 }
12787 
12788 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12789 				 struct bpf_reg_state *src_reg)
12790 {
12791 	s32 smin_val = src_reg->s32_min_value;
12792 	u32 umin_val = src_reg->u32_min_value;
12793 	u32 umax_val = src_reg->u32_max_value;
12794 
12795 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12796 		/* Ain't nobody got time to multiply that sign */
12797 		__mark_reg32_unbounded(dst_reg);
12798 		return;
12799 	}
12800 	/* Both values are positive, so we can work with unsigned and
12801 	 * copy the result to signed (unless it exceeds S32_MAX).
12802 	 */
12803 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12804 		/* Potential overflow, we know nothing */
12805 		__mark_reg32_unbounded(dst_reg);
12806 		return;
12807 	}
12808 	dst_reg->u32_min_value *= umin_val;
12809 	dst_reg->u32_max_value *= umax_val;
12810 	if (dst_reg->u32_max_value > S32_MAX) {
12811 		/* Overflow possible, we know nothing */
12812 		dst_reg->s32_min_value = S32_MIN;
12813 		dst_reg->s32_max_value = S32_MAX;
12814 	} else {
12815 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12816 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12817 	}
12818 }
12819 
12820 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12821 			       struct bpf_reg_state *src_reg)
12822 {
12823 	s64 smin_val = src_reg->smin_value;
12824 	u64 umin_val = src_reg->umin_value;
12825 	u64 umax_val = src_reg->umax_value;
12826 
12827 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12828 		/* Ain't nobody got time to multiply that sign */
12829 		__mark_reg64_unbounded(dst_reg);
12830 		return;
12831 	}
12832 	/* Both values are positive, so we can work with unsigned and
12833 	 * copy the result to signed (unless it exceeds S64_MAX).
12834 	 */
12835 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12836 		/* Potential overflow, we know nothing */
12837 		__mark_reg64_unbounded(dst_reg);
12838 		return;
12839 	}
12840 	dst_reg->umin_value *= umin_val;
12841 	dst_reg->umax_value *= umax_val;
12842 	if (dst_reg->umax_value > S64_MAX) {
12843 		/* Overflow possible, we know nothing */
12844 		dst_reg->smin_value = S64_MIN;
12845 		dst_reg->smax_value = S64_MAX;
12846 	} else {
12847 		dst_reg->smin_value = dst_reg->umin_value;
12848 		dst_reg->smax_value = dst_reg->umax_value;
12849 	}
12850 }
12851 
12852 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12853 				 struct bpf_reg_state *src_reg)
12854 {
12855 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12856 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12857 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12858 	s32 smin_val = src_reg->s32_min_value;
12859 	u32 umax_val = src_reg->u32_max_value;
12860 
12861 	if (src_known && dst_known) {
12862 		__mark_reg32_known(dst_reg, var32_off.value);
12863 		return;
12864 	}
12865 
12866 	/* We get our minimum from the var_off, since that's inherently
12867 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12868 	 */
12869 	dst_reg->u32_min_value = var32_off.value;
12870 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12871 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12872 		/* Lose signed bounds when ANDing negative numbers,
12873 		 * ain't nobody got time for that.
12874 		 */
12875 		dst_reg->s32_min_value = S32_MIN;
12876 		dst_reg->s32_max_value = S32_MAX;
12877 	} else {
12878 		/* ANDing two positives gives a positive, so safe to
12879 		 * cast result into s64.
12880 		 */
12881 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12882 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12883 	}
12884 }
12885 
12886 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12887 			       struct bpf_reg_state *src_reg)
12888 {
12889 	bool src_known = tnum_is_const(src_reg->var_off);
12890 	bool dst_known = tnum_is_const(dst_reg->var_off);
12891 	s64 smin_val = src_reg->smin_value;
12892 	u64 umax_val = src_reg->umax_value;
12893 
12894 	if (src_known && dst_known) {
12895 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12896 		return;
12897 	}
12898 
12899 	/* We get our minimum from the var_off, since that's inherently
12900 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12901 	 */
12902 	dst_reg->umin_value = dst_reg->var_off.value;
12903 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12904 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12905 		/* Lose signed bounds when ANDing negative numbers,
12906 		 * ain't nobody got time for that.
12907 		 */
12908 		dst_reg->smin_value = S64_MIN;
12909 		dst_reg->smax_value = S64_MAX;
12910 	} else {
12911 		/* ANDing two positives gives a positive, so safe to
12912 		 * cast result into s64.
12913 		 */
12914 		dst_reg->smin_value = dst_reg->umin_value;
12915 		dst_reg->smax_value = dst_reg->umax_value;
12916 	}
12917 	/* We may learn something more from the var_off */
12918 	__update_reg_bounds(dst_reg);
12919 }
12920 
12921 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12922 				struct bpf_reg_state *src_reg)
12923 {
12924 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12925 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12926 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12927 	s32 smin_val = src_reg->s32_min_value;
12928 	u32 umin_val = src_reg->u32_min_value;
12929 
12930 	if (src_known && dst_known) {
12931 		__mark_reg32_known(dst_reg, var32_off.value);
12932 		return;
12933 	}
12934 
12935 	/* We get our maximum from the var_off, and our minimum is the
12936 	 * maximum of the operands' minima
12937 	 */
12938 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12939 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12940 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12941 		/* Lose signed bounds when ORing negative numbers,
12942 		 * ain't nobody got time for that.
12943 		 */
12944 		dst_reg->s32_min_value = S32_MIN;
12945 		dst_reg->s32_max_value = S32_MAX;
12946 	} else {
12947 		/* ORing two positives gives a positive, so safe to
12948 		 * cast result into s64.
12949 		 */
12950 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12951 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12952 	}
12953 }
12954 
12955 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12956 			      struct bpf_reg_state *src_reg)
12957 {
12958 	bool src_known = tnum_is_const(src_reg->var_off);
12959 	bool dst_known = tnum_is_const(dst_reg->var_off);
12960 	s64 smin_val = src_reg->smin_value;
12961 	u64 umin_val = src_reg->umin_value;
12962 
12963 	if (src_known && dst_known) {
12964 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12965 		return;
12966 	}
12967 
12968 	/* We get our maximum from the var_off, and our minimum is the
12969 	 * maximum of the operands' minima
12970 	 */
12971 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12972 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12973 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12974 		/* Lose signed bounds when ORing negative numbers,
12975 		 * ain't nobody got time for that.
12976 		 */
12977 		dst_reg->smin_value = S64_MIN;
12978 		dst_reg->smax_value = S64_MAX;
12979 	} else {
12980 		/* ORing two positives gives a positive, so safe to
12981 		 * cast result into s64.
12982 		 */
12983 		dst_reg->smin_value = dst_reg->umin_value;
12984 		dst_reg->smax_value = dst_reg->umax_value;
12985 	}
12986 	/* We may learn something more from the var_off */
12987 	__update_reg_bounds(dst_reg);
12988 }
12989 
12990 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12991 				 struct bpf_reg_state *src_reg)
12992 {
12993 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12994 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12995 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12996 	s32 smin_val = src_reg->s32_min_value;
12997 
12998 	if (src_known && dst_known) {
12999 		__mark_reg32_known(dst_reg, var32_off.value);
13000 		return;
13001 	}
13002 
13003 	/* We get both minimum and maximum from the var32_off. */
13004 	dst_reg->u32_min_value = var32_off.value;
13005 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13006 
13007 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13008 		/* XORing two positive sign numbers gives a positive,
13009 		 * so safe to cast u32 result into s32.
13010 		 */
13011 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13012 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13013 	} else {
13014 		dst_reg->s32_min_value = S32_MIN;
13015 		dst_reg->s32_max_value = S32_MAX;
13016 	}
13017 }
13018 
13019 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13020 			       struct bpf_reg_state *src_reg)
13021 {
13022 	bool src_known = tnum_is_const(src_reg->var_off);
13023 	bool dst_known = tnum_is_const(dst_reg->var_off);
13024 	s64 smin_val = src_reg->smin_value;
13025 
13026 	if (src_known && dst_known) {
13027 		/* dst_reg->var_off.value has been updated earlier */
13028 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13029 		return;
13030 	}
13031 
13032 	/* We get both minimum and maximum from the var_off. */
13033 	dst_reg->umin_value = dst_reg->var_off.value;
13034 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13035 
13036 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13037 		/* XORing two positive sign numbers gives a positive,
13038 		 * so safe to cast u64 result into s64.
13039 		 */
13040 		dst_reg->smin_value = dst_reg->umin_value;
13041 		dst_reg->smax_value = dst_reg->umax_value;
13042 	} else {
13043 		dst_reg->smin_value = S64_MIN;
13044 		dst_reg->smax_value = S64_MAX;
13045 	}
13046 
13047 	__update_reg_bounds(dst_reg);
13048 }
13049 
13050 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13051 				   u64 umin_val, u64 umax_val)
13052 {
13053 	/* We lose all sign bit information (except what we can pick
13054 	 * up from var_off)
13055 	 */
13056 	dst_reg->s32_min_value = S32_MIN;
13057 	dst_reg->s32_max_value = S32_MAX;
13058 	/* If we might shift our top bit out, then we know nothing */
13059 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13060 		dst_reg->u32_min_value = 0;
13061 		dst_reg->u32_max_value = U32_MAX;
13062 	} else {
13063 		dst_reg->u32_min_value <<= umin_val;
13064 		dst_reg->u32_max_value <<= umax_val;
13065 	}
13066 }
13067 
13068 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13069 				 struct bpf_reg_state *src_reg)
13070 {
13071 	u32 umax_val = src_reg->u32_max_value;
13072 	u32 umin_val = src_reg->u32_min_value;
13073 	/* u32 alu operation will zext upper bits */
13074 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13075 
13076 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13077 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13078 	/* Not required but being careful mark reg64 bounds as unknown so
13079 	 * that we are forced to pick them up from tnum and zext later and
13080 	 * if some path skips this step we are still safe.
13081 	 */
13082 	__mark_reg64_unbounded(dst_reg);
13083 	__update_reg32_bounds(dst_reg);
13084 }
13085 
13086 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13087 				   u64 umin_val, u64 umax_val)
13088 {
13089 	/* Special case <<32 because it is a common compiler pattern to sign
13090 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13091 	 * positive we know this shift will also be positive so we can track
13092 	 * bounds correctly. Otherwise we lose all sign bit information except
13093 	 * what we can pick up from var_off. Perhaps we can generalize this
13094 	 * later to shifts of any length.
13095 	 */
13096 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13097 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13098 	else
13099 		dst_reg->smax_value = S64_MAX;
13100 
13101 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13102 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13103 	else
13104 		dst_reg->smin_value = S64_MIN;
13105 
13106 	/* If we might shift our top bit out, then we know nothing */
13107 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13108 		dst_reg->umin_value = 0;
13109 		dst_reg->umax_value = U64_MAX;
13110 	} else {
13111 		dst_reg->umin_value <<= umin_val;
13112 		dst_reg->umax_value <<= umax_val;
13113 	}
13114 }
13115 
13116 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13117 			       struct bpf_reg_state *src_reg)
13118 {
13119 	u64 umax_val = src_reg->umax_value;
13120 	u64 umin_val = src_reg->umin_value;
13121 
13122 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13123 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13124 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13125 
13126 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13127 	/* We may learn something more from the var_off */
13128 	__update_reg_bounds(dst_reg);
13129 }
13130 
13131 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13132 				 struct bpf_reg_state *src_reg)
13133 {
13134 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13135 	u32 umax_val = src_reg->u32_max_value;
13136 	u32 umin_val = src_reg->u32_min_value;
13137 
13138 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13139 	 * be negative, then either:
13140 	 * 1) src_reg might be zero, so the sign bit of the result is
13141 	 *    unknown, so we lose our signed bounds
13142 	 * 2) it's known negative, thus the unsigned bounds capture the
13143 	 *    signed bounds
13144 	 * 3) the signed bounds cross zero, so they tell us nothing
13145 	 *    about the result
13146 	 * If the value in dst_reg is known nonnegative, then again the
13147 	 * unsigned bounds capture the signed bounds.
13148 	 * Thus, in all cases it suffices to blow away our signed bounds
13149 	 * and rely on inferring new ones from the unsigned bounds and
13150 	 * var_off of the result.
13151 	 */
13152 	dst_reg->s32_min_value = S32_MIN;
13153 	dst_reg->s32_max_value = S32_MAX;
13154 
13155 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13156 	dst_reg->u32_min_value >>= umax_val;
13157 	dst_reg->u32_max_value >>= umin_val;
13158 
13159 	__mark_reg64_unbounded(dst_reg);
13160 	__update_reg32_bounds(dst_reg);
13161 }
13162 
13163 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13164 			       struct bpf_reg_state *src_reg)
13165 {
13166 	u64 umax_val = src_reg->umax_value;
13167 	u64 umin_val = src_reg->umin_value;
13168 
13169 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13170 	 * be negative, then either:
13171 	 * 1) src_reg might be zero, so the sign bit of the result is
13172 	 *    unknown, so we lose our signed bounds
13173 	 * 2) it's known negative, thus the unsigned bounds capture the
13174 	 *    signed bounds
13175 	 * 3) the signed bounds cross zero, so they tell us nothing
13176 	 *    about the result
13177 	 * If the value in dst_reg is known nonnegative, then again the
13178 	 * unsigned bounds capture the signed bounds.
13179 	 * Thus, in all cases it suffices to blow away our signed bounds
13180 	 * and rely on inferring new ones from the unsigned bounds and
13181 	 * var_off of the result.
13182 	 */
13183 	dst_reg->smin_value = S64_MIN;
13184 	dst_reg->smax_value = S64_MAX;
13185 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13186 	dst_reg->umin_value >>= umax_val;
13187 	dst_reg->umax_value >>= umin_val;
13188 
13189 	/* Its not easy to operate on alu32 bounds here because it depends
13190 	 * on bits being shifted in. Take easy way out and mark unbounded
13191 	 * so we can recalculate later from tnum.
13192 	 */
13193 	__mark_reg32_unbounded(dst_reg);
13194 	__update_reg_bounds(dst_reg);
13195 }
13196 
13197 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13198 				  struct bpf_reg_state *src_reg)
13199 {
13200 	u64 umin_val = src_reg->u32_min_value;
13201 
13202 	/* Upon reaching here, src_known is true and
13203 	 * umax_val is equal to umin_val.
13204 	 */
13205 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13206 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13207 
13208 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13209 
13210 	/* blow away the dst_reg umin_value/umax_value and rely on
13211 	 * dst_reg var_off to refine the result.
13212 	 */
13213 	dst_reg->u32_min_value = 0;
13214 	dst_reg->u32_max_value = U32_MAX;
13215 
13216 	__mark_reg64_unbounded(dst_reg);
13217 	__update_reg32_bounds(dst_reg);
13218 }
13219 
13220 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13221 				struct bpf_reg_state *src_reg)
13222 {
13223 	u64 umin_val = src_reg->umin_value;
13224 
13225 	/* Upon reaching here, src_known is true and umax_val is equal
13226 	 * to umin_val.
13227 	 */
13228 	dst_reg->smin_value >>= umin_val;
13229 	dst_reg->smax_value >>= umin_val;
13230 
13231 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13232 
13233 	/* blow away the dst_reg umin_value/umax_value and rely on
13234 	 * dst_reg var_off to refine the result.
13235 	 */
13236 	dst_reg->umin_value = 0;
13237 	dst_reg->umax_value = U64_MAX;
13238 
13239 	/* Its not easy to operate on alu32 bounds here because it depends
13240 	 * on bits being shifted in from upper 32-bits. Take easy way out
13241 	 * and mark unbounded so we can recalculate later from tnum.
13242 	 */
13243 	__mark_reg32_unbounded(dst_reg);
13244 	__update_reg_bounds(dst_reg);
13245 }
13246 
13247 /* WARNING: This function does calculations on 64-bit values, but the actual
13248  * execution may occur on 32-bit values. Therefore, things like bitshifts
13249  * need extra checks in the 32-bit case.
13250  */
13251 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13252 				      struct bpf_insn *insn,
13253 				      struct bpf_reg_state *dst_reg,
13254 				      struct bpf_reg_state src_reg)
13255 {
13256 	struct bpf_reg_state *regs = cur_regs(env);
13257 	u8 opcode = BPF_OP(insn->code);
13258 	bool src_known;
13259 	s64 smin_val, smax_val;
13260 	u64 umin_val, umax_val;
13261 	s32 s32_min_val, s32_max_val;
13262 	u32 u32_min_val, u32_max_val;
13263 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13264 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13265 	int ret;
13266 
13267 	smin_val = src_reg.smin_value;
13268 	smax_val = src_reg.smax_value;
13269 	umin_val = src_reg.umin_value;
13270 	umax_val = src_reg.umax_value;
13271 
13272 	s32_min_val = src_reg.s32_min_value;
13273 	s32_max_val = src_reg.s32_max_value;
13274 	u32_min_val = src_reg.u32_min_value;
13275 	u32_max_val = src_reg.u32_max_value;
13276 
13277 	if (alu32) {
13278 		src_known = tnum_subreg_is_const(src_reg.var_off);
13279 		if ((src_known &&
13280 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13281 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13282 			/* Taint dst register if offset had invalid bounds
13283 			 * derived from e.g. dead branches.
13284 			 */
13285 			__mark_reg_unknown(env, dst_reg);
13286 			return 0;
13287 		}
13288 	} else {
13289 		src_known = tnum_is_const(src_reg.var_off);
13290 		if ((src_known &&
13291 		     (smin_val != smax_val || umin_val != umax_val)) ||
13292 		    smin_val > smax_val || umin_val > umax_val) {
13293 			/* Taint dst register if offset had invalid bounds
13294 			 * derived from e.g. dead branches.
13295 			 */
13296 			__mark_reg_unknown(env, dst_reg);
13297 			return 0;
13298 		}
13299 	}
13300 
13301 	if (!src_known &&
13302 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13303 		__mark_reg_unknown(env, dst_reg);
13304 		return 0;
13305 	}
13306 
13307 	if (sanitize_needed(opcode)) {
13308 		ret = sanitize_val_alu(env, insn);
13309 		if (ret < 0)
13310 			return sanitize_err(env, insn, ret, NULL, NULL);
13311 	}
13312 
13313 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13314 	 * There are two classes of instructions: The first class we track both
13315 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13316 	 * greatest amount of precision when alu operations are mixed with jmp32
13317 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13318 	 * and BPF_OR. This is possible because these ops have fairly easy to
13319 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13320 	 * See alu32 verifier tests for examples. The second class of
13321 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13322 	 * with regards to tracking sign/unsigned bounds because the bits may
13323 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13324 	 * the reg unbounded in the subreg bound space and use the resulting
13325 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13326 	 */
13327 	switch (opcode) {
13328 	case BPF_ADD:
13329 		scalar32_min_max_add(dst_reg, &src_reg);
13330 		scalar_min_max_add(dst_reg, &src_reg);
13331 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13332 		break;
13333 	case BPF_SUB:
13334 		scalar32_min_max_sub(dst_reg, &src_reg);
13335 		scalar_min_max_sub(dst_reg, &src_reg);
13336 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13337 		break;
13338 	case BPF_MUL:
13339 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13340 		scalar32_min_max_mul(dst_reg, &src_reg);
13341 		scalar_min_max_mul(dst_reg, &src_reg);
13342 		break;
13343 	case BPF_AND:
13344 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13345 		scalar32_min_max_and(dst_reg, &src_reg);
13346 		scalar_min_max_and(dst_reg, &src_reg);
13347 		break;
13348 	case BPF_OR:
13349 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13350 		scalar32_min_max_or(dst_reg, &src_reg);
13351 		scalar_min_max_or(dst_reg, &src_reg);
13352 		break;
13353 	case BPF_XOR:
13354 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13355 		scalar32_min_max_xor(dst_reg, &src_reg);
13356 		scalar_min_max_xor(dst_reg, &src_reg);
13357 		break;
13358 	case BPF_LSH:
13359 		if (umax_val >= insn_bitness) {
13360 			/* Shifts greater than 31 or 63 are undefined.
13361 			 * This includes shifts by a negative number.
13362 			 */
13363 			mark_reg_unknown(env, regs, insn->dst_reg);
13364 			break;
13365 		}
13366 		if (alu32)
13367 			scalar32_min_max_lsh(dst_reg, &src_reg);
13368 		else
13369 			scalar_min_max_lsh(dst_reg, &src_reg);
13370 		break;
13371 	case BPF_RSH:
13372 		if (umax_val >= insn_bitness) {
13373 			/* Shifts greater than 31 or 63 are undefined.
13374 			 * This includes shifts by a negative number.
13375 			 */
13376 			mark_reg_unknown(env, regs, insn->dst_reg);
13377 			break;
13378 		}
13379 		if (alu32)
13380 			scalar32_min_max_rsh(dst_reg, &src_reg);
13381 		else
13382 			scalar_min_max_rsh(dst_reg, &src_reg);
13383 		break;
13384 	case BPF_ARSH:
13385 		if (umax_val >= insn_bitness) {
13386 			/* Shifts greater than 31 or 63 are undefined.
13387 			 * This includes shifts by a negative number.
13388 			 */
13389 			mark_reg_unknown(env, regs, insn->dst_reg);
13390 			break;
13391 		}
13392 		if (alu32)
13393 			scalar32_min_max_arsh(dst_reg, &src_reg);
13394 		else
13395 			scalar_min_max_arsh(dst_reg, &src_reg);
13396 		break;
13397 	default:
13398 		mark_reg_unknown(env, regs, insn->dst_reg);
13399 		break;
13400 	}
13401 
13402 	/* ALU32 ops are zero extended into 64bit register */
13403 	if (alu32)
13404 		zext_32_to_64(dst_reg);
13405 	reg_bounds_sync(dst_reg);
13406 	return 0;
13407 }
13408 
13409 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13410  * and var_off.
13411  */
13412 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13413 				   struct bpf_insn *insn)
13414 {
13415 	struct bpf_verifier_state *vstate = env->cur_state;
13416 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13417 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13418 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13419 	u8 opcode = BPF_OP(insn->code);
13420 	int err;
13421 
13422 	dst_reg = &regs[insn->dst_reg];
13423 	src_reg = NULL;
13424 	if (dst_reg->type != SCALAR_VALUE)
13425 		ptr_reg = dst_reg;
13426 	else
13427 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13428 		 * incorrectly propagated into other registers by find_equal_scalars()
13429 		 */
13430 		dst_reg->id = 0;
13431 	if (BPF_SRC(insn->code) == BPF_X) {
13432 		src_reg = &regs[insn->src_reg];
13433 		if (src_reg->type != SCALAR_VALUE) {
13434 			if (dst_reg->type != SCALAR_VALUE) {
13435 				/* Combining two pointers by any ALU op yields
13436 				 * an arbitrary scalar. Disallow all math except
13437 				 * pointer subtraction
13438 				 */
13439 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13440 					mark_reg_unknown(env, regs, insn->dst_reg);
13441 					return 0;
13442 				}
13443 				verbose(env, "R%d pointer %s pointer prohibited\n",
13444 					insn->dst_reg,
13445 					bpf_alu_string[opcode >> 4]);
13446 				return -EACCES;
13447 			} else {
13448 				/* scalar += pointer
13449 				 * This is legal, but we have to reverse our
13450 				 * src/dest handling in computing the range
13451 				 */
13452 				err = mark_chain_precision(env, insn->dst_reg);
13453 				if (err)
13454 					return err;
13455 				return adjust_ptr_min_max_vals(env, insn,
13456 							       src_reg, dst_reg);
13457 			}
13458 		} else if (ptr_reg) {
13459 			/* pointer += scalar */
13460 			err = mark_chain_precision(env, insn->src_reg);
13461 			if (err)
13462 				return err;
13463 			return adjust_ptr_min_max_vals(env, insn,
13464 						       dst_reg, src_reg);
13465 		} else if (dst_reg->precise) {
13466 			/* if dst_reg is precise, src_reg should be precise as well */
13467 			err = mark_chain_precision(env, insn->src_reg);
13468 			if (err)
13469 				return err;
13470 		}
13471 	} else {
13472 		/* Pretend the src is a reg with a known value, since we only
13473 		 * need to be able to read from this state.
13474 		 */
13475 		off_reg.type = SCALAR_VALUE;
13476 		__mark_reg_known(&off_reg, insn->imm);
13477 		src_reg = &off_reg;
13478 		if (ptr_reg) /* pointer += K */
13479 			return adjust_ptr_min_max_vals(env, insn,
13480 						       ptr_reg, src_reg);
13481 	}
13482 
13483 	/* Got here implies adding two SCALAR_VALUEs */
13484 	if (WARN_ON_ONCE(ptr_reg)) {
13485 		print_verifier_state(env, state, true);
13486 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13487 		return -EINVAL;
13488 	}
13489 	if (WARN_ON(!src_reg)) {
13490 		print_verifier_state(env, state, true);
13491 		verbose(env, "verifier internal error: no src_reg\n");
13492 		return -EINVAL;
13493 	}
13494 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13495 }
13496 
13497 /* check validity of 32-bit and 64-bit arithmetic operations */
13498 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13499 {
13500 	struct bpf_reg_state *regs = cur_regs(env);
13501 	u8 opcode = BPF_OP(insn->code);
13502 	int err;
13503 
13504 	if (opcode == BPF_END || opcode == BPF_NEG) {
13505 		if (opcode == BPF_NEG) {
13506 			if (BPF_SRC(insn->code) != BPF_K ||
13507 			    insn->src_reg != BPF_REG_0 ||
13508 			    insn->off != 0 || insn->imm != 0) {
13509 				verbose(env, "BPF_NEG uses reserved fields\n");
13510 				return -EINVAL;
13511 			}
13512 		} else {
13513 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13514 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13515 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13516 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13517 				verbose(env, "BPF_END uses reserved fields\n");
13518 				return -EINVAL;
13519 			}
13520 		}
13521 
13522 		/* check src operand */
13523 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13524 		if (err)
13525 			return err;
13526 
13527 		if (is_pointer_value(env, insn->dst_reg)) {
13528 			verbose(env, "R%d pointer arithmetic prohibited\n",
13529 				insn->dst_reg);
13530 			return -EACCES;
13531 		}
13532 
13533 		/* check dest operand */
13534 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13535 		if (err)
13536 			return err;
13537 
13538 	} else if (opcode == BPF_MOV) {
13539 
13540 		if (BPF_SRC(insn->code) == BPF_X) {
13541 			if (insn->imm != 0) {
13542 				verbose(env, "BPF_MOV uses reserved fields\n");
13543 				return -EINVAL;
13544 			}
13545 
13546 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13547 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13548 					verbose(env, "BPF_MOV uses reserved fields\n");
13549 					return -EINVAL;
13550 				}
13551 			} else {
13552 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13553 				    insn->off != 32) {
13554 					verbose(env, "BPF_MOV uses reserved fields\n");
13555 					return -EINVAL;
13556 				}
13557 			}
13558 
13559 			/* check src operand */
13560 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13561 			if (err)
13562 				return err;
13563 		} else {
13564 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13565 				verbose(env, "BPF_MOV uses reserved fields\n");
13566 				return -EINVAL;
13567 			}
13568 		}
13569 
13570 		/* check dest operand, mark as required later */
13571 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13572 		if (err)
13573 			return err;
13574 
13575 		if (BPF_SRC(insn->code) == BPF_X) {
13576 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13577 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13578 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13579 				       !tnum_is_const(src_reg->var_off);
13580 
13581 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13582 				if (insn->off == 0) {
13583 					/* case: R1 = R2
13584 					 * copy register state to dest reg
13585 					 */
13586 					if (need_id)
13587 						/* Assign src and dst registers the same ID
13588 						 * that will be used by find_equal_scalars()
13589 						 * to propagate min/max range.
13590 						 */
13591 						src_reg->id = ++env->id_gen;
13592 					copy_register_state(dst_reg, src_reg);
13593 					dst_reg->live |= REG_LIVE_WRITTEN;
13594 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13595 				} else {
13596 					/* case: R1 = (s8, s16 s32)R2 */
13597 					if (is_pointer_value(env, insn->src_reg)) {
13598 						verbose(env,
13599 							"R%d sign-extension part of pointer\n",
13600 							insn->src_reg);
13601 						return -EACCES;
13602 					} else if (src_reg->type == SCALAR_VALUE) {
13603 						bool no_sext;
13604 
13605 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13606 						if (no_sext && need_id)
13607 							src_reg->id = ++env->id_gen;
13608 						copy_register_state(dst_reg, src_reg);
13609 						if (!no_sext)
13610 							dst_reg->id = 0;
13611 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13612 						dst_reg->live |= REG_LIVE_WRITTEN;
13613 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13614 					} else {
13615 						mark_reg_unknown(env, regs, insn->dst_reg);
13616 					}
13617 				}
13618 			} else {
13619 				/* R1 = (u32) R2 */
13620 				if (is_pointer_value(env, insn->src_reg)) {
13621 					verbose(env,
13622 						"R%d partial copy of pointer\n",
13623 						insn->src_reg);
13624 					return -EACCES;
13625 				} else if (src_reg->type == SCALAR_VALUE) {
13626 					if (insn->off == 0) {
13627 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13628 
13629 						if (is_src_reg_u32 && need_id)
13630 							src_reg->id = ++env->id_gen;
13631 						copy_register_state(dst_reg, src_reg);
13632 						/* Make sure ID is cleared if src_reg is not in u32
13633 						 * range otherwise dst_reg min/max could be incorrectly
13634 						 * propagated into src_reg by find_equal_scalars()
13635 						 */
13636 						if (!is_src_reg_u32)
13637 							dst_reg->id = 0;
13638 						dst_reg->live |= REG_LIVE_WRITTEN;
13639 						dst_reg->subreg_def = env->insn_idx + 1;
13640 					} else {
13641 						/* case: W1 = (s8, s16)W2 */
13642 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13643 
13644 						if (no_sext && need_id)
13645 							src_reg->id = ++env->id_gen;
13646 						copy_register_state(dst_reg, src_reg);
13647 						if (!no_sext)
13648 							dst_reg->id = 0;
13649 						dst_reg->live |= REG_LIVE_WRITTEN;
13650 						dst_reg->subreg_def = env->insn_idx + 1;
13651 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13652 					}
13653 				} else {
13654 					mark_reg_unknown(env, regs,
13655 							 insn->dst_reg);
13656 				}
13657 				zext_32_to_64(dst_reg);
13658 				reg_bounds_sync(dst_reg);
13659 			}
13660 		} else {
13661 			/* case: R = imm
13662 			 * remember the value we stored into this reg
13663 			 */
13664 			/* clear any state __mark_reg_known doesn't set */
13665 			mark_reg_unknown(env, regs, insn->dst_reg);
13666 			regs[insn->dst_reg].type = SCALAR_VALUE;
13667 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13668 				__mark_reg_known(regs + insn->dst_reg,
13669 						 insn->imm);
13670 			} else {
13671 				__mark_reg_known(regs + insn->dst_reg,
13672 						 (u32)insn->imm);
13673 			}
13674 		}
13675 
13676 	} else if (opcode > BPF_END) {
13677 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13678 		return -EINVAL;
13679 
13680 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13681 
13682 		if (BPF_SRC(insn->code) == BPF_X) {
13683 			if (insn->imm != 0 || insn->off > 1 ||
13684 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13685 				verbose(env, "BPF_ALU uses reserved fields\n");
13686 				return -EINVAL;
13687 			}
13688 			/* check src1 operand */
13689 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13690 			if (err)
13691 				return err;
13692 		} else {
13693 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13694 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13695 				verbose(env, "BPF_ALU uses reserved fields\n");
13696 				return -EINVAL;
13697 			}
13698 		}
13699 
13700 		/* check src2 operand */
13701 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13702 		if (err)
13703 			return err;
13704 
13705 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13706 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13707 			verbose(env, "div by zero\n");
13708 			return -EINVAL;
13709 		}
13710 
13711 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13712 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13713 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13714 
13715 			if (insn->imm < 0 || insn->imm >= size) {
13716 				verbose(env, "invalid shift %d\n", insn->imm);
13717 				return -EINVAL;
13718 			}
13719 		}
13720 
13721 		/* check dest operand */
13722 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13723 		if (err)
13724 			return err;
13725 
13726 		return adjust_reg_min_max_vals(env, insn);
13727 	}
13728 
13729 	return 0;
13730 }
13731 
13732 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13733 				   struct bpf_reg_state *dst_reg,
13734 				   enum bpf_reg_type type,
13735 				   bool range_right_open)
13736 {
13737 	struct bpf_func_state *state;
13738 	struct bpf_reg_state *reg;
13739 	int new_range;
13740 
13741 	if (dst_reg->off < 0 ||
13742 	    (dst_reg->off == 0 && range_right_open))
13743 		/* This doesn't give us any range */
13744 		return;
13745 
13746 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13747 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13748 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13749 		 * than pkt_end, but that's because it's also less than pkt.
13750 		 */
13751 		return;
13752 
13753 	new_range = dst_reg->off;
13754 	if (range_right_open)
13755 		new_range++;
13756 
13757 	/* Examples for register markings:
13758 	 *
13759 	 * pkt_data in dst register:
13760 	 *
13761 	 *   r2 = r3;
13762 	 *   r2 += 8;
13763 	 *   if (r2 > pkt_end) goto <handle exception>
13764 	 *   <access okay>
13765 	 *
13766 	 *   r2 = r3;
13767 	 *   r2 += 8;
13768 	 *   if (r2 < pkt_end) goto <access okay>
13769 	 *   <handle exception>
13770 	 *
13771 	 *   Where:
13772 	 *     r2 == dst_reg, pkt_end == src_reg
13773 	 *     r2=pkt(id=n,off=8,r=0)
13774 	 *     r3=pkt(id=n,off=0,r=0)
13775 	 *
13776 	 * pkt_data in src register:
13777 	 *
13778 	 *   r2 = r3;
13779 	 *   r2 += 8;
13780 	 *   if (pkt_end >= r2) goto <access okay>
13781 	 *   <handle exception>
13782 	 *
13783 	 *   r2 = r3;
13784 	 *   r2 += 8;
13785 	 *   if (pkt_end <= r2) goto <handle exception>
13786 	 *   <access okay>
13787 	 *
13788 	 *   Where:
13789 	 *     pkt_end == dst_reg, r2 == src_reg
13790 	 *     r2=pkt(id=n,off=8,r=0)
13791 	 *     r3=pkt(id=n,off=0,r=0)
13792 	 *
13793 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13794 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13795 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13796 	 * the check.
13797 	 */
13798 
13799 	/* If our ids match, then we must have the same max_value.  And we
13800 	 * don't care about the other reg's fixed offset, since if it's too big
13801 	 * the range won't allow anything.
13802 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13803 	 */
13804 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13805 		if (reg->type == type && reg->id == dst_reg->id)
13806 			/* keep the maximum range already checked */
13807 			reg->range = max(reg->range, new_range);
13808 	}));
13809 }
13810 
13811 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13812 {
13813 	struct tnum subreg = tnum_subreg(reg->var_off);
13814 	s32 sval = (s32)val;
13815 
13816 	switch (opcode) {
13817 	case BPF_JEQ:
13818 		if (tnum_is_const(subreg))
13819 			return !!tnum_equals_const(subreg, val);
13820 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13821 			return 0;
13822 		break;
13823 	case BPF_JNE:
13824 		if (tnum_is_const(subreg))
13825 			return !tnum_equals_const(subreg, val);
13826 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13827 			return 1;
13828 		break;
13829 	case BPF_JSET:
13830 		if ((~subreg.mask & subreg.value) & val)
13831 			return 1;
13832 		if (!((subreg.mask | subreg.value) & val))
13833 			return 0;
13834 		break;
13835 	case BPF_JGT:
13836 		if (reg->u32_min_value > val)
13837 			return 1;
13838 		else if (reg->u32_max_value <= val)
13839 			return 0;
13840 		break;
13841 	case BPF_JSGT:
13842 		if (reg->s32_min_value > sval)
13843 			return 1;
13844 		else if (reg->s32_max_value <= sval)
13845 			return 0;
13846 		break;
13847 	case BPF_JLT:
13848 		if (reg->u32_max_value < val)
13849 			return 1;
13850 		else if (reg->u32_min_value >= val)
13851 			return 0;
13852 		break;
13853 	case BPF_JSLT:
13854 		if (reg->s32_max_value < sval)
13855 			return 1;
13856 		else if (reg->s32_min_value >= sval)
13857 			return 0;
13858 		break;
13859 	case BPF_JGE:
13860 		if (reg->u32_min_value >= val)
13861 			return 1;
13862 		else if (reg->u32_max_value < val)
13863 			return 0;
13864 		break;
13865 	case BPF_JSGE:
13866 		if (reg->s32_min_value >= sval)
13867 			return 1;
13868 		else if (reg->s32_max_value < sval)
13869 			return 0;
13870 		break;
13871 	case BPF_JLE:
13872 		if (reg->u32_max_value <= val)
13873 			return 1;
13874 		else if (reg->u32_min_value > val)
13875 			return 0;
13876 		break;
13877 	case BPF_JSLE:
13878 		if (reg->s32_max_value <= sval)
13879 			return 1;
13880 		else if (reg->s32_min_value > sval)
13881 			return 0;
13882 		break;
13883 	}
13884 
13885 	return -1;
13886 }
13887 
13888 
13889 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13890 {
13891 	s64 sval = (s64)val;
13892 
13893 	switch (opcode) {
13894 	case BPF_JEQ:
13895 		if (tnum_is_const(reg->var_off))
13896 			return !!tnum_equals_const(reg->var_off, val);
13897 		else if (val < reg->umin_value || val > reg->umax_value)
13898 			return 0;
13899 		break;
13900 	case BPF_JNE:
13901 		if (tnum_is_const(reg->var_off))
13902 			return !tnum_equals_const(reg->var_off, val);
13903 		else if (val < reg->umin_value || val > reg->umax_value)
13904 			return 1;
13905 		break;
13906 	case BPF_JSET:
13907 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13908 			return 1;
13909 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13910 			return 0;
13911 		break;
13912 	case BPF_JGT:
13913 		if (reg->umin_value > val)
13914 			return 1;
13915 		else if (reg->umax_value <= val)
13916 			return 0;
13917 		break;
13918 	case BPF_JSGT:
13919 		if (reg->smin_value > sval)
13920 			return 1;
13921 		else if (reg->smax_value <= sval)
13922 			return 0;
13923 		break;
13924 	case BPF_JLT:
13925 		if (reg->umax_value < val)
13926 			return 1;
13927 		else if (reg->umin_value >= val)
13928 			return 0;
13929 		break;
13930 	case BPF_JSLT:
13931 		if (reg->smax_value < sval)
13932 			return 1;
13933 		else if (reg->smin_value >= sval)
13934 			return 0;
13935 		break;
13936 	case BPF_JGE:
13937 		if (reg->umin_value >= val)
13938 			return 1;
13939 		else if (reg->umax_value < val)
13940 			return 0;
13941 		break;
13942 	case BPF_JSGE:
13943 		if (reg->smin_value >= sval)
13944 			return 1;
13945 		else if (reg->smax_value < sval)
13946 			return 0;
13947 		break;
13948 	case BPF_JLE:
13949 		if (reg->umax_value <= val)
13950 			return 1;
13951 		else if (reg->umin_value > val)
13952 			return 0;
13953 		break;
13954 	case BPF_JSLE:
13955 		if (reg->smax_value <= sval)
13956 			return 1;
13957 		else if (reg->smin_value > sval)
13958 			return 0;
13959 		break;
13960 	}
13961 
13962 	return -1;
13963 }
13964 
13965 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13966  * and return:
13967  *  1 - branch will be taken and "goto target" will be executed
13968  *  0 - branch will not be taken and fall-through to next insn
13969  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13970  *      range [0,10]
13971  */
13972 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13973 			   bool is_jmp32)
13974 {
13975 	if (__is_pointer_value(false, reg)) {
13976 		if (!reg_not_null(reg))
13977 			return -1;
13978 
13979 		/* If pointer is valid tests against zero will fail so we can
13980 		 * use this to direct branch taken.
13981 		 */
13982 		if (val != 0)
13983 			return -1;
13984 
13985 		switch (opcode) {
13986 		case BPF_JEQ:
13987 			return 0;
13988 		case BPF_JNE:
13989 			return 1;
13990 		default:
13991 			return -1;
13992 		}
13993 	}
13994 
13995 	if (is_jmp32)
13996 		return is_branch32_taken(reg, val, opcode);
13997 	return is_branch64_taken(reg, val, opcode);
13998 }
13999 
14000 static int flip_opcode(u32 opcode)
14001 {
14002 	/* How can we transform "a <op> b" into "b <op> a"? */
14003 	static const u8 opcode_flip[16] = {
14004 		/* these stay the same */
14005 		[BPF_JEQ  >> 4] = BPF_JEQ,
14006 		[BPF_JNE  >> 4] = BPF_JNE,
14007 		[BPF_JSET >> 4] = BPF_JSET,
14008 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14009 		[BPF_JGE  >> 4] = BPF_JLE,
14010 		[BPF_JGT  >> 4] = BPF_JLT,
14011 		[BPF_JLE  >> 4] = BPF_JGE,
14012 		[BPF_JLT  >> 4] = BPF_JGT,
14013 		[BPF_JSGE >> 4] = BPF_JSLE,
14014 		[BPF_JSGT >> 4] = BPF_JSLT,
14015 		[BPF_JSLE >> 4] = BPF_JSGE,
14016 		[BPF_JSLT >> 4] = BPF_JSGT
14017 	};
14018 	return opcode_flip[opcode >> 4];
14019 }
14020 
14021 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14022 				   struct bpf_reg_state *src_reg,
14023 				   u8 opcode)
14024 {
14025 	struct bpf_reg_state *pkt;
14026 
14027 	if (src_reg->type == PTR_TO_PACKET_END) {
14028 		pkt = dst_reg;
14029 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14030 		pkt = src_reg;
14031 		opcode = flip_opcode(opcode);
14032 	} else {
14033 		return -1;
14034 	}
14035 
14036 	if (pkt->range >= 0)
14037 		return -1;
14038 
14039 	switch (opcode) {
14040 	case BPF_JLE:
14041 		/* pkt <= pkt_end */
14042 		fallthrough;
14043 	case BPF_JGT:
14044 		/* pkt > pkt_end */
14045 		if (pkt->range == BEYOND_PKT_END)
14046 			/* pkt has at last one extra byte beyond pkt_end */
14047 			return opcode == BPF_JGT;
14048 		break;
14049 	case BPF_JLT:
14050 		/* pkt < pkt_end */
14051 		fallthrough;
14052 	case BPF_JGE:
14053 		/* pkt >= pkt_end */
14054 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14055 			return opcode == BPF_JGE;
14056 		break;
14057 	}
14058 	return -1;
14059 }
14060 
14061 /* Adjusts the register min/max values in the case that the dst_reg is the
14062  * variable register that we are working on, and src_reg is a constant or we're
14063  * simply doing a BPF_K check.
14064  * In JEQ/JNE cases we also adjust the var_off values.
14065  */
14066 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14067 			    struct bpf_reg_state *false_reg,
14068 			    u64 val, u32 val32,
14069 			    u8 opcode, bool is_jmp32)
14070 {
14071 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14072 	struct tnum false_64off = false_reg->var_off;
14073 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14074 	struct tnum true_64off = true_reg->var_off;
14075 	s64 sval = (s64)val;
14076 	s32 sval32 = (s32)val32;
14077 
14078 	/* If the dst_reg is a pointer, we can't learn anything about its
14079 	 * variable offset from the compare (unless src_reg were a pointer into
14080 	 * the same object, but we don't bother with that.
14081 	 * Since false_reg and true_reg have the same type by construction, we
14082 	 * only need to check one of them for pointerness.
14083 	 */
14084 	if (__is_pointer_value(false, false_reg))
14085 		return;
14086 
14087 	switch (opcode) {
14088 	/* JEQ/JNE comparison doesn't change the register equivalence.
14089 	 *
14090 	 * r1 = r2;
14091 	 * if (r1 == 42) goto label;
14092 	 * ...
14093 	 * label: // here both r1 and r2 are known to be 42.
14094 	 *
14095 	 * Hence when marking register as known preserve it's ID.
14096 	 */
14097 	case BPF_JEQ:
14098 		if (is_jmp32) {
14099 			__mark_reg32_known(true_reg, val32);
14100 			true_32off = tnum_subreg(true_reg->var_off);
14101 		} else {
14102 			___mark_reg_known(true_reg, val);
14103 			true_64off = true_reg->var_off;
14104 		}
14105 		break;
14106 	case BPF_JNE:
14107 		if (is_jmp32) {
14108 			__mark_reg32_known(false_reg, val32);
14109 			false_32off = tnum_subreg(false_reg->var_off);
14110 		} else {
14111 			___mark_reg_known(false_reg, val);
14112 			false_64off = false_reg->var_off;
14113 		}
14114 		break;
14115 	case BPF_JSET:
14116 		if (is_jmp32) {
14117 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14118 			if (is_power_of_2(val32))
14119 				true_32off = tnum_or(true_32off,
14120 						     tnum_const(val32));
14121 		} else {
14122 			false_64off = tnum_and(false_64off, tnum_const(~val));
14123 			if (is_power_of_2(val))
14124 				true_64off = tnum_or(true_64off,
14125 						     tnum_const(val));
14126 		}
14127 		break;
14128 	case BPF_JGE:
14129 	case BPF_JGT:
14130 	{
14131 		if (is_jmp32) {
14132 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14133 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14134 
14135 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14136 						       false_umax);
14137 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14138 						      true_umin);
14139 		} else {
14140 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14141 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14142 
14143 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14144 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14145 		}
14146 		break;
14147 	}
14148 	case BPF_JSGE:
14149 	case BPF_JSGT:
14150 	{
14151 		if (is_jmp32) {
14152 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14153 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14154 
14155 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14156 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14157 		} else {
14158 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14159 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14160 
14161 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14162 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14163 		}
14164 		break;
14165 	}
14166 	case BPF_JLE:
14167 	case BPF_JLT:
14168 	{
14169 		if (is_jmp32) {
14170 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14171 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14172 
14173 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14174 						       false_umin);
14175 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14176 						      true_umax);
14177 		} else {
14178 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14179 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14180 
14181 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14182 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14183 		}
14184 		break;
14185 	}
14186 	case BPF_JSLE:
14187 	case BPF_JSLT:
14188 	{
14189 		if (is_jmp32) {
14190 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14191 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14192 
14193 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14194 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14195 		} else {
14196 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14197 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14198 
14199 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14200 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14201 		}
14202 		break;
14203 	}
14204 	default:
14205 		return;
14206 	}
14207 
14208 	if (is_jmp32) {
14209 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14210 					     tnum_subreg(false_32off));
14211 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14212 					    tnum_subreg(true_32off));
14213 		__reg_combine_32_into_64(false_reg);
14214 		__reg_combine_32_into_64(true_reg);
14215 	} else {
14216 		false_reg->var_off = false_64off;
14217 		true_reg->var_off = true_64off;
14218 		__reg_combine_64_into_32(false_reg);
14219 		__reg_combine_64_into_32(true_reg);
14220 	}
14221 }
14222 
14223 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14224  * the variable reg.
14225  */
14226 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14227 				struct bpf_reg_state *false_reg,
14228 				u64 val, u32 val32,
14229 				u8 opcode, bool is_jmp32)
14230 {
14231 	opcode = flip_opcode(opcode);
14232 	/* This uses zero as "not present in table"; luckily the zero opcode,
14233 	 * BPF_JA, can't get here.
14234 	 */
14235 	if (opcode)
14236 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14237 }
14238 
14239 /* Regs are known to be equal, so intersect their min/max/var_off */
14240 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14241 				  struct bpf_reg_state *dst_reg)
14242 {
14243 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14244 							dst_reg->umin_value);
14245 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14246 							dst_reg->umax_value);
14247 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14248 							dst_reg->smin_value);
14249 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14250 							dst_reg->smax_value);
14251 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14252 							     dst_reg->var_off);
14253 	reg_bounds_sync(src_reg);
14254 	reg_bounds_sync(dst_reg);
14255 }
14256 
14257 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14258 				struct bpf_reg_state *true_dst,
14259 				struct bpf_reg_state *false_src,
14260 				struct bpf_reg_state *false_dst,
14261 				u8 opcode)
14262 {
14263 	switch (opcode) {
14264 	case BPF_JEQ:
14265 		__reg_combine_min_max(true_src, true_dst);
14266 		break;
14267 	case BPF_JNE:
14268 		__reg_combine_min_max(false_src, false_dst);
14269 		break;
14270 	}
14271 }
14272 
14273 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14274 				 struct bpf_reg_state *reg, u32 id,
14275 				 bool is_null)
14276 {
14277 	if (type_may_be_null(reg->type) && reg->id == id &&
14278 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14279 		/* Old offset (both fixed and variable parts) should have been
14280 		 * known-zero, because we don't allow pointer arithmetic on
14281 		 * pointers that might be NULL. If we see this happening, don't
14282 		 * convert the register.
14283 		 *
14284 		 * But in some cases, some helpers that return local kptrs
14285 		 * advance offset for the returned pointer. In those cases, it
14286 		 * is fine to expect to see reg->off.
14287 		 */
14288 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14289 			return;
14290 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14291 		    WARN_ON_ONCE(reg->off))
14292 			return;
14293 
14294 		if (is_null) {
14295 			reg->type = SCALAR_VALUE;
14296 			/* We don't need id and ref_obj_id from this point
14297 			 * onwards anymore, thus we should better reset it,
14298 			 * so that state pruning has chances to take effect.
14299 			 */
14300 			reg->id = 0;
14301 			reg->ref_obj_id = 0;
14302 
14303 			return;
14304 		}
14305 
14306 		mark_ptr_not_null_reg(reg);
14307 
14308 		if (!reg_may_point_to_spin_lock(reg)) {
14309 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14310 			 * in release_reference().
14311 			 *
14312 			 * reg->id is still used by spin_lock ptr. Other
14313 			 * than spin_lock ptr type, reg->id can be reset.
14314 			 */
14315 			reg->id = 0;
14316 		}
14317 	}
14318 }
14319 
14320 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14321  * be folded together at some point.
14322  */
14323 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14324 				  bool is_null)
14325 {
14326 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14327 	struct bpf_reg_state *regs = state->regs, *reg;
14328 	u32 ref_obj_id = regs[regno].ref_obj_id;
14329 	u32 id = regs[regno].id;
14330 
14331 	if (ref_obj_id && ref_obj_id == id && is_null)
14332 		/* regs[regno] is in the " == NULL" branch.
14333 		 * No one could have freed the reference state before
14334 		 * doing the NULL check.
14335 		 */
14336 		WARN_ON_ONCE(release_reference_state(state, id));
14337 
14338 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14339 		mark_ptr_or_null_reg(state, reg, id, is_null);
14340 	}));
14341 }
14342 
14343 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14344 				   struct bpf_reg_state *dst_reg,
14345 				   struct bpf_reg_state *src_reg,
14346 				   struct bpf_verifier_state *this_branch,
14347 				   struct bpf_verifier_state *other_branch)
14348 {
14349 	if (BPF_SRC(insn->code) != BPF_X)
14350 		return false;
14351 
14352 	/* Pointers are always 64-bit. */
14353 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14354 		return false;
14355 
14356 	switch (BPF_OP(insn->code)) {
14357 	case BPF_JGT:
14358 		if ((dst_reg->type == PTR_TO_PACKET &&
14359 		     src_reg->type == PTR_TO_PACKET_END) ||
14360 		    (dst_reg->type == PTR_TO_PACKET_META &&
14361 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14362 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14363 			find_good_pkt_pointers(this_branch, dst_reg,
14364 					       dst_reg->type, false);
14365 			mark_pkt_end(other_branch, insn->dst_reg, true);
14366 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14367 			    src_reg->type == PTR_TO_PACKET) ||
14368 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14369 			    src_reg->type == PTR_TO_PACKET_META)) {
14370 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14371 			find_good_pkt_pointers(other_branch, src_reg,
14372 					       src_reg->type, true);
14373 			mark_pkt_end(this_branch, insn->src_reg, false);
14374 		} else {
14375 			return false;
14376 		}
14377 		break;
14378 	case BPF_JLT:
14379 		if ((dst_reg->type == PTR_TO_PACKET &&
14380 		     src_reg->type == PTR_TO_PACKET_END) ||
14381 		    (dst_reg->type == PTR_TO_PACKET_META &&
14382 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14383 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14384 			find_good_pkt_pointers(other_branch, dst_reg,
14385 					       dst_reg->type, true);
14386 			mark_pkt_end(this_branch, insn->dst_reg, false);
14387 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14388 			    src_reg->type == PTR_TO_PACKET) ||
14389 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14390 			    src_reg->type == PTR_TO_PACKET_META)) {
14391 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14392 			find_good_pkt_pointers(this_branch, src_reg,
14393 					       src_reg->type, false);
14394 			mark_pkt_end(other_branch, insn->src_reg, true);
14395 		} else {
14396 			return false;
14397 		}
14398 		break;
14399 	case BPF_JGE:
14400 		if ((dst_reg->type == PTR_TO_PACKET &&
14401 		     src_reg->type == PTR_TO_PACKET_END) ||
14402 		    (dst_reg->type == PTR_TO_PACKET_META &&
14403 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14404 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14405 			find_good_pkt_pointers(this_branch, dst_reg,
14406 					       dst_reg->type, true);
14407 			mark_pkt_end(other_branch, insn->dst_reg, false);
14408 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14409 			    src_reg->type == PTR_TO_PACKET) ||
14410 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14411 			    src_reg->type == PTR_TO_PACKET_META)) {
14412 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14413 			find_good_pkt_pointers(other_branch, src_reg,
14414 					       src_reg->type, false);
14415 			mark_pkt_end(this_branch, insn->src_reg, true);
14416 		} else {
14417 			return false;
14418 		}
14419 		break;
14420 	case BPF_JLE:
14421 		if ((dst_reg->type == PTR_TO_PACKET &&
14422 		     src_reg->type == PTR_TO_PACKET_END) ||
14423 		    (dst_reg->type == PTR_TO_PACKET_META &&
14424 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14425 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14426 			find_good_pkt_pointers(other_branch, dst_reg,
14427 					       dst_reg->type, false);
14428 			mark_pkt_end(this_branch, insn->dst_reg, true);
14429 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14430 			    src_reg->type == PTR_TO_PACKET) ||
14431 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14432 			    src_reg->type == PTR_TO_PACKET_META)) {
14433 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14434 			find_good_pkt_pointers(this_branch, src_reg,
14435 					       src_reg->type, true);
14436 			mark_pkt_end(other_branch, insn->src_reg, false);
14437 		} else {
14438 			return false;
14439 		}
14440 		break;
14441 	default:
14442 		return false;
14443 	}
14444 
14445 	return true;
14446 }
14447 
14448 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14449 			       struct bpf_reg_state *known_reg)
14450 {
14451 	struct bpf_func_state *state;
14452 	struct bpf_reg_state *reg;
14453 
14454 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14455 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14456 			copy_register_state(reg, known_reg);
14457 	}));
14458 }
14459 
14460 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14461 			     struct bpf_insn *insn, int *insn_idx)
14462 {
14463 	struct bpf_verifier_state *this_branch = env->cur_state;
14464 	struct bpf_verifier_state *other_branch;
14465 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14466 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14467 	struct bpf_reg_state *eq_branch_regs;
14468 	u8 opcode = BPF_OP(insn->code);
14469 	bool is_jmp32;
14470 	int pred = -1;
14471 	int err;
14472 
14473 	/* Only conditional jumps are expected to reach here. */
14474 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14475 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14476 		return -EINVAL;
14477 	}
14478 
14479 	/* check src2 operand */
14480 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14481 	if (err)
14482 		return err;
14483 
14484 	dst_reg = &regs[insn->dst_reg];
14485 	if (BPF_SRC(insn->code) == BPF_X) {
14486 		if (insn->imm != 0) {
14487 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14488 			return -EINVAL;
14489 		}
14490 
14491 		/* check src1 operand */
14492 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14493 		if (err)
14494 			return err;
14495 
14496 		src_reg = &regs[insn->src_reg];
14497 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14498 		    is_pointer_value(env, insn->src_reg)) {
14499 			verbose(env, "R%d pointer comparison prohibited\n",
14500 				insn->src_reg);
14501 			return -EACCES;
14502 		}
14503 	} else {
14504 		if (insn->src_reg != BPF_REG_0) {
14505 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14506 			return -EINVAL;
14507 		}
14508 	}
14509 
14510 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14511 
14512 	if (BPF_SRC(insn->code) == BPF_K) {
14513 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14514 	} else if (src_reg->type == SCALAR_VALUE &&
14515 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14516 		pred = is_branch_taken(dst_reg,
14517 				       tnum_subreg(src_reg->var_off).value,
14518 				       opcode,
14519 				       is_jmp32);
14520 	} else if (src_reg->type == SCALAR_VALUE &&
14521 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14522 		pred = is_branch_taken(dst_reg,
14523 				       src_reg->var_off.value,
14524 				       opcode,
14525 				       is_jmp32);
14526 	} else if (dst_reg->type == SCALAR_VALUE &&
14527 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14528 		pred = is_branch_taken(src_reg,
14529 				       tnum_subreg(dst_reg->var_off).value,
14530 				       flip_opcode(opcode),
14531 				       is_jmp32);
14532 	} else if (dst_reg->type == SCALAR_VALUE &&
14533 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14534 		pred = is_branch_taken(src_reg,
14535 				       dst_reg->var_off.value,
14536 				       flip_opcode(opcode),
14537 				       is_jmp32);
14538 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14539 		   reg_is_pkt_pointer_any(src_reg) &&
14540 		   !is_jmp32) {
14541 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14542 	}
14543 
14544 	if (pred >= 0) {
14545 		/* If we get here with a dst_reg pointer type it is because
14546 		 * above is_branch_taken() special cased the 0 comparison.
14547 		 */
14548 		if (!__is_pointer_value(false, dst_reg))
14549 			err = mark_chain_precision(env, insn->dst_reg);
14550 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14551 		    !__is_pointer_value(false, src_reg))
14552 			err = mark_chain_precision(env, insn->src_reg);
14553 		if (err)
14554 			return err;
14555 	}
14556 
14557 	if (pred == 1) {
14558 		/* Only follow the goto, ignore fall-through. If needed, push
14559 		 * the fall-through branch for simulation under speculative
14560 		 * execution.
14561 		 */
14562 		if (!env->bypass_spec_v1 &&
14563 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14564 					       *insn_idx))
14565 			return -EFAULT;
14566 		if (env->log.level & BPF_LOG_LEVEL)
14567 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14568 		*insn_idx += insn->off;
14569 		return 0;
14570 	} else if (pred == 0) {
14571 		/* Only follow the fall-through branch, since that's where the
14572 		 * program will go. If needed, push the goto branch for
14573 		 * simulation under speculative execution.
14574 		 */
14575 		if (!env->bypass_spec_v1 &&
14576 		    !sanitize_speculative_path(env, insn,
14577 					       *insn_idx + insn->off + 1,
14578 					       *insn_idx))
14579 			return -EFAULT;
14580 		if (env->log.level & BPF_LOG_LEVEL)
14581 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14582 		return 0;
14583 	}
14584 
14585 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14586 				  false);
14587 	if (!other_branch)
14588 		return -EFAULT;
14589 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14590 
14591 	/* detect if we are comparing against a constant value so we can adjust
14592 	 * our min/max values for our dst register.
14593 	 * this is only legit if both are scalars (or pointers to the same
14594 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14595 	 * because otherwise the different base pointers mean the offsets aren't
14596 	 * comparable.
14597 	 */
14598 	if (BPF_SRC(insn->code) == BPF_X) {
14599 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14600 
14601 		if (dst_reg->type == SCALAR_VALUE &&
14602 		    src_reg->type == SCALAR_VALUE) {
14603 			if (tnum_is_const(src_reg->var_off) ||
14604 			    (is_jmp32 &&
14605 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14606 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14607 						dst_reg,
14608 						src_reg->var_off.value,
14609 						tnum_subreg(src_reg->var_off).value,
14610 						opcode, is_jmp32);
14611 			else if (tnum_is_const(dst_reg->var_off) ||
14612 				 (is_jmp32 &&
14613 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14614 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14615 						    src_reg,
14616 						    dst_reg->var_off.value,
14617 						    tnum_subreg(dst_reg->var_off).value,
14618 						    opcode, is_jmp32);
14619 			else if (!is_jmp32 &&
14620 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14621 				/* Comparing for equality, we can combine knowledge */
14622 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14623 						    &other_branch_regs[insn->dst_reg],
14624 						    src_reg, dst_reg, opcode);
14625 			if (src_reg->id &&
14626 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14627 				find_equal_scalars(this_branch, src_reg);
14628 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14629 			}
14630 
14631 		}
14632 	} else if (dst_reg->type == SCALAR_VALUE) {
14633 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14634 					dst_reg, insn->imm, (u32)insn->imm,
14635 					opcode, is_jmp32);
14636 	}
14637 
14638 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14639 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14640 		find_equal_scalars(this_branch, dst_reg);
14641 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14642 	}
14643 
14644 	/* if one pointer register is compared to another pointer
14645 	 * register check if PTR_MAYBE_NULL could be lifted.
14646 	 * E.g. register A - maybe null
14647 	 *      register B - not null
14648 	 * for JNE A, B, ... - A is not null in the false branch;
14649 	 * for JEQ A, B, ... - A is not null in the true branch.
14650 	 *
14651 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14652 	 * not need to be null checked by the BPF program, i.e.,
14653 	 * could be null even without PTR_MAYBE_NULL marking, so
14654 	 * only propagate nullness when neither reg is that type.
14655 	 */
14656 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14657 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14658 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14659 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14660 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14661 		eq_branch_regs = NULL;
14662 		switch (opcode) {
14663 		case BPF_JEQ:
14664 			eq_branch_regs = other_branch_regs;
14665 			break;
14666 		case BPF_JNE:
14667 			eq_branch_regs = regs;
14668 			break;
14669 		default:
14670 			/* do nothing */
14671 			break;
14672 		}
14673 		if (eq_branch_regs) {
14674 			if (type_may_be_null(src_reg->type))
14675 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14676 			else
14677 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14678 		}
14679 	}
14680 
14681 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14682 	 * NOTE: these optimizations below are related with pointer comparison
14683 	 *       which will never be JMP32.
14684 	 */
14685 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14686 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14687 	    type_may_be_null(dst_reg->type)) {
14688 		/* Mark all identical registers in each branch as either
14689 		 * safe or unknown depending R == 0 or R != 0 conditional.
14690 		 */
14691 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14692 				      opcode == BPF_JNE);
14693 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14694 				      opcode == BPF_JEQ);
14695 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14696 					   this_branch, other_branch) &&
14697 		   is_pointer_value(env, insn->dst_reg)) {
14698 		verbose(env, "R%d pointer comparison prohibited\n",
14699 			insn->dst_reg);
14700 		return -EACCES;
14701 	}
14702 	if (env->log.level & BPF_LOG_LEVEL)
14703 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14704 	return 0;
14705 }
14706 
14707 /* verify BPF_LD_IMM64 instruction */
14708 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14709 {
14710 	struct bpf_insn_aux_data *aux = cur_aux(env);
14711 	struct bpf_reg_state *regs = cur_regs(env);
14712 	struct bpf_reg_state *dst_reg;
14713 	struct bpf_map *map;
14714 	int err;
14715 
14716 	if (BPF_SIZE(insn->code) != BPF_DW) {
14717 		verbose(env, "invalid BPF_LD_IMM insn\n");
14718 		return -EINVAL;
14719 	}
14720 	if (insn->off != 0) {
14721 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14722 		return -EINVAL;
14723 	}
14724 
14725 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14726 	if (err)
14727 		return err;
14728 
14729 	dst_reg = &regs[insn->dst_reg];
14730 	if (insn->src_reg == 0) {
14731 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14732 
14733 		dst_reg->type = SCALAR_VALUE;
14734 		__mark_reg_known(&regs[insn->dst_reg], imm);
14735 		return 0;
14736 	}
14737 
14738 	/* All special src_reg cases are listed below. From this point onwards
14739 	 * we either succeed and assign a corresponding dst_reg->type after
14740 	 * zeroing the offset, or fail and reject the program.
14741 	 */
14742 	mark_reg_known_zero(env, regs, insn->dst_reg);
14743 
14744 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14745 		dst_reg->type = aux->btf_var.reg_type;
14746 		switch (base_type(dst_reg->type)) {
14747 		case PTR_TO_MEM:
14748 			dst_reg->mem_size = aux->btf_var.mem_size;
14749 			break;
14750 		case PTR_TO_BTF_ID:
14751 			dst_reg->btf = aux->btf_var.btf;
14752 			dst_reg->btf_id = aux->btf_var.btf_id;
14753 			break;
14754 		default:
14755 			verbose(env, "bpf verifier is misconfigured\n");
14756 			return -EFAULT;
14757 		}
14758 		return 0;
14759 	}
14760 
14761 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14762 		struct bpf_prog_aux *aux = env->prog->aux;
14763 		u32 subprogno = find_subprog(env,
14764 					     env->insn_idx + insn->imm + 1);
14765 
14766 		if (!aux->func_info) {
14767 			verbose(env, "missing btf func_info\n");
14768 			return -EINVAL;
14769 		}
14770 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14771 			verbose(env, "callback function not static\n");
14772 			return -EINVAL;
14773 		}
14774 
14775 		dst_reg->type = PTR_TO_FUNC;
14776 		dst_reg->subprogno = subprogno;
14777 		return 0;
14778 	}
14779 
14780 	map = env->used_maps[aux->map_index];
14781 	dst_reg->map_ptr = map;
14782 
14783 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14784 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14785 		dst_reg->type = PTR_TO_MAP_VALUE;
14786 		dst_reg->off = aux->map_off;
14787 		WARN_ON_ONCE(map->max_entries != 1);
14788 		/* We want reg->id to be same (0) as map_value is not distinct */
14789 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14790 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14791 		dst_reg->type = CONST_PTR_TO_MAP;
14792 	} else {
14793 		verbose(env, "bpf verifier is misconfigured\n");
14794 		return -EINVAL;
14795 	}
14796 
14797 	return 0;
14798 }
14799 
14800 static bool may_access_skb(enum bpf_prog_type type)
14801 {
14802 	switch (type) {
14803 	case BPF_PROG_TYPE_SOCKET_FILTER:
14804 	case BPF_PROG_TYPE_SCHED_CLS:
14805 	case BPF_PROG_TYPE_SCHED_ACT:
14806 		return true;
14807 	default:
14808 		return false;
14809 	}
14810 }
14811 
14812 /* verify safety of LD_ABS|LD_IND instructions:
14813  * - they can only appear in the programs where ctx == skb
14814  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14815  *   preserve R6-R9, and store return value into R0
14816  *
14817  * Implicit input:
14818  *   ctx == skb == R6 == CTX
14819  *
14820  * Explicit input:
14821  *   SRC == any register
14822  *   IMM == 32-bit immediate
14823  *
14824  * Output:
14825  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14826  */
14827 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14828 {
14829 	struct bpf_reg_state *regs = cur_regs(env);
14830 	static const int ctx_reg = BPF_REG_6;
14831 	u8 mode = BPF_MODE(insn->code);
14832 	int i, err;
14833 
14834 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14835 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14836 		return -EINVAL;
14837 	}
14838 
14839 	if (!env->ops->gen_ld_abs) {
14840 		verbose(env, "bpf verifier is misconfigured\n");
14841 		return -EINVAL;
14842 	}
14843 
14844 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14845 	    BPF_SIZE(insn->code) == BPF_DW ||
14846 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14847 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14848 		return -EINVAL;
14849 	}
14850 
14851 	/* check whether implicit source operand (register R6) is readable */
14852 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14853 	if (err)
14854 		return err;
14855 
14856 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14857 	 * gen_ld_abs() may terminate the program at runtime, leading to
14858 	 * reference leak.
14859 	 */
14860 	err = check_reference_leak(env);
14861 	if (err) {
14862 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14863 		return err;
14864 	}
14865 
14866 	if (env->cur_state->active_lock.ptr) {
14867 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14868 		return -EINVAL;
14869 	}
14870 
14871 	if (env->cur_state->active_rcu_lock) {
14872 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14873 		return -EINVAL;
14874 	}
14875 
14876 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14877 		verbose(env,
14878 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14879 		return -EINVAL;
14880 	}
14881 
14882 	if (mode == BPF_IND) {
14883 		/* check explicit source operand */
14884 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14885 		if (err)
14886 			return err;
14887 	}
14888 
14889 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14890 	if (err < 0)
14891 		return err;
14892 
14893 	/* reset caller saved regs to unreadable */
14894 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14895 		mark_reg_not_init(env, regs, caller_saved[i]);
14896 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14897 	}
14898 
14899 	/* mark destination R0 register as readable, since it contains
14900 	 * the value fetched from the packet.
14901 	 * Already marked as written above.
14902 	 */
14903 	mark_reg_unknown(env, regs, BPF_REG_0);
14904 	/* ld_abs load up to 32-bit skb data. */
14905 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14906 	return 0;
14907 }
14908 
14909 static int check_return_code(struct bpf_verifier_env *env)
14910 {
14911 	struct tnum enforce_attach_type_range = tnum_unknown;
14912 	const struct bpf_prog *prog = env->prog;
14913 	struct bpf_reg_state *reg;
14914 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14915 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14916 	int err;
14917 	struct bpf_func_state *frame = env->cur_state->frame[0];
14918 	const bool is_subprog = frame->subprogno;
14919 
14920 	/* LSM and struct_ops func-ptr's return type could be "void" */
14921 	if (!is_subprog) {
14922 		switch (prog_type) {
14923 		case BPF_PROG_TYPE_LSM:
14924 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14925 				/* See below, can be 0 or 0-1 depending on hook. */
14926 				break;
14927 			fallthrough;
14928 		case BPF_PROG_TYPE_STRUCT_OPS:
14929 			if (!prog->aux->attach_func_proto->type)
14930 				return 0;
14931 			break;
14932 		default:
14933 			break;
14934 		}
14935 	}
14936 
14937 	/* eBPF calling convention is such that R0 is used
14938 	 * to return the value from eBPF program.
14939 	 * Make sure that it's readable at this time
14940 	 * of bpf_exit, which means that program wrote
14941 	 * something into it earlier
14942 	 */
14943 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14944 	if (err)
14945 		return err;
14946 
14947 	if (is_pointer_value(env, BPF_REG_0)) {
14948 		verbose(env, "R0 leaks addr as return value\n");
14949 		return -EACCES;
14950 	}
14951 
14952 	reg = cur_regs(env) + BPF_REG_0;
14953 
14954 	if (frame->in_async_callback_fn) {
14955 		/* enforce return zero from async callbacks like timer */
14956 		if (reg->type != SCALAR_VALUE) {
14957 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14958 				reg_type_str(env, reg->type));
14959 			return -EINVAL;
14960 		}
14961 
14962 		if (!tnum_in(const_0, reg->var_off)) {
14963 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14964 			return -EINVAL;
14965 		}
14966 		return 0;
14967 	}
14968 
14969 	if (is_subprog) {
14970 		if (reg->type != SCALAR_VALUE) {
14971 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14972 				reg_type_str(env, reg->type));
14973 			return -EINVAL;
14974 		}
14975 		return 0;
14976 	}
14977 
14978 	switch (prog_type) {
14979 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14980 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14981 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14982 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14983 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14984 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14985 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14986 			range = tnum_range(1, 1);
14987 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14988 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14989 			range = tnum_range(0, 3);
14990 		break;
14991 	case BPF_PROG_TYPE_CGROUP_SKB:
14992 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14993 			range = tnum_range(0, 3);
14994 			enforce_attach_type_range = tnum_range(2, 3);
14995 		}
14996 		break;
14997 	case BPF_PROG_TYPE_CGROUP_SOCK:
14998 	case BPF_PROG_TYPE_SOCK_OPS:
14999 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15000 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15001 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15002 		break;
15003 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15004 		if (!env->prog->aux->attach_btf_id)
15005 			return 0;
15006 		range = tnum_const(0);
15007 		break;
15008 	case BPF_PROG_TYPE_TRACING:
15009 		switch (env->prog->expected_attach_type) {
15010 		case BPF_TRACE_FENTRY:
15011 		case BPF_TRACE_FEXIT:
15012 			range = tnum_const(0);
15013 			break;
15014 		case BPF_TRACE_RAW_TP:
15015 		case BPF_MODIFY_RETURN:
15016 			return 0;
15017 		case BPF_TRACE_ITER:
15018 			break;
15019 		default:
15020 			return -ENOTSUPP;
15021 		}
15022 		break;
15023 	case BPF_PROG_TYPE_SK_LOOKUP:
15024 		range = tnum_range(SK_DROP, SK_PASS);
15025 		break;
15026 
15027 	case BPF_PROG_TYPE_LSM:
15028 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15029 			/* Regular BPF_PROG_TYPE_LSM programs can return
15030 			 * any value.
15031 			 */
15032 			return 0;
15033 		}
15034 		if (!env->prog->aux->attach_func_proto->type) {
15035 			/* Make sure programs that attach to void
15036 			 * hooks don't try to modify return value.
15037 			 */
15038 			range = tnum_range(1, 1);
15039 		}
15040 		break;
15041 
15042 	case BPF_PROG_TYPE_NETFILTER:
15043 		range = tnum_range(NF_DROP, NF_ACCEPT);
15044 		break;
15045 	case BPF_PROG_TYPE_EXT:
15046 		/* freplace program can return anything as its return value
15047 		 * depends on the to-be-replaced kernel func or bpf program.
15048 		 */
15049 	default:
15050 		return 0;
15051 	}
15052 
15053 	if (reg->type != SCALAR_VALUE) {
15054 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15055 			reg_type_str(env, reg->type));
15056 		return -EINVAL;
15057 	}
15058 
15059 	if (!tnum_in(range, reg->var_off)) {
15060 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15061 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15062 		    prog_type == BPF_PROG_TYPE_LSM &&
15063 		    !prog->aux->attach_func_proto->type)
15064 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15065 		return -EINVAL;
15066 	}
15067 
15068 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15069 	    tnum_in(enforce_attach_type_range, reg->var_off))
15070 		env->prog->enforce_expected_attach_type = 1;
15071 	return 0;
15072 }
15073 
15074 /* non-recursive DFS pseudo code
15075  * 1  procedure DFS-iterative(G,v):
15076  * 2      label v as discovered
15077  * 3      let S be a stack
15078  * 4      S.push(v)
15079  * 5      while S is not empty
15080  * 6            t <- S.peek()
15081  * 7            if t is what we're looking for:
15082  * 8                return t
15083  * 9            for all edges e in G.adjacentEdges(t) do
15084  * 10               if edge e is already labelled
15085  * 11                   continue with the next edge
15086  * 12               w <- G.adjacentVertex(t,e)
15087  * 13               if vertex w is not discovered and not explored
15088  * 14                   label e as tree-edge
15089  * 15                   label w as discovered
15090  * 16                   S.push(w)
15091  * 17                   continue at 5
15092  * 18               else if vertex w is discovered
15093  * 19                   label e as back-edge
15094  * 20               else
15095  * 21                   // vertex w is explored
15096  * 22                   label e as forward- or cross-edge
15097  * 23           label t as explored
15098  * 24           S.pop()
15099  *
15100  * convention:
15101  * 0x10 - discovered
15102  * 0x11 - discovered and fall-through edge labelled
15103  * 0x12 - discovered and fall-through and branch edges labelled
15104  * 0x20 - explored
15105  */
15106 
15107 enum {
15108 	DISCOVERED = 0x10,
15109 	EXPLORED = 0x20,
15110 	FALLTHROUGH = 1,
15111 	BRANCH = 2,
15112 };
15113 
15114 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15115 {
15116 	env->insn_aux_data[idx].prune_point = true;
15117 }
15118 
15119 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15120 {
15121 	return env->insn_aux_data[insn_idx].prune_point;
15122 }
15123 
15124 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15125 {
15126 	env->insn_aux_data[idx].force_checkpoint = true;
15127 }
15128 
15129 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15130 {
15131 	return env->insn_aux_data[insn_idx].force_checkpoint;
15132 }
15133 
15134 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15135 {
15136 	env->insn_aux_data[idx].calls_callback = true;
15137 }
15138 
15139 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15140 {
15141 	return env->insn_aux_data[insn_idx].calls_callback;
15142 }
15143 
15144 enum {
15145 	DONE_EXPLORING = 0,
15146 	KEEP_EXPLORING = 1,
15147 };
15148 
15149 /* t, w, e - match pseudo-code above:
15150  * t - index of current instruction
15151  * w - next instruction
15152  * e - edge
15153  */
15154 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15155 {
15156 	int *insn_stack = env->cfg.insn_stack;
15157 	int *insn_state = env->cfg.insn_state;
15158 
15159 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15160 		return DONE_EXPLORING;
15161 
15162 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15163 		return DONE_EXPLORING;
15164 
15165 	if (w < 0 || w >= env->prog->len) {
15166 		verbose_linfo(env, t, "%d: ", t);
15167 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15168 		return -EINVAL;
15169 	}
15170 
15171 	if (e == BRANCH) {
15172 		/* mark branch target for state pruning */
15173 		mark_prune_point(env, w);
15174 		mark_jmp_point(env, w);
15175 	}
15176 
15177 	if (insn_state[w] == 0) {
15178 		/* tree-edge */
15179 		insn_state[t] = DISCOVERED | e;
15180 		insn_state[w] = DISCOVERED;
15181 		if (env->cfg.cur_stack >= env->prog->len)
15182 			return -E2BIG;
15183 		insn_stack[env->cfg.cur_stack++] = w;
15184 		return KEEP_EXPLORING;
15185 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15186 		if (env->bpf_capable)
15187 			return DONE_EXPLORING;
15188 		verbose_linfo(env, t, "%d: ", t);
15189 		verbose_linfo(env, w, "%d: ", w);
15190 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15191 		return -EINVAL;
15192 	} else if (insn_state[w] == EXPLORED) {
15193 		/* forward- or cross-edge */
15194 		insn_state[t] = DISCOVERED | e;
15195 	} else {
15196 		verbose(env, "insn state internal bug\n");
15197 		return -EFAULT;
15198 	}
15199 	return DONE_EXPLORING;
15200 }
15201 
15202 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15203 				struct bpf_verifier_env *env,
15204 				bool visit_callee)
15205 {
15206 	int ret, insn_sz;
15207 
15208 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15209 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15210 	if (ret)
15211 		return ret;
15212 
15213 	mark_prune_point(env, t + insn_sz);
15214 	/* when we exit from subprog, we need to record non-linear history */
15215 	mark_jmp_point(env, t + insn_sz);
15216 
15217 	if (visit_callee) {
15218 		mark_prune_point(env, t);
15219 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15220 	}
15221 	return ret;
15222 }
15223 
15224 /* Visits the instruction at index t and returns one of the following:
15225  *  < 0 - an error occurred
15226  *  DONE_EXPLORING - the instruction was fully explored
15227  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15228  */
15229 static int visit_insn(int t, struct bpf_verifier_env *env)
15230 {
15231 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15232 	int ret, off, insn_sz;
15233 
15234 	if (bpf_pseudo_func(insn))
15235 		return visit_func_call_insn(t, insns, env, true);
15236 
15237 	/* All non-branch instructions have a single fall-through edge. */
15238 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15239 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15240 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15241 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15242 	}
15243 
15244 	switch (BPF_OP(insn->code)) {
15245 	case BPF_EXIT:
15246 		return DONE_EXPLORING;
15247 
15248 	case BPF_CALL:
15249 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15250 			/* Mark this call insn as a prune point to trigger
15251 			 * is_state_visited() check before call itself is
15252 			 * processed by __check_func_call(). Otherwise new
15253 			 * async state will be pushed for further exploration.
15254 			 */
15255 			mark_prune_point(env, t);
15256 		/* For functions that invoke callbacks it is not known how many times
15257 		 * callback would be called. Verifier models callback calling functions
15258 		 * by repeatedly visiting callback bodies and returning to origin call
15259 		 * instruction.
15260 		 * In order to stop such iteration verifier needs to identify when a
15261 		 * state identical some state from a previous iteration is reached.
15262 		 * Check below forces creation of checkpoint before callback calling
15263 		 * instruction to allow search for such identical states.
15264 		 */
15265 		if (is_sync_callback_calling_insn(insn)) {
15266 			mark_calls_callback(env, t);
15267 			mark_force_checkpoint(env, t);
15268 			mark_prune_point(env, t);
15269 			mark_jmp_point(env, t);
15270 		}
15271 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15272 			struct bpf_kfunc_call_arg_meta meta;
15273 
15274 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15275 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15276 				mark_prune_point(env, t);
15277 				/* Checking and saving state checkpoints at iter_next() call
15278 				 * is crucial for fast convergence of open-coded iterator loop
15279 				 * logic, so we need to force it. If we don't do that,
15280 				 * is_state_visited() might skip saving a checkpoint, causing
15281 				 * unnecessarily long sequence of not checkpointed
15282 				 * instructions and jumps, leading to exhaustion of jump
15283 				 * history buffer, and potentially other undesired outcomes.
15284 				 * It is expected that with correct open-coded iterators
15285 				 * convergence will happen quickly, so we don't run a risk of
15286 				 * exhausting memory.
15287 				 */
15288 				mark_force_checkpoint(env, t);
15289 			}
15290 		}
15291 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15292 
15293 	case BPF_JA:
15294 		if (BPF_SRC(insn->code) != BPF_K)
15295 			return -EINVAL;
15296 
15297 		if (BPF_CLASS(insn->code) == BPF_JMP)
15298 			off = insn->off;
15299 		else
15300 			off = insn->imm;
15301 
15302 		/* unconditional jump with single edge */
15303 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15304 		if (ret)
15305 			return ret;
15306 
15307 		mark_prune_point(env, t + off + 1);
15308 		mark_jmp_point(env, t + off + 1);
15309 
15310 		return ret;
15311 
15312 	default:
15313 		/* conditional jump with two edges */
15314 		mark_prune_point(env, t);
15315 
15316 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15317 		if (ret)
15318 			return ret;
15319 
15320 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15321 	}
15322 }
15323 
15324 /* non-recursive depth-first-search to detect loops in BPF program
15325  * loop == back-edge in directed graph
15326  */
15327 static int check_cfg(struct bpf_verifier_env *env)
15328 {
15329 	int insn_cnt = env->prog->len;
15330 	int *insn_stack, *insn_state;
15331 	int ret = 0;
15332 	int i;
15333 
15334 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15335 	if (!insn_state)
15336 		return -ENOMEM;
15337 
15338 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15339 	if (!insn_stack) {
15340 		kvfree(insn_state);
15341 		return -ENOMEM;
15342 	}
15343 
15344 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15345 	insn_stack[0] = 0; /* 0 is the first instruction */
15346 	env->cfg.cur_stack = 1;
15347 
15348 	while (env->cfg.cur_stack > 0) {
15349 		int t = insn_stack[env->cfg.cur_stack - 1];
15350 
15351 		ret = visit_insn(t, env);
15352 		switch (ret) {
15353 		case DONE_EXPLORING:
15354 			insn_state[t] = EXPLORED;
15355 			env->cfg.cur_stack--;
15356 			break;
15357 		case KEEP_EXPLORING:
15358 			break;
15359 		default:
15360 			if (ret > 0) {
15361 				verbose(env, "visit_insn internal bug\n");
15362 				ret = -EFAULT;
15363 			}
15364 			goto err_free;
15365 		}
15366 	}
15367 
15368 	if (env->cfg.cur_stack < 0) {
15369 		verbose(env, "pop stack internal bug\n");
15370 		ret = -EFAULT;
15371 		goto err_free;
15372 	}
15373 
15374 	for (i = 0; i < insn_cnt; i++) {
15375 		struct bpf_insn *insn = &env->prog->insnsi[i];
15376 
15377 		if (insn_state[i] != EXPLORED) {
15378 			verbose(env, "unreachable insn %d\n", i);
15379 			ret = -EINVAL;
15380 			goto err_free;
15381 		}
15382 		if (bpf_is_ldimm64(insn)) {
15383 			if (insn_state[i + 1] != 0) {
15384 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15385 				ret = -EINVAL;
15386 				goto err_free;
15387 			}
15388 			i++; /* skip second half of ldimm64 */
15389 		}
15390 	}
15391 	ret = 0; /* cfg looks good */
15392 
15393 err_free:
15394 	kvfree(insn_state);
15395 	kvfree(insn_stack);
15396 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15397 	return ret;
15398 }
15399 
15400 static int check_abnormal_return(struct bpf_verifier_env *env)
15401 {
15402 	int i;
15403 
15404 	for (i = 1; i < env->subprog_cnt; i++) {
15405 		if (env->subprog_info[i].has_ld_abs) {
15406 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15407 			return -EINVAL;
15408 		}
15409 		if (env->subprog_info[i].has_tail_call) {
15410 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15411 			return -EINVAL;
15412 		}
15413 	}
15414 	return 0;
15415 }
15416 
15417 /* The minimum supported BTF func info size */
15418 #define MIN_BPF_FUNCINFO_SIZE	8
15419 #define MAX_FUNCINFO_REC_SIZE	252
15420 
15421 static int check_btf_func(struct bpf_verifier_env *env,
15422 			  const union bpf_attr *attr,
15423 			  bpfptr_t uattr)
15424 {
15425 	const struct btf_type *type, *func_proto, *ret_type;
15426 	u32 i, nfuncs, urec_size, min_size;
15427 	u32 krec_size = sizeof(struct bpf_func_info);
15428 	struct bpf_func_info *krecord;
15429 	struct bpf_func_info_aux *info_aux = NULL;
15430 	struct bpf_prog *prog;
15431 	const struct btf *btf;
15432 	bpfptr_t urecord;
15433 	u32 prev_offset = 0;
15434 	bool scalar_return;
15435 	int ret = -ENOMEM;
15436 
15437 	nfuncs = attr->func_info_cnt;
15438 	if (!nfuncs) {
15439 		if (check_abnormal_return(env))
15440 			return -EINVAL;
15441 		return 0;
15442 	}
15443 
15444 	if (nfuncs != env->subprog_cnt) {
15445 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15446 		return -EINVAL;
15447 	}
15448 
15449 	urec_size = attr->func_info_rec_size;
15450 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15451 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15452 	    urec_size % sizeof(u32)) {
15453 		verbose(env, "invalid func info rec size %u\n", urec_size);
15454 		return -EINVAL;
15455 	}
15456 
15457 	prog = env->prog;
15458 	btf = prog->aux->btf;
15459 
15460 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15461 	min_size = min_t(u32, krec_size, urec_size);
15462 
15463 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15464 	if (!krecord)
15465 		return -ENOMEM;
15466 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15467 	if (!info_aux)
15468 		goto err_free;
15469 
15470 	for (i = 0; i < nfuncs; i++) {
15471 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15472 		if (ret) {
15473 			if (ret == -E2BIG) {
15474 				verbose(env, "nonzero tailing record in func info");
15475 				/* set the size kernel expects so loader can zero
15476 				 * out the rest of the record.
15477 				 */
15478 				if (copy_to_bpfptr_offset(uattr,
15479 							  offsetof(union bpf_attr, func_info_rec_size),
15480 							  &min_size, sizeof(min_size)))
15481 					ret = -EFAULT;
15482 			}
15483 			goto err_free;
15484 		}
15485 
15486 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15487 			ret = -EFAULT;
15488 			goto err_free;
15489 		}
15490 
15491 		/* check insn_off */
15492 		ret = -EINVAL;
15493 		if (i == 0) {
15494 			if (krecord[i].insn_off) {
15495 				verbose(env,
15496 					"nonzero insn_off %u for the first func info record",
15497 					krecord[i].insn_off);
15498 				goto err_free;
15499 			}
15500 		} else if (krecord[i].insn_off <= prev_offset) {
15501 			verbose(env,
15502 				"same or smaller insn offset (%u) than previous func info record (%u)",
15503 				krecord[i].insn_off, prev_offset);
15504 			goto err_free;
15505 		}
15506 
15507 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15508 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15509 			goto err_free;
15510 		}
15511 
15512 		/* check type_id */
15513 		type = btf_type_by_id(btf, krecord[i].type_id);
15514 		if (!type || !btf_type_is_func(type)) {
15515 			verbose(env, "invalid type id %d in func info",
15516 				krecord[i].type_id);
15517 			goto err_free;
15518 		}
15519 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15520 
15521 		func_proto = btf_type_by_id(btf, type->type);
15522 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15523 			/* btf_func_check() already verified it during BTF load */
15524 			goto err_free;
15525 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15526 		scalar_return =
15527 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15528 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15529 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15530 			goto err_free;
15531 		}
15532 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15533 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15534 			goto err_free;
15535 		}
15536 
15537 		prev_offset = krecord[i].insn_off;
15538 		bpfptr_add(&urecord, urec_size);
15539 	}
15540 
15541 	prog->aux->func_info = krecord;
15542 	prog->aux->func_info_cnt = nfuncs;
15543 	prog->aux->func_info_aux = info_aux;
15544 	return 0;
15545 
15546 err_free:
15547 	kvfree(krecord);
15548 	kfree(info_aux);
15549 	return ret;
15550 }
15551 
15552 static void adjust_btf_func(struct bpf_verifier_env *env)
15553 {
15554 	struct bpf_prog_aux *aux = env->prog->aux;
15555 	int i;
15556 
15557 	if (!aux->func_info)
15558 		return;
15559 
15560 	for (i = 0; i < env->subprog_cnt; i++)
15561 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15562 }
15563 
15564 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15565 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15566 
15567 static int check_btf_line(struct bpf_verifier_env *env,
15568 			  const union bpf_attr *attr,
15569 			  bpfptr_t uattr)
15570 {
15571 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15572 	struct bpf_subprog_info *sub;
15573 	struct bpf_line_info *linfo;
15574 	struct bpf_prog *prog;
15575 	const struct btf *btf;
15576 	bpfptr_t ulinfo;
15577 	int err;
15578 
15579 	nr_linfo = attr->line_info_cnt;
15580 	if (!nr_linfo)
15581 		return 0;
15582 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15583 		return -EINVAL;
15584 
15585 	rec_size = attr->line_info_rec_size;
15586 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15587 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15588 	    rec_size & (sizeof(u32) - 1))
15589 		return -EINVAL;
15590 
15591 	/* Need to zero it in case the userspace may
15592 	 * pass in a smaller bpf_line_info object.
15593 	 */
15594 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15595 			 GFP_KERNEL | __GFP_NOWARN);
15596 	if (!linfo)
15597 		return -ENOMEM;
15598 
15599 	prog = env->prog;
15600 	btf = prog->aux->btf;
15601 
15602 	s = 0;
15603 	sub = env->subprog_info;
15604 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15605 	expected_size = sizeof(struct bpf_line_info);
15606 	ncopy = min_t(u32, expected_size, rec_size);
15607 	for (i = 0; i < nr_linfo; i++) {
15608 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15609 		if (err) {
15610 			if (err == -E2BIG) {
15611 				verbose(env, "nonzero tailing record in line_info");
15612 				if (copy_to_bpfptr_offset(uattr,
15613 							  offsetof(union bpf_attr, line_info_rec_size),
15614 							  &expected_size, sizeof(expected_size)))
15615 					err = -EFAULT;
15616 			}
15617 			goto err_free;
15618 		}
15619 
15620 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15621 			err = -EFAULT;
15622 			goto err_free;
15623 		}
15624 
15625 		/*
15626 		 * Check insn_off to ensure
15627 		 * 1) strictly increasing AND
15628 		 * 2) bounded by prog->len
15629 		 *
15630 		 * The linfo[0].insn_off == 0 check logically falls into
15631 		 * the later "missing bpf_line_info for func..." case
15632 		 * because the first linfo[0].insn_off must be the
15633 		 * first sub also and the first sub must have
15634 		 * subprog_info[0].start == 0.
15635 		 */
15636 		if ((i && linfo[i].insn_off <= prev_offset) ||
15637 		    linfo[i].insn_off >= prog->len) {
15638 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15639 				i, linfo[i].insn_off, prev_offset,
15640 				prog->len);
15641 			err = -EINVAL;
15642 			goto err_free;
15643 		}
15644 
15645 		if (!prog->insnsi[linfo[i].insn_off].code) {
15646 			verbose(env,
15647 				"Invalid insn code at line_info[%u].insn_off\n",
15648 				i);
15649 			err = -EINVAL;
15650 			goto err_free;
15651 		}
15652 
15653 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15654 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15655 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15656 			err = -EINVAL;
15657 			goto err_free;
15658 		}
15659 
15660 		if (s != env->subprog_cnt) {
15661 			if (linfo[i].insn_off == sub[s].start) {
15662 				sub[s].linfo_idx = i;
15663 				s++;
15664 			} else if (sub[s].start < linfo[i].insn_off) {
15665 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15666 				err = -EINVAL;
15667 				goto err_free;
15668 			}
15669 		}
15670 
15671 		prev_offset = linfo[i].insn_off;
15672 		bpfptr_add(&ulinfo, rec_size);
15673 	}
15674 
15675 	if (s != env->subprog_cnt) {
15676 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15677 			env->subprog_cnt - s, s);
15678 		err = -EINVAL;
15679 		goto err_free;
15680 	}
15681 
15682 	prog->aux->linfo = linfo;
15683 	prog->aux->nr_linfo = nr_linfo;
15684 
15685 	return 0;
15686 
15687 err_free:
15688 	kvfree(linfo);
15689 	return err;
15690 }
15691 
15692 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15693 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15694 
15695 static int check_core_relo(struct bpf_verifier_env *env,
15696 			   const union bpf_attr *attr,
15697 			   bpfptr_t uattr)
15698 {
15699 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15700 	struct bpf_core_relo core_relo = {};
15701 	struct bpf_prog *prog = env->prog;
15702 	const struct btf *btf = prog->aux->btf;
15703 	struct bpf_core_ctx ctx = {
15704 		.log = &env->log,
15705 		.btf = btf,
15706 	};
15707 	bpfptr_t u_core_relo;
15708 	int err;
15709 
15710 	nr_core_relo = attr->core_relo_cnt;
15711 	if (!nr_core_relo)
15712 		return 0;
15713 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15714 		return -EINVAL;
15715 
15716 	rec_size = attr->core_relo_rec_size;
15717 	if (rec_size < MIN_CORE_RELO_SIZE ||
15718 	    rec_size > MAX_CORE_RELO_SIZE ||
15719 	    rec_size % sizeof(u32))
15720 		return -EINVAL;
15721 
15722 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15723 	expected_size = sizeof(struct bpf_core_relo);
15724 	ncopy = min_t(u32, expected_size, rec_size);
15725 
15726 	/* Unlike func_info and line_info, copy and apply each CO-RE
15727 	 * relocation record one at a time.
15728 	 */
15729 	for (i = 0; i < nr_core_relo; i++) {
15730 		/* future proofing when sizeof(bpf_core_relo) changes */
15731 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15732 		if (err) {
15733 			if (err == -E2BIG) {
15734 				verbose(env, "nonzero tailing record in core_relo");
15735 				if (copy_to_bpfptr_offset(uattr,
15736 							  offsetof(union bpf_attr, core_relo_rec_size),
15737 							  &expected_size, sizeof(expected_size)))
15738 					err = -EFAULT;
15739 			}
15740 			break;
15741 		}
15742 
15743 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15744 			err = -EFAULT;
15745 			break;
15746 		}
15747 
15748 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15749 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15750 				i, core_relo.insn_off, prog->len);
15751 			err = -EINVAL;
15752 			break;
15753 		}
15754 
15755 		err = bpf_core_apply(&ctx, &core_relo, i,
15756 				     &prog->insnsi[core_relo.insn_off / 8]);
15757 		if (err)
15758 			break;
15759 		bpfptr_add(&u_core_relo, rec_size);
15760 	}
15761 	return err;
15762 }
15763 
15764 static int check_btf_info(struct bpf_verifier_env *env,
15765 			  const union bpf_attr *attr,
15766 			  bpfptr_t uattr)
15767 {
15768 	struct btf *btf;
15769 	int err;
15770 
15771 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15772 		if (check_abnormal_return(env))
15773 			return -EINVAL;
15774 		return 0;
15775 	}
15776 
15777 	btf = btf_get_by_fd(attr->prog_btf_fd);
15778 	if (IS_ERR(btf))
15779 		return PTR_ERR(btf);
15780 	if (btf_is_kernel(btf)) {
15781 		btf_put(btf);
15782 		return -EACCES;
15783 	}
15784 	env->prog->aux->btf = btf;
15785 
15786 	err = check_btf_func(env, attr, uattr);
15787 	if (err)
15788 		return err;
15789 
15790 	err = check_btf_line(env, attr, uattr);
15791 	if (err)
15792 		return err;
15793 
15794 	err = check_core_relo(env, attr, uattr);
15795 	if (err)
15796 		return err;
15797 
15798 	return 0;
15799 }
15800 
15801 /* check %cur's range satisfies %old's */
15802 static bool range_within(struct bpf_reg_state *old,
15803 			 struct bpf_reg_state *cur)
15804 {
15805 	return old->umin_value <= cur->umin_value &&
15806 	       old->umax_value >= cur->umax_value &&
15807 	       old->smin_value <= cur->smin_value &&
15808 	       old->smax_value >= cur->smax_value &&
15809 	       old->u32_min_value <= cur->u32_min_value &&
15810 	       old->u32_max_value >= cur->u32_max_value &&
15811 	       old->s32_min_value <= cur->s32_min_value &&
15812 	       old->s32_max_value >= cur->s32_max_value;
15813 }
15814 
15815 /* If in the old state two registers had the same id, then they need to have
15816  * the same id in the new state as well.  But that id could be different from
15817  * the old state, so we need to track the mapping from old to new ids.
15818  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15819  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15820  * regs with a different old id could still have new id 9, we don't care about
15821  * that.
15822  * So we look through our idmap to see if this old id has been seen before.  If
15823  * so, we require the new id to match; otherwise, we add the id pair to the map.
15824  */
15825 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15826 {
15827 	struct bpf_id_pair *map = idmap->map;
15828 	unsigned int i;
15829 
15830 	/* either both IDs should be set or both should be zero */
15831 	if (!!old_id != !!cur_id)
15832 		return false;
15833 
15834 	if (old_id == 0) /* cur_id == 0 as well */
15835 		return true;
15836 
15837 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15838 		if (!map[i].old) {
15839 			/* Reached an empty slot; haven't seen this id before */
15840 			map[i].old = old_id;
15841 			map[i].cur = cur_id;
15842 			return true;
15843 		}
15844 		if (map[i].old == old_id)
15845 			return map[i].cur == cur_id;
15846 		if (map[i].cur == cur_id)
15847 			return false;
15848 	}
15849 	/* We ran out of idmap slots, which should be impossible */
15850 	WARN_ON_ONCE(1);
15851 	return false;
15852 }
15853 
15854 /* Similar to check_ids(), but allocate a unique temporary ID
15855  * for 'old_id' or 'cur_id' of zero.
15856  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15857  */
15858 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15859 {
15860 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15861 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15862 
15863 	return check_ids(old_id, cur_id, idmap);
15864 }
15865 
15866 static void clean_func_state(struct bpf_verifier_env *env,
15867 			     struct bpf_func_state *st)
15868 {
15869 	enum bpf_reg_liveness live;
15870 	int i, j;
15871 
15872 	for (i = 0; i < BPF_REG_FP; i++) {
15873 		live = st->regs[i].live;
15874 		/* liveness must not touch this register anymore */
15875 		st->regs[i].live |= REG_LIVE_DONE;
15876 		if (!(live & REG_LIVE_READ))
15877 			/* since the register is unused, clear its state
15878 			 * to make further comparison simpler
15879 			 */
15880 			__mark_reg_not_init(env, &st->regs[i]);
15881 	}
15882 
15883 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15884 		live = st->stack[i].spilled_ptr.live;
15885 		/* liveness must not touch this stack slot anymore */
15886 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15887 		if (!(live & REG_LIVE_READ)) {
15888 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15889 			for (j = 0; j < BPF_REG_SIZE; j++)
15890 				st->stack[i].slot_type[j] = STACK_INVALID;
15891 		}
15892 	}
15893 }
15894 
15895 static void clean_verifier_state(struct bpf_verifier_env *env,
15896 				 struct bpf_verifier_state *st)
15897 {
15898 	int i;
15899 
15900 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15901 		/* all regs in this state in all frames were already marked */
15902 		return;
15903 
15904 	for (i = 0; i <= st->curframe; i++)
15905 		clean_func_state(env, st->frame[i]);
15906 }
15907 
15908 /* the parentage chains form a tree.
15909  * the verifier states are added to state lists at given insn and
15910  * pushed into state stack for future exploration.
15911  * when the verifier reaches bpf_exit insn some of the verifer states
15912  * stored in the state lists have their final liveness state already,
15913  * but a lot of states will get revised from liveness point of view when
15914  * the verifier explores other branches.
15915  * Example:
15916  * 1: r0 = 1
15917  * 2: if r1 == 100 goto pc+1
15918  * 3: r0 = 2
15919  * 4: exit
15920  * when the verifier reaches exit insn the register r0 in the state list of
15921  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15922  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15923  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15924  *
15925  * Since the verifier pushes the branch states as it sees them while exploring
15926  * the program the condition of walking the branch instruction for the second
15927  * time means that all states below this branch were already explored and
15928  * their final liveness marks are already propagated.
15929  * Hence when the verifier completes the search of state list in is_state_visited()
15930  * we can call this clean_live_states() function to mark all liveness states
15931  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15932  * will not be used.
15933  * This function also clears the registers and stack for states that !READ
15934  * to simplify state merging.
15935  *
15936  * Important note here that walking the same branch instruction in the callee
15937  * doesn't meant that the states are DONE. The verifier has to compare
15938  * the callsites
15939  */
15940 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15941 			      struct bpf_verifier_state *cur)
15942 {
15943 	struct bpf_verifier_state_list *sl;
15944 
15945 	sl = *explored_state(env, insn);
15946 	while (sl) {
15947 		if (sl->state.branches)
15948 			goto next;
15949 		if (sl->state.insn_idx != insn ||
15950 		    !same_callsites(&sl->state, cur))
15951 			goto next;
15952 		clean_verifier_state(env, &sl->state);
15953 next:
15954 		sl = sl->next;
15955 	}
15956 }
15957 
15958 static bool regs_exact(const struct bpf_reg_state *rold,
15959 		       const struct bpf_reg_state *rcur,
15960 		       struct bpf_idmap *idmap)
15961 {
15962 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15963 	       check_ids(rold->id, rcur->id, idmap) &&
15964 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15965 }
15966 
15967 /* Returns true if (rold safe implies rcur safe) */
15968 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15969 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15970 {
15971 	if (exact)
15972 		return regs_exact(rold, rcur, idmap);
15973 
15974 	if (!(rold->live & REG_LIVE_READ))
15975 		/* explored state didn't use this */
15976 		return true;
15977 	if (rold->type == NOT_INIT)
15978 		/* explored state can't have used this */
15979 		return true;
15980 	if (rcur->type == NOT_INIT)
15981 		return false;
15982 
15983 	/* Enforce that register types have to match exactly, including their
15984 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15985 	 * rule.
15986 	 *
15987 	 * One can make a point that using a pointer register as unbounded
15988 	 * SCALAR would be technically acceptable, but this could lead to
15989 	 * pointer leaks because scalars are allowed to leak while pointers
15990 	 * are not. We could make this safe in special cases if root is
15991 	 * calling us, but it's probably not worth the hassle.
15992 	 *
15993 	 * Also, register types that are *not* MAYBE_NULL could technically be
15994 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15995 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15996 	 * to the same map).
15997 	 * However, if the old MAYBE_NULL register then got NULL checked,
15998 	 * doing so could have affected others with the same id, and we can't
15999 	 * check for that because we lost the id when we converted to
16000 	 * a non-MAYBE_NULL variant.
16001 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16002 	 * non-MAYBE_NULL registers as well.
16003 	 */
16004 	if (rold->type != rcur->type)
16005 		return false;
16006 
16007 	switch (base_type(rold->type)) {
16008 	case SCALAR_VALUE:
16009 		if (env->explore_alu_limits) {
16010 			/* explore_alu_limits disables tnum_in() and range_within()
16011 			 * logic and requires everything to be strict
16012 			 */
16013 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16014 			       check_scalar_ids(rold->id, rcur->id, idmap);
16015 		}
16016 		if (!rold->precise)
16017 			return true;
16018 		/* Why check_ids() for scalar registers?
16019 		 *
16020 		 * Consider the following BPF code:
16021 		 *   1: r6 = ... unbound scalar, ID=a ...
16022 		 *   2: r7 = ... unbound scalar, ID=b ...
16023 		 *   3: if (r6 > r7) goto +1
16024 		 *   4: r6 = r7
16025 		 *   5: if (r6 > X) goto ...
16026 		 *   6: ... memory operation using r7 ...
16027 		 *
16028 		 * First verification path is [1-6]:
16029 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16030 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16031 		 *   r7 <= X, because r6 and r7 share same id.
16032 		 * Next verification path is [1-4, 6].
16033 		 *
16034 		 * Instruction (6) would be reached in two states:
16035 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16036 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16037 		 *
16038 		 * Use check_ids() to distinguish these states.
16039 		 * ---
16040 		 * Also verify that new value satisfies old value range knowledge.
16041 		 */
16042 		return range_within(rold, rcur) &&
16043 		       tnum_in(rold->var_off, rcur->var_off) &&
16044 		       check_scalar_ids(rold->id, rcur->id, idmap);
16045 	case PTR_TO_MAP_KEY:
16046 	case PTR_TO_MAP_VALUE:
16047 	case PTR_TO_MEM:
16048 	case PTR_TO_BUF:
16049 	case PTR_TO_TP_BUFFER:
16050 		/* If the new min/max/var_off satisfy the old ones and
16051 		 * everything else matches, we are OK.
16052 		 */
16053 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16054 		       range_within(rold, rcur) &&
16055 		       tnum_in(rold->var_off, rcur->var_off) &&
16056 		       check_ids(rold->id, rcur->id, idmap) &&
16057 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16058 	case PTR_TO_PACKET_META:
16059 	case PTR_TO_PACKET:
16060 		/* We must have at least as much range as the old ptr
16061 		 * did, so that any accesses which were safe before are
16062 		 * still safe.  This is true even if old range < old off,
16063 		 * since someone could have accessed through (ptr - k), or
16064 		 * even done ptr -= k in a register, to get a safe access.
16065 		 */
16066 		if (rold->range > rcur->range)
16067 			return false;
16068 		/* If the offsets don't match, we can't trust our alignment;
16069 		 * nor can we be sure that we won't fall out of range.
16070 		 */
16071 		if (rold->off != rcur->off)
16072 			return false;
16073 		/* id relations must be preserved */
16074 		if (!check_ids(rold->id, rcur->id, idmap))
16075 			return false;
16076 		/* new val must satisfy old val knowledge */
16077 		return range_within(rold, rcur) &&
16078 		       tnum_in(rold->var_off, rcur->var_off);
16079 	case PTR_TO_STACK:
16080 		/* two stack pointers are equal only if they're pointing to
16081 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16082 		 */
16083 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16084 	default:
16085 		return regs_exact(rold, rcur, idmap);
16086 	}
16087 }
16088 
16089 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16090 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16091 {
16092 	int i, spi;
16093 
16094 	/* walk slots of the explored stack and ignore any additional
16095 	 * slots in the current stack, since explored(safe) state
16096 	 * didn't use them
16097 	 */
16098 	for (i = 0; i < old->allocated_stack; i++) {
16099 		struct bpf_reg_state *old_reg, *cur_reg;
16100 
16101 		spi = i / BPF_REG_SIZE;
16102 
16103 		if (exact &&
16104 		    (i >= cur->allocated_stack ||
16105 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16106 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16107 			return false;
16108 
16109 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16110 			i += BPF_REG_SIZE - 1;
16111 			/* explored state didn't use this */
16112 			continue;
16113 		}
16114 
16115 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16116 			continue;
16117 
16118 		if (env->allow_uninit_stack &&
16119 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16120 			continue;
16121 
16122 		/* explored stack has more populated slots than current stack
16123 		 * and these slots were used
16124 		 */
16125 		if (i >= cur->allocated_stack)
16126 			return false;
16127 
16128 		/* if old state was safe with misc data in the stack
16129 		 * it will be safe with zero-initialized stack.
16130 		 * The opposite is not true
16131 		 */
16132 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16133 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16134 			continue;
16135 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16136 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16137 			/* Ex: old explored (safe) state has STACK_SPILL in
16138 			 * this stack slot, but current has STACK_MISC ->
16139 			 * this verifier states are not equivalent,
16140 			 * return false to continue verification of this path
16141 			 */
16142 			return false;
16143 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16144 			continue;
16145 		/* Both old and cur are having same slot_type */
16146 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16147 		case STACK_SPILL:
16148 			/* when explored and current stack slot are both storing
16149 			 * spilled registers, check that stored pointers types
16150 			 * are the same as well.
16151 			 * Ex: explored safe path could have stored
16152 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16153 			 * but current path has stored:
16154 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16155 			 * such verifier states are not equivalent.
16156 			 * return false to continue verification of this path
16157 			 */
16158 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16159 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16160 				return false;
16161 			break;
16162 		case STACK_DYNPTR:
16163 			old_reg = &old->stack[spi].spilled_ptr;
16164 			cur_reg = &cur->stack[spi].spilled_ptr;
16165 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16166 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16167 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16168 				return false;
16169 			break;
16170 		case STACK_ITER:
16171 			old_reg = &old->stack[spi].spilled_ptr;
16172 			cur_reg = &cur->stack[spi].spilled_ptr;
16173 			/* iter.depth is not compared between states as it
16174 			 * doesn't matter for correctness and would otherwise
16175 			 * prevent convergence; we maintain it only to prevent
16176 			 * infinite loop check triggering, see
16177 			 * iter_active_depths_differ()
16178 			 */
16179 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16180 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16181 			    old_reg->iter.state != cur_reg->iter.state ||
16182 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16183 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16184 				return false;
16185 			break;
16186 		case STACK_MISC:
16187 		case STACK_ZERO:
16188 		case STACK_INVALID:
16189 			continue;
16190 		/* Ensure that new unhandled slot types return false by default */
16191 		default:
16192 			return false;
16193 		}
16194 	}
16195 	return true;
16196 }
16197 
16198 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16199 		    struct bpf_idmap *idmap)
16200 {
16201 	int i;
16202 
16203 	if (old->acquired_refs != cur->acquired_refs)
16204 		return false;
16205 
16206 	for (i = 0; i < old->acquired_refs; i++) {
16207 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16208 			return false;
16209 	}
16210 
16211 	return true;
16212 }
16213 
16214 /* compare two verifier states
16215  *
16216  * all states stored in state_list are known to be valid, since
16217  * verifier reached 'bpf_exit' instruction through them
16218  *
16219  * this function is called when verifier exploring different branches of
16220  * execution popped from the state stack. If it sees an old state that has
16221  * more strict register state and more strict stack state then this execution
16222  * branch doesn't need to be explored further, since verifier already
16223  * concluded that more strict state leads to valid finish.
16224  *
16225  * Therefore two states are equivalent if register state is more conservative
16226  * and explored stack state is more conservative than the current one.
16227  * Example:
16228  *       explored                   current
16229  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16230  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16231  *
16232  * In other words if current stack state (one being explored) has more
16233  * valid slots than old one that already passed validation, it means
16234  * the verifier can stop exploring and conclude that current state is valid too
16235  *
16236  * Similarly with registers. If explored state has register type as invalid
16237  * whereas register type in current state is meaningful, it means that
16238  * the current state will reach 'bpf_exit' instruction safely
16239  */
16240 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16241 			      struct bpf_func_state *cur, bool exact)
16242 {
16243 	int i;
16244 
16245 	if (old->callback_depth > cur->callback_depth)
16246 		return false;
16247 
16248 	for (i = 0; i < MAX_BPF_REG; i++)
16249 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16250 			     &env->idmap_scratch, exact))
16251 			return false;
16252 
16253 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16254 		return false;
16255 
16256 	if (!refsafe(old, cur, &env->idmap_scratch))
16257 		return false;
16258 
16259 	return true;
16260 }
16261 
16262 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16263 {
16264 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16265 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16266 }
16267 
16268 static bool states_equal(struct bpf_verifier_env *env,
16269 			 struct bpf_verifier_state *old,
16270 			 struct bpf_verifier_state *cur,
16271 			 bool exact)
16272 {
16273 	int i;
16274 
16275 	if (old->curframe != cur->curframe)
16276 		return false;
16277 
16278 	reset_idmap_scratch(env);
16279 
16280 	/* Verification state from speculative execution simulation
16281 	 * must never prune a non-speculative execution one.
16282 	 */
16283 	if (old->speculative && !cur->speculative)
16284 		return false;
16285 
16286 	if (old->active_lock.ptr != cur->active_lock.ptr)
16287 		return false;
16288 
16289 	/* Old and cur active_lock's have to be either both present
16290 	 * or both absent.
16291 	 */
16292 	if (!!old->active_lock.id != !!cur->active_lock.id)
16293 		return false;
16294 
16295 	if (old->active_lock.id &&
16296 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16297 		return false;
16298 
16299 	if (old->active_rcu_lock != cur->active_rcu_lock)
16300 		return false;
16301 
16302 	/* for states to be equal callsites have to be the same
16303 	 * and all frame states need to be equivalent
16304 	 */
16305 	for (i = 0; i <= old->curframe; i++) {
16306 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16307 			return false;
16308 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16309 			return false;
16310 	}
16311 	return true;
16312 }
16313 
16314 /* Return 0 if no propagation happened. Return negative error code if error
16315  * happened. Otherwise, return the propagated bit.
16316  */
16317 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16318 				  struct bpf_reg_state *reg,
16319 				  struct bpf_reg_state *parent_reg)
16320 {
16321 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16322 	u8 flag = reg->live & REG_LIVE_READ;
16323 	int err;
16324 
16325 	/* When comes here, read flags of PARENT_REG or REG could be any of
16326 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16327 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16328 	 */
16329 	if (parent_flag == REG_LIVE_READ64 ||
16330 	    /* Or if there is no read flag from REG. */
16331 	    !flag ||
16332 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16333 	    parent_flag == flag)
16334 		return 0;
16335 
16336 	err = mark_reg_read(env, reg, parent_reg, flag);
16337 	if (err)
16338 		return err;
16339 
16340 	return flag;
16341 }
16342 
16343 /* A write screens off any subsequent reads; but write marks come from the
16344  * straight-line code between a state and its parent.  When we arrive at an
16345  * equivalent state (jump target or such) we didn't arrive by the straight-line
16346  * code, so read marks in the state must propagate to the parent regardless
16347  * of the state's write marks. That's what 'parent == state->parent' comparison
16348  * in mark_reg_read() is for.
16349  */
16350 static int propagate_liveness(struct bpf_verifier_env *env,
16351 			      const struct bpf_verifier_state *vstate,
16352 			      struct bpf_verifier_state *vparent)
16353 {
16354 	struct bpf_reg_state *state_reg, *parent_reg;
16355 	struct bpf_func_state *state, *parent;
16356 	int i, frame, err = 0;
16357 
16358 	if (vparent->curframe != vstate->curframe) {
16359 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16360 		     vparent->curframe, vstate->curframe);
16361 		return -EFAULT;
16362 	}
16363 	/* Propagate read liveness of registers... */
16364 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16365 	for (frame = 0; frame <= vstate->curframe; frame++) {
16366 		parent = vparent->frame[frame];
16367 		state = vstate->frame[frame];
16368 		parent_reg = parent->regs;
16369 		state_reg = state->regs;
16370 		/* We don't need to worry about FP liveness, it's read-only */
16371 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16372 			err = propagate_liveness_reg(env, &state_reg[i],
16373 						     &parent_reg[i]);
16374 			if (err < 0)
16375 				return err;
16376 			if (err == REG_LIVE_READ64)
16377 				mark_insn_zext(env, &parent_reg[i]);
16378 		}
16379 
16380 		/* Propagate stack slots. */
16381 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16382 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16383 			parent_reg = &parent->stack[i].spilled_ptr;
16384 			state_reg = &state->stack[i].spilled_ptr;
16385 			err = propagate_liveness_reg(env, state_reg,
16386 						     parent_reg);
16387 			if (err < 0)
16388 				return err;
16389 		}
16390 	}
16391 	return 0;
16392 }
16393 
16394 /* find precise scalars in the previous equivalent state and
16395  * propagate them into the current state
16396  */
16397 static int propagate_precision(struct bpf_verifier_env *env,
16398 			       const struct bpf_verifier_state *old)
16399 {
16400 	struct bpf_reg_state *state_reg;
16401 	struct bpf_func_state *state;
16402 	int i, err = 0, fr;
16403 	bool first;
16404 
16405 	for (fr = old->curframe; fr >= 0; fr--) {
16406 		state = old->frame[fr];
16407 		state_reg = state->regs;
16408 		first = true;
16409 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16410 			if (state_reg->type != SCALAR_VALUE ||
16411 			    !state_reg->precise ||
16412 			    !(state_reg->live & REG_LIVE_READ))
16413 				continue;
16414 			if (env->log.level & BPF_LOG_LEVEL2) {
16415 				if (first)
16416 					verbose(env, "frame %d: propagating r%d", fr, i);
16417 				else
16418 					verbose(env, ",r%d", i);
16419 			}
16420 			bt_set_frame_reg(&env->bt, fr, i);
16421 			first = false;
16422 		}
16423 
16424 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16425 			if (!is_spilled_reg(&state->stack[i]))
16426 				continue;
16427 			state_reg = &state->stack[i].spilled_ptr;
16428 			if (state_reg->type != SCALAR_VALUE ||
16429 			    !state_reg->precise ||
16430 			    !(state_reg->live & REG_LIVE_READ))
16431 				continue;
16432 			if (env->log.level & BPF_LOG_LEVEL2) {
16433 				if (first)
16434 					verbose(env, "frame %d: propagating fp%d",
16435 						fr, (-i - 1) * BPF_REG_SIZE);
16436 				else
16437 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16438 			}
16439 			bt_set_frame_slot(&env->bt, fr, i);
16440 			first = false;
16441 		}
16442 		if (!first)
16443 			verbose(env, "\n");
16444 	}
16445 
16446 	err = mark_chain_precision_batch(env);
16447 	if (err < 0)
16448 		return err;
16449 
16450 	return 0;
16451 }
16452 
16453 static bool states_maybe_looping(struct bpf_verifier_state *old,
16454 				 struct bpf_verifier_state *cur)
16455 {
16456 	struct bpf_func_state *fold, *fcur;
16457 	int i, fr = cur->curframe;
16458 
16459 	if (old->curframe != fr)
16460 		return false;
16461 
16462 	fold = old->frame[fr];
16463 	fcur = cur->frame[fr];
16464 	for (i = 0; i < MAX_BPF_REG; i++)
16465 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16466 			   offsetof(struct bpf_reg_state, parent)))
16467 			return false;
16468 	return true;
16469 }
16470 
16471 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16472 {
16473 	return env->insn_aux_data[insn_idx].is_iter_next;
16474 }
16475 
16476 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16477  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16478  * states to match, which otherwise would look like an infinite loop. So while
16479  * iter_next() calls are taken care of, we still need to be careful and
16480  * prevent erroneous and too eager declaration of "ininite loop", when
16481  * iterators are involved.
16482  *
16483  * Here's a situation in pseudo-BPF assembly form:
16484  *
16485  *   0: again:                          ; set up iter_next() call args
16486  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16487  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16488  *   3:   if r0 == 0 goto done
16489  *   4:   ... something useful here ...
16490  *   5:   goto again                    ; another iteration
16491  *   6: done:
16492  *   7:   r1 = &it
16493  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16494  *   9:   exit
16495  *
16496  * This is a typical loop. Let's assume that we have a prune point at 1:,
16497  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16498  * again`, assuming other heuristics don't get in a way).
16499  *
16500  * When we first time come to 1:, let's say we have some state X. We proceed
16501  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16502  * Now we come back to validate that forked ACTIVE state. We proceed through
16503  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16504  * are converging. But the problem is that we don't know that yet, as this
16505  * convergence has to happen at iter_next() call site only. So if nothing is
16506  * done, at 1: verifier will use bounded loop logic and declare infinite
16507  * looping (and would be *technically* correct, if not for iterator's
16508  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16509  * don't want that. So what we do in process_iter_next_call() when we go on
16510  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16511  * a different iteration. So when we suspect an infinite loop, we additionally
16512  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16513  * pretend we are not looping and wait for next iter_next() call.
16514  *
16515  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16516  * loop, because that would actually mean infinite loop, as DRAINED state is
16517  * "sticky", and so we'll keep returning into the same instruction with the
16518  * same state (at least in one of possible code paths).
16519  *
16520  * This approach allows to keep infinite loop heuristic even in the face of
16521  * active iterator. E.g., C snippet below is and will be detected as
16522  * inifintely looping:
16523  *
16524  *   struct bpf_iter_num it;
16525  *   int *p, x;
16526  *
16527  *   bpf_iter_num_new(&it, 0, 10);
16528  *   while ((p = bpf_iter_num_next(&t))) {
16529  *       x = p;
16530  *       while (x--) {} // <<-- infinite loop here
16531  *   }
16532  *
16533  */
16534 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16535 {
16536 	struct bpf_reg_state *slot, *cur_slot;
16537 	struct bpf_func_state *state;
16538 	int i, fr;
16539 
16540 	for (fr = old->curframe; fr >= 0; fr--) {
16541 		state = old->frame[fr];
16542 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16543 			if (state->stack[i].slot_type[0] != STACK_ITER)
16544 				continue;
16545 
16546 			slot = &state->stack[i].spilled_ptr;
16547 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16548 				continue;
16549 
16550 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16551 			if (cur_slot->iter.depth != slot->iter.depth)
16552 				return true;
16553 		}
16554 	}
16555 	return false;
16556 }
16557 
16558 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16559 {
16560 	struct bpf_verifier_state_list *new_sl;
16561 	struct bpf_verifier_state_list *sl, **pprev;
16562 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16563 	int i, j, n, err, states_cnt = 0;
16564 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16565 	bool add_new_state = force_new_state;
16566 	bool force_exact;
16567 
16568 	/* bpf progs typically have pruning point every 4 instructions
16569 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16570 	 * Do not add new state for future pruning if the verifier hasn't seen
16571 	 * at least 2 jumps and at least 8 instructions.
16572 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16573 	 * In tests that amounts to up to 50% reduction into total verifier
16574 	 * memory consumption and 20% verifier time speedup.
16575 	 */
16576 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16577 	    env->insn_processed - env->prev_insn_processed >= 8)
16578 		add_new_state = true;
16579 
16580 	pprev = explored_state(env, insn_idx);
16581 	sl = *pprev;
16582 
16583 	clean_live_states(env, insn_idx, cur);
16584 
16585 	while (sl) {
16586 		states_cnt++;
16587 		if (sl->state.insn_idx != insn_idx)
16588 			goto next;
16589 
16590 		if (sl->state.branches) {
16591 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16592 
16593 			if (frame->in_async_callback_fn &&
16594 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16595 				/* Different async_entry_cnt means that the verifier is
16596 				 * processing another entry into async callback.
16597 				 * Seeing the same state is not an indication of infinite
16598 				 * loop or infinite recursion.
16599 				 * But finding the same state doesn't mean that it's safe
16600 				 * to stop processing the current state. The previous state
16601 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16602 				 * Checking in_async_callback_fn alone is not enough either.
16603 				 * Since the verifier still needs to catch infinite loops
16604 				 * inside async callbacks.
16605 				 */
16606 				goto skip_inf_loop_check;
16607 			}
16608 			/* BPF open-coded iterators loop detection is special.
16609 			 * states_maybe_looping() logic is too simplistic in detecting
16610 			 * states that *might* be equivalent, because it doesn't know
16611 			 * about ID remapping, so don't even perform it.
16612 			 * See process_iter_next_call() and iter_active_depths_differ()
16613 			 * for overview of the logic. When current and one of parent
16614 			 * states are detected as equivalent, it's a good thing: we prove
16615 			 * convergence and can stop simulating further iterations.
16616 			 * It's safe to assume that iterator loop will finish, taking into
16617 			 * account iter_next() contract of eventually returning
16618 			 * sticky NULL result.
16619 			 *
16620 			 * Note, that states have to be compared exactly in this case because
16621 			 * read and precision marks might not be finalized inside the loop.
16622 			 * E.g. as in the program below:
16623 			 *
16624 			 *     1. r7 = -16
16625 			 *     2. r6 = bpf_get_prandom_u32()
16626 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16627 			 *     4.   if (r6 != 42) {
16628 			 *     5.     r7 = -32
16629 			 *     6.     r6 = bpf_get_prandom_u32()
16630 			 *     7.     continue
16631 			 *     8.   }
16632 			 *     9.   r0 = r10
16633 			 *    10.   r0 += r7
16634 			 *    11.   r8 = *(u64 *)(r0 + 0)
16635 			 *    12.   r6 = bpf_get_prandom_u32()
16636 			 *    13. }
16637 			 *
16638 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16639 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16640 			 * not have read or precision mark for r7 yet, thus inexact states
16641 			 * comparison would discard current state with r7=-32
16642 			 * => unsafe memory access at 11 would not be caught.
16643 			 */
16644 			if (is_iter_next_insn(env, insn_idx)) {
16645 				if (states_equal(env, &sl->state, cur, true)) {
16646 					struct bpf_func_state *cur_frame;
16647 					struct bpf_reg_state *iter_state, *iter_reg;
16648 					int spi;
16649 
16650 					cur_frame = cur->frame[cur->curframe];
16651 					/* btf_check_iter_kfuncs() enforces that
16652 					 * iter state pointer is always the first arg
16653 					 */
16654 					iter_reg = &cur_frame->regs[BPF_REG_1];
16655 					/* current state is valid due to states_equal(),
16656 					 * so we can assume valid iter and reg state,
16657 					 * no need for extra (re-)validations
16658 					 */
16659 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16660 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16661 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16662 						update_loop_entry(cur, &sl->state);
16663 						goto hit;
16664 					}
16665 				}
16666 				goto skip_inf_loop_check;
16667 			}
16668 			if (calls_callback(env, insn_idx)) {
16669 				if (states_equal(env, &sl->state, cur, true))
16670 					goto hit;
16671 				goto skip_inf_loop_check;
16672 			}
16673 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16674 			if (states_maybe_looping(&sl->state, cur) &&
16675 			    states_equal(env, &sl->state, cur, false) &&
16676 			    !iter_active_depths_differ(&sl->state, cur) &&
16677 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16678 				verbose_linfo(env, insn_idx, "; ");
16679 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16680 				verbose(env, "cur state:");
16681 				print_verifier_state(env, cur->frame[cur->curframe], true);
16682 				verbose(env, "old state:");
16683 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16684 				return -EINVAL;
16685 			}
16686 			/* if the verifier is processing a loop, avoid adding new state
16687 			 * too often, since different loop iterations have distinct
16688 			 * states and may not help future pruning.
16689 			 * This threshold shouldn't be too low to make sure that
16690 			 * a loop with large bound will be rejected quickly.
16691 			 * The most abusive loop will be:
16692 			 * r1 += 1
16693 			 * if r1 < 1000000 goto pc-2
16694 			 * 1M insn_procssed limit / 100 == 10k peak states.
16695 			 * This threshold shouldn't be too high either, since states
16696 			 * at the end of the loop are likely to be useful in pruning.
16697 			 */
16698 skip_inf_loop_check:
16699 			if (!force_new_state &&
16700 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16701 			    env->insn_processed - env->prev_insn_processed < 100)
16702 				add_new_state = false;
16703 			goto miss;
16704 		}
16705 		/* If sl->state is a part of a loop and this loop's entry is a part of
16706 		 * current verification path then states have to be compared exactly.
16707 		 * 'force_exact' is needed to catch the following case:
16708 		 *
16709 		 *                initial     Here state 'succ' was processed first,
16710 		 *                  |         it was eventually tracked to produce a
16711 		 *                  V         state identical to 'hdr'.
16712 		 *     .---------> hdr        All branches from 'succ' had been explored
16713 		 *     |            |         and thus 'succ' has its .branches == 0.
16714 		 *     |            V
16715 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16716 		 *     |    |       |         to the same instruction + callsites.
16717 		 *     |    V       V         In such case it is necessary to check
16718 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16719 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16720 		 *     |    V       V         same loop exact flag has to be set.
16721 		 *     |   succ <- cur        To check if that is the case, verify
16722 		 *     |    |                 if loop entry of 'succ' is in current
16723 		 *     |    V                 DFS path.
16724 		 *     |   ...
16725 		 *     |    |
16726 		 *     '----'
16727 		 *
16728 		 * Additional details are in the comment before get_loop_entry().
16729 		 */
16730 		loop_entry = get_loop_entry(&sl->state);
16731 		force_exact = loop_entry && loop_entry->branches > 0;
16732 		if (states_equal(env, &sl->state, cur, force_exact)) {
16733 			if (force_exact)
16734 				update_loop_entry(cur, loop_entry);
16735 hit:
16736 			sl->hit_cnt++;
16737 			/* reached equivalent register/stack state,
16738 			 * prune the search.
16739 			 * Registers read by the continuation are read by us.
16740 			 * If we have any write marks in env->cur_state, they
16741 			 * will prevent corresponding reads in the continuation
16742 			 * from reaching our parent (an explored_state).  Our
16743 			 * own state will get the read marks recorded, but
16744 			 * they'll be immediately forgotten as we're pruning
16745 			 * this state and will pop a new one.
16746 			 */
16747 			err = propagate_liveness(env, &sl->state, cur);
16748 
16749 			/* if previous state reached the exit with precision and
16750 			 * current state is equivalent to it (except precsion marks)
16751 			 * the precision needs to be propagated back in
16752 			 * the current state.
16753 			 */
16754 			err = err ? : push_jmp_history(env, cur);
16755 			err = err ? : propagate_precision(env, &sl->state);
16756 			if (err)
16757 				return err;
16758 			return 1;
16759 		}
16760 miss:
16761 		/* when new state is not going to be added do not increase miss count.
16762 		 * Otherwise several loop iterations will remove the state
16763 		 * recorded earlier. The goal of these heuristics is to have
16764 		 * states from some iterations of the loop (some in the beginning
16765 		 * and some at the end) to help pruning.
16766 		 */
16767 		if (add_new_state)
16768 			sl->miss_cnt++;
16769 		/* heuristic to determine whether this state is beneficial
16770 		 * to keep checking from state equivalence point of view.
16771 		 * Higher numbers increase max_states_per_insn and verification time,
16772 		 * but do not meaningfully decrease insn_processed.
16773 		 * 'n' controls how many times state could miss before eviction.
16774 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16775 		 * too early would hinder iterator convergence.
16776 		 */
16777 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16778 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16779 			/* the state is unlikely to be useful. Remove it to
16780 			 * speed up verification
16781 			 */
16782 			*pprev = sl->next;
16783 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16784 			    !sl->state.used_as_loop_entry) {
16785 				u32 br = sl->state.branches;
16786 
16787 				WARN_ONCE(br,
16788 					  "BUG live_done but branches_to_explore %d\n",
16789 					  br);
16790 				free_verifier_state(&sl->state, false);
16791 				kfree(sl);
16792 				env->peak_states--;
16793 			} else {
16794 				/* cannot free this state, since parentage chain may
16795 				 * walk it later. Add it for free_list instead to
16796 				 * be freed at the end of verification
16797 				 */
16798 				sl->next = env->free_list;
16799 				env->free_list = sl;
16800 			}
16801 			sl = *pprev;
16802 			continue;
16803 		}
16804 next:
16805 		pprev = &sl->next;
16806 		sl = *pprev;
16807 	}
16808 
16809 	if (env->max_states_per_insn < states_cnt)
16810 		env->max_states_per_insn = states_cnt;
16811 
16812 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16813 		return 0;
16814 
16815 	if (!add_new_state)
16816 		return 0;
16817 
16818 	/* There were no equivalent states, remember the current one.
16819 	 * Technically the current state is not proven to be safe yet,
16820 	 * but it will either reach outer most bpf_exit (which means it's safe)
16821 	 * or it will be rejected. When there are no loops the verifier won't be
16822 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16823 	 * again on the way to bpf_exit.
16824 	 * When looping the sl->state.branches will be > 0 and this state
16825 	 * will not be considered for equivalence until branches == 0.
16826 	 */
16827 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16828 	if (!new_sl)
16829 		return -ENOMEM;
16830 	env->total_states++;
16831 	env->peak_states++;
16832 	env->prev_jmps_processed = env->jmps_processed;
16833 	env->prev_insn_processed = env->insn_processed;
16834 
16835 	/* forget precise markings we inherited, see __mark_chain_precision */
16836 	if (env->bpf_capable)
16837 		mark_all_scalars_imprecise(env, cur);
16838 
16839 	/* add new state to the head of linked list */
16840 	new = &new_sl->state;
16841 	err = copy_verifier_state(new, cur);
16842 	if (err) {
16843 		free_verifier_state(new, false);
16844 		kfree(new_sl);
16845 		return err;
16846 	}
16847 	new->insn_idx = insn_idx;
16848 	WARN_ONCE(new->branches != 1,
16849 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16850 
16851 	cur->parent = new;
16852 	cur->first_insn_idx = insn_idx;
16853 	cur->dfs_depth = new->dfs_depth + 1;
16854 	clear_jmp_history(cur);
16855 	new_sl->next = *explored_state(env, insn_idx);
16856 	*explored_state(env, insn_idx) = new_sl;
16857 	/* connect new state to parentage chain. Current frame needs all
16858 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16859 	 * to the stack implicitly by JITs) so in callers' frames connect just
16860 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16861 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16862 	 * from callee with its full parentage chain, anyway.
16863 	 */
16864 	/* clear write marks in current state: the writes we did are not writes
16865 	 * our child did, so they don't screen off its reads from us.
16866 	 * (There are no read marks in current state, because reads always mark
16867 	 * their parent and current state never has children yet.  Only
16868 	 * explored_states can get read marks.)
16869 	 */
16870 	for (j = 0; j <= cur->curframe; j++) {
16871 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16872 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16873 		for (i = 0; i < BPF_REG_FP; i++)
16874 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16875 	}
16876 
16877 	/* all stack frames are accessible from callee, clear them all */
16878 	for (j = 0; j <= cur->curframe; j++) {
16879 		struct bpf_func_state *frame = cur->frame[j];
16880 		struct bpf_func_state *newframe = new->frame[j];
16881 
16882 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16883 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16884 			frame->stack[i].spilled_ptr.parent =
16885 						&newframe->stack[i].spilled_ptr;
16886 		}
16887 	}
16888 	return 0;
16889 }
16890 
16891 /* Return true if it's OK to have the same insn return a different type. */
16892 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16893 {
16894 	switch (base_type(type)) {
16895 	case PTR_TO_CTX:
16896 	case PTR_TO_SOCKET:
16897 	case PTR_TO_SOCK_COMMON:
16898 	case PTR_TO_TCP_SOCK:
16899 	case PTR_TO_XDP_SOCK:
16900 	case PTR_TO_BTF_ID:
16901 		return false;
16902 	default:
16903 		return true;
16904 	}
16905 }
16906 
16907 /* If an instruction was previously used with particular pointer types, then we
16908  * need to be careful to avoid cases such as the below, where it may be ok
16909  * for one branch accessing the pointer, but not ok for the other branch:
16910  *
16911  * R1 = sock_ptr
16912  * goto X;
16913  * ...
16914  * R1 = some_other_valid_ptr;
16915  * goto X;
16916  * ...
16917  * R2 = *(u32 *)(R1 + 0);
16918  */
16919 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16920 {
16921 	return src != prev && (!reg_type_mismatch_ok(src) ||
16922 			       !reg_type_mismatch_ok(prev));
16923 }
16924 
16925 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16926 			     bool allow_trust_missmatch)
16927 {
16928 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16929 
16930 	if (*prev_type == NOT_INIT) {
16931 		/* Saw a valid insn
16932 		 * dst_reg = *(u32 *)(src_reg + off)
16933 		 * save type to validate intersecting paths
16934 		 */
16935 		*prev_type = type;
16936 	} else if (reg_type_mismatch(type, *prev_type)) {
16937 		/* Abuser program is trying to use the same insn
16938 		 * dst_reg = *(u32*) (src_reg + off)
16939 		 * with different pointer types:
16940 		 * src_reg == ctx in one branch and
16941 		 * src_reg == stack|map in some other branch.
16942 		 * Reject it.
16943 		 */
16944 		if (allow_trust_missmatch &&
16945 		    base_type(type) == PTR_TO_BTF_ID &&
16946 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16947 			/*
16948 			 * Have to support a use case when one path through
16949 			 * the program yields TRUSTED pointer while another
16950 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16951 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16952 			 */
16953 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16954 		} else {
16955 			verbose(env, "same insn cannot be used with different pointers\n");
16956 			return -EINVAL;
16957 		}
16958 	}
16959 
16960 	return 0;
16961 }
16962 
16963 static int do_check(struct bpf_verifier_env *env)
16964 {
16965 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16966 	struct bpf_verifier_state *state = env->cur_state;
16967 	struct bpf_insn *insns = env->prog->insnsi;
16968 	struct bpf_reg_state *regs;
16969 	int insn_cnt = env->prog->len;
16970 	bool do_print_state = false;
16971 	int prev_insn_idx = -1;
16972 
16973 	for (;;) {
16974 		struct bpf_insn *insn;
16975 		u8 class;
16976 		int err;
16977 
16978 		env->prev_insn_idx = prev_insn_idx;
16979 		if (env->insn_idx >= insn_cnt) {
16980 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16981 				env->insn_idx, insn_cnt);
16982 			return -EFAULT;
16983 		}
16984 
16985 		insn = &insns[env->insn_idx];
16986 		class = BPF_CLASS(insn->code);
16987 
16988 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16989 			verbose(env,
16990 				"BPF program is too large. Processed %d insn\n",
16991 				env->insn_processed);
16992 			return -E2BIG;
16993 		}
16994 
16995 		state->last_insn_idx = env->prev_insn_idx;
16996 
16997 		if (is_prune_point(env, env->insn_idx)) {
16998 			err = is_state_visited(env, env->insn_idx);
16999 			if (err < 0)
17000 				return err;
17001 			if (err == 1) {
17002 				/* found equivalent state, can prune the search */
17003 				if (env->log.level & BPF_LOG_LEVEL) {
17004 					if (do_print_state)
17005 						verbose(env, "\nfrom %d to %d%s: safe\n",
17006 							env->prev_insn_idx, env->insn_idx,
17007 							env->cur_state->speculative ?
17008 							" (speculative execution)" : "");
17009 					else
17010 						verbose(env, "%d: safe\n", env->insn_idx);
17011 				}
17012 				goto process_bpf_exit;
17013 			}
17014 		}
17015 
17016 		if (is_jmp_point(env, env->insn_idx)) {
17017 			err = push_jmp_history(env, state);
17018 			if (err)
17019 				return err;
17020 		}
17021 
17022 		if (signal_pending(current))
17023 			return -EAGAIN;
17024 
17025 		if (need_resched())
17026 			cond_resched();
17027 
17028 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17029 			verbose(env, "\nfrom %d to %d%s:",
17030 				env->prev_insn_idx, env->insn_idx,
17031 				env->cur_state->speculative ?
17032 				" (speculative execution)" : "");
17033 			print_verifier_state(env, state->frame[state->curframe], true);
17034 			do_print_state = false;
17035 		}
17036 
17037 		if (env->log.level & BPF_LOG_LEVEL) {
17038 			const struct bpf_insn_cbs cbs = {
17039 				.cb_call	= disasm_kfunc_name,
17040 				.cb_print	= verbose,
17041 				.private_data	= env,
17042 			};
17043 
17044 			if (verifier_state_scratched(env))
17045 				print_insn_state(env, state->frame[state->curframe]);
17046 
17047 			verbose_linfo(env, env->insn_idx, "; ");
17048 			env->prev_log_pos = env->log.end_pos;
17049 			verbose(env, "%d: ", env->insn_idx);
17050 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17051 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17052 			env->prev_log_pos = env->log.end_pos;
17053 		}
17054 
17055 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17056 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17057 							   env->prev_insn_idx);
17058 			if (err)
17059 				return err;
17060 		}
17061 
17062 		regs = cur_regs(env);
17063 		sanitize_mark_insn_seen(env);
17064 		prev_insn_idx = env->insn_idx;
17065 
17066 		if (class == BPF_ALU || class == BPF_ALU64) {
17067 			err = check_alu_op(env, insn);
17068 			if (err)
17069 				return err;
17070 
17071 		} else if (class == BPF_LDX) {
17072 			enum bpf_reg_type src_reg_type;
17073 
17074 			/* check for reserved fields is already done */
17075 
17076 			/* check src operand */
17077 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17078 			if (err)
17079 				return err;
17080 
17081 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17082 			if (err)
17083 				return err;
17084 
17085 			src_reg_type = regs[insn->src_reg].type;
17086 
17087 			/* check that memory (src_reg + off) is readable,
17088 			 * the state of dst_reg will be updated by this func
17089 			 */
17090 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17091 					       insn->off, BPF_SIZE(insn->code),
17092 					       BPF_READ, insn->dst_reg, false,
17093 					       BPF_MODE(insn->code) == BPF_MEMSX);
17094 			if (err)
17095 				return err;
17096 
17097 			err = save_aux_ptr_type(env, src_reg_type, true);
17098 			if (err)
17099 				return err;
17100 		} else if (class == BPF_STX) {
17101 			enum bpf_reg_type dst_reg_type;
17102 
17103 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17104 				err = check_atomic(env, env->insn_idx, insn);
17105 				if (err)
17106 					return err;
17107 				env->insn_idx++;
17108 				continue;
17109 			}
17110 
17111 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17112 				verbose(env, "BPF_STX uses reserved fields\n");
17113 				return -EINVAL;
17114 			}
17115 
17116 			/* check src1 operand */
17117 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17118 			if (err)
17119 				return err;
17120 			/* check src2 operand */
17121 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17122 			if (err)
17123 				return err;
17124 
17125 			dst_reg_type = regs[insn->dst_reg].type;
17126 
17127 			/* check that memory (dst_reg + off) is writeable */
17128 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17129 					       insn->off, BPF_SIZE(insn->code),
17130 					       BPF_WRITE, insn->src_reg, false, false);
17131 			if (err)
17132 				return err;
17133 
17134 			err = save_aux_ptr_type(env, dst_reg_type, false);
17135 			if (err)
17136 				return err;
17137 		} else if (class == BPF_ST) {
17138 			enum bpf_reg_type dst_reg_type;
17139 
17140 			if (BPF_MODE(insn->code) != BPF_MEM ||
17141 			    insn->src_reg != BPF_REG_0) {
17142 				verbose(env, "BPF_ST uses reserved fields\n");
17143 				return -EINVAL;
17144 			}
17145 			/* check src operand */
17146 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17147 			if (err)
17148 				return err;
17149 
17150 			dst_reg_type = regs[insn->dst_reg].type;
17151 
17152 			/* check that memory (dst_reg + off) is writeable */
17153 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17154 					       insn->off, BPF_SIZE(insn->code),
17155 					       BPF_WRITE, -1, false, false);
17156 			if (err)
17157 				return err;
17158 
17159 			err = save_aux_ptr_type(env, dst_reg_type, false);
17160 			if (err)
17161 				return err;
17162 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17163 			u8 opcode = BPF_OP(insn->code);
17164 
17165 			env->jmps_processed++;
17166 			if (opcode == BPF_CALL) {
17167 				if (BPF_SRC(insn->code) != BPF_K ||
17168 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17169 				     && insn->off != 0) ||
17170 				    (insn->src_reg != BPF_REG_0 &&
17171 				     insn->src_reg != BPF_PSEUDO_CALL &&
17172 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17173 				    insn->dst_reg != BPF_REG_0 ||
17174 				    class == BPF_JMP32) {
17175 					verbose(env, "BPF_CALL uses reserved fields\n");
17176 					return -EINVAL;
17177 				}
17178 
17179 				if (env->cur_state->active_lock.ptr) {
17180 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17181 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17182 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17183 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17184 						verbose(env, "function calls are not allowed while holding a lock\n");
17185 						return -EINVAL;
17186 					}
17187 				}
17188 				if (insn->src_reg == BPF_PSEUDO_CALL)
17189 					err = check_func_call(env, insn, &env->insn_idx);
17190 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17191 					err = check_kfunc_call(env, insn, &env->insn_idx);
17192 				else
17193 					err = check_helper_call(env, insn, &env->insn_idx);
17194 				if (err)
17195 					return err;
17196 
17197 				mark_reg_scratched(env, BPF_REG_0);
17198 			} else if (opcode == BPF_JA) {
17199 				if (BPF_SRC(insn->code) != BPF_K ||
17200 				    insn->src_reg != BPF_REG_0 ||
17201 				    insn->dst_reg != BPF_REG_0 ||
17202 				    (class == BPF_JMP && insn->imm != 0) ||
17203 				    (class == BPF_JMP32 && insn->off != 0)) {
17204 					verbose(env, "BPF_JA uses reserved fields\n");
17205 					return -EINVAL;
17206 				}
17207 
17208 				if (class == BPF_JMP)
17209 					env->insn_idx += insn->off + 1;
17210 				else
17211 					env->insn_idx += insn->imm + 1;
17212 				continue;
17213 
17214 			} else if (opcode == BPF_EXIT) {
17215 				if (BPF_SRC(insn->code) != BPF_K ||
17216 				    insn->imm != 0 ||
17217 				    insn->src_reg != BPF_REG_0 ||
17218 				    insn->dst_reg != BPF_REG_0 ||
17219 				    class == BPF_JMP32) {
17220 					verbose(env, "BPF_EXIT uses reserved fields\n");
17221 					return -EINVAL;
17222 				}
17223 
17224 				if (env->cur_state->active_lock.ptr &&
17225 				    !in_rbtree_lock_required_cb(env)) {
17226 					verbose(env, "bpf_spin_unlock is missing\n");
17227 					return -EINVAL;
17228 				}
17229 
17230 				if (env->cur_state->active_rcu_lock &&
17231 				    !in_rbtree_lock_required_cb(env)) {
17232 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17233 					return -EINVAL;
17234 				}
17235 
17236 				/* We must do check_reference_leak here before
17237 				 * prepare_func_exit to handle the case when
17238 				 * state->curframe > 0, it may be a callback
17239 				 * function, for which reference_state must
17240 				 * match caller reference state when it exits.
17241 				 */
17242 				err = check_reference_leak(env);
17243 				if (err)
17244 					return err;
17245 
17246 				if (state->curframe) {
17247 					/* exit from nested function */
17248 					err = prepare_func_exit(env, &env->insn_idx);
17249 					if (err)
17250 						return err;
17251 					do_print_state = true;
17252 					continue;
17253 				}
17254 
17255 				err = check_return_code(env);
17256 				if (err)
17257 					return err;
17258 process_bpf_exit:
17259 				mark_verifier_state_scratched(env);
17260 				update_branch_counts(env, env->cur_state);
17261 				err = pop_stack(env, &prev_insn_idx,
17262 						&env->insn_idx, pop_log);
17263 				if (err < 0) {
17264 					if (err != -ENOENT)
17265 						return err;
17266 					break;
17267 				} else {
17268 					do_print_state = true;
17269 					continue;
17270 				}
17271 			} else {
17272 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17273 				if (err)
17274 					return err;
17275 			}
17276 		} else if (class == BPF_LD) {
17277 			u8 mode = BPF_MODE(insn->code);
17278 
17279 			if (mode == BPF_ABS || mode == BPF_IND) {
17280 				err = check_ld_abs(env, insn);
17281 				if (err)
17282 					return err;
17283 
17284 			} else if (mode == BPF_IMM) {
17285 				err = check_ld_imm(env, insn);
17286 				if (err)
17287 					return err;
17288 
17289 				env->insn_idx++;
17290 				sanitize_mark_insn_seen(env);
17291 			} else {
17292 				verbose(env, "invalid BPF_LD mode\n");
17293 				return -EINVAL;
17294 			}
17295 		} else {
17296 			verbose(env, "unknown insn class %d\n", class);
17297 			return -EINVAL;
17298 		}
17299 
17300 		env->insn_idx++;
17301 	}
17302 
17303 	return 0;
17304 }
17305 
17306 static int find_btf_percpu_datasec(struct btf *btf)
17307 {
17308 	const struct btf_type *t;
17309 	const char *tname;
17310 	int i, n;
17311 
17312 	/*
17313 	 * Both vmlinux and module each have their own ".data..percpu"
17314 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17315 	 * types to look at only module's own BTF types.
17316 	 */
17317 	n = btf_nr_types(btf);
17318 	if (btf_is_module(btf))
17319 		i = btf_nr_types(btf_vmlinux);
17320 	else
17321 		i = 1;
17322 
17323 	for(; i < n; i++) {
17324 		t = btf_type_by_id(btf, i);
17325 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17326 			continue;
17327 
17328 		tname = btf_name_by_offset(btf, t->name_off);
17329 		if (!strcmp(tname, ".data..percpu"))
17330 			return i;
17331 	}
17332 
17333 	return -ENOENT;
17334 }
17335 
17336 /* replace pseudo btf_id with kernel symbol address */
17337 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17338 			       struct bpf_insn *insn,
17339 			       struct bpf_insn_aux_data *aux)
17340 {
17341 	const struct btf_var_secinfo *vsi;
17342 	const struct btf_type *datasec;
17343 	struct btf_mod_pair *btf_mod;
17344 	const struct btf_type *t;
17345 	const char *sym_name;
17346 	bool percpu = false;
17347 	u32 type, id = insn->imm;
17348 	struct btf *btf;
17349 	s32 datasec_id;
17350 	u64 addr;
17351 	int i, btf_fd, err;
17352 
17353 	btf_fd = insn[1].imm;
17354 	if (btf_fd) {
17355 		btf = btf_get_by_fd(btf_fd);
17356 		if (IS_ERR(btf)) {
17357 			verbose(env, "invalid module BTF object FD specified.\n");
17358 			return -EINVAL;
17359 		}
17360 	} else {
17361 		if (!btf_vmlinux) {
17362 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17363 			return -EINVAL;
17364 		}
17365 		btf = btf_vmlinux;
17366 		btf_get(btf);
17367 	}
17368 
17369 	t = btf_type_by_id(btf, id);
17370 	if (!t) {
17371 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17372 		err = -ENOENT;
17373 		goto err_put;
17374 	}
17375 
17376 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17377 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17378 		err = -EINVAL;
17379 		goto err_put;
17380 	}
17381 
17382 	sym_name = btf_name_by_offset(btf, t->name_off);
17383 	addr = kallsyms_lookup_name(sym_name);
17384 	if (!addr) {
17385 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17386 			sym_name);
17387 		err = -ENOENT;
17388 		goto err_put;
17389 	}
17390 	insn[0].imm = (u32)addr;
17391 	insn[1].imm = addr >> 32;
17392 
17393 	if (btf_type_is_func(t)) {
17394 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17395 		aux->btf_var.mem_size = 0;
17396 		goto check_btf;
17397 	}
17398 
17399 	datasec_id = find_btf_percpu_datasec(btf);
17400 	if (datasec_id > 0) {
17401 		datasec = btf_type_by_id(btf, datasec_id);
17402 		for_each_vsi(i, datasec, vsi) {
17403 			if (vsi->type == id) {
17404 				percpu = true;
17405 				break;
17406 			}
17407 		}
17408 	}
17409 
17410 	type = t->type;
17411 	t = btf_type_skip_modifiers(btf, type, NULL);
17412 	if (percpu) {
17413 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17414 		aux->btf_var.btf = btf;
17415 		aux->btf_var.btf_id = type;
17416 	} else if (!btf_type_is_struct(t)) {
17417 		const struct btf_type *ret;
17418 		const char *tname;
17419 		u32 tsize;
17420 
17421 		/* resolve the type size of ksym. */
17422 		ret = btf_resolve_size(btf, t, &tsize);
17423 		if (IS_ERR(ret)) {
17424 			tname = btf_name_by_offset(btf, t->name_off);
17425 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17426 				tname, PTR_ERR(ret));
17427 			err = -EINVAL;
17428 			goto err_put;
17429 		}
17430 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17431 		aux->btf_var.mem_size = tsize;
17432 	} else {
17433 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17434 		aux->btf_var.btf = btf;
17435 		aux->btf_var.btf_id = type;
17436 	}
17437 check_btf:
17438 	/* check whether we recorded this BTF (and maybe module) already */
17439 	for (i = 0; i < env->used_btf_cnt; i++) {
17440 		if (env->used_btfs[i].btf == btf) {
17441 			btf_put(btf);
17442 			return 0;
17443 		}
17444 	}
17445 
17446 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17447 		err = -E2BIG;
17448 		goto err_put;
17449 	}
17450 
17451 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17452 	btf_mod->btf = btf;
17453 	btf_mod->module = NULL;
17454 
17455 	/* if we reference variables from kernel module, bump its refcount */
17456 	if (btf_is_module(btf)) {
17457 		btf_mod->module = btf_try_get_module(btf);
17458 		if (!btf_mod->module) {
17459 			err = -ENXIO;
17460 			goto err_put;
17461 		}
17462 	}
17463 
17464 	env->used_btf_cnt++;
17465 
17466 	return 0;
17467 err_put:
17468 	btf_put(btf);
17469 	return err;
17470 }
17471 
17472 static bool is_tracing_prog_type(enum bpf_prog_type type)
17473 {
17474 	switch (type) {
17475 	case BPF_PROG_TYPE_KPROBE:
17476 	case BPF_PROG_TYPE_TRACEPOINT:
17477 	case BPF_PROG_TYPE_PERF_EVENT:
17478 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17479 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17480 		return true;
17481 	default:
17482 		return false;
17483 	}
17484 }
17485 
17486 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17487 					struct bpf_map *map,
17488 					struct bpf_prog *prog)
17489 
17490 {
17491 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17492 
17493 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17494 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17495 		if (is_tracing_prog_type(prog_type)) {
17496 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17497 			return -EINVAL;
17498 		}
17499 	}
17500 
17501 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17502 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17503 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17504 			return -EINVAL;
17505 		}
17506 
17507 		if (is_tracing_prog_type(prog_type)) {
17508 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17509 			return -EINVAL;
17510 		}
17511 	}
17512 
17513 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17514 		if (is_tracing_prog_type(prog_type)) {
17515 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17516 			return -EINVAL;
17517 		}
17518 	}
17519 
17520 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17521 	    !bpf_offload_prog_map_match(prog, map)) {
17522 		verbose(env, "offload device mismatch between prog and map\n");
17523 		return -EINVAL;
17524 	}
17525 
17526 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17527 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17528 		return -EINVAL;
17529 	}
17530 
17531 	if (prog->aux->sleepable)
17532 		switch (map->map_type) {
17533 		case BPF_MAP_TYPE_HASH:
17534 		case BPF_MAP_TYPE_LRU_HASH:
17535 		case BPF_MAP_TYPE_ARRAY:
17536 		case BPF_MAP_TYPE_PERCPU_HASH:
17537 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17538 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17539 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17540 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17541 		case BPF_MAP_TYPE_RINGBUF:
17542 		case BPF_MAP_TYPE_USER_RINGBUF:
17543 		case BPF_MAP_TYPE_INODE_STORAGE:
17544 		case BPF_MAP_TYPE_SK_STORAGE:
17545 		case BPF_MAP_TYPE_TASK_STORAGE:
17546 		case BPF_MAP_TYPE_CGRP_STORAGE:
17547 			break;
17548 		default:
17549 			verbose(env,
17550 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17551 			return -EINVAL;
17552 		}
17553 
17554 	return 0;
17555 }
17556 
17557 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17558 {
17559 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17560 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17561 }
17562 
17563 /* find and rewrite pseudo imm in ld_imm64 instructions:
17564  *
17565  * 1. if it accesses map FD, replace it with actual map pointer.
17566  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17567  *
17568  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17569  */
17570 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17571 {
17572 	struct bpf_insn *insn = env->prog->insnsi;
17573 	int insn_cnt = env->prog->len;
17574 	int i, j, err;
17575 
17576 	err = bpf_prog_calc_tag(env->prog);
17577 	if (err)
17578 		return err;
17579 
17580 	for (i = 0; i < insn_cnt; i++, insn++) {
17581 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17582 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17583 		    insn->imm != 0)) {
17584 			verbose(env, "BPF_LDX uses reserved fields\n");
17585 			return -EINVAL;
17586 		}
17587 
17588 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17589 			struct bpf_insn_aux_data *aux;
17590 			struct bpf_map *map;
17591 			struct fd f;
17592 			u64 addr;
17593 			u32 fd;
17594 
17595 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17596 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17597 			    insn[1].off != 0) {
17598 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17599 				return -EINVAL;
17600 			}
17601 
17602 			if (insn[0].src_reg == 0)
17603 				/* valid generic load 64-bit imm */
17604 				goto next_insn;
17605 
17606 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17607 				aux = &env->insn_aux_data[i];
17608 				err = check_pseudo_btf_id(env, insn, aux);
17609 				if (err)
17610 					return err;
17611 				goto next_insn;
17612 			}
17613 
17614 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17615 				aux = &env->insn_aux_data[i];
17616 				aux->ptr_type = PTR_TO_FUNC;
17617 				goto next_insn;
17618 			}
17619 
17620 			/* In final convert_pseudo_ld_imm64() step, this is
17621 			 * converted into regular 64-bit imm load insn.
17622 			 */
17623 			switch (insn[0].src_reg) {
17624 			case BPF_PSEUDO_MAP_VALUE:
17625 			case BPF_PSEUDO_MAP_IDX_VALUE:
17626 				break;
17627 			case BPF_PSEUDO_MAP_FD:
17628 			case BPF_PSEUDO_MAP_IDX:
17629 				if (insn[1].imm == 0)
17630 					break;
17631 				fallthrough;
17632 			default:
17633 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17634 				return -EINVAL;
17635 			}
17636 
17637 			switch (insn[0].src_reg) {
17638 			case BPF_PSEUDO_MAP_IDX_VALUE:
17639 			case BPF_PSEUDO_MAP_IDX:
17640 				if (bpfptr_is_null(env->fd_array)) {
17641 					verbose(env, "fd_idx without fd_array is invalid\n");
17642 					return -EPROTO;
17643 				}
17644 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17645 							    insn[0].imm * sizeof(fd),
17646 							    sizeof(fd)))
17647 					return -EFAULT;
17648 				break;
17649 			default:
17650 				fd = insn[0].imm;
17651 				break;
17652 			}
17653 
17654 			f = fdget(fd);
17655 			map = __bpf_map_get(f);
17656 			if (IS_ERR(map)) {
17657 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17658 				return PTR_ERR(map);
17659 			}
17660 
17661 			err = check_map_prog_compatibility(env, map, env->prog);
17662 			if (err) {
17663 				fdput(f);
17664 				return err;
17665 			}
17666 
17667 			aux = &env->insn_aux_data[i];
17668 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17669 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17670 				addr = (unsigned long)map;
17671 			} else {
17672 				u32 off = insn[1].imm;
17673 
17674 				if (off >= BPF_MAX_VAR_OFF) {
17675 					verbose(env, "direct value offset of %u is not allowed\n", off);
17676 					fdput(f);
17677 					return -EINVAL;
17678 				}
17679 
17680 				if (!map->ops->map_direct_value_addr) {
17681 					verbose(env, "no direct value access support for this map type\n");
17682 					fdput(f);
17683 					return -EINVAL;
17684 				}
17685 
17686 				err = map->ops->map_direct_value_addr(map, &addr, off);
17687 				if (err) {
17688 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17689 						map->value_size, off);
17690 					fdput(f);
17691 					return err;
17692 				}
17693 
17694 				aux->map_off = off;
17695 				addr += off;
17696 			}
17697 
17698 			insn[0].imm = (u32)addr;
17699 			insn[1].imm = addr >> 32;
17700 
17701 			/* check whether we recorded this map already */
17702 			for (j = 0; j < env->used_map_cnt; j++) {
17703 				if (env->used_maps[j] == map) {
17704 					aux->map_index = j;
17705 					fdput(f);
17706 					goto next_insn;
17707 				}
17708 			}
17709 
17710 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17711 				fdput(f);
17712 				return -E2BIG;
17713 			}
17714 
17715 			if (env->prog->aux->sleepable)
17716 				atomic64_inc(&map->sleepable_refcnt);
17717 			/* hold the map. If the program is rejected by verifier,
17718 			 * the map will be released by release_maps() or it
17719 			 * will be used by the valid program until it's unloaded
17720 			 * and all maps are released in bpf_free_used_maps()
17721 			 */
17722 			bpf_map_inc(map);
17723 
17724 			aux->map_index = env->used_map_cnt;
17725 			env->used_maps[env->used_map_cnt++] = map;
17726 
17727 			if (bpf_map_is_cgroup_storage(map) &&
17728 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17729 				verbose(env, "only one cgroup storage of each type is allowed\n");
17730 				fdput(f);
17731 				return -EBUSY;
17732 			}
17733 
17734 			fdput(f);
17735 next_insn:
17736 			insn++;
17737 			i++;
17738 			continue;
17739 		}
17740 
17741 		/* Basic sanity check before we invest more work here. */
17742 		if (!bpf_opcode_in_insntable(insn->code)) {
17743 			verbose(env, "unknown opcode %02x\n", insn->code);
17744 			return -EINVAL;
17745 		}
17746 	}
17747 
17748 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17749 	 * 'struct bpf_map *' into a register instead of user map_fd.
17750 	 * These pointers will be used later by verifier to validate map access.
17751 	 */
17752 	return 0;
17753 }
17754 
17755 /* drop refcnt of maps used by the rejected program */
17756 static void release_maps(struct bpf_verifier_env *env)
17757 {
17758 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17759 			     env->used_map_cnt);
17760 }
17761 
17762 /* drop refcnt of maps used by the rejected program */
17763 static void release_btfs(struct bpf_verifier_env *env)
17764 {
17765 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17766 			     env->used_btf_cnt);
17767 }
17768 
17769 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17770 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17771 {
17772 	struct bpf_insn *insn = env->prog->insnsi;
17773 	int insn_cnt = env->prog->len;
17774 	int i;
17775 
17776 	for (i = 0; i < insn_cnt; i++, insn++) {
17777 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17778 			continue;
17779 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17780 			continue;
17781 		insn->src_reg = 0;
17782 	}
17783 }
17784 
17785 /* single env->prog->insni[off] instruction was replaced with the range
17786  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17787  * [0, off) and [off, end) to new locations, so the patched range stays zero
17788  */
17789 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17790 				 struct bpf_insn_aux_data *new_data,
17791 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17792 {
17793 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17794 	struct bpf_insn *insn = new_prog->insnsi;
17795 	u32 old_seen = old_data[off].seen;
17796 	u32 prog_len;
17797 	int i;
17798 
17799 	/* aux info at OFF always needs adjustment, no matter fast path
17800 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17801 	 * original insn at old prog.
17802 	 */
17803 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17804 
17805 	if (cnt == 1)
17806 		return;
17807 	prog_len = new_prog->len;
17808 
17809 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17810 	memcpy(new_data + off + cnt - 1, old_data + off,
17811 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17812 	for (i = off; i < off + cnt - 1; i++) {
17813 		/* Expand insni[off]'s seen count to the patched range. */
17814 		new_data[i].seen = old_seen;
17815 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17816 	}
17817 	env->insn_aux_data = new_data;
17818 	vfree(old_data);
17819 }
17820 
17821 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17822 {
17823 	int i;
17824 
17825 	if (len == 1)
17826 		return;
17827 	/* NOTE: fake 'exit' subprog should be updated as well. */
17828 	for (i = 0; i <= env->subprog_cnt; i++) {
17829 		if (env->subprog_info[i].start <= off)
17830 			continue;
17831 		env->subprog_info[i].start += len - 1;
17832 	}
17833 }
17834 
17835 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17836 {
17837 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17838 	int i, sz = prog->aux->size_poke_tab;
17839 	struct bpf_jit_poke_descriptor *desc;
17840 
17841 	for (i = 0; i < sz; i++) {
17842 		desc = &tab[i];
17843 		if (desc->insn_idx <= off)
17844 			continue;
17845 		desc->insn_idx += len - 1;
17846 	}
17847 }
17848 
17849 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17850 					    const struct bpf_insn *patch, u32 len)
17851 {
17852 	struct bpf_prog *new_prog;
17853 	struct bpf_insn_aux_data *new_data = NULL;
17854 
17855 	if (len > 1) {
17856 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17857 					      sizeof(struct bpf_insn_aux_data)));
17858 		if (!new_data)
17859 			return NULL;
17860 	}
17861 
17862 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17863 	if (IS_ERR(new_prog)) {
17864 		if (PTR_ERR(new_prog) == -ERANGE)
17865 			verbose(env,
17866 				"insn %d cannot be patched due to 16-bit range\n",
17867 				env->insn_aux_data[off].orig_idx);
17868 		vfree(new_data);
17869 		return NULL;
17870 	}
17871 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17872 	adjust_subprog_starts(env, off, len);
17873 	adjust_poke_descs(new_prog, off, len);
17874 	return new_prog;
17875 }
17876 
17877 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17878 					      u32 off, u32 cnt)
17879 {
17880 	int i, j;
17881 
17882 	/* find first prog starting at or after off (first to remove) */
17883 	for (i = 0; i < env->subprog_cnt; i++)
17884 		if (env->subprog_info[i].start >= off)
17885 			break;
17886 	/* find first prog starting at or after off + cnt (first to stay) */
17887 	for (j = i; j < env->subprog_cnt; j++)
17888 		if (env->subprog_info[j].start >= off + cnt)
17889 			break;
17890 	/* if j doesn't start exactly at off + cnt, we are just removing
17891 	 * the front of previous prog
17892 	 */
17893 	if (env->subprog_info[j].start != off + cnt)
17894 		j--;
17895 
17896 	if (j > i) {
17897 		struct bpf_prog_aux *aux = env->prog->aux;
17898 		int move;
17899 
17900 		/* move fake 'exit' subprog as well */
17901 		move = env->subprog_cnt + 1 - j;
17902 
17903 		memmove(env->subprog_info + i,
17904 			env->subprog_info + j,
17905 			sizeof(*env->subprog_info) * move);
17906 		env->subprog_cnt -= j - i;
17907 
17908 		/* remove func_info */
17909 		if (aux->func_info) {
17910 			move = aux->func_info_cnt - j;
17911 
17912 			memmove(aux->func_info + i,
17913 				aux->func_info + j,
17914 				sizeof(*aux->func_info) * move);
17915 			aux->func_info_cnt -= j - i;
17916 			/* func_info->insn_off is set after all code rewrites,
17917 			 * in adjust_btf_func() - no need to adjust
17918 			 */
17919 		}
17920 	} else {
17921 		/* convert i from "first prog to remove" to "first to adjust" */
17922 		if (env->subprog_info[i].start == off)
17923 			i++;
17924 	}
17925 
17926 	/* update fake 'exit' subprog as well */
17927 	for (; i <= env->subprog_cnt; i++)
17928 		env->subprog_info[i].start -= cnt;
17929 
17930 	return 0;
17931 }
17932 
17933 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17934 				      u32 cnt)
17935 {
17936 	struct bpf_prog *prog = env->prog;
17937 	u32 i, l_off, l_cnt, nr_linfo;
17938 	struct bpf_line_info *linfo;
17939 
17940 	nr_linfo = prog->aux->nr_linfo;
17941 	if (!nr_linfo)
17942 		return 0;
17943 
17944 	linfo = prog->aux->linfo;
17945 
17946 	/* find first line info to remove, count lines to be removed */
17947 	for (i = 0; i < nr_linfo; i++)
17948 		if (linfo[i].insn_off >= off)
17949 			break;
17950 
17951 	l_off = i;
17952 	l_cnt = 0;
17953 	for (; i < nr_linfo; i++)
17954 		if (linfo[i].insn_off < off + cnt)
17955 			l_cnt++;
17956 		else
17957 			break;
17958 
17959 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17960 	 * last removed linfo.  prog is already modified, so prog->len == off
17961 	 * means no live instructions after (tail of the program was removed).
17962 	 */
17963 	if (prog->len != off && l_cnt &&
17964 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17965 		l_cnt--;
17966 		linfo[--i].insn_off = off + cnt;
17967 	}
17968 
17969 	/* remove the line info which refer to the removed instructions */
17970 	if (l_cnt) {
17971 		memmove(linfo + l_off, linfo + i,
17972 			sizeof(*linfo) * (nr_linfo - i));
17973 
17974 		prog->aux->nr_linfo -= l_cnt;
17975 		nr_linfo = prog->aux->nr_linfo;
17976 	}
17977 
17978 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17979 	for (i = l_off; i < nr_linfo; i++)
17980 		linfo[i].insn_off -= cnt;
17981 
17982 	/* fix up all subprogs (incl. 'exit') which start >= off */
17983 	for (i = 0; i <= env->subprog_cnt; i++)
17984 		if (env->subprog_info[i].linfo_idx > l_off) {
17985 			/* program may have started in the removed region but
17986 			 * may not be fully removed
17987 			 */
17988 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17989 				env->subprog_info[i].linfo_idx -= l_cnt;
17990 			else
17991 				env->subprog_info[i].linfo_idx = l_off;
17992 		}
17993 
17994 	return 0;
17995 }
17996 
17997 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17998 {
17999 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18000 	unsigned int orig_prog_len = env->prog->len;
18001 	int err;
18002 
18003 	if (bpf_prog_is_offloaded(env->prog->aux))
18004 		bpf_prog_offload_remove_insns(env, off, cnt);
18005 
18006 	err = bpf_remove_insns(env->prog, off, cnt);
18007 	if (err)
18008 		return err;
18009 
18010 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18011 	if (err)
18012 		return err;
18013 
18014 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18015 	if (err)
18016 		return err;
18017 
18018 	memmove(aux_data + off,	aux_data + off + cnt,
18019 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18020 
18021 	return 0;
18022 }
18023 
18024 /* The verifier does more data flow analysis than llvm and will not
18025  * explore branches that are dead at run time. Malicious programs can
18026  * have dead code too. Therefore replace all dead at-run-time code
18027  * with 'ja -1'.
18028  *
18029  * Just nops are not optimal, e.g. if they would sit at the end of the
18030  * program and through another bug we would manage to jump there, then
18031  * we'd execute beyond program memory otherwise. Returning exception
18032  * code also wouldn't work since we can have subprogs where the dead
18033  * code could be located.
18034  */
18035 static void sanitize_dead_code(struct bpf_verifier_env *env)
18036 {
18037 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18038 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18039 	struct bpf_insn *insn = env->prog->insnsi;
18040 	const int insn_cnt = env->prog->len;
18041 	int i;
18042 
18043 	for (i = 0; i < insn_cnt; i++) {
18044 		if (aux_data[i].seen)
18045 			continue;
18046 		memcpy(insn + i, &trap, sizeof(trap));
18047 		aux_data[i].zext_dst = false;
18048 	}
18049 }
18050 
18051 static bool insn_is_cond_jump(u8 code)
18052 {
18053 	u8 op;
18054 
18055 	op = BPF_OP(code);
18056 	if (BPF_CLASS(code) == BPF_JMP32)
18057 		return op != BPF_JA;
18058 
18059 	if (BPF_CLASS(code) != BPF_JMP)
18060 		return false;
18061 
18062 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18063 }
18064 
18065 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18066 {
18067 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18068 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18069 	struct bpf_insn *insn = env->prog->insnsi;
18070 	const int insn_cnt = env->prog->len;
18071 	int i;
18072 
18073 	for (i = 0; i < insn_cnt; i++, insn++) {
18074 		if (!insn_is_cond_jump(insn->code))
18075 			continue;
18076 
18077 		if (!aux_data[i + 1].seen)
18078 			ja.off = insn->off;
18079 		else if (!aux_data[i + 1 + insn->off].seen)
18080 			ja.off = 0;
18081 		else
18082 			continue;
18083 
18084 		if (bpf_prog_is_offloaded(env->prog->aux))
18085 			bpf_prog_offload_replace_insn(env, i, &ja);
18086 
18087 		memcpy(insn, &ja, sizeof(ja));
18088 	}
18089 }
18090 
18091 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18092 {
18093 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18094 	int insn_cnt = env->prog->len;
18095 	int i, err;
18096 
18097 	for (i = 0; i < insn_cnt; i++) {
18098 		int j;
18099 
18100 		j = 0;
18101 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18102 			j++;
18103 		if (!j)
18104 			continue;
18105 
18106 		err = verifier_remove_insns(env, i, j);
18107 		if (err)
18108 			return err;
18109 		insn_cnt = env->prog->len;
18110 	}
18111 
18112 	return 0;
18113 }
18114 
18115 static int opt_remove_nops(struct bpf_verifier_env *env)
18116 {
18117 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18118 	struct bpf_insn *insn = env->prog->insnsi;
18119 	int insn_cnt = env->prog->len;
18120 	int i, err;
18121 
18122 	for (i = 0; i < insn_cnt; i++) {
18123 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18124 			continue;
18125 
18126 		err = verifier_remove_insns(env, i, 1);
18127 		if (err)
18128 			return err;
18129 		insn_cnt--;
18130 		i--;
18131 	}
18132 
18133 	return 0;
18134 }
18135 
18136 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18137 					 const union bpf_attr *attr)
18138 {
18139 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18140 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18141 	int i, patch_len, delta = 0, len = env->prog->len;
18142 	struct bpf_insn *insns = env->prog->insnsi;
18143 	struct bpf_prog *new_prog;
18144 	bool rnd_hi32;
18145 
18146 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18147 	zext_patch[1] = BPF_ZEXT_REG(0);
18148 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18149 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18150 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18151 	for (i = 0; i < len; i++) {
18152 		int adj_idx = i + delta;
18153 		struct bpf_insn insn;
18154 		int load_reg;
18155 
18156 		insn = insns[adj_idx];
18157 		load_reg = insn_def_regno(&insn);
18158 		if (!aux[adj_idx].zext_dst) {
18159 			u8 code, class;
18160 			u32 imm_rnd;
18161 
18162 			if (!rnd_hi32)
18163 				continue;
18164 
18165 			code = insn.code;
18166 			class = BPF_CLASS(code);
18167 			if (load_reg == -1)
18168 				continue;
18169 
18170 			/* NOTE: arg "reg" (the fourth one) is only used for
18171 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18172 			 *       here.
18173 			 */
18174 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18175 				if (class == BPF_LD &&
18176 				    BPF_MODE(code) == BPF_IMM)
18177 					i++;
18178 				continue;
18179 			}
18180 
18181 			/* ctx load could be transformed into wider load. */
18182 			if (class == BPF_LDX &&
18183 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18184 				continue;
18185 
18186 			imm_rnd = get_random_u32();
18187 			rnd_hi32_patch[0] = insn;
18188 			rnd_hi32_patch[1].imm = imm_rnd;
18189 			rnd_hi32_patch[3].dst_reg = load_reg;
18190 			patch = rnd_hi32_patch;
18191 			patch_len = 4;
18192 			goto apply_patch_buffer;
18193 		}
18194 
18195 		/* Add in an zero-extend instruction if a) the JIT has requested
18196 		 * it or b) it's a CMPXCHG.
18197 		 *
18198 		 * The latter is because: BPF_CMPXCHG always loads a value into
18199 		 * R0, therefore always zero-extends. However some archs'
18200 		 * equivalent instruction only does this load when the
18201 		 * comparison is successful. This detail of CMPXCHG is
18202 		 * orthogonal to the general zero-extension behaviour of the
18203 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18204 		 */
18205 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18206 			continue;
18207 
18208 		/* Zero-extension is done by the caller. */
18209 		if (bpf_pseudo_kfunc_call(&insn))
18210 			continue;
18211 
18212 		if (WARN_ON(load_reg == -1)) {
18213 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18214 			return -EFAULT;
18215 		}
18216 
18217 		zext_patch[0] = insn;
18218 		zext_patch[1].dst_reg = load_reg;
18219 		zext_patch[1].src_reg = load_reg;
18220 		patch = zext_patch;
18221 		patch_len = 2;
18222 apply_patch_buffer:
18223 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18224 		if (!new_prog)
18225 			return -ENOMEM;
18226 		env->prog = new_prog;
18227 		insns = new_prog->insnsi;
18228 		aux = env->insn_aux_data;
18229 		delta += patch_len - 1;
18230 	}
18231 
18232 	return 0;
18233 }
18234 
18235 /* convert load instructions that access fields of a context type into a
18236  * sequence of instructions that access fields of the underlying structure:
18237  *     struct __sk_buff    -> struct sk_buff
18238  *     struct bpf_sock_ops -> struct sock
18239  */
18240 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18241 {
18242 	const struct bpf_verifier_ops *ops = env->ops;
18243 	int i, cnt, size, ctx_field_size, delta = 0;
18244 	const int insn_cnt = env->prog->len;
18245 	struct bpf_insn insn_buf[16], *insn;
18246 	u32 target_size, size_default, off;
18247 	struct bpf_prog *new_prog;
18248 	enum bpf_access_type type;
18249 	bool is_narrower_load;
18250 
18251 	if (ops->gen_prologue || env->seen_direct_write) {
18252 		if (!ops->gen_prologue) {
18253 			verbose(env, "bpf verifier is misconfigured\n");
18254 			return -EINVAL;
18255 		}
18256 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18257 					env->prog);
18258 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18259 			verbose(env, "bpf verifier is misconfigured\n");
18260 			return -EINVAL;
18261 		} else if (cnt) {
18262 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18263 			if (!new_prog)
18264 				return -ENOMEM;
18265 
18266 			env->prog = new_prog;
18267 			delta += cnt - 1;
18268 		}
18269 	}
18270 
18271 	if (bpf_prog_is_offloaded(env->prog->aux))
18272 		return 0;
18273 
18274 	insn = env->prog->insnsi + delta;
18275 
18276 	for (i = 0; i < insn_cnt; i++, insn++) {
18277 		bpf_convert_ctx_access_t convert_ctx_access;
18278 		u8 mode;
18279 
18280 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18281 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18282 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18283 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18284 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18285 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18286 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18287 			type = BPF_READ;
18288 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18289 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18290 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18291 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18292 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18293 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18294 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18295 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18296 			type = BPF_WRITE;
18297 		} else {
18298 			continue;
18299 		}
18300 
18301 		if (type == BPF_WRITE &&
18302 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18303 			struct bpf_insn patch[] = {
18304 				*insn,
18305 				BPF_ST_NOSPEC(),
18306 			};
18307 
18308 			cnt = ARRAY_SIZE(patch);
18309 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18310 			if (!new_prog)
18311 				return -ENOMEM;
18312 
18313 			delta    += cnt - 1;
18314 			env->prog = new_prog;
18315 			insn      = new_prog->insnsi + i + delta;
18316 			continue;
18317 		}
18318 
18319 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18320 		case PTR_TO_CTX:
18321 			if (!ops->convert_ctx_access)
18322 				continue;
18323 			convert_ctx_access = ops->convert_ctx_access;
18324 			break;
18325 		case PTR_TO_SOCKET:
18326 		case PTR_TO_SOCK_COMMON:
18327 			convert_ctx_access = bpf_sock_convert_ctx_access;
18328 			break;
18329 		case PTR_TO_TCP_SOCK:
18330 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18331 			break;
18332 		case PTR_TO_XDP_SOCK:
18333 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18334 			break;
18335 		case PTR_TO_BTF_ID:
18336 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18337 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18338 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18339 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18340 		 * any faults for loads into such types. BPF_WRITE is disallowed
18341 		 * for this case.
18342 		 */
18343 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18344 			if (type == BPF_READ) {
18345 				if (BPF_MODE(insn->code) == BPF_MEM)
18346 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18347 						     BPF_SIZE((insn)->code);
18348 				else
18349 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18350 						     BPF_SIZE((insn)->code);
18351 				env->prog->aux->num_exentries++;
18352 			}
18353 			continue;
18354 		default:
18355 			continue;
18356 		}
18357 
18358 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18359 		size = BPF_LDST_BYTES(insn);
18360 		mode = BPF_MODE(insn->code);
18361 
18362 		/* If the read access is a narrower load of the field,
18363 		 * convert to a 4/8-byte load, to minimum program type specific
18364 		 * convert_ctx_access changes. If conversion is successful,
18365 		 * we will apply proper mask to the result.
18366 		 */
18367 		is_narrower_load = size < ctx_field_size;
18368 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18369 		off = insn->off;
18370 		if (is_narrower_load) {
18371 			u8 size_code;
18372 
18373 			if (type == BPF_WRITE) {
18374 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18375 				return -EINVAL;
18376 			}
18377 
18378 			size_code = BPF_H;
18379 			if (ctx_field_size == 4)
18380 				size_code = BPF_W;
18381 			else if (ctx_field_size == 8)
18382 				size_code = BPF_DW;
18383 
18384 			insn->off = off & ~(size_default - 1);
18385 			insn->code = BPF_LDX | BPF_MEM | size_code;
18386 		}
18387 
18388 		target_size = 0;
18389 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18390 					 &target_size);
18391 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18392 		    (ctx_field_size && !target_size)) {
18393 			verbose(env, "bpf verifier is misconfigured\n");
18394 			return -EINVAL;
18395 		}
18396 
18397 		if (is_narrower_load && size < target_size) {
18398 			u8 shift = bpf_ctx_narrow_access_offset(
18399 				off, size, size_default) * 8;
18400 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18401 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18402 				return -EINVAL;
18403 			}
18404 			if (ctx_field_size <= 4) {
18405 				if (shift)
18406 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18407 									insn->dst_reg,
18408 									shift);
18409 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18410 								(1 << size * 8) - 1);
18411 			} else {
18412 				if (shift)
18413 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18414 									insn->dst_reg,
18415 									shift);
18416 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18417 								(1ULL << size * 8) - 1);
18418 			}
18419 		}
18420 		if (mode == BPF_MEMSX)
18421 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18422 						       insn->dst_reg, insn->dst_reg,
18423 						       size * 8, 0);
18424 
18425 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18426 		if (!new_prog)
18427 			return -ENOMEM;
18428 
18429 		delta += cnt - 1;
18430 
18431 		/* keep walking new program and skip insns we just inserted */
18432 		env->prog = new_prog;
18433 		insn      = new_prog->insnsi + i + delta;
18434 	}
18435 
18436 	return 0;
18437 }
18438 
18439 static int jit_subprogs(struct bpf_verifier_env *env)
18440 {
18441 	struct bpf_prog *prog = env->prog, **func, *tmp;
18442 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18443 	struct bpf_map *map_ptr;
18444 	struct bpf_insn *insn;
18445 	void *old_bpf_func;
18446 	int err, num_exentries;
18447 
18448 	if (env->subprog_cnt <= 1)
18449 		return 0;
18450 
18451 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18452 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18453 			continue;
18454 
18455 		/* Upon error here we cannot fall back to interpreter but
18456 		 * need a hard reject of the program. Thus -EFAULT is
18457 		 * propagated in any case.
18458 		 */
18459 		subprog = find_subprog(env, i + insn->imm + 1);
18460 		if (subprog < 0) {
18461 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18462 				  i + insn->imm + 1);
18463 			return -EFAULT;
18464 		}
18465 		/* temporarily remember subprog id inside insn instead of
18466 		 * aux_data, since next loop will split up all insns into funcs
18467 		 */
18468 		insn->off = subprog;
18469 		/* remember original imm in case JIT fails and fallback
18470 		 * to interpreter will be needed
18471 		 */
18472 		env->insn_aux_data[i].call_imm = insn->imm;
18473 		/* point imm to __bpf_call_base+1 from JITs point of view */
18474 		insn->imm = 1;
18475 		if (bpf_pseudo_func(insn))
18476 			/* jit (e.g. x86_64) may emit fewer instructions
18477 			 * if it learns a u32 imm is the same as a u64 imm.
18478 			 * Force a non zero here.
18479 			 */
18480 			insn[1].imm = 1;
18481 	}
18482 
18483 	err = bpf_prog_alloc_jited_linfo(prog);
18484 	if (err)
18485 		goto out_undo_insn;
18486 
18487 	err = -ENOMEM;
18488 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18489 	if (!func)
18490 		goto out_undo_insn;
18491 
18492 	for (i = 0; i < env->subprog_cnt; i++) {
18493 		subprog_start = subprog_end;
18494 		subprog_end = env->subprog_info[i + 1].start;
18495 
18496 		len = subprog_end - subprog_start;
18497 		/* bpf_prog_run() doesn't call subprogs directly,
18498 		 * hence main prog stats include the runtime of subprogs.
18499 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18500 		 * func[i]->stats will never be accessed and stays NULL
18501 		 */
18502 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18503 		if (!func[i])
18504 			goto out_free;
18505 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18506 		       len * sizeof(struct bpf_insn));
18507 		func[i]->type = prog->type;
18508 		func[i]->len = len;
18509 		if (bpf_prog_calc_tag(func[i]))
18510 			goto out_free;
18511 		func[i]->is_func = 1;
18512 		func[i]->aux->func_idx = i;
18513 		/* Below members will be freed only at prog->aux */
18514 		func[i]->aux->btf = prog->aux->btf;
18515 		func[i]->aux->func_info = prog->aux->func_info;
18516 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18517 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18518 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18519 
18520 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18521 			struct bpf_jit_poke_descriptor *poke;
18522 
18523 			poke = &prog->aux->poke_tab[j];
18524 			if (poke->insn_idx < subprog_end &&
18525 			    poke->insn_idx >= subprog_start)
18526 				poke->aux = func[i]->aux;
18527 		}
18528 
18529 		func[i]->aux->name[0] = 'F';
18530 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18531 		func[i]->jit_requested = 1;
18532 		func[i]->blinding_requested = prog->blinding_requested;
18533 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18534 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18535 		func[i]->aux->linfo = prog->aux->linfo;
18536 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18537 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18538 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18539 		num_exentries = 0;
18540 		insn = func[i]->insnsi;
18541 		for (j = 0; j < func[i]->len; j++, insn++) {
18542 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18543 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18544 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18545 				num_exentries++;
18546 		}
18547 		func[i]->aux->num_exentries = num_exentries;
18548 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18549 		func[i] = bpf_int_jit_compile(func[i]);
18550 		if (!func[i]->jited) {
18551 			err = -ENOTSUPP;
18552 			goto out_free;
18553 		}
18554 		cond_resched();
18555 	}
18556 
18557 	/* at this point all bpf functions were successfully JITed
18558 	 * now populate all bpf_calls with correct addresses and
18559 	 * run last pass of JIT
18560 	 */
18561 	for (i = 0; i < env->subprog_cnt; i++) {
18562 		insn = func[i]->insnsi;
18563 		for (j = 0; j < func[i]->len; j++, insn++) {
18564 			if (bpf_pseudo_func(insn)) {
18565 				subprog = insn->off;
18566 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18567 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18568 				continue;
18569 			}
18570 			if (!bpf_pseudo_call(insn))
18571 				continue;
18572 			subprog = insn->off;
18573 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18574 		}
18575 
18576 		/* we use the aux data to keep a list of the start addresses
18577 		 * of the JITed images for each function in the program
18578 		 *
18579 		 * for some architectures, such as powerpc64, the imm field
18580 		 * might not be large enough to hold the offset of the start
18581 		 * address of the callee's JITed image from __bpf_call_base
18582 		 *
18583 		 * in such cases, we can lookup the start address of a callee
18584 		 * by using its subprog id, available from the off field of
18585 		 * the call instruction, as an index for this list
18586 		 */
18587 		func[i]->aux->func = func;
18588 		func[i]->aux->func_cnt = env->subprog_cnt;
18589 	}
18590 	for (i = 0; i < env->subprog_cnt; i++) {
18591 		old_bpf_func = func[i]->bpf_func;
18592 		tmp = bpf_int_jit_compile(func[i]);
18593 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18594 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18595 			err = -ENOTSUPP;
18596 			goto out_free;
18597 		}
18598 		cond_resched();
18599 	}
18600 
18601 	/* finally lock prog and jit images for all functions and
18602 	 * populate kallsysm. Begin at the first subprogram, since
18603 	 * bpf_prog_load will add the kallsyms for the main program.
18604 	 */
18605 	for (i = 1; i < env->subprog_cnt; i++) {
18606 		bpf_prog_lock_ro(func[i]);
18607 		bpf_prog_kallsyms_add(func[i]);
18608 	}
18609 
18610 	/* Last step: make now unused interpreter insns from main
18611 	 * prog consistent for later dump requests, so they can
18612 	 * later look the same as if they were interpreted only.
18613 	 */
18614 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18615 		if (bpf_pseudo_func(insn)) {
18616 			insn[0].imm = env->insn_aux_data[i].call_imm;
18617 			insn[1].imm = insn->off;
18618 			insn->off = 0;
18619 			continue;
18620 		}
18621 		if (!bpf_pseudo_call(insn))
18622 			continue;
18623 		insn->off = env->insn_aux_data[i].call_imm;
18624 		subprog = find_subprog(env, i + insn->off + 1);
18625 		insn->imm = subprog;
18626 	}
18627 
18628 	prog->jited = 1;
18629 	prog->bpf_func = func[0]->bpf_func;
18630 	prog->jited_len = func[0]->jited_len;
18631 	prog->aux->extable = func[0]->aux->extable;
18632 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18633 	prog->aux->func = func;
18634 	prog->aux->func_cnt = env->subprog_cnt;
18635 	bpf_prog_jit_attempt_done(prog);
18636 	return 0;
18637 out_free:
18638 	/* We failed JIT'ing, so at this point we need to unregister poke
18639 	 * descriptors from subprogs, so that kernel is not attempting to
18640 	 * patch it anymore as we're freeing the subprog JIT memory.
18641 	 */
18642 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18643 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18644 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18645 	}
18646 	/* At this point we're guaranteed that poke descriptors are not
18647 	 * live anymore. We can just unlink its descriptor table as it's
18648 	 * released with the main prog.
18649 	 */
18650 	for (i = 0; i < env->subprog_cnt; i++) {
18651 		if (!func[i])
18652 			continue;
18653 		func[i]->aux->poke_tab = NULL;
18654 		bpf_jit_free(func[i]);
18655 	}
18656 	kfree(func);
18657 out_undo_insn:
18658 	/* cleanup main prog to be interpreted */
18659 	prog->jit_requested = 0;
18660 	prog->blinding_requested = 0;
18661 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18662 		if (!bpf_pseudo_call(insn))
18663 			continue;
18664 		insn->off = 0;
18665 		insn->imm = env->insn_aux_data[i].call_imm;
18666 	}
18667 	bpf_prog_jit_attempt_done(prog);
18668 	return err;
18669 }
18670 
18671 static int fixup_call_args(struct bpf_verifier_env *env)
18672 {
18673 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18674 	struct bpf_prog *prog = env->prog;
18675 	struct bpf_insn *insn = prog->insnsi;
18676 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18677 	int i, depth;
18678 #endif
18679 	int err = 0;
18680 
18681 	if (env->prog->jit_requested &&
18682 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18683 		err = jit_subprogs(env);
18684 		if (err == 0)
18685 			return 0;
18686 		if (err == -EFAULT)
18687 			return err;
18688 	}
18689 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18690 	if (has_kfunc_call) {
18691 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18692 		return -EINVAL;
18693 	}
18694 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18695 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18696 		 * have to be rejected, since interpreter doesn't support them yet.
18697 		 */
18698 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18699 		return -EINVAL;
18700 	}
18701 	for (i = 0; i < prog->len; i++, insn++) {
18702 		if (bpf_pseudo_func(insn)) {
18703 			/* When JIT fails the progs with callback calls
18704 			 * have to be rejected, since interpreter doesn't support them yet.
18705 			 */
18706 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18707 			return -EINVAL;
18708 		}
18709 
18710 		if (!bpf_pseudo_call(insn))
18711 			continue;
18712 		depth = get_callee_stack_depth(env, insn, i);
18713 		if (depth < 0)
18714 			return depth;
18715 		bpf_patch_call_args(insn, depth);
18716 	}
18717 	err = 0;
18718 #endif
18719 	return err;
18720 }
18721 
18722 /* replace a generic kfunc with a specialized version if necessary */
18723 static void specialize_kfunc(struct bpf_verifier_env *env,
18724 			     u32 func_id, u16 offset, unsigned long *addr)
18725 {
18726 	struct bpf_prog *prog = env->prog;
18727 	bool seen_direct_write;
18728 	void *xdp_kfunc;
18729 	bool is_rdonly;
18730 
18731 	if (bpf_dev_bound_kfunc_id(func_id)) {
18732 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18733 		if (xdp_kfunc) {
18734 			*addr = (unsigned long)xdp_kfunc;
18735 			return;
18736 		}
18737 		/* fallback to default kfunc when not supported by netdev */
18738 	}
18739 
18740 	if (offset)
18741 		return;
18742 
18743 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18744 		seen_direct_write = env->seen_direct_write;
18745 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18746 
18747 		if (is_rdonly)
18748 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18749 
18750 		/* restore env->seen_direct_write to its original value, since
18751 		 * may_access_direct_pkt_data mutates it
18752 		 */
18753 		env->seen_direct_write = seen_direct_write;
18754 	}
18755 }
18756 
18757 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18758 					    u16 struct_meta_reg,
18759 					    u16 node_offset_reg,
18760 					    struct bpf_insn *insn,
18761 					    struct bpf_insn *insn_buf,
18762 					    int *cnt)
18763 {
18764 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18765 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18766 
18767 	insn_buf[0] = addr[0];
18768 	insn_buf[1] = addr[1];
18769 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18770 	insn_buf[3] = *insn;
18771 	*cnt = 4;
18772 }
18773 
18774 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18775 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18776 {
18777 	const struct bpf_kfunc_desc *desc;
18778 
18779 	if (!insn->imm) {
18780 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18781 		return -EINVAL;
18782 	}
18783 
18784 	*cnt = 0;
18785 
18786 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18787 	 * __bpf_call_base, unless the JIT needs to call functions that are
18788 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18789 	 */
18790 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18791 	if (!desc) {
18792 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18793 			insn->imm);
18794 		return -EFAULT;
18795 	}
18796 
18797 	if (!bpf_jit_supports_far_kfunc_call())
18798 		insn->imm = BPF_CALL_IMM(desc->addr);
18799 	if (insn->off)
18800 		return 0;
18801 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18802 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18803 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18804 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18805 
18806 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18807 		insn_buf[1] = addr[0];
18808 		insn_buf[2] = addr[1];
18809 		insn_buf[3] = *insn;
18810 		*cnt = 4;
18811 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18812 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18813 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18814 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18815 
18816 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18817 		    !kptr_struct_meta) {
18818 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18819 				insn_idx);
18820 			return -EFAULT;
18821 		}
18822 
18823 		insn_buf[0] = addr[0];
18824 		insn_buf[1] = addr[1];
18825 		insn_buf[2] = *insn;
18826 		*cnt = 3;
18827 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18828 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18829 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18830 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18831 		int struct_meta_reg = BPF_REG_3;
18832 		int node_offset_reg = BPF_REG_4;
18833 
18834 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18835 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18836 			struct_meta_reg = BPF_REG_4;
18837 			node_offset_reg = BPF_REG_5;
18838 		}
18839 
18840 		if (!kptr_struct_meta) {
18841 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18842 				insn_idx);
18843 			return -EFAULT;
18844 		}
18845 
18846 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18847 						node_offset_reg, insn, insn_buf, cnt);
18848 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18849 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18850 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18851 		*cnt = 1;
18852 	}
18853 	return 0;
18854 }
18855 
18856 /* Do various post-verification rewrites in a single program pass.
18857  * These rewrites simplify JIT and interpreter implementations.
18858  */
18859 static int do_misc_fixups(struct bpf_verifier_env *env)
18860 {
18861 	struct bpf_prog *prog = env->prog;
18862 	enum bpf_attach_type eatype = prog->expected_attach_type;
18863 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18864 	struct bpf_insn *insn = prog->insnsi;
18865 	const struct bpf_func_proto *fn;
18866 	const int insn_cnt = prog->len;
18867 	const struct bpf_map_ops *ops;
18868 	struct bpf_insn_aux_data *aux;
18869 	struct bpf_insn insn_buf[16];
18870 	struct bpf_prog *new_prog;
18871 	struct bpf_map *map_ptr;
18872 	int i, ret, cnt, delta = 0;
18873 
18874 	for (i = 0; i < insn_cnt; i++, insn++) {
18875 		/* Make divide-by-zero exceptions impossible. */
18876 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18877 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18878 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18879 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18880 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18881 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18882 			struct bpf_insn *patchlet;
18883 			struct bpf_insn chk_and_div[] = {
18884 				/* [R,W]x div 0 -> 0 */
18885 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18886 					     BPF_JNE | BPF_K, insn->src_reg,
18887 					     0, 2, 0),
18888 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18889 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18890 				*insn,
18891 			};
18892 			struct bpf_insn chk_and_mod[] = {
18893 				/* [R,W]x mod 0 -> [R,W]x */
18894 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18895 					     BPF_JEQ | BPF_K, insn->src_reg,
18896 					     0, 1 + (is64 ? 0 : 1), 0),
18897 				*insn,
18898 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18899 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18900 			};
18901 
18902 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18903 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18904 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18905 
18906 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18907 			if (!new_prog)
18908 				return -ENOMEM;
18909 
18910 			delta    += cnt - 1;
18911 			env->prog = prog = new_prog;
18912 			insn      = new_prog->insnsi + i + delta;
18913 			continue;
18914 		}
18915 
18916 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18917 		if (BPF_CLASS(insn->code) == BPF_LD &&
18918 		    (BPF_MODE(insn->code) == BPF_ABS ||
18919 		     BPF_MODE(insn->code) == BPF_IND)) {
18920 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18921 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18922 				verbose(env, "bpf verifier is misconfigured\n");
18923 				return -EINVAL;
18924 			}
18925 
18926 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18927 			if (!new_prog)
18928 				return -ENOMEM;
18929 
18930 			delta    += cnt - 1;
18931 			env->prog = prog = new_prog;
18932 			insn      = new_prog->insnsi + i + delta;
18933 			continue;
18934 		}
18935 
18936 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18937 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18938 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18939 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18940 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18941 			struct bpf_insn *patch = &insn_buf[0];
18942 			bool issrc, isneg, isimm;
18943 			u32 off_reg;
18944 
18945 			aux = &env->insn_aux_data[i + delta];
18946 			if (!aux->alu_state ||
18947 			    aux->alu_state == BPF_ALU_NON_POINTER)
18948 				continue;
18949 
18950 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18951 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18952 				BPF_ALU_SANITIZE_SRC;
18953 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18954 
18955 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18956 			if (isimm) {
18957 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18958 			} else {
18959 				if (isneg)
18960 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18961 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18962 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18963 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18964 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18965 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18966 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18967 			}
18968 			if (!issrc)
18969 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18970 			insn->src_reg = BPF_REG_AX;
18971 			if (isneg)
18972 				insn->code = insn->code == code_add ?
18973 					     code_sub : code_add;
18974 			*patch++ = *insn;
18975 			if (issrc && isneg && !isimm)
18976 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18977 			cnt = patch - insn_buf;
18978 
18979 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18980 			if (!new_prog)
18981 				return -ENOMEM;
18982 
18983 			delta    += cnt - 1;
18984 			env->prog = prog = new_prog;
18985 			insn      = new_prog->insnsi + i + delta;
18986 			continue;
18987 		}
18988 
18989 		if (insn->code != (BPF_JMP | BPF_CALL))
18990 			continue;
18991 		if (insn->src_reg == BPF_PSEUDO_CALL)
18992 			continue;
18993 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18994 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18995 			if (ret)
18996 				return ret;
18997 			if (cnt == 0)
18998 				continue;
18999 
19000 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19001 			if (!new_prog)
19002 				return -ENOMEM;
19003 
19004 			delta	 += cnt - 1;
19005 			env->prog = prog = new_prog;
19006 			insn	  = new_prog->insnsi + i + delta;
19007 			continue;
19008 		}
19009 
19010 		if (insn->imm == BPF_FUNC_get_route_realm)
19011 			prog->dst_needed = 1;
19012 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19013 			bpf_user_rnd_init_once();
19014 		if (insn->imm == BPF_FUNC_override_return)
19015 			prog->kprobe_override = 1;
19016 		if (insn->imm == BPF_FUNC_tail_call) {
19017 			/* If we tail call into other programs, we
19018 			 * cannot make any assumptions since they can
19019 			 * be replaced dynamically during runtime in
19020 			 * the program array.
19021 			 */
19022 			prog->cb_access = 1;
19023 			if (!allow_tail_call_in_subprogs(env))
19024 				prog->aux->stack_depth = MAX_BPF_STACK;
19025 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19026 
19027 			/* mark bpf_tail_call as different opcode to avoid
19028 			 * conditional branch in the interpreter for every normal
19029 			 * call and to prevent accidental JITing by JIT compiler
19030 			 * that doesn't support bpf_tail_call yet
19031 			 */
19032 			insn->imm = 0;
19033 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19034 
19035 			aux = &env->insn_aux_data[i + delta];
19036 			if (env->bpf_capable && !prog->blinding_requested &&
19037 			    prog->jit_requested &&
19038 			    !bpf_map_key_poisoned(aux) &&
19039 			    !bpf_map_ptr_poisoned(aux) &&
19040 			    !bpf_map_ptr_unpriv(aux)) {
19041 				struct bpf_jit_poke_descriptor desc = {
19042 					.reason = BPF_POKE_REASON_TAIL_CALL,
19043 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19044 					.tail_call.key = bpf_map_key_immediate(aux),
19045 					.insn_idx = i + delta,
19046 				};
19047 
19048 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19049 				if (ret < 0) {
19050 					verbose(env, "adding tail call poke descriptor failed\n");
19051 					return ret;
19052 				}
19053 
19054 				insn->imm = ret + 1;
19055 				continue;
19056 			}
19057 
19058 			if (!bpf_map_ptr_unpriv(aux))
19059 				continue;
19060 
19061 			/* instead of changing every JIT dealing with tail_call
19062 			 * emit two extra insns:
19063 			 * if (index >= max_entries) goto out;
19064 			 * index &= array->index_mask;
19065 			 * to avoid out-of-bounds cpu speculation
19066 			 */
19067 			if (bpf_map_ptr_poisoned(aux)) {
19068 				verbose(env, "tail_call abusing map_ptr\n");
19069 				return -EINVAL;
19070 			}
19071 
19072 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19073 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19074 						  map_ptr->max_entries, 2);
19075 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19076 						    container_of(map_ptr,
19077 								 struct bpf_array,
19078 								 map)->index_mask);
19079 			insn_buf[2] = *insn;
19080 			cnt = 3;
19081 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19082 			if (!new_prog)
19083 				return -ENOMEM;
19084 
19085 			delta    += cnt - 1;
19086 			env->prog = prog = new_prog;
19087 			insn      = new_prog->insnsi + i + delta;
19088 			continue;
19089 		}
19090 
19091 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19092 			/* The verifier will process callback_fn as many times as necessary
19093 			 * with different maps and the register states prepared by
19094 			 * set_timer_callback_state will be accurate.
19095 			 *
19096 			 * The following use case is valid:
19097 			 *   map1 is shared by prog1, prog2, prog3.
19098 			 *   prog1 calls bpf_timer_init for some map1 elements
19099 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19100 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19101 			 *   prog3 calls bpf_timer_start for some map1 elements.
19102 			 *     Those that were not both bpf_timer_init-ed and
19103 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19104 			 */
19105 			struct bpf_insn ld_addrs[2] = {
19106 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19107 			};
19108 
19109 			insn_buf[0] = ld_addrs[0];
19110 			insn_buf[1] = ld_addrs[1];
19111 			insn_buf[2] = *insn;
19112 			cnt = 3;
19113 
19114 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19115 			if (!new_prog)
19116 				return -ENOMEM;
19117 
19118 			delta    += cnt - 1;
19119 			env->prog = prog = new_prog;
19120 			insn      = new_prog->insnsi + i + delta;
19121 			goto patch_call_imm;
19122 		}
19123 
19124 		if (is_storage_get_function(insn->imm)) {
19125 			if (!env->prog->aux->sleepable ||
19126 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19127 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19128 			else
19129 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19130 			insn_buf[1] = *insn;
19131 			cnt = 2;
19132 
19133 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19134 			if (!new_prog)
19135 				return -ENOMEM;
19136 
19137 			delta += cnt - 1;
19138 			env->prog = prog = new_prog;
19139 			insn = new_prog->insnsi + i + delta;
19140 			goto patch_call_imm;
19141 		}
19142 
19143 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19144 		 * and other inlining handlers are currently limited to 64 bit
19145 		 * only.
19146 		 */
19147 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19148 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19149 		     insn->imm == BPF_FUNC_map_update_elem ||
19150 		     insn->imm == BPF_FUNC_map_delete_elem ||
19151 		     insn->imm == BPF_FUNC_map_push_elem   ||
19152 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19153 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19154 		     insn->imm == BPF_FUNC_redirect_map    ||
19155 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19156 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19157 			aux = &env->insn_aux_data[i + delta];
19158 			if (bpf_map_ptr_poisoned(aux))
19159 				goto patch_call_imm;
19160 
19161 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19162 			ops = map_ptr->ops;
19163 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19164 			    ops->map_gen_lookup) {
19165 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19166 				if (cnt == -EOPNOTSUPP)
19167 					goto patch_map_ops_generic;
19168 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19169 					verbose(env, "bpf verifier is misconfigured\n");
19170 					return -EINVAL;
19171 				}
19172 
19173 				new_prog = bpf_patch_insn_data(env, i + delta,
19174 							       insn_buf, cnt);
19175 				if (!new_prog)
19176 					return -ENOMEM;
19177 
19178 				delta    += cnt - 1;
19179 				env->prog = prog = new_prog;
19180 				insn      = new_prog->insnsi + i + delta;
19181 				continue;
19182 			}
19183 
19184 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19185 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19186 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19187 				     (long (*)(struct bpf_map *map, void *key))NULL));
19188 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19189 				     (long (*)(struct bpf_map *map, void *key, void *value,
19190 					      u64 flags))NULL));
19191 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19192 				     (long (*)(struct bpf_map *map, void *value,
19193 					      u64 flags))NULL));
19194 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19195 				     (long (*)(struct bpf_map *map, void *value))NULL));
19196 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19197 				     (long (*)(struct bpf_map *map, void *value))NULL));
19198 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19199 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19200 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19201 				     (long (*)(struct bpf_map *map,
19202 					      bpf_callback_t callback_fn,
19203 					      void *callback_ctx,
19204 					      u64 flags))NULL));
19205 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19206 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19207 
19208 patch_map_ops_generic:
19209 			switch (insn->imm) {
19210 			case BPF_FUNC_map_lookup_elem:
19211 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19212 				continue;
19213 			case BPF_FUNC_map_update_elem:
19214 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19215 				continue;
19216 			case BPF_FUNC_map_delete_elem:
19217 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19218 				continue;
19219 			case BPF_FUNC_map_push_elem:
19220 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19221 				continue;
19222 			case BPF_FUNC_map_pop_elem:
19223 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19224 				continue;
19225 			case BPF_FUNC_map_peek_elem:
19226 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19227 				continue;
19228 			case BPF_FUNC_redirect_map:
19229 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19230 				continue;
19231 			case BPF_FUNC_for_each_map_elem:
19232 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19233 				continue;
19234 			case BPF_FUNC_map_lookup_percpu_elem:
19235 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19236 				continue;
19237 			}
19238 
19239 			goto patch_call_imm;
19240 		}
19241 
19242 		/* Implement bpf_jiffies64 inline. */
19243 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19244 		    insn->imm == BPF_FUNC_jiffies64) {
19245 			struct bpf_insn ld_jiffies_addr[2] = {
19246 				BPF_LD_IMM64(BPF_REG_0,
19247 					     (unsigned long)&jiffies),
19248 			};
19249 
19250 			insn_buf[0] = ld_jiffies_addr[0];
19251 			insn_buf[1] = ld_jiffies_addr[1];
19252 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19253 						  BPF_REG_0, 0);
19254 			cnt = 3;
19255 
19256 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19257 						       cnt);
19258 			if (!new_prog)
19259 				return -ENOMEM;
19260 
19261 			delta    += cnt - 1;
19262 			env->prog = prog = new_prog;
19263 			insn      = new_prog->insnsi + i + delta;
19264 			continue;
19265 		}
19266 
19267 		/* Implement bpf_get_func_arg inline. */
19268 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19269 		    insn->imm == BPF_FUNC_get_func_arg) {
19270 			/* Load nr_args from ctx - 8 */
19271 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19272 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19273 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19274 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19275 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19276 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19277 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19278 			insn_buf[7] = BPF_JMP_A(1);
19279 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19280 			cnt = 9;
19281 
19282 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19283 			if (!new_prog)
19284 				return -ENOMEM;
19285 
19286 			delta    += cnt - 1;
19287 			env->prog = prog = new_prog;
19288 			insn      = new_prog->insnsi + i + delta;
19289 			continue;
19290 		}
19291 
19292 		/* Implement bpf_get_func_ret inline. */
19293 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19294 		    insn->imm == BPF_FUNC_get_func_ret) {
19295 			if (eatype == BPF_TRACE_FEXIT ||
19296 			    eatype == BPF_MODIFY_RETURN) {
19297 				/* Load nr_args from ctx - 8 */
19298 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19299 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19300 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19301 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19302 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19303 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19304 				cnt = 6;
19305 			} else {
19306 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19307 				cnt = 1;
19308 			}
19309 
19310 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19311 			if (!new_prog)
19312 				return -ENOMEM;
19313 
19314 			delta    += cnt - 1;
19315 			env->prog = prog = new_prog;
19316 			insn      = new_prog->insnsi + i + delta;
19317 			continue;
19318 		}
19319 
19320 		/* Implement get_func_arg_cnt inline. */
19321 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19322 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19323 			/* Load nr_args from ctx - 8 */
19324 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19325 
19326 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19327 			if (!new_prog)
19328 				return -ENOMEM;
19329 
19330 			env->prog = prog = new_prog;
19331 			insn      = new_prog->insnsi + i + delta;
19332 			continue;
19333 		}
19334 
19335 		/* Implement bpf_get_func_ip inline. */
19336 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19337 		    insn->imm == BPF_FUNC_get_func_ip) {
19338 			/* Load IP address from ctx - 16 */
19339 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19340 
19341 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19342 			if (!new_prog)
19343 				return -ENOMEM;
19344 
19345 			env->prog = prog = new_prog;
19346 			insn      = new_prog->insnsi + i + delta;
19347 			continue;
19348 		}
19349 
19350 patch_call_imm:
19351 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19352 		/* all functions that have prototype and verifier allowed
19353 		 * programs to call them, must be real in-kernel functions
19354 		 */
19355 		if (!fn->func) {
19356 			verbose(env,
19357 				"kernel subsystem misconfigured func %s#%d\n",
19358 				func_id_name(insn->imm), insn->imm);
19359 			return -EFAULT;
19360 		}
19361 		insn->imm = fn->func - __bpf_call_base;
19362 	}
19363 
19364 	/* Since poke tab is now finalized, publish aux to tracker. */
19365 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19366 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19367 		if (!map_ptr->ops->map_poke_track ||
19368 		    !map_ptr->ops->map_poke_untrack ||
19369 		    !map_ptr->ops->map_poke_run) {
19370 			verbose(env, "bpf verifier is misconfigured\n");
19371 			return -EINVAL;
19372 		}
19373 
19374 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19375 		if (ret < 0) {
19376 			verbose(env, "tracking tail call prog failed\n");
19377 			return ret;
19378 		}
19379 	}
19380 
19381 	sort_kfunc_descs_by_imm_off(env->prog);
19382 
19383 	return 0;
19384 }
19385 
19386 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19387 					int position,
19388 					s32 stack_base,
19389 					u32 callback_subprogno,
19390 					u32 *cnt)
19391 {
19392 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19393 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19394 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19395 	int reg_loop_max = BPF_REG_6;
19396 	int reg_loop_cnt = BPF_REG_7;
19397 	int reg_loop_ctx = BPF_REG_8;
19398 
19399 	struct bpf_prog *new_prog;
19400 	u32 callback_start;
19401 	u32 call_insn_offset;
19402 	s32 callback_offset;
19403 
19404 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19405 	 * be careful to modify this code in sync.
19406 	 */
19407 	struct bpf_insn insn_buf[] = {
19408 		/* Return error and jump to the end of the patch if
19409 		 * expected number of iterations is too big.
19410 		 */
19411 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19412 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19413 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19414 		/* spill R6, R7, R8 to use these as loop vars */
19415 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19416 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19417 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19418 		/* initialize loop vars */
19419 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19420 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19421 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19422 		/* loop header,
19423 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19424 		 */
19425 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19426 		/* callback call,
19427 		 * correct callback offset would be set after patching
19428 		 */
19429 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19430 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19431 		BPF_CALL_REL(0),
19432 		/* increment loop counter */
19433 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19434 		/* jump to loop header if callback returned 0 */
19435 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19436 		/* return value of bpf_loop,
19437 		 * set R0 to the number of iterations
19438 		 */
19439 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19440 		/* restore original values of R6, R7, R8 */
19441 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19442 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19443 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19444 	};
19445 
19446 	*cnt = ARRAY_SIZE(insn_buf);
19447 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19448 	if (!new_prog)
19449 		return new_prog;
19450 
19451 	/* callback start is known only after patching */
19452 	callback_start = env->subprog_info[callback_subprogno].start;
19453 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19454 	call_insn_offset = position + 12;
19455 	callback_offset = callback_start - call_insn_offset - 1;
19456 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19457 
19458 	return new_prog;
19459 }
19460 
19461 static bool is_bpf_loop_call(struct bpf_insn *insn)
19462 {
19463 	return insn->code == (BPF_JMP | BPF_CALL) &&
19464 		insn->src_reg == 0 &&
19465 		insn->imm == BPF_FUNC_loop;
19466 }
19467 
19468 /* For all sub-programs in the program (including main) check
19469  * insn_aux_data to see if there are bpf_loop calls that require
19470  * inlining. If such calls are found the calls are replaced with a
19471  * sequence of instructions produced by `inline_bpf_loop` function and
19472  * subprog stack_depth is increased by the size of 3 registers.
19473  * This stack space is used to spill values of the R6, R7, R8.  These
19474  * registers are used to store the loop bound, counter and context
19475  * variables.
19476  */
19477 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19478 {
19479 	struct bpf_subprog_info *subprogs = env->subprog_info;
19480 	int i, cur_subprog = 0, cnt, delta = 0;
19481 	struct bpf_insn *insn = env->prog->insnsi;
19482 	int insn_cnt = env->prog->len;
19483 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19484 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19485 	u16 stack_depth_extra = 0;
19486 
19487 	for (i = 0; i < insn_cnt; i++, insn++) {
19488 		struct bpf_loop_inline_state *inline_state =
19489 			&env->insn_aux_data[i + delta].loop_inline_state;
19490 
19491 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19492 			struct bpf_prog *new_prog;
19493 
19494 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19495 			new_prog = inline_bpf_loop(env,
19496 						   i + delta,
19497 						   -(stack_depth + stack_depth_extra),
19498 						   inline_state->callback_subprogno,
19499 						   &cnt);
19500 			if (!new_prog)
19501 				return -ENOMEM;
19502 
19503 			delta     += cnt - 1;
19504 			env->prog  = new_prog;
19505 			insn       = new_prog->insnsi + i + delta;
19506 		}
19507 
19508 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19509 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19510 			cur_subprog++;
19511 			stack_depth = subprogs[cur_subprog].stack_depth;
19512 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19513 			stack_depth_extra = 0;
19514 		}
19515 	}
19516 
19517 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19518 
19519 	return 0;
19520 }
19521 
19522 static void free_states(struct bpf_verifier_env *env)
19523 {
19524 	struct bpf_verifier_state_list *sl, *sln;
19525 	int i;
19526 
19527 	sl = env->free_list;
19528 	while (sl) {
19529 		sln = sl->next;
19530 		free_verifier_state(&sl->state, false);
19531 		kfree(sl);
19532 		sl = sln;
19533 	}
19534 	env->free_list = NULL;
19535 
19536 	if (!env->explored_states)
19537 		return;
19538 
19539 	for (i = 0; i < state_htab_size(env); i++) {
19540 		sl = env->explored_states[i];
19541 
19542 		while (sl) {
19543 			sln = sl->next;
19544 			free_verifier_state(&sl->state, false);
19545 			kfree(sl);
19546 			sl = sln;
19547 		}
19548 		env->explored_states[i] = NULL;
19549 	}
19550 }
19551 
19552 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19553 {
19554 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19555 	struct bpf_verifier_state *state;
19556 	struct bpf_reg_state *regs;
19557 	int ret, i;
19558 
19559 	env->prev_linfo = NULL;
19560 	env->pass_cnt++;
19561 
19562 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19563 	if (!state)
19564 		return -ENOMEM;
19565 	state->curframe = 0;
19566 	state->speculative = false;
19567 	state->branches = 1;
19568 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19569 	if (!state->frame[0]) {
19570 		kfree(state);
19571 		return -ENOMEM;
19572 	}
19573 	env->cur_state = state;
19574 	init_func_state(env, state->frame[0],
19575 			BPF_MAIN_FUNC /* callsite */,
19576 			0 /* frameno */,
19577 			subprog);
19578 	state->first_insn_idx = env->subprog_info[subprog].start;
19579 	state->last_insn_idx = -1;
19580 
19581 	regs = state->frame[state->curframe]->regs;
19582 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19583 		ret = btf_prepare_func_args(env, subprog, regs);
19584 		if (ret)
19585 			goto out;
19586 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19587 			if (regs[i].type == PTR_TO_CTX)
19588 				mark_reg_known_zero(env, regs, i);
19589 			else if (regs[i].type == SCALAR_VALUE)
19590 				mark_reg_unknown(env, regs, i);
19591 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19592 				const u32 mem_size = regs[i].mem_size;
19593 
19594 				mark_reg_known_zero(env, regs, i);
19595 				regs[i].mem_size = mem_size;
19596 				regs[i].id = ++env->id_gen;
19597 			}
19598 		}
19599 	} else {
19600 		/* 1st arg to a function */
19601 		regs[BPF_REG_1].type = PTR_TO_CTX;
19602 		mark_reg_known_zero(env, regs, BPF_REG_1);
19603 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19604 		if (ret == -EFAULT)
19605 			/* unlikely verifier bug. abort.
19606 			 * ret == 0 and ret < 0 are sadly acceptable for
19607 			 * main() function due to backward compatibility.
19608 			 * Like socket filter program may be written as:
19609 			 * int bpf_prog(struct pt_regs *ctx)
19610 			 * and never dereference that ctx in the program.
19611 			 * 'struct pt_regs' is a type mismatch for socket
19612 			 * filter that should be using 'struct __sk_buff'.
19613 			 */
19614 			goto out;
19615 	}
19616 
19617 	ret = do_check(env);
19618 out:
19619 	/* check for NULL is necessary, since cur_state can be freed inside
19620 	 * do_check() under memory pressure.
19621 	 */
19622 	if (env->cur_state) {
19623 		free_verifier_state(env->cur_state, true);
19624 		env->cur_state = NULL;
19625 	}
19626 	while (!pop_stack(env, NULL, NULL, false));
19627 	if (!ret && pop_log)
19628 		bpf_vlog_reset(&env->log, 0);
19629 	free_states(env);
19630 	return ret;
19631 }
19632 
19633 /* Verify all global functions in a BPF program one by one based on their BTF.
19634  * All global functions must pass verification. Otherwise the whole program is rejected.
19635  * Consider:
19636  * int bar(int);
19637  * int foo(int f)
19638  * {
19639  *    return bar(f);
19640  * }
19641  * int bar(int b)
19642  * {
19643  *    ...
19644  * }
19645  * foo() will be verified first for R1=any_scalar_value. During verification it
19646  * will be assumed that bar() already verified successfully and call to bar()
19647  * from foo() will be checked for type match only. Later bar() will be verified
19648  * independently to check that it's safe for R1=any_scalar_value.
19649  */
19650 static int do_check_subprogs(struct bpf_verifier_env *env)
19651 {
19652 	struct bpf_prog_aux *aux = env->prog->aux;
19653 	int i, ret;
19654 
19655 	if (!aux->func_info)
19656 		return 0;
19657 
19658 	for (i = 1; i < env->subprog_cnt; i++) {
19659 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19660 			continue;
19661 		env->insn_idx = env->subprog_info[i].start;
19662 		WARN_ON_ONCE(env->insn_idx == 0);
19663 		ret = do_check_common(env, i);
19664 		if (ret) {
19665 			return ret;
19666 		} else if (env->log.level & BPF_LOG_LEVEL) {
19667 			verbose(env,
19668 				"Func#%d is safe for any args that match its prototype\n",
19669 				i);
19670 		}
19671 	}
19672 	return 0;
19673 }
19674 
19675 static int do_check_main(struct bpf_verifier_env *env)
19676 {
19677 	int ret;
19678 
19679 	env->insn_idx = 0;
19680 	ret = do_check_common(env, 0);
19681 	if (!ret)
19682 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19683 	return ret;
19684 }
19685 
19686 
19687 static void print_verification_stats(struct bpf_verifier_env *env)
19688 {
19689 	int i;
19690 
19691 	if (env->log.level & BPF_LOG_STATS) {
19692 		verbose(env, "verification time %lld usec\n",
19693 			div_u64(env->verification_time, 1000));
19694 		verbose(env, "stack depth ");
19695 		for (i = 0; i < env->subprog_cnt; i++) {
19696 			u32 depth = env->subprog_info[i].stack_depth;
19697 
19698 			verbose(env, "%d", depth);
19699 			if (i + 1 < env->subprog_cnt)
19700 				verbose(env, "+");
19701 		}
19702 		verbose(env, "\n");
19703 	}
19704 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19705 		"total_states %d peak_states %d mark_read %d\n",
19706 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19707 		env->max_states_per_insn, env->total_states,
19708 		env->peak_states, env->longest_mark_read_walk);
19709 }
19710 
19711 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19712 {
19713 	const struct btf_type *t, *func_proto;
19714 	const struct bpf_struct_ops *st_ops;
19715 	const struct btf_member *member;
19716 	struct bpf_prog *prog = env->prog;
19717 	u32 btf_id, member_idx;
19718 	const char *mname;
19719 
19720 	if (!prog->gpl_compatible) {
19721 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19722 		return -EINVAL;
19723 	}
19724 
19725 	btf_id = prog->aux->attach_btf_id;
19726 	st_ops = bpf_struct_ops_find(btf_id);
19727 	if (!st_ops) {
19728 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19729 			btf_id);
19730 		return -ENOTSUPP;
19731 	}
19732 
19733 	t = st_ops->type;
19734 	member_idx = prog->expected_attach_type;
19735 	if (member_idx >= btf_type_vlen(t)) {
19736 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19737 			member_idx, st_ops->name);
19738 		return -EINVAL;
19739 	}
19740 
19741 	member = &btf_type_member(t)[member_idx];
19742 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19743 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19744 					       NULL);
19745 	if (!func_proto) {
19746 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19747 			mname, member_idx, st_ops->name);
19748 		return -EINVAL;
19749 	}
19750 
19751 	if (st_ops->check_member) {
19752 		int err = st_ops->check_member(t, member, prog);
19753 
19754 		if (err) {
19755 			verbose(env, "attach to unsupported member %s of struct %s\n",
19756 				mname, st_ops->name);
19757 			return err;
19758 		}
19759 	}
19760 
19761 	prog->aux->attach_func_proto = func_proto;
19762 	prog->aux->attach_func_name = mname;
19763 	env->ops = st_ops->verifier_ops;
19764 
19765 	return 0;
19766 }
19767 #define SECURITY_PREFIX "security_"
19768 
19769 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19770 {
19771 	if (within_error_injection_list(addr) ||
19772 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19773 		return 0;
19774 
19775 	return -EINVAL;
19776 }
19777 
19778 /* list of non-sleepable functions that are otherwise on
19779  * ALLOW_ERROR_INJECTION list
19780  */
19781 BTF_SET_START(btf_non_sleepable_error_inject)
19782 /* Three functions below can be called from sleepable and non-sleepable context.
19783  * Assume non-sleepable from bpf safety point of view.
19784  */
19785 BTF_ID(func, __filemap_add_folio)
19786 BTF_ID(func, should_fail_alloc_page)
19787 BTF_ID(func, should_failslab)
19788 BTF_SET_END(btf_non_sleepable_error_inject)
19789 
19790 static int check_non_sleepable_error_inject(u32 btf_id)
19791 {
19792 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19793 }
19794 
19795 int bpf_check_attach_target(struct bpf_verifier_log *log,
19796 			    const struct bpf_prog *prog,
19797 			    const struct bpf_prog *tgt_prog,
19798 			    u32 btf_id,
19799 			    struct bpf_attach_target_info *tgt_info)
19800 {
19801 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19802 	const char prefix[] = "btf_trace_";
19803 	int ret = 0, subprog = -1, i;
19804 	const struct btf_type *t;
19805 	bool conservative = true;
19806 	const char *tname;
19807 	struct btf *btf;
19808 	long addr = 0;
19809 	struct module *mod = NULL;
19810 
19811 	if (!btf_id) {
19812 		bpf_log(log, "Tracing programs must provide btf_id\n");
19813 		return -EINVAL;
19814 	}
19815 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19816 	if (!btf) {
19817 		bpf_log(log,
19818 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19819 		return -EINVAL;
19820 	}
19821 	t = btf_type_by_id(btf, btf_id);
19822 	if (!t) {
19823 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19824 		return -EINVAL;
19825 	}
19826 	tname = btf_name_by_offset(btf, t->name_off);
19827 	if (!tname) {
19828 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19829 		return -EINVAL;
19830 	}
19831 	if (tgt_prog) {
19832 		struct bpf_prog_aux *aux = tgt_prog->aux;
19833 
19834 		if (bpf_prog_is_dev_bound(prog->aux) &&
19835 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19836 			bpf_log(log, "Target program bound device mismatch");
19837 			return -EINVAL;
19838 		}
19839 
19840 		for (i = 0; i < aux->func_info_cnt; i++)
19841 			if (aux->func_info[i].type_id == btf_id) {
19842 				subprog = i;
19843 				break;
19844 			}
19845 		if (subprog == -1) {
19846 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19847 			return -EINVAL;
19848 		}
19849 		conservative = aux->func_info_aux[subprog].unreliable;
19850 		if (prog_extension) {
19851 			if (conservative) {
19852 				bpf_log(log,
19853 					"Cannot replace static functions\n");
19854 				return -EINVAL;
19855 			}
19856 			if (!prog->jit_requested) {
19857 				bpf_log(log,
19858 					"Extension programs should be JITed\n");
19859 				return -EINVAL;
19860 			}
19861 		}
19862 		if (!tgt_prog->jited) {
19863 			bpf_log(log, "Can attach to only JITed progs\n");
19864 			return -EINVAL;
19865 		}
19866 		if (tgt_prog->type == prog->type) {
19867 			/* Cannot fentry/fexit another fentry/fexit program.
19868 			 * Cannot attach program extension to another extension.
19869 			 * It's ok to attach fentry/fexit to extension program.
19870 			 */
19871 			bpf_log(log, "Cannot recursively attach\n");
19872 			return -EINVAL;
19873 		}
19874 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19875 		    prog_extension &&
19876 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19877 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19878 			/* Program extensions can extend all program types
19879 			 * except fentry/fexit. The reason is the following.
19880 			 * The fentry/fexit programs are used for performance
19881 			 * analysis, stats and can be attached to any program
19882 			 * type except themselves. When extension program is
19883 			 * replacing XDP function it is necessary to allow
19884 			 * performance analysis of all functions. Both original
19885 			 * XDP program and its program extension. Hence
19886 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19887 			 * allowed. If extending of fentry/fexit was allowed it
19888 			 * would be possible to create long call chain
19889 			 * fentry->extension->fentry->extension beyond
19890 			 * reasonable stack size. Hence extending fentry is not
19891 			 * allowed.
19892 			 */
19893 			bpf_log(log, "Cannot extend fentry/fexit\n");
19894 			return -EINVAL;
19895 		}
19896 	} else {
19897 		if (prog_extension) {
19898 			bpf_log(log, "Cannot replace kernel functions\n");
19899 			return -EINVAL;
19900 		}
19901 	}
19902 
19903 	switch (prog->expected_attach_type) {
19904 	case BPF_TRACE_RAW_TP:
19905 		if (tgt_prog) {
19906 			bpf_log(log,
19907 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19908 			return -EINVAL;
19909 		}
19910 		if (!btf_type_is_typedef(t)) {
19911 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19912 				btf_id);
19913 			return -EINVAL;
19914 		}
19915 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19916 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19917 				btf_id, tname);
19918 			return -EINVAL;
19919 		}
19920 		tname += sizeof(prefix) - 1;
19921 		t = btf_type_by_id(btf, t->type);
19922 		if (!btf_type_is_ptr(t))
19923 			/* should never happen in valid vmlinux build */
19924 			return -EINVAL;
19925 		t = btf_type_by_id(btf, t->type);
19926 		if (!btf_type_is_func_proto(t))
19927 			/* should never happen in valid vmlinux build */
19928 			return -EINVAL;
19929 
19930 		break;
19931 	case BPF_TRACE_ITER:
19932 		if (!btf_type_is_func(t)) {
19933 			bpf_log(log, "attach_btf_id %u is not a function\n",
19934 				btf_id);
19935 			return -EINVAL;
19936 		}
19937 		t = btf_type_by_id(btf, t->type);
19938 		if (!btf_type_is_func_proto(t))
19939 			return -EINVAL;
19940 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19941 		if (ret)
19942 			return ret;
19943 		break;
19944 	default:
19945 		if (!prog_extension)
19946 			return -EINVAL;
19947 		fallthrough;
19948 	case BPF_MODIFY_RETURN:
19949 	case BPF_LSM_MAC:
19950 	case BPF_LSM_CGROUP:
19951 	case BPF_TRACE_FENTRY:
19952 	case BPF_TRACE_FEXIT:
19953 		if (!btf_type_is_func(t)) {
19954 			bpf_log(log, "attach_btf_id %u is not a function\n",
19955 				btf_id);
19956 			return -EINVAL;
19957 		}
19958 		if (prog_extension &&
19959 		    btf_check_type_match(log, prog, btf, t))
19960 			return -EINVAL;
19961 		t = btf_type_by_id(btf, t->type);
19962 		if (!btf_type_is_func_proto(t))
19963 			return -EINVAL;
19964 
19965 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19966 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19967 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19968 			return -EINVAL;
19969 
19970 		if (tgt_prog && conservative)
19971 			t = NULL;
19972 
19973 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19974 		if (ret < 0)
19975 			return ret;
19976 
19977 		if (tgt_prog) {
19978 			if (subprog == 0)
19979 				addr = (long) tgt_prog->bpf_func;
19980 			else
19981 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19982 		} else {
19983 			if (btf_is_module(btf)) {
19984 				mod = btf_try_get_module(btf);
19985 				if (mod)
19986 					addr = find_kallsyms_symbol_value(mod, tname);
19987 				else
19988 					addr = 0;
19989 			} else {
19990 				addr = kallsyms_lookup_name(tname);
19991 			}
19992 			if (!addr) {
19993 				module_put(mod);
19994 				bpf_log(log,
19995 					"The address of function %s cannot be found\n",
19996 					tname);
19997 				return -ENOENT;
19998 			}
19999 		}
20000 
20001 		if (prog->aux->sleepable) {
20002 			ret = -EINVAL;
20003 			switch (prog->type) {
20004 			case BPF_PROG_TYPE_TRACING:
20005 
20006 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20007 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20008 				 */
20009 				if (!check_non_sleepable_error_inject(btf_id) &&
20010 				    within_error_injection_list(addr))
20011 					ret = 0;
20012 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20013 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20014 				 */
20015 				else {
20016 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20017 										prog);
20018 
20019 					if (flags && (*flags & KF_SLEEPABLE))
20020 						ret = 0;
20021 				}
20022 				break;
20023 			case BPF_PROG_TYPE_LSM:
20024 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20025 				 * Only some of them are sleepable.
20026 				 */
20027 				if (bpf_lsm_is_sleepable_hook(btf_id))
20028 					ret = 0;
20029 				break;
20030 			default:
20031 				break;
20032 			}
20033 			if (ret) {
20034 				module_put(mod);
20035 				bpf_log(log, "%s is not sleepable\n", tname);
20036 				return ret;
20037 			}
20038 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20039 			if (tgt_prog) {
20040 				module_put(mod);
20041 				bpf_log(log, "can't modify return codes of BPF programs\n");
20042 				return -EINVAL;
20043 			}
20044 			ret = -EINVAL;
20045 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20046 			    !check_attach_modify_return(addr, tname))
20047 				ret = 0;
20048 			if (ret) {
20049 				module_put(mod);
20050 				bpf_log(log, "%s() is not modifiable\n", tname);
20051 				return ret;
20052 			}
20053 		}
20054 
20055 		break;
20056 	}
20057 	tgt_info->tgt_addr = addr;
20058 	tgt_info->tgt_name = tname;
20059 	tgt_info->tgt_type = t;
20060 	tgt_info->tgt_mod = mod;
20061 	return 0;
20062 }
20063 
20064 BTF_SET_START(btf_id_deny)
20065 BTF_ID_UNUSED
20066 #ifdef CONFIG_SMP
20067 BTF_ID(func, migrate_disable)
20068 BTF_ID(func, migrate_enable)
20069 #endif
20070 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20071 BTF_ID(func, rcu_read_unlock_strict)
20072 #endif
20073 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20074 BTF_ID(func, preempt_count_add)
20075 BTF_ID(func, preempt_count_sub)
20076 #endif
20077 #ifdef CONFIG_PREEMPT_RCU
20078 BTF_ID(func, __rcu_read_lock)
20079 BTF_ID(func, __rcu_read_unlock)
20080 #endif
20081 BTF_SET_END(btf_id_deny)
20082 
20083 static bool can_be_sleepable(struct bpf_prog *prog)
20084 {
20085 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20086 		switch (prog->expected_attach_type) {
20087 		case BPF_TRACE_FENTRY:
20088 		case BPF_TRACE_FEXIT:
20089 		case BPF_MODIFY_RETURN:
20090 		case BPF_TRACE_ITER:
20091 			return true;
20092 		default:
20093 			return false;
20094 		}
20095 	}
20096 	return prog->type == BPF_PROG_TYPE_LSM ||
20097 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20098 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20099 }
20100 
20101 static int check_attach_btf_id(struct bpf_verifier_env *env)
20102 {
20103 	struct bpf_prog *prog = env->prog;
20104 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20105 	struct bpf_attach_target_info tgt_info = {};
20106 	u32 btf_id = prog->aux->attach_btf_id;
20107 	struct bpf_trampoline *tr;
20108 	int ret;
20109 	u64 key;
20110 
20111 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20112 		if (prog->aux->sleepable)
20113 			/* attach_btf_id checked to be zero already */
20114 			return 0;
20115 		verbose(env, "Syscall programs can only be sleepable\n");
20116 		return -EINVAL;
20117 	}
20118 
20119 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20120 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20121 		return -EINVAL;
20122 	}
20123 
20124 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20125 		return check_struct_ops_btf_id(env);
20126 
20127 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20128 	    prog->type != BPF_PROG_TYPE_LSM &&
20129 	    prog->type != BPF_PROG_TYPE_EXT)
20130 		return 0;
20131 
20132 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20133 	if (ret)
20134 		return ret;
20135 
20136 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20137 		/* to make freplace equivalent to their targets, they need to
20138 		 * inherit env->ops and expected_attach_type for the rest of the
20139 		 * verification
20140 		 */
20141 		env->ops = bpf_verifier_ops[tgt_prog->type];
20142 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20143 	}
20144 
20145 	/* store info about the attachment target that will be used later */
20146 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20147 	prog->aux->attach_func_name = tgt_info.tgt_name;
20148 	prog->aux->mod = tgt_info.tgt_mod;
20149 
20150 	if (tgt_prog) {
20151 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20152 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20153 	}
20154 
20155 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20156 		prog->aux->attach_btf_trace = true;
20157 		return 0;
20158 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20159 		if (!bpf_iter_prog_supported(prog))
20160 			return -EINVAL;
20161 		return 0;
20162 	}
20163 
20164 	if (prog->type == BPF_PROG_TYPE_LSM) {
20165 		ret = bpf_lsm_verify_prog(&env->log, prog);
20166 		if (ret < 0)
20167 			return ret;
20168 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20169 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20170 		return -EINVAL;
20171 	}
20172 
20173 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20174 	tr = bpf_trampoline_get(key, &tgt_info);
20175 	if (!tr)
20176 		return -ENOMEM;
20177 
20178 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20179 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20180 
20181 	prog->aux->dst_trampoline = tr;
20182 	return 0;
20183 }
20184 
20185 struct btf *bpf_get_btf_vmlinux(void)
20186 {
20187 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20188 		mutex_lock(&bpf_verifier_lock);
20189 		if (!btf_vmlinux)
20190 			btf_vmlinux = btf_parse_vmlinux();
20191 		mutex_unlock(&bpf_verifier_lock);
20192 	}
20193 	return btf_vmlinux;
20194 }
20195 
20196 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20197 {
20198 	u64 start_time = ktime_get_ns();
20199 	struct bpf_verifier_env *env;
20200 	int i, len, ret = -EINVAL, err;
20201 	u32 log_true_size;
20202 	bool is_priv;
20203 
20204 	/* no program is valid */
20205 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20206 		return -EINVAL;
20207 
20208 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20209 	 * allocate/free it every time bpf_check() is called
20210 	 */
20211 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20212 	if (!env)
20213 		return -ENOMEM;
20214 
20215 	env->bt.env = env;
20216 
20217 	len = (*prog)->len;
20218 	env->insn_aux_data =
20219 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20220 	ret = -ENOMEM;
20221 	if (!env->insn_aux_data)
20222 		goto err_free_env;
20223 	for (i = 0; i < len; i++)
20224 		env->insn_aux_data[i].orig_idx = i;
20225 	env->prog = *prog;
20226 	env->ops = bpf_verifier_ops[env->prog->type];
20227 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20228 	is_priv = bpf_capable();
20229 
20230 	bpf_get_btf_vmlinux();
20231 
20232 	/* grab the mutex to protect few globals used by verifier */
20233 	if (!is_priv)
20234 		mutex_lock(&bpf_verifier_lock);
20235 
20236 	/* user could have requested verbose verifier output
20237 	 * and supplied buffer to store the verification trace
20238 	 */
20239 	ret = bpf_vlog_init(&env->log, attr->log_level,
20240 			    (char __user *) (unsigned long) attr->log_buf,
20241 			    attr->log_size);
20242 	if (ret)
20243 		goto err_unlock;
20244 
20245 	mark_verifier_state_clean(env);
20246 
20247 	if (IS_ERR(btf_vmlinux)) {
20248 		/* Either gcc or pahole or kernel are broken. */
20249 		verbose(env, "in-kernel BTF is malformed\n");
20250 		ret = PTR_ERR(btf_vmlinux);
20251 		goto skip_full_check;
20252 	}
20253 
20254 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20255 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20256 		env->strict_alignment = true;
20257 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20258 		env->strict_alignment = false;
20259 
20260 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20261 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20262 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20263 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20264 	env->bpf_capable = bpf_capable();
20265 
20266 	if (is_priv)
20267 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20268 
20269 	env->explored_states = kvcalloc(state_htab_size(env),
20270 				       sizeof(struct bpf_verifier_state_list *),
20271 				       GFP_USER);
20272 	ret = -ENOMEM;
20273 	if (!env->explored_states)
20274 		goto skip_full_check;
20275 
20276 	ret = add_subprog_and_kfunc(env);
20277 	if (ret < 0)
20278 		goto skip_full_check;
20279 
20280 	ret = check_subprogs(env);
20281 	if (ret < 0)
20282 		goto skip_full_check;
20283 
20284 	ret = check_btf_info(env, attr, uattr);
20285 	if (ret < 0)
20286 		goto skip_full_check;
20287 
20288 	ret = check_attach_btf_id(env);
20289 	if (ret)
20290 		goto skip_full_check;
20291 
20292 	ret = resolve_pseudo_ldimm64(env);
20293 	if (ret < 0)
20294 		goto skip_full_check;
20295 
20296 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20297 		ret = bpf_prog_offload_verifier_prep(env->prog);
20298 		if (ret)
20299 			goto skip_full_check;
20300 	}
20301 
20302 	ret = check_cfg(env);
20303 	if (ret < 0)
20304 		goto skip_full_check;
20305 
20306 	ret = do_check_subprogs(env);
20307 	ret = ret ?: do_check_main(env);
20308 
20309 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20310 		ret = bpf_prog_offload_finalize(env);
20311 
20312 skip_full_check:
20313 	kvfree(env->explored_states);
20314 
20315 	if (ret == 0)
20316 		ret = check_max_stack_depth(env);
20317 
20318 	/* instruction rewrites happen after this point */
20319 	if (ret == 0)
20320 		ret = optimize_bpf_loop(env);
20321 
20322 	if (is_priv) {
20323 		if (ret == 0)
20324 			opt_hard_wire_dead_code_branches(env);
20325 		if (ret == 0)
20326 			ret = opt_remove_dead_code(env);
20327 		if (ret == 0)
20328 			ret = opt_remove_nops(env);
20329 	} else {
20330 		if (ret == 0)
20331 			sanitize_dead_code(env);
20332 	}
20333 
20334 	if (ret == 0)
20335 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20336 		ret = convert_ctx_accesses(env);
20337 
20338 	if (ret == 0)
20339 		ret = do_misc_fixups(env);
20340 
20341 	/* do 32-bit optimization after insn patching has done so those patched
20342 	 * insns could be handled correctly.
20343 	 */
20344 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20345 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20346 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20347 								     : false;
20348 	}
20349 
20350 	if (ret == 0)
20351 		ret = fixup_call_args(env);
20352 
20353 	env->verification_time = ktime_get_ns() - start_time;
20354 	print_verification_stats(env);
20355 	env->prog->aux->verified_insns = env->insn_processed;
20356 
20357 	/* preserve original error even if log finalization is successful */
20358 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20359 	if (err)
20360 		ret = err;
20361 
20362 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20363 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20364 				  &log_true_size, sizeof(log_true_size))) {
20365 		ret = -EFAULT;
20366 		goto err_release_maps;
20367 	}
20368 
20369 	if (ret)
20370 		goto err_release_maps;
20371 
20372 	if (env->used_map_cnt) {
20373 		/* if program passed verifier, update used_maps in bpf_prog_info */
20374 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20375 							  sizeof(env->used_maps[0]),
20376 							  GFP_KERNEL);
20377 
20378 		if (!env->prog->aux->used_maps) {
20379 			ret = -ENOMEM;
20380 			goto err_release_maps;
20381 		}
20382 
20383 		memcpy(env->prog->aux->used_maps, env->used_maps,
20384 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20385 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20386 	}
20387 	if (env->used_btf_cnt) {
20388 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20389 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20390 							  sizeof(env->used_btfs[0]),
20391 							  GFP_KERNEL);
20392 		if (!env->prog->aux->used_btfs) {
20393 			ret = -ENOMEM;
20394 			goto err_release_maps;
20395 		}
20396 
20397 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20398 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20399 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20400 	}
20401 	if (env->used_map_cnt || env->used_btf_cnt) {
20402 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20403 		 * bpf_ld_imm64 instructions
20404 		 */
20405 		convert_pseudo_ld_imm64(env);
20406 	}
20407 
20408 	adjust_btf_func(env);
20409 
20410 err_release_maps:
20411 	if (!env->prog->aux->used_maps)
20412 		/* if we didn't copy map pointers into bpf_prog_info, release
20413 		 * them now. Otherwise free_used_maps() will release them.
20414 		 */
20415 		release_maps(env);
20416 	if (!env->prog->aux->used_btfs)
20417 		release_btfs(env);
20418 
20419 	/* extension progs temporarily inherit the attach_type of their targets
20420 	   for verification purposes, so set it back to zero before returning
20421 	 */
20422 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20423 		env->prog->expected_attach_type = 0;
20424 
20425 	*prog = env->prog;
20426 err_unlock:
20427 	if (!is_priv)
20428 		mutex_unlock(&bpf_verifier_lock);
20429 	vfree(env->insn_aux_data);
20430 err_free_env:
20431 	kfree(env);
20432 	return ret;
20433 }
20434