xref: /openbmc/linux/kernel/bpf/verifier.c (revision 7e2e638c)
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_release(enum bpf_arg_type type)
7991 {
7992 	return type & OBJ_RELEASE;
7993 }
7994 
7995 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7996 {
7997 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7998 }
7999 
8000 static int int_ptr_type_to_size(enum bpf_arg_type type)
8001 {
8002 	if (type == ARG_PTR_TO_INT)
8003 		return sizeof(u32);
8004 	else if (type == ARG_PTR_TO_LONG)
8005 		return sizeof(u64);
8006 
8007 	return -EINVAL;
8008 }
8009 
8010 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8011 				 const struct bpf_call_arg_meta *meta,
8012 				 enum bpf_arg_type *arg_type)
8013 {
8014 	if (!meta->map_ptr) {
8015 		/* kernel subsystem misconfigured verifier */
8016 		verbose(env, "invalid map_ptr to access map->type\n");
8017 		return -EACCES;
8018 	}
8019 
8020 	switch (meta->map_ptr->map_type) {
8021 	case BPF_MAP_TYPE_SOCKMAP:
8022 	case BPF_MAP_TYPE_SOCKHASH:
8023 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8024 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8025 		} else {
8026 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8027 			return -EINVAL;
8028 		}
8029 		break;
8030 	case BPF_MAP_TYPE_BLOOM_FILTER:
8031 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8032 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8033 		break;
8034 	default:
8035 		break;
8036 	}
8037 	return 0;
8038 }
8039 
8040 struct bpf_reg_types {
8041 	const enum bpf_reg_type types[10];
8042 	u32 *btf_id;
8043 };
8044 
8045 static const struct bpf_reg_types sock_types = {
8046 	.types = {
8047 		PTR_TO_SOCK_COMMON,
8048 		PTR_TO_SOCKET,
8049 		PTR_TO_TCP_SOCK,
8050 		PTR_TO_XDP_SOCK,
8051 	},
8052 };
8053 
8054 #ifdef CONFIG_NET
8055 static const struct bpf_reg_types btf_id_sock_common_types = {
8056 	.types = {
8057 		PTR_TO_SOCK_COMMON,
8058 		PTR_TO_SOCKET,
8059 		PTR_TO_TCP_SOCK,
8060 		PTR_TO_XDP_SOCK,
8061 		PTR_TO_BTF_ID,
8062 		PTR_TO_BTF_ID | PTR_TRUSTED,
8063 	},
8064 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8065 };
8066 #endif
8067 
8068 static const struct bpf_reg_types mem_types = {
8069 	.types = {
8070 		PTR_TO_STACK,
8071 		PTR_TO_PACKET,
8072 		PTR_TO_PACKET_META,
8073 		PTR_TO_MAP_KEY,
8074 		PTR_TO_MAP_VALUE,
8075 		PTR_TO_MEM,
8076 		PTR_TO_MEM | MEM_RINGBUF,
8077 		PTR_TO_BUF,
8078 		PTR_TO_BTF_ID | PTR_TRUSTED,
8079 	},
8080 };
8081 
8082 static const struct bpf_reg_types int_ptr_types = {
8083 	.types = {
8084 		PTR_TO_STACK,
8085 		PTR_TO_PACKET,
8086 		PTR_TO_PACKET_META,
8087 		PTR_TO_MAP_KEY,
8088 		PTR_TO_MAP_VALUE,
8089 	},
8090 };
8091 
8092 static const struct bpf_reg_types spin_lock_types = {
8093 	.types = {
8094 		PTR_TO_MAP_VALUE,
8095 		PTR_TO_BTF_ID | MEM_ALLOC,
8096 	}
8097 };
8098 
8099 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8100 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8101 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8102 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8103 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8104 static const struct bpf_reg_types btf_ptr_types = {
8105 	.types = {
8106 		PTR_TO_BTF_ID,
8107 		PTR_TO_BTF_ID | PTR_TRUSTED,
8108 		PTR_TO_BTF_ID | MEM_RCU,
8109 	},
8110 };
8111 static const struct bpf_reg_types percpu_btf_ptr_types = {
8112 	.types = {
8113 		PTR_TO_BTF_ID | MEM_PERCPU,
8114 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8115 	}
8116 };
8117 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8118 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8119 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8120 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8121 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8122 static const struct bpf_reg_types dynptr_types = {
8123 	.types = {
8124 		PTR_TO_STACK,
8125 		CONST_PTR_TO_DYNPTR,
8126 	}
8127 };
8128 
8129 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8130 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8131 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8132 	[ARG_CONST_SIZE]		= &scalar_types,
8133 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8134 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8135 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8136 	[ARG_PTR_TO_CTX]		= &context_types,
8137 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8138 #ifdef CONFIG_NET
8139 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8140 #endif
8141 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8142 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8143 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8144 	[ARG_PTR_TO_MEM]		= &mem_types,
8145 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8146 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8147 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8148 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8149 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8150 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8151 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8152 	[ARG_PTR_TO_TIMER]		= &timer_types,
8153 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8154 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8155 };
8156 
8157 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8158 			  enum bpf_arg_type arg_type,
8159 			  const u32 *arg_btf_id,
8160 			  struct bpf_call_arg_meta *meta)
8161 {
8162 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8163 	enum bpf_reg_type expected, type = reg->type;
8164 	const struct bpf_reg_types *compatible;
8165 	int i, j;
8166 
8167 	compatible = compatible_reg_types[base_type(arg_type)];
8168 	if (!compatible) {
8169 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8170 		return -EFAULT;
8171 	}
8172 
8173 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8174 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8175 	 *
8176 	 * Same for MAYBE_NULL:
8177 	 *
8178 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8179 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8180 	 *
8181 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8182 	 *
8183 	 * Therefore we fold these flags depending on the arg_type before comparison.
8184 	 */
8185 	if (arg_type & MEM_RDONLY)
8186 		type &= ~MEM_RDONLY;
8187 	if (arg_type & PTR_MAYBE_NULL)
8188 		type &= ~PTR_MAYBE_NULL;
8189 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8190 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8191 
8192 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8193 		type &= ~MEM_ALLOC;
8194 
8195 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8196 		expected = compatible->types[i];
8197 		if (expected == NOT_INIT)
8198 			break;
8199 
8200 		if (type == expected)
8201 			goto found;
8202 	}
8203 
8204 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8205 	for (j = 0; j + 1 < i; j++)
8206 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8207 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8208 	return -EACCES;
8209 
8210 found:
8211 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8212 		return 0;
8213 
8214 	if (compatible == &mem_types) {
8215 		if (!(arg_type & MEM_RDONLY)) {
8216 			verbose(env,
8217 				"%s() may write into memory pointed by R%d type=%s\n",
8218 				func_id_name(meta->func_id),
8219 				regno, reg_type_str(env, reg->type));
8220 			return -EACCES;
8221 		}
8222 		return 0;
8223 	}
8224 
8225 	switch ((int)reg->type) {
8226 	case PTR_TO_BTF_ID:
8227 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8228 	case PTR_TO_BTF_ID | MEM_RCU:
8229 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8230 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8231 	{
8232 		/* For bpf_sk_release, it needs to match against first member
8233 		 * 'struct sock_common', hence make an exception for it. This
8234 		 * allows bpf_sk_release to work for multiple socket types.
8235 		 */
8236 		bool strict_type_match = arg_type_is_release(arg_type) &&
8237 					 meta->func_id != BPF_FUNC_sk_release;
8238 
8239 		if (type_may_be_null(reg->type) &&
8240 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8241 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8242 			return -EACCES;
8243 		}
8244 
8245 		if (!arg_btf_id) {
8246 			if (!compatible->btf_id) {
8247 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8248 				return -EFAULT;
8249 			}
8250 			arg_btf_id = compatible->btf_id;
8251 		}
8252 
8253 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8254 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8255 				return -EACCES;
8256 		} else {
8257 			if (arg_btf_id == BPF_PTR_POISON) {
8258 				verbose(env, "verifier internal error:");
8259 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8260 					regno);
8261 				return -EACCES;
8262 			}
8263 
8264 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8265 						  btf_vmlinux, *arg_btf_id,
8266 						  strict_type_match)) {
8267 				verbose(env, "R%d is of type %s but %s is expected\n",
8268 					regno, btf_type_name(reg->btf, reg->btf_id),
8269 					btf_type_name(btf_vmlinux, *arg_btf_id));
8270 				return -EACCES;
8271 			}
8272 		}
8273 		break;
8274 	}
8275 	case PTR_TO_BTF_ID | MEM_ALLOC:
8276 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8277 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8278 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8279 			return -EFAULT;
8280 		}
8281 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8282 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8283 				return -EACCES;
8284 		}
8285 		break;
8286 	case PTR_TO_BTF_ID | MEM_PERCPU:
8287 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8288 		/* Handled by helper specific checks */
8289 		break;
8290 	default:
8291 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8292 		return -EFAULT;
8293 	}
8294 	return 0;
8295 }
8296 
8297 static struct btf_field *
8298 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8299 {
8300 	struct btf_field *field;
8301 	struct btf_record *rec;
8302 
8303 	rec = reg_btf_record(reg);
8304 	if (!rec)
8305 		return NULL;
8306 
8307 	field = btf_record_find(rec, off, fields);
8308 	if (!field)
8309 		return NULL;
8310 
8311 	return field;
8312 }
8313 
8314 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8315 			   const struct bpf_reg_state *reg, int regno,
8316 			   enum bpf_arg_type arg_type)
8317 {
8318 	u32 type = reg->type;
8319 
8320 	/* When referenced register is passed to release function, its fixed
8321 	 * offset must be 0.
8322 	 *
8323 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8324 	 * meta->release_regno.
8325 	 */
8326 	if (arg_type_is_release(arg_type)) {
8327 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8328 		 * may not directly point to the object being released, but to
8329 		 * dynptr pointing to such object, which might be at some offset
8330 		 * on the stack. In that case, we simply to fallback to the
8331 		 * default handling.
8332 		 */
8333 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8334 			return 0;
8335 
8336 		/* Doing check_ptr_off_reg check for the offset will catch this
8337 		 * because fixed_off_ok is false, but checking here allows us
8338 		 * to give the user a better error message.
8339 		 */
8340 		if (reg->off) {
8341 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8342 				regno);
8343 			return -EINVAL;
8344 		}
8345 		return __check_ptr_off_reg(env, reg, regno, false);
8346 	}
8347 
8348 	switch (type) {
8349 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8350 	case PTR_TO_STACK:
8351 	case PTR_TO_PACKET:
8352 	case PTR_TO_PACKET_META:
8353 	case PTR_TO_MAP_KEY:
8354 	case PTR_TO_MAP_VALUE:
8355 	case PTR_TO_MEM:
8356 	case PTR_TO_MEM | MEM_RDONLY:
8357 	case PTR_TO_MEM | MEM_RINGBUF:
8358 	case PTR_TO_BUF:
8359 	case PTR_TO_BUF | MEM_RDONLY:
8360 	case SCALAR_VALUE:
8361 		return 0;
8362 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8363 	 * fixed offset.
8364 	 */
8365 	case PTR_TO_BTF_ID:
8366 	case PTR_TO_BTF_ID | MEM_ALLOC:
8367 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8368 	case PTR_TO_BTF_ID | MEM_RCU:
8369 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8370 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8371 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8372 		 * its fixed offset must be 0. In the other cases, fixed offset
8373 		 * can be non-zero. This was already checked above. So pass
8374 		 * fixed_off_ok as true to allow fixed offset for all other
8375 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8376 		 * still need to do checks instead of returning.
8377 		 */
8378 		return __check_ptr_off_reg(env, reg, regno, true);
8379 	default:
8380 		return __check_ptr_off_reg(env, reg, regno, false);
8381 	}
8382 }
8383 
8384 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8385 						const struct bpf_func_proto *fn,
8386 						struct bpf_reg_state *regs)
8387 {
8388 	struct bpf_reg_state *state = NULL;
8389 	int i;
8390 
8391 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8392 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8393 			if (state) {
8394 				verbose(env, "verifier internal error: multiple dynptr args\n");
8395 				return NULL;
8396 			}
8397 			state = &regs[BPF_REG_1 + i];
8398 		}
8399 
8400 	if (!state)
8401 		verbose(env, "verifier internal error: no dynptr arg found\n");
8402 
8403 	return state;
8404 }
8405 
8406 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8407 {
8408 	struct bpf_func_state *state = func(env, reg);
8409 	int spi;
8410 
8411 	if (reg->type == CONST_PTR_TO_DYNPTR)
8412 		return reg->id;
8413 	spi = dynptr_get_spi(env, reg);
8414 	if (spi < 0)
8415 		return spi;
8416 	return state->stack[spi].spilled_ptr.id;
8417 }
8418 
8419 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8420 {
8421 	struct bpf_func_state *state = func(env, reg);
8422 	int spi;
8423 
8424 	if (reg->type == CONST_PTR_TO_DYNPTR)
8425 		return reg->ref_obj_id;
8426 	spi = dynptr_get_spi(env, reg);
8427 	if (spi < 0)
8428 		return spi;
8429 	return state->stack[spi].spilled_ptr.ref_obj_id;
8430 }
8431 
8432 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8433 					    struct bpf_reg_state *reg)
8434 {
8435 	struct bpf_func_state *state = func(env, reg);
8436 	int spi;
8437 
8438 	if (reg->type == CONST_PTR_TO_DYNPTR)
8439 		return reg->dynptr.type;
8440 
8441 	spi = __get_spi(reg->off);
8442 	if (spi < 0) {
8443 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8444 		return BPF_DYNPTR_TYPE_INVALID;
8445 	}
8446 
8447 	return state->stack[spi].spilled_ptr.dynptr.type;
8448 }
8449 
8450 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8451 			  struct bpf_call_arg_meta *meta,
8452 			  const struct bpf_func_proto *fn,
8453 			  int insn_idx)
8454 {
8455 	u32 regno = BPF_REG_1 + arg;
8456 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8457 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8458 	enum bpf_reg_type type = reg->type;
8459 	u32 *arg_btf_id = NULL;
8460 	int err = 0;
8461 
8462 	if (arg_type == ARG_DONTCARE)
8463 		return 0;
8464 
8465 	err = check_reg_arg(env, regno, SRC_OP);
8466 	if (err)
8467 		return err;
8468 
8469 	if (arg_type == ARG_ANYTHING) {
8470 		if (is_pointer_value(env, regno)) {
8471 			verbose(env, "R%d leaks addr into helper function\n",
8472 				regno);
8473 			return -EACCES;
8474 		}
8475 		return 0;
8476 	}
8477 
8478 	if (type_is_pkt_pointer(type) &&
8479 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8480 		verbose(env, "helper access to the packet is not allowed\n");
8481 		return -EACCES;
8482 	}
8483 
8484 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8485 		err = resolve_map_arg_type(env, meta, &arg_type);
8486 		if (err)
8487 			return err;
8488 	}
8489 
8490 	if (register_is_null(reg) && type_may_be_null(arg_type))
8491 		/* A NULL register has a SCALAR_VALUE type, so skip
8492 		 * type checking.
8493 		 */
8494 		goto skip_type_check;
8495 
8496 	/* arg_btf_id and arg_size are in a union. */
8497 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8498 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8499 		arg_btf_id = fn->arg_btf_id[arg];
8500 
8501 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8502 	if (err)
8503 		return err;
8504 
8505 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8506 	if (err)
8507 		return err;
8508 
8509 skip_type_check:
8510 	if (arg_type_is_release(arg_type)) {
8511 		if (arg_type_is_dynptr(arg_type)) {
8512 			struct bpf_func_state *state = func(env, reg);
8513 			int spi;
8514 
8515 			/* Only dynptr created on stack can be released, thus
8516 			 * the get_spi and stack state checks for spilled_ptr
8517 			 * should only be done before process_dynptr_func for
8518 			 * PTR_TO_STACK.
8519 			 */
8520 			if (reg->type == PTR_TO_STACK) {
8521 				spi = dynptr_get_spi(env, reg);
8522 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8523 					verbose(env, "arg %d is an unacquired reference\n", regno);
8524 					return -EINVAL;
8525 				}
8526 			} else {
8527 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8528 				return -EINVAL;
8529 			}
8530 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8531 			verbose(env, "R%d must be referenced when passed to release function\n",
8532 				regno);
8533 			return -EINVAL;
8534 		}
8535 		if (meta->release_regno) {
8536 			verbose(env, "verifier internal error: more than one release argument\n");
8537 			return -EFAULT;
8538 		}
8539 		meta->release_regno = regno;
8540 	}
8541 
8542 	if (reg->ref_obj_id) {
8543 		if (meta->ref_obj_id) {
8544 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8545 				regno, reg->ref_obj_id,
8546 				meta->ref_obj_id);
8547 			return -EFAULT;
8548 		}
8549 		meta->ref_obj_id = reg->ref_obj_id;
8550 	}
8551 
8552 	switch (base_type(arg_type)) {
8553 	case ARG_CONST_MAP_PTR:
8554 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8555 		if (meta->map_ptr) {
8556 			/* Use map_uid (which is unique id of inner map) to reject:
8557 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8558 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8559 			 * if (inner_map1 && inner_map2) {
8560 			 *     timer = bpf_map_lookup_elem(inner_map1);
8561 			 *     if (timer)
8562 			 *         // mismatch would have been allowed
8563 			 *         bpf_timer_init(timer, inner_map2);
8564 			 * }
8565 			 *
8566 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8567 			 */
8568 			if (meta->map_ptr != reg->map_ptr ||
8569 			    meta->map_uid != reg->map_uid) {
8570 				verbose(env,
8571 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8572 					meta->map_uid, reg->map_uid);
8573 				return -EINVAL;
8574 			}
8575 		}
8576 		meta->map_ptr = reg->map_ptr;
8577 		meta->map_uid = reg->map_uid;
8578 		break;
8579 	case ARG_PTR_TO_MAP_KEY:
8580 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8581 		 * check that [key, key + map->key_size) are within
8582 		 * stack limits and initialized
8583 		 */
8584 		if (!meta->map_ptr) {
8585 			/* in function declaration map_ptr must come before
8586 			 * map_key, so that it's verified and known before
8587 			 * we have to check map_key here. Otherwise it means
8588 			 * that kernel subsystem misconfigured verifier
8589 			 */
8590 			verbose(env, "invalid map_ptr to access map->key\n");
8591 			return -EACCES;
8592 		}
8593 		err = check_helper_mem_access(env, regno,
8594 					      meta->map_ptr->key_size, false,
8595 					      NULL);
8596 		break;
8597 	case ARG_PTR_TO_MAP_VALUE:
8598 		if (type_may_be_null(arg_type) && register_is_null(reg))
8599 			return 0;
8600 
8601 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8602 		 * check [value, value + map->value_size) validity
8603 		 */
8604 		if (!meta->map_ptr) {
8605 			/* kernel subsystem misconfigured verifier */
8606 			verbose(env, "invalid map_ptr to access map->value\n");
8607 			return -EACCES;
8608 		}
8609 		meta->raw_mode = arg_type & MEM_UNINIT;
8610 		err = check_helper_mem_access(env, regno,
8611 					      meta->map_ptr->value_size, false,
8612 					      meta);
8613 		break;
8614 	case ARG_PTR_TO_PERCPU_BTF_ID:
8615 		if (!reg->btf_id) {
8616 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8617 			return -EACCES;
8618 		}
8619 		meta->ret_btf = reg->btf;
8620 		meta->ret_btf_id = reg->btf_id;
8621 		break;
8622 	case ARG_PTR_TO_SPIN_LOCK:
8623 		if (in_rbtree_lock_required_cb(env)) {
8624 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8625 			return -EACCES;
8626 		}
8627 		if (meta->func_id == BPF_FUNC_spin_lock) {
8628 			err = process_spin_lock(env, regno, true);
8629 			if (err)
8630 				return err;
8631 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8632 			err = process_spin_lock(env, regno, false);
8633 			if (err)
8634 				return err;
8635 		} else {
8636 			verbose(env, "verifier internal error\n");
8637 			return -EFAULT;
8638 		}
8639 		break;
8640 	case ARG_PTR_TO_TIMER:
8641 		err = process_timer_func(env, regno, meta);
8642 		if (err)
8643 			return err;
8644 		break;
8645 	case ARG_PTR_TO_FUNC:
8646 		meta->subprogno = reg->subprogno;
8647 		break;
8648 	case ARG_PTR_TO_MEM:
8649 		/* The access to this pointer is only checked when we hit the
8650 		 * next is_mem_size argument below.
8651 		 */
8652 		meta->raw_mode = arg_type & MEM_UNINIT;
8653 		if (arg_type & MEM_FIXED_SIZE) {
8654 			err = check_helper_mem_access(env, regno,
8655 						      fn->arg_size[arg], false,
8656 						      meta);
8657 		}
8658 		break;
8659 	case ARG_CONST_SIZE:
8660 		err = check_mem_size_reg(env, reg, regno, false, meta);
8661 		break;
8662 	case ARG_CONST_SIZE_OR_ZERO:
8663 		err = check_mem_size_reg(env, reg, regno, true, meta);
8664 		break;
8665 	case ARG_PTR_TO_DYNPTR:
8666 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8667 		if (err)
8668 			return err;
8669 		break;
8670 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8671 		if (!tnum_is_const(reg->var_off)) {
8672 			verbose(env, "R%d is not a known constant'\n",
8673 				regno);
8674 			return -EACCES;
8675 		}
8676 		meta->mem_size = reg->var_off.value;
8677 		err = mark_chain_precision(env, regno);
8678 		if (err)
8679 			return err;
8680 		break;
8681 	case ARG_PTR_TO_INT:
8682 	case ARG_PTR_TO_LONG:
8683 	{
8684 		int size = int_ptr_type_to_size(arg_type);
8685 
8686 		err = check_helper_mem_access(env, regno, size, false, meta);
8687 		if (err)
8688 			return err;
8689 		err = check_ptr_alignment(env, reg, 0, size, true);
8690 		break;
8691 	}
8692 	case ARG_PTR_TO_CONST_STR:
8693 	{
8694 		struct bpf_map *map = reg->map_ptr;
8695 		int map_off;
8696 		u64 map_addr;
8697 		char *str_ptr;
8698 
8699 		if (!bpf_map_is_rdonly(map)) {
8700 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8701 			return -EACCES;
8702 		}
8703 
8704 		if (!tnum_is_const(reg->var_off)) {
8705 			verbose(env, "R%d is not a constant address'\n", regno);
8706 			return -EACCES;
8707 		}
8708 
8709 		if (!map->ops->map_direct_value_addr) {
8710 			verbose(env, "no direct value access support for this map type\n");
8711 			return -EACCES;
8712 		}
8713 
8714 		err = check_map_access(env, regno, reg->off,
8715 				       map->value_size - reg->off, false,
8716 				       ACCESS_HELPER);
8717 		if (err)
8718 			return err;
8719 
8720 		map_off = reg->off + reg->var_off.value;
8721 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8722 		if (err) {
8723 			verbose(env, "direct value access on string failed\n");
8724 			return err;
8725 		}
8726 
8727 		str_ptr = (char *)(long)(map_addr);
8728 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8729 			verbose(env, "string is not zero-terminated\n");
8730 			return -EINVAL;
8731 		}
8732 		break;
8733 	}
8734 	case ARG_PTR_TO_KPTR:
8735 		err = process_kptr_func(env, regno, meta);
8736 		if (err)
8737 			return err;
8738 		break;
8739 	}
8740 
8741 	return err;
8742 }
8743 
8744 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8745 {
8746 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8747 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8748 
8749 	if (func_id != BPF_FUNC_map_update_elem &&
8750 	    func_id != BPF_FUNC_map_delete_elem)
8751 		return false;
8752 
8753 	/* It's not possible to get access to a locked struct sock in these
8754 	 * contexts, so updating is safe.
8755 	 */
8756 	switch (type) {
8757 	case BPF_PROG_TYPE_TRACING:
8758 		if (eatype == BPF_TRACE_ITER)
8759 			return true;
8760 		break;
8761 	case BPF_PROG_TYPE_SOCK_OPS:
8762 		/* map_update allowed only via dedicated helpers with event type checks */
8763 		if (func_id == BPF_FUNC_map_delete_elem)
8764 			return true;
8765 		break;
8766 	case BPF_PROG_TYPE_SOCKET_FILTER:
8767 	case BPF_PROG_TYPE_SCHED_CLS:
8768 	case BPF_PROG_TYPE_SCHED_ACT:
8769 	case BPF_PROG_TYPE_XDP:
8770 	case BPF_PROG_TYPE_SK_REUSEPORT:
8771 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8772 	case BPF_PROG_TYPE_SK_LOOKUP:
8773 		return true;
8774 	default:
8775 		break;
8776 	}
8777 
8778 	verbose(env, "cannot update sockmap in this context\n");
8779 	return false;
8780 }
8781 
8782 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8783 {
8784 	return env->prog->jit_requested &&
8785 	       bpf_jit_supports_subprog_tailcalls();
8786 }
8787 
8788 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8789 					struct bpf_map *map, int func_id)
8790 {
8791 	if (!map)
8792 		return 0;
8793 
8794 	/* We need a two way check, first is from map perspective ... */
8795 	switch (map->map_type) {
8796 	case BPF_MAP_TYPE_PROG_ARRAY:
8797 		if (func_id != BPF_FUNC_tail_call)
8798 			goto error;
8799 		break;
8800 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8801 		if (func_id != BPF_FUNC_perf_event_read &&
8802 		    func_id != BPF_FUNC_perf_event_output &&
8803 		    func_id != BPF_FUNC_skb_output &&
8804 		    func_id != BPF_FUNC_perf_event_read_value &&
8805 		    func_id != BPF_FUNC_xdp_output)
8806 			goto error;
8807 		break;
8808 	case BPF_MAP_TYPE_RINGBUF:
8809 		if (func_id != BPF_FUNC_ringbuf_output &&
8810 		    func_id != BPF_FUNC_ringbuf_reserve &&
8811 		    func_id != BPF_FUNC_ringbuf_query &&
8812 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8813 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8814 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8815 			goto error;
8816 		break;
8817 	case BPF_MAP_TYPE_USER_RINGBUF:
8818 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8819 			goto error;
8820 		break;
8821 	case BPF_MAP_TYPE_STACK_TRACE:
8822 		if (func_id != BPF_FUNC_get_stackid)
8823 			goto error;
8824 		break;
8825 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8826 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8827 		    func_id != BPF_FUNC_current_task_under_cgroup)
8828 			goto error;
8829 		break;
8830 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8831 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8832 		if (func_id != BPF_FUNC_get_local_storage)
8833 			goto error;
8834 		break;
8835 	case BPF_MAP_TYPE_DEVMAP:
8836 	case BPF_MAP_TYPE_DEVMAP_HASH:
8837 		if (func_id != BPF_FUNC_redirect_map &&
8838 		    func_id != BPF_FUNC_map_lookup_elem)
8839 			goto error;
8840 		break;
8841 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8842 	 * appear.
8843 	 */
8844 	case BPF_MAP_TYPE_CPUMAP:
8845 		if (func_id != BPF_FUNC_redirect_map)
8846 			goto error;
8847 		break;
8848 	case BPF_MAP_TYPE_XSKMAP:
8849 		if (func_id != BPF_FUNC_redirect_map &&
8850 		    func_id != BPF_FUNC_map_lookup_elem)
8851 			goto error;
8852 		break;
8853 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8854 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8855 		if (func_id != BPF_FUNC_map_lookup_elem)
8856 			goto error;
8857 		break;
8858 	case BPF_MAP_TYPE_SOCKMAP:
8859 		if (func_id != BPF_FUNC_sk_redirect_map &&
8860 		    func_id != BPF_FUNC_sock_map_update &&
8861 		    func_id != BPF_FUNC_msg_redirect_map &&
8862 		    func_id != BPF_FUNC_sk_select_reuseport &&
8863 		    func_id != BPF_FUNC_map_lookup_elem &&
8864 		    !may_update_sockmap(env, func_id))
8865 			goto error;
8866 		break;
8867 	case BPF_MAP_TYPE_SOCKHASH:
8868 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8869 		    func_id != BPF_FUNC_sock_hash_update &&
8870 		    func_id != BPF_FUNC_msg_redirect_hash &&
8871 		    func_id != BPF_FUNC_sk_select_reuseport &&
8872 		    func_id != BPF_FUNC_map_lookup_elem &&
8873 		    !may_update_sockmap(env, func_id))
8874 			goto error;
8875 		break;
8876 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8877 		if (func_id != BPF_FUNC_sk_select_reuseport)
8878 			goto error;
8879 		break;
8880 	case BPF_MAP_TYPE_QUEUE:
8881 	case BPF_MAP_TYPE_STACK:
8882 		if (func_id != BPF_FUNC_map_peek_elem &&
8883 		    func_id != BPF_FUNC_map_pop_elem &&
8884 		    func_id != BPF_FUNC_map_push_elem)
8885 			goto error;
8886 		break;
8887 	case BPF_MAP_TYPE_SK_STORAGE:
8888 		if (func_id != BPF_FUNC_sk_storage_get &&
8889 		    func_id != BPF_FUNC_sk_storage_delete &&
8890 		    func_id != BPF_FUNC_kptr_xchg)
8891 			goto error;
8892 		break;
8893 	case BPF_MAP_TYPE_INODE_STORAGE:
8894 		if (func_id != BPF_FUNC_inode_storage_get &&
8895 		    func_id != BPF_FUNC_inode_storage_delete &&
8896 		    func_id != BPF_FUNC_kptr_xchg)
8897 			goto error;
8898 		break;
8899 	case BPF_MAP_TYPE_TASK_STORAGE:
8900 		if (func_id != BPF_FUNC_task_storage_get &&
8901 		    func_id != BPF_FUNC_task_storage_delete &&
8902 		    func_id != BPF_FUNC_kptr_xchg)
8903 			goto error;
8904 		break;
8905 	case BPF_MAP_TYPE_CGRP_STORAGE:
8906 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8907 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8908 		    func_id != BPF_FUNC_kptr_xchg)
8909 			goto error;
8910 		break;
8911 	case BPF_MAP_TYPE_BLOOM_FILTER:
8912 		if (func_id != BPF_FUNC_map_peek_elem &&
8913 		    func_id != BPF_FUNC_map_push_elem)
8914 			goto error;
8915 		break;
8916 	default:
8917 		break;
8918 	}
8919 
8920 	/* ... and second from the function itself. */
8921 	switch (func_id) {
8922 	case BPF_FUNC_tail_call:
8923 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8924 			goto error;
8925 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8926 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8927 			return -EINVAL;
8928 		}
8929 		break;
8930 	case BPF_FUNC_perf_event_read:
8931 	case BPF_FUNC_perf_event_output:
8932 	case BPF_FUNC_perf_event_read_value:
8933 	case BPF_FUNC_skb_output:
8934 	case BPF_FUNC_xdp_output:
8935 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8936 			goto error;
8937 		break;
8938 	case BPF_FUNC_ringbuf_output:
8939 	case BPF_FUNC_ringbuf_reserve:
8940 	case BPF_FUNC_ringbuf_query:
8941 	case BPF_FUNC_ringbuf_reserve_dynptr:
8942 	case BPF_FUNC_ringbuf_submit_dynptr:
8943 	case BPF_FUNC_ringbuf_discard_dynptr:
8944 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8945 			goto error;
8946 		break;
8947 	case BPF_FUNC_user_ringbuf_drain:
8948 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8949 			goto error;
8950 		break;
8951 	case BPF_FUNC_get_stackid:
8952 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8953 			goto error;
8954 		break;
8955 	case BPF_FUNC_current_task_under_cgroup:
8956 	case BPF_FUNC_skb_under_cgroup:
8957 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8958 			goto error;
8959 		break;
8960 	case BPF_FUNC_redirect_map:
8961 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8962 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8963 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8964 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8965 			goto error;
8966 		break;
8967 	case BPF_FUNC_sk_redirect_map:
8968 	case BPF_FUNC_msg_redirect_map:
8969 	case BPF_FUNC_sock_map_update:
8970 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8971 			goto error;
8972 		break;
8973 	case BPF_FUNC_sk_redirect_hash:
8974 	case BPF_FUNC_msg_redirect_hash:
8975 	case BPF_FUNC_sock_hash_update:
8976 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8977 			goto error;
8978 		break;
8979 	case BPF_FUNC_get_local_storage:
8980 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8981 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8982 			goto error;
8983 		break;
8984 	case BPF_FUNC_sk_select_reuseport:
8985 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8986 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8987 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8988 			goto error;
8989 		break;
8990 	case BPF_FUNC_map_pop_elem:
8991 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8992 		    map->map_type != BPF_MAP_TYPE_STACK)
8993 			goto error;
8994 		break;
8995 	case BPF_FUNC_map_peek_elem:
8996 	case BPF_FUNC_map_push_elem:
8997 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8998 		    map->map_type != BPF_MAP_TYPE_STACK &&
8999 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9000 			goto error;
9001 		break;
9002 	case BPF_FUNC_map_lookup_percpu_elem:
9003 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9004 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9005 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9006 			goto error;
9007 		break;
9008 	case BPF_FUNC_sk_storage_get:
9009 	case BPF_FUNC_sk_storage_delete:
9010 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9011 			goto error;
9012 		break;
9013 	case BPF_FUNC_inode_storage_get:
9014 	case BPF_FUNC_inode_storage_delete:
9015 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9016 			goto error;
9017 		break;
9018 	case BPF_FUNC_task_storage_get:
9019 	case BPF_FUNC_task_storage_delete:
9020 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9021 			goto error;
9022 		break;
9023 	case BPF_FUNC_cgrp_storage_get:
9024 	case BPF_FUNC_cgrp_storage_delete:
9025 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9026 			goto error;
9027 		break;
9028 	default:
9029 		break;
9030 	}
9031 
9032 	return 0;
9033 error:
9034 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9035 		map->map_type, func_id_name(func_id), func_id);
9036 	return -EINVAL;
9037 }
9038 
9039 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9040 {
9041 	int count = 0;
9042 
9043 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9044 		count++;
9045 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9046 		count++;
9047 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9048 		count++;
9049 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9050 		count++;
9051 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9052 		count++;
9053 
9054 	/* We only support one arg being in raw mode at the moment,
9055 	 * which is sufficient for the helper functions we have
9056 	 * right now.
9057 	 */
9058 	return count <= 1;
9059 }
9060 
9061 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9062 {
9063 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9064 	bool has_size = fn->arg_size[arg] != 0;
9065 	bool is_next_size = false;
9066 
9067 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9068 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9069 
9070 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9071 		return is_next_size;
9072 
9073 	return has_size == is_next_size || is_next_size == is_fixed;
9074 }
9075 
9076 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9077 {
9078 	/* bpf_xxx(..., buf, len) call will access 'len'
9079 	 * bytes from memory 'buf'. Both arg types need
9080 	 * to be paired, so make sure there's no buggy
9081 	 * helper function specification.
9082 	 */
9083 	if (arg_type_is_mem_size(fn->arg1_type) ||
9084 	    check_args_pair_invalid(fn, 0) ||
9085 	    check_args_pair_invalid(fn, 1) ||
9086 	    check_args_pair_invalid(fn, 2) ||
9087 	    check_args_pair_invalid(fn, 3) ||
9088 	    check_args_pair_invalid(fn, 4))
9089 		return false;
9090 
9091 	return true;
9092 }
9093 
9094 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9095 {
9096 	int i;
9097 
9098 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9099 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9100 			return !!fn->arg_btf_id[i];
9101 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9102 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9103 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9104 		    /* arg_btf_id and arg_size are in a union. */
9105 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9106 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9107 			return false;
9108 	}
9109 
9110 	return true;
9111 }
9112 
9113 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9114 {
9115 	return check_raw_mode_ok(fn) &&
9116 	       check_arg_pair_ok(fn) &&
9117 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9118 }
9119 
9120 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9121  * are now invalid, so turn them into unknown SCALAR_VALUE.
9122  *
9123  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9124  * since these slices point to packet data.
9125  */
9126 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9127 {
9128 	struct bpf_func_state *state;
9129 	struct bpf_reg_state *reg;
9130 
9131 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9132 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9133 			mark_reg_invalid(env, reg);
9134 	}));
9135 }
9136 
9137 enum {
9138 	AT_PKT_END = -1,
9139 	BEYOND_PKT_END = -2,
9140 };
9141 
9142 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9143 {
9144 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9145 	struct bpf_reg_state *reg = &state->regs[regn];
9146 
9147 	if (reg->type != PTR_TO_PACKET)
9148 		/* PTR_TO_PACKET_META is not supported yet */
9149 		return;
9150 
9151 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9152 	 * How far beyond pkt_end it goes is unknown.
9153 	 * if (!range_open) it's the case of pkt >= pkt_end
9154 	 * if (range_open) it's the case of pkt > pkt_end
9155 	 * hence this pointer is at least 1 byte bigger than pkt_end
9156 	 */
9157 	if (range_open)
9158 		reg->range = BEYOND_PKT_END;
9159 	else
9160 		reg->range = AT_PKT_END;
9161 }
9162 
9163 /* The pointer with the specified id has released its reference to kernel
9164  * resources. Identify all copies of the same pointer and clear the reference.
9165  */
9166 static int release_reference(struct bpf_verifier_env *env,
9167 			     int ref_obj_id)
9168 {
9169 	struct bpf_func_state *state;
9170 	struct bpf_reg_state *reg;
9171 	int err;
9172 
9173 	err = release_reference_state(cur_func(env), ref_obj_id);
9174 	if (err)
9175 		return err;
9176 
9177 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9178 		if (reg->ref_obj_id == ref_obj_id)
9179 			mark_reg_invalid(env, reg);
9180 	}));
9181 
9182 	return 0;
9183 }
9184 
9185 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9186 {
9187 	struct bpf_func_state *unused;
9188 	struct bpf_reg_state *reg;
9189 
9190 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9191 		if (type_is_non_owning_ref(reg->type))
9192 			mark_reg_invalid(env, reg);
9193 	}));
9194 }
9195 
9196 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9197 				    struct bpf_reg_state *regs)
9198 {
9199 	int i;
9200 
9201 	/* after the call registers r0 - r5 were scratched */
9202 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9203 		mark_reg_not_init(env, regs, caller_saved[i]);
9204 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9205 	}
9206 }
9207 
9208 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9209 				   struct bpf_func_state *caller,
9210 				   struct bpf_func_state *callee,
9211 				   int insn_idx);
9212 
9213 static int set_callee_state(struct bpf_verifier_env *env,
9214 			    struct bpf_func_state *caller,
9215 			    struct bpf_func_state *callee, int insn_idx);
9216 
9217 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9218 			    set_callee_state_fn set_callee_state_cb,
9219 			    struct bpf_verifier_state *state)
9220 {
9221 	struct bpf_func_state *caller, *callee;
9222 	int err;
9223 
9224 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9225 		verbose(env, "the call stack of %d frames is too deep\n",
9226 			state->curframe + 2);
9227 		return -E2BIG;
9228 	}
9229 
9230 	if (state->frame[state->curframe + 1]) {
9231 		verbose(env, "verifier bug. Frame %d already allocated\n",
9232 			state->curframe + 1);
9233 		return -EFAULT;
9234 	}
9235 
9236 	caller = state->frame[state->curframe];
9237 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9238 	if (!callee)
9239 		return -ENOMEM;
9240 	state->frame[state->curframe + 1] = callee;
9241 
9242 	/* callee cannot access r0, r6 - r9 for reading and has to write
9243 	 * into its own stack before reading from it.
9244 	 * callee can read/write into caller's stack
9245 	 */
9246 	init_func_state(env, callee,
9247 			/* remember the callsite, it will be used by bpf_exit */
9248 			callsite,
9249 			state->curframe + 1 /* frameno within this callchain */,
9250 			subprog /* subprog number within this prog */);
9251 	/* Transfer references to the callee */
9252 	err = copy_reference_state(callee, caller);
9253 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9254 	if (err)
9255 		goto err_out;
9256 
9257 	/* only increment it after check_reg_arg() finished */
9258 	state->curframe++;
9259 
9260 	return 0;
9261 
9262 err_out:
9263 	free_func_state(callee);
9264 	state->frame[state->curframe + 1] = NULL;
9265 	return err;
9266 }
9267 
9268 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9269 			      int insn_idx, int subprog,
9270 			      set_callee_state_fn set_callee_state_cb)
9271 {
9272 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9273 	struct bpf_func_state *caller, *callee;
9274 	int err;
9275 
9276 	caller = state->frame[state->curframe];
9277 	err = btf_check_subprog_call(env, subprog, caller->regs);
9278 	if (err == -EFAULT)
9279 		return err;
9280 
9281 	/* set_callee_state is used for direct subprog calls, but we are
9282 	 * interested in validating only BPF helpers that can call subprogs as
9283 	 * callbacks
9284 	 */
9285 	if (bpf_pseudo_kfunc_call(insn) &&
9286 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9287 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9288 			func_id_name(insn->imm), insn->imm);
9289 		return -EFAULT;
9290 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9291 		   !is_callback_calling_function(insn->imm)) { /* helper */
9292 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9293 			func_id_name(insn->imm), insn->imm);
9294 		return -EFAULT;
9295 	}
9296 
9297 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9298 	    insn->src_reg == 0 &&
9299 	    insn->imm == BPF_FUNC_timer_set_callback) {
9300 		struct bpf_verifier_state *async_cb;
9301 
9302 		/* there is no real recursion here. timer callbacks are async */
9303 		env->subprog_info[subprog].is_async_cb = true;
9304 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9305 					 insn_idx, subprog);
9306 		if (!async_cb)
9307 			return -EFAULT;
9308 		callee = async_cb->frame[0];
9309 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9310 
9311 		/* Convert bpf_timer_set_callback() args into timer callback args */
9312 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9313 		if (err)
9314 			return err;
9315 
9316 		return 0;
9317 	}
9318 
9319 	/* for callback functions enqueue entry to callback and
9320 	 * proceed with next instruction within current frame.
9321 	 */
9322 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9323 	if (!callback_state)
9324 		return -ENOMEM;
9325 
9326 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9327 			       callback_state);
9328 	if (err)
9329 		return err;
9330 
9331 	callback_state->callback_unroll_depth++;
9332 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9333 	caller->callback_depth = 0;
9334 	return 0;
9335 }
9336 
9337 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9338 			   int *insn_idx)
9339 {
9340 	struct bpf_verifier_state *state = env->cur_state;
9341 	struct bpf_func_state *caller;
9342 	int err, subprog, target_insn;
9343 
9344 	target_insn = *insn_idx + insn->imm + 1;
9345 	subprog = find_subprog(env, target_insn);
9346 	if (subprog < 0) {
9347 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9348 		return -EFAULT;
9349 	}
9350 
9351 	caller = state->frame[state->curframe];
9352 	err = btf_check_subprog_call(env, subprog, caller->regs);
9353 	if (err == -EFAULT)
9354 		return err;
9355 	if (subprog_is_global(env, subprog)) {
9356 		if (err) {
9357 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9358 			return err;
9359 		}
9360 
9361 		if (env->log.level & BPF_LOG_LEVEL)
9362 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9363 		clear_caller_saved_regs(env, caller->regs);
9364 
9365 		/* All global functions return a 64-bit SCALAR_VALUE */
9366 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9367 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9368 
9369 		/* continue with next insn after call */
9370 		return 0;
9371 	}
9372 
9373 	/* for regular function entry setup new frame and continue
9374 	 * from that frame.
9375 	 */
9376 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9377 	if (err)
9378 		return err;
9379 
9380 	clear_caller_saved_regs(env, caller->regs);
9381 
9382 	/* and go analyze first insn of the callee */
9383 	*insn_idx = env->subprog_info[subprog].start - 1;
9384 
9385 	if (env->log.level & BPF_LOG_LEVEL) {
9386 		verbose(env, "caller:\n");
9387 		print_verifier_state(env, caller, true);
9388 		verbose(env, "callee:\n");
9389 		print_verifier_state(env, state->frame[state->curframe], true);
9390 	}
9391 
9392 	return 0;
9393 }
9394 
9395 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9396 				   struct bpf_func_state *caller,
9397 				   struct bpf_func_state *callee)
9398 {
9399 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9400 	 *      void *callback_ctx, u64 flags);
9401 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9402 	 *      void *callback_ctx);
9403 	 */
9404 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9405 
9406 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9407 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9408 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9409 
9410 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9411 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9412 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9413 
9414 	/* pointer to stack or null */
9415 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9416 
9417 	/* unused */
9418 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9419 	return 0;
9420 }
9421 
9422 static int set_callee_state(struct bpf_verifier_env *env,
9423 			    struct bpf_func_state *caller,
9424 			    struct bpf_func_state *callee, int insn_idx)
9425 {
9426 	int i;
9427 
9428 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9429 	 * pointers, which connects us up to the liveness chain
9430 	 */
9431 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9432 		callee->regs[i] = caller->regs[i];
9433 	return 0;
9434 }
9435 
9436 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9437 				       struct bpf_func_state *caller,
9438 				       struct bpf_func_state *callee,
9439 				       int insn_idx)
9440 {
9441 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9442 	struct bpf_map *map;
9443 	int err;
9444 
9445 	if (bpf_map_ptr_poisoned(insn_aux)) {
9446 		verbose(env, "tail_call abusing map_ptr\n");
9447 		return -EINVAL;
9448 	}
9449 
9450 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9451 	if (!map->ops->map_set_for_each_callback_args ||
9452 	    !map->ops->map_for_each_callback) {
9453 		verbose(env, "callback function not allowed for map\n");
9454 		return -ENOTSUPP;
9455 	}
9456 
9457 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9458 	if (err)
9459 		return err;
9460 
9461 	callee->in_callback_fn = true;
9462 	callee->callback_ret_range = tnum_range(0, 1);
9463 	return 0;
9464 }
9465 
9466 static int set_loop_callback_state(struct bpf_verifier_env *env,
9467 				   struct bpf_func_state *caller,
9468 				   struct bpf_func_state *callee,
9469 				   int insn_idx)
9470 {
9471 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9472 	 *	    u64 flags);
9473 	 * callback_fn(u32 index, void *callback_ctx);
9474 	 */
9475 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9476 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9477 
9478 	/* unused */
9479 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9480 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9481 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9482 
9483 	callee->in_callback_fn = true;
9484 	callee->callback_ret_range = tnum_range(0, 1);
9485 	return 0;
9486 }
9487 
9488 static int set_timer_callback_state(struct bpf_verifier_env *env,
9489 				    struct bpf_func_state *caller,
9490 				    struct bpf_func_state *callee,
9491 				    int insn_idx)
9492 {
9493 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9494 
9495 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9496 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9497 	 */
9498 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9499 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9500 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9501 
9502 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9503 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9504 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9505 
9506 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9507 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9508 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9509 
9510 	/* unused */
9511 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9512 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9513 	callee->in_async_callback_fn = true;
9514 	callee->callback_ret_range = tnum_range(0, 1);
9515 	return 0;
9516 }
9517 
9518 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9519 				       struct bpf_func_state *caller,
9520 				       struct bpf_func_state *callee,
9521 				       int insn_idx)
9522 {
9523 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9524 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9525 	 * (callback_fn)(struct task_struct *task,
9526 	 *               struct vm_area_struct *vma, void *callback_ctx);
9527 	 */
9528 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9529 
9530 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9531 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9532 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9533 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9534 
9535 	/* pointer to stack or null */
9536 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9537 
9538 	/* unused */
9539 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9540 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9541 	callee->in_callback_fn = true;
9542 	callee->callback_ret_range = tnum_range(0, 1);
9543 	return 0;
9544 }
9545 
9546 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9547 					   struct bpf_func_state *caller,
9548 					   struct bpf_func_state *callee,
9549 					   int insn_idx)
9550 {
9551 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9552 	 *			  callback_ctx, u64 flags);
9553 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9554 	 */
9555 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9556 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9557 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9558 
9559 	/* unused */
9560 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9561 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9562 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9563 
9564 	callee->in_callback_fn = true;
9565 	callee->callback_ret_range = tnum_range(0, 1);
9566 	return 0;
9567 }
9568 
9569 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9570 					 struct bpf_func_state *caller,
9571 					 struct bpf_func_state *callee,
9572 					 int insn_idx)
9573 {
9574 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9575 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9576 	 *
9577 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9578 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9579 	 * by this point, so look at 'root'
9580 	 */
9581 	struct btf_field *field;
9582 
9583 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9584 				      BPF_RB_ROOT);
9585 	if (!field || !field->graph_root.value_btf_id)
9586 		return -EFAULT;
9587 
9588 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9589 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9590 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9591 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9592 
9593 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9594 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9595 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9596 	callee->in_callback_fn = true;
9597 	callee->callback_ret_range = tnum_range(0, 1);
9598 	return 0;
9599 }
9600 
9601 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9602 
9603 /* Are we currently verifying the callback for a rbtree helper that must
9604  * be called with lock held? If so, no need to complain about unreleased
9605  * lock
9606  */
9607 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9608 {
9609 	struct bpf_verifier_state *state = env->cur_state;
9610 	struct bpf_insn *insn = env->prog->insnsi;
9611 	struct bpf_func_state *callee;
9612 	int kfunc_btf_id;
9613 
9614 	if (!state->curframe)
9615 		return false;
9616 
9617 	callee = state->frame[state->curframe];
9618 
9619 	if (!callee->in_callback_fn)
9620 		return false;
9621 
9622 	kfunc_btf_id = insn[callee->callsite].imm;
9623 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9624 }
9625 
9626 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9627 {
9628 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9629 	struct bpf_func_state *caller, *callee;
9630 	struct bpf_reg_state *r0;
9631 	bool in_callback_fn;
9632 	int err;
9633 
9634 	callee = state->frame[state->curframe];
9635 	r0 = &callee->regs[BPF_REG_0];
9636 	if (r0->type == PTR_TO_STACK) {
9637 		/* technically it's ok to return caller's stack pointer
9638 		 * (or caller's caller's pointer) back to the caller,
9639 		 * since these pointers are valid. Only current stack
9640 		 * pointer will be invalid as soon as function exits,
9641 		 * but let's be conservative
9642 		 */
9643 		verbose(env, "cannot return stack pointer to the caller\n");
9644 		return -EINVAL;
9645 	}
9646 
9647 	caller = state->frame[state->curframe - 1];
9648 	if (callee->in_callback_fn) {
9649 		/* enforce R0 return value range [0, 1]. */
9650 		struct tnum range = callee->callback_ret_range;
9651 
9652 		if (r0->type != SCALAR_VALUE) {
9653 			verbose(env, "R0 not a scalar value\n");
9654 			return -EACCES;
9655 		}
9656 
9657 		/* we are going to rely on register's precise value */
9658 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9659 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9660 		if (err)
9661 			return err;
9662 
9663 		if (!tnum_in(range, r0->var_off)) {
9664 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9665 			return -EINVAL;
9666 		}
9667 		if (!calls_callback(env, callee->callsite)) {
9668 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9669 				*insn_idx, callee->callsite);
9670 			return -EFAULT;
9671 		}
9672 	} else {
9673 		/* return to the caller whatever r0 had in the callee */
9674 		caller->regs[BPF_REG_0] = *r0;
9675 	}
9676 
9677 	/* callback_fn frame should have released its own additions to parent's
9678 	 * reference state at this point, or check_reference_leak would
9679 	 * complain, hence it must be the same as the caller. There is no need
9680 	 * to copy it back.
9681 	 */
9682 	if (!callee->in_callback_fn) {
9683 		/* Transfer references to the caller */
9684 		err = copy_reference_state(caller, callee);
9685 		if (err)
9686 			return err;
9687 	}
9688 
9689 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9690 	 * there function call logic would reschedule callback visit. If iteration
9691 	 * converges is_state_visited() would prune that visit eventually.
9692 	 */
9693 	in_callback_fn = callee->in_callback_fn;
9694 	if (in_callback_fn)
9695 		*insn_idx = callee->callsite;
9696 	else
9697 		*insn_idx = callee->callsite + 1;
9698 
9699 	if (env->log.level & BPF_LOG_LEVEL) {
9700 		verbose(env, "returning from callee:\n");
9701 		print_verifier_state(env, callee, true);
9702 		verbose(env, "to caller at %d:\n", *insn_idx);
9703 		print_verifier_state(env, caller, true);
9704 	}
9705 	/* clear everything in the callee */
9706 	free_func_state(callee);
9707 	state->frame[state->curframe--] = NULL;
9708 
9709 	/* for callbacks widen imprecise scalars to make programs like below verify:
9710 	 *
9711 	 *   struct ctx { int i; }
9712 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9713 	 *   ...
9714 	 *   struct ctx = { .i = 0; }
9715 	 *   bpf_loop(100, cb, &ctx, 0);
9716 	 *
9717 	 * This is similar to what is done in process_iter_next_call() for open
9718 	 * coded iterators.
9719 	 */
9720 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9721 	if (prev_st) {
9722 		err = widen_imprecise_scalars(env, prev_st, state);
9723 		if (err)
9724 			return err;
9725 	}
9726 	return 0;
9727 }
9728 
9729 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9730 				   int func_id,
9731 				   struct bpf_call_arg_meta *meta)
9732 {
9733 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9734 
9735 	if (ret_type != RET_INTEGER)
9736 		return;
9737 
9738 	switch (func_id) {
9739 	case BPF_FUNC_get_stack:
9740 	case BPF_FUNC_get_task_stack:
9741 	case BPF_FUNC_probe_read_str:
9742 	case BPF_FUNC_probe_read_kernel_str:
9743 	case BPF_FUNC_probe_read_user_str:
9744 		ret_reg->smax_value = meta->msize_max_value;
9745 		ret_reg->s32_max_value = meta->msize_max_value;
9746 		ret_reg->smin_value = -MAX_ERRNO;
9747 		ret_reg->s32_min_value = -MAX_ERRNO;
9748 		reg_bounds_sync(ret_reg);
9749 		break;
9750 	case BPF_FUNC_get_smp_processor_id:
9751 		ret_reg->umax_value = nr_cpu_ids - 1;
9752 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9753 		ret_reg->smax_value = nr_cpu_ids - 1;
9754 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9755 		ret_reg->umin_value = 0;
9756 		ret_reg->u32_min_value = 0;
9757 		ret_reg->smin_value = 0;
9758 		ret_reg->s32_min_value = 0;
9759 		reg_bounds_sync(ret_reg);
9760 		break;
9761 	}
9762 }
9763 
9764 static int
9765 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9766 		int func_id, int insn_idx)
9767 {
9768 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9769 	struct bpf_map *map = meta->map_ptr;
9770 
9771 	if (func_id != BPF_FUNC_tail_call &&
9772 	    func_id != BPF_FUNC_map_lookup_elem &&
9773 	    func_id != BPF_FUNC_map_update_elem &&
9774 	    func_id != BPF_FUNC_map_delete_elem &&
9775 	    func_id != BPF_FUNC_map_push_elem &&
9776 	    func_id != BPF_FUNC_map_pop_elem &&
9777 	    func_id != BPF_FUNC_map_peek_elem &&
9778 	    func_id != BPF_FUNC_for_each_map_elem &&
9779 	    func_id != BPF_FUNC_redirect_map &&
9780 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9781 		return 0;
9782 
9783 	if (map == NULL) {
9784 		verbose(env, "kernel subsystem misconfigured verifier\n");
9785 		return -EINVAL;
9786 	}
9787 
9788 	/* In case of read-only, some additional restrictions
9789 	 * need to be applied in order to prevent altering the
9790 	 * state of the map from program side.
9791 	 */
9792 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9793 	    (func_id == BPF_FUNC_map_delete_elem ||
9794 	     func_id == BPF_FUNC_map_update_elem ||
9795 	     func_id == BPF_FUNC_map_push_elem ||
9796 	     func_id == BPF_FUNC_map_pop_elem)) {
9797 		verbose(env, "write into map forbidden\n");
9798 		return -EACCES;
9799 	}
9800 
9801 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9802 		bpf_map_ptr_store(aux, meta->map_ptr,
9803 				  !meta->map_ptr->bypass_spec_v1);
9804 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9805 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9806 				  !meta->map_ptr->bypass_spec_v1);
9807 	return 0;
9808 }
9809 
9810 static int
9811 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9812 		int func_id, int insn_idx)
9813 {
9814 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9815 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9816 	struct bpf_map *map = meta->map_ptr;
9817 	u64 val, max;
9818 	int err;
9819 
9820 	if (func_id != BPF_FUNC_tail_call)
9821 		return 0;
9822 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9823 		verbose(env, "kernel subsystem misconfigured verifier\n");
9824 		return -EINVAL;
9825 	}
9826 
9827 	reg = &regs[BPF_REG_3];
9828 	val = reg->var_off.value;
9829 	max = map->max_entries;
9830 
9831 	if (!(register_is_const(reg) && val < max)) {
9832 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9833 		return 0;
9834 	}
9835 
9836 	err = mark_chain_precision(env, BPF_REG_3);
9837 	if (err)
9838 		return err;
9839 	if (bpf_map_key_unseen(aux))
9840 		bpf_map_key_store(aux, val);
9841 	else if (!bpf_map_key_poisoned(aux) &&
9842 		  bpf_map_key_immediate(aux) != val)
9843 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9844 	return 0;
9845 }
9846 
9847 static int check_reference_leak(struct bpf_verifier_env *env)
9848 {
9849 	struct bpf_func_state *state = cur_func(env);
9850 	bool refs_lingering = false;
9851 	int i;
9852 
9853 	if (state->frameno && !state->in_callback_fn)
9854 		return 0;
9855 
9856 	for (i = 0; i < state->acquired_refs; i++) {
9857 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9858 			continue;
9859 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9860 			state->refs[i].id, state->refs[i].insn_idx);
9861 		refs_lingering = true;
9862 	}
9863 	return refs_lingering ? -EINVAL : 0;
9864 }
9865 
9866 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9867 				   struct bpf_reg_state *regs)
9868 {
9869 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9870 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9871 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9872 	struct bpf_bprintf_data data = {};
9873 	int err, fmt_map_off, num_args;
9874 	u64 fmt_addr;
9875 	char *fmt;
9876 
9877 	/* data must be an array of u64 */
9878 	if (data_len_reg->var_off.value % 8)
9879 		return -EINVAL;
9880 	num_args = data_len_reg->var_off.value / 8;
9881 
9882 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9883 	 * and map_direct_value_addr is set.
9884 	 */
9885 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9886 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9887 						  fmt_map_off);
9888 	if (err) {
9889 		verbose(env, "verifier bug\n");
9890 		return -EFAULT;
9891 	}
9892 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9893 
9894 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9895 	 * can focus on validating the format specifiers.
9896 	 */
9897 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9898 	if (err < 0)
9899 		verbose(env, "Invalid format string\n");
9900 
9901 	return err;
9902 }
9903 
9904 static int check_get_func_ip(struct bpf_verifier_env *env)
9905 {
9906 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9907 	int func_id = BPF_FUNC_get_func_ip;
9908 
9909 	if (type == BPF_PROG_TYPE_TRACING) {
9910 		if (!bpf_prog_has_trampoline(env->prog)) {
9911 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9912 				func_id_name(func_id), func_id);
9913 			return -ENOTSUPP;
9914 		}
9915 		return 0;
9916 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9917 		return 0;
9918 	}
9919 
9920 	verbose(env, "func %s#%d not supported for program type %d\n",
9921 		func_id_name(func_id), func_id, type);
9922 	return -ENOTSUPP;
9923 }
9924 
9925 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9926 {
9927 	return &env->insn_aux_data[env->insn_idx];
9928 }
9929 
9930 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9931 {
9932 	struct bpf_reg_state *regs = cur_regs(env);
9933 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9934 	bool reg_is_null = register_is_null(reg);
9935 
9936 	if (reg_is_null)
9937 		mark_chain_precision(env, BPF_REG_4);
9938 
9939 	return reg_is_null;
9940 }
9941 
9942 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9943 {
9944 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9945 
9946 	if (!state->initialized) {
9947 		state->initialized = 1;
9948 		state->fit_for_inline = loop_flag_is_zero(env);
9949 		state->callback_subprogno = subprogno;
9950 		return;
9951 	}
9952 
9953 	if (!state->fit_for_inline)
9954 		return;
9955 
9956 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9957 				 state->callback_subprogno == subprogno);
9958 }
9959 
9960 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9961 			     int *insn_idx_p)
9962 {
9963 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9964 	const struct bpf_func_proto *fn = NULL;
9965 	enum bpf_return_type ret_type;
9966 	enum bpf_type_flag ret_flag;
9967 	struct bpf_reg_state *regs;
9968 	struct bpf_call_arg_meta meta;
9969 	int insn_idx = *insn_idx_p;
9970 	bool changes_data;
9971 	int i, err, func_id;
9972 
9973 	/* find function prototype */
9974 	func_id = insn->imm;
9975 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9976 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9977 			func_id);
9978 		return -EINVAL;
9979 	}
9980 
9981 	if (env->ops->get_func_proto)
9982 		fn = env->ops->get_func_proto(func_id, env->prog);
9983 	if (!fn) {
9984 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9985 			func_id);
9986 		return -EINVAL;
9987 	}
9988 
9989 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9990 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9991 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9992 		return -EINVAL;
9993 	}
9994 
9995 	if (fn->allowed && !fn->allowed(env->prog)) {
9996 		verbose(env, "helper call is not allowed in probe\n");
9997 		return -EINVAL;
9998 	}
9999 
10000 	if (!env->prog->aux->sleepable && fn->might_sleep) {
10001 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10002 		return -EINVAL;
10003 	}
10004 
10005 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10006 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10007 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10008 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10009 			func_id_name(func_id), func_id);
10010 		return -EINVAL;
10011 	}
10012 
10013 	memset(&meta, 0, sizeof(meta));
10014 	meta.pkt_access = fn->pkt_access;
10015 
10016 	err = check_func_proto(fn, func_id);
10017 	if (err) {
10018 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10019 			func_id_name(func_id), func_id);
10020 		return err;
10021 	}
10022 
10023 	if (env->cur_state->active_rcu_lock) {
10024 		if (fn->might_sleep) {
10025 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10026 				func_id_name(func_id), func_id);
10027 			return -EINVAL;
10028 		}
10029 
10030 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10031 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10032 	}
10033 
10034 	meta.func_id = func_id;
10035 	/* check args */
10036 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10037 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10038 		if (err)
10039 			return err;
10040 	}
10041 
10042 	err = record_func_map(env, &meta, func_id, insn_idx);
10043 	if (err)
10044 		return err;
10045 
10046 	err = record_func_key(env, &meta, func_id, insn_idx);
10047 	if (err)
10048 		return err;
10049 
10050 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10051 	 * is inferred from register state.
10052 	 */
10053 	for (i = 0; i < meta.access_size; i++) {
10054 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10055 				       BPF_WRITE, -1, false, false);
10056 		if (err)
10057 			return err;
10058 	}
10059 
10060 	regs = cur_regs(env);
10061 
10062 	if (meta.release_regno) {
10063 		err = -EINVAL;
10064 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10065 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10066 		 * is safe to do directly.
10067 		 */
10068 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10069 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10070 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10071 				return -EFAULT;
10072 			}
10073 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10074 		} else if (meta.ref_obj_id) {
10075 			err = release_reference(env, meta.ref_obj_id);
10076 		} else if (register_is_null(&regs[meta.release_regno])) {
10077 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10078 			 * released is NULL, which must be > R0.
10079 			 */
10080 			err = 0;
10081 		}
10082 		if (err) {
10083 			verbose(env, "func %s#%d reference has not been acquired before\n",
10084 				func_id_name(func_id), func_id);
10085 			return err;
10086 		}
10087 	}
10088 
10089 	switch (func_id) {
10090 	case BPF_FUNC_tail_call:
10091 		err = check_reference_leak(env);
10092 		if (err) {
10093 			verbose(env, "tail_call would lead to reference leak\n");
10094 			return err;
10095 		}
10096 		break;
10097 	case BPF_FUNC_get_local_storage:
10098 		/* check that flags argument in get_local_storage(map, flags) is 0,
10099 		 * this is required because get_local_storage() can't return an error.
10100 		 */
10101 		if (!register_is_null(&regs[BPF_REG_2])) {
10102 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10103 			return -EINVAL;
10104 		}
10105 		break;
10106 	case BPF_FUNC_for_each_map_elem:
10107 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10108 					 set_map_elem_callback_state);
10109 		break;
10110 	case BPF_FUNC_timer_set_callback:
10111 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10112 					 set_timer_callback_state);
10113 		break;
10114 	case BPF_FUNC_find_vma:
10115 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10116 					 set_find_vma_callback_state);
10117 		break;
10118 	case BPF_FUNC_snprintf:
10119 		err = check_bpf_snprintf_call(env, regs);
10120 		break;
10121 	case BPF_FUNC_loop:
10122 		update_loop_inline_state(env, meta.subprogno);
10123 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10124 		 * is finished, thus mark it precise.
10125 		 */
10126 		err = mark_chain_precision(env, BPF_REG_1);
10127 		if (err)
10128 			return err;
10129 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10130 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10131 						 set_loop_callback_state);
10132 		} else {
10133 			cur_func(env)->callback_depth = 0;
10134 			if (env->log.level & BPF_LOG_LEVEL2)
10135 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10136 					env->cur_state->curframe);
10137 		}
10138 		break;
10139 	case BPF_FUNC_dynptr_from_mem:
10140 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10141 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10142 				reg_type_str(env, regs[BPF_REG_1].type));
10143 			return -EACCES;
10144 		}
10145 		break;
10146 	case BPF_FUNC_set_retval:
10147 		if (prog_type == BPF_PROG_TYPE_LSM &&
10148 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10149 			if (!env->prog->aux->attach_func_proto->type) {
10150 				/* Make sure programs that attach to void
10151 				 * hooks don't try to modify return value.
10152 				 */
10153 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10154 				return -EINVAL;
10155 			}
10156 		}
10157 		break;
10158 	case BPF_FUNC_dynptr_data:
10159 	{
10160 		struct bpf_reg_state *reg;
10161 		int id, ref_obj_id;
10162 
10163 		reg = get_dynptr_arg_reg(env, fn, regs);
10164 		if (!reg)
10165 			return -EFAULT;
10166 
10167 
10168 		if (meta.dynptr_id) {
10169 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10170 			return -EFAULT;
10171 		}
10172 		if (meta.ref_obj_id) {
10173 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10174 			return -EFAULT;
10175 		}
10176 
10177 		id = dynptr_id(env, reg);
10178 		if (id < 0) {
10179 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10180 			return id;
10181 		}
10182 
10183 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10184 		if (ref_obj_id < 0) {
10185 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10186 			return ref_obj_id;
10187 		}
10188 
10189 		meta.dynptr_id = id;
10190 		meta.ref_obj_id = ref_obj_id;
10191 
10192 		break;
10193 	}
10194 	case BPF_FUNC_dynptr_write:
10195 	{
10196 		enum bpf_dynptr_type dynptr_type;
10197 		struct bpf_reg_state *reg;
10198 
10199 		reg = get_dynptr_arg_reg(env, fn, regs);
10200 		if (!reg)
10201 			return -EFAULT;
10202 
10203 		dynptr_type = dynptr_get_type(env, reg);
10204 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10205 			return -EFAULT;
10206 
10207 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10208 			/* this will trigger clear_all_pkt_pointers(), which will
10209 			 * invalidate all dynptr slices associated with the skb
10210 			 */
10211 			changes_data = true;
10212 
10213 		break;
10214 	}
10215 	case BPF_FUNC_user_ringbuf_drain:
10216 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10217 					 set_user_ringbuf_callback_state);
10218 		break;
10219 	}
10220 
10221 	if (err)
10222 		return err;
10223 
10224 	/* reset caller saved regs */
10225 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10226 		mark_reg_not_init(env, regs, caller_saved[i]);
10227 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10228 	}
10229 
10230 	/* helper call returns 64-bit value. */
10231 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10232 
10233 	/* update return register (already marked as written above) */
10234 	ret_type = fn->ret_type;
10235 	ret_flag = type_flag(ret_type);
10236 
10237 	switch (base_type(ret_type)) {
10238 	case RET_INTEGER:
10239 		/* sets type to SCALAR_VALUE */
10240 		mark_reg_unknown(env, regs, BPF_REG_0);
10241 		break;
10242 	case RET_VOID:
10243 		regs[BPF_REG_0].type = NOT_INIT;
10244 		break;
10245 	case RET_PTR_TO_MAP_VALUE:
10246 		/* There is no offset yet applied, variable or fixed */
10247 		mark_reg_known_zero(env, regs, BPF_REG_0);
10248 		/* remember map_ptr, so that check_map_access()
10249 		 * can check 'value_size' boundary of memory access
10250 		 * to map element returned from bpf_map_lookup_elem()
10251 		 */
10252 		if (meta.map_ptr == NULL) {
10253 			verbose(env,
10254 				"kernel subsystem misconfigured verifier\n");
10255 			return -EINVAL;
10256 		}
10257 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10258 		regs[BPF_REG_0].map_uid = meta.map_uid;
10259 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10260 		if (!type_may_be_null(ret_type) &&
10261 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10262 			regs[BPF_REG_0].id = ++env->id_gen;
10263 		}
10264 		break;
10265 	case RET_PTR_TO_SOCKET:
10266 		mark_reg_known_zero(env, regs, BPF_REG_0);
10267 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10268 		break;
10269 	case RET_PTR_TO_SOCK_COMMON:
10270 		mark_reg_known_zero(env, regs, BPF_REG_0);
10271 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10272 		break;
10273 	case RET_PTR_TO_TCP_SOCK:
10274 		mark_reg_known_zero(env, regs, BPF_REG_0);
10275 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10276 		break;
10277 	case RET_PTR_TO_MEM:
10278 		mark_reg_known_zero(env, regs, BPF_REG_0);
10279 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10280 		regs[BPF_REG_0].mem_size = meta.mem_size;
10281 		break;
10282 	case RET_PTR_TO_MEM_OR_BTF_ID:
10283 	{
10284 		const struct btf_type *t;
10285 
10286 		mark_reg_known_zero(env, regs, BPF_REG_0);
10287 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10288 		if (!btf_type_is_struct(t)) {
10289 			u32 tsize;
10290 			const struct btf_type *ret;
10291 			const char *tname;
10292 
10293 			/* resolve the type size of ksym. */
10294 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10295 			if (IS_ERR(ret)) {
10296 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10297 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10298 					tname, PTR_ERR(ret));
10299 				return -EINVAL;
10300 			}
10301 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10302 			regs[BPF_REG_0].mem_size = tsize;
10303 		} else {
10304 			/* MEM_RDONLY may be carried from ret_flag, but it
10305 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10306 			 * it will confuse the check of PTR_TO_BTF_ID in
10307 			 * check_mem_access().
10308 			 */
10309 			ret_flag &= ~MEM_RDONLY;
10310 
10311 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10312 			regs[BPF_REG_0].btf = meta.ret_btf;
10313 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10314 		}
10315 		break;
10316 	}
10317 	case RET_PTR_TO_BTF_ID:
10318 	{
10319 		struct btf *ret_btf;
10320 		int ret_btf_id;
10321 
10322 		mark_reg_known_zero(env, regs, BPF_REG_0);
10323 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10324 		if (func_id == BPF_FUNC_kptr_xchg) {
10325 			ret_btf = meta.kptr_field->kptr.btf;
10326 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10327 			if (!btf_is_kernel(ret_btf))
10328 				regs[BPF_REG_0].type |= MEM_ALLOC;
10329 		} else {
10330 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10331 				verbose(env, "verifier internal error:");
10332 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10333 					func_id_name(func_id));
10334 				return -EINVAL;
10335 			}
10336 			ret_btf = btf_vmlinux;
10337 			ret_btf_id = *fn->ret_btf_id;
10338 		}
10339 		if (ret_btf_id == 0) {
10340 			verbose(env, "invalid return type %u of func %s#%d\n",
10341 				base_type(ret_type), func_id_name(func_id),
10342 				func_id);
10343 			return -EINVAL;
10344 		}
10345 		regs[BPF_REG_0].btf = ret_btf;
10346 		regs[BPF_REG_0].btf_id = ret_btf_id;
10347 		break;
10348 	}
10349 	default:
10350 		verbose(env, "unknown return type %u of func %s#%d\n",
10351 			base_type(ret_type), func_id_name(func_id), func_id);
10352 		return -EINVAL;
10353 	}
10354 
10355 	if (type_may_be_null(regs[BPF_REG_0].type))
10356 		regs[BPF_REG_0].id = ++env->id_gen;
10357 
10358 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10359 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10360 			func_id_name(func_id), func_id);
10361 		return -EFAULT;
10362 	}
10363 
10364 	if (is_dynptr_ref_function(func_id))
10365 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10366 
10367 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10368 		/* For release_reference() */
10369 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10370 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10371 		int id = acquire_reference_state(env, insn_idx);
10372 
10373 		if (id < 0)
10374 			return id;
10375 		/* For mark_ptr_or_null_reg() */
10376 		regs[BPF_REG_0].id = id;
10377 		/* For release_reference() */
10378 		regs[BPF_REG_0].ref_obj_id = id;
10379 	}
10380 
10381 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10382 
10383 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10384 	if (err)
10385 		return err;
10386 
10387 	if ((func_id == BPF_FUNC_get_stack ||
10388 	     func_id == BPF_FUNC_get_task_stack) &&
10389 	    !env->prog->has_callchain_buf) {
10390 		const char *err_str;
10391 
10392 #ifdef CONFIG_PERF_EVENTS
10393 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10394 		err_str = "cannot get callchain buffer for func %s#%d\n";
10395 #else
10396 		err = -ENOTSUPP;
10397 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10398 #endif
10399 		if (err) {
10400 			verbose(env, err_str, func_id_name(func_id), func_id);
10401 			return err;
10402 		}
10403 
10404 		env->prog->has_callchain_buf = true;
10405 	}
10406 
10407 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10408 		env->prog->call_get_stack = true;
10409 
10410 	if (func_id == BPF_FUNC_get_func_ip) {
10411 		if (check_get_func_ip(env))
10412 			return -ENOTSUPP;
10413 		env->prog->call_get_func_ip = true;
10414 	}
10415 
10416 	if (changes_data)
10417 		clear_all_pkt_pointers(env);
10418 	return 0;
10419 }
10420 
10421 /* mark_btf_func_reg_size() is used when the reg size is determined by
10422  * the BTF func_proto's return value size and argument.
10423  */
10424 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10425 				   size_t reg_size)
10426 {
10427 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10428 
10429 	if (regno == BPF_REG_0) {
10430 		/* Function return value */
10431 		reg->live |= REG_LIVE_WRITTEN;
10432 		reg->subreg_def = reg_size == sizeof(u64) ?
10433 			DEF_NOT_SUBREG : env->insn_idx + 1;
10434 	} else {
10435 		/* Function argument */
10436 		if (reg_size == sizeof(u64)) {
10437 			mark_insn_zext(env, reg);
10438 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10439 		} else {
10440 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10441 		}
10442 	}
10443 }
10444 
10445 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10446 {
10447 	return meta->kfunc_flags & KF_ACQUIRE;
10448 }
10449 
10450 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10451 {
10452 	return meta->kfunc_flags & KF_RELEASE;
10453 }
10454 
10455 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10456 {
10457 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10458 }
10459 
10460 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10461 {
10462 	return meta->kfunc_flags & KF_SLEEPABLE;
10463 }
10464 
10465 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10466 {
10467 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10468 }
10469 
10470 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10471 {
10472 	return meta->kfunc_flags & KF_RCU;
10473 }
10474 
10475 static bool __kfunc_param_match_suffix(const struct btf *btf,
10476 				       const struct btf_param *arg,
10477 				       const char *suffix)
10478 {
10479 	int suffix_len = strlen(suffix), len;
10480 	const char *param_name;
10481 
10482 	/* In the future, this can be ported to use BTF tagging */
10483 	param_name = btf_name_by_offset(btf, arg->name_off);
10484 	if (str_is_empty(param_name))
10485 		return false;
10486 	len = strlen(param_name);
10487 	if (len < suffix_len)
10488 		return false;
10489 	param_name += len - suffix_len;
10490 	return !strncmp(param_name, suffix, suffix_len);
10491 }
10492 
10493 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10494 				  const struct btf_param *arg,
10495 				  const struct bpf_reg_state *reg)
10496 {
10497 	const struct btf_type *t;
10498 
10499 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10500 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10501 		return false;
10502 
10503 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10504 }
10505 
10506 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10507 					const struct btf_param *arg,
10508 					const struct bpf_reg_state *reg)
10509 {
10510 	const struct btf_type *t;
10511 
10512 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10513 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10514 		return false;
10515 
10516 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10517 }
10518 
10519 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10520 {
10521 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10522 }
10523 
10524 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10525 {
10526 	return __kfunc_param_match_suffix(btf, arg, "__k");
10527 }
10528 
10529 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10530 {
10531 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10532 }
10533 
10534 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10535 {
10536 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10537 }
10538 
10539 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10540 {
10541 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10542 }
10543 
10544 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10545 {
10546 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10547 }
10548 
10549 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10550 					  const struct btf_param *arg,
10551 					  const char *name)
10552 {
10553 	int len, target_len = strlen(name);
10554 	const char *param_name;
10555 
10556 	param_name = btf_name_by_offset(btf, arg->name_off);
10557 	if (str_is_empty(param_name))
10558 		return false;
10559 	len = strlen(param_name);
10560 	if (len != target_len)
10561 		return false;
10562 	if (strcmp(param_name, name))
10563 		return false;
10564 
10565 	return true;
10566 }
10567 
10568 enum {
10569 	KF_ARG_DYNPTR_ID,
10570 	KF_ARG_LIST_HEAD_ID,
10571 	KF_ARG_LIST_NODE_ID,
10572 	KF_ARG_RB_ROOT_ID,
10573 	KF_ARG_RB_NODE_ID,
10574 };
10575 
10576 BTF_ID_LIST(kf_arg_btf_ids)
10577 BTF_ID(struct, bpf_dynptr_kern)
10578 BTF_ID(struct, bpf_list_head)
10579 BTF_ID(struct, bpf_list_node)
10580 BTF_ID(struct, bpf_rb_root)
10581 BTF_ID(struct, bpf_rb_node)
10582 
10583 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10584 				    const struct btf_param *arg, int type)
10585 {
10586 	const struct btf_type *t;
10587 	u32 res_id;
10588 
10589 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10590 	if (!t)
10591 		return false;
10592 	if (!btf_type_is_ptr(t))
10593 		return false;
10594 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10595 	if (!t)
10596 		return false;
10597 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10598 }
10599 
10600 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10601 {
10602 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10603 }
10604 
10605 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10606 {
10607 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10608 }
10609 
10610 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10611 {
10612 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10613 }
10614 
10615 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10616 {
10617 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10618 }
10619 
10620 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10621 {
10622 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10623 }
10624 
10625 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10626 				  const struct btf_param *arg)
10627 {
10628 	const struct btf_type *t;
10629 
10630 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10631 	if (!t)
10632 		return false;
10633 
10634 	return true;
10635 }
10636 
10637 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10638 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10639 					const struct btf *btf,
10640 					const struct btf_type *t, int rec)
10641 {
10642 	const struct btf_type *member_type;
10643 	const struct btf_member *member;
10644 	u32 i;
10645 
10646 	if (!btf_type_is_struct(t))
10647 		return false;
10648 
10649 	for_each_member(i, t, member) {
10650 		const struct btf_array *array;
10651 
10652 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10653 		if (btf_type_is_struct(member_type)) {
10654 			if (rec >= 3) {
10655 				verbose(env, "max struct nesting depth exceeded\n");
10656 				return false;
10657 			}
10658 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10659 				return false;
10660 			continue;
10661 		}
10662 		if (btf_type_is_array(member_type)) {
10663 			array = btf_array(member_type);
10664 			if (!array->nelems)
10665 				return false;
10666 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10667 			if (!btf_type_is_scalar(member_type))
10668 				return false;
10669 			continue;
10670 		}
10671 		if (!btf_type_is_scalar(member_type))
10672 			return false;
10673 	}
10674 	return true;
10675 }
10676 
10677 enum kfunc_ptr_arg_type {
10678 	KF_ARG_PTR_TO_CTX,
10679 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10680 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10681 	KF_ARG_PTR_TO_DYNPTR,
10682 	KF_ARG_PTR_TO_ITER,
10683 	KF_ARG_PTR_TO_LIST_HEAD,
10684 	KF_ARG_PTR_TO_LIST_NODE,
10685 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10686 	KF_ARG_PTR_TO_MEM,
10687 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10688 	KF_ARG_PTR_TO_CALLBACK,
10689 	KF_ARG_PTR_TO_RB_ROOT,
10690 	KF_ARG_PTR_TO_RB_NODE,
10691 };
10692 
10693 enum special_kfunc_type {
10694 	KF_bpf_obj_new_impl,
10695 	KF_bpf_obj_drop_impl,
10696 	KF_bpf_refcount_acquire_impl,
10697 	KF_bpf_list_push_front_impl,
10698 	KF_bpf_list_push_back_impl,
10699 	KF_bpf_list_pop_front,
10700 	KF_bpf_list_pop_back,
10701 	KF_bpf_cast_to_kern_ctx,
10702 	KF_bpf_rdonly_cast,
10703 	KF_bpf_rcu_read_lock,
10704 	KF_bpf_rcu_read_unlock,
10705 	KF_bpf_rbtree_remove,
10706 	KF_bpf_rbtree_add_impl,
10707 	KF_bpf_rbtree_first,
10708 	KF_bpf_dynptr_from_skb,
10709 	KF_bpf_dynptr_from_xdp,
10710 	KF_bpf_dynptr_slice,
10711 	KF_bpf_dynptr_slice_rdwr,
10712 	KF_bpf_dynptr_clone,
10713 };
10714 
10715 BTF_SET_START(special_kfunc_set)
10716 BTF_ID(func, bpf_obj_new_impl)
10717 BTF_ID(func, bpf_obj_drop_impl)
10718 BTF_ID(func, bpf_refcount_acquire_impl)
10719 BTF_ID(func, bpf_list_push_front_impl)
10720 BTF_ID(func, bpf_list_push_back_impl)
10721 BTF_ID(func, bpf_list_pop_front)
10722 BTF_ID(func, bpf_list_pop_back)
10723 BTF_ID(func, bpf_cast_to_kern_ctx)
10724 BTF_ID(func, bpf_rdonly_cast)
10725 BTF_ID(func, bpf_rbtree_remove)
10726 BTF_ID(func, bpf_rbtree_add_impl)
10727 BTF_ID(func, bpf_rbtree_first)
10728 BTF_ID(func, bpf_dynptr_from_skb)
10729 BTF_ID(func, bpf_dynptr_from_xdp)
10730 BTF_ID(func, bpf_dynptr_slice)
10731 BTF_ID(func, bpf_dynptr_slice_rdwr)
10732 BTF_ID(func, bpf_dynptr_clone)
10733 BTF_SET_END(special_kfunc_set)
10734 
10735 BTF_ID_LIST(special_kfunc_list)
10736 BTF_ID(func, bpf_obj_new_impl)
10737 BTF_ID(func, bpf_obj_drop_impl)
10738 BTF_ID(func, bpf_refcount_acquire_impl)
10739 BTF_ID(func, bpf_list_push_front_impl)
10740 BTF_ID(func, bpf_list_push_back_impl)
10741 BTF_ID(func, bpf_list_pop_front)
10742 BTF_ID(func, bpf_list_pop_back)
10743 BTF_ID(func, bpf_cast_to_kern_ctx)
10744 BTF_ID(func, bpf_rdonly_cast)
10745 BTF_ID(func, bpf_rcu_read_lock)
10746 BTF_ID(func, bpf_rcu_read_unlock)
10747 BTF_ID(func, bpf_rbtree_remove)
10748 BTF_ID(func, bpf_rbtree_add_impl)
10749 BTF_ID(func, bpf_rbtree_first)
10750 BTF_ID(func, bpf_dynptr_from_skb)
10751 BTF_ID(func, bpf_dynptr_from_xdp)
10752 BTF_ID(func, bpf_dynptr_slice)
10753 BTF_ID(func, bpf_dynptr_slice_rdwr)
10754 BTF_ID(func, bpf_dynptr_clone)
10755 
10756 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10757 {
10758 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10759 	    meta->arg_owning_ref) {
10760 		return false;
10761 	}
10762 
10763 	return meta->kfunc_flags & KF_RET_NULL;
10764 }
10765 
10766 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10767 {
10768 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10769 }
10770 
10771 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10772 {
10773 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10774 }
10775 
10776 static enum kfunc_ptr_arg_type
10777 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10778 		       struct bpf_kfunc_call_arg_meta *meta,
10779 		       const struct btf_type *t, const struct btf_type *ref_t,
10780 		       const char *ref_tname, const struct btf_param *args,
10781 		       int argno, int nargs)
10782 {
10783 	u32 regno = argno + 1;
10784 	struct bpf_reg_state *regs = cur_regs(env);
10785 	struct bpf_reg_state *reg = &regs[regno];
10786 	bool arg_mem_size = false;
10787 
10788 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10789 		return KF_ARG_PTR_TO_CTX;
10790 
10791 	/* In this function, we verify the kfunc's BTF as per the argument type,
10792 	 * leaving the rest of the verification with respect to the register
10793 	 * type to our caller. When a set of conditions hold in the BTF type of
10794 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10795 	 */
10796 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10797 		return KF_ARG_PTR_TO_CTX;
10798 
10799 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10800 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10801 
10802 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10803 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10804 
10805 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10806 		return KF_ARG_PTR_TO_DYNPTR;
10807 
10808 	if (is_kfunc_arg_iter(meta, argno))
10809 		return KF_ARG_PTR_TO_ITER;
10810 
10811 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10812 		return KF_ARG_PTR_TO_LIST_HEAD;
10813 
10814 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10815 		return KF_ARG_PTR_TO_LIST_NODE;
10816 
10817 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10818 		return KF_ARG_PTR_TO_RB_ROOT;
10819 
10820 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10821 		return KF_ARG_PTR_TO_RB_NODE;
10822 
10823 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10824 		if (!btf_type_is_struct(ref_t)) {
10825 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10826 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10827 			return -EINVAL;
10828 		}
10829 		return KF_ARG_PTR_TO_BTF_ID;
10830 	}
10831 
10832 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10833 		return KF_ARG_PTR_TO_CALLBACK;
10834 
10835 
10836 	if (argno + 1 < nargs &&
10837 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10838 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10839 		arg_mem_size = true;
10840 
10841 	/* This is the catch all argument type of register types supported by
10842 	 * check_helper_mem_access. However, we only allow when argument type is
10843 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10844 	 * arg_mem_size is true, the pointer can be void *.
10845 	 */
10846 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10847 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10848 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10849 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10850 		return -EINVAL;
10851 	}
10852 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10853 }
10854 
10855 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10856 					struct bpf_reg_state *reg,
10857 					const struct btf_type *ref_t,
10858 					const char *ref_tname, u32 ref_id,
10859 					struct bpf_kfunc_call_arg_meta *meta,
10860 					int argno)
10861 {
10862 	const struct btf_type *reg_ref_t;
10863 	bool strict_type_match = false;
10864 	const struct btf *reg_btf;
10865 	const char *reg_ref_tname;
10866 	u32 reg_ref_id;
10867 
10868 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10869 		reg_btf = reg->btf;
10870 		reg_ref_id = reg->btf_id;
10871 	} else {
10872 		reg_btf = btf_vmlinux;
10873 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10874 	}
10875 
10876 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10877 	 * or releasing a reference, or are no-cast aliases. We do _not_
10878 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10879 	 * as we want to enable BPF programs to pass types that are bitwise
10880 	 * equivalent without forcing them to explicitly cast with something
10881 	 * like bpf_cast_to_kern_ctx().
10882 	 *
10883 	 * For example, say we had a type like the following:
10884 	 *
10885 	 * struct bpf_cpumask {
10886 	 *	cpumask_t cpumask;
10887 	 *	refcount_t usage;
10888 	 * };
10889 	 *
10890 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10891 	 * to a struct cpumask, so it would be safe to pass a struct
10892 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10893 	 *
10894 	 * The philosophy here is similar to how we allow scalars of different
10895 	 * types to be passed to kfuncs as long as the size is the same. The
10896 	 * only difference here is that we're simply allowing
10897 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10898 	 * resolve types.
10899 	 */
10900 	if (is_kfunc_acquire(meta) ||
10901 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10902 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10903 		strict_type_match = true;
10904 
10905 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10906 
10907 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10908 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10909 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10910 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10911 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10912 			btf_type_str(reg_ref_t), reg_ref_tname);
10913 		return -EINVAL;
10914 	}
10915 	return 0;
10916 }
10917 
10918 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10919 {
10920 	struct bpf_verifier_state *state = env->cur_state;
10921 	struct btf_record *rec = reg_btf_record(reg);
10922 
10923 	if (!state->active_lock.ptr) {
10924 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10925 		return -EFAULT;
10926 	}
10927 
10928 	if (type_flag(reg->type) & NON_OWN_REF) {
10929 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10930 		return -EFAULT;
10931 	}
10932 
10933 	reg->type |= NON_OWN_REF;
10934 	if (rec->refcount_off >= 0)
10935 		reg->type |= MEM_RCU;
10936 
10937 	return 0;
10938 }
10939 
10940 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10941 {
10942 	struct bpf_func_state *state, *unused;
10943 	struct bpf_reg_state *reg;
10944 	int i;
10945 
10946 	state = cur_func(env);
10947 
10948 	if (!ref_obj_id) {
10949 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10950 			     "owning -> non-owning conversion\n");
10951 		return -EFAULT;
10952 	}
10953 
10954 	for (i = 0; i < state->acquired_refs; i++) {
10955 		if (state->refs[i].id != ref_obj_id)
10956 			continue;
10957 
10958 		/* Clear ref_obj_id here so release_reference doesn't clobber
10959 		 * the whole reg
10960 		 */
10961 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10962 			if (reg->ref_obj_id == ref_obj_id) {
10963 				reg->ref_obj_id = 0;
10964 				ref_set_non_owning(env, reg);
10965 			}
10966 		}));
10967 		return 0;
10968 	}
10969 
10970 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10971 	return -EFAULT;
10972 }
10973 
10974 /* Implementation details:
10975  *
10976  * Each register points to some region of memory, which we define as an
10977  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10978  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10979  * allocation. The lock and the data it protects are colocated in the same
10980  * memory region.
10981  *
10982  * Hence, everytime a register holds a pointer value pointing to such
10983  * allocation, the verifier preserves a unique reg->id for it.
10984  *
10985  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10986  * bpf_spin_lock is called.
10987  *
10988  * To enable this, lock state in the verifier captures two values:
10989  *	active_lock.ptr = Register's type specific pointer
10990  *	active_lock.id  = A unique ID for each register pointer value
10991  *
10992  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10993  * supported register types.
10994  *
10995  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10996  * allocated objects is the reg->btf pointer.
10997  *
10998  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10999  * can establish the provenance of the map value statically for each distinct
11000  * lookup into such maps. They always contain a single map value hence unique
11001  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11002  *
11003  * So, in case of global variables, they use array maps with max_entries = 1,
11004  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11005  * into the same map value as max_entries is 1, as described above).
11006  *
11007  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11008  * outer map pointer (in verifier context), but each lookup into an inner map
11009  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11010  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11011  * will get different reg->id assigned to each lookup, hence different
11012  * active_lock.id.
11013  *
11014  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11015  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11016  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11017  */
11018 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11019 {
11020 	void *ptr;
11021 	u32 id;
11022 
11023 	switch ((int)reg->type) {
11024 	case PTR_TO_MAP_VALUE:
11025 		ptr = reg->map_ptr;
11026 		break;
11027 	case PTR_TO_BTF_ID | MEM_ALLOC:
11028 		ptr = reg->btf;
11029 		break;
11030 	default:
11031 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11032 		return -EFAULT;
11033 	}
11034 	id = reg->id;
11035 
11036 	if (!env->cur_state->active_lock.ptr)
11037 		return -EINVAL;
11038 	if (env->cur_state->active_lock.ptr != ptr ||
11039 	    env->cur_state->active_lock.id != id) {
11040 		verbose(env, "held lock and object are not in the same allocation\n");
11041 		return -EINVAL;
11042 	}
11043 	return 0;
11044 }
11045 
11046 static bool is_bpf_list_api_kfunc(u32 btf_id)
11047 {
11048 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11049 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11050 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11051 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11052 }
11053 
11054 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11055 {
11056 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11057 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11058 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11059 }
11060 
11061 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11062 {
11063 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11064 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11065 }
11066 
11067 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11068 {
11069 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11070 }
11071 
11072 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11073 {
11074 	return is_bpf_rbtree_api_kfunc(btf_id);
11075 }
11076 
11077 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11078 					  enum btf_field_type head_field_type,
11079 					  u32 kfunc_btf_id)
11080 {
11081 	bool ret;
11082 
11083 	switch (head_field_type) {
11084 	case BPF_LIST_HEAD:
11085 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11086 		break;
11087 	case BPF_RB_ROOT:
11088 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11089 		break;
11090 	default:
11091 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11092 			btf_field_type_name(head_field_type));
11093 		return false;
11094 	}
11095 
11096 	if (!ret)
11097 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11098 			btf_field_type_name(head_field_type));
11099 	return ret;
11100 }
11101 
11102 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11103 					  enum btf_field_type node_field_type,
11104 					  u32 kfunc_btf_id)
11105 {
11106 	bool ret;
11107 
11108 	switch (node_field_type) {
11109 	case BPF_LIST_NODE:
11110 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11111 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11112 		break;
11113 	case BPF_RB_NODE:
11114 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11115 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11116 		break;
11117 	default:
11118 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11119 			btf_field_type_name(node_field_type));
11120 		return false;
11121 	}
11122 
11123 	if (!ret)
11124 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11125 			btf_field_type_name(node_field_type));
11126 	return ret;
11127 }
11128 
11129 static int
11130 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11131 				   struct bpf_reg_state *reg, u32 regno,
11132 				   struct bpf_kfunc_call_arg_meta *meta,
11133 				   enum btf_field_type head_field_type,
11134 				   struct btf_field **head_field)
11135 {
11136 	const char *head_type_name;
11137 	struct btf_field *field;
11138 	struct btf_record *rec;
11139 	u32 head_off;
11140 
11141 	if (meta->btf != btf_vmlinux) {
11142 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11143 		return -EFAULT;
11144 	}
11145 
11146 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11147 		return -EFAULT;
11148 
11149 	head_type_name = btf_field_type_name(head_field_type);
11150 	if (!tnum_is_const(reg->var_off)) {
11151 		verbose(env,
11152 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11153 			regno, head_type_name);
11154 		return -EINVAL;
11155 	}
11156 
11157 	rec = reg_btf_record(reg);
11158 	head_off = reg->off + reg->var_off.value;
11159 	field = btf_record_find(rec, head_off, head_field_type);
11160 	if (!field) {
11161 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11162 		return -EINVAL;
11163 	}
11164 
11165 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11166 	if (check_reg_allocation_locked(env, reg)) {
11167 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11168 			rec->spin_lock_off, head_type_name);
11169 		return -EINVAL;
11170 	}
11171 
11172 	if (*head_field) {
11173 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11174 		return -EFAULT;
11175 	}
11176 	*head_field = field;
11177 	return 0;
11178 }
11179 
11180 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11181 					   struct bpf_reg_state *reg, u32 regno,
11182 					   struct bpf_kfunc_call_arg_meta *meta)
11183 {
11184 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11185 							  &meta->arg_list_head.field);
11186 }
11187 
11188 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11189 					     struct bpf_reg_state *reg, u32 regno,
11190 					     struct bpf_kfunc_call_arg_meta *meta)
11191 {
11192 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11193 							  &meta->arg_rbtree_root.field);
11194 }
11195 
11196 static int
11197 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11198 				   struct bpf_reg_state *reg, u32 regno,
11199 				   struct bpf_kfunc_call_arg_meta *meta,
11200 				   enum btf_field_type head_field_type,
11201 				   enum btf_field_type node_field_type,
11202 				   struct btf_field **node_field)
11203 {
11204 	const char *node_type_name;
11205 	const struct btf_type *et, *t;
11206 	struct btf_field *field;
11207 	u32 node_off;
11208 
11209 	if (meta->btf != btf_vmlinux) {
11210 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11211 		return -EFAULT;
11212 	}
11213 
11214 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11215 		return -EFAULT;
11216 
11217 	node_type_name = btf_field_type_name(node_field_type);
11218 	if (!tnum_is_const(reg->var_off)) {
11219 		verbose(env,
11220 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11221 			regno, node_type_name);
11222 		return -EINVAL;
11223 	}
11224 
11225 	node_off = reg->off + reg->var_off.value;
11226 	field = reg_find_field_offset(reg, node_off, node_field_type);
11227 	if (!field || field->offset != node_off) {
11228 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11229 		return -EINVAL;
11230 	}
11231 
11232 	field = *node_field;
11233 
11234 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11235 	t = btf_type_by_id(reg->btf, reg->btf_id);
11236 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11237 				  field->graph_root.value_btf_id, true)) {
11238 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11239 			"in struct %s, but arg is at offset=%d in struct %s\n",
11240 			btf_field_type_name(head_field_type),
11241 			btf_field_type_name(node_field_type),
11242 			field->graph_root.node_offset,
11243 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11244 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11245 		return -EINVAL;
11246 	}
11247 	meta->arg_btf = reg->btf;
11248 	meta->arg_btf_id = reg->btf_id;
11249 
11250 	if (node_off != field->graph_root.node_offset) {
11251 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11252 			node_off, btf_field_type_name(node_field_type),
11253 			field->graph_root.node_offset,
11254 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11255 		return -EINVAL;
11256 	}
11257 
11258 	return 0;
11259 }
11260 
11261 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11262 					   struct bpf_reg_state *reg, u32 regno,
11263 					   struct bpf_kfunc_call_arg_meta *meta)
11264 {
11265 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11266 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11267 						  &meta->arg_list_head.field);
11268 }
11269 
11270 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11271 					     struct bpf_reg_state *reg, u32 regno,
11272 					     struct bpf_kfunc_call_arg_meta *meta)
11273 {
11274 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11275 						  BPF_RB_ROOT, BPF_RB_NODE,
11276 						  &meta->arg_rbtree_root.field);
11277 }
11278 
11279 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11280 			    int insn_idx)
11281 {
11282 	const char *func_name = meta->func_name, *ref_tname;
11283 	const struct btf *btf = meta->btf;
11284 	const struct btf_param *args;
11285 	struct btf_record *rec;
11286 	u32 i, nargs;
11287 	int ret;
11288 
11289 	args = (const struct btf_param *)(meta->func_proto + 1);
11290 	nargs = btf_type_vlen(meta->func_proto);
11291 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11292 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11293 			MAX_BPF_FUNC_REG_ARGS);
11294 		return -EINVAL;
11295 	}
11296 
11297 	/* Check that BTF function arguments match actual types that the
11298 	 * verifier sees.
11299 	 */
11300 	for (i = 0; i < nargs; i++) {
11301 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11302 		const struct btf_type *t, *ref_t, *resolve_ret;
11303 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11304 		u32 regno = i + 1, ref_id, type_size;
11305 		bool is_ret_buf_sz = false;
11306 		int kf_arg_type;
11307 
11308 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11309 
11310 		if (is_kfunc_arg_ignore(btf, &args[i]))
11311 			continue;
11312 
11313 		if (btf_type_is_scalar(t)) {
11314 			if (reg->type != SCALAR_VALUE) {
11315 				verbose(env, "R%d is not a scalar\n", regno);
11316 				return -EINVAL;
11317 			}
11318 
11319 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11320 				if (meta->arg_constant.found) {
11321 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11322 					return -EFAULT;
11323 				}
11324 				if (!tnum_is_const(reg->var_off)) {
11325 					verbose(env, "R%d must be a known constant\n", regno);
11326 					return -EINVAL;
11327 				}
11328 				ret = mark_chain_precision(env, regno);
11329 				if (ret < 0)
11330 					return ret;
11331 				meta->arg_constant.found = true;
11332 				meta->arg_constant.value = reg->var_off.value;
11333 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11334 				meta->r0_rdonly = true;
11335 				is_ret_buf_sz = true;
11336 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11337 				is_ret_buf_sz = true;
11338 			}
11339 
11340 			if (is_ret_buf_sz) {
11341 				if (meta->r0_size) {
11342 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11343 					return -EINVAL;
11344 				}
11345 
11346 				if (!tnum_is_const(reg->var_off)) {
11347 					verbose(env, "R%d is not a const\n", regno);
11348 					return -EINVAL;
11349 				}
11350 
11351 				meta->r0_size = reg->var_off.value;
11352 				ret = mark_chain_precision(env, regno);
11353 				if (ret)
11354 					return ret;
11355 			}
11356 			continue;
11357 		}
11358 
11359 		if (!btf_type_is_ptr(t)) {
11360 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11361 			return -EINVAL;
11362 		}
11363 
11364 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11365 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11366 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11367 			return -EACCES;
11368 		}
11369 
11370 		if (reg->ref_obj_id) {
11371 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11372 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11373 					regno, reg->ref_obj_id,
11374 					meta->ref_obj_id);
11375 				return -EFAULT;
11376 			}
11377 			meta->ref_obj_id = reg->ref_obj_id;
11378 			if (is_kfunc_release(meta))
11379 				meta->release_regno = regno;
11380 		}
11381 
11382 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11383 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11384 
11385 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11386 		if (kf_arg_type < 0)
11387 			return kf_arg_type;
11388 
11389 		switch (kf_arg_type) {
11390 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11391 		case KF_ARG_PTR_TO_BTF_ID:
11392 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11393 				break;
11394 
11395 			if (!is_trusted_reg(reg)) {
11396 				if (!is_kfunc_rcu(meta)) {
11397 					verbose(env, "R%d must be referenced or trusted\n", regno);
11398 					return -EINVAL;
11399 				}
11400 				if (!is_rcu_reg(reg)) {
11401 					verbose(env, "R%d must be a rcu pointer\n", regno);
11402 					return -EINVAL;
11403 				}
11404 			}
11405 
11406 			fallthrough;
11407 		case KF_ARG_PTR_TO_CTX:
11408 			/* Trusted arguments have the same offset checks as release arguments */
11409 			arg_type |= OBJ_RELEASE;
11410 			break;
11411 		case KF_ARG_PTR_TO_DYNPTR:
11412 		case KF_ARG_PTR_TO_ITER:
11413 		case KF_ARG_PTR_TO_LIST_HEAD:
11414 		case KF_ARG_PTR_TO_LIST_NODE:
11415 		case KF_ARG_PTR_TO_RB_ROOT:
11416 		case KF_ARG_PTR_TO_RB_NODE:
11417 		case KF_ARG_PTR_TO_MEM:
11418 		case KF_ARG_PTR_TO_MEM_SIZE:
11419 		case KF_ARG_PTR_TO_CALLBACK:
11420 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11421 			/* Trusted by default */
11422 			break;
11423 		default:
11424 			WARN_ON_ONCE(1);
11425 			return -EFAULT;
11426 		}
11427 
11428 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11429 			arg_type |= OBJ_RELEASE;
11430 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11431 		if (ret < 0)
11432 			return ret;
11433 
11434 		switch (kf_arg_type) {
11435 		case KF_ARG_PTR_TO_CTX:
11436 			if (reg->type != PTR_TO_CTX) {
11437 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11438 				return -EINVAL;
11439 			}
11440 
11441 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11442 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11443 				if (ret < 0)
11444 					return -EINVAL;
11445 				meta->ret_btf_id  = ret;
11446 			}
11447 			break;
11448 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11449 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11450 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11451 				return -EINVAL;
11452 			}
11453 			if (!reg->ref_obj_id) {
11454 				verbose(env, "allocated object must be referenced\n");
11455 				return -EINVAL;
11456 			}
11457 			if (meta->btf == btf_vmlinux &&
11458 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11459 				meta->arg_btf = reg->btf;
11460 				meta->arg_btf_id = reg->btf_id;
11461 			}
11462 			break;
11463 		case KF_ARG_PTR_TO_DYNPTR:
11464 		{
11465 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11466 			int clone_ref_obj_id = 0;
11467 
11468 			if (reg->type != PTR_TO_STACK &&
11469 			    reg->type != CONST_PTR_TO_DYNPTR) {
11470 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11471 				return -EINVAL;
11472 			}
11473 
11474 			if (reg->type == CONST_PTR_TO_DYNPTR)
11475 				dynptr_arg_type |= MEM_RDONLY;
11476 
11477 			if (is_kfunc_arg_uninit(btf, &args[i]))
11478 				dynptr_arg_type |= MEM_UNINIT;
11479 
11480 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11481 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11482 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11483 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11484 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11485 				   (dynptr_arg_type & MEM_UNINIT)) {
11486 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11487 
11488 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11489 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11490 					return -EFAULT;
11491 				}
11492 
11493 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11494 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11495 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11496 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11497 					return -EFAULT;
11498 				}
11499 			}
11500 
11501 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11502 			if (ret < 0)
11503 				return ret;
11504 
11505 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11506 				int id = dynptr_id(env, reg);
11507 
11508 				if (id < 0) {
11509 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11510 					return id;
11511 				}
11512 				meta->initialized_dynptr.id = id;
11513 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11514 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11515 			}
11516 
11517 			break;
11518 		}
11519 		case KF_ARG_PTR_TO_ITER:
11520 			ret = process_iter_arg(env, regno, insn_idx, meta);
11521 			if (ret < 0)
11522 				return ret;
11523 			break;
11524 		case KF_ARG_PTR_TO_LIST_HEAD:
11525 			if (reg->type != PTR_TO_MAP_VALUE &&
11526 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11527 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11528 				return -EINVAL;
11529 			}
11530 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11531 				verbose(env, "allocated object must be referenced\n");
11532 				return -EINVAL;
11533 			}
11534 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11535 			if (ret < 0)
11536 				return ret;
11537 			break;
11538 		case KF_ARG_PTR_TO_RB_ROOT:
11539 			if (reg->type != PTR_TO_MAP_VALUE &&
11540 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11541 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11542 				return -EINVAL;
11543 			}
11544 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11545 				verbose(env, "allocated object must be referenced\n");
11546 				return -EINVAL;
11547 			}
11548 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11549 			if (ret < 0)
11550 				return ret;
11551 			break;
11552 		case KF_ARG_PTR_TO_LIST_NODE:
11553 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11554 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11555 				return -EINVAL;
11556 			}
11557 			if (!reg->ref_obj_id) {
11558 				verbose(env, "allocated object must be referenced\n");
11559 				return -EINVAL;
11560 			}
11561 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11562 			if (ret < 0)
11563 				return ret;
11564 			break;
11565 		case KF_ARG_PTR_TO_RB_NODE:
11566 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11567 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11568 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11569 					return -EINVAL;
11570 				}
11571 				if (in_rbtree_lock_required_cb(env)) {
11572 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11573 					return -EINVAL;
11574 				}
11575 			} else {
11576 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11577 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11578 					return -EINVAL;
11579 				}
11580 				if (!reg->ref_obj_id) {
11581 					verbose(env, "allocated object must be referenced\n");
11582 					return -EINVAL;
11583 				}
11584 			}
11585 
11586 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11587 			if (ret < 0)
11588 				return ret;
11589 			break;
11590 		case KF_ARG_PTR_TO_BTF_ID:
11591 			/* Only base_type is checked, further checks are done here */
11592 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11593 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11594 			    !reg2btf_ids[base_type(reg->type)]) {
11595 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11596 				verbose(env, "expected %s or socket\n",
11597 					reg_type_str(env, base_type(reg->type) |
11598 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11599 				return -EINVAL;
11600 			}
11601 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11602 			if (ret < 0)
11603 				return ret;
11604 			break;
11605 		case KF_ARG_PTR_TO_MEM:
11606 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11607 			if (IS_ERR(resolve_ret)) {
11608 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11609 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11610 				return -EINVAL;
11611 			}
11612 			ret = check_mem_reg(env, reg, regno, type_size);
11613 			if (ret < 0)
11614 				return ret;
11615 			break;
11616 		case KF_ARG_PTR_TO_MEM_SIZE:
11617 		{
11618 			struct bpf_reg_state *buff_reg = &regs[regno];
11619 			const struct btf_param *buff_arg = &args[i];
11620 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11621 			const struct btf_param *size_arg = &args[i + 1];
11622 
11623 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11624 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11625 				if (ret < 0) {
11626 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11627 					return ret;
11628 				}
11629 			}
11630 
11631 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11632 				if (meta->arg_constant.found) {
11633 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11634 					return -EFAULT;
11635 				}
11636 				if (!tnum_is_const(size_reg->var_off)) {
11637 					verbose(env, "R%d must be a known constant\n", regno + 1);
11638 					return -EINVAL;
11639 				}
11640 				meta->arg_constant.found = true;
11641 				meta->arg_constant.value = size_reg->var_off.value;
11642 			}
11643 
11644 			/* Skip next '__sz' or '__szk' argument */
11645 			i++;
11646 			break;
11647 		}
11648 		case KF_ARG_PTR_TO_CALLBACK:
11649 			if (reg->type != PTR_TO_FUNC) {
11650 				verbose(env, "arg%d expected pointer to func\n", i);
11651 				return -EINVAL;
11652 			}
11653 			meta->subprogno = reg->subprogno;
11654 			break;
11655 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11656 			if (!type_is_ptr_alloc_obj(reg->type)) {
11657 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11658 				return -EINVAL;
11659 			}
11660 			if (!type_is_non_owning_ref(reg->type))
11661 				meta->arg_owning_ref = true;
11662 
11663 			rec = reg_btf_record(reg);
11664 			if (!rec) {
11665 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11666 				return -EFAULT;
11667 			}
11668 
11669 			if (rec->refcount_off < 0) {
11670 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11671 				return -EINVAL;
11672 			}
11673 
11674 			meta->arg_btf = reg->btf;
11675 			meta->arg_btf_id = reg->btf_id;
11676 			break;
11677 		}
11678 	}
11679 
11680 	if (is_kfunc_release(meta) && !meta->release_regno) {
11681 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11682 			func_name);
11683 		return -EINVAL;
11684 	}
11685 
11686 	return 0;
11687 }
11688 
11689 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11690 			    struct bpf_insn *insn,
11691 			    struct bpf_kfunc_call_arg_meta *meta,
11692 			    const char **kfunc_name)
11693 {
11694 	const struct btf_type *func, *func_proto;
11695 	u32 func_id, *kfunc_flags;
11696 	const char *func_name;
11697 	struct btf *desc_btf;
11698 
11699 	if (kfunc_name)
11700 		*kfunc_name = NULL;
11701 
11702 	if (!insn->imm)
11703 		return -EINVAL;
11704 
11705 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11706 	if (IS_ERR(desc_btf))
11707 		return PTR_ERR(desc_btf);
11708 
11709 	func_id = insn->imm;
11710 	func = btf_type_by_id(desc_btf, func_id);
11711 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11712 	if (kfunc_name)
11713 		*kfunc_name = func_name;
11714 	func_proto = btf_type_by_id(desc_btf, func->type);
11715 
11716 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11717 	if (!kfunc_flags) {
11718 		return -EACCES;
11719 	}
11720 
11721 	memset(meta, 0, sizeof(*meta));
11722 	meta->btf = desc_btf;
11723 	meta->func_id = func_id;
11724 	meta->kfunc_flags = *kfunc_flags;
11725 	meta->func_proto = func_proto;
11726 	meta->func_name = func_name;
11727 
11728 	return 0;
11729 }
11730 
11731 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11732 			    int *insn_idx_p)
11733 {
11734 	const struct btf_type *t, *ptr_type;
11735 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11736 	struct bpf_reg_state *regs = cur_regs(env);
11737 	const char *func_name, *ptr_type_name;
11738 	bool sleepable, rcu_lock, rcu_unlock;
11739 	struct bpf_kfunc_call_arg_meta meta;
11740 	struct bpf_insn_aux_data *insn_aux;
11741 	int err, insn_idx = *insn_idx_p;
11742 	const struct btf_param *args;
11743 	const struct btf_type *ret_t;
11744 	struct btf *desc_btf;
11745 
11746 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11747 	if (!insn->imm)
11748 		return 0;
11749 
11750 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11751 	if (err == -EACCES && func_name)
11752 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11753 	if (err)
11754 		return err;
11755 	desc_btf = meta.btf;
11756 	insn_aux = &env->insn_aux_data[insn_idx];
11757 
11758 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11759 
11760 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11761 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11762 		return -EACCES;
11763 	}
11764 
11765 	sleepable = is_kfunc_sleepable(&meta);
11766 	if (sleepable && !env->prog->aux->sleepable) {
11767 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11768 		return -EACCES;
11769 	}
11770 
11771 	/* Check the arguments */
11772 	err = check_kfunc_args(env, &meta, insn_idx);
11773 	if (err < 0)
11774 		return err;
11775 
11776 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11777 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11778 					 set_rbtree_add_callback_state);
11779 		if (err) {
11780 			verbose(env, "kfunc %s#%d failed callback verification\n",
11781 				func_name, meta.func_id);
11782 			return err;
11783 		}
11784 	}
11785 
11786 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11787 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11788 
11789 	if (env->cur_state->active_rcu_lock) {
11790 		struct bpf_func_state *state;
11791 		struct bpf_reg_state *reg;
11792 
11793 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11794 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11795 			return -EACCES;
11796 		}
11797 
11798 		if (rcu_lock) {
11799 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11800 			return -EINVAL;
11801 		} else if (rcu_unlock) {
11802 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11803 				if (reg->type & MEM_RCU) {
11804 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11805 					reg->type |= PTR_UNTRUSTED;
11806 				}
11807 			}));
11808 			env->cur_state->active_rcu_lock = false;
11809 		} else if (sleepable) {
11810 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11811 			return -EACCES;
11812 		}
11813 	} else if (rcu_lock) {
11814 		env->cur_state->active_rcu_lock = true;
11815 	} else if (rcu_unlock) {
11816 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11817 		return -EINVAL;
11818 	}
11819 
11820 	/* In case of release function, we get register number of refcounted
11821 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11822 	 */
11823 	if (meta.release_regno) {
11824 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11825 		if (err) {
11826 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11827 				func_name, meta.func_id);
11828 			return err;
11829 		}
11830 	}
11831 
11832 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11833 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11834 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11835 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11836 		insn_aux->insert_off = regs[BPF_REG_2].off;
11837 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11838 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11839 		if (err) {
11840 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11841 				func_name, meta.func_id);
11842 			return err;
11843 		}
11844 
11845 		err = release_reference(env, release_ref_obj_id);
11846 		if (err) {
11847 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11848 				func_name, meta.func_id);
11849 			return err;
11850 		}
11851 	}
11852 
11853 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11854 		mark_reg_not_init(env, regs, caller_saved[i]);
11855 
11856 	/* Check return type */
11857 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11858 
11859 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11860 		/* Only exception is bpf_obj_new_impl */
11861 		if (meta.btf != btf_vmlinux ||
11862 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11863 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11864 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11865 			return -EINVAL;
11866 		}
11867 	}
11868 
11869 	if (btf_type_is_scalar(t)) {
11870 		mark_reg_unknown(env, regs, BPF_REG_0);
11871 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11872 	} else if (btf_type_is_ptr(t)) {
11873 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11874 
11875 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11876 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11877 				struct btf *ret_btf;
11878 				u32 ret_btf_id;
11879 
11880 				if (unlikely(!bpf_global_ma_set))
11881 					return -ENOMEM;
11882 
11883 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11884 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11885 					return -EINVAL;
11886 				}
11887 
11888 				ret_btf = env->prog->aux->btf;
11889 				ret_btf_id = meta.arg_constant.value;
11890 
11891 				/* This may be NULL due to user not supplying a BTF */
11892 				if (!ret_btf) {
11893 					verbose(env, "bpf_obj_new requires prog BTF\n");
11894 					return -EINVAL;
11895 				}
11896 
11897 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11898 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11899 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11900 					return -EINVAL;
11901 				}
11902 
11903 				mark_reg_known_zero(env, regs, BPF_REG_0);
11904 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11905 				regs[BPF_REG_0].btf = ret_btf;
11906 				regs[BPF_REG_0].btf_id = ret_btf_id;
11907 
11908 				insn_aux->obj_new_size = ret_t->size;
11909 				insn_aux->kptr_struct_meta =
11910 					btf_find_struct_meta(ret_btf, ret_btf_id);
11911 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11912 				mark_reg_known_zero(env, regs, BPF_REG_0);
11913 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11914 				regs[BPF_REG_0].btf = meta.arg_btf;
11915 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11916 
11917 				insn_aux->kptr_struct_meta =
11918 					btf_find_struct_meta(meta.arg_btf,
11919 							     meta.arg_btf_id);
11920 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11921 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11922 				struct btf_field *field = meta.arg_list_head.field;
11923 
11924 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11925 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11926 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11927 				struct btf_field *field = meta.arg_rbtree_root.field;
11928 
11929 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11930 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11931 				mark_reg_known_zero(env, regs, BPF_REG_0);
11932 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11933 				regs[BPF_REG_0].btf = desc_btf;
11934 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11935 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11936 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11937 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11938 					verbose(env,
11939 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11940 					return -EINVAL;
11941 				}
11942 
11943 				mark_reg_known_zero(env, regs, BPF_REG_0);
11944 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11945 				regs[BPF_REG_0].btf = desc_btf;
11946 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11947 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11948 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11949 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11950 
11951 				mark_reg_known_zero(env, regs, BPF_REG_0);
11952 
11953 				if (!meta.arg_constant.found) {
11954 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11955 					return -EFAULT;
11956 				}
11957 
11958 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11959 
11960 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11961 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11962 
11963 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11964 					regs[BPF_REG_0].type |= MEM_RDONLY;
11965 				} else {
11966 					/* this will set env->seen_direct_write to true */
11967 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11968 						verbose(env, "the prog does not allow writes to packet data\n");
11969 						return -EINVAL;
11970 					}
11971 				}
11972 
11973 				if (!meta.initialized_dynptr.id) {
11974 					verbose(env, "verifier internal error: no dynptr id\n");
11975 					return -EFAULT;
11976 				}
11977 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11978 
11979 				/* we don't need to set BPF_REG_0's ref obj id
11980 				 * because packet slices are not refcounted (see
11981 				 * dynptr_type_refcounted)
11982 				 */
11983 			} else {
11984 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11985 					meta.func_name);
11986 				return -EFAULT;
11987 			}
11988 		} else if (!__btf_type_is_struct(ptr_type)) {
11989 			if (!meta.r0_size) {
11990 				__u32 sz;
11991 
11992 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11993 					meta.r0_size = sz;
11994 					meta.r0_rdonly = true;
11995 				}
11996 			}
11997 			if (!meta.r0_size) {
11998 				ptr_type_name = btf_name_by_offset(desc_btf,
11999 								   ptr_type->name_off);
12000 				verbose(env,
12001 					"kernel function %s returns pointer type %s %s is not supported\n",
12002 					func_name,
12003 					btf_type_str(ptr_type),
12004 					ptr_type_name);
12005 				return -EINVAL;
12006 			}
12007 
12008 			mark_reg_known_zero(env, regs, BPF_REG_0);
12009 			regs[BPF_REG_0].type = PTR_TO_MEM;
12010 			regs[BPF_REG_0].mem_size = meta.r0_size;
12011 
12012 			if (meta.r0_rdonly)
12013 				regs[BPF_REG_0].type |= MEM_RDONLY;
12014 
12015 			/* Ensures we don't access the memory after a release_reference() */
12016 			if (meta.ref_obj_id)
12017 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12018 		} else {
12019 			mark_reg_known_zero(env, regs, BPF_REG_0);
12020 			regs[BPF_REG_0].btf = desc_btf;
12021 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12022 			regs[BPF_REG_0].btf_id = ptr_type_id;
12023 		}
12024 
12025 		if (is_kfunc_ret_null(&meta)) {
12026 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12027 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12028 			regs[BPF_REG_0].id = ++env->id_gen;
12029 		}
12030 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12031 		if (is_kfunc_acquire(&meta)) {
12032 			int id = acquire_reference_state(env, insn_idx);
12033 
12034 			if (id < 0)
12035 				return id;
12036 			if (is_kfunc_ret_null(&meta))
12037 				regs[BPF_REG_0].id = id;
12038 			regs[BPF_REG_0].ref_obj_id = id;
12039 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12040 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12041 		}
12042 
12043 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12044 			regs[BPF_REG_0].id = ++env->id_gen;
12045 	} else if (btf_type_is_void(t)) {
12046 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12047 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12048 				insn_aux->kptr_struct_meta =
12049 					btf_find_struct_meta(meta.arg_btf,
12050 							     meta.arg_btf_id);
12051 			}
12052 		}
12053 	}
12054 
12055 	nargs = btf_type_vlen(meta.func_proto);
12056 	args = (const struct btf_param *)(meta.func_proto + 1);
12057 	for (i = 0; i < nargs; i++) {
12058 		u32 regno = i + 1;
12059 
12060 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12061 		if (btf_type_is_ptr(t))
12062 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12063 		else
12064 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12065 			mark_btf_func_reg_size(env, regno, t->size);
12066 	}
12067 
12068 	if (is_iter_next_kfunc(&meta)) {
12069 		err = process_iter_next_call(env, insn_idx, &meta);
12070 		if (err)
12071 			return err;
12072 	}
12073 
12074 	return 0;
12075 }
12076 
12077 static bool signed_add_overflows(s64 a, s64 b)
12078 {
12079 	/* Do the add in u64, where overflow is well-defined */
12080 	s64 res = (s64)((u64)a + (u64)b);
12081 
12082 	if (b < 0)
12083 		return res > a;
12084 	return res < a;
12085 }
12086 
12087 static bool signed_add32_overflows(s32 a, s32 b)
12088 {
12089 	/* Do the add in u32, where overflow is well-defined */
12090 	s32 res = (s32)((u32)a + (u32)b);
12091 
12092 	if (b < 0)
12093 		return res > a;
12094 	return res < a;
12095 }
12096 
12097 static bool signed_sub_overflows(s64 a, s64 b)
12098 {
12099 	/* Do the sub in u64, where overflow is well-defined */
12100 	s64 res = (s64)((u64)a - (u64)b);
12101 
12102 	if (b < 0)
12103 		return res < a;
12104 	return res > a;
12105 }
12106 
12107 static bool signed_sub32_overflows(s32 a, s32 b)
12108 {
12109 	/* Do the sub in u32, where overflow is well-defined */
12110 	s32 res = (s32)((u32)a - (u32)b);
12111 
12112 	if (b < 0)
12113 		return res < a;
12114 	return res > a;
12115 }
12116 
12117 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12118 				  const struct bpf_reg_state *reg,
12119 				  enum bpf_reg_type type)
12120 {
12121 	bool known = tnum_is_const(reg->var_off);
12122 	s64 val = reg->var_off.value;
12123 	s64 smin = reg->smin_value;
12124 
12125 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12126 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12127 			reg_type_str(env, type), val);
12128 		return false;
12129 	}
12130 
12131 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12132 		verbose(env, "%s pointer offset %d is not allowed\n",
12133 			reg_type_str(env, type), reg->off);
12134 		return false;
12135 	}
12136 
12137 	if (smin == S64_MIN) {
12138 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12139 			reg_type_str(env, type));
12140 		return false;
12141 	}
12142 
12143 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12144 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12145 			smin, reg_type_str(env, type));
12146 		return false;
12147 	}
12148 
12149 	return true;
12150 }
12151 
12152 enum {
12153 	REASON_BOUNDS	= -1,
12154 	REASON_TYPE	= -2,
12155 	REASON_PATHS	= -3,
12156 	REASON_LIMIT	= -4,
12157 	REASON_STACK	= -5,
12158 };
12159 
12160 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12161 			      u32 *alu_limit, bool mask_to_left)
12162 {
12163 	u32 max = 0, ptr_limit = 0;
12164 
12165 	switch (ptr_reg->type) {
12166 	case PTR_TO_STACK:
12167 		/* Offset 0 is out-of-bounds, but acceptable start for the
12168 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12169 		 * offset where we would need to deal with min/max bounds is
12170 		 * currently prohibited for unprivileged.
12171 		 */
12172 		max = MAX_BPF_STACK + mask_to_left;
12173 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12174 		break;
12175 	case PTR_TO_MAP_VALUE:
12176 		max = ptr_reg->map_ptr->value_size;
12177 		ptr_limit = (mask_to_left ?
12178 			     ptr_reg->smin_value :
12179 			     ptr_reg->umax_value) + ptr_reg->off;
12180 		break;
12181 	default:
12182 		return REASON_TYPE;
12183 	}
12184 
12185 	if (ptr_limit >= max)
12186 		return REASON_LIMIT;
12187 	*alu_limit = ptr_limit;
12188 	return 0;
12189 }
12190 
12191 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12192 				    const struct bpf_insn *insn)
12193 {
12194 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12195 }
12196 
12197 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12198 				       u32 alu_state, u32 alu_limit)
12199 {
12200 	/* If we arrived here from different branches with different
12201 	 * state or limits to sanitize, then this won't work.
12202 	 */
12203 	if (aux->alu_state &&
12204 	    (aux->alu_state != alu_state ||
12205 	     aux->alu_limit != alu_limit))
12206 		return REASON_PATHS;
12207 
12208 	/* Corresponding fixup done in do_misc_fixups(). */
12209 	aux->alu_state = alu_state;
12210 	aux->alu_limit = alu_limit;
12211 	return 0;
12212 }
12213 
12214 static int sanitize_val_alu(struct bpf_verifier_env *env,
12215 			    struct bpf_insn *insn)
12216 {
12217 	struct bpf_insn_aux_data *aux = cur_aux(env);
12218 
12219 	if (can_skip_alu_sanitation(env, insn))
12220 		return 0;
12221 
12222 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12223 }
12224 
12225 static bool sanitize_needed(u8 opcode)
12226 {
12227 	return opcode == BPF_ADD || opcode == BPF_SUB;
12228 }
12229 
12230 struct bpf_sanitize_info {
12231 	struct bpf_insn_aux_data aux;
12232 	bool mask_to_left;
12233 };
12234 
12235 static struct bpf_verifier_state *
12236 sanitize_speculative_path(struct bpf_verifier_env *env,
12237 			  const struct bpf_insn *insn,
12238 			  u32 next_idx, u32 curr_idx)
12239 {
12240 	struct bpf_verifier_state *branch;
12241 	struct bpf_reg_state *regs;
12242 
12243 	branch = push_stack(env, next_idx, curr_idx, true);
12244 	if (branch && insn) {
12245 		regs = branch->frame[branch->curframe]->regs;
12246 		if (BPF_SRC(insn->code) == BPF_K) {
12247 			mark_reg_unknown(env, regs, insn->dst_reg);
12248 		} else if (BPF_SRC(insn->code) == BPF_X) {
12249 			mark_reg_unknown(env, regs, insn->dst_reg);
12250 			mark_reg_unknown(env, regs, insn->src_reg);
12251 		}
12252 	}
12253 	return branch;
12254 }
12255 
12256 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12257 			    struct bpf_insn *insn,
12258 			    const struct bpf_reg_state *ptr_reg,
12259 			    const struct bpf_reg_state *off_reg,
12260 			    struct bpf_reg_state *dst_reg,
12261 			    struct bpf_sanitize_info *info,
12262 			    const bool commit_window)
12263 {
12264 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12265 	struct bpf_verifier_state *vstate = env->cur_state;
12266 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12267 	bool off_is_neg = off_reg->smin_value < 0;
12268 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12269 	u8 opcode = BPF_OP(insn->code);
12270 	u32 alu_state, alu_limit;
12271 	struct bpf_reg_state tmp;
12272 	bool ret;
12273 	int err;
12274 
12275 	if (can_skip_alu_sanitation(env, insn))
12276 		return 0;
12277 
12278 	/* We already marked aux for masking from non-speculative
12279 	 * paths, thus we got here in the first place. We only care
12280 	 * to explore bad access from here.
12281 	 */
12282 	if (vstate->speculative)
12283 		goto do_sim;
12284 
12285 	if (!commit_window) {
12286 		if (!tnum_is_const(off_reg->var_off) &&
12287 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12288 			return REASON_BOUNDS;
12289 
12290 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12291 				     (opcode == BPF_SUB && !off_is_neg);
12292 	}
12293 
12294 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12295 	if (err < 0)
12296 		return err;
12297 
12298 	if (commit_window) {
12299 		/* In commit phase we narrow the masking window based on
12300 		 * the observed pointer move after the simulated operation.
12301 		 */
12302 		alu_state = info->aux.alu_state;
12303 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12304 	} else {
12305 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12306 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12307 		alu_state |= ptr_is_dst_reg ?
12308 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12309 
12310 		/* Limit pruning on unknown scalars to enable deep search for
12311 		 * potential masking differences from other program paths.
12312 		 */
12313 		if (!off_is_imm)
12314 			env->explore_alu_limits = true;
12315 	}
12316 
12317 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12318 	if (err < 0)
12319 		return err;
12320 do_sim:
12321 	/* If we're in commit phase, we're done here given we already
12322 	 * pushed the truncated dst_reg into the speculative verification
12323 	 * stack.
12324 	 *
12325 	 * Also, when register is a known constant, we rewrite register-based
12326 	 * operation to immediate-based, and thus do not need masking (and as
12327 	 * a consequence, do not need to simulate the zero-truncation either).
12328 	 */
12329 	if (commit_window || off_is_imm)
12330 		return 0;
12331 
12332 	/* Simulate and find potential out-of-bounds access under
12333 	 * speculative execution from truncation as a result of
12334 	 * masking when off was not within expected range. If off
12335 	 * sits in dst, then we temporarily need to move ptr there
12336 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12337 	 * for cases where we use K-based arithmetic in one direction
12338 	 * and truncated reg-based in the other in order to explore
12339 	 * bad access.
12340 	 */
12341 	if (!ptr_is_dst_reg) {
12342 		tmp = *dst_reg;
12343 		copy_register_state(dst_reg, ptr_reg);
12344 	}
12345 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12346 					env->insn_idx);
12347 	if (!ptr_is_dst_reg && ret)
12348 		*dst_reg = tmp;
12349 	return !ret ? REASON_STACK : 0;
12350 }
12351 
12352 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12353 {
12354 	struct bpf_verifier_state *vstate = env->cur_state;
12355 
12356 	/* If we simulate paths under speculation, we don't update the
12357 	 * insn as 'seen' such that when we verify unreachable paths in
12358 	 * the non-speculative domain, sanitize_dead_code() can still
12359 	 * rewrite/sanitize them.
12360 	 */
12361 	if (!vstate->speculative)
12362 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12363 }
12364 
12365 static int sanitize_err(struct bpf_verifier_env *env,
12366 			const struct bpf_insn *insn, int reason,
12367 			const struct bpf_reg_state *off_reg,
12368 			const struct bpf_reg_state *dst_reg)
12369 {
12370 	static const char *err = "pointer arithmetic with it prohibited for !root";
12371 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12372 	u32 dst = insn->dst_reg, src = insn->src_reg;
12373 
12374 	switch (reason) {
12375 	case REASON_BOUNDS:
12376 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12377 			off_reg == dst_reg ? dst : src, err);
12378 		break;
12379 	case REASON_TYPE:
12380 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12381 			off_reg == dst_reg ? src : dst, err);
12382 		break;
12383 	case REASON_PATHS:
12384 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12385 			dst, op, err);
12386 		break;
12387 	case REASON_LIMIT:
12388 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12389 			dst, op, err);
12390 		break;
12391 	case REASON_STACK:
12392 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12393 			dst, err);
12394 		break;
12395 	default:
12396 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12397 			reason);
12398 		break;
12399 	}
12400 
12401 	return -EACCES;
12402 }
12403 
12404 /* check that stack access falls within stack limits and that 'reg' doesn't
12405  * have a variable offset.
12406  *
12407  * Variable offset is prohibited for unprivileged mode for simplicity since it
12408  * requires corresponding support in Spectre masking for stack ALU.  See also
12409  * retrieve_ptr_limit().
12410  *
12411  *
12412  * 'off' includes 'reg->off'.
12413  */
12414 static int check_stack_access_for_ptr_arithmetic(
12415 				struct bpf_verifier_env *env,
12416 				int regno,
12417 				const struct bpf_reg_state *reg,
12418 				int off)
12419 {
12420 	if (!tnum_is_const(reg->var_off)) {
12421 		char tn_buf[48];
12422 
12423 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12424 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12425 			regno, tn_buf, off);
12426 		return -EACCES;
12427 	}
12428 
12429 	if (off >= 0 || off < -MAX_BPF_STACK) {
12430 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12431 			"prohibited for !root; off=%d\n", regno, off);
12432 		return -EACCES;
12433 	}
12434 
12435 	return 0;
12436 }
12437 
12438 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12439 				 const struct bpf_insn *insn,
12440 				 const struct bpf_reg_state *dst_reg)
12441 {
12442 	u32 dst = insn->dst_reg;
12443 
12444 	/* For unprivileged we require that resulting offset must be in bounds
12445 	 * in order to be able to sanitize access later on.
12446 	 */
12447 	if (env->bypass_spec_v1)
12448 		return 0;
12449 
12450 	switch (dst_reg->type) {
12451 	case PTR_TO_STACK:
12452 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12453 					dst_reg->off + dst_reg->var_off.value))
12454 			return -EACCES;
12455 		break;
12456 	case PTR_TO_MAP_VALUE:
12457 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12458 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12459 				"prohibited for !root\n", dst);
12460 			return -EACCES;
12461 		}
12462 		break;
12463 	default:
12464 		break;
12465 	}
12466 
12467 	return 0;
12468 }
12469 
12470 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12471  * Caller should also handle BPF_MOV case separately.
12472  * If we return -EACCES, caller may want to try again treating pointer as a
12473  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12474  */
12475 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12476 				   struct bpf_insn *insn,
12477 				   const struct bpf_reg_state *ptr_reg,
12478 				   const struct bpf_reg_state *off_reg)
12479 {
12480 	struct bpf_verifier_state *vstate = env->cur_state;
12481 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12482 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12483 	bool known = tnum_is_const(off_reg->var_off);
12484 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12485 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12486 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12487 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12488 	struct bpf_sanitize_info info = {};
12489 	u8 opcode = BPF_OP(insn->code);
12490 	u32 dst = insn->dst_reg;
12491 	int ret;
12492 
12493 	dst_reg = &regs[dst];
12494 
12495 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12496 	    smin_val > smax_val || umin_val > umax_val) {
12497 		/* Taint dst register if offset had invalid bounds derived from
12498 		 * e.g. dead branches.
12499 		 */
12500 		__mark_reg_unknown(env, dst_reg);
12501 		return 0;
12502 	}
12503 
12504 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12505 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12506 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12507 			__mark_reg_unknown(env, dst_reg);
12508 			return 0;
12509 		}
12510 
12511 		verbose(env,
12512 			"R%d 32-bit pointer arithmetic prohibited\n",
12513 			dst);
12514 		return -EACCES;
12515 	}
12516 
12517 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12518 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12519 			dst, reg_type_str(env, ptr_reg->type));
12520 		return -EACCES;
12521 	}
12522 
12523 	switch (base_type(ptr_reg->type)) {
12524 	case PTR_TO_FLOW_KEYS:
12525 		if (known)
12526 			break;
12527 		fallthrough;
12528 	case CONST_PTR_TO_MAP:
12529 		/* smin_val represents the known value */
12530 		if (known && smin_val == 0 && opcode == BPF_ADD)
12531 			break;
12532 		fallthrough;
12533 	case PTR_TO_PACKET_END:
12534 	case PTR_TO_SOCKET:
12535 	case PTR_TO_SOCK_COMMON:
12536 	case PTR_TO_TCP_SOCK:
12537 	case PTR_TO_XDP_SOCK:
12538 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12539 			dst, reg_type_str(env, ptr_reg->type));
12540 		return -EACCES;
12541 	default:
12542 		break;
12543 	}
12544 
12545 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12546 	 * The id may be overwritten later if we create a new variable offset.
12547 	 */
12548 	dst_reg->type = ptr_reg->type;
12549 	dst_reg->id = ptr_reg->id;
12550 
12551 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12552 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12553 		return -EINVAL;
12554 
12555 	/* pointer types do not carry 32-bit bounds at the moment. */
12556 	__mark_reg32_unbounded(dst_reg);
12557 
12558 	if (sanitize_needed(opcode)) {
12559 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12560 				       &info, false);
12561 		if (ret < 0)
12562 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12563 	}
12564 
12565 	switch (opcode) {
12566 	case BPF_ADD:
12567 		/* We can take a fixed offset as long as it doesn't overflow
12568 		 * the s32 'off' field
12569 		 */
12570 		if (known && (ptr_reg->off + smin_val ==
12571 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12572 			/* pointer += K.  Accumulate it into fixed offset */
12573 			dst_reg->smin_value = smin_ptr;
12574 			dst_reg->smax_value = smax_ptr;
12575 			dst_reg->umin_value = umin_ptr;
12576 			dst_reg->umax_value = umax_ptr;
12577 			dst_reg->var_off = ptr_reg->var_off;
12578 			dst_reg->off = ptr_reg->off + smin_val;
12579 			dst_reg->raw = ptr_reg->raw;
12580 			break;
12581 		}
12582 		/* A new variable offset is created.  Note that off_reg->off
12583 		 * == 0, since it's a scalar.
12584 		 * dst_reg gets the pointer type and since some positive
12585 		 * integer value was added to the pointer, give it a new 'id'
12586 		 * if it's a PTR_TO_PACKET.
12587 		 * this creates a new 'base' pointer, off_reg (variable) gets
12588 		 * added into the variable offset, and we copy the fixed offset
12589 		 * from ptr_reg.
12590 		 */
12591 		if (signed_add_overflows(smin_ptr, smin_val) ||
12592 		    signed_add_overflows(smax_ptr, smax_val)) {
12593 			dst_reg->smin_value = S64_MIN;
12594 			dst_reg->smax_value = S64_MAX;
12595 		} else {
12596 			dst_reg->smin_value = smin_ptr + smin_val;
12597 			dst_reg->smax_value = smax_ptr + smax_val;
12598 		}
12599 		if (umin_ptr + umin_val < umin_ptr ||
12600 		    umax_ptr + umax_val < umax_ptr) {
12601 			dst_reg->umin_value = 0;
12602 			dst_reg->umax_value = U64_MAX;
12603 		} else {
12604 			dst_reg->umin_value = umin_ptr + umin_val;
12605 			dst_reg->umax_value = umax_ptr + umax_val;
12606 		}
12607 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12608 		dst_reg->off = ptr_reg->off;
12609 		dst_reg->raw = ptr_reg->raw;
12610 		if (reg_is_pkt_pointer(ptr_reg)) {
12611 			dst_reg->id = ++env->id_gen;
12612 			/* something was added to pkt_ptr, set range to zero */
12613 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12614 		}
12615 		break;
12616 	case BPF_SUB:
12617 		if (dst_reg == off_reg) {
12618 			/* scalar -= pointer.  Creates an unknown scalar */
12619 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12620 				dst);
12621 			return -EACCES;
12622 		}
12623 		/* We don't allow subtraction from FP, because (according to
12624 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12625 		 * be able to deal with it.
12626 		 */
12627 		if (ptr_reg->type == PTR_TO_STACK) {
12628 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12629 				dst);
12630 			return -EACCES;
12631 		}
12632 		if (known && (ptr_reg->off - smin_val ==
12633 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12634 			/* pointer -= K.  Subtract it from fixed offset */
12635 			dst_reg->smin_value = smin_ptr;
12636 			dst_reg->smax_value = smax_ptr;
12637 			dst_reg->umin_value = umin_ptr;
12638 			dst_reg->umax_value = umax_ptr;
12639 			dst_reg->var_off = ptr_reg->var_off;
12640 			dst_reg->id = ptr_reg->id;
12641 			dst_reg->off = ptr_reg->off - smin_val;
12642 			dst_reg->raw = ptr_reg->raw;
12643 			break;
12644 		}
12645 		/* A new variable offset is created.  If the subtrahend is known
12646 		 * nonnegative, then any reg->range we had before is still good.
12647 		 */
12648 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12649 		    signed_sub_overflows(smax_ptr, smin_val)) {
12650 			/* Overflow possible, we know nothing */
12651 			dst_reg->smin_value = S64_MIN;
12652 			dst_reg->smax_value = S64_MAX;
12653 		} else {
12654 			dst_reg->smin_value = smin_ptr - smax_val;
12655 			dst_reg->smax_value = smax_ptr - smin_val;
12656 		}
12657 		if (umin_ptr < umax_val) {
12658 			/* Overflow possible, we know nothing */
12659 			dst_reg->umin_value = 0;
12660 			dst_reg->umax_value = U64_MAX;
12661 		} else {
12662 			/* Cannot overflow (as long as bounds are consistent) */
12663 			dst_reg->umin_value = umin_ptr - umax_val;
12664 			dst_reg->umax_value = umax_ptr - umin_val;
12665 		}
12666 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12667 		dst_reg->off = ptr_reg->off;
12668 		dst_reg->raw = ptr_reg->raw;
12669 		if (reg_is_pkt_pointer(ptr_reg)) {
12670 			dst_reg->id = ++env->id_gen;
12671 			/* something was added to pkt_ptr, set range to zero */
12672 			if (smin_val < 0)
12673 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12674 		}
12675 		break;
12676 	case BPF_AND:
12677 	case BPF_OR:
12678 	case BPF_XOR:
12679 		/* bitwise ops on pointers are troublesome, prohibit. */
12680 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12681 			dst, bpf_alu_string[opcode >> 4]);
12682 		return -EACCES;
12683 	default:
12684 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12685 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12686 			dst, bpf_alu_string[opcode >> 4]);
12687 		return -EACCES;
12688 	}
12689 
12690 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12691 		return -EINVAL;
12692 	reg_bounds_sync(dst_reg);
12693 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12694 		return -EACCES;
12695 	if (sanitize_needed(opcode)) {
12696 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12697 				       &info, true);
12698 		if (ret < 0)
12699 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12700 	}
12701 
12702 	return 0;
12703 }
12704 
12705 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12706 				 struct bpf_reg_state *src_reg)
12707 {
12708 	s32 smin_val = src_reg->s32_min_value;
12709 	s32 smax_val = src_reg->s32_max_value;
12710 	u32 umin_val = src_reg->u32_min_value;
12711 	u32 umax_val = src_reg->u32_max_value;
12712 
12713 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12714 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12715 		dst_reg->s32_min_value = S32_MIN;
12716 		dst_reg->s32_max_value = S32_MAX;
12717 	} else {
12718 		dst_reg->s32_min_value += smin_val;
12719 		dst_reg->s32_max_value += smax_val;
12720 	}
12721 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12722 	    dst_reg->u32_max_value + umax_val < umax_val) {
12723 		dst_reg->u32_min_value = 0;
12724 		dst_reg->u32_max_value = U32_MAX;
12725 	} else {
12726 		dst_reg->u32_min_value += umin_val;
12727 		dst_reg->u32_max_value += umax_val;
12728 	}
12729 }
12730 
12731 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12732 			       struct bpf_reg_state *src_reg)
12733 {
12734 	s64 smin_val = src_reg->smin_value;
12735 	s64 smax_val = src_reg->smax_value;
12736 	u64 umin_val = src_reg->umin_value;
12737 	u64 umax_val = src_reg->umax_value;
12738 
12739 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12740 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12741 		dst_reg->smin_value = S64_MIN;
12742 		dst_reg->smax_value = S64_MAX;
12743 	} else {
12744 		dst_reg->smin_value += smin_val;
12745 		dst_reg->smax_value += smax_val;
12746 	}
12747 	if (dst_reg->umin_value + umin_val < umin_val ||
12748 	    dst_reg->umax_value + umax_val < umax_val) {
12749 		dst_reg->umin_value = 0;
12750 		dst_reg->umax_value = U64_MAX;
12751 	} else {
12752 		dst_reg->umin_value += umin_val;
12753 		dst_reg->umax_value += umax_val;
12754 	}
12755 }
12756 
12757 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12758 				 struct bpf_reg_state *src_reg)
12759 {
12760 	s32 smin_val = src_reg->s32_min_value;
12761 	s32 smax_val = src_reg->s32_max_value;
12762 	u32 umin_val = src_reg->u32_min_value;
12763 	u32 umax_val = src_reg->u32_max_value;
12764 
12765 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12766 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12767 		/* Overflow possible, we know nothing */
12768 		dst_reg->s32_min_value = S32_MIN;
12769 		dst_reg->s32_max_value = S32_MAX;
12770 	} else {
12771 		dst_reg->s32_min_value -= smax_val;
12772 		dst_reg->s32_max_value -= smin_val;
12773 	}
12774 	if (dst_reg->u32_min_value < umax_val) {
12775 		/* Overflow possible, we know nothing */
12776 		dst_reg->u32_min_value = 0;
12777 		dst_reg->u32_max_value = U32_MAX;
12778 	} else {
12779 		/* Cannot overflow (as long as bounds are consistent) */
12780 		dst_reg->u32_min_value -= umax_val;
12781 		dst_reg->u32_max_value -= umin_val;
12782 	}
12783 }
12784 
12785 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12786 			       struct bpf_reg_state *src_reg)
12787 {
12788 	s64 smin_val = src_reg->smin_value;
12789 	s64 smax_val = src_reg->smax_value;
12790 	u64 umin_val = src_reg->umin_value;
12791 	u64 umax_val = src_reg->umax_value;
12792 
12793 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12794 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12795 		/* Overflow possible, we know nothing */
12796 		dst_reg->smin_value = S64_MIN;
12797 		dst_reg->smax_value = S64_MAX;
12798 	} else {
12799 		dst_reg->smin_value -= smax_val;
12800 		dst_reg->smax_value -= smin_val;
12801 	}
12802 	if (dst_reg->umin_value < umax_val) {
12803 		/* Overflow possible, we know nothing */
12804 		dst_reg->umin_value = 0;
12805 		dst_reg->umax_value = U64_MAX;
12806 	} else {
12807 		/* Cannot overflow (as long as bounds are consistent) */
12808 		dst_reg->umin_value -= umax_val;
12809 		dst_reg->umax_value -= umin_val;
12810 	}
12811 }
12812 
12813 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12814 				 struct bpf_reg_state *src_reg)
12815 {
12816 	s32 smin_val = src_reg->s32_min_value;
12817 	u32 umin_val = src_reg->u32_min_value;
12818 	u32 umax_val = src_reg->u32_max_value;
12819 
12820 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12821 		/* Ain't nobody got time to multiply that sign */
12822 		__mark_reg32_unbounded(dst_reg);
12823 		return;
12824 	}
12825 	/* Both values are positive, so we can work with unsigned and
12826 	 * copy the result to signed (unless it exceeds S32_MAX).
12827 	 */
12828 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12829 		/* Potential overflow, we know nothing */
12830 		__mark_reg32_unbounded(dst_reg);
12831 		return;
12832 	}
12833 	dst_reg->u32_min_value *= umin_val;
12834 	dst_reg->u32_max_value *= umax_val;
12835 	if (dst_reg->u32_max_value > S32_MAX) {
12836 		/* Overflow possible, we know nothing */
12837 		dst_reg->s32_min_value = S32_MIN;
12838 		dst_reg->s32_max_value = S32_MAX;
12839 	} else {
12840 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12841 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12842 	}
12843 }
12844 
12845 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12846 			       struct bpf_reg_state *src_reg)
12847 {
12848 	s64 smin_val = src_reg->smin_value;
12849 	u64 umin_val = src_reg->umin_value;
12850 	u64 umax_val = src_reg->umax_value;
12851 
12852 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12853 		/* Ain't nobody got time to multiply that sign */
12854 		__mark_reg64_unbounded(dst_reg);
12855 		return;
12856 	}
12857 	/* Both values are positive, so we can work with unsigned and
12858 	 * copy the result to signed (unless it exceeds S64_MAX).
12859 	 */
12860 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12861 		/* Potential overflow, we know nothing */
12862 		__mark_reg64_unbounded(dst_reg);
12863 		return;
12864 	}
12865 	dst_reg->umin_value *= umin_val;
12866 	dst_reg->umax_value *= umax_val;
12867 	if (dst_reg->umax_value > S64_MAX) {
12868 		/* Overflow possible, we know nothing */
12869 		dst_reg->smin_value = S64_MIN;
12870 		dst_reg->smax_value = S64_MAX;
12871 	} else {
12872 		dst_reg->smin_value = dst_reg->umin_value;
12873 		dst_reg->smax_value = dst_reg->umax_value;
12874 	}
12875 }
12876 
12877 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12878 				 struct bpf_reg_state *src_reg)
12879 {
12880 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12881 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12882 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12883 	s32 smin_val = src_reg->s32_min_value;
12884 	u32 umax_val = src_reg->u32_max_value;
12885 
12886 	if (src_known && dst_known) {
12887 		__mark_reg32_known(dst_reg, var32_off.value);
12888 		return;
12889 	}
12890 
12891 	/* We get our minimum from the var_off, since that's inherently
12892 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12893 	 */
12894 	dst_reg->u32_min_value = var32_off.value;
12895 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12896 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12897 		/* Lose signed bounds when ANDing negative numbers,
12898 		 * ain't nobody got time for that.
12899 		 */
12900 		dst_reg->s32_min_value = S32_MIN;
12901 		dst_reg->s32_max_value = S32_MAX;
12902 	} else {
12903 		/* ANDing two positives gives a positive, so safe to
12904 		 * cast result into s64.
12905 		 */
12906 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12907 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12908 	}
12909 }
12910 
12911 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12912 			       struct bpf_reg_state *src_reg)
12913 {
12914 	bool src_known = tnum_is_const(src_reg->var_off);
12915 	bool dst_known = tnum_is_const(dst_reg->var_off);
12916 	s64 smin_val = src_reg->smin_value;
12917 	u64 umax_val = src_reg->umax_value;
12918 
12919 	if (src_known && dst_known) {
12920 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12921 		return;
12922 	}
12923 
12924 	/* We get our minimum from the var_off, since that's inherently
12925 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12926 	 */
12927 	dst_reg->umin_value = dst_reg->var_off.value;
12928 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12929 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12930 		/* Lose signed bounds when ANDing negative numbers,
12931 		 * ain't nobody got time for that.
12932 		 */
12933 		dst_reg->smin_value = S64_MIN;
12934 		dst_reg->smax_value = S64_MAX;
12935 	} else {
12936 		/* ANDing two positives gives a positive, so safe to
12937 		 * cast result into s64.
12938 		 */
12939 		dst_reg->smin_value = dst_reg->umin_value;
12940 		dst_reg->smax_value = dst_reg->umax_value;
12941 	}
12942 	/* We may learn something more from the var_off */
12943 	__update_reg_bounds(dst_reg);
12944 }
12945 
12946 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12947 				struct bpf_reg_state *src_reg)
12948 {
12949 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12950 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12951 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12952 	s32 smin_val = src_reg->s32_min_value;
12953 	u32 umin_val = src_reg->u32_min_value;
12954 
12955 	if (src_known && dst_known) {
12956 		__mark_reg32_known(dst_reg, var32_off.value);
12957 		return;
12958 	}
12959 
12960 	/* We get our maximum from the var_off, and our minimum is the
12961 	 * maximum of the operands' minima
12962 	 */
12963 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12964 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12965 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12966 		/* Lose signed bounds when ORing negative numbers,
12967 		 * ain't nobody got time for that.
12968 		 */
12969 		dst_reg->s32_min_value = S32_MIN;
12970 		dst_reg->s32_max_value = S32_MAX;
12971 	} else {
12972 		/* ORing two positives gives a positive, so safe to
12973 		 * cast result into s64.
12974 		 */
12975 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12976 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12977 	}
12978 }
12979 
12980 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12981 			      struct bpf_reg_state *src_reg)
12982 {
12983 	bool src_known = tnum_is_const(src_reg->var_off);
12984 	bool dst_known = tnum_is_const(dst_reg->var_off);
12985 	s64 smin_val = src_reg->smin_value;
12986 	u64 umin_val = src_reg->umin_value;
12987 
12988 	if (src_known && dst_known) {
12989 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12990 		return;
12991 	}
12992 
12993 	/* We get our maximum from the var_off, and our minimum is the
12994 	 * maximum of the operands' minima
12995 	 */
12996 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12997 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12998 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12999 		/* Lose signed bounds when ORing negative numbers,
13000 		 * ain't nobody got time for that.
13001 		 */
13002 		dst_reg->smin_value = S64_MIN;
13003 		dst_reg->smax_value = S64_MAX;
13004 	} else {
13005 		/* ORing two positives gives a positive, so safe to
13006 		 * cast result into s64.
13007 		 */
13008 		dst_reg->smin_value = dst_reg->umin_value;
13009 		dst_reg->smax_value = dst_reg->umax_value;
13010 	}
13011 	/* We may learn something more from the var_off */
13012 	__update_reg_bounds(dst_reg);
13013 }
13014 
13015 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13016 				 struct bpf_reg_state *src_reg)
13017 {
13018 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13019 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13020 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13021 	s32 smin_val = src_reg->s32_min_value;
13022 
13023 	if (src_known && dst_known) {
13024 		__mark_reg32_known(dst_reg, var32_off.value);
13025 		return;
13026 	}
13027 
13028 	/* We get both minimum and maximum from the var32_off. */
13029 	dst_reg->u32_min_value = var32_off.value;
13030 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13031 
13032 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13033 		/* XORing two positive sign numbers gives a positive,
13034 		 * so safe to cast u32 result into s32.
13035 		 */
13036 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13037 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13038 	} else {
13039 		dst_reg->s32_min_value = S32_MIN;
13040 		dst_reg->s32_max_value = S32_MAX;
13041 	}
13042 }
13043 
13044 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13045 			       struct bpf_reg_state *src_reg)
13046 {
13047 	bool src_known = tnum_is_const(src_reg->var_off);
13048 	bool dst_known = tnum_is_const(dst_reg->var_off);
13049 	s64 smin_val = src_reg->smin_value;
13050 
13051 	if (src_known && dst_known) {
13052 		/* dst_reg->var_off.value has been updated earlier */
13053 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13054 		return;
13055 	}
13056 
13057 	/* We get both minimum and maximum from the var_off. */
13058 	dst_reg->umin_value = dst_reg->var_off.value;
13059 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13060 
13061 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13062 		/* XORing two positive sign numbers gives a positive,
13063 		 * so safe to cast u64 result into s64.
13064 		 */
13065 		dst_reg->smin_value = dst_reg->umin_value;
13066 		dst_reg->smax_value = dst_reg->umax_value;
13067 	} else {
13068 		dst_reg->smin_value = S64_MIN;
13069 		dst_reg->smax_value = S64_MAX;
13070 	}
13071 
13072 	__update_reg_bounds(dst_reg);
13073 }
13074 
13075 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13076 				   u64 umin_val, u64 umax_val)
13077 {
13078 	/* We lose all sign bit information (except what we can pick
13079 	 * up from var_off)
13080 	 */
13081 	dst_reg->s32_min_value = S32_MIN;
13082 	dst_reg->s32_max_value = S32_MAX;
13083 	/* If we might shift our top bit out, then we know nothing */
13084 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13085 		dst_reg->u32_min_value = 0;
13086 		dst_reg->u32_max_value = U32_MAX;
13087 	} else {
13088 		dst_reg->u32_min_value <<= umin_val;
13089 		dst_reg->u32_max_value <<= umax_val;
13090 	}
13091 }
13092 
13093 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13094 				 struct bpf_reg_state *src_reg)
13095 {
13096 	u32 umax_val = src_reg->u32_max_value;
13097 	u32 umin_val = src_reg->u32_min_value;
13098 	/* u32 alu operation will zext upper bits */
13099 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13100 
13101 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13102 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13103 	/* Not required but being careful mark reg64 bounds as unknown so
13104 	 * that we are forced to pick them up from tnum and zext later and
13105 	 * if some path skips this step we are still safe.
13106 	 */
13107 	__mark_reg64_unbounded(dst_reg);
13108 	__update_reg32_bounds(dst_reg);
13109 }
13110 
13111 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13112 				   u64 umin_val, u64 umax_val)
13113 {
13114 	/* Special case <<32 because it is a common compiler pattern to sign
13115 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13116 	 * positive we know this shift will also be positive so we can track
13117 	 * bounds correctly. Otherwise we lose all sign bit information except
13118 	 * what we can pick up from var_off. Perhaps we can generalize this
13119 	 * later to shifts of any length.
13120 	 */
13121 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13122 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13123 	else
13124 		dst_reg->smax_value = S64_MAX;
13125 
13126 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13127 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13128 	else
13129 		dst_reg->smin_value = S64_MIN;
13130 
13131 	/* If we might shift our top bit out, then we know nothing */
13132 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13133 		dst_reg->umin_value = 0;
13134 		dst_reg->umax_value = U64_MAX;
13135 	} else {
13136 		dst_reg->umin_value <<= umin_val;
13137 		dst_reg->umax_value <<= umax_val;
13138 	}
13139 }
13140 
13141 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13142 			       struct bpf_reg_state *src_reg)
13143 {
13144 	u64 umax_val = src_reg->umax_value;
13145 	u64 umin_val = src_reg->umin_value;
13146 
13147 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13148 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13149 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13150 
13151 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13152 	/* We may learn something more from the var_off */
13153 	__update_reg_bounds(dst_reg);
13154 }
13155 
13156 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13157 				 struct bpf_reg_state *src_reg)
13158 {
13159 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13160 	u32 umax_val = src_reg->u32_max_value;
13161 	u32 umin_val = src_reg->u32_min_value;
13162 
13163 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13164 	 * be negative, then either:
13165 	 * 1) src_reg might be zero, so the sign bit of the result is
13166 	 *    unknown, so we lose our signed bounds
13167 	 * 2) it's known negative, thus the unsigned bounds capture the
13168 	 *    signed bounds
13169 	 * 3) the signed bounds cross zero, so they tell us nothing
13170 	 *    about the result
13171 	 * If the value in dst_reg is known nonnegative, then again the
13172 	 * unsigned bounds capture the signed bounds.
13173 	 * Thus, in all cases it suffices to blow away our signed bounds
13174 	 * and rely on inferring new ones from the unsigned bounds and
13175 	 * var_off of the result.
13176 	 */
13177 	dst_reg->s32_min_value = S32_MIN;
13178 	dst_reg->s32_max_value = S32_MAX;
13179 
13180 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13181 	dst_reg->u32_min_value >>= umax_val;
13182 	dst_reg->u32_max_value >>= umin_val;
13183 
13184 	__mark_reg64_unbounded(dst_reg);
13185 	__update_reg32_bounds(dst_reg);
13186 }
13187 
13188 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13189 			       struct bpf_reg_state *src_reg)
13190 {
13191 	u64 umax_val = src_reg->umax_value;
13192 	u64 umin_val = src_reg->umin_value;
13193 
13194 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13195 	 * be negative, then either:
13196 	 * 1) src_reg might be zero, so the sign bit of the result is
13197 	 *    unknown, so we lose our signed bounds
13198 	 * 2) it's known negative, thus the unsigned bounds capture the
13199 	 *    signed bounds
13200 	 * 3) the signed bounds cross zero, so they tell us nothing
13201 	 *    about the result
13202 	 * If the value in dst_reg is known nonnegative, then again the
13203 	 * unsigned bounds capture the signed bounds.
13204 	 * Thus, in all cases it suffices to blow away our signed bounds
13205 	 * and rely on inferring new ones from the unsigned bounds and
13206 	 * var_off of the result.
13207 	 */
13208 	dst_reg->smin_value = S64_MIN;
13209 	dst_reg->smax_value = S64_MAX;
13210 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13211 	dst_reg->umin_value >>= umax_val;
13212 	dst_reg->umax_value >>= umin_val;
13213 
13214 	/* Its not easy to operate on alu32 bounds here because it depends
13215 	 * on bits being shifted in. Take easy way out and mark unbounded
13216 	 * so we can recalculate later from tnum.
13217 	 */
13218 	__mark_reg32_unbounded(dst_reg);
13219 	__update_reg_bounds(dst_reg);
13220 }
13221 
13222 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13223 				  struct bpf_reg_state *src_reg)
13224 {
13225 	u64 umin_val = src_reg->u32_min_value;
13226 
13227 	/* Upon reaching here, src_known is true and
13228 	 * umax_val is equal to umin_val.
13229 	 */
13230 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13231 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13232 
13233 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13234 
13235 	/* blow away the dst_reg umin_value/umax_value and rely on
13236 	 * dst_reg var_off to refine the result.
13237 	 */
13238 	dst_reg->u32_min_value = 0;
13239 	dst_reg->u32_max_value = U32_MAX;
13240 
13241 	__mark_reg64_unbounded(dst_reg);
13242 	__update_reg32_bounds(dst_reg);
13243 }
13244 
13245 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13246 				struct bpf_reg_state *src_reg)
13247 {
13248 	u64 umin_val = src_reg->umin_value;
13249 
13250 	/* Upon reaching here, src_known is true and umax_val is equal
13251 	 * to umin_val.
13252 	 */
13253 	dst_reg->smin_value >>= umin_val;
13254 	dst_reg->smax_value >>= umin_val;
13255 
13256 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13257 
13258 	/* blow away the dst_reg umin_value/umax_value and rely on
13259 	 * dst_reg var_off to refine the result.
13260 	 */
13261 	dst_reg->umin_value = 0;
13262 	dst_reg->umax_value = U64_MAX;
13263 
13264 	/* Its not easy to operate on alu32 bounds here because it depends
13265 	 * on bits being shifted in from upper 32-bits. Take easy way out
13266 	 * and mark unbounded so we can recalculate later from tnum.
13267 	 */
13268 	__mark_reg32_unbounded(dst_reg);
13269 	__update_reg_bounds(dst_reg);
13270 }
13271 
13272 /* WARNING: This function does calculations on 64-bit values, but the actual
13273  * execution may occur on 32-bit values. Therefore, things like bitshifts
13274  * need extra checks in the 32-bit case.
13275  */
13276 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13277 				      struct bpf_insn *insn,
13278 				      struct bpf_reg_state *dst_reg,
13279 				      struct bpf_reg_state src_reg)
13280 {
13281 	struct bpf_reg_state *regs = cur_regs(env);
13282 	u8 opcode = BPF_OP(insn->code);
13283 	bool src_known;
13284 	s64 smin_val, smax_val;
13285 	u64 umin_val, umax_val;
13286 	s32 s32_min_val, s32_max_val;
13287 	u32 u32_min_val, u32_max_val;
13288 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13289 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13290 	int ret;
13291 
13292 	smin_val = src_reg.smin_value;
13293 	smax_val = src_reg.smax_value;
13294 	umin_val = src_reg.umin_value;
13295 	umax_val = src_reg.umax_value;
13296 
13297 	s32_min_val = src_reg.s32_min_value;
13298 	s32_max_val = src_reg.s32_max_value;
13299 	u32_min_val = src_reg.u32_min_value;
13300 	u32_max_val = src_reg.u32_max_value;
13301 
13302 	if (alu32) {
13303 		src_known = tnum_subreg_is_const(src_reg.var_off);
13304 		if ((src_known &&
13305 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13306 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13307 			/* Taint dst register if offset had invalid bounds
13308 			 * derived from e.g. dead branches.
13309 			 */
13310 			__mark_reg_unknown(env, dst_reg);
13311 			return 0;
13312 		}
13313 	} else {
13314 		src_known = tnum_is_const(src_reg.var_off);
13315 		if ((src_known &&
13316 		     (smin_val != smax_val || umin_val != umax_val)) ||
13317 		    smin_val > smax_val || umin_val > umax_val) {
13318 			/* Taint dst register if offset had invalid bounds
13319 			 * derived from e.g. dead branches.
13320 			 */
13321 			__mark_reg_unknown(env, dst_reg);
13322 			return 0;
13323 		}
13324 	}
13325 
13326 	if (!src_known &&
13327 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13328 		__mark_reg_unknown(env, dst_reg);
13329 		return 0;
13330 	}
13331 
13332 	if (sanitize_needed(opcode)) {
13333 		ret = sanitize_val_alu(env, insn);
13334 		if (ret < 0)
13335 			return sanitize_err(env, insn, ret, NULL, NULL);
13336 	}
13337 
13338 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13339 	 * There are two classes of instructions: The first class we track both
13340 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13341 	 * greatest amount of precision when alu operations are mixed with jmp32
13342 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13343 	 * and BPF_OR. This is possible because these ops have fairly easy to
13344 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13345 	 * See alu32 verifier tests for examples. The second class of
13346 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13347 	 * with regards to tracking sign/unsigned bounds because the bits may
13348 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13349 	 * the reg unbounded in the subreg bound space and use the resulting
13350 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13351 	 */
13352 	switch (opcode) {
13353 	case BPF_ADD:
13354 		scalar32_min_max_add(dst_reg, &src_reg);
13355 		scalar_min_max_add(dst_reg, &src_reg);
13356 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13357 		break;
13358 	case BPF_SUB:
13359 		scalar32_min_max_sub(dst_reg, &src_reg);
13360 		scalar_min_max_sub(dst_reg, &src_reg);
13361 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13362 		break;
13363 	case BPF_MUL:
13364 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13365 		scalar32_min_max_mul(dst_reg, &src_reg);
13366 		scalar_min_max_mul(dst_reg, &src_reg);
13367 		break;
13368 	case BPF_AND:
13369 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13370 		scalar32_min_max_and(dst_reg, &src_reg);
13371 		scalar_min_max_and(dst_reg, &src_reg);
13372 		break;
13373 	case BPF_OR:
13374 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13375 		scalar32_min_max_or(dst_reg, &src_reg);
13376 		scalar_min_max_or(dst_reg, &src_reg);
13377 		break;
13378 	case BPF_XOR:
13379 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13380 		scalar32_min_max_xor(dst_reg, &src_reg);
13381 		scalar_min_max_xor(dst_reg, &src_reg);
13382 		break;
13383 	case BPF_LSH:
13384 		if (umax_val >= insn_bitness) {
13385 			/* Shifts greater than 31 or 63 are undefined.
13386 			 * This includes shifts by a negative number.
13387 			 */
13388 			mark_reg_unknown(env, regs, insn->dst_reg);
13389 			break;
13390 		}
13391 		if (alu32)
13392 			scalar32_min_max_lsh(dst_reg, &src_reg);
13393 		else
13394 			scalar_min_max_lsh(dst_reg, &src_reg);
13395 		break;
13396 	case BPF_RSH:
13397 		if (umax_val >= insn_bitness) {
13398 			/* Shifts greater than 31 or 63 are undefined.
13399 			 * This includes shifts by a negative number.
13400 			 */
13401 			mark_reg_unknown(env, regs, insn->dst_reg);
13402 			break;
13403 		}
13404 		if (alu32)
13405 			scalar32_min_max_rsh(dst_reg, &src_reg);
13406 		else
13407 			scalar_min_max_rsh(dst_reg, &src_reg);
13408 		break;
13409 	case BPF_ARSH:
13410 		if (umax_val >= insn_bitness) {
13411 			/* Shifts greater than 31 or 63 are undefined.
13412 			 * This includes shifts by a negative number.
13413 			 */
13414 			mark_reg_unknown(env, regs, insn->dst_reg);
13415 			break;
13416 		}
13417 		if (alu32)
13418 			scalar32_min_max_arsh(dst_reg, &src_reg);
13419 		else
13420 			scalar_min_max_arsh(dst_reg, &src_reg);
13421 		break;
13422 	default:
13423 		mark_reg_unknown(env, regs, insn->dst_reg);
13424 		break;
13425 	}
13426 
13427 	/* ALU32 ops are zero extended into 64bit register */
13428 	if (alu32)
13429 		zext_32_to_64(dst_reg);
13430 	reg_bounds_sync(dst_reg);
13431 	return 0;
13432 }
13433 
13434 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13435  * and var_off.
13436  */
13437 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13438 				   struct bpf_insn *insn)
13439 {
13440 	struct bpf_verifier_state *vstate = env->cur_state;
13441 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13442 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13443 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13444 	u8 opcode = BPF_OP(insn->code);
13445 	int err;
13446 
13447 	dst_reg = &regs[insn->dst_reg];
13448 	src_reg = NULL;
13449 	if (dst_reg->type != SCALAR_VALUE)
13450 		ptr_reg = dst_reg;
13451 	else
13452 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13453 		 * incorrectly propagated into other registers by find_equal_scalars()
13454 		 */
13455 		dst_reg->id = 0;
13456 	if (BPF_SRC(insn->code) == BPF_X) {
13457 		src_reg = &regs[insn->src_reg];
13458 		if (src_reg->type != SCALAR_VALUE) {
13459 			if (dst_reg->type != SCALAR_VALUE) {
13460 				/* Combining two pointers by any ALU op yields
13461 				 * an arbitrary scalar. Disallow all math except
13462 				 * pointer subtraction
13463 				 */
13464 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13465 					mark_reg_unknown(env, regs, insn->dst_reg);
13466 					return 0;
13467 				}
13468 				verbose(env, "R%d pointer %s pointer prohibited\n",
13469 					insn->dst_reg,
13470 					bpf_alu_string[opcode >> 4]);
13471 				return -EACCES;
13472 			} else {
13473 				/* scalar += pointer
13474 				 * This is legal, but we have to reverse our
13475 				 * src/dest handling in computing the range
13476 				 */
13477 				err = mark_chain_precision(env, insn->dst_reg);
13478 				if (err)
13479 					return err;
13480 				return adjust_ptr_min_max_vals(env, insn,
13481 							       src_reg, dst_reg);
13482 			}
13483 		} else if (ptr_reg) {
13484 			/* pointer += scalar */
13485 			err = mark_chain_precision(env, insn->src_reg);
13486 			if (err)
13487 				return err;
13488 			return adjust_ptr_min_max_vals(env, insn,
13489 						       dst_reg, src_reg);
13490 		} else if (dst_reg->precise) {
13491 			/* if dst_reg is precise, src_reg should be precise as well */
13492 			err = mark_chain_precision(env, insn->src_reg);
13493 			if (err)
13494 				return err;
13495 		}
13496 	} else {
13497 		/* Pretend the src is a reg with a known value, since we only
13498 		 * need to be able to read from this state.
13499 		 */
13500 		off_reg.type = SCALAR_VALUE;
13501 		__mark_reg_known(&off_reg, insn->imm);
13502 		src_reg = &off_reg;
13503 		if (ptr_reg) /* pointer += K */
13504 			return adjust_ptr_min_max_vals(env, insn,
13505 						       ptr_reg, src_reg);
13506 	}
13507 
13508 	/* Got here implies adding two SCALAR_VALUEs */
13509 	if (WARN_ON_ONCE(ptr_reg)) {
13510 		print_verifier_state(env, state, true);
13511 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13512 		return -EINVAL;
13513 	}
13514 	if (WARN_ON(!src_reg)) {
13515 		print_verifier_state(env, state, true);
13516 		verbose(env, "verifier internal error: no src_reg\n");
13517 		return -EINVAL;
13518 	}
13519 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13520 }
13521 
13522 /* check validity of 32-bit and 64-bit arithmetic operations */
13523 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13524 {
13525 	struct bpf_reg_state *regs = cur_regs(env);
13526 	u8 opcode = BPF_OP(insn->code);
13527 	int err;
13528 
13529 	if (opcode == BPF_END || opcode == BPF_NEG) {
13530 		if (opcode == BPF_NEG) {
13531 			if (BPF_SRC(insn->code) != BPF_K ||
13532 			    insn->src_reg != BPF_REG_0 ||
13533 			    insn->off != 0 || insn->imm != 0) {
13534 				verbose(env, "BPF_NEG uses reserved fields\n");
13535 				return -EINVAL;
13536 			}
13537 		} else {
13538 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13539 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13540 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13541 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13542 				verbose(env, "BPF_END uses reserved fields\n");
13543 				return -EINVAL;
13544 			}
13545 		}
13546 
13547 		/* check src operand */
13548 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13549 		if (err)
13550 			return err;
13551 
13552 		if (is_pointer_value(env, insn->dst_reg)) {
13553 			verbose(env, "R%d pointer arithmetic prohibited\n",
13554 				insn->dst_reg);
13555 			return -EACCES;
13556 		}
13557 
13558 		/* check dest operand */
13559 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13560 		if (err)
13561 			return err;
13562 
13563 	} else if (opcode == BPF_MOV) {
13564 
13565 		if (BPF_SRC(insn->code) == BPF_X) {
13566 			if (insn->imm != 0) {
13567 				verbose(env, "BPF_MOV uses reserved fields\n");
13568 				return -EINVAL;
13569 			}
13570 
13571 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13572 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13573 					verbose(env, "BPF_MOV uses reserved fields\n");
13574 					return -EINVAL;
13575 				}
13576 			} else {
13577 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13578 				    insn->off != 32) {
13579 					verbose(env, "BPF_MOV uses reserved fields\n");
13580 					return -EINVAL;
13581 				}
13582 			}
13583 
13584 			/* check src operand */
13585 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13586 			if (err)
13587 				return err;
13588 		} else {
13589 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13590 				verbose(env, "BPF_MOV uses reserved fields\n");
13591 				return -EINVAL;
13592 			}
13593 		}
13594 
13595 		/* check dest operand, mark as required later */
13596 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13597 		if (err)
13598 			return err;
13599 
13600 		if (BPF_SRC(insn->code) == BPF_X) {
13601 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13602 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13603 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13604 				       !tnum_is_const(src_reg->var_off);
13605 
13606 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13607 				if (insn->off == 0) {
13608 					/* case: R1 = R2
13609 					 * copy register state to dest reg
13610 					 */
13611 					if (need_id)
13612 						/* Assign src and dst registers the same ID
13613 						 * that will be used by find_equal_scalars()
13614 						 * to propagate min/max range.
13615 						 */
13616 						src_reg->id = ++env->id_gen;
13617 					copy_register_state(dst_reg, src_reg);
13618 					dst_reg->live |= REG_LIVE_WRITTEN;
13619 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13620 				} else {
13621 					/* case: R1 = (s8, s16 s32)R2 */
13622 					if (is_pointer_value(env, insn->src_reg)) {
13623 						verbose(env,
13624 							"R%d sign-extension part of pointer\n",
13625 							insn->src_reg);
13626 						return -EACCES;
13627 					} else if (src_reg->type == SCALAR_VALUE) {
13628 						bool no_sext;
13629 
13630 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13631 						if (no_sext && need_id)
13632 							src_reg->id = ++env->id_gen;
13633 						copy_register_state(dst_reg, src_reg);
13634 						if (!no_sext)
13635 							dst_reg->id = 0;
13636 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13637 						dst_reg->live |= REG_LIVE_WRITTEN;
13638 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13639 					} else {
13640 						mark_reg_unknown(env, regs, insn->dst_reg);
13641 					}
13642 				}
13643 			} else {
13644 				/* R1 = (u32) R2 */
13645 				if (is_pointer_value(env, insn->src_reg)) {
13646 					verbose(env,
13647 						"R%d partial copy of pointer\n",
13648 						insn->src_reg);
13649 					return -EACCES;
13650 				} else if (src_reg->type == SCALAR_VALUE) {
13651 					if (insn->off == 0) {
13652 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13653 
13654 						if (is_src_reg_u32 && need_id)
13655 							src_reg->id = ++env->id_gen;
13656 						copy_register_state(dst_reg, src_reg);
13657 						/* Make sure ID is cleared if src_reg is not in u32
13658 						 * range otherwise dst_reg min/max could be incorrectly
13659 						 * propagated into src_reg by find_equal_scalars()
13660 						 */
13661 						if (!is_src_reg_u32)
13662 							dst_reg->id = 0;
13663 						dst_reg->live |= REG_LIVE_WRITTEN;
13664 						dst_reg->subreg_def = env->insn_idx + 1;
13665 					} else {
13666 						/* case: W1 = (s8, s16)W2 */
13667 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13668 
13669 						if (no_sext && need_id)
13670 							src_reg->id = ++env->id_gen;
13671 						copy_register_state(dst_reg, src_reg);
13672 						if (!no_sext)
13673 							dst_reg->id = 0;
13674 						dst_reg->live |= REG_LIVE_WRITTEN;
13675 						dst_reg->subreg_def = env->insn_idx + 1;
13676 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13677 					}
13678 				} else {
13679 					mark_reg_unknown(env, regs,
13680 							 insn->dst_reg);
13681 				}
13682 				zext_32_to_64(dst_reg);
13683 				reg_bounds_sync(dst_reg);
13684 			}
13685 		} else {
13686 			/* case: R = imm
13687 			 * remember the value we stored into this reg
13688 			 */
13689 			/* clear any state __mark_reg_known doesn't set */
13690 			mark_reg_unknown(env, regs, insn->dst_reg);
13691 			regs[insn->dst_reg].type = SCALAR_VALUE;
13692 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13693 				__mark_reg_known(regs + insn->dst_reg,
13694 						 insn->imm);
13695 			} else {
13696 				__mark_reg_known(regs + insn->dst_reg,
13697 						 (u32)insn->imm);
13698 			}
13699 		}
13700 
13701 	} else if (opcode > BPF_END) {
13702 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13703 		return -EINVAL;
13704 
13705 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13706 
13707 		if (BPF_SRC(insn->code) == BPF_X) {
13708 			if (insn->imm != 0 || insn->off > 1 ||
13709 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13710 				verbose(env, "BPF_ALU uses reserved fields\n");
13711 				return -EINVAL;
13712 			}
13713 			/* check src1 operand */
13714 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13715 			if (err)
13716 				return err;
13717 		} else {
13718 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13719 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13720 				verbose(env, "BPF_ALU uses reserved fields\n");
13721 				return -EINVAL;
13722 			}
13723 		}
13724 
13725 		/* check src2 operand */
13726 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13727 		if (err)
13728 			return err;
13729 
13730 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13731 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13732 			verbose(env, "div by zero\n");
13733 			return -EINVAL;
13734 		}
13735 
13736 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13737 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13738 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13739 
13740 			if (insn->imm < 0 || insn->imm >= size) {
13741 				verbose(env, "invalid shift %d\n", insn->imm);
13742 				return -EINVAL;
13743 			}
13744 		}
13745 
13746 		/* check dest operand */
13747 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13748 		if (err)
13749 			return err;
13750 
13751 		return adjust_reg_min_max_vals(env, insn);
13752 	}
13753 
13754 	return 0;
13755 }
13756 
13757 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13758 				   struct bpf_reg_state *dst_reg,
13759 				   enum bpf_reg_type type,
13760 				   bool range_right_open)
13761 {
13762 	struct bpf_func_state *state;
13763 	struct bpf_reg_state *reg;
13764 	int new_range;
13765 
13766 	if (dst_reg->off < 0 ||
13767 	    (dst_reg->off == 0 && range_right_open))
13768 		/* This doesn't give us any range */
13769 		return;
13770 
13771 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13772 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13773 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13774 		 * than pkt_end, but that's because it's also less than pkt.
13775 		 */
13776 		return;
13777 
13778 	new_range = dst_reg->off;
13779 	if (range_right_open)
13780 		new_range++;
13781 
13782 	/* Examples for register markings:
13783 	 *
13784 	 * pkt_data in dst register:
13785 	 *
13786 	 *   r2 = r3;
13787 	 *   r2 += 8;
13788 	 *   if (r2 > pkt_end) goto <handle exception>
13789 	 *   <access okay>
13790 	 *
13791 	 *   r2 = r3;
13792 	 *   r2 += 8;
13793 	 *   if (r2 < pkt_end) goto <access okay>
13794 	 *   <handle exception>
13795 	 *
13796 	 *   Where:
13797 	 *     r2 == dst_reg, pkt_end == src_reg
13798 	 *     r2=pkt(id=n,off=8,r=0)
13799 	 *     r3=pkt(id=n,off=0,r=0)
13800 	 *
13801 	 * pkt_data in src register:
13802 	 *
13803 	 *   r2 = r3;
13804 	 *   r2 += 8;
13805 	 *   if (pkt_end >= r2) goto <access okay>
13806 	 *   <handle exception>
13807 	 *
13808 	 *   r2 = r3;
13809 	 *   r2 += 8;
13810 	 *   if (pkt_end <= r2) goto <handle exception>
13811 	 *   <access okay>
13812 	 *
13813 	 *   Where:
13814 	 *     pkt_end == dst_reg, r2 == src_reg
13815 	 *     r2=pkt(id=n,off=8,r=0)
13816 	 *     r3=pkt(id=n,off=0,r=0)
13817 	 *
13818 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13819 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13820 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13821 	 * the check.
13822 	 */
13823 
13824 	/* If our ids match, then we must have the same max_value.  And we
13825 	 * don't care about the other reg's fixed offset, since if it's too big
13826 	 * the range won't allow anything.
13827 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13828 	 */
13829 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13830 		if (reg->type == type && reg->id == dst_reg->id)
13831 			/* keep the maximum range already checked */
13832 			reg->range = max(reg->range, new_range);
13833 	}));
13834 }
13835 
13836 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13837 {
13838 	struct tnum subreg = tnum_subreg(reg->var_off);
13839 	s32 sval = (s32)val;
13840 
13841 	switch (opcode) {
13842 	case BPF_JEQ:
13843 		if (tnum_is_const(subreg))
13844 			return !!tnum_equals_const(subreg, val);
13845 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13846 			return 0;
13847 		break;
13848 	case BPF_JNE:
13849 		if (tnum_is_const(subreg))
13850 			return !tnum_equals_const(subreg, val);
13851 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13852 			return 1;
13853 		break;
13854 	case BPF_JSET:
13855 		if ((~subreg.mask & subreg.value) & val)
13856 			return 1;
13857 		if (!((subreg.mask | subreg.value) & val))
13858 			return 0;
13859 		break;
13860 	case BPF_JGT:
13861 		if (reg->u32_min_value > val)
13862 			return 1;
13863 		else if (reg->u32_max_value <= val)
13864 			return 0;
13865 		break;
13866 	case BPF_JSGT:
13867 		if (reg->s32_min_value > sval)
13868 			return 1;
13869 		else if (reg->s32_max_value <= sval)
13870 			return 0;
13871 		break;
13872 	case BPF_JLT:
13873 		if (reg->u32_max_value < val)
13874 			return 1;
13875 		else if (reg->u32_min_value >= val)
13876 			return 0;
13877 		break;
13878 	case BPF_JSLT:
13879 		if (reg->s32_max_value < sval)
13880 			return 1;
13881 		else if (reg->s32_min_value >= sval)
13882 			return 0;
13883 		break;
13884 	case BPF_JGE:
13885 		if (reg->u32_min_value >= val)
13886 			return 1;
13887 		else if (reg->u32_max_value < val)
13888 			return 0;
13889 		break;
13890 	case BPF_JSGE:
13891 		if (reg->s32_min_value >= sval)
13892 			return 1;
13893 		else if (reg->s32_max_value < sval)
13894 			return 0;
13895 		break;
13896 	case BPF_JLE:
13897 		if (reg->u32_max_value <= val)
13898 			return 1;
13899 		else if (reg->u32_min_value > val)
13900 			return 0;
13901 		break;
13902 	case BPF_JSLE:
13903 		if (reg->s32_max_value <= sval)
13904 			return 1;
13905 		else if (reg->s32_min_value > sval)
13906 			return 0;
13907 		break;
13908 	}
13909 
13910 	return -1;
13911 }
13912 
13913 
13914 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13915 {
13916 	s64 sval = (s64)val;
13917 
13918 	switch (opcode) {
13919 	case BPF_JEQ:
13920 		if (tnum_is_const(reg->var_off))
13921 			return !!tnum_equals_const(reg->var_off, val);
13922 		else if (val < reg->umin_value || val > reg->umax_value)
13923 			return 0;
13924 		break;
13925 	case BPF_JNE:
13926 		if (tnum_is_const(reg->var_off))
13927 			return !tnum_equals_const(reg->var_off, val);
13928 		else if (val < reg->umin_value || val > reg->umax_value)
13929 			return 1;
13930 		break;
13931 	case BPF_JSET:
13932 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13933 			return 1;
13934 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13935 			return 0;
13936 		break;
13937 	case BPF_JGT:
13938 		if (reg->umin_value > val)
13939 			return 1;
13940 		else if (reg->umax_value <= val)
13941 			return 0;
13942 		break;
13943 	case BPF_JSGT:
13944 		if (reg->smin_value > sval)
13945 			return 1;
13946 		else if (reg->smax_value <= sval)
13947 			return 0;
13948 		break;
13949 	case BPF_JLT:
13950 		if (reg->umax_value < val)
13951 			return 1;
13952 		else if (reg->umin_value >= val)
13953 			return 0;
13954 		break;
13955 	case BPF_JSLT:
13956 		if (reg->smax_value < sval)
13957 			return 1;
13958 		else if (reg->smin_value >= sval)
13959 			return 0;
13960 		break;
13961 	case BPF_JGE:
13962 		if (reg->umin_value >= val)
13963 			return 1;
13964 		else if (reg->umax_value < val)
13965 			return 0;
13966 		break;
13967 	case BPF_JSGE:
13968 		if (reg->smin_value >= sval)
13969 			return 1;
13970 		else if (reg->smax_value < sval)
13971 			return 0;
13972 		break;
13973 	case BPF_JLE:
13974 		if (reg->umax_value <= val)
13975 			return 1;
13976 		else if (reg->umin_value > val)
13977 			return 0;
13978 		break;
13979 	case BPF_JSLE:
13980 		if (reg->smax_value <= sval)
13981 			return 1;
13982 		else if (reg->smin_value > sval)
13983 			return 0;
13984 		break;
13985 	}
13986 
13987 	return -1;
13988 }
13989 
13990 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13991  * and return:
13992  *  1 - branch will be taken and "goto target" will be executed
13993  *  0 - branch will not be taken and fall-through to next insn
13994  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13995  *      range [0,10]
13996  */
13997 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13998 			   bool is_jmp32)
13999 {
14000 	if (__is_pointer_value(false, reg)) {
14001 		if (!reg_not_null(reg))
14002 			return -1;
14003 
14004 		/* If pointer is valid tests against zero will fail so we can
14005 		 * use this to direct branch taken.
14006 		 */
14007 		if (val != 0)
14008 			return -1;
14009 
14010 		switch (opcode) {
14011 		case BPF_JEQ:
14012 			return 0;
14013 		case BPF_JNE:
14014 			return 1;
14015 		default:
14016 			return -1;
14017 		}
14018 	}
14019 
14020 	if (is_jmp32)
14021 		return is_branch32_taken(reg, val, opcode);
14022 	return is_branch64_taken(reg, val, opcode);
14023 }
14024 
14025 static int flip_opcode(u32 opcode)
14026 {
14027 	/* How can we transform "a <op> b" into "b <op> a"? */
14028 	static const u8 opcode_flip[16] = {
14029 		/* these stay the same */
14030 		[BPF_JEQ  >> 4] = BPF_JEQ,
14031 		[BPF_JNE  >> 4] = BPF_JNE,
14032 		[BPF_JSET >> 4] = BPF_JSET,
14033 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14034 		[BPF_JGE  >> 4] = BPF_JLE,
14035 		[BPF_JGT  >> 4] = BPF_JLT,
14036 		[BPF_JLE  >> 4] = BPF_JGE,
14037 		[BPF_JLT  >> 4] = BPF_JGT,
14038 		[BPF_JSGE >> 4] = BPF_JSLE,
14039 		[BPF_JSGT >> 4] = BPF_JSLT,
14040 		[BPF_JSLE >> 4] = BPF_JSGE,
14041 		[BPF_JSLT >> 4] = BPF_JSGT
14042 	};
14043 	return opcode_flip[opcode >> 4];
14044 }
14045 
14046 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14047 				   struct bpf_reg_state *src_reg,
14048 				   u8 opcode)
14049 {
14050 	struct bpf_reg_state *pkt;
14051 
14052 	if (src_reg->type == PTR_TO_PACKET_END) {
14053 		pkt = dst_reg;
14054 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14055 		pkt = src_reg;
14056 		opcode = flip_opcode(opcode);
14057 	} else {
14058 		return -1;
14059 	}
14060 
14061 	if (pkt->range >= 0)
14062 		return -1;
14063 
14064 	switch (opcode) {
14065 	case BPF_JLE:
14066 		/* pkt <= pkt_end */
14067 		fallthrough;
14068 	case BPF_JGT:
14069 		/* pkt > pkt_end */
14070 		if (pkt->range == BEYOND_PKT_END)
14071 			/* pkt has at last one extra byte beyond pkt_end */
14072 			return opcode == BPF_JGT;
14073 		break;
14074 	case BPF_JLT:
14075 		/* pkt < pkt_end */
14076 		fallthrough;
14077 	case BPF_JGE:
14078 		/* pkt >= pkt_end */
14079 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14080 			return opcode == BPF_JGE;
14081 		break;
14082 	}
14083 	return -1;
14084 }
14085 
14086 /* Adjusts the register min/max values in the case that the dst_reg is the
14087  * variable register that we are working on, and src_reg is a constant or we're
14088  * simply doing a BPF_K check.
14089  * In JEQ/JNE cases we also adjust the var_off values.
14090  */
14091 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14092 			    struct bpf_reg_state *false_reg,
14093 			    u64 val, u32 val32,
14094 			    u8 opcode, bool is_jmp32)
14095 {
14096 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14097 	struct tnum false_64off = false_reg->var_off;
14098 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14099 	struct tnum true_64off = true_reg->var_off;
14100 	s64 sval = (s64)val;
14101 	s32 sval32 = (s32)val32;
14102 
14103 	/* If the dst_reg is a pointer, we can't learn anything about its
14104 	 * variable offset from the compare (unless src_reg were a pointer into
14105 	 * the same object, but we don't bother with that.
14106 	 * Since false_reg and true_reg have the same type by construction, we
14107 	 * only need to check one of them for pointerness.
14108 	 */
14109 	if (__is_pointer_value(false, false_reg))
14110 		return;
14111 
14112 	switch (opcode) {
14113 	/* JEQ/JNE comparison doesn't change the register equivalence.
14114 	 *
14115 	 * r1 = r2;
14116 	 * if (r1 == 42) goto label;
14117 	 * ...
14118 	 * label: // here both r1 and r2 are known to be 42.
14119 	 *
14120 	 * Hence when marking register as known preserve it's ID.
14121 	 */
14122 	case BPF_JEQ:
14123 		if (is_jmp32) {
14124 			__mark_reg32_known(true_reg, val32);
14125 			true_32off = tnum_subreg(true_reg->var_off);
14126 		} else {
14127 			___mark_reg_known(true_reg, val);
14128 			true_64off = true_reg->var_off;
14129 		}
14130 		break;
14131 	case BPF_JNE:
14132 		if (is_jmp32) {
14133 			__mark_reg32_known(false_reg, val32);
14134 			false_32off = tnum_subreg(false_reg->var_off);
14135 		} else {
14136 			___mark_reg_known(false_reg, val);
14137 			false_64off = false_reg->var_off;
14138 		}
14139 		break;
14140 	case BPF_JSET:
14141 		if (is_jmp32) {
14142 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14143 			if (is_power_of_2(val32))
14144 				true_32off = tnum_or(true_32off,
14145 						     tnum_const(val32));
14146 		} else {
14147 			false_64off = tnum_and(false_64off, tnum_const(~val));
14148 			if (is_power_of_2(val))
14149 				true_64off = tnum_or(true_64off,
14150 						     tnum_const(val));
14151 		}
14152 		break;
14153 	case BPF_JGE:
14154 	case BPF_JGT:
14155 	{
14156 		if (is_jmp32) {
14157 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14158 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14159 
14160 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14161 						       false_umax);
14162 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14163 						      true_umin);
14164 		} else {
14165 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14166 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14167 
14168 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14169 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14170 		}
14171 		break;
14172 	}
14173 	case BPF_JSGE:
14174 	case BPF_JSGT:
14175 	{
14176 		if (is_jmp32) {
14177 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14178 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14179 
14180 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14181 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14182 		} else {
14183 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14184 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14185 
14186 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14187 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14188 		}
14189 		break;
14190 	}
14191 	case BPF_JLE:
14192 	case BPF_JLT:
14193 	{
14194 		if (is_jmp32) {
14195 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14196 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14197 
14198 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14199 						       false_umin);
14200 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14201 						      true_umax);
14202 		} else {
14203 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14204 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14205 
14206 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14207 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14208 		}
14209 		break;
14210 	}
14211 	case BPF_JSLE:
14212 	case BPF_JSLT:
14213 	{
14214 		if (is_jmp32) {
14215 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14216 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14217 
14218 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14219 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14220 		} else {
14221 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14222 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14223 
14224 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14225 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14226 		}
14227 		break;
14228 	}
14229 	default:
14230 		return;
14231 	}
14232 
14233 	if (is_jmp32) {
14234 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14235 					     tnum_subreg(false_32off));
14236 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14237 					    tnum_subreg(true_32off));
14238 		__reg_combine_32_into_64(false_reg);
14239 		__reg_combine_32_into_64(true_reg);
14240 	} else {
14241 		false_reg->var_off = false_64off;
14242 		true_reg->var_off = true_64off;
14243 		__reg_combine_64_into_32(false_reg);
14244 		__reg_combine_64_into_32(true_reg);
14245 	}
14246 }
14247 
14248 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14249  * the variable reg.
14250  */
14251 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14252 				struct bpf_reg_state *false_reg,
14253 				u64 val, u32 val32,
14254 				u8 opcode, bool is_jmp32)
14255 {
14256 	opcode = flip_opcode(opcode);
14257 	/* This uses zero as "not present in table"; luckily the zero opcode,
14258 	 * BPF_JA, can't get here.
14259 	 */
14260 	if (opcode)
14261 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14262 }
14263 
14264 /* Regs are known to be equal, so intersect their min/max/var_off */
14265 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14266 				  struct bpf_reg_state *dst_reg)
14267 {
14268 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14269 							dst_reg->umin_value);
14270 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14271 							dst_reg->umax_value);
14272 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14273 							dst_reg->smin_value);
14274 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14275 							dst_reg->smax_value);
14276 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14277 							     dst_reg->var_off);
14278 	reg_bounds_sync(src_reg);
14279 	reg_bounds_sync(dst_reg);
14280 }
14281 
14282 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14283 				struct bpf_reg_state *true_dst,
14284 				struct bpf_reg_state *false_src,
14285 				struct bpf_reg_state *false_dst,
14286 				u8 opcode)
14287 {
14288 	switch (opcode) {
14289 	case BPF_JEQ:
14290 		__reg_combine_min_max(true_src, true_dst);
14291 		break;
14292 	case BPF_JNE:
14293 		__reg_combine_min_max(false_src, false_dst);
14294 		break;
14295 	}
14296 }
14297 
14298 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14299 				 struct bpf_reg_state *reg, u32 id,
14300 				 bool is_null)
14301 {
14302 	if (type_may_be_null(reg->type) && reg->id == id &&
14303 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14304 		/* Old offset (both fixed and variable parts) should have been
14305 		 * known-zero, because we don't allow pointer arithmetic on
14306 		 * pointers that might be NULL. If we see this happening, don't
14307 		 * convert the register.
14308 		 *
14309 		 * But in some cases, some helpers that return local kptrs
14310 		 * advance offset for the returned pointer. In those cases, it
14311 		 * is fine to expect to see reg->off.
14312 		 */
14313 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14314 			return;
14315 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14316 		    WARN_ON_ONCE(reg->off))
14317 			return;
14318 
14319 		if (is_null) {
14320 			reg->type = SCALAR_VALUE;
14321 			/* We don't need id and ref_obj_id from this point
14322 			 * onwards anymore, thus we should better reset it,
14323 			 * so that state pruning has chances to take effect.
14324 			 */
14325 			reg->id = 0;
14326 			reg->ref_obj_id = 0;
14327 
14328 			return;
14329 		}
14330 
14331 		mark_ptr_not_null_reg(reg);
14332 
14333 		if (!reg_may_point_to_spin_lock(reg)) {
14334 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14335 			 * in release_reference().
14336 			 *
14337 			 * reg->id is still used by spin_lock ptr. Other
14338 			 * than spin_lock ptr type, reg->id can be reset.
14339 			 */
14340 			reg->id = 0;
14341 		}
14342 	}
14343 }
14344 
14345 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14346  * be folded together at some point.
14347  */
14348 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14349 				  bool is_null)
14350 {
14351 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14352 	struct bpf_reg_state *regs = state->regs, *reg;
14353 	u32 ref_obj_id = regs[regno].ref_obj_id;
14354 	u32 id = regs[regno].id;
14355 
14356 	if (ref_obj_id && ref_obj_id == id && is_null)
14357 		/* regs[regno] is in the " == NULL" branch.
14358 		 * No one could have freed the reference state before
14359 		 * doing the NULL check.
14360 		 */
14361 		WARN_ON_ONCE(release_reference_state(state, id));
14362 
14363 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14364 		mark_ptr_or_null_reg(state, reg, id, is_null);
14365 	}));
14366 }
14367 
14368 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14369 				   struct bpf_reg_state *dst_reg,
14370 				   struct bpf_reg_state *src_reg,
14371 				   struct bpf_verifier_state *this_branch,
14372 				   struct bpf_verifier_state *other_branch)
14373 {
14374 	if (BPF_SRC(insn->code) != BPF_X)
14375 		return false;
14376 
14377 	/* Pointers are always 64-bit. */
14378 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14379 		return false;
14380 
14381 	switch (BPF_OP(insn->code)) {
14382 	case BPF_JGT:
14383 		if ((dst_reg->type == PTR_TO_PACKET &&
14384 		     src_reg->type == PTR_TO_PACKET_END) ||
14385 		    (dst_reg->type == PTR_TO_PACKET_META &&
14386 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14387 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14388 			find_good_pkt_pointers(this_branch, dst_reg,
14389 					       dst_reg->type, false);
14390 			mark_pkt_end(other_branch, insn->dst_reg, true);
14391 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14392 			    src_reg->type == PTR_TO_PACKET) ||
14393 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14394 			    src_reg->type == PTR_TO_PACKET_META)) {
14395 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14396 			find_good_pkt_pointers(other_branch, src_reg,
14397 					       src_reg->type, true);
14398 			mark_pkt_end(this_branch, insn->src_reg, false);
14399 		} else {
14400 			return false;
14401 		}
14402 		break;
14403 	case BPF_JLT:
14404 		if ((dst_reg->type == PTR_TO_PACKET &&
14405 		     src_reg->type == PTR_TO_PACKET_END) ||
14406 		    (dst_reg->type == PTR_TO_PACKET_META &&
14407 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14408 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14409 			find_good_pkt_pointers(other_branch, dst_reg,
14410 					       dst_reg->type, true);
14411 			mark_pkt_end(this_branch, insn->dst_reg, false);
14412 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14413 			    src_reg->type == PTR_TO_PACKET) ||
14414 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14415 			    src_reg->type == PTR_TO_PACKET_META)) {
14416 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14417 			find_good_pkt_pointers(this_branch, src_reg,
14418 					       src_reg->type, false);
14419 			mark_pkt_end(other_branch, insn->src_reg, true);
14420 		} else {
14421 			return false;
14422 		}
14423 		break;
14424 	case BPF_JGE:
14425 		if ((dst_reg->type == PTR_TO_PACKET &&
14426 		     src_reg->type == PTR_TO_PACKET_END) ||
14427 		    (dst_reg->type == PTR_TO_PACKET_META &&
14428 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14429 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14430 			find_good_pkt_pointers(this_branch, dst_reg,
14431 					       dst_reg->type, true);
14432 			mark_pkt_end(other_branch, insn->dst_reg, false);
14433 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14434 			    src_reg->type == PTR_TO_PACKET) ||
14435 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14436 			    src_reg->type == PTR_TO_PACKET_META)) {
14437 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14438 			find_good_pkt_pointers(other_branch, src_reg,
14439 					       src_reg->type, false);
14440 			mark_pkt_end(this_branch, insn->src_reg, true);
14441 		} else {
14442 			return false;
14443 		}
14444 		break;
14445 	case BPF_JLE:
14446 		if ((dst_reg->type == PTR_TO_PACKET &&
14447 		     src_reg->type == PTR_TO_PACKET_END) ||
14448 		    (dst_reg->type == PTR_TO_PACKET_META &&
14449 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14450 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14451 			find_good_pkt_pointers(other_branch, dst_reg,
14452 					       dst_reg->type, false);
14453 			mark_pkt_end(this_branch, insn->dst_reg, true);
14454 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14455 			    src_reg->type == PTR_TO_PACKET) ||
14456 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14457 			    src_reg->type == PTR_TO_PACKET_META)) {
14458 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14459 			find_good_pkt_pointers(this_branch, src_reg,
14460 					       src_reg->type, true);
14461 			mark_pkt_end(other_branch, insn->src_reg, false);
14462 		} else {
14463 			return false;
14464 		}
14465 		break;
14466 	default:
14467 		return false;
14468 	}
14469 
14470 	return true;
14471 }
14472 
14473 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14474 			       struct bpf_reg_state *known_reg)
14475 {
14476 	struct bpf_func_state *state;
14477 	struct bpf_reg_state *reg;
14478 
14479 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14480 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14481 			copy_register_state(reg, known_reg);
14482 	}));
14483 }
14484 
14485 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14486 			     struct bpf_insn *insn, int *insn_idx)
14487 {
14488 	struct bpf_verifier_state *this_branch = env->cur_state;
14489 	struct bpf_verifier_state *other_branch;
14490 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14491 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14492 	struct bpf_reg_state *eq_branch_regs;
14493 	u8 opcode = BPF_OP(insn->code);
14494 	bool is_jmp32;
14495 	int pred = -1;
14496 	int err;
14497 
14498 	/* Only conditional jumps are expected to reach here. */
14499 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14500 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14501 		return -EINVAL;
14502 	}
14503 
14504 	/* check src2 operand */
14505 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14506 	if (err)
14507 		return err;
14508 
14509 	dst_reg = &regs[insn->dst_reg];
14510 	if (BPF_SRC(insn->code) == BPF_X) {
14511 		if (insn->imm != 0) {
14512 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14513 			return -EINVAL;
14514 		}
14515 
14516 		/* check src1 operand */
14517 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14518 		if (err)
14519 			return err;
14520 
14521 		src_reg = &regs[insn->src_reg];
14522 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14523 		    is_pointer_value(env, insn->src_reg)) {
14524 			verbose(env, "R%d pointer comparison prohibited\n",
14525 				insn->src_reg);
14526 			return -EACCES;
14527 		}
14528 	} else {
14529 		if (insn->src_reg != BPF_REG_0) {
14530 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14531 			return -EINVAL;
14532 		}
14533 	}
14534 
14535 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14536 
14537 	if (BPF_SRC(insn->code) == BPF_K) {
14538 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14539 	} else if (src_reg->type == SCALAR_VALUE &&
14540 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14541 		pred = is_branch_taken(dst_reg,
14542 				       tnum_subreg(src_reg->var_off).value,
14543 				       opcode,
14544 				       is_jmp32);
14545 	} else if (src_reg->type == SCALAR_VALUE &&
14546 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14547 		pred = is_branch_taken(dst_reg,
14548 				       src_reg->var_off.value,
14549 				       opcode,
14550 				       is_jmp32);
14551 	} else if (dst_reg->type == SCALAR_VALUE &&
14552 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14553 		pred = is_branch_taken(src_reg,
14554 				       tnum_subreg(dst_reg->var_off).value,
14555 				       flip_opcode(opcode),
14556 				       is_jmp32);
14557 	} else if (dst_reg->type == SCALAR_VALUE &&
14558 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14559 		pred = is_branch_taken(src_reg,
14560 				       dst_reg->var_off.value,
14561 				       flip_opcode(opcode),
14562 				       is_jmp32);
14563 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14564 		   reg_is_pkt_pointer_any(src_reg) &&
14565 		   !is_jmp32) {
14566 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14567 	}
14568 
14569 	if (pred >= 0) {
14570 		/* If we get here with a dst_reg pointer type it is because
14571 		 * above is_branch_taken() special cased the 0 comparison.
14572 		 */
14573 		if (!__is_pointer_value(false, dst_reg))
14574 			err = mark_chain_precision(env, insn->dst_reg);
14575 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14576 		    !__is_pointer_value(false, src_reg))
14577 			err = mark_chain_precision(env, insn->src_reg);
14578 		if (err)
14579 			return err;
14580 	}
14581 
14582 	if (pred == 1) {
14583 		/* Only follow the goto, ignore fall-through. If needed, push
14584 		 * the fall-through branch for simulation under speculative
14585 		 * execution.
14586 		 */
14587 		if (!env->bypass_spec_v1 &&
14588 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14589 					       *insn_idx))
14590 			return -EFAULT;
14591 		if (env->log.level & BPF_LOG_LEVEL)
14592 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14593 		*insn_idx += insn->off;
14594 		return 0;
14595 	} else if (pred == 0) {
14596 		/* Only follow the fall-through branch, since that's where the
14597 		 * program will go. If needed, push the goto branch for
14598 		 * simulation under speculative execution.
14599 		 */
14600 		if (!env->bypass_spec_v1 &&
14601 		    !sanitize_speculative_path(env, insn,
14602 					       *insn_idx + insn->off + 1,
14603 					       *insn_idx))
14604 			return -EFAULT;
14605 		if (env->log.level & BPF_LOG_LEVEL)
14606 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14607 		return 0;
14608 	}
14609 
14610 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14611 				  false);
14612 	if (!other_branch)
14613 		return -EFAULT;
14614 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14615 
14616 	/* detect if we are comparing against a constant value so we can adjust
14617 	 * our min/max values for our dst register.
14618 	 * this is only legit if both are scalars (or pointers to the same
14619 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14620 	 * because otherwise the different base pointers mean the offsets aren't
14621 	 * comparable.
14622 	 */
14623 	if (BPF_SRC(insn->code) == BPF_X) {
14624 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14625 
14626 		if (dst_reg->type == SCALAR_VALUE &&
14627 		    src_reg->type == SCALAR_VALUE) {
14628 			if (tnum_is_const(src_reg->var_off) ||
14629 			    (is_jmp32 &&
14630 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14631 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14632 						dst_reg,
14633 						src_reg->var_off.value,
14634 						tnum_subreg(src_reg->var_off).value,
14635 						opcode, is_jmp32);
14636 			else if (tnum_is_const(dst_reg->var_off) ||
14637 				 (is_jmp32 &&
14638 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14639 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14640 						    src_reg,
14641 						    dst_reg->var_off.value,
14642 						    tnum_subreg(dst_reg->var_off).value,
14643 						    opcode, is_jmp32);
14644 			else if (!is_jmp32 &&
14645 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14646 				/* Comparing for equality, we can combine knowledge */
14647 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14648 						    &other_branch_regs[insn->dst_reg],
14649 						    src_reg, dst_reg, opcode);
14650 			if (src_reg->id &&
14651 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14652 				find_equal_scalars(this_branch, src_reg);
14653 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14654 			}
14655 
14656 		}
14657 	} else if (dst_reg->type == SCALAR_VALUE) {
14658 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14659 					dst_reg, insn->imm, (u32)insn->imm,
14660 					opcode, is_jmp32);
14661 	}
14662 
14663 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14664 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14665 		find_equal_scalars(this_branch, dst_reg);
14666 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14667 	}
14668 
14669 	/* if one pointer register is compared to another pointer
14670 	 * register check if PTR_MAYBE_NULL could be lifted.
14671 	 * E.g. register A - maybe null
14672 	 *      register B - not null
14673 	 * for JNE A, B, ... - A is not null in the false branch;
14674 	 * for JEQ A, B, ... - A is not null in the true branch.
14675 	 *
14676 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14677 	 * not need to be null checked by the BPF program, i.e.,
14678 	 * could be null even without PTR_MAYBE_NULL marking, so
14679 	 * only propagate nullness when neither reg is that type.
14680 	 */
14681 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14682 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14683 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14684 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14685 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14686 		eq_branch_regs = NULL;
14687 		switch (opcode) {
14688 		case BPF_JEQ:
14689 			eq_branch_regs = other_branch_regs;
14690 			break;
14691 		case BPF_JNE:
14692 			eq_branch_regs = regs;
14693 			break;
14694 		default:
14695 			/* do nothing */
14696 			break;
14697 		}
14698 		if (eq_branch_regs) {
14699 			if (type_may_be_null(src_reg->type))
14700 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14701 			else
14702 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14703 		}
14704 	}
14705 
14706 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14707 	 * NOTE: these optimizations below are related with pointer comparison
14708 	 *       which will never be JMP32.
14709 	 */
14710 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14711 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14712 	    type_may_be_null(dst_reg->type)) {
14713 		/* Mark all identical registers in each branch as either
14714 		 * safe or unknown depending R == 0 or R != 0 conditional.
14715 		 */
14716 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14717 				      opcode == BPF_JNE);
14718 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14719 				      opcode == BPF_JEQ);
14720 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14721 					   this_branch, other_branch) &&
14722 		   is_pointer_value(env, insn->dst_reg)) {
14723 		verbose(env, "R%d pointer comparison prohibited\n",
14724 			insn->dst_reg);
14725 		return -EACCES;
14726 	}
14727 	if (env->log.level & BPF_LOG_LEVEL)
14728 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14729 	return 0;
14730 }
14731 
14732 /* verify BPF_LD_IMM64 instruction */
14733 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14734 {
14735 	struct bpf_insn_aux_data *aux = cur_aux(env);
14736 	struct bpf_reg_state *regs = cur_regs(env);
14737 	struct bpf_reg_state *dst_reg;
14738 	struct bpf_map *map;
14739 	int err;
14740 
14741 	if (BPF_SIZE(insn->code) != BPF_DW) {
14742 		verbose(env, "invalid BPF_LD_IMM insn\n");
14743 		return -EINVAL;
14744 	}
14745 	if (insn->off != 0) {
14746 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14747 		return -EINVAL;
14748 	}
14749 
14750 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14751 	if (err)
14752 		return err;
14753 
14754 	dst_reg = &regs[insn->dst_reg];
14755 	if (insn->src_reg == 0) {
14756 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14757 
14758 		dst_reg->type = SCALAR_VALUE;
14759 		__mark_reg_known(&regs[insn->dst_reg], imm);
14760 		return 0;
14761 	}
14762 
14763 	/* All special src_reg cases are listed below. From this point onwards
14764 	 * we either succeed and assign a corresponding dst_reg->type after
14765 	 * zeroing the offset, or fail and reject the program.
14766 	 */
14767 	mark_reg_known_zero(env, regs, insn->dst_reg);
14768 
14769 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14770 		dst_reg->type = aux->btf_var.reg_type;
14771 		switch (base_type(dst_reg->type)) {
14772 		case PTR_TO_MEM:
14773 			dst_reg->mem_size = aux->btf_var.mem_size;
14774 			break;
14775 		case PTR_TO_BTF_ID:
14776 			dst_reg->btf = aux->btf_var.btf;
14777 			dst_reg->btf_id = aux->btf_var.btf_id;
14778 			break;
14779 		default:
14780 			verbose(env, "bpf verifier is misconfigured\n");
14781 			return -EFAULT;
14782 		}
14783 		return 0;
14784 	}
14785 
14786 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14787 		struct bpf_prog_aux *aux = env->prog->aux;
14788 		u32 subprogno = find_subprog(env,
14789 					     env->insn_idx + insn->imm + 1);
14790 
14791 		if (!aux->func_info) {
14792 			verbose(env, "missing btf func_info\n");
14793 			return -EINVAL;
14794 		}
14795 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14796 			verbose(env, "callback function not static\n");
14797 			return -EINVAL;
14798 		}
14799 
14800 		dst_reg->type = PTR_TO_FUNC;
14801 		dst_reg->subprogno = subprogno;
14802 		return 0;
14803 	}
14804 
14805 	map = env->used_maps[aux->map_index];
14806 	dst_reg->map_ptr = map;
14807 
14808 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14809 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14810 		dst_reg->type = PTR_TO_MAP_VALUE;
14811 		dst_reg->off = aux->map_off;
14812 		WARN_ON_ONCE(map->max_entries != 1);
14813 		/* We want reg->id to be same (0) as map_value is not distinct */
14814 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14815 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14816 		dst_reg->type = CONST_PTR_TO_MAP;
14817 	} else {
14818 		verbose(env, "bpf verifier is misconfigured\n");
14819 		return -EINVAL;
14820 	}
14821 
14822 	return 0;
14823 }
14824 
14825 static bool may_access_skb(enum bpf_prog_type type)
14826 {
14827 	switch (type) {
14828 	case BPF_PROG_TYPE_SOCKET_FILTER:
14829 	case BPF_PROG_TYPE_SCHED_CLS:
14830 	case BPF_PROG_TYPE_SCHED_ACT:
14831 		return true;
14832 	default:
14833 		return false;
14834 	}
14835 }
14836 
14837 /* verify safety of LD_ABS|LD_IND instructions:
14838  * - they can only appear in the programs where ctx == skb
14839  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14840  *   preserve R6-R9, and store return value into R0
14841  *
14842  * Implicit input:
14843  *   ctx == skb == R6 == CTX
14844  *
14845  * Explicit input:
14846  *   SRC == any register
14847  *   IMM == 32-bit immediate
14848  *
14849  * Output:
14850  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14851  */
14852 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14853 {
14854 	struct bpf_reg_state *regs = cur_regs(env);
14855 	static const int ctx_reg = BPF_REG_6;
14856 	u8 mode = BPF_MODE(insn->code);
14857 	int i, err;
14858 
14859 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14860 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14861 		return -EINVAL;
14862 	}
14863 
14864 	if (!env->ops->gen_ld_abs) {
14865 		verbose(env, "bpf verifier is misconfigured\n");
14866 		return -EINVAL;
14867 	}
14868 
14869 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14870 	    BPF_SIZE(insn->code) == BPF_DW ||
14871 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14872 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14873 		return -EINVAL;
14874 	}
14875 
14876 	/* check whether implicit source operand (register R6) is readable */
14877 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14878 	if (err)
14879 		return err;
14880 
14881 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14882 	 * gen_ld_abs() may terminate the program at runtime, leading to
14883 	 * reference leak.
14884 	 */
14885 	err = check_reference_leak(env);
14886 	if (err) {
14887 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14888 		return err;
14889 	}
14890 
14891 	if (env->cur_state->active_lock.ptr) {
14892 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14893 		return -EINVAL;
14894 	}
14895 
14896 	if (env->cur_state->active_rcu_lock) {
14897 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14898 		return -EINVAL;
14899 	}
14900 
14901 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14902 		verbose(env,
14903 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14904 		return -EINVAL;
14905 	}
14906 
14907 	if (mode == BPF_IND) {
14908 		/* check explicit source operand */
14909 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14910 		if (err)
14911 			return err;
14912 	}
14913 
14914 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14915 	if (err < 0)
14916 		return err;
14917 
14918 	/* reset caller saved regs to unreadable */
14919 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14920 		mark_reg_not_init(env, regs, caller_saved[i]);
14921 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14922 	}
14923 
14924 	/* mark destination R0 register as readable, since it contains
14925 	 * the value fetched from the packet.
14926 	 * Already marked as written above.
14927 	 */
14928 	mark_reg_unknown(env, regs, BPF_REG_0);
14929 	/* ld_abs load up to 32-bit skb data. */
14930 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14931 	return 0;
14932 }
14933 
14934 static int check_return_code(struct bpf_verifier_env *env)
14935 {
14936 	struct tnum enforce_attach_type_range = tnum_unknown;
14937 	const struct bpf_prog *prog = env->prog;
14938 	struct bpf_reg_state *reg;
14939 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14940 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14941 	int err;
14942 	struct bpf_func_state *frame = env->cur_state->frame[0];
14943 	const bool is_subprog = frame->subprogno;
14944 
14945 	/* LSM and struct_ops func-ptr's return type could be "void" */
14946 	if (!is_subprog) {
14947 		switch (prog_type) {
14948 		case BPF_PROG_TYPE_LSM:
14949 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14950 				/* See below, can be 0 or 0-1 depending on hook. */
14951 				break;
14952 			fallthrough;
14953 		case BPF_PROG_TYPE_STRUCT_OPS:
14954 			if (!prog->aux->attach_func_proto->type)
14955 				return 0;
14956 			break;
14957 		default:
14958 			break;
14959 		}
14960 	}
14961 
14962 	/* eBPF calling convention is such that R0 is used
14963 	 * to return the value from eBPF program.
14964 	 * Make sure that it's readable at this time
14965 	 * of bpf_exit, which means that program wrote
14966 	 * something into it earlier
14967 	 */
14968 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14969 	if (err)
14970 		return err;
14971 
14972 	if (is_pointer_value(env, BPF_REG_0)) {
14973 		verbose(env, "R0 leaks addr as return value\n");
14974 		return -EACCES;
14975 	}
14976 
14977 	reg = cur_regs(env) + BPF_REG_0;
14978 
14979 	if (frame->in_async_callback_fn) {
14980 		/* enforce return zero from async callbacks like timer */
14981 		if (reg->type != SCALAR_VALUE) {
14982 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14983 				reg_type_str(env, reg->type));
14984 			return -EINVAL;
14985 		}
14986 
14987 		if (!tnum_in(const_0, reg->var_off)) {
14988 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14989 			return -EINVAL;
14990 		}
14991 		return 0;
14992 	}
14993 
14994 	if (is_subprog) {
14995 		if (reg->type != SCALAR_VALUE) {
14996 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14997 				reg_type_str(env, reg->type));
14998 			return -EINVAL;
14999 		}
15000 		return 0;
15001 	}
15002 
15003 	switch (prog_type) {
15004 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15005 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15006 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15007 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15008 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15009 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15010 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15011 			range = tnum_range(1, 1);
15012 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15013 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15014 			range = tnum_range(0, 3);
15015 		break;
15016 	case BPF_PROG_TYPE_CGROUP_SKB:
15017 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15018 			range = tnum_range(0, 3);
15019 			enforce_attach_type_range = tnum_range(2, 3);
15020 		}
15021 		break;
15022 	case BPF_PROG_TYPE_CGROUP_SOCK:
15023 	case BPF_PROG_TYPE_SOCK_OPS:
15024 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15025 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15026 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15027 		break;
15028 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15029 		if (!env->prog->aux->attach_btf_id)
15030 			return 0;
15031 		range = tnum_const(0);
15032 		break;
15033 	case BPF_PROG_TYPE_TRACING:
15034 		switch (env->prog->expected_attach_type) {
15035 		case BPF_TRACE_FENTRY:
15036 		case BPF_TRACE_FEXIT:
15037 			range = tnum_const(0);
15038 			break;
15039 		case BPF_TRACE_RAW_TP:
15040 		case BPF_MODIFY_RETURN:
15041 			return 0;
15042 		case BPF_TRACE_ITER:
15043 			break;
15044 		default:
15045 			return -ENOTSUPP;
15046 		}
15047 		break;
15048 	case BPF_PROG_TYPE_SK_LOOKUP:
15049 		range = tnum_range(SK_DROP, SK_PASS);
15050 		break;
15051 
15052 	case BPF_PROG_TYPE_LSM:
15053 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15054 			/* Regular BPF_PROG_TYPE_LSM programs can return
15055 			 * any value.
15056 			 */
15057 			return 0;
15058 		}
15059 		if (!env->prog->aux->attach_func_proto->type) {
15060 			/* Make sure programs that attach to void
15061 			 * hooks don't try to modify return value.
15062 			 */
15063 			range = tnum_range(1, 1);
15064 		}
15065 		break;
15066 
15067 	case BPF_PROG_TYPE_NETFILTER:
15068 		range = tnum_range(NF_DROP, NF_ACCEPT);
15069 		break;
15070 	case BPF_PROG_TYPE_EXT:
15071 		/* freplace program can return anything as its return value
15072 		 * depends on the to-be-replaced kernel func or bpf program.
15073 		 */
15074 	default:
15075 		return 0;
15076 	}
15077 
15078 	if (reg->type != SCALAR_VALUE) {
15079 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15080 			reg_type_str(env, reg->type));
15081 		return -EINVAL;
15082 	}
15083 
15084 	if (!tnum_in(range, reg->var_off)) {
15085 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15086 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15087 		    prog_type == BPF_PROG_TYPE_LSM &&
15088 		    !prog->aux->attach_func_proto->type)
15089 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15090 		return -EINVAL;
15091 	}
15092 
15093 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15094 	    tnum_in(enforce_attach_type_range, reg->var_off))
15095 		env->prog->enforce_expected_attach_type = 1;
15096 	return 0;
15097 }
15098 
15099 /* non-recursive DFS pseudo code
15100  * 1  procedure DFS-iterative(G,v):
15101  * 2      label v as discovered
15102  * 3      let S be a stack
15103  * 4      S.push(v)
15104  * 5      while S is not empty
15105  * 6            t <- S.peek()
15106  * 7            if t is what we're looking for:
15107  * 8                return t
15108  * 9            for all edges e in G.adjacentEdges(t) do
15109  * 10               if edge e is already labelled
15110  * 11                   continue with the next edge
15111  * 12               w <- G.adjacentVertex(t,e)
15112  * 13               if vertex w is not discovered and not explored
15113  * 14                   label e as tree-edge
15114  * 15                   label w as discovered
15115  * 16                   S.push(w)
15116  * 17                   continue at 5
15117  * 18               else if vertex w is discovered
15118  * 19                   label e as back-edge
15119  * 20               else
15120  * 21                   // vertex w is explored
15121  * 22                   label e as forward- or cross-edge
15122  * 23           label t as explored
15123  * 24           S.pop()
15124  *
15125  * convention:
15126  * 0x10 - discovered
15127  * 0x11 - discovered and fall-through edge labelled
15128  * 0x12 - discovered and fall-through and branch edges labelled
15129  * 0x20 - explored
15130  */
15131 
15132 enum {
15133 	DISCOVERED = 0x10,
15134 	EXPLORED = 0x20,
15135 	FALLTHROUGH = 1,
15136 	BRANCH = 2,
15137 };
15138 
15139 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15140 {
15141 	env->insn_aux_data[idx].prune_point = true;
15142 }
15143 
15144 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15145 {
15146 	return env->insn_aux_data[insn_idx].prune_point;
15147 }
15148 
15149 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15150 {
15151 	env->insn_aux_data[idx].force_checkpoint = true;
15152 }
15153 
15154 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15155 {
15156 	return env->insn_aux_data[insn_idx].force_checkpoint;
15157 }
15158 
15159 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15160 {
15161 	env->insn_aux_data[idx].calls_callback = true;
15162 }
15163 
15164 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15165 {
15166 	return env->insn_aux_data[insn_idx].calls_callback;
15167 }
15168 
15169 enum {
15170 	DONE_EXPLORING = 0,
15171 	KEEP_EXPLORING = 1,
15172 };
15173 
15174 /* t, w, e - match pseudo-code above:
15175  * t - index of current instruction
15176  * w - next instruction
15177  * e - edge
15178  */
15179 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15180 {
15181 	int *insn_stack = env->cfg.insn_stack;
15182 	int *insn_state = env->cfg.insn_state;
15183 
15184 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15185 		return DONE_EXPLORING;
15186 
15187 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15188 		return DONE_EXPLORING;
15189 
15190 	if (w < 0 || w >= env->prog->len) {
15191 		verbose_linfo(env, t, "%d: ", t);
15192 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15193 		return -EINVAL;
15194 	}
15195 
15196 	if (e == BRANCH) {
15197 		/* mark branch target for state pruning */
15198 		mark_prune_point(env, w);
15199 		mark_jmp_point(env, w);
15200 	}
15201 
15202 	if (insn_state[w] == 0) {
15203 		/* tree-edge */
15204 		insn_state[t] = DISCOVERED | e;
15205 		insn_state[w] = DISCOVERED;
15206 		if (env->cfg.cur_stack >= env->prog->len)
15207 			return -E2BIG;
15208 		insn_stack[env->cfg.cur_stack++] = w;
15209 		return KEEP_EXPLORING;
15210 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15211 		if (env->bpf_capable)
15212 			return DONE_EXPLORING;
15213 		verbose_linfo(env, t, "%d: ", t);
15214 		verbose_linfo(env, w, "%d: ", w);
15215 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15216 		return -EINVAL;
15217 	} else if (insn_state[w] == EXPLORED) {
15218 		/* forward- or cross-edge */
15219 		insn_state[t] = DISCOVERED | e;
15220 	} else {
15221 		verbose(env, "insn state internal bug\n");
15222 		return -EFAULT;
15223 	}
15224 	return DONE_EXPLORING;
15225 }
15226 
15227 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15228 				struct bpf_verifier_env *env,
15229 				bool visit_callee)
15230 {
15231 	int ret, insn_sz;
15232 
15233 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15234 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15235 	if (ret)
15236 		return ret;
15237 
15238 	mark_prune_point(env, t + insn_sz);
15239 	/* when we exit from subprog, we need to record non-linear history */
15240 	mark_jmp_point(env, t + insn_sz);
15241 
15242 	if (visit_callee) {
15243 		mark_prune_point(env, t);
15244 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15245 	}
15246 	return ret;
15247 }
15248 
15249 /* Visits the instruction at index t and returns one of the following:
15250  *  < 0 - an error occurred
15251  *  DONE_EXPLORING - the instruction was fully explored
15252  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15253  */
15254 static int visit_insn(int t, struct bpf_verifier_env *env)
15255 {
15256 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15257 	int ret, off, insn_sz;
15258 
15259 	if (bpf_pseudo_func(insn))
15260 		return visit_func_call_insn(t, insns, env, true);
15261 
15262 	/* All non-branch instructions have a single fall-through edge. */
15263 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15264 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15265 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15266 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15267 	}
15268 
15269 	switch (BPF_OP(insn->code)) {
15270 	case BPF_EXIT:
15271 		return DONE_EXPLORING;
15272 
15273 	case BPF_CALL:
15274 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15275 			/* Mark this call insn as a prune point to trigger
15276 			 * is_state_visited() check before call itself is
15277 			 * processed by __check_func_call(). Otherwise new
15278 			 * async state will be pushed for further exploration.
15279 			 */
15280 			mark_prune_point(env, t);
15281 		/* For functions that invoke callbacks it is not known how many times
15282 		 * callback would be called. Verifier models callback calling functions
15283 		 * by repeatedly visiting callback bodies and returning to origin call
15284 		 * instruction.
15285 		 * In order to stop such iteration verifier needs to identify when a
15286 		 * state identical some state from a previous iteration is reached.
15287 		 * Check below forces creation of checkpoint before callback calling
15288 		 * instruction to allow search for such identical states.
15289 		 */
15290 		if (is_sync_callback_calling_insn(insn)) {
15291 			mark_calls_callback(env, t);
15292 			mark_force_checkpoint(env, t);
15293 			mark_prune_point(env, t);
15294 			mark_jmp_point(env, t);
15295 		}
15296 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15297 			struct bpf_kfunc_call_arg_meta meta;
15298 
15299 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15300 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15301 				mark_prune_point(env, t);
15302 				/* Checking and saving state checkpoints at iter_next() call
15303 				 * is crucial for fast convergence of open-coded iterator loop
15304 				 * logic, so we need to force it. If we don't do that,
15305 				 * is_state_visited() might skip saving a checkpoint, causing
15306 				 * unnecessarily long sequence of not checkpointed
15307 				 * instructions and jumps, leading to exhaustion of jump
15308 				 * history buffer, and potentially other undesired outcomes.
15309 				 * It is expected that with correct open-coded iterators
15310 				 * convergence will happen quickly, so we don't run a risk of
15311 				 * exhausting memory.
15312 				 */
15313 				mark_force_checkpoint(env, t);
15314 			}
15315 		}
15316 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15317 
15318 	case BPF_JA:
15319 		if (BPF_SRC(insn->code) != BPF_K)
15320 			return -EINVAL;
15321 
15322 		if (BPF_CLASS(insn->code) == BPF_JMP)
15323 			off = insn->off;
15324 		else
15325 			off = insn->imm;
15326 
15327 		/* unconditional jump with single edge */
15328 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15329 		if (ret)
15330 			return ret;
15331 
15332 		mark_prune_point(env, t + off + 1);
15333 		mark_jmp_point(env, t + off + 1);
15334 
15335 		return ret;
15336 
15337 	default:
15338 		/* conditional jump with two edges */
15339 		mark_prune_point(env, t);
15340 
15341 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15342 		if (ret)
15343 			return ret;
15344 
15345 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15346 	}
15347 }
15348 
15349 /* non-recursive depth-first-search to detect loops in BPF program
15350  * loop == back-edge in directed graph
15351  */
15352 static int check_cfg(struct bpf_verifier_env *env)
15353 {
15354 	int insn_cnt = env->prog->len;
15355 	int *insn_stack, *insn_state;
15356 	int ret = 0;
15357 	int i;
15358 
15359 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15360 	if (!insn_state)
15361 		return -ENOMEM;
15362 
15363 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15364 	if (!insn_stack) {
15365 		kvfree(insn_state);
15366 		return -ENOMEM;
15367 	}
15368 
15369 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15370 	insn_stack[0] = 0; /* 0 is the first instruction */
15371 	env->cfg.cur_stack = 1;
15372 
15373 	while (env->cfg.cur_stack > 0) {
15374 		int t = insn_stack[env->cfg.cur_stack - 1];
15375 
15376 		ret = visit_insn(t, env);
15377 		switch (ret) {
15378 		case DONE_EXPLORING:
15379 			insn_state[t] = EXPLORED;
15380 			env->cfg.cur_stack--;
15381 			break;
15382 		case KEEP_EXPLORING:
15383 			break;
15384 		default:
15385 			if (ret > 0) {
15386 				verbose(env, "visit_insn internal bug\n");
15387 				ret = -EFAULT;
15388 			}
15389 			goto err_free;
15390 		}
15391 	}
15392 
15393 	if (env->cfg.cur_stack < 0) {
15394 		verbose(env, "pop stack internal bug\n");
15395 		ret = -EFAULT;
15396 		goto err_free;
15397 	}
15398 
15399 	for (i = 0; i < insn_cnt; i++) {
15400 		struct bpf_insn *insn = &env->prog->insnsi[i];
15401 
15402 		if (insn_state[i] != EXPLORED) {
15403 			verbose(env, "unreachable insn %d\n", i);
15404 			ret = -EINVAL;
15405 			goto err_free;
15406 		}
15407 		if (bpf_is_ldimm64(insn)) {
15408 			if (insn_state[i + 1] != 0) {
15409 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15410 				ret = -EINVAL;
15411 				goto err_free;
15412 			}
15413 			i++; /* skip second half of ldimm64 */
15414 		}
15415 	}
15416 	ret = 0; /* cfg looks good */
15417 
15418 err_free:
15419 	kvfree(insn_state);
15420 	kvfree(insn_stack);
15421 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15422 	return ret;
15423 }
15424 
15425 static int check_abnormal_return(struct bpf_verifier_env *env)
15426 {
15427 	int i;
15428 
15429 	for (i = 1; i < env->subprog_cnt; i++) {
15430 		if (env->subprog_info[i].has_ld_abs) {
15431 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15432 			return -EINVAL;
15433 		}
15434 		if (env->subprog_info[i].has_tail_call) {
15435 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15436 			return -EINVAL;
15437 		}
15438 	}
15439 	return 0;
15440 }
15441 
15442 /* The minimum supported BTF func info size */
15443 #define MIN_BPF_FUNCINFO_SIZE	8
15444 #define MAX_FUNCINFO_REC_SIZE	252
15445 
15446 static int check_btf_func(struct bpf_verifier_env *env,
15447 			  const union bpf_attr *attr,
15448 			  bpfptr_t uattr)
15449 {
15450 	const struct btf_type *type, *func_proto, *ret_type;
15451 	u32 i, nfuncs, urec_size, min_size;
15452 	u32 krec_size = sizeof(struct bpf_func_info);
15453 	struct bpf_func_info *krecord;
15454 	struct bpf_func_info_aux *info_aux = NULL;
15455 	struct bpf_prog *prog;
15456 	const struct btf *btf;
15457 	bpfptr_t urecord;
15458 	u32 prev_offset = 0;
15459 	bool scalar_return;
15460 	int ret = -ENOMEM;
15461 
15462 	nfuncs = attr->func_info_cnt;
15463 	if (!nfuncs) {
15464 		if (check_abnormal_return(env))
15465 			return -EINVAL;
15466 		return 0;
15467 	}
15468 
15469 	if (nfuncs != env->subprog_cnt) {
15470 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15471 		return -EINVAL;
15472 	}
15473 
15474 	urec_size = attr->func_info_rec_size;
15475 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15476 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15477 	    urec_size % sizeof(u32)) {
15478 		verbose(env, "invalid func info rec size %u\n", urec_size);
15479 		return -EINVAL;
15480 	}
15481 
15482 	prog = env->prog;
15483 	btf = prog->aux->btf;
15484 
15485 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15486 	min_size = min_t(u32, krec_size, urec_size);
15487 
15488 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15489 	if (!krecord)
15490 		return -ENOMEM;
15491 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15492 	if (!info_aux)
15493 		goto err_free;
15494 
15495 	for (i = 0; i < nfuncs; i++) {
15496 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15497 		if (ret) {
15498 			if (ret == -E2BIG) {
15499 				verbose(env, "nonzero tailing record in func info");
15500 				/* set the size kernel expects so loader can zero
15501 				 * out the rest of the record.
15502 				 */
15503 				if (copy_to_bpfptr_offset(uattr,
15504 							  offsetof(union bpf_attr, func_info_rec_size),
15505 							  &min_size, sizeof(min_size)))
15506 					ret = -EFAULT;
15507 			}
15508 			goto err_free;
15509 		}
15510 
15511 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15512 			ret = -EFAULT;
15513 			goto err_free;
15514 		}
15515 
15516 		/* check insn_off */
15517 		ret = -EINVAL;
15518 		if (i == 0) {
15519 			if (krecord[i].insn_off) {
15520 				verbose(env,
15521 					"nonzero insn_off %u for the first func info record",
15522 					krecord[i].insn_off);
15523 				goto err_free;
15524 			}
15525 		} else if (krecord[i].insn_off <= prev_offset) {
15526 			verbose(env,
15527 				"same or smaller insn offset (%u) than previous func info record (%u)",
15528 				krecord[i].insn_off, prev_offset);
15529 			goto err_free;
15530 		}
15531 
15532 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15533 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15534 			goto err_free;
15535 		}
15536 
15537 		/* check type_id */
15538 		type = btf_type_by_id(btf, krecord[i].type_id);
15539 		if (!type || !btf_type_is_func(type)) {
15540 			verbose(env, "invalid type id %d in func info",
15541 				krecord[i].type_id);
15542 			goto err_free;
15543 		}
15544 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15545 
15546 		func_proto = btf_type_by_id(btf, type->type);
15547 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15548 			/* btf_func_check() already verified it during BTF load */
15549 			goto err_free;
15550 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15551 		scalar_return =
15552 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15553 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15554 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15555 			goto err_free;
15556 		}
15557 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15558 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15559 			goto err_free;
15560 		}
15561 
15562 		prev_offset = krecord[i].insn_off;
15563 		bpfptr_add(&urecord, urec_size);
15564 	}
15565 
15566 	prog->aux->func_info = krecord;
15567 	prog->aux->func_info_cnt = nfuncs;
15568 	prog->aux->func_info_aux = info_aux;
15569 	return 0;
15570 
15571 err_free:
15572 	kvfree(krecord);
15573 	kfree(info_aux);
15574 	return ret;
15575 }
15576 
15577 static void adjust_btf_func(struct bpf_verifier_env *env)
15578 {
15579 	struct bpf_prog_aux *aux = env->prog->aux;
15580 	int i;
15581 
15582 	if (!aux->func_info)
15583 		return;
15584 
15585 	for (i = 0; i < env->subprog_cnt; i++)
15586 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15587 }
15588 
15589 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15590 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15591 
15592 static int check_btf_line(struct bpf_verifier_env *env,
15593 			  const union bpf_attr *attr,
15594 			  bpfptr_t uattr)
15595 {
15596 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15597 	struct bpf_subprog_info *sub;
15598 	struct bpf_line_info *linfo;
15599 	struct bpf_prog *prog;
15600 	const struct btf *btf;
15601 	bpfptr_t ulinfo;
15602 	int err;
15603 
15604 	nr_linfo = attr->line_info_cnt;
15605 	if (!nr_linfo)
15606 		return 0;
15607 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15608 		return -EINVAL;
15609 
15610 	rec_size = attr->line_info_rec_size;
15611 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15612 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15613 	    rec_size & (sizeof(u32) - 1))
15614 		return -EINVAL;
15615 
15616 	/* Need to zero it in case the userspace may
15617 	 * pass in a smaller bpf_line_info object.
15618 	 */
15619 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15620 			 GFP_KERNEL | __GFP_NOWARN);
15621 	if (!linfo)
15622 		return -ENOMEM;
15623 
15624 	prog = env->prog;
15625 	btf = prog->aux->btf;
15626 
15627 	s = 0;
15628 	sub = env->subprog_info;
15629 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15630 	expected_size = sizeof(struct bpf_line_info);
15631 	ncopy = min_t(u32, expected_size, rec_size);
15632 	for (i = 0; i < nr_linfo; i++) {
15633 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15634 		if (err) {
15635 			if (err == -E2BIG) {
15636 				verbose(env, "nonzero tailing record in line_info");
15637 				if (copy_to_bpfptr_offset(uattr,
15638 							  offsetof(union bpf_attr, line_info_rec_size),
15639 							  &expected_size, sizeof(expected_size)))
15640 					err = -EFAULT;
15641 			}
15642 			goto err_free;
15643 		}
15644 
15645 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15646 			err = -EFAULT;
15647 			goto err_free;
15648 		}
15649 
15650 		/*
15651 		 * Check insn_off to ensure
15652 		 * 1) strictly increasing AND
15653 		 * 2) bounded by prog->len
15654 		 *
15655 		 * The linfo[0].insn_off == 0 check logically falls into
15656 		 * the later "missing bpf_line_info for func..." case
15657 		 * because the first linfo[0].insn_off must be the
15658 		 * first sub also and the first sub must have
15659 		 * subprog_info[0].start == 0.
15660 		 */
15661 		if ((i && linfo[i].insn_off <= prev_offset) ||
15662 		    linfo[i].insn_off >= prog->len) {
15663 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15664 				i, linfo[i].insn_off, prev_offset,
15665 				prog->len);
15666 			err = -EINVAL;
15667 			goto err_free;
15668 		}
15669 
15670 		if (!prog->insnsi[linfo[i].insn_off].code) {
15671 			verbose(env,
15672 				"Invalid insn code at line_info[%u].insn_off\n",
15673 				i);
15674 			err = -EINVAL;
15675 			goto err_free;
15676 		}
15677 
15678 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15679 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15680 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15681 			err = -EINVAL;
15682 			goto err_free;
15683 		}
15684 
15685 		if (s != env->subprog_cnt) {
15686 			if (linfo[i].insn_off == sub[s].start) {
15687 				sub[s].linfo_idx = i;
15688 				s++;
15689 			} else if (sub[s].start < linfo[i].insn_off) {
15690 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15691 				err = -EINVAL;
15692 				goto err_free;
15693 			}
15694 		}
15695 
15696 		prev_offset = linfo[i].insn_off;
15697 		bpfptr_add(&ulinfo, rec_size);
15698 	}
15699 
15700 	if (s != env->subprog_cnt) {
15701 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15702 			env->subprog_cnt - s, s);
15703 		err = -EINVAL;
15704 		goto err_free;
15705 	}
15706 
15707 	prog->aux->linfo = linfo;
15708 	prog->aux->nr_linfo = nr_linfo;
15709 
15710 	return 0;
15711 
15712 err_free:
15713 	kvfree(linfo);
15714 	return err;
15715 }
15716 
15717 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15718 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15719 
15720 static int check_core_relo(struct bpf_verifier_env *env,
15721 			   const union bpf_attr *attr,
15722 			   bpfptr_t uattr)
15723 {
15724 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15725 	struct bpf_core_relo core_relo = {};
15726 	struct bpf_prog *prog = env->prog;
15727 	const struct btf *btf = prog->aux->btf;
15728 	struct bpf_core_ctx ctx = {
15729 		.log = &env->log,
15730 		.btf = btf,
15731 	};
15732 	bpfptr_t u_core_relo;
15733 	int err;
15734 
15735 	nr_core_relo = attr->core_relo_cnt;
15736 	if (!nr_core_relo)
15737 		return 0;
15738 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15739 		return -EINVAL;
15740 
15741 	rec_size = attr->core_relo_rec_size;
15742 	if (rec_size < MIN_CORE_RELO_SIZE ||
15743 	    rec_size > MAX_CORE_RELO_SIZE ||
15744 	    rec_size % sizeof(u32))
15745 		return -EINVAL;
15746 
15747 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15748 	expected_size = sizeof(struct bpf_core_relo);
15749 	ncopy = min_t(u32, expected_size, rec_size);
15750 
15751 	/* Unlike func_info and line_info, copy and apply each CO-RE
15752 	 * relocation record one at a time.
15753 	 */
15754 	for (i = 0; i < nr_core_relo; i++) {
15755 		/* future proofing when sizeof(bpf_core_relo) changes */
15756 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15757 		if (err) {
15758 			if (err == -E2BIG) {
15759 				verbose(env, "nonzero tailing record in core_relo");
15760 				if (copy_to_bpfptr_offset(uattr,
15761 							  offsetof(union bpf_attr, core_relo_rec_size),
15762 							  &expected_size, sizeof(expected_size)))
15763 					err = -EFAULT;
15764 			}
15765 			break;
15766 		}
15767 
15768 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15769 			err = -EFAULT;
15770 			break;
15771 		}
15772 
15773 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15774 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15775 				i, core_relo.insn_off, prog->len);
15776 			err = -EINVAL;
15777 			break;
15778 		}
15779 
15780 		err = bpf_core_apply(&ctx, &core_relo, i,
15781 				     &prog->insnsi[core_relo.insn_off / 8]);
15782 		if (err)
15783 			break;
15784 		bpfptr_add(&u_core_relo, rec_size);
15785 	}
15786 	return err;
15787 }
15788 
15789 static int check_btf_info(struct bpf_verifier_env *env,
15790 			  const union bpf_attr *attr,
15791 			  bpfptr_t uattr)
15792 {
15793 	struct btf *btf;
15794 	int err;
15795 
15796 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15797 		if (check_abnormal_return(env))
15798 			return -EINVAL;
15799 		return 0;
15800 	}
15801 
15802 	btf = btf_get_by_fd(attr->prog_btf_fd);
15803 	if (IS_ERR(btf))
15804 		return PTR_ERR(btf);
15805 	if (btf_is_kernel(btf)) {
15806 		btf_put(btf);
15807 		return -EACCES;
15808 	}
15809 	env->prog->aux->btf = btf;
15810 
15811 	err = check_btf_func(env, attr, uattr);
15812 	if (err)
15813 		return err;
15814 
15815 	err = check_btf_line(env, attr, uattr);
15816 	if (err)
15817 		return err;
15818 
15819 	err = check_core_relo(env, attr, uattr);
15820 	if (err)
15821 		return err;
15822 
15823 	return 0;
15824 }
15825 
15826 /* check %cur's range satisfies %old's */
15827 static bool range_within(struct bpf_reg_state *old,
15828 			 struct bpf_reg_state *cur)
15829 {
15830 	return old->umin_value <= cur->umin_value &&
15831 	       old->umax_value >= cur->umax_value &&
15832 	       old->smin_value <= cur->smin_value &&
15833 	       old->smax_value >= cur->smax_value &&
15834 	       old->u32_min_value <= cur->u32_min_value &&
15835 	       old->u32_max_value >= cur->u32_max_value &&
15836 	       old->s32_min_value <= cur->s32_min_value &&
15837 	       old->s32_max_value >= cur->s32_max_value;
15838 }
15839 
15840 /* If in the old state two registers had the same id, then they need to have
15841  * the same id in the new state as well.  But that id could be different from
15842  * the old state, so we need to track the mapping from old to new ids.
15843  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15844  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15845  * regs with a different old id could still have new id 9, we don't care about
15846  * that.
15847  * So we look through our idmap to see if this old id has been seen before.  If
15848  * so, we require the new id to match; otherwise, we add the id pair to the map.
15849  */
15850 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15851 {
15852 	struct bpf_id_pair *map = idmap->map;
15853 	unsigned int i;
15854 
15855 	/* either both IDs should be set or both should be zero */
15856 	if (!!old_id != !!cur_id)
15857 		return false;
15858 
15859 	if (old_id == 0) /* cur_id == 0 as well */
15860 		return true;
15861 
15862 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15863 		if (!map[i].old) {
15864 			/* Reached an empty slot; haven't seen this id before */
15865 			map[i].old = old_id;
15866 			map[i].cur = cur_id;
15867 			return true;
15868 		}
15869 		if (map[i].old == old_id)
15870 			return map[i].cur == cur_id;
15871 		if (map[i].cur == cur_id)
15872 			return false;
15873 	}
15874 	/* We ran out of idmap slots, which should be impossible */
15875 	WARN_ON_ONCE(1);
15876 	return false;
15877 }
15878 
15879 /* Similar to check_ids(), but allocate a unique temporary ID
15880  * for 'old_id' or 'cur_id' of zero.
15881  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15882  */
15883 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15884 {
15885 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15886 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15887 
15888 	return check_ids(old_id, cur_id, idmap);
15889 }
15890 
15891 static void clean_func_state(struct bpf_verifier_env *env,
15892 			     struct bpf_func_state *st)
15893 {
15894 	enum bpf_reg_liveness live;
15895 	int i, j;
15896 
15897 	for (i = 0; i < BPF_REG_FP; i++) {
15898 		live = st->regs[i].live;
15899 		/* liveness must not touch this register anymore */
15900 		st->regs[i].live |= REG_LIVE_DONE;
15901 		if (!(live & REG_LIVE_READ))
15902 			/* since the register is unused, clear its state
15903 			 * to make further comparison simpler
15904 			 */
15905 			__mark_reg_not_init(env, &st->regs[i]);
15906 	}
15907 
15908 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15909 		live = st->stack[i].spilled_ptr.live;
15910 		/* liveness must not touch this stack slot anymore */
15911 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15912 		if (!(live & REG_LIVE_READ)) {
15913 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15914 			for (j = 0; j < BPF_REG_SIZE; j++)
15915 				st->stack[i].slot_type[j] = STACK_INVALID;
15916 		}
15917 	}
15918 }
15919 
15920 static void clean_verifier_state(struct bpf_verifier_env *env,
15921 				 struct bpf_verifier_state *st)
15922 {
15923 	int i;
15924 
15925 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15926 		/* all regs in this state in all frames were already marked */
15927 		return;
15928 
15929 	for (i = 0; i <= st->curframe; i++)
15930 		clean_func_state(env, st->frame[i]);
15931 }
15932 
15933 /* the parentage chains form a tree.
15934  * the verifier states are added to state lists at given insn and
15935  * pushed into state stack for future exploration.
15936  * when the verifier reaches bpf_exit insn some of the verifer states
15937  * stored in the state lists have their final liveness state already,
15938  * but a lot of states will get revised from liveness point of view when
15939  * the verifier explores other branches.
15940  * Example:
15941  * 1: r0 = 1
15942  * 2: if r1 == 100 goto pc+1
15943  * 3: r0 = 2
15944  * 4: exit
15945  * when the verifier reaches exit insn the register r0 in the state list of
15946  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15947  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15948  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15949  *
15950  * Since the verifier pushes the branch states as it sees them while exploring
15951  * the program the condition of walking the branch instruction for the second
15952  * time means that all states below this branch were already explored and
15953  * their final liveness marks are already propagated.
15954  * Hence when the verifier completes the search of state list in is_state_visited()
15955  * we can call this clean_live_states() function to mark all liveness states
15956  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15957  * will not be used.
15958  * This function also clears the registers and stack for states that !READ
15959  * to simplify state merging.
15960  *
15961  * Important note here that walking the same branch instruction in the callee
15962  * doesn't meant that the states are DONE. The verifier has to compare
15963  * the callsites
15964  */
15965 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15966 			      struct bpf_verifier_state *cur)
15967 {
15968 	struct bpf_verifier_state_list *sl;
15969 
15970 	sl = *explored_state(env, insn);
15971 	while (sl) {
15972 		if (sl->state.branches)
15973 			goto next;
15974 		if (sl->state.insn_idx != insn ||
15975 		    !same_callsites(&sl->state, cur))
15976 			goto next;
15977 		clean_verifier_state(env, &sl->state);
15978 next:
15979 		sl = sl->next;
15980 	}
15981 }
15982 
15983 static bool regs_exact(const struct bpf_reg_state *rold,
15984 		       const struct bpf_reg_state *rcur,
15985 		       struct bpf_idmap *idmap)
15986 {
15987 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15988 	       check_ids(rold->id, rcur->id, idmap) &&
15989 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15990 }
15991 
15992 /* Returns true if (rold safe implies rcur safe) */
15993 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15994 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15995 {
15996 	if (exact)
15997 		return regs_exact(rold, rcur, idmap);
15998 
15999 	if (!(rold->live & REG_LIVE_READ))
16000 		/* explored state didn't use this */
16001 		return true;
16002 	if (rold->type == NOT_INIT)
16003 		/* explored state can't have used this */
16004 		return true;
16005 	if (rcur->type == NOT_INIT)
16006 		return false;
16007 
16008 	/* Enforce that register types have to match exactly, including their
16009 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16010 	 * rule.
16011 	 *
16012 	 * One can make a point that using a pointer register as unbounded
16013 	 * SCALAR would be technically acceptable, but this could lead to
16014 	 * pointer leaks because scalars are allowed to leak while pointers
16015 	 * are not. We could make this safe in special cases if root is
16016 	 * calling us, but it's probably not worth the hassle.
16017 	 *
16018 	 * Also, register types that are *not* MAYBE_NULL could technically be
16019 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16020 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16021 	 * to the same map).
16022 	 * However, if the old MAYBE_NULL register then got NULL checked,
16023 	 * doing so could have affected others with the same id, and we can't
16024 	 * check for that because we lost the id when we converted to
16025 	 * a non-MAYBE_NULL variant.
16026 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16027 	 * non-MAYBE_NULL registers as well.
16028 	 */
16029 	if (rold->type != rcur->type)
16030 		return false;
16031 
16032 	switch (base_type(rold->type)) {
16033 	case SCALAR_VALUE:
16034 		if (env->explore_alu_limits) {
16035 			/* explore_alu_limits disables tnum_in() and range_within()
16036 			 * logic and requires everything to be strict
16037 			 */
16038 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16039 			       check_scalar_ids(rold->id, rcur->id, idmap);
16040 		}
16041 		if (!rold->precise)
16042 			return true;
16043 		/* Why check_ids() for scalar registers?
16044 		 *
16045 		 * Consider the following BPF code:
16046 		 *   1: r6 = ... unbound scalar, ID=a ...
16047 		 *   2: r7 = ... unbound scalar, ID=b ...
16048 		 *   3: if (r6 > r7) goto +1
16049 		 *   4: r6 = r7
16050 		 *   5: if (r6 > X) goto ...
16051 		 *   6: ... memory operation using r7 ...
16052 		 *
16053 		 * First verification path is [1-6]:
16054 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16055 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16056 		 *   r7 <= X, because r6 and r7 share same id.
16057 		 * Next verification path is [1-4, 6].
16058 		 *
16059 		 * Instruction (6) would be reached in two states:
16060 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16061 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16062 		 *
16063 		 * Use check_ids() to distinguish these states.
16064 		 * ---
16065 		 * Also verify that new value satisfies old value range knowledge.
16066 		 */
16067 		return range_within(rold, rcur) &&
16068 		       tnum_in(rold->var_off, rcur->var_off) &&
16069 		       check_scalar_ids(rold->id, rcur->id, idmap);
16070 	case PTR_TO_MAP_KEY:
16071 	case PTR_TO_MAP_VALUE:
16072 	case PTR_TO_MEM:
16073 	case PTR_TO_BUF:
16074 	case PTR_TO_TP_BUFFER:
16075 		/* If the new min/max/var_off satisfy the old ones and
16076 		 * everything else matches, we are OK.
16077 		 */
16078 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16079 		       range_within(rold, rcur) &&
16080 		       tnum_in(rold->var_off, rcur->var_off) &&
16081 		       check_ids(rold->id, rcur->id, idmap) &&
16082 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16083 	case PTR_TO_PACKET_META:
16084 	case PTR_TO_PACKET:
16085 		/* We must have at least as much range as the old ptr
16086 		 * did, so that any accesses which were safe before are
16087 		 * still safe.  This is true even if old range < old off,
16088 		 * since someone could have accessed through (ptr - k), or
16089 		 * even done ptr -= k in a register, to get a safe access.
16090 		 */
16091 		if (rold->range > rcur->range)
16092 			return false;
16093 		/* If the offsets don't match, we can't trust our alignment;
16094 		 * nor can we be sure that we won't fall out of range.
16095 		 */
16096 		if (rold->off != rcur->off)
16097 			return false;
16098 		/* id relations must be preserved */
16099 		if (!check_ids(rold->id, rcur->id, idmap))
16100 			return false;
16101 		/* new val must satisfy old val knowledge */
16102 		return range_within(rold, rcur) &&
16103 		       tnum_in(rold->var_off, rcur->var_off);
16104 	case PTR_TO_STACK:
16105 		/* two stack pointers are equal only if they're pointing to
16106 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16107 		 */
16108 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16109 	default:
16110 		return regs_exact(rold, rcur, idmap);
16111 	}
16112 }
16113 
16114 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16115 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16116 {
16117 	int i, spi;
16118 
16119 	/* walk slots of the explored stack and ignore any additional
16120 	 * slots in the current stack, since explored(safe) state
16121 	 * didn't use them
16122 	 */
16123 	for (i = 0; i < old->allocated_stack; i++) {
16124 		struct bpf_reg_state *old_reg, *cur_reg;
16125 
16126 		spi = i / BPF_REG_SIZE;
16127 
16128 		if (exact &&
16129 		    (i >= cur->allocated_stack ||
16130 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16131 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16132 			return false;
16133 
16134 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16135 			i += BPF_REG_SIZE - 1;
16136 			/* explored state didn't use this */
16137 			continue;
16138 		}
16139 
16140 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16141 			continue;
16142 
16143 		if (env->allow_uninit_stack &&
16144 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16145 			continue;
16146 
16147 		/* explored stack has more populated slots than current stack
16148 		 * and these slots were used
16149 		 */
16150 		if (i >= cur->allocated_stack)
16151 			return false;
16152 
16153 		/* if old state was safe with misc data in the stack
16154 		 * it will be safe with zero-initialized stack.
16155 		 * The opposite is not true
16156 		 */
16157 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16158 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16159 			continue;
16160 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16161 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16162 			/* Ex: old explored (safe) state has STACK_SPILL in
16163 			 * this stack slot, but current has STACK_MISC ->
16164 			 * this verifier states are not equivalent,
16165 			 * return false to continue verification of this path
16166 			 */
16167 			return false;
16168 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16169 			continue;
16170 		/* Both old and cur are having same slot_type */
16171 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16172 		case STACK_SPILL:
16173 			/* when explored and current stack slot are both storing
16174 			 * spilled registers, check that stored pointers types
16175 			 * are the same as well.
16176 			 * Ex: explored safe path could have stored
16177 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16178 			 * but current path has stored:
16179 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16180 			 * such verifier states are not equivalent.
16181 			 * return false to continue verification of this path
16182 			 */
16183 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16184 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16185 				return false;
16186 			break;
16187 		case STACK_DYNPTR:
16188 			old_reg = &old->stack[spi].spilled_ptr;
16189 			cur_reg = &cur->stack[spi].spilled_ptr;
16190 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16191 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16192 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16193 				return false;
16194 			break;
16195 		case STACK_ITER:
16196 			old_reg = &old->stack[spi].spilled_ptr;
16197 			cur_reg = &cur->stack[spi].spilled_ptr;
16198 			/* iter.depth is not compared between states as it
16199 			 * doesn't matter for correctness and would otherwise
16200 			 * prevent convergence; we maintain it only to prevent
16201 			 * infinite loop check triggering, see
16202 			 * iter_active_depths_differ()
16203 			 */
16204 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16205 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16206 			    old_reg->iter.state != cur_reg->iter.state ||
16207 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16208 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16209 				return false;
16210 			break;
16211 		case STACK_MISC:
16212 		case STACK_ZERO:
16213 		case STACK_INVALID:
16214 			continue;
16215 		/* Ensure that new unhandled slot types return false by default */
16216 		default:
16217 			return false;
16218 		}
16219 	}
16220 	return true;
16221 }
16222 
16223 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16224 		    struct bpf_idmap *idmap)
16225 {
16226 	int i;
16227 
16228 	if (old->acquired_refs != cur->acquired_refs)
16229 		return false;
16230 
16231 	for (i = 0; i < old->acquired_refs; i++) {
16232 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16233 			return false;
16234 	}
16235 
16236 	return true;
16237 }
16238 
16239 /* compare two verifier states
16240  *
16241  * all states stored in state_list are known to be valid, since
16242  * verifier reached 'bpf_exit' instruction through them
16243  *
16244  * this function is called when verifier exploring different branches of
16245  * execution popped from the state stack. If it sees an old state that has
16246  * more strict register state and more strict stack state then this execution
16247  * branch doesn't need to be explored further, since verifier already
16248  * concluded that more strict state leads to valid finish.
16249  *
16250  * Therefore two states are equivalent if register state is more conservative
16251  * and explored stack state is more conservative than the current one.
16252  * Example:
16253  *       explored                   current
16254  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16255  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16256  *
16257  * In other words if current stack state (one being explored) has more
16258  * valid slots than old one that already passed validation, it means
16259  * the verifier can stop exploring and conclude that current state is valid too
16260  *
16261  * Similarly with registers. If explored state has register type as invalid
16262  * whereas register type in current state is meaningful, it means that
16263  * the current state will reach 'bpf_exit' instruction safely
16264  */
16265 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16266 			      struct bpf_func_state *cur, bool exact)
16267 {
16268 	int i;
16269 
16270 	if (old->callback_depth > cur->callback_depth)
16271 		return false;
16272 
16273 	for (i = 0; i < MAX_BPF_REG; i++)
16274 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16275 			     &env->idmap_scratch, exact))
16276 			return false;
16277 
16278 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16279 		return false;
16280 
16281 	if (!refsafe(old, cur, &env->idmap_scratch))
16282 		return false;
16283 
16284 	return true;
16285 }
16286 
16287 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16288 {
16289 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16290 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16291 }
16292 
16293 static bool states_equal(struct bpf_verifier_env *env,
16294 			 struct bpf_verifier_state *old,
16295 			 struct bpf_verifier_state *cur,
16296 			 bool exact)
16297 {
16298 	int i;
16299 
16300 	if (old->curframe != cur->curframe)
16301 		return false;
16302 
16303 	reset_idmap_scratch(env);
16304 
16305 	/* Verification state from speculative execution simulation
16306 	 * must never prune a non-speculative execution one.
16307 	 */
16308 	if (old->speculative && !cur->speculative)
16309 		return false;
16310 
16311 	if (old->active_lock.ptr != cur->active_lock.ptr)
16312 		return false;
16313 
16314 	/* Old and cur active_lock's have to be either both present
16315 	 * or both absent.
16316 	 */
16317 	if (!!old->active_lock.id != !!cur->active_lock.id)
16318 		return false;
16319 
16320 	if (old->active_lock.id &&
16321 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16322 		return false;
16323 
16324 	if (old->active_rcu_lock != cur->active_rcu_lock)
16325 		return false;
16326 
16327 	/* for states to be equal callsites have to be the same
16328 	 * and all frame states need to be equivalent
16329 	 */
16330 	for (i = 0; i <= old->curframe; i++) {
16331 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16332 			return false;
16333 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16334 			return false;
16335 	}
16336 	return true;
16337 }
16338 
16339 /* Return 0 if no propagation happened. Return negative error code if error
16340  * happened. Otherwise, return the propagated bit.
16341  */
16342 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16343 				  struct bpf_reg_state *reg,
16344 				  struct bpf_reg_state *parent_reg)
16345 {
16346 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16347 	u8 flag = reg->live & REG_LIVE_READ;
16348 	int err;
16349 
16350 	/* When comes here, read flags of PARENT_REG or REG could be any of
16351 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16352 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16353 	 */
16354 	if (parent_flag == REG_LIVE_READ64 ||
16355 	    /* Or if there is no read flag from REG. */
16356 	    !flag ||
16357 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16358 	    parent_flag == flag)
16359 		return 0;
16360 
16361 	err = mark_reg_read(env, reg, parent_reg, flag);
16362 	if (err)
16363 		return err;
16364 
16365 	return flag;
16366 }
16367 
16368 /* A write screens off any subsequent reads; but write marks come from the
16369  * straight-line code between a state and its parent.  When we arrive at an
16370  * equivalent state (jump target or such) we didn't arrive by the straight-line
16371  * code, so read marks in the state must propagate to the parent regardless
16372  * of the state's write marks. That's what 'parent == state->parent' comparison
16373  * in mark_reg_read() is for.
16374  */
16375 static int propagate_liveness(struct bpf_verifier_env *env,
16376 			      const struct bpf_verifier_state *vstate,
16377 			      struct bpf_verifier_state *vparent)
16378 {
16379 	struct bpf_reg_state *state_reg, *parent_reg;
16380 	struct bpf_func_state *state, *parent;
16381 	int i, frame, err = 0;
16382 
16383 	if (vparent->curframe != vstate->curframe) {
16384 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16385 		     vparent->curframe, vstate->curframe);
16386 		return -EFAULT;
16387 	}
16388 	/* Propagate read liveness of registers... */
16389 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16390 	for (frame = 0; frame <= vstate->curframe; frame++) {
16391 		parent = vparent->frame[frame];
16392 		state = vstate->frame[frame];
16393 		parent_reg = parent->regs;
16394 		state_reg = state->regs;
16395 		/* We don't need to worry about FP liveness, it's read-only */
16396 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16397 			err = propagate_liveness_reg(env, &state_reg[i],
16398 						     &parent_reg[i]);
16399 			if (err < 0)
16400 				return err;
16401 			if (err == REG_LIVE_READ64)
16402 				mark_insn_zext(env, &parent_reg[i]);
16403 		}
16404 
16405 		/* Propagate stack slots. */
16406 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16407 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16408 			parent_reg = &parent->stack[i].spilled_ptr;
16409 			state_reg = &state->stack[i].spilled_ptr;
16410 			err = propagate_liveness_reg(env, state_reg,
16411 						     parent_reg);
16412 			if (err < 0)
16413 				return err;
16414 		}
16415 	}
16416 	return 0;
16417 }
16418 
16419 /* find precise scalars in the previous equivalent state and
16420  * propagate them into the current state
16421  */
16422 static int propagate_precision(struct bpf_verifier_env *env,
16423 			       const struct bpf_verifier_state *old)
16424 {
16425 	struct bpf_reg_state *state_reg;
16426 	struct bpf_func_state *state;
16427 	int i, err = 0, fr;
16428 	bool first;
16429 
16430 	for (fr = old->curframe; fr >= 0; fr--) {
16431 		state = old->frame[fr];
16432 		state_reg = state->regs;
16433 		first = true;
16434 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16435 			if (state_reg->type != SCALAR_VALUE ||
16436 			    !state_reg->precise ||
16437 			    !(state_reg->live & REG_LIVE_READ))
16438 				continue;
16439 			if (env->log.level & BPF_LOG_LEVEL2) {
16440 				if (first)
16441 					verbose(env, "frame %d: propagating r%d", fr, i);
16442 				else
16443 					verbose(env, ",r%d", i);
16444 			}
16445 			bt_set_frame_reg(&env->bt, fr, i);
16446 			first = false;
16447 		}
16448 
16449 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16450 			if (!is_spilled_reg(&state->stack[i]))
16451 				continue;
16452 			state_reg = &state->stack[i].spilled_ptr;
16453 			if (state_reg->type != SCALAR_VALUE ||
16454 			    !state_reg->precise ||
16455 			    !(state_reg->live & REG_LIVE_READ))
16456 				continue;
16457 			if (env->log.level & BPF_LOG_LEVEL2) {
16458 				if (first)
16459 					verbose(env, "frame %d: propagating fp%d",
16460 						fr, (-i - 1) * BPF_REG_SIZE);
16461 				else
16462 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16463 			}
16464 			bt_set_frame_slot(&env->bt, fr, i);
16465 			first = false;
16466 		}
16467 		if (!first)
16468 			verbose(env, "\n");
16469 	}
16470 
16471 	err = mark_chain_precision_batch(env);
16472 	if (err < 0)
16473 		return err;
16474 
16475 	return 0;
16476 }
16477 
16478 static bool states_maybe_looping(struct bpf_verifier_state *old,
16479 				 struct bpf_verifier_state *cur)
16480 {
16481 	struct bpf_func_state *fold, *fcur;
16482 	int i, fr = cur->curframe;
16483 
16484 	if (old->curframe != fr)
16485 		return false;
16486 
16487 	fold = old->frame[fr];
16488 	fcur = cur->frame[fr];
16489 	for (i = 0; i < MAX_BPF_REG; i++)
16490 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16491 			   offsetof(struct bpf_reg_state, parent)))
16492 			return false;
16493 	return true;
16494 }
16495 
16496 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16497 {
16498 	return env->insn_aux_data[insn_idx].is_iter_next;
16499 }
16500 
16501 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16502  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16503  * states to match, which otherwise would look like an infinite loop. So while
16504  * iter_next() calls are taken care of, we still need to be careful and
16505  * prevent erroneous and too eager declaration of "ininite loop", when
16506  * iterators are involved.
16507  *
16508  * Here's a situation in pseudo-BPF assembly form:
16509  *
16510  *   0: again:                          ; set up iter_next() call args
16511  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16512  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16513  *   3:   if r0 == 0 goto done
16514  *   4:   ... something useful here ...
16515  *   5:   goto again                    ; another iteration
16516  *   6: done:
16517  *   7:   r1 = &it
16518  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16519  *   9:   exit
16520  *
16521  * This is a typical loop. Let's assume that we have a prune point at 1:,
16522  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16523  * again`, assuming other heuristics don't get in a way).
16524  *
16525  * When we first time come to 1:, let's say we have some state X. We proceed
16526  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16527  * Now we come back to validate that forked ACTIVE state. We proceed through
16528  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16529  * are converging. But the problem is that we don't know that yet, as this
16530  * convergence has to happen at iter_next() call site only. So if nothing is
16531  * done, at 1: verifier will use bounded loop logic and declare infinite
16532  * looping (and would be *technically* correct, if not for iterator's
16533  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16534  * don't want that. So what we do in process_iter_next_call() when we go on
16535  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16536  * a different iteration. So when we suspect an infinite loop, we additionally
16537  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16538  * pretend we are not looping and wait for next iter_next() call.
16539  *
16540  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16541  * loop, because that would actually mean infinite loop, as DRAINED state is
16542  * "sticky", and so we'll keep returning into the same instruction with the
16543  * same state (at least in one of possible code paths).
16544  *
16545  * This approach allows to keep infinite loop heuristic even in the face of
16546  * active iterator. E.g., C snippet below is and will be detected as
16547  * inifintely looping:
16548  *
16549  *   struct bpf_iter_num it;
16550  *   int *p, x;
16551  *
16552  *   bpf_iter_num_new(&it, 0, 10);
16553  *   while ((p = bpf_iter_num_next(&t))) {
16554  *       x = p;
16555  *       while (x--) {} // <<-- infinite loop here
16556  *   }
16557  *
16558  */
16559 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16560 {
16561 	struct bpf_reg_state *slot, *cur_slot;
16562 	struct bpf_func_state *state;
16563 	int i, fr;
16564 
16565 	for (fr = old->curframe; fr >= 0; fr--) {
16566 		state = old->frame[fr];
16567 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16568 			if (state->stack[i].slot_type[0] != STACK_ITER)
16569 				continue;
16570 
16571 			slot = &state->stack[i].spilled_ptr;
16572 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16573 				continue;
16574 
16575 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16576 			if (cur_slot->iter.depth != slot->iter.depth)
16577 				return true;
16578 		}
16579 	}
16580 	return false;
16581 }
16582 
16583 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16584 {
16585 	struct bpf_verifier_state_list *new_sl;
16586 	struct bpf_verifier_state_list *sl, **pprev;
16587 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16588 	int i, j, n, err, states_cnt = 0;
16589 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16590 	bool add_new_state = force_new_state;
16591 	bool force_exact;
16592 
16593 	/* bpf progs typically have pruning point every 4 instructions
16594 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16595 	 * Do not add new state for future pruning if the verifier hasn't seen
16596 	 * at least 2 jumps and at least 8 instructions.
16597 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16598 	 * In tests that amounts to up to 50% reduction into total verifier
16599 	 * memory consumption and 20% verifier time speedup.
16600 	 */
16601 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16602 	    env->insn_processed - env->prev_insn_processed >= 8)
16603 		add_new_state = true;
16604 
16605 	pprev = explored_state(env, insn_idx);
16606 	sl = *pprev;
16607 
16608 	clean_live_states(env, insn_idx, cur);
16609 
16610 	while (sl) {
16611 		states_cnt++;
16612 		if (sl->state.insn_idx != insn_idx)
16613 			goto next;
16614 
16615 		if (sl->state.branches) {
16616 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16617 
16618 			if (frame->in_async_callback_fn &&
16619 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16620 				/* Different async_entry_cnt means that the verifier is
16621 				 * processing another entry into async callback.
16622 				 * Seeing the same state is not an indication of infinite
16623 				 * loop or infinite recursion.
16624 				 * But finding the same state doesn't mean that it's safe
16625 				 * to stop processing the current state. The previous state
16626 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16627 				 * Checking in_async_callback_fn alone is not enough either.
16628 				 * Since the verifier still needs to catch infinite loops
16629 				 * inside async callbacks.
16630 				 */
16631 				goto skip_inf_loop_check;
16632 			}
16633 			/* BPF open-coded iterators loop detection is special.
16634 			 * states_maybe_looping() logic is too simplistic in detecting
16635 			 * states that *might* be equivalent, because it doesn't know
16636 			 * about ID remapping, so don't even perform it.
16637 			 * See process_iter_next_call() and iter_active_depths_differ()
16638 			 * for overview of the logic. When current and one of parent
16639 			 * states are detected as equivalent, it's a good thing: we prove
16640 			 * convergence and can stop simulating further iterations.
16641 			 * It's safe to assume that iterator loop will finish, taking into
16642 			 * account iter_next() contract of eventually returning
16643 			 * sticky NULL result.
16644 			 *
16645 			 * Note, that states have to be compared exactly in this case because
16646 			 * read and precision marks might not be finalized inside the loop.
16647 			 * E.g. as in the program below:
16648 			 *
16649 			 *     1. r7 = -16
16650 			 *     2. r6 = bpf_get_prandom_u32()
16651 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16652 			 *     4.   if (r6 != 42) {
16653 			 *     5.     r7 = -32
16654 			 *     6.     r6 = bpf_get_prandom_u32()
16655 			 *     7.     continue
16656 			 *     8.   }
16657 			 *     9.   r0 = r10
16658 			 *    10.   r0 += r7
16659 			 *    11.   r8 = *(u64 *)(r0 + 0)
16660 			 *    12.   r6 = bpf_get_prandom_u32()
16661 			 *    13. }
16662 			 *
16663 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16664 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16665 			 * not have read or precision mark for r7 yet, thus inexact states
16666 			 * comparison would discard current state with r7=-32
16667 			 * => unsafe memory access at 11 would not be caught.
16668 			 */
16669 			if (is_iter_next_insn(env, insn_idx)) {
16670 				if (states_equal(env, &sl->state, cur, true)) {
16671 					struct bpf_func_state *cur_frame;
16672 					struct bpf_reg_state *iter_state, *iter_reg;
16673 					int spi;
16674 
16675 					cur_frame = cur->frame[cur->curframe];
16676 					/* btf_check_iter_kfuncs() enforces that
16677 					 * iter state pointer is always the first arg
16678 					 */
16679 					iter_reg = &cur_frame->regs[BPF_REG_1];
16680 					/* current state is valid due to states_equal(),
16681 					 * so we can assume valid iter and reg state,
16682 					 * no need for extra (re-)validations
16683 					 */
16684 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16685 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16686 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16687 						update_loop_entry(cur, &sl->state);
16688 						goto hit;
16689 					}
16690 				}
16691 				goto skip_inf_loop_check;
16692 			}
16693 			if (calls_callback(env, insn_idx)) {
16694 				if (states_equal(env, &sl->state, cur, true))
16695 					goto hit;
16696 				goto skip_inf_loop_check;
16697 			}
16698 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16699 			if (states_maybe_looping(&sl->state, cur) &&
16700 			    states_equal(env, &sl->state, cur, false) &&
16701 			    !iter_active_depths_differ(&sl->state, cur) &&
16702 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16703 				verbose_linfo(env, insn_idx, "; ");
16704 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16705 				verbose(env, "cur state:");
16706 				print_verifier_state(env, cur->frame[cur->curframe], true);
16707 				verbose(env, "old state:");
16708 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16709 				return -EINVAL;
16710 			}
16711 			/* if the verifier is processing a loop, avoid adding new state
16712 			 * too often, since different loop iterations have distinct
16713 			 * states and may not help future pruning.
16714 			 * This threshold shouldn't be too low to make sure that
16715 			 * a loop with large bound will be rejected quickly.
16716 			 * The most abusive loop will be:
16717 			 * r1 += 1
16718 			 * if r1 < 1000000 goto pc-2
16719 			 * 1M insn_procssed limit / 100 == 10k peak states.
16720 			 * This threshold shouldn't be too high either, since states
16721 			 * at the end of the loop are likely to be useful in pruning.
16722 			 */
16723 skip_inf_loop_check:
16724 			if (!force_new_state &&
16725 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16726 			    env->insn_processed - env->prev_insn_processed < 100)
16727 				add_new_state = false;
16728 			goto miss;
16729 		}
16730 		/* If sl->state is a part of a loop and this loop's entry is a part of
16731 		 * current verification path then states have to be compared exactly.
16732 		 * 'force_exact' is needed to catch the following case:
16733 		 *
16734 		 *                initial     Here state 'succ' was processed first,
16735 		 *                  |         it was eventually tracked to produce a
16736 		 *                  V         state identical to 'hdr'.
16737 		 *     .---------> hdr        All branches from 'succ' had been explored
16738 		 *     |            |         and thus 'succ' has its .branches == 0.
16739 		 *     |            V
16740 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16741 		 *     |    |       |         to the same instruction + callsites.
16742 		 *     |    V       V         In such case it is necessary to check
16743 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16744 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16745 		 *     |    V       V         same loop exact flag has to be set.
16746 		 *     |   succ <- cur        To check if that is the case, verify
16747 		 *     |    |                 if loop entry of 'succ' is in current
16748 		 *     |    V                 DFS path.
16749 		 *     |   ...
16750 		 *     |    |
16751 		 *     '----'
16752 		 *
16753 		 * Additional details are in the comment before get_loop_entry().
16754 		 */
16755 		loop_entry = get_loop_entry(&sl->state);
16756 		force_exact = loop_entry && loop_entry->branches > 0;
16757 		if (states_equal(env, &sl->state, cur, force_exact)) {
16758 			if (force_exact)
16759 				update_loop_entry(cur, loop_entry);
16760 hit:
16761 			sl->hit_cnt++;
16762 			/* reached equivalent register/stack state,
16763 			 * prune the search.
16764 			 * Registers read by the continuation are read by us.
16765 			 * If we have any write marks in env->cur_state, they
16766 			 * will prevent corresponding reads in the continuation
16767 			 * from reaching our parent (an explored_state).  Our
16768 			 * own state will get the read marks recorded, but
16769 			 * they'll be immediately forgotten as we're pruning
16770 			 * this state and will pop a new one.
16771 			 */
16772 			err = propagate_liveness(env, &sl->state, cur);
16773 
16774 			/* if previous state reached the exit with precision and
16775 			 * current state is equivalent to it (except precsion marks)
16776 			 * the precision needs to be propagated back in
16777 			 * the current state.
16778 			 */
16779 			err = err ? : push_jmp_history(env, cur);
16780 			err = err ? : propagate_precision(env, &sl->state);
16781 			if (err)
16782 				return err;
16783 			return 1;
16784 		}
16785 miss:
16786 		/* when new state is not going to be added do not increase miss count.
16787 		 * Otherwise several loop iterations will remove the state
16788 		 * recorded earlier. The goal of these heuristics is to have
16789 		 * states from some iterations of the loop (some in the beginning
16790 		 * and some at the end) to help pruning.
16791 		 */
16792 		if (add_new_state)
16793 			sl->miss_cnt++;
16794 		/* heuristic to determine whether this state is beneficial
16795 		 * to keep checking from state equivalence point of view.
16796 		 * Higher numbers increase max_states_per_insn and verification time,
16797 		 * but do not meaningfully decrease insn_processed.
16798 		 * 'n' controls how many times state could miss before eviction.
16799 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16800 		 * too early would hinder iterator convergence.
16801 		 */
16802 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16803 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16804 			/* the state is unlikely to be useful. Remove it to
16805 			 * speed up verification
16806 			 */
16807 			*pprev = sl->next;
16808 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16809 			    !sl->state.used_as_loop_entry) {
16810 				u32 br = sl->state.branches;
16811 
16812 				WARN_ONCE(br,
16813 					  "BUG live_done but branches_to_explore %d\n",
16814 					  br);
16815 				free_verifier_state(&sl->state, false);
16816 				kfree(sl);
16817 				env->peak_states--;
16818 			} else {
16819 				/* cannot free this state, since parentage chain may
16820 				 * walk it later. Add it for free_list instead to
16821 				 * be freed at the end of verification
16822 				 */
16823 				sl->next = env->free_list;
16824 				env->free_list = sl;
16825 			}
16826 			sl = *pprev;
16827 			continue;
16828 		}
16829 next:
16830 		pprev = &sl->next;
16831 		sl = *pprev;
16832 	}
16833 
16834 	if (env->max_states_per_insn < states_cnt)
16835 		env->max_states_per_insn = states_cnt;
16836 
16837 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16838 		return 0;
16839 
16840 	if (!add_new_state)
16841 		return 0;
16842 
16843 	/* There were no equivalent states, remember the current one.
16844 	 * Technically the current state is not proven to be safe yet,
16845 	 * but it will either reach outer most bpf_exit (which means it's safe)
16846 	 * or it will be rejected. When there are no loops the verifier won't be
16847 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16848 	 * again on the way to bpf_exit.
16849 	 * When looping the sl->state.branches will be > 0 and this state
16850 	 * will not be considered for equivalence until branches == 0.
16851 	 */
16852 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16853 	if (!new_sl)
16854 		return -ENOMEM;
16855 	env->total_states++;
16856 	env->peak_states++;
16857 	env->prev_jmps_processed = env->jmps_processed;
16858 	env->prev_insn_processed = env->insn_processed;
16859 
16860 	/* forget precise markings we inherited, see __mark_chain_precision */
16861 	if (env->bpf_capable)
16862 		mark_all_scalars_imprecise(env, cur);
16863 
16864 	/* add new state to the head of linked list */
16865 	new = &new_sl->state;
16866 	err = copy_verifier_state(new, cur);
16867 	if (err) {
16868 		free_verifier_state(new, false);
16869 		kfree(new_sl);
16870 		return err;
16871 	}
16872 	new->insn_idx = insn_idx;
16873 	WARN_ONCE(new->branches != 1,
16874 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16875 
16876 	cur->parent = new;
16877 	cur->first_insn_idx = insn_idx;
16878 	cur->dfs_depth = new->dfs_depth + 1;
16879 	clear_jmp_history(cur);
16880 	new_sl->next = *explored_state(env, insn_idx);
16881 	*explored_state(env, insn_idx) = new_sl;
16882 	/* connect new state to parentage chain. Current frame needs all
16883 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16884 	 * to the stack implicitly by JITs) so in callers' frames connect just
16885 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16886 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16887 	 * from callee with its full parentage chain, anyway.
16888 	 */
16889 	/* clear write marks in current state: the writes we did are not writes
16890 	 * our child did, so they don't screen off its reads from us.
16891 	 * (There are no read marks in current state, because reads always mark
16892 	 * their parent and current state never has children yet.  Only
16893 	 * explored_states can get read marks.)
16894 	 */
16895 	for (j = 0; j <= cur->curframe; j++) {
16896 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16897 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16898 		for (i = 0; i < BPF_REG_FP; i++)
16899 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16900 	}
16901 
16902 	/* all stack frames are accessible from callee, clear them all */
16903 	for (j = 0; j <= cur->curframe; j++) {
16904 		struct bpf_func_state *frame = cur->frame[j];
16905 		struct bpf_func_state *newframe = new->frame[j];
16906 
16907 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16908 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16909 			frame->stack[i].spilled_ptr.parent =
16910 						&newframe->stack[i].spilled_ptr;
16911 		}
16912 	}
16913 	return 0;
16914 }
16915 
16916 /* Return true if it's OK to have the same insn return a different type. */
16917 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16918 {
16919 	switch (base_type(type)) {
16920 	case PTR_TO_CTX:
16921 	case PTR_TO_SOCKET:
16922 	case PTR_TO_SOCK_COMMON:
16923 	case PTR_TO_TCP_SOCK:
16924 	case PTR_TO_XDP_SOCK:
16925 	case PTR_TO_BTF_ID:
16926 		return false;
16927 	default:
16928 		return true;
16929 	}
16930 }
16931 
16932 /* If an instruction was previously used with particular pointer types, then we
16933  * need to be careful to avoid cases such as the below, where it may be ok
16934  * for one branch accessing the pointer, but not ok for the other branch:
16935  *
16936  * R1 = sock_ptr
16937  * goto X;
16938  * ...
16939  * R1 = some_other_valid_ptr;
16940  * goto X;
16941  * ...
16942  * R2 = *(u32 *)(R1 + 0);
16943  */
16944 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16945 {
16946 	return src != prev && (!reg_type_mismatch_ok(src) ||
16947 			       !reg_type_mismatch_ok(prev));
16948 }
16949 
16950 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16951 			     bool allow_trust_missmatch)
16952 {
16953 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16954 
16955 	if (*prev_type == NOT_INIT) {
16956 		/* Saw a valid insn
16957 		 * dst_reg = *(u32 *)(src_reg + off)
16958 		 * save type to validate intersecting paths
16959 		 */
16960 		*prev_type = type;
16961 	} else if (reg_type_mismatch(type, *prev_type)) {
16962 		/* Abuser program is trying to use the same insn
16963 		 * dst_reg = *(u32*) (src_reg + off)
16964 		 * with different pointer types:
16965 		 * src_reg == ctx in one branch and
16966 		 * src_reg == stack|map in some other branch.
16967 		 * Reject it.
16968 		 */
16969 		if (allow_trust_missmatch &&
16970 		    base_type(type) == PTR_TO_BTF_ID &&
16971 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16972 			/*
16973 			 * Have to support a use case when one path through
16974 			 * the program yields TRUSTED pointer while another
16975 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16976 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16977 			 */
16978 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16979 		} else {
16980 			verbose(env, "same insn cannot be used with different pointers\n");
16981 			return -EINVAL;
16982 		}
16983 	}
16984 
16985 	return 0;
16986 }
16987 
16988 static int do_check(struct bpf_verifier_env *env)
16989 {
16990 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16991 	struct bpf_verifier_state *state = env->cur_state;
16992 	struct bpf_insn *insns = env->prog->insnsi;
16993 	struct bpf_reg_state *regs;
16994 	int insn_cnt = env->prog->len;
16995 	bool do_print_state = false;
16996 	int prev_insn_idx = -1;
16997 
16998 	for (;;) {
16999 		struct bpf_insn *insn;
17000 		u8 class;
17001 		int err;
17002 
17003 		env->prev_insn_idx = prev_insn_idx;
17004 		if (env->insn_idx >= insn_cnt) {
17005 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17006 				env->insn_idx, insn_cnt);
17007 			return -EFAULT;
17008 		}
17009 
17010 		insn = &insns[env->insn_idx];
17011 		class = BPF_CLASS(insn->code);
17012 
17013 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17014 			verbose(env,
17015 				"BPF program is too large. Processed %d insn\n",
17016 				env->insn_processed);
17017 			return -E2BIG;
17018 		}
17019 
17020 		state->last_insn_idx = env->prev_insn_idx;
17021 
17022 		if (is_prune_point(env, env->insn_idx)) {
17023 			err = is_state_visited(env, env->insn_idx);
17024 			if (err < 0)
17025 				return err;
17026 			if (err == 1) {
17027 				/* found equivalent state, can prune the search */
17028 				if (env->log.level & BPF_LOG_LEVEL) {
17029 					if (do_print_state)
17030 						verbose(env, "\nfrom %d to %d%s: safe\n",
17031 							env->prev_insn_idx, env->insn_idx,
17032 							env->cur_state->speculative ?
17033 							" (speculative execution)" : "");
17034 					else
17035 						verbose(env, "%d: safe\n", env->insn_idx);
17036 				}
17037 				goto process_bpf_exit;
17038 			}
17039 		}
17040 
17041 		if (is_jmp_point(env, env->insn_idx)) {
17042 			err = push_jmp_history(env, state);
17043 			if (err)
17044 				return err;
17045 		}
17046 
17047 		if (signal_pending(current))
17048 			return -EAGAIN;
17049 
17050 		if (need_resched())
17051 			cond_resched();
17052 
17053 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17054 			verbose(env, "\nfrom %d to %d%s:",
17055 				env->prev_insn_idx, env->insn_idx,
17056 				env->cur_state->speculative ?
17057 				" (speculative execution)" : "");
17058 			print_verifier_state(env, state->frame[state->curframe], true);
17059 			do_print_state = false;
17060 		}
17061 
17062 		if (env->log.level & BPF_LOG_LEVEL) {
17063 			const struct bpf_insn_cbs cbs = {
17064 				.cb_call	= disasm_kfunc_name,
17065 				.cb_print	= verbose,
17066 				.private_data	= env,
17067 			};
17068 
17069 			if (verifier_state_scratched(env))
17070 				print_insn_state(env, state->frame[state->curframe]);
17071 
17072 			verbose_linfo(env, env->insn_idx, "; ");
17073 			env->prev_log_pos = env->log.end_pos;
17074 			verbose(env, "%d: ", env->insn_idx);
17075 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17076 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17077 			env->prev_log_pos = env->log.end_pos;
17078 		}
17079 
17080 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17081 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17082 							   env->prev_insn_idx);
17083 			if (err)
17084 				return err;
17085 		}
17086 
17087 		regs = cur_regs(env);
17088 		sanitize_mark_insn_seen(env);
17089 		prev_insn_idx = env->insn_idx;
17090 
17091 		if (class == BPF_ALU || class == BPF_ALU64) {
17092 			err = check_alu_op(env, insn);
17093 			if (err)
17094 				return err;
17095 
17096 		} else if (class == BPF_LDX) {
17097 			enum bpf_reg_type src_reg_type;
17098 
17099 			/* check for reserved fields is already done */
17100 
17101 			/* check src operand */
17102 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17103 			if (err)
17104 				return err;
17105 
17106 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17107 			if (err)
17108 				return err;
17109 
17110 			src_reg_type = regs[insn->src_reg].type;
17111 
17112 			/* check that memory (src_reg + off) is readable,
17113 			 * the state of dst_reg will be updated by this func
17114 			 */
17115 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17116 					       insn->off, BPF_SIZE(insn->code),
17117 					       BPF_READ, insn->dst_reg, false,
17118 					       BPF_MODE(insn->code) == BPF_MEMSX);
17119 			if (err)
17120 				return err;
17121 
17122 			err = save_aux_ptr_type(env, src_reg_type, true);
17123 			if (err)
17124 				return err;
17125 		} else if (class == BPF_STX) {
17126 			enum bpf_reg_type dst_reg_type;
17127 
17128 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17129 				err = check_atomic(env, env->insn_idx, insn);
17130 				if (err)
17131 					return err;
17132 				env->insn_idx++;
17133 				continue;
17134 			}
17135 
17136 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17137 				verbose(env, "BPF_STX uses reserved fields\n");
17138 				return -EINVAL;
17139 			}
17140 
17141 			/* check src1 operand */
17142 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17143 			if (err)
17144 				return err;
17145 			/* check src2 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, insn->src_reg, 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_ST) {
17163 			enum bpf_reg_type dst_reg_type;
17164 
17165 			if (BPF_MODE(insn->code) != BPF_MEM ||
17166 			    insn->src_reg != BPF_REG_0) {
17167 				verbose(env, "BPF_ST uses reserved fields\n");
17168 				return -EINVAL;
17169 			}
17170 			/* check src operand */
17171 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17172 			if (err)
17173 				return err;
17174 
17175 			dst_reg_type = regs[insn->dst_reg].type;
17176 
17177 			/* check that memory (dst_reg + off) is writeable */
17178 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17179 					       insn->off, BPF_SIZE(insn->code),
17180 					       BPF_WRITE, -1, false, false);
17181 			if (err)
17182 				return err;
17183 
17184 			err = save_aux_ptr_type(env, dst_reg_type, false);
17185 			if (err)
17186 				return err;
17187 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17188 			u8 opcode = BPF_OP(insn->code);
17189 
17190 			env->jmps_processed++;
17191 			if (opcode == BPF_CALL) {
17192 				if (BPF_SRC(insn->code) != BPF_K ||
17193 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17194 				     && insn->off != 0) ||
17195 				    (insn->src_reg != BPF_REG_0 &&
17196 				     insn->src_reg != BPF_PSEUDO_CALL &&
17197 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17198 				    insn->dst_reg != BPF_REG_0 ||
17199 				    class == BPF_JMP32) {
17200 					verbose(env, "BPF_CALL uses reserved fields\n");
17201 					return -EINVAL;
17202 				}
17203 
17204 				if (env->cur_state->active_lock.ptr) {
17205 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17206 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17207 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17208 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17209 						verbose(env, "function calls are not allowed while holding a lock\n");
17210 						return -EINVAL;
17211 					}
17212 				}
17213 				if (insn->src_reg == BPF_PSEUDO_CALL)
17214 					err = check_func_call(env, insn, &env->insn_idx);
17215 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17216 					err = check_kfunc_call(env, insn, &env->insn_idx);
17217 				else
17218 					err = check_helper_call(env, insn, &env->insn_idx);
17219 				if (err)
17220 					return err;
17221 
17222 				mark_reg_scratched(env, BPF_REG_0);
17223 			} else if (opcode == BPF_JA) {
17224 				if (BPF_SRC(insn->code) != BPF_K ||
17225 				    insn->src_reg != BPF_REG_0 ||
17226 				    insn->dst_reg != BPF_REG_0 ||
17227 				    (class == BPF_JMP && insn->imm != 0) ||
17228 				    (class == BPF_JMP32 && insn->off != 0)) {
17229 					verbose(env, "BPF_JA uses reserved fields\n");
17230 					return -EINVAL;
17231 				}
17232 
17233 				if (class == BPF_JMP)
17234 					env->insn_idx += insn->off + 1;
17235 				else
17236 					env->insn_idx += insn->imm + 1;
17237 				continue;
17238 
17239 			} else if (opcode == BPF_EXIT) {
17240 				if (BPF_SRC(insn->code) != BPF_K ||
17241 				    insn->imm != 0 ||
17242 				    insn->src_reg != BPF_REG_0 ||
17243 				    insn->dst_reg != BPF_REG_0 ||
17244 				    class == BPF_JMP32) {
17245 					verbose(env, "BPF_EXIT uses reserved fields\n");
17246 					return -EINVAL;
17247 				}
17248 
17249 				if (env->cur_state->active_lock.ptr &&
17250 				    !in_rbtree_lock_required_cb(env)) {
17251 					verbose(env, "bpf_spin_unlock is missing\n");
17252 					return -EINVAL;
17253 				}
17254 
17255 				if (env->cur_state->active_rcu_lock &&
17256 				    !in_rbtree_lock_required_cb(env)) {
17257 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17258 					return -EINVAL;
17259 				}
17260 
17261 				/* We must do check_reference_leak here before
17262 				 * prepare_func_exit to handle the case when
17263 				 * state->curframe > 0, it may be a callback
17264 				 * function, for which reference_state must
17265 				 * match caller reference state when it exits.
17266 				 */
17267 				err = check_reference_leak(env);
17268 				if (err)
17269 					return err;
17270 
17271 				if (state->curframe) {
17272 					/* exit from nested function */
17273 					err = prepare_func_exit(env, &env->insn_idx);
17274 					if (err)
17275 						return err;
17276 					do_print_state = true;
17277 					continue;
17278 				}
17279 
17280 				err = check_return_code(env);
17281 				if (err)
17282 					return err;
17283 process_bpf_exit:
17284 				mark_verifier_state_scratched(env);
17285 				update_branch_counts(env, env->cur_state);
17286 				err = pop_stack(env, &prev_insn_idx,
17287 						&env->insn_idx, pop_log);
17288 				if (err < 0) {
17289 					if (err != -ENOENT)
17290 						return err;
17291 					break;
17292 				} else {
17293 					do_print_state = true;
17294 					continue;
17295 				}
17296 			} else {
17297 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17298 				if (err)
17299 					return err;
17300 			}
17301 		} else if (class == BPF_LD) {
17302 			u8 mode = BPF_MODE(insn->code);
17303 
17304 			if (mode == BPF_ABS || mode == BPF_IND) {
17305 				err = check_ld_abs(env, insn);
17306 				if (err)
17307 					return err;
17308 
17309 			} else if (mode == BPF_IMM) {
17310 				err = check_ld_imm(env, insn);
17311 				if (err)
17312 					return err;
17313 
17314 				env->insn_idx++;
17315 				sanitize_mark_insn_seen(env);
17316 			} else {
17317 				verbose(env, "invalid BPF_LD mode\n");
17318 				return -EINVAL;
17319 			}
17320 		} else {
17321 			verbose(env, "unknown insn class %d\n", class);
17322 			return -EINVAL;
17323 		}
17324 
17325 		env->insn_idx++;
17326 	}
17327 
17328 	return 0;
17329 }
17330 
17331 static int find_btf_percpu_datasec(struct btf *btf)
17332 {
17333 	const struct btf_type *t;
17334 	const char *tname;
17335 	int i, n;
17336 
17337 	/*
17338 	 * Both vmlinux and module each have their own ".data..percpu"
17339 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17340 	 * types to look at only module's own BTF types.
17341 	 */
17342 	n = btf_nr_types(btf);
17343 	if (btf_is_module(btf))
17344 		i = btf_nr_types(btf_vmlinux);
17345 	else
17346 		i = 1;
17347 
17348 	for(; i < n; i++) {
17349 		t = btf_type_by_id(btf, i);
17350 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17351 			continue;
17352 
17353 		tname = btf_name_by_offset(btf, t->name_off);
17354 		if (!strcmp(tname, ".data..percpu"))
17355 			return i;
17356 	}
17357 
17358 	return -ENOENT;
17359 }
17360 
17361 /* replace pseudo btf_id with kernel symbol address */
17362 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17363 			       struct bpf_insn *insn,
17364 			       struct bpf_insn_aux_data *aux)
17365 {
17366 	const struct btf_var_secinfo *vsi;
17367 	const struct btf_type *datasec;
17368 	struct btf_mod_pair *btf_mod;
17369 	const struct btf_type *t;
17370 	const char *sym_name;
17371 	bool percpu = false;
17372 	u32 type, id = insn->imm;
17373 	struct btf *btf;
17374 	s32 datasec_id;
17375 	u64 addr;
17376 	int i, btf_fd, err;
17377 
17378 	btf_fd = insn[1].imm;
17379 	if (btf_fd) {
17380 		btf = btf_get_by_fd(btf_fd);
17381 		if (IS_ERR(btf)) {
17382 			verbose(env, "invalid module BTF object FD specified.\n");
17383 			return -EINVAL;
17384 		}
17385 	} else {
17386 		if (!btf_vmlinux) {
17387 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17388 			return -EINVAL;
17389 		}
17390 		btf = btf_vmlinux;
17391 		btf_get(btf);
17392 	}
17393 
17394 	t = btf_type_by_id(btf, id);
17395 	if (!t) {
17396 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17397 		err = -ENOENT;
17398 		goto err_put;
17399 	}
17400 
17401 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17402 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17403 		err = -EINVAL;
17404 		goto err_put;
17405 	}
17406 
17407 	sym_name = btf_name_by_offset(btf, t->name_off);
17408 	addr = kallsyms_lookup_name(sym_name);
17409 	if (!addr) {
17410 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17411 			sym_name);
17412 		err = -ENOENT;
17413 		goto err_put;
17414 	}
17415 	insn[0].imm = (u32)addr;
17416 	insn[1].imm = addr >> 32;
17417 
17418 	if (btf_type_is_func(t)) {
17419 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17420 		aux->btf_var.mem_size = 0;
17421 		goto check_btf;
17422 	}
17423 
17424 	datasec_id = find_btf_percpu_datasec(btf);
17425 	if (datasec_id > 0) {
17426 		datasec = btf_type_by_id(btf, datasec_id);
17427 		for_each_vsi(i, datasec, vsi) {
17428 			if (vsi->type == id) {
17429 				percpu = true;
17430 				break;
17431 			}
17432 		}
17433 	}
17434 
17435 	type = t->type;
17436 	t = btf_type_skip_modifiers(btf, type, NULL);
17437 	if (percpu) {
17438 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17439 		aux->btf_var.btf = btf;
17440 		aux->btf_var.btf_id = type;
17441 	} else if (!btf_type_is_struct(t)) {
17442 		const struct btf_type *ret;
17443 		const char *tname;
17444 		u32 tsize;
17445 
17446 		/* resolve the type size of ksym. */
17447 		ret = btf_resolve_size(btf, t, &tsize);
17448 		if (IS_ERR(ret)) {
17449 			tname = btf_name_by_offset(btf, t->name_off);
17450 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17451 				tname, PTR_ERR(ret));
17452 			err = -EINVAL;
17453 			goto err_put;
17454 		}
17455 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17456 		aux->btf_var.mem_size = tsize;
17457 	} else {
17458 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17459 		aux->btf_var.btf = btf;
17460 		aux->btf_var.btf_id = type;
17461 	}
17462 check_btf:
17463 	/* check whether we recorded this BTF (and maybe module) already */
17464 	for (i = 0; i < env->used_btf_cnt; i++) {
17465 		if (env->used_btfs[i].btf == btf) {
17466 			btf_put(btf);
17467 			return 0;
17468 		}
17469 	}
17470 
17471 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17472 		err = -E2BIG;
17473 		goto err_put;
17474 	}
17475 
17476 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17477 	btf_mod->btf = btf;
17478 	btf_mod->module = NULL;
17479 
17480 	/* if we reference variables from kernel module, bump its refcount */
17481 	if (btf_is_module(btf)) {
17482 		btf_mod->module = btf_try_get_module(btf);
17483 		if (!btf_mod->module) {
17484 			err = -ENXIO;
17485 			goto err_put;
17486 		}
17487 	}
17488 
17489 	env->used_btf_cnt++;
17490 
17491 	return 0;
17492 err_put:
17493 	btf_put(btf);
17494 	return err;
17495 }
17496 
17497 static bool is_tracing_prog_type(enum bpf_prog_type type)
17498 {
17499 	switch (type) {
17500 	case BPF_PROG_TYPE_KPROBE:
17501 	case BPF_PROG_TYPE_TRACEPOINT:
17502 	case BPF_PROG_TYPE_PERF_EVENT:
17503 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17504 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17505 		return true;
17506 	default:
17507 		return false;
17508 	}
17509 }
17510 
17511 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17512 					struct bpf_map *map,
17513 					struct bpf_prog *prog)
17514 
17515 {
17516 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17517 
17518 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17519 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17520 		if (is_tracing_prog_type(prog_type)) {
17521 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17522 			return -EINVAL;
17523 		}
17524 	}
17525 
17526 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17527 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17528 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17529 			return -EINVAL;
17530 		}
17531 
17532 		if (is_tracing_prog_type(prog_type)) {
17533 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17534 			return -EINVAL;
17535 		}
17536 	}
17537 
17538 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17539 		if (is_tracing_prog_type(prog_type)) {
17540 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17541 			return -EINVAL;
17542 		}
17543 	}
17544 
17545 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17546 	    !bpf_offload_prog_map_match(prog, map)) {
17547 		verbose(env, "offload device mismatch between prog and map\n");
17548 		return -EINVAL;
17549 	}
17550 
17551 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17552 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17553 		return -EINVAL;
17554 	}
17555 
17556 	if (prog->aux->sleepable)
17557 		switch (map->map_type) {
17558 		case BPF_MAP_TYPE_HASH:
17559 		case BPF_MAP_TYPE_LRU_HASH:
17560 		case BPF_MAP_TYPE_ARRAY:
17561 		case BPF_MAP_TYPE_PERCPU_HASH:
17562 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17563 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17564 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17565 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17566 		case BPF_MAP_TYPE_RINGBUF:
17567 		case BPF_MAP_TYPE_USER_RINGBUF:
17568 		case BPF_MAP_TYPE_INODE_STORAGE:
17569 		case BPF_MAP_TYPE_SK_STORAGE:
17570 		case BPF_MAP_TYPE_TASK_STORAGE:
17571 		case BPF_MAP_TYPE_CGRP_STORAGE:
17572 			break;
17573 		default:
17574 			verbose(env,
17575 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17576 			return -EINVAL;
17577 		}
17578 
17579 	return 0;
17580 }
17581 
17582 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17583 {
17584 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17585 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17586 }
17587 
17588 /* find and rewrite pseudo imm in ld_imm64 instructions:
17589  *
17590  * 1. if it accesses map FD, replace it with actual map pointer.
17591  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17592  *
17593  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17594  */
17595 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17596 {
17597 	struct bpf_insn *insn = env->prog->insnsi;
17598 	int insn_cnt = env->prog->len;
17599 	int i, j, err;
17600 
17601 	err = bpf_prog_calc_tag(env->prog);
17602 	if (err)
17603 		return err;
17604 
17605 	for (i = 0; i < insn_cnt; i++, insn++) {
17606 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17607 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17608 		    insn->imm != 0)) {
17609 			verbose(env, "BPF_LDX uses reserved fields\n");
17610 			return -EINVAL;
17611 		}
17612 
17613 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17614 			struct bpf_insn_aux_data *aux;
17615 			struct bpf_map *map;
17616 			struct fd f;
17617 			u64 addr;
17618 			u32 fd;
17619 
17620 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17621 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17622 			    insn[1].off != 0) {
17623 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17624 				return -EINVAL;
17625 			}
17626 
17627 			if (insn[0].src_reg == 0)
17628 				/* valid generic load 64-bit imm */
17629 				goto next_insn;
17630 
17631 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17632 				aux = &env->insn_aux_data[i];
17633 				err = check_pseudo_btf_id(env, insn, aux);
17634 				if (err)
17635 					return err;
17636 				goto next_insn;
17637 			}
17638 
17639 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17640 				aux = &env->insn_aux_data[i];
17641 				aux->ptr_type = PTR_TO_FUNC;
17642 				goto next_insn;
17643 			}
17644 
17645 			/* In final convert_pseudo_ld_imm64() step, this is
17646 			 * converted into regular 64-bit imm load insn.
17647 			 */
17648 			switch (insn[0].src_reg) {
17649 			case BPF_PSEUDO_MAP_VALUE:
17650 			case BPF_PSEUDO_MAP_IDX_VALUE:
17651 				break;
17652 			case BPF_PSEUDO_MAP_FD:
17653 			case BPF_PSEUDO_MAP_IDX:
17654 				if (insn[1].imm == 0)
17655 					break;
17656 				fallthrough;
17657 			default:
17658 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17659 				return -EINVAL;
17660 			}
17661 
17662 			switch (insn[0].src_reg) {
17663 			case BPF_PSEUDO_MAP_IDX_VALUE:
17664 			case BPF_PSEUDO_MAP_IDX:
17665 				if (bpfptr_is_null(env->fd_array)) {
17666 					verbose(env, "fd_idx without fd_array is invalid\n");
17667 					return -EPROTO;
17668 				}
17669 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17670 							    insn[0].imm * sizeof(fd),
17671 							    sizeof(fd)))
17672 					return -EFAULT;
17673 				break;
17674 			default:
17675 				fd = insn[0].imm;
17676 				break;
17677 			}
17678 
17679 			f = fdget(fd);
17680 			map = __bpf_map_get(f);
17681 			if (IS_ERR(map)) {
17682 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17683 				return PTR_ERR(map);
17684 			}
17685 
17686 			err = check_map_prog_compatibility(env, map, env->prog);
17687 			if (err) {
17688 				fdput(f);
17689 				return err;
17690 			}
17691 
17692 			aux = &env->insn_aux_data[i];
17693 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17694 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17695 				addr = (unsigned long)map;
17696 			} else {
17697 				u32 off = insn[1].imm;
17698 
17699 				if (off >= BPF_MAX_VAR_OFF) {
17700 					verbose(env, "direct value offset of %u is not allowed\n", off);
17701 					fdput(f);
17702 					return -EINVAL;
17703 				}
17704 
17705 				if (!map->ops->map_direct_value_addr) {
17706 					verbose(env, "no direct value access support for this map type\n");
17707 					fdput(f);
17708 					return -EINVAL;
17709 				}
17710 
17711 				err = map->ops->map_direct_value_addr(map, &addr, off);
17712 				if (err) {
17713 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17714 						map->value_size, off);
17715 					fdput(f);
17716 					return err;
17717 				}
17718 
17719 				aux->map_off = off;
17720 				addr += off;
17721 			}
17722 
17723 			insn[0].imm = (u32)addr;
17724 			insn[1].imm = addr >> 32;
17725 
17726 			/* check whether we recorded this map already */
17727 			for (j = 0; j < env->used_map_cnt; j++) {
17728 				if (env->used_maps[j] == map) {
17729 					aux->map_index = j;
17730 					fdput(f);
17731 					goto next_insn;
17732 				}
17733 			}
17734 
17735 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17736 				fdput(f);
17737 				return -E2BIG;
17738 			}
17739 
17740 			if (env->prog->aux->sleepable)
17741 				atomic64_inc(&map->sleepable_refcnt);
17742 			/* hold the map. If the program is rejected by verifier,
17743 			 * the map will be released by release_maps() or it
17744 			 * will be used by the valid program until it's unloaded
17745 			 * and all maps are released in bpf_free_used_maps()
17746 			 */
17747 			bpf_map_inc(map);
17748 
17749 			aux->map_index = env->used_map_cnt;
17750 			env->used_maps[env->used_map_cnt++] = map;
17751 
17752 			if (bpf_map_is_cgroup_storage(map) &&
17753 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17754 				verbose(env, "only one cgroup storage of each type is allowed\n");
17755 				fdput(f);
17756 				return -EBUSY;
17757 			}
17758 
17759 			fdput(f);
17760 next_insn:
17761 			insn++;
17762 			i++;
17763 			continue;
17764 		}
17765 
17766 		/* Basic sanity check before we invest more work here. */
17767 		if (!bpf_opcode_in_insntable(insn->code)) {
17768 			verbose(env, "unknown opcode %02x\n", insn->code);
17769 			return -EINVAL;
17770 		}
17771 	}
17772 
17773 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17774 	 * 'struct bpf_map *' into a register instead of user map_fd.
17775 	 * These pointers will be used later by verifier to validate map access.
17776 	 */
17777 	return 0;
17778 }
17779 
17780 /* drop refcnt of maps used by the rejected program */
17781 static void release_maps(struct bpf_verifier_env *env)
17782 {
17783 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17784 			     env->used_map_cnt);
17785 }
17786 
17787 /* drop refcnt of maps used by the rejected program */
17788 static void release_btfs(struct bpf_verifier_env *env)
17789 {
17790 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17791 			     env->used_btf_cnt);
17792 }
17793 
17794 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17795 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17796 {
17797 	struct bpf_insn *insn = env->prog->insnsi;
17798 	int insn_cnt = env->prog->len;
17799 	int i;
17800 
17801 	for (i = 0; i < insn_cnt; i++, insn++) {
17802 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17803 			continue;
17804 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17805 			continue;
17806 		insn->src_reg = 0;
17807 	}
17808 }
17809 
17810 /* single env->prog->insni[off] instruction was replaced with the range
17811  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17812  * [0, off) and [off, end) to new locations, so the patched range stays zero
17813  */
17814 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17815 				 struct bpf_insn_aux_data *new_data,
17816 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17817 {
17818 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17819 	struct bpf_insn *insn = new_prog->insnsi;
17820 	u32 old_seen = old_data[off].seen;
17821 	u32 prog_len;
17822 	int i;
17823 
17824 	/* aux info at OFF always needs adjustment, no matter fast path
17825 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17826 	 * original insn at old prog.
17827 	 */
17828 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17829 
17830 	if (cnt == 1)
17831 		return;
17832 	prog_len = new_prog->len;
17833 
17834 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17835 	memcpy(new_data + off + cnt - 1, old_data + off,
17836 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17837 	for (i = off; i < off + cnt - 1; i++) {
17838 		/* Expand insni[off]'s seen count to the patched range. */
17839 		new_data[i].seen = old_seen;
17840 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17841 	}
17842 	env->insn_aux_data = new_data;
17843 	vfree(old_data);
17844 }
17845 
17846 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17847 {
17848 	int i;
17849 
17850 	if (len == 1)
17851 		return;
17852 	/* NOTE: fake 'exit' subprog should be updated as well. */
17853 	for (i = 0; i <= env->subprog_cnt; i++) {
17854 		if (env->subprog_info[i].start <= off)
17855 			continue;
17856 		env->subprog_info[i].start += len - 1;
17857 	}
17858 }
17859 
17860 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17861 {
17862 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17863 	int i, sz = prog->aux->size_poke_tab;
17864 	struct bpf_jit_poke_descriptor *desc;
17865 
17866 	for (i = 0; i < sz; i++) {
17867 		desc = &tab[i];
17868 		if (desc->insn_idx <= off)
17869 			continue;
17870 		desc->insn_idx += len - 1;
17871 	}
17872 }
17873 
17874 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17875 					    const struct bpf_insn *patch, u32 len)
17876 {
17877 	struct bpf_prog *new_prog;
17878 	struct bpf_insn_aux_data *new_data = NULL;
17879 
17880 	if (len > 1) {
17881 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17882 					      sizeof(struct bpf_insn_aux_data)));
17883 		if (!new_data)
17884 			return NULL;
17885 	}
17886 
17887 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17888 	if (IS_ERR(new_prog)) {
17889 		if (PTR_ERR(new_prog) == -ERANGE)
17890 			verbose(env,
17891 				"insn %d cannot be patched due to 16-bit range\n",
17892 				env->insn_aux_data[off].orig_idx);
17893 		vfree(new_data);
17894 		return NULL;
17895 	}
17896 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17897 	adjust_subprog_starts(env, off, len);
17898 	adjust_poke_descs(new_prog, off, len);
17899 	return new_prog;
17900 }
17901 
17902 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17903 					      u32 off, u32 cnt)
17904 {
17905 	int i, j;
17906 
17907 	/* find first prog starting at or after off (first to remove) */
17908 	for (i = 0; i < env->subprog_cnt; i++)
17909 		if (env->subprog_info[i].start >= off)
17910 			break;
17911 	/* find first prog starting at or after off + cnt (first to stay) */
17912 	for (j = i; j < env->subprog_cnt; j++)
17913 		if (env->subprog_info[j].start >= off + cnt)
17914 			break;
17915 	/* if j doesn't start exactly at off + cnt, we are just removing
17916 	 * the front of previous prog
17917 	 */
17918 	if (env->subprog_info[j].start != off + cnt)
17919 		j--;
17920 
17921 	if (j > i) {
17922 		struct bpf_prog_aux *aux = env->prog->aux;
17923 		int move;
17924 
17925 		/* move fake 'exit' subprog as well */
17926 		move = env->subprog_cnt + 1 - j;
17927 
17928 		memmove(env->subprog_info + i,
17929 			env->subprog_info + j,
17930 			sizeof(*env->subprog_info) * move);
17931 		env->subprog_cnt -= j - i;
17932 
17933 		/* remove func_info */
17934 		if (aux->func_info) {
17935 			move = aux->func_info_cnt - j;
17936 
17937 			memmove(aux->func_info + i,
17938 				aux->func_info + j,
17939 				sizeof(*aux->func_info) * move);
17940 			aux->func_info_cnt -= j - i;
17941 			/* func_info->insn_off is set after all code rewrites,
17942 			 * in adjust_btf_func() - no need to adjust
17943 			 */
17944 		}
17945 	} else {
17946 		/* convert i from "first prog to remove" to "first to adjust" */
17947 		if (env->subprog_info[i].start == off)
17948 			i++;
17949 	}
17950 
17951 	/* update fake 'exit' subprog as well */
17952 	for (; i <= env->subprog_cnt; i++)
17953 		env->subprog_info[i].start -= cnt;
17954 
17955 	return 0;
17956 }
17957 
17958 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17959 				      u32 cnt)
17960 {
17961 	struct bpf_prog *prog = env->prog;
17962 	u32 i, l_off, l_cnt, nr_linfo;
17963 	struct bpf_line_info *linfo;
17964 
17965 	nr_linfo = prog->aux->nr_linfo;
17966 	if (!nr_linfo)
17967 		return 0;
17968 
17969 	linfo = prog->aux->linfo;
17970 
17971 	/* find first line info to remove, count lines to be removed */
17972 	for (i = 0; i < nr_linfo; i++)
17973 		if (linfo[i].insn_off >= off)
17974 			break;
17975 
17976 	l_off = i;
17977 	l_cnt = 0;
17978 	for (; i < nr_linfo; i++)
17979 		if (linfo[i].insn_off < off + cnt)
17980 			l_cnt++;
17981 		else
17982 			break;
17983 
17984 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17985 	 * last removed linfo.  prog is already modified, so prog->len == off
17986 	 * means no live instructions after (tail of the program was removed).
17987 	 */
17988 	if (prog->len != off && l_cnt &&
17989 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17990 		l_cnt--;
17991 		linfo[--i].insn_off = off + cnt;
17992 	}
17993 
17994 	/* remove the line info which refer to the removed instructions */
17995 	if (l_cnt) {
17996 		memmove(linfo + l_off, linfo + i,
17997 			sizeof(*linfo) * (nr_linfo - i));
17998 
17999 		prog->aux->nr_linfo -= l_cnt;
18000 		nr_linfo = prog->aux->nr_linfo;
18001 	}
18002 
18003 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18004 	for (i = l_off; i < nr_linfo; i++)
18005 		linfo[i].insn_off -= cnt;
18006 
18007 	/* fix up all subprogs (incl. 'exit') which start >= off */
18008 	for (i = 0; i <= env->subprog_cnt; i++)
18009 		if (env->subprog_info[i].linfo_idx > l_off) {
18010 			/* program may have started in the removed region but
18011 			 * may not be fully removed
18012 			 */
18013 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18014 				env->subprog_info[i].linfo_idx -= l_cnt;
18015 			else
18016 				env->subprog_info[i].linfo_idx = l_off;
18017 		}
18018 
18019 	return 0;
18020 }
18021 
18022 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18023 {
18024 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18025 	unsigned int orig_prog_len = env->prog->len;
18026 	int err;
18027 
18028 	if (bpf_prog_is_offloaded(env->prog->aux))
18029 		bpf_prog_offload_remove_insns(env, off, cnt);
18030 
18031 	err = bpf_remove_insns(env->prog, off, cnt);
18032 	if (err)
18033 		return err;
18034 
18035 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18036 	if (err)
18037 		return err;
18038 
18039 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18040 	if (err)
18041 		return err;
18042 
18043 	memmove(aux_data + off,	aux_data + off + cnt,
18044 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18045 
18046 	return 0;
18047 }
18048 
18049 /* The verifier does more data flow analysis than llvm and will not
18050  * explore branches that are dead at run time. Malicious programs can
18051  * have dead code too. Therefore replace all dead at-run-time code
18052  * with 'ja -1'.
18053  *
18054  * Just nops are not optimal, e.g. if they would sit at the end of the
18055  * program and through another bug we would manage to jump there, then
18056  * we'd execute beyond program memory otherwise. Returning exception
18057  * code also wouldn't work since we can have subprogs where the dead
18058  * code could be located.
18059  */
18060 static void sanitize_dead_code(struct bpf_verifier_env *env)
18061 {
18062 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18063 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18064 	struct bpf_insn *insn = env->prog->insnsi;
18065 	const int insn_cnt = env->prog->len;
18066 	int i;
18067 
18068 	for (i = 0; i < insn_cnt; i++) {
18069 		if (aux_data[i].seen)
18070 			continue;
18071 		memcpy(insn + i, &trap, sizeof(trap));
18072 		aux_data[i].zext_dst = false;
18073 	}
18074 }
18075 
18076 static bool insn_is_cond_jump(u8 code)
18077 {
18078 	u8 op;
18079 
18080 	op = BPF_OP(code);
18081 	if (BPF_CLASS(code) == BPF_JMP32)
18082 		return op != BPF_JA;
18083 
18084 	if (BPF_CLASS(code) != BPF_JMP)
18085 		return false;
18086 
18087 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18088 }
18089 
18090 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18091 {
18092 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18093 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18094 	struct bpf_insn *insn = env->prog->insnsi;
18095 	const int insn_cnt = env->prog->len;
18096 	int i;
18097 
18098 	for (i = 0; i < insn_cnt; i++, insn++) {
18099 		if (!insn_is_cond_jump(insn->code))
18100 			continue;
18101 
18102 		if (!aux_data[i + 1].seen)
18103 			ja.off = insn->off;
18104 		else if (!aux_data[i + 1 + insn->off].seen)
18105 			ja.off = 0;
18106 		else
18107 			continue;
18108 
18109 		if (bpf_prog_is_offloaded(env->prog->aux))
18110 			bpf_prog_offload_replace_insn(env, i, &ja);
18111 
18112 		memcpy(insn, &ja, sizeof(ja));
18113 	}
18114 }
18115 
18116 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18117 {
18118 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18119 	int insn_cnt = env->prog->len;
18120 	int i, err;
18121 
18122 	for (i = 0; i < insn_cnt; i++) {
18123 		int j;
18124 
18125 		j = 0;
18126 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18127 			j++;
18128 		if (!j)
18129 			continue;
18130 
18131 		err = verifier_remove_insns(env, i, j);
18132 		if (err)
18133 			return err;
18134 		insn_cnt = env->prog->len;
18135 	}
18136 
18137 	return 0;
18138 }
18139 
18140 static int opt_remove_nops(struct bpf_verifier_env *env)
18141 {
18142 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18143 	struct bpf_insn *insn = env->prog->insnsi;
18144 	int insn_cnt = env->prog->len;
18145 	int i, err;
18146 
18147 	for (i = 0; i < insn_cnt; i++) {
18148 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18149 			continue;
18150 
18151 		err = verifier_remove_insns(env, i, 1);
18152 		if (err)
18153 			return err;
18154 		insn_cnt--;
18155 		i--;
18156 	}
18157 
18158 	return 0;
18159 }
18160 
18161 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18162 					 const union bpf_attr *attr)
18163 {
18164 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18165 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18166 	int i, patch_len, delta = 0, len = env->prog->len;
18167 	struct bpf_insn *insns = env->prog->insnsi;
18168 	struct bpf_prog *new_prog;
18169 	bool rnd_hi32;
18170 
18171 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18172 	zext_patch[1] = BPF_ZEXT_REG(0);
18173 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18174 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18175 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18176 	for (i = 0; i < len; i++) {
18177 		int adj_idx = i + delta;
18178 		struct bpf_insn insn;
18179 		int load_reg;
18180 
18181 		insn = insns[adj_idx];
18182 		load_reg = insn_def_regno(&insn);
18183 		if (!aux[adj_idx].zext_dst) {
18184 			u8 code, class;
18185 			u32 imm_rnd;
18186 
18187 			if (!rnd_hi32)
18188 				continue;
18189 
18190 			code = insn.code;
18191 			class = BPF_CLASS(code);
18192 			if (load_reg == -1)
18193 				continue;
18194 
18195 			/* NOTE: arg "reg" (the fourth one) is only used for
18196 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18197 			 *       here.
18198 			 */
18199 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18200 				if (class == BPF_LD &&
18201 				    BPF_MODE(code) == BPF_IMM)
18202 					i++;
18203 				continue;
18204 			}
18205 
18206 			/* ctx load could be transformed into wider load. */
18207 			if (class == BPF_LDX &&
18208 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18209 				continue;
18210 
18211 			imm_rnd = get_random_u32();
18212 			rnd_hi32_patch[0] = insn;
18213 			rnd_hi32_patch[1].imm = imm_rnd;
18214 			rnd_hi32_patch[3].dst_reg = load_reg;
18215 			patch = rnd_hi32_patch;
18216 			patch_len = 4;
18217 			goto apply_patch_buffer;
18218 		}
18219 
18220 		/* Add in an zero-extend instruction if a) the JIT has requested
18221 		 * it or b) it's a CMPXCHG.
18222 		 *
18223 		 * The latter is because: BPF_CMPXCHG always loads a value into
18224 		 * R0, therefore always zero-extends. However some archs'
18225 		 * equivalent instruction only does this load when the
18226 		 * comparison is successful. This detail of CMPXCHG is
18227 		 * orthogonal to the general zero-extension behaviour of the
18228 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18229 		 */
18230 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18231 			continue;
18232 
18233 		/* Zero-extension is done by the caller. */
18234 		if (bpf_pseudo_kfunc_call(&insn))
18235 			continue;
18236 
18237 		if (WARN_ON(load_reg == -1)) {
18238 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18239 			return -EFAULT;
18240 		}
18241 
18242 		zext_patch[0] = insn;
18243 		zext_patch[1].dst_reg = load_reg;
18244 		zext_patch[1].src_reg = load_reg;
18245 		patch = zext_patch;
18246 		patch_len = 2;
18247 apply_patch_buffer:
18248 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18249 		if (!new_prog)
18250 			return -ENOMEM;
18251 		env->prog = new_prog;
18252 		insns = new_prog->insnsi;
18253 		aux = env->insn_aux_data;
18254 		delta += patch_len - 1;
18255 	}
18256 
18257 	return 0;
18258 }
18259 
18260 /* convert load instructions that access fields of a context type into a
18261  * sequence of instructions that access fields of the underlying structure:
18262  *     struct __sk_buff    -> struct sk_buff
18263  *     struct bpf_sock_ops -> struct sock
18264  */
18265 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18266 {
18267 	const struct bpf_verifier_ops *ops = env->ops;
18268 	int i, cnt, size, ctx_field_size, delta = 0;
18269 	const int insn_cnt = env->prog->len;
18270 	struct bpf_insn insn_buf[16], *insn;
18271 	u32 target_size, size_default, off;
18272 	struct bpf_prog *new_prog;
18273 	enum bpf_access_type type;
18274 	bool is_narrower_load;
18275 
18276 	if (ops->gen_prologue || env->seen_direct_write) {
18277 		if (!ops->gen_prologue) {
18278 			verbose(env, "bpf verifier is misconfigured\n");
18279 			return -EINVAL;
18280 		}
18281 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18282 					env->prog);
18283 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18284 			verbose(env, "bpf verifier is misconfigured\n");
18285 			return -EINVAL;
18286 		} else if (cnt) {
18287 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18288 			if (!new_prog)
18289 				return -ENOMEM;
18290 
18291 			env->prog = new_prog;
18292 			delta += cnt - 1;
18293 		}
18294 	}
18295 
18296 	if (bpf_prog_is_offloaded(env->prog->aux))
18297 		return 0;
18298 
18299 	insn = env->prog->insnsi + delta;
18300 
18301 	for (i = 0; i < insn_cnt; i++, insn++) {
18302 		bpf_convert_ctx_access_t convert_ctx_access;
18303 		u8 mode;
18304 
18305 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18306 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18307 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18308 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18309 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18310 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18311 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18312 			type = BPF_READ;
18313 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18314 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18315 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18316 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18317 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18318 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18319 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18320 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18321 			type = BPF_WRITE;
18322 		} else {
18323 			continue;
18324 		}
18325 
18326 		if (type == BPF_WRITE &&
18327 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18328 			struct bpf_insn patch[] = {
18329 				*insn,
18330 				BPF_ST_NOSPEC(),
18331 			};
18332 
18333 			cnt = ARRAY_SIZE(patch);
18334 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18335 			if (!new_prog)
18336 				return -ENOMEM;
18337 
18338 			delta    += cnt - 1;
18339 			env->prog = new_prog;
18340 			insn      = new_prog->insnsi + i + delta;
18341 			continue;
18342 		}
18343 
18344 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18345 		case PTR_TO_CTX:
18346 			if (!ops->convert_ctx_access)
18347 				continue;
18348 			convert_ctx_access = ops->convert_ctx_access;
18349 			break;
18350 		case PTR_TO_SOCKET:
18351 		case PTR_TO_SOCK_COMMON:
18352 			convert_ctx_access = bpf_sock_convert_ctx_access;
18353 			break;
18354 		case PTR_TO_TCP_SOCK:
18355 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18356 			break;
18357 		case PTR_TO_XDP_SOCK:
18358 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18359 			break;
18360 		case PTR_TO_BTF_ID:
18361 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18362 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18363 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18364 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18365 		 * any faults for loads into such types. BPF_WRITE is disallowed
18366 		 * for this case.
18367 		 */
18368 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18369 			if (type == BPF_READ) {
18370 				if (BPF_MODE(insn->code) == BPF_MEM)
18371 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18372 						     BPF_SIZE((insn)->code);
18373 				else
18374 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18375 						     BPF_SIZE((insn)->code);
18376 				env->prog->aux->num_exentries++;
18377 			}
18378 			continue;
18379 		default:
18380 			continue;
18381 		}
18382 
18383 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18384 		size = BPF_LDST_BYTES(insn);
18385 		mode = BPF_MODE(insn->code);
18386 
18387 		/* If the read access is a narrower load of the field,
18388 		 * convert to a 4/8-byte load, to minimum program type specific
18389 		 * convert_ctx_access changes. If conversion is successful,
18390 		 * we will apply proper mask to the result.
18391 		 */
18392 		is_narrower_load = size < ctx_field_size;
18393 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18394 		off = insn->off;
18395 		if (is_narrower_load) {
18396 			u8 size_code;
18397 
18398 			if (type == BPF_WRITE) {
18399 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18400 				return -EINVAL;
18401 			}
18402 
18403 			size_code = BPF_H;
18404 			if (ctx_field_size == 4)
18405 				size_code = BPF_W;
18406 			else if (ctx_field_size == 8)
18407 				size_code = BPF_DW;
18408 
18409 			insn->off = off & ~(size_default - 1);
18410 			insn->code = BPF_LDX | BPF_MEM | size_code;
18411 		}
18412 
18413 		target_size = 0;
18414 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18415 					 &target_size);
18416 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18417 		    (ctx_field_size && !target_size)) {
18418 			verbose(env, "bpf verifier is misconfigured\n");
18419 			return -EINVAL;
18420 		}
18421 
18422 		if (is_narrower_load && size < target_size) {
18423 			u8 shift = bpf_ctx_narrow_access_offset(
18424 				off, size, size_default) * 8;
18425 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18426 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18427 				return -EINVAL;
18428 			}
18429 			if (ctx_field_size <= 4) {
18430 				if (shift)
18431 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18432 									insn->dst_reg,
18433 									shift);
18434 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18435 								(1 << size * 8) - 1);
18436 			} else {
18437 				if (shift)
18438 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18439 									insn->dst_reg,
18440 									shift);
18441 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18442 								(1ULL << size * 8) - 1);
18443 			}
18444 		}
18445 		if (mode == BPF_MEMSX)
18446 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18447 						       insn->dst_reg, insn->dst_reg,
18448 						       size * 8, 0);
18449 
18450 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18451 		if (!new_prog)
18452 			return -ENOMEM;
18453 
18454 		delta += cnt - 1;
18455 
18456 		/* keep walking new program and skip insns we just inserted */
18457 		env->prog = new_prog;
18458 		insn      = new_prog->insnsi + i + delta;
18459 	}
18460 
18461 	return 0;
18462 }
18463 
18464 static int jit_subprogs(struct bpf_verifier_env *env)
18465 {
18466 	struct bpf_prog *prog = env->prog, **func, *tmp;
18467 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18468 	struct bpf_map *map_ptr;
18469 	struct bpf_insn *insn;
18470 	void *old_bpf_func;
18471 	int err, num_exentries;
18472 
18473 	if (env->subprog_cnt <= 1)
18474 		return 0;
18475 
18476 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18477 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18478 			continue;
18479 
18480 		/* Upon error here we cannot fall back to interpreter but
18481 		 * need a hard reject of the program. Thus -EFAULT is
18482 		 * propagated in any case.
18483 		 */
18484 		subprog = find_subprog(env, i + insn->imm + 1);
18485 		if (subprog < 0) {
18486 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18487 				  i + insn->imm + 1);
18488 			return -EFAULT;
18489 		}
18490 		/* temporarily remember subprog id inside insn instead of
18491 		 * aux_data, since next loop will split up all insns into funcs
18492 		 */
18493 		insn->off = subprog;
18494 		/* remember original imm in case JIT fails and fallback
18495 		 * to interpreter will be needed
18496 		 */
18497 		env->insn_aux_data[i].call_imm = insn->imm;
18498 		/* point imm to __bpf_call_base+1 from JITs point of view */
18499 		insn->imm = 1;
18500 		if (bpf_pseudo_func(insn))
18501 			/* jit (e.g. x86_64) may emit fewer instructions
18502 			 * if it learns a u32 imm is the same as a u64 imm.
18503 			 * Force a non zero here.
18504 			 */
18505 			insn[1].imm = 1;
18506 	}
18507 
18508 	err = bpf_prog_alloc_jited_linfo(prog);
18509 	if (err)
18510 		goto out_undo_insn;
18511 
18512 	err = -ENOMEM;
18513 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18514 	if (!func)
18515 		goto out_undo_insn;
18516 
18517 	for (i = 0; i < env->subprog_cnt; i++) {
18518 		subprog_start = subprog_end;
18519 		subprog_end = env->subprog_info[i + 1].start;
18520 
18521 		len = subprog_end - subprog_start;
18522 		/* bpf_prog_run() doesn't call subprogs directly,
18523 		 * hence main prog stats include the runtime of subprogs.
18524 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18525 		 * func[i]->stats will never be accessed and stays NULL
18526 		 */
18527 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18528 		if (!func[i])
18529 			goto out_free;
18530 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18531 		       len * sizeof(struct bpf_insn));
18532 		func[i]->type = prog->type;
18533 		func[i]->len = len;
18534 		if (bpf_prog_calc_tag(func[i]))
18535 			goto out_free;
18536 		func[i]->is_func = 1;
18537 		func[i]->aux->func_idx = i;
18538 		/* Below members will be freed only at prog->aux */
18539 		func[i]->aux->btf = prog->aux->btf;
18540 		func[i]->aux->func_info = prog->aux->func_info;
18541 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18542 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18543 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18544 
18545 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18546 			struct bpf_jit_poke_descriptor *poke;
18547 
18548 			poke = &prog->aux->poke_tab[j];
18549 			if (poke->insn_idx < subprog_end &&
18550 			    poke->insn_idx >= subprog_start)
18551 				poke->aux = func[i]->aux;
18552 		}
18553 
18554 		func[i]->aux->name[0] = 'F';
18555 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18556 		func[i]->jit_requested = 1;
18557 		func[i]->blinding_requested = prog->blinding_requested;
18558 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18559 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18560 		func[i]->aux->linfo = prog->aux->linfo;
18561 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18562 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18563 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18564 		num_exentries = 0;
18565 		insn = func[i]->insnsi;
18566 		for (j = 0; j < func[i]->len; j++, insn++) {
18567 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18568 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18569 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18570 				num_exentries++;
18571 		}
18572 		func[i]->aux->num_exentries = num_exentries;
18573 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18574 		func[i] = bpf_int_jit_compile(func[i]);
18575 		if (!func[i]->jited) {
18576 			err = -ENOTSUPP;
18577 			goto out_free;
18578 		}
18579 		cond_resched();
18580 	}
18581 
18582 	/* at this point all bpf functions were successfully JITed
18583 	 * now populate all bpf_calls with correct addresses and
18584 	 * run last pass of JIT
18585 	 */
18586 	for (i = 0; i < env->subprog_cnt; i++) {
18587 		insn = func[i]->insnsi;
18588 		for (j = 0; j < func[i]->len; j++, insn++) {
18589 			if (bpf_pseudo_func(insn)) {
18590 				subprog = insn->off;
18591 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18592 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18593 				continue;
18594 			}
18595 			if (!bpf_pseudo_call(insn))
18596 				continue;
18597 			subprog = insn->off;
18598 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18599 		}
18600 
18601 		/* we use the aux data to keep a list of the start addresses
18602 		 * of the JITed images for each function in the program
18603 		 *
18604 		 * for some architectures, such as powerpc64, the imm field
18605 		 * might not be large enough to hold the offset of the start
18606 		 * address of the callee's JITed image from __bpf_call_base
18607 		 *
18608 		 * in such cases, we can lookup the start address of a callee
18609 		 * by using its subprog id, available from the off field of
18610 		 * the call instruction, as an index for this list
18611 		 */
18612 		func[i]->aux->func = func;
18613 		func[i]->aux->func_cnt = env->subprog_cnt;
18614 	}
18615 	for (i = 0; i < env->subprog_cnt; i++) {
18616 		old_bpf_func = func[i]->bpf_func;
18617 		tmp = bpf_int_jit_compile(func[i]);
18618 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18619 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18620 			err = -ENOTSUPP;
18621 			goto out_free;
18622 		}
18623 		cond_resched();
18624 	}
18625 
18626 	/* finally lock prog and jit images for all functions and
18627 	 * populate kallsysm. Begin at the first subprogram, since
18628 	 * bpf_prog_load will add the kallsyms for the main program.
18629 	 */
18630 	for (i = 1; i < env->subprog_cnt; i++) {
18631 		bpf_prog_lock_ro(func[i]);
18632 		bpf_prog_kallsyms_add(func[i]);
18633 	}
18634 
18635 	/* Last step: make now unused interpreter insns from main
18636 	 * prog consistent for later dump requests, so they can
18637 	 * later look the same as if they were interpreted only.
18638 	 */
18639 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18640 		if (bpf_pseudo_func(insn)) {
18641 			insn[0].imm = env->insn_aux_data[i].call_imm;
18642 			insn[1].imm = insn->off;
18643 			insn->off = 0;
18644 			continue;
18645 		}
18646 		if (!bpf_pseudo_call(insn))
18647 			continue;
18648 		insn->off = env->insn_aux_data[i].call_imm;
18649 		subprog = find_subprog(env, i + insn->off + 1);
18650 		insn->imm = subprog;
18651 	}
18652 
18653 	prog->jited = 1;
18654 	prog->bpf_func = func[0]->bpf_func;
18655 	prog->jited_len = func[0]->jited_len;
18656 	prog->aux->extable = func[0]->aux->extable;
18657 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18658 	prog->aux->func = func;
18659 	prog->aux->func_cnt = env->subprog_cnt;
18660 	bpf_prog_jit_attempt_done(prog);
18661 	return 0;
18662 out_free:
18663 	/* We failed JIT'ing, so at this point we need to unregister poke
18664 	 * descriptors from subprogs, so that kernel is not attempting to
18665 	 * patch it anymore as we're freeing the subprog JIT memory.
18666 	 */
18667 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18668 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18669 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18670 	}
18671 	/* At this point we're guaranteed that poke descriptors are not
18672 	 * live anymore. We can just unlink its descriptor table as it's
18673 	 * released with the main prog.
18674 	 */
18675 	for (i = 0; i < env->subprog_cnt; i++) {
18676 		if (!func[i])
18677 			continue;
18678 		func[i]->aux->poke_tab = NULL;
18679 		bpf_jit_free(func[i]);
18680 	}
18681 	kfree(func);
18682 out_undo_insn:
18683 	/* cleanup main prog to be interpreted */
18684 	prog->jit_requested = 0;
18685 	prog->blinding_requested = 0;
18686 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18687 		if (!bpf_pseudo_call(insn))
18688 			continue;
18689 		insn->off = 0;
18690 		insn->imm = env->insn_aux_data[i].call_imm;
18691 	}
18692 	bpf_prog_jit_attempt_done(prog);
18693 	return err;
18694 }
18695 
18696 static int fixup_call_args(struct bpf_verifier_env *env)
18697 {
18698 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18699 	struct bpf_prog *prog = env->prog;
18700 	struct bpf_insn *insn = prog->insnsi;
18701 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18702 	int i, depth;
18703 #endif
18704 	int err = 0;
18705 
18706 	if (env->prog->jit_requested &&
18707 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18708 		err = jit_subprogs(env);
18709 		if (err == 0)
18710 			return 0;
18711 		if (err == -EFAULT)
18712 			return err;
18713 	}
18714 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18715 	if (has_kfunc_call) {
18716 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18717 		return -EINVAL;
18718 	}
18719 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18720 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18721 		 * have to be rejected, since interpreter doesn't support them yet.
18722 		 */
18723 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18724 		return -EINVAL;
18725 	}
18726 	for (i = 0; i < prog->len; i++, insn++) {
18727 		if (bpf_pseudo_func(insn)) {
18728 			/* When JIT fails the progs with callback calls
18729 			 * have to be rejected, since interpreter doesn't support them yet.
18730 			 */
18731 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18732 			return -EINVAL;
18733 		}
18734 
18735 		if (!bpf_pseudo_call(insn))
18736 			continue;
18737 		depth = get_callee_stack_depth(env, insn, i);
18738 		if (depth < 0)
18739 			return depth;
18740 		bpf_patch_call_args(insn, depth);
18741 	}
18742 	err = 0;
18743 #endif
18744 	return err;
18745 }
18746 
18747 /* replace a generic kfunc with a specialized version if necessary */
18748 static void specialize_kfunc(struct bpf_verifier_env *env,
18749 			     u32 func_id, u16 offset, unsigned long *addr)
18750 {
18751 	struct bpf_prog *prog = env->prog;
18752 	bool seen_direct_write;
18753 	void *xdp_kfunc;
18754 	bool is_rdonly;
18755 
18756 	if (bpf_dev_bound_kfunc_id(func_id)) {
18757 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18758 		if (xdp_kfunc) {
18759 			*addr = (unsigned long)xdp_kfunc;
18760 			return;
18761 		}
18762 		/* fallback to default kfunc when not supported by netdev */
18763 	}
18764 
18765 	if (offset)
18766 		return;
18767 
18768 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18769 		seen_direct_write = env->seen_direct_write;
18770 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18771 
18772 		if (is_rdonly)
18773 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18774 
18775 		/* restore env->seen_direct_write to its original value, since
18776 		 * may_access_direct_pkt_data mutates it
18777 		 */
18778 		env->seen_direct_write = seen_direct_write;
18779 	}
18780 }
18781 
18782 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18783 					    u16 struct_meta_reg,
18784 					    u16 node_offset_reg,
18785 					    struct bpf_insn *insn,
18786 					    struct bpf_insn *insn_buf,
18787 					    int *cnt)
18788 {
18789 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18790 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18791 
18792 	insn_buf[0] = addr[0];
18793 	insn_buf[1] = addr[1];
18794 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18795 	insn_buf[3] = *insn;
18796 	*cnt = 4;
18797 }
18798 
18799 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18800 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18801 {
18802 	const struct bpf_kfunc_desc *desc;
18803 
18804 	if (!insn->imm) {
18805 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18806 		return -EINVAL;
18807 	}
18808 
18809 	*cnt = 0;
18810 
18811 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18812 	 * __bpf_call_base, unless the JIT needs to call functions that are
18813 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18814 	 */
18815 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18816 	if (!desc) {
18817 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18818 			insn->imm);
18819 		return -EFAULT;
18820 	}
18821 
18822 	if (!bpf_jit_supports_far_kfunc_call())
18823 		insn->imm = BPF_CALL_IMM(desc->addr);
18824 	if (insn->off)
18825 		return 0;
18826 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18827 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18828 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18829 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18830 
18831 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18832 		insn_buf[1] = addr[0];
18833 		insn_buf[2] = addr[1];
18834 		insn_buf[3] = *insn;
18835 		*cnt = 4;
18836 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18837 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18838 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18839 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18840 
18841 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18842 		    !kptr_struct_meta) {
18843 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18844 				insn_idx);
18845 			return -EFAULT;
18846 		}
18847 
18848 		insn_buf[0] = addr[0];
18849 		insn_buf[1] = addr[1];
18850 		insn_buf[2] = *insn;
18851 		*cnt = 3;
18852 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18853 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18854 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18855 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18856 		int struct_meta_reg = BPF_REG_3;
18857 		int node_offset_reg = BPF_REG_4;
18858 
18859 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18860 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18861 			struct_meta_reg = BPF_REG_4;
18862 			node_offset_reg = BPF_REG_5;
18863 		}
18864 
18865 		if (!kptr_struct_meta) {
18866 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18867 				insn_idx);
18868 			return -EFAULT;
18869 		}
18870 
18871 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18872 						node_offset_reg, insn, insn_buf, cnt);
18873 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18874 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18875 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18876 		*cnt = 1;
18877 	}
18878 	return 0;
18879 }
18880 
18881 /* Do various post-verification rewrites in a single program pass.
18882  * These rewrites simplify JIT and interpreter implementations.
18883  */
18884 static int do_misc_fixups(struct bpf_verifier_env *env)
18885 {
18886 	struct bpf_prog *prog = env->prog;
18887 	enum bpf_attach_type eatype = prog->expected_attach_type;
18888 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18889 	struct bpf_insn *insn = prog->insnsi;
18890 	const struct bpf_func_proto *fn;
18891 	const int insn_cnt = prog->len;
18892 	const struct bpf_map_ops *ops;
18893 	struct bpf_insn_aux_data *aux;
18894 	struct bpf_insn insn_buf[16];
18895 	struct bpf_prog *new_prog;
18896 	struct bpf_map *map_ptr;
18897 	int i, ret, cnt, delta = 0;
18898 
18899 	for (i = 0; i < insn_cnt; i++, insn++) {
18900 		/* Make divide-by-zero exceptions impossible. */
18901 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18902 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18903 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18904 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18905 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18906 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18907 			struct bpf_insn *patchlet;
18908 			struct bpf_insn chk_and_div[] = {
18909 				/* [R,W]x div 0 -> 0 */
18910 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18911 					     BPF_JNE | BPF_K, insn->src_reg,
18912 					     0, 2, 0),
18913 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18914 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18915 				*insn,
18916 			};
18917 			struct bpf_insn chk_and_mod[] = {
18918 				/* [R,W]x mod 0 -> [R,W]x */
18919 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18920 					     BPF_JEQ | BPF_K, insn->src_reg,
18921 					     0, 1 + (is64 ? 0 : 1), 0),
18922 				*insn,
18923 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18924 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18925 			};
18926 
18927 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18928 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18929 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18930 
18931 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18932 			if (!new_prog)
18933 				return -ENOMEM;
18934 
18935 			delta    += cnt - 1;
18936 			env->prog = prog = new_prog;
18937 			insn      = new_prog->insnsi + i + delta;
18938 			continue;
18939 		}
18940 
18941 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18942 		if (BPF_CLASS(insn->code) == BPF_LD &&
18943 		    (BPF_MODE(insn->code) == BPF_ABS ||
18944 		     BPF_MODE(insn->code) == BPF_IND)) {
18945 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18946 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18947 				verbose(env, "bpf verifier is misconfigured\n");
18948 				return -EINVAL;
18949 			}
18950 
18951 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18952 			if (!new_prog)
18953 				return -ENOMEM;
18954 
18955 			delta    += cnt - 1;
18956 			env->prog = prog = new_prog;
18957 			insn      = new_prog->insnsi + i + delta;
18958 			continue;
18959 		}
18960 
18961 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18962 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18963 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18964 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18965 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18966 			struct bpf_insn *patch = &insn_buf[0];
18967 			bool issrc, isneg, isimm;
18968 			u32 off_reg;
18969 
18970 			aux = &env->insn_aux_data[i + delta];
18971 			if (!aux->alu_state ||
18972 			    aux->alu_state == BPF_ALU_NON_POINTER)
18973 				continue;
18974 
18975 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18976 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18977 				BPF_ALU_SANITIZE_SRC;
18978 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18979 
18980 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18981 			if (isimm) {
18982 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18983 			} else {
18984 				if (isneg)
18985 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18986 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18987 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18988 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18989 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18990 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18991 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18992 			}
18993 			if (!issrc)
18994 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18995 			insn->src_reg = BPF_REG_AX;
18996 			if (isneg)
18997 				insn->code = insn->code == code_add ?
18998 					     code_sub : code_add;
18999 			*patch++ = *insn;
19000 			if (issrc && isneg && !isimm)
19001 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19002 			cnt = patch - insn_buf;
19003 
19004 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19005 			if (!new_prog)
19006 				return -ENOMEM;
19007 
19008 			delta    += cnt - 1;
19009 			env->prog = prog = new_prog;
19010 			insn      = new_prog->insnsi + i + delta;
19011 			continue;
19012 		}
19013 
19014 		if (insn->code != (BPF_JMP | BPF_CALL))
19015 			continue;
19016 		if (insn->src_reg == BPF_PSEUDO_CALL)
19017 			continue;
19018 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19019 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19020 			if (ret)
19021 				return ret;
19022 			if (cnt == 0)
19023 				continue;
19024 
19025 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19026 			if (!new_prog)
19027 				return -ENOMEM;
19028 
19029 			delta	 += cnt - 1;
19030 			env->prog = prog = new_prog;
19031 			insn	  = new_prog->insnsi + i + delta;
19032 			continue;
19033 		}
19034 
19035 		if (insn->imm == BPF_FUNC_get_route_realm)
19036 			prog->dst_needed = 1;
19037 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19038 			bpf_user_rnd_init_once();
19039 		if (insn->imm == BPF_FUNC_override_return)
19040 			prog->kprobe_override = 1;
19041 		if (insn->imm == BPF_FUNC_tail_call) {
19042 			/* If we tail call into other programs, we
19043 			 * cannot make any assumptions since they can
19044 			 * be replaced dynamically during runtime in
19045 			 * the program array.
19046 			 */
19047 			prog->cb_access = 1;
19048 			if (!allow_tail_call_in_subprogs(env))
19049 				prog->aux->stack_depth = MAX_BPF_STACK;
19050 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19051 
19052 			/* mark bpf_tail_call as different opcode to avoid
19053 			 * conditional branch in the interpreter for every normal
19054 			 * call and to prevent accidental JITing by JIT compiler
19055 			 * that doesn't support bpf_tail_call yet
19056 			 */
19057 			insn->imm = 0;
19058 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19059 
19060 			aux = &env->insn_aux_data[i + delta];
19061 			if (env->bpf_capable && !prog->blinding_requested &&
19062 			    prog->jit_requested &&
19063 			    !bpf_map_key_poisoned(aux) &&
19064 			    !bpf_map_ptr_poisoned(aux) &&
19065 			    !bpf_map_ptr_unpriv(aux)) {
19066 				struct bpf_jit_poke_descriptor desc = {
19067 					.reason = BPF_POKE_REASON_TAIL_CALL,
19068 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19069 					.tail_call.key = bpf_map_key_immediate(aux),
19070 					.insn_idx = i + delta,
19071 				};
19072 
19073 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19074 				if (ret < 0) {
19075 					verbose(env, "adding tail call poke descriptor failed\n");
19076 					return ret;
19077 				}
19078 
19079 				insn->imm = ret + 1;
19080 				continue;
19081 			}
19082 
19083 			if (!bpf_map_ptr_unpriv(aux))
19084 				continue;
19085 
19086 			/* instead of changing every JIT dealing with tail_call
19087 			 * emit two extra insns:
19088 			 * if (index >= max_entries) goto out;
19089 			 * index &= array->index_mask;
19090 			 * to avoid out-of-bounds cpu speculation
19091 			 */
19092 			if (bpf_map_ptr_poisoned(aux)) {
19093 				verbose(env, "tail_call abusing map_ptr\n");
19094 				return -EINVAL;
19095 			}
19096 
19097 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19098 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19099 						  map_ptr->max_entries, 2);
19100 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19101 						    container_of(map_ptr,
19102 								 struct bpf_array,
19103 								 map)->index_mask);
19104 			insn_buf[2] = *insn;
19105 			cnt = 3;
19106 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19107 			if (!new_prog)
19108 				return -ENOMEM;
19109 
19110 			delta    += cnt - 1;
19111 			env->prog = prog = new_prog;
19112 			insn      = new_prog->insnsi + i + delta;
19113 			continue;
19114 		}
19115 
19116 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19117 			/* The verifier will process callback_fn as many times as necessary
19118 			 * with different maps and the register states prepared by
19119 			 * set_timer_callback_state will be accurate.
19120 			 *
19121 			 * The following use case is valid:
19122 			 *   map1 is shared by prog1, prog2, prog3.
19123 			 *   prog1 calls bpf_timer_init for some map1 elements
19124 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19125 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19126 			 *   prog3 calls bpf_timer_start for some map1 elements.
19127 			 *     Those that were not both bpf_timer_init-ed and
19128 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19129 			 */
19130 			struct bpf_insn ld_addrs[2] = {
19131 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19132 			};
19133 
19134 			insn_buf[0] = ld_addrs[0];
19135 			insn_buf[1] = ld_addrs[1];
19136 			insn_buf[2] = *insn;
19137 			cnt = 3;
19138 
19139 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19140 			if (!new_prog)
19141 				return -ENOMEM;
19142 
19143 			delta    += cnt - 1;
19144 			env->prog = prog = new_prog;
19145 			insn      = new_prog->insnsi + i + delta;
19146 			goto patch_call_imm;
19147 		}
19148 
19149 		if (is_storage_get_function(insn->imm)) {
19150 			if (!env->prog->aux->sleepable ||
19151 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19152 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19153 			else
19154 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19155 			insn_buf[1] = *insn;
19156 			cnt = 2;
19157 
19158 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19159 			if (!new_prog)
19160 				return -ENOMEM;
19161 
19162 			delta += cnt - 1;
19163 			env->prog = prog = new_prog;
19164 			insn = new_prog->insnsi + i + delta;
19165 			goto patch_call_imm;
19166 		}
19167 
19168 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19169 		 * and other inlining handlers are currently limited to 64 bit
19170 		 * only.
19171 		 */
19172 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19173 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19174 		     insn->imm == BPF_FUNC_map_update_elem ||
19175 		     insn->imm == BPF_FUNC_map_delete_elem ||
19176 		     insn->imm == BPF_FUNC_map_push_elem   ||
19177 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19178 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19179 		     insn->imm == BPF_FUNC_redirect_map    ||
19180 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19181 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19182 			aux = &env->insn_aux_data[i + delta];
19183 			if (bpf_map_ptr_poisoned(aux))
19184 				goto patch_call_imm;
19185 
19186 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19187 			ops = map_ptr->ops;
19188 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19189 			    ops->map_gen_lookup) {
19190 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19191 				if (cnt == -EOPNOTSUPP)
19192 					goto patch_map_ops_generic;
19193 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19194 					verbose(env, "bpf verifier is misconfigured\n");
19195 					return -EINVAL;
19196 				}
19197 
19198 				new_prog = bpf_patch_insn_data(env, i + delta,
19199 							       insn_buf, cnt);
19200 				if (!new_prog)
19201 					return -ENOMEM;
19202 
19203 				delta    += cnt - 1;
19204 				env->prog = prog = new_prog;
19205 				insn      = new_prog->insnsi + i + delta;
19206 				continue;
19207 			}
19208 
19209 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19210 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19211 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19212 				     (long (*)(struct bpf_map *map, void *key))NULL));
19213 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19214 				     (long (*)(struct bpf_map *map, void *key, void *value,
19215 					      u64 flags))NULL));
19216 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19217 				     (long (*)(struct bpf_map *map, void *value,
19218 					      u64 flags))NULL));
19219 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19220 				     (long (*)(struct bpf_map *map, void *value))NULL));
19221 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19222 				     (long (*)(struct bpf_map *map, void *value))NULL));
19223 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19224 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19225 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19226 				     (long (*)(struct bpf_map *map,
19227 					      bpf_callback_t callback_fn,
19228 					      void *callback_ctx,
19229 					      u64 flags))NULL));
19230 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19231 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19232 
19233 patch_map_ops_generic:
19234 			switch (insn->imm) {
19235 			case BPF_FUNC_map_lookup_elem:
19236 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19237 				continue;
19238 			case BPF_FUNC_map_update_elem:
19239 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19240 				continue;
19241 			case BPF_FUNC_map_delete_elem:
19242 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19243 				continue;
19244 			case BPF_FUNC_map_push_elem:
19245 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19246 				continue;
19247 			case BPF_FUNC_map_pop_elem:
19248 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19249 				continue;
19250 			case BPF_FUNC_map_peek_elem:
19251 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19252 				continue;
19253 			case BPF_FUNC_redirect_map:
19254 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19255 				continue;
19256 			case BPF_FUNC_for_each_map_elem:
19257 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19258 				continue;
19259 			case BPF_FUNC_map_lookup_percpu_elem:
19260 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19261 				continue;
19262 			}
19263 
19264 			goto patch_call_imm;
19265 		}
19266 
19267 		/* Implement bpf_jiffies64 inline. */
19268 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19269 		    insn->imm == BPF_FUNC_jiffies64) {
19270 			struct bpf_insn ld_jiffies_addr[2] = {
19271 				BPF_LD_IMM64(BPF_REG_0,
19272 					     (unsigned long)&jiffies),
19273 			};
19274 
19275 			insn_buf[0] = ld_jiffies_addr[0];
19276 			insn_buf[1] = ld_jiffies_addr[1];
19277 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19278 						  BPF_REG_0, 0);
19279 			cnt = 3;
19280 
19281 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19282 						       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_arg inline. */
19293 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19294 		    insn->imm == BPF_FUNC_get_func_arg) {
19295 			/* Load nr_args from ctx - 8 */
19296 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19297 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19298 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19299 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19300 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19301 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19302 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19303 			insn_buf[7] = BPF_JMP_A(1);
19304 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19305 			cnt = 9;
19306 
19307 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19308 			if (!new_prog)
19309 				return -ENOMEM;
19310 
19311 			delta    += cnt - 1;
19312 			env->prog = prog = new_prog;
19313 			insn      = new_prog->insnsi + i + delta;
19314 			continue;
19315 		}
19316 
19317 		/* Implement bpf_get_func_ret inline. */
19318 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19319 		    insn->imm == BPF_FUNC_get_func_ret) {
19320 			if (eatype == BPF_TRACE_FEXIT ||
19321 			    eatype == BPF_MODIFY_RETURN) {
19322 				/* Load nr_args from ctx - 8 */
19323 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19324 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19325 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19326 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19327 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19328 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19329 				cnt = 6;
19330 			} else {
19331 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19332 				cnt = 1;
19333 			}
19334 
19335 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19336 			if (!new_prog)
19337 				return -ENOMEM;
19338 
19339 			delta    += cnt - 1;
19340 			env->prog = prog = new_prog;
19341 			insn      = new_prog->insnsi + i + delta;
19342 			continue;
19343 		}
19344 
19345 		/* Implement get_func_arg_cnt inline. */
19346 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19347 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19348 			/* Load nr_args from ctx - 8 */
19349 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19350 
19351 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19352 			if (!new_prog)
19353 				return -ENOMEM;
19354 
19355 			env->prog = prog = new_prog;
19356 			insn      = new_prog->insnsi + i + delta;
19357 			continue;
19358 		}
19359 
19360 		/* Implement bpf_get_func_ip inline. */
19361 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19362 		    insn->imm == BPF_FUNC_get_func_ip) {
19363 			/* Load IP address from ctx - 16 */
19364 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19365 
19366 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19367 			if (!new_prog)
19368 				return -ENOMEM;
19369 
19370 			env->prog = prog = new_prog;
19371 			insn      = new_prog->insnsi + i + delta;
19372 			continue;
19373 		}
19374 
19375 patch_call_imm:
19376 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19377 		/* all functions that have prototype and verifier allowed
19378 		 * programs to call them, must be real in-kernel functions
19379 		 */
19380 		if (!fn->func) {
19381 			verbose(env,
19382 				"kernel subsystem misconfigured func %s#%d\n",
19383 				func_id_name(insn->imm), insn->imm);
19384 			return -EFAULT;
19385 		}
19386 		insn->imm = fn->func - __bpf_call_base;
19387 	}
19388 
19389 	/* Since poke tab is now finalized, publish aux to tracker. */
19390 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19391 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19392 		if (!map_ptr->ops->map_poke_track ||
19393 		    !map_ptr->ops->map_poke_untrack ||
19394 		    !map_ptr->ops->map_poke_run) {
19395 			verbose(env, "bpf verifier is misconfigured\n");
19396 			return -EINVAL;
19397 		}
19398 
19399 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19400 		if (ret < 0) {
19401 			verbose(env, "tracking tail call prog failed\n");
19402 			return ret;
19403 		}
19404 	}
19405 
19406 	sort_kfunc_descs_by_imm_off(env->prog);
19407 
19408 	return 0;
19409 }
19410 
19411 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19412 					int position,
19413 					s32 stack_base,
19414 					u32 callback_subprogno,
19415 					u32 *cnt)
19416 {
19417 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19418 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19419 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19420 	int reg_loop_max = BPF_REG_6;
19421 	int reg_loop_cnt = BPF_REG_7;
19422 	int reg_loop_ctx = BPF_REG_8;
19423 
19424 	struct bpf_prog *new_prog;
19425 	u32 callback_start;
19426 	u32 call_insn_offset;
19427 	s32 callback_offset;
19428 
19429 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19430 	 * be careful to modify this code in sync.
19431 	 */
19432 	struct bpf_insn insn_buf[] = {
19433 		/* Return error and jump to the end of the patch if
19434 		 * expected number of iterations is too big.
19435 		 */
19436 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19437 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19438 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19439 		/* spill R6, R7, R8 to use these as loop vars */
19440 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19441 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19442 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19443 		/* initialize loop vars */
19444 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19445 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19446 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19447 		/* loop header,
19448 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19449 		 */
19450 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19451 		/* callback call,
19452 		 * correct callback offset would be set after patching
19453 		 */
19454 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19455 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19456 		BPF_CALL_REL(0),
19457 		/* increment loop counter */
19458 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19459 		/* jump to loop header if callback returned 0 */
19460 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19461 		/* return value of bpf_loop,
19462 		 * set R0 to the number of iterations
19463 		 */
19464 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19465 		/* restore original values of R6, R7, R8 */
19466 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19467 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19468 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19469 	};
19470 
19471 	*cnt = ARRAY_SIZE(insn_buf);
19472 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19473 	if (!new_prog)
19474 		return new_prog;
19475 
19476 	/* callback start is known only after patching */
19477 	callback_start = env->subprog_info[callback_subprogno].start;
19478 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19479 	call_insn_offset = position + 12;
19480 	callback_offset = callback_start - call_insn_offset - 1;
19481 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19482 
19483 	return new_prog;
19484 }
19485 
19486 static bool is_bpf_loop_call(struct bpf_insn *insn)
19487 {
19488 	return insn->code == (BPF_JMP | BPF_CALL) &&
19489 		insn->src_reg == 0 &&
19490 		insn->imm == BPF_FUNC_loop;
19491 }
19492 
19493 /* For all sub-programs in the program (including main) check
19494  * insn_aux_data to see if there are bpf_loop calls that require
19495  * inlining. If such calls are found the calls are replaced with a
19496  * sequence of instructions produced by `inline_bpf_loop` function and
19497  * subprog stack_depth is increased by the size of 3 registers.
19498  * This stack space is used to spill values of the R6, R7, R8.  These
19499  * registers are used to store the loop bound, counter and context
19500  * variables.
19501  */
19502 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19503 {
19504 	struct bpf_subprog_info *subprogs = env->subprog_info;
19505 	int i, cur_subprog = 0, cnt, delta = 0;
19506 	struct bpf_insn *insn = env->prog->insnsi;
19507 	int insn_cnt = env->prog->len;
19508 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19509 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19510 	u16 stack_depth_extra = 0;
19511 
19512 	for (i = 0; i < insn_cnt; i++, insn++) {
19513 		struct bpf_loop_inline_state *inline_state =
19514 			&env->insn_aux_data[i + delta].loop_inline_state;
19515 
19516 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19517 			struct bpf_prog *new_prog;
19518 
19519 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19520 			new_prog = inline_bpf_loop(env,
19521 						   i + delta,
19522 						   -(stack_depth + stack_depth_extra),
19523 						   inline_state->callback_subprogno,
19524 						   &cnt);
19525 			if (!new_prog)
19526 				return -ENOMEM;
19527 
19528 			delta     += cnt - 1;
19529 			env->prog  = new_prog;
19530 			insn       = new_prog->insnsi + i + delta;
19531 		}
19532 
19533 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19534 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19535 			cur_subprog++;
19536 			stack_depth = subprogs[cur_subprog].stack_depth;
19537 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19538 			stack_depth_extra = 0;
19539 		}
19540 	}
19541 
19542 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19543 
19544 	return 0;
19545 }
19546 
19547 static void free_states(struct bpf_verifier_env *env)
19548 {
19549 	struct bpf_verifier_state_list *sl, *sln;
19550 	int i;
19551 
19552 	sl = env->free_list;
19553 	while (sl) {
19554 		sln = sl->next;
19555 		free_verifier_state(&sl->state, false);
19556 		kfree(sl);
19557 		sl = sln;
19558 	}
19559 	env->free_list = NULL;
19560 
19561 	if (!env->explored_states)
19562 		return;
19563 
19564 	for (i = 0; i < state_htab_size(env); i++) {
19565 		sl = env->explored_states[i];
19566 
19567 		while (sl) {
19568 			sln = sl->next;
19569 			free_verifier_state(&sl->state, false);
19570 			kfree(sl);
19571 			sl = sln;
19572 		}
19573 		env->explored_states[i] = NULL;
19574 	}
19575 }
19576 
19577 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19578 {
19579 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19580 	struct bpf_verifier_state *state;
19581 	struct bpf_reg_state *regs;
19582 	int ret, i;
19583 
19584 	env->prev_linfo = NULL;
19585 	env->pass_cnt++;
19586 
19587 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19588 	if (!state)
19589 		return -ENOMEM;
19590 	state->curframe = 0;
19591 	state->speculative = false;
19592 	state->branches = 1;
19593 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19594 	if (!state->frame[0]) {
19595 		kfree(state);
19596 		return -ENOMEM;
19597 	}
19598 	env->cur_state = state;
19599 	init_func_state(env, state->frame[0],
19600 			BPF_MAIN_FUNC /* callsite */,
19601 			0 /* frameno */,
19602 			subprog);
19603 	state->first_insn_idx = env->subprog_info[subprog].start;
19604 	state->last_insn_idx = -1;
19605 
19606 	regs = state->frame[state->curframe]->regs;
19607 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19608 		ret = btf_prepare_func_args(env, subprog, regs);
19609 		if (ret)
19610 			goto out;
19611 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19612 			if (regs[i].type == PTR_TO_CTX)
19613 				mark_reg_known_zero(env, regs, i);
19614 			else if (regs[i].type == SCALAR_VALUE)
19615 				mark_reg_unknown(env, regs, i);
19616 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19617 				const u32 mem_size = regs[i].mem_size;
19618 
19619 				mark_reg_known_zero(env, regs, i);
19620 				regs[i].mem_size = mem_size;
19621 				regs[i].id = ++env->id_gen;
19622 			}
19623 		}
19624 	} else {
19625 		/* 1st arg to a function */
19626 		regs[BPF_REG_1].type = PTR_TO_CTX;
19627 		mark_reg_known_zero(env, regs, BPF_REG_1);
19628 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19629 		if (ret == -EFAULT)
19630 			/* unlikely verifier bug. abort.
19631 			 * ret == 0 and ret < 0 are sadly acceptable for
19632 			 * main() function due to backward compatibility.
19633 			 * Like socket filter program may be written as:
19634 			 * int bpf_prog(struct pt_regs *ctx)
19635 			 * and never dereference that ctx in the program.
19636 			 * 'struct pt_regs' is a type mismatch for socket
19637 			 * filter that should be using 'struct __sk_buff'.
19638 			 */
19639 			goto out;
19640 	}
19641 
19642 	ret = do_check(env);
19643 out:
19644 	/* check for NULL is necessary, since cur_state can be freed inside
19645 	 * do_check() under memory pressure.
19646 	 */
19647 	if (env->cur_state) {
19648 		free_verifier_state(env->cur_state, true);
19649 		env->cur_state = NULL;
19650 	}
19651 	while (!pop_stack(env, NULL, NULL, false));
19652 	if (!ret && pop_log)
19653 		bpf_vlog_reset(&env->log, 0);
19654 	free_states(env);
19655 	return ret;
19656 }
19657 
19658 /* Verify all global functions in a BPF program one by one based on their BTF.
19659  * All global functions must pass verification. Otherwise the whole program is rejected.
19660  * Consider:
19661  * int bar(int);
19662  * int foo(int f)
19663  * {
19664  *    return bar(f);
19665  * }
19666  * int bar(int b)
19667  * {
19668  *    ...
19669  * }
19670  * foo() will be verified first for R1=any_scalar_value. During verification it
19671  * will be assumed that bar() already verified successfully and call to bar()
19672  * from foo() will be checked for type match only. Later bar() will be verified
19673  * independently to check that it's safe for R1=any_scalar_value.
19674  */
19675 static int do_check_subprogs(struct bpf_verifier_env *env)
19676 {
19677 	struct bpf_prog_aux *aux = env->prog->aux;
19678 	int i, ret;
19679 
19680 	if (!aux->func_info)
19681 		return 0;
19682 
19683 	for (i = 1; i < env->subprog_cnt; i++) {
19684 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19685 			continue;
19686 		env->insn_idx = env->subprog_info[i].start;
19687 		WARN_ON_ONCE(env->insn_idx == 0);
19688 		ret = do_check_common(env, i);
19689 		if (ret) {
19690 			return ret;
19691 		} else if (env->log.level & BPF_LOG_LEVEL) {
19692 			verbose(env,
19693 				"Func#%d is safe for any args that match its prototype\n",
19694 				i);
19695 		}
19696 	}
19697 	return 0;
19698 }
19699 
19700 static int do_check_main(struct bpf_verifier_env *env)
19701 {
19702 	int ret;
19703 
19704 	env->insn_idx = 0;
19705 	ret = do_check_common(env, 0);
19706 	if (!ret)
19707 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19708 	return ret;
19709 }
19710 
19711 
19712 static void print_verification_stats(struct bpf_verifier_env *env)
19713 {
19714 	int i;
19715 
19716 	if (env->log.level & BPF_LOG_STATS) {
19717 		verbose(env, "verification time %lld usec\n",
19718 			div_u64(env->verification_time, 1000));
19719 		verbose(env, "stack depth ");
19720 		for (i = 0; i < env->subprog_cnt; i++) {
19721 			u32 depth = env->subprog_info[i].stack_depth;
19722 
19723 			verbose(env, "%d", depth);
19724 			if (i + 1 < env->subprog_cnt)
19725 				verbose(env, "+");
19726 		}
19727 		verbose(env, "\n");
19728 	}
19729 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19730 		"total_states %d peak_states %d mark_read %d\n",
19731 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19732 		env->max_states_per_insn, env->total_states,
19733 		env->peak_states, env->longest_mark_read_walk);
19734 }
19735 
19736 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19737 {
19738 	const struct btf_type *t, *func_proto;
19739 	const struct bpf_struct_ops *st_ops;
19740 	const struct btf_member *member;
19741 	struct bpf_prog *prog = env->prog;
19742 	u32 btf_id, member_idx;
19743 	const char *mname;
19744 
19745 	if (!prog->gpl_compatible) {
19746 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19747 		return -EINVAL;
19748 	}
19749 
19750 	btf_id = prog->aux->attach_btf_id;
19751 	st_ops = bpf_struct_ops_find(btf_id);
19752 	if (!st_ops) {
19753 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19754 			btf_id);
19755 		return -ENOTSUPP;
19756 	}
19757 
19758 	t = st_ops->type;
19759 	member_idx = prog->expected_attach_type;
19760 	if (member_idx >= btf_type_vlen(t)) {
19761 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19762 			member_idx, st_ops->name);
19763 		return -EINVAL;
19764 	}
19765 
19766 	member = &btf_type_member(t)[member_idx];
19767 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19768 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19769 					       NULL);
19770 	if (!func_proto) {
19771 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19772 			mname, member_idx, st_ops->name);
19773 		return -EINVAL;
19774 	}
19775 
19776 	if (st_ops->check_member) {
19777 		int err = st_ops->check_member(t, member, prog);
19778 
19779 		if (err) {
19780 			verbose(env, "attach to unsupported member %s of struct %s\n",
19781 				mname, st_ops->name);
19782 			return err;
19783 		}
19784 	}
19785 
19786 	prog->aux->attach_func_proto = func_proto;
19787 	prog->aux->attach_func_name = mname;
19788 	env->ops = st_ops->verifier_ops;
19789 
19790 	return 0;
19791 }
19792 #define SECURITY_PREFIX "security_"
19793 
19794 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19795 {
19796 	if (within_error_injection_list(addr) ||
19797 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19798 		return 0;
19799 
19800 	return -EINVAL;
19801 }
19802 
19803 /* list of non-sleepable functions that are otherwise on
19804  * ALLOW_ERROR_INJECTION list
19805  */
19806 BTF_SET_START(btf_non_sleepable_error_inject)
19807 /* Three functions below can be called from sleepable and non-sleepable context.
19808  * Assume non-sleepable from bpf safety point of view.
19809  */
19810 BTF_ID(func, __filemap_add_folio)
19811 BTF_ID(func, should_fail_alloc_page)
19812 BTF_ID(func, should_failslab)
19813 BTF_SET_END(btf_non_sleepable_error_inject)
19814 
19815 static int check_non_sleepable_error_inject(u32 btf_id)
19816 {
19817 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19818 }
19819 
19820 int bpf_check_attach_target(struct bpf_verifier_log *log,
19821 			    const struct bpf_prog *prog,
19822 			    const struct bpf_prog *tgt_prog,
19823 			    u32 btf_id,
19824 			    struct bpf_attach_target_info *tgt_info)
19825 {
19826 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19827 	const char prefix[] = "btf_trace_";
19828 	int ret = 0, subprog = -1, i;
19829 	const struct btf_type *t;
19830 	bool conservative = true;
19831 	const char *tname;
19832 	struct btf *btf;
19833 	long addr = 0;
19834 	struct module *mod = NULL;
19835 
19836 	if (!btf_id) {
19837 		bpf_log(log, "Tracing programs must provide btf_id\n");
19838 		return -EINVAL;
19839 	}
19840 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19841 	if (!btf) {
19842 		bpf_log(log,
19843 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19844 		return -EINVAL;
19845 	}
19846 	t = btf_type_by_id(btf, btf_id);
19847 	if (!t) {
19848 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19849 		return -EINVAL;
19850 	}
19851 	tname = btf_name_by_offset(btf, t->name_off);
19852 	if (!tname) {
19853 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19854 		return -EINVAL;
19855 	}
19856 	if (tgt_prog) {
19857 		struct bpf_prog_aux *aux = tgt_prog->aux;
19858 
19859 		if (bpf_prog_is_dev_bound(prog->aux) &&
19860 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19861 			bpf_log(log, "Target program bound device mismatch");
19862 			return -EINVAL;
19863 		}
19864 
19865 		for (i = 0; i < aux->func_info_cnt; i++)
19866 			if (aux->func_info[i].type_id == btf_id) {
19867 				subprog = i;
19868 				break;
19869 			}
19870 		if (subprog == -1) {
19871 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19872 			return -EINVAL;
19873 		}
19874 		conservative = aux->func_info_aux[subprog].unreliable;
19875 		if (prog_extension) {
19876 			if (conservative) {
19877 				bpf_log(log,
19878 					"Cannot replace static functions\n");
19879 				return -EINVAL;
19880 			}
19881 			if (!prog->jit_requested) {
19882 				bpf_log(log,
19883 					"Extension programs should be JITed\n");
19884 				return -EINVAL;
19885 			}
19886 		}
19887 		if (!tgt_prog->jited) {
19888 			bpf_log(log, "Can attach to only JITed progs\n");
19889 			return -EINVAL;
19890 		}
19891 		if (tgt_prog->type == prog->type) {
19892 			/* Cannot fentry/fexit another fentry/fexit program.
19893 			 * Cannot attach program extension to another extension.
19894 			 * It's ok to attach fentry/fexit to extension program.
19895 			 */
19896 			bpf_log(log, "Cannot recursively attach\n");
19897 			return -EINVAL;
19898 		}
19899 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19900 		    prog_extension &&
19901 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19902 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19903 			/* Program extensions can extend all program types
19904 			 * except fentry/fexit. The reason is the following.
19905 			 * The fentry/fexit programs are used for performance
19906 			 * analysis, stats and can be attached to any program
19907 			 * type except themselves. When extension program is
19908 			 * replacing XDP function it is necessary to allow
19909 			 * performance analysis of all functions. Both original
19910 			 * XDP program and its program extension. Hence
19911 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19912 			 * allowed. If extending of fentry/fexit was allowed it
19913 			 * would be possible to create long call chain
19914 			 * fentry->extension->fentry->extension beyond
19915 			 * reasonable stack size. Hence extending fentry is not
19916 			 * allowed.
19917 			 */
19918 			bpf_log(log, "Cannot extend fentry/fexit\n");
19919 			return -EINVAL;
19920 		}
19921 	} else {
19922 		if (prog_extension) {
19923 			bpf_log(log, "Cannot replace kernel functions\n");
19924 			return -EINVAL;
19925 		}
19926 	}
19927 
19928 	switch (prog->expected_attach_type) {
19929 	case BPF_TRACE_RAW_TP:
19930 		if (tgt_prog) {
19931 			bpf_log(log,
19932 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19933 			return -EINVAL;
19934 		}
19935 		if (!btf_type_is_typedef(t)) {
19936 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19937 				btf_id);
19938 			return -EINVAL;
19939 		}
19940 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19941 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19942 				btf_id, tname);
19943 			return -EINVAL;
19944 		}
19945 		tname += sizeof(prefix) - 1;
19946 		t = btf_type_by_id(btf, t->type);
19947 		if (!btf_type_is_ptr(t))
19948 			/* should never happen in valid vmlinux build */
19949 			return -EINVAL;
19950 		t = btf_type_by_id(btf, t->type);
19951 		if (!btf_type_is_func_proto(t))
19952 			/* should never happen in valid vmlinux build */
19953 			return -EINVAL;
19954 
19955 		break;
19956 	case BPF_TRACE_ITER:
19957 		if (!btf_type_is_func(t)) {
19958 			bpf_log(log, "attach_btf_id %u is not a function\n",
19959 				btf_id);
19960 			return -EINVAL;
19961 		}
19962 		t = btf_type_by_id(btf, t->type);
19963 		if (!btf_type_is_func_proto(t))
19964 			return -EINVAL;
19965 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19966 		if (ret)
19967 			return ret;
19968 		break;
19969 	default:
19970 		if (!prog_extension)
19971 			return -EINVAL;
19972 		fallthrough;
19973 	case BPF_MODIFY_RETURN:
19974 	case BPF_LSM_MAC:
19975 	case BPF_LSM_CGROUP:
19976 	case BPF_TRACE_FENTRY:
19977 	case BPF_TRACE_FEXIT:
19978 		if (!btf_type_is_func(t)) {
19979 			bpf_log(log, "attach_btf_id %u is not a function\n",
19980 				btf_id);
19981 			return -EINVAL;
19982 		}
19983 		if (prog_extension &&
19984 		    btf_check_type_match(log, prog, btf, t))
19985 			return -EINVAL;
19986 		t = btf_type_by_id(btf, t->type);
19987 		if (!btf_type_is_func_proto(t))
19988 			return -EINVAL;
19989 
19990 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19991 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19992 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19993 			return -EINVAL;
19994 
19995 		if (tgt_prog && conservative)
19996 			t = NULL;
19997 
19998 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19999 		if (ret < 0)
20000 			return ret;
20001 
20002 		if (tgt_prog) {
20003 			if (subprog == 0)
20004 				addr = (long) tgt_prog->bpf_func;
20005 			else
20006 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20007 		} else {
20008 			if (btf_is_module(btf)) {
20009 				mod = btf_try_get_module(btf);
20010 				if (mod)
20011 					addr = find_kallsyms_symbol_value(mod, tname);
20012 				else
20013 					addr = 0;
20014 			} else {
20015 				addr = kallsyms_lookup_name(tname);
20016 			}
20017 			if (!addr) {
20018 				module_put(mod);
20019 				bpf_log(log,
20020 					"The address of function %s cannot be found\n",
20021 					tname);
20022 				return -ENOENT;
20023 			}
20024 		}
20025 
20026 		if (prog->aux->sleepable) {
20027 			ret = -EINVAL;
20028 			switch (prog->type) {
20029 			case BPF_PROG_TYPE_TRACING:
20030 
20031 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20032 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20033 				 */
20034 				if (!check_non_sleepable_error_inject(btf_id) &&
20035 				    within_error_injection_list(addr))
20036 					ret = 0;
20037 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20038 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20039 				 */
20040 				else {
20041 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20042 										prog);
20043 
20044 					if (flags && (*flags & KF_SLEEPABLE))
20045 						ret = 0;
20046 				}
20047 				break;
20048 			case BPF_PROG_TYPE_LSM:
20049 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20050 				 * Only some of them are sleepable.
20051 				 */
20052 				if (bpf_lsm_is_sleepable_hook(btf_id))
20053 					ret = 0;
20054 				break;
20055 			default:
20056 				break;
20057 			}
20058 			if (ret) {
20059 				module_put(mod);
20060 				bpf_log(log, "%s is not sleepable\n", tname);
20061 				return ret;
20062 			}
20063 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20064 			if (tgt_prog) {
20065 				module_put(mod);
20066 				bpf_log(log, "can't modify return codes of BPF programs\n");
20067 				return -EINVAL;
20068 			}
20069 			ret = -EINVAL;
20070 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20071 			    !check_attach_modify_return(addr, tname))
20072 				ret = 0;
20073 			if (ret) {
20074 				module_put(mod);
20075 				bpf_log(log, "%s() is not modifiable\n", tname);
20076 				return ret;
20077 			}
20078 		}
20079 
20080 		break;
20081 	}
20082 	tgt_info->tgt_addr = addr;
20083 	tgt_info->tgt_name = tname;
20084 	tgt_info->tgt_type = t;
20085 	tgt_info->tgt_mod = mod;
20086 	return 0;
20087 }
20088 
20089 BTF_SET_START(btf_id_deny)
20090 BTF_ID_UNUSED
20091 #ifdef CONFIG_SMP
20092 BTF_ID(func, migrate_disable)
20093 BTF_ID(func, migrate_enable)
20094 #endif
20095 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20096 BTF_ID(func, rcu_read_unlock_strict)
20097 #endif
20098 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20099 BTF_ID(func, preempt_count_add)
20100 BTF_ID(func, preempt_count_sub)
20101 #endif
20102 #ifdef CONFIG_PREEMPT_RCU
20103 BTF_ID(func, __rcu_read_lock)
20104 BTF_ID(func, __rcu_read_unlock)
20105 #endif
20106 BTF_SET_END(btf_id_deny)
20107 
20108 static bool can_be_sleepable(struct bpf_prog *prog)
20109 {
20110 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20111 		switch (prog->expected_attach_type) {
20112 		case BPF_TRACE_FENTRY:
20113 		case BPF_TRACE_FEXIT:
20114 		case BPF_MODIFY_RETURN:
20115 		case BPF_TRACE_ITER:
20116 			return true;
20117 		default:
20118 			return false;
20119 		}
20120 	}
20121 	return prog->type == BPF_PROG_TYPE_LSM ||
20122 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20123 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20124 }
20125 
20126 static int check_attach_btf_id(struct bpf_verifier_env *env)
20127 {
20128 	struct bpf_prog *prog = env->prog;
20129 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20130 	struct bpf_attach_target_info tgt_info = {};
20131 	u32 btf_id = prog->aux->attach_btf_id;
20132 	struct bpf_trampoline *tr;
20133 	int ret;
20134 	u64 key;
20135 
20136 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20137 		if (prog->aux->sleepable)
20138 			/* attach_btf_id checked to be zero already */
20139 			return 0;
20140 		verbose(env, "Syscall programs can only be sleepable\n");
20141 		return -EINVAL;
20142 	}
20143 
20144 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20145 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20146 		return -EINVAL;
20147 	}
20148 
20149 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20150 		return check_struct_ops_btf_id(env);
20151 
20152 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20153 	    prog->type != BPF_PROG_TYPE_LSM &&
20154 	    prog->type != BPF_PROG_TYPE_EXT)
20155 		return 0;
20156 
20157 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20158 	if (ret)
20159 		return ret;
20160 
20161 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20162 		/* to make freplace equivalent to their targets, they need to
20163 		 * inherit env->ops and expected_attach_type for the rest of the
20164 		 * verification
20165 		 */
20166 		env->ops = bpf_verifier_ops[tgt_prog->type];
20167 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20168 	}
20169 
20170 	/* store info about the attachment target that will be used later */
20171 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20172 	prog->aux->attach_func_name = tgt_info.tgt_name;
20173 	prog->aux->mod = tgt_info.tgt_mod;
20174 
20175 	if (tgt_prog) {
20176 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20177 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20178 	}
20179 
20180 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20181 		prog->aux->attach_btf_trace = true;
20182 		return 0;
20183 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20184 		if (!bpf_iter_prog_supported(prog))
20185 			return -EINVAL;
20186 		return 0;
20187 	}
20188 
20189 	if (prog->type == BPF_PROG_TYPE_LSM) {
20190 		ret = bpf_lsm_verify_prog(&env->log, prog);
20191 		if (ret < 0)
20192 			return ret;
20193 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20194 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20195 		return -EINVAL;
20196 	}
20197 
20198 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20199 	tr = bpf_trampoline_get(key, &tgt_info);
20200 	if (!tr)
20201 		return -ENOMEM;
20202 
20203 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20204 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20205 
20206 	prog->aux->dst_trampoline = tr;
20207 	return 0;
20208 }
20209 
20210 struct btf *bpf_get_btf_vmlinux(void)
20211 {
20212 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20213 		mutex_lock(&bpf_verifier_lock);
20214 		if (!btf_vmlinux)
20215 			btf_vmlinux = btf_parse_vmlinux();
20216 		mutex_unlock(&bpf_verifier_lock);
20217 	}
20218 	return btf_vmlinux;
20219 }
20220 
20221 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20222 {
20223 	u64 start_time = ktime_get_ns();
20224 	struct bpf_verifier_env *env;
20225 	int i, len, ret = -EINVAL, err;
20226 	u32 log_true_size;
20227 	bool is_priv;
20228 
20229 	/* no program is valid */
20230 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20231 		return -EINVAL;
20232 
20233 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20234 	 * allocate/free it every time bpf_check() is called
20235 	 */
20236 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20237 	if (!env)
20238 		return -ENOMEM;
20239 
20240 	env->bt.env = env;
20241 
20242 	len = (*prog)->len;
20243 	env->insn_aux_data =
20244 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20245 	ret = -ENOMEM;
20246 	if (!env->insn_aux_data)
20247 		goto err_free_env;
20248 	for (i = 0; i < len; i++)
20249 		env->insn_aux_data[i].orig_idx = i;
20250 	env->prog = *prog;
20251 	env->ops = bpf_verifier_ops[env->prog->type];
20252 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20253 	is_priv = bpf_capable();
20254 
20255 	bpf_get_btf_vmlinux();
20256 
20257 	/* grab the mutex to protect few globals used by verifier */
20258 	if (!is_priv)
20259 		mutex_lock(&bpf_verifier_lock);
20260 
20261 	/* user could have requested verbose verifier output
20262 	 * and supplied buffer to store the verification trace
20263 	 */
20264 	ret = bpf_vlog_init(&env->log, attr->log_level,
20265 			    (char __user *) (unsigned long) attr->log_buf,
20266 			    attr->log_size);
20267 	if (ret)
20268 		goto err_unlock;
20269 
20270 	mark_verifier_state_clean(env);
20271 
20272 	if (IS_ERR(btf_vmlinux)) {
20273 		/* Either gcc or pahole or kernel are broken. */
20274 		verbose(env, "in-kernel BTF is malformed\n");
20275 		ret = PTR_ERR(btf_vmlinux);
20276 		goto skip_full_check;
20277 	}
20278 
20279 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20280 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20281 		env->strict_alignment = true;
20282 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20283 		env->strict_alignment = false;
20284 
20285 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20286 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20287 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20288 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20289 	env->bpf_capable = bpf_capable();
20290 
20291 	if (is_priv)
20292 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20293 
20294 	env->explored_states = kvcalloc(state_htab_size(env),
20295 				       sizeof(struct bpf_verifier_state_list *),
20296 				       GFP_USER);
20297 	ret = -ENOMEM;
20298 	if (!env->explored_states)
20299 		goto skip_full_check;
20300 
20301 	ret = add_subprog_and_kfunc(env);
20302 	if (ret < 0)
20303 		goto skip_full_check;
20304 
20305 	ret = check_subprogs(env);
20306 	if (ret < 0)
20307 		goto skip_full_check;
20308 
20309 	ret = check_btf_info(env, attr, uattr);
20310 	if (ret < 0)
20311 		goto skip_full_check;
20312 
20313 	ret = check_attach_btf_id(env);
20314 	if (ret)
20315 		goto skip_full_check;
20316 
20317 	ret = resolve_pseudo_ldimm64(env);
20318 	if (ret < 0)
20319 		goto skip_full_check;
20320 
20321 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20322 		ret = bpf_prog_offload_verifier_prep(env->prog);
20323 		if (ret)
20324 			goto skip_full_check;
20325 	}
20326 
20327 	ret = check_cfg(env);
20328 	if (ret < 0)
20329 		goto skip_full_check;
20330 
20331 	ret = do_check_subprogs(env);
20332 	ret = ret ?: do_check_main(env);
20333 
20334 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20335 		ret = bpf_prog_offload_finalize(env);
20336 
20337 skip_full_check:
20338 	kvfree(env->explored_states);
20339 
20340 	if (ret == 0)
20341 		ret = check_max_stack_depth(env);
20342 
20343 	/* instruction rewrites happen after this point */
20344 	if (ret == 0)
20345 		ret = optimize_bpf_loop(env);
20346 
20347 	if (is_priv) {
20348 		if (ret == 0)
20349 			opt_hard_wire_dead_code_branches(env);
20350 		if (ret == 0)
20351 			ret = opt_remove_dead_code(env);
20352 		if (ret == 0)
20353 			ret = opt_remove_nops(env);
20354 	} else {
20355 		if (ret == 0)
20356 			sanitize_dead_code(env);
20357 	}
20358 
20359 	if (ret == 0)
20360 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20361 		ret = convert_ctx_accesses(env);
20362 
20363 	if (ret == 0)
20364 		ret = do_misc_fixups(env);
20365 
20366 	/* do 32-bit optimization after insn patching has done so those patched
20367 	 * insns could be handled correctly.
20368 	 */
20369 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20370 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20371 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20372 								     : false;
20373 	}
20374 
20375 	if (ret == 0)
20376 		ret = fixup_call_args(env);
20377 
20378 	env->verification_time = ktime_get_ns() - start_time;
20379 	print_verification_stats(env);
20380 	env->prog->aux->verified_insns = env->insn_processed;
20381 
20382 	/* preserve original error even if log finalization is successful */
20383 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20384 	if (err)
20385 		ret = err;
20386 
20387 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20388 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20389 				  &log_true_size, sizeof(log_true_size))) {
20390 		ret = -EFAULT;
20391 		goto err_release_maps;
20392 	}
20393 
20394 	if (ret)
20395 		goto err_release_maps;
20396 
20397 	if (env->used_map_cnt) {
20398 		/* if program passed verifier, update used_maps in bpf_prog_info */
20399 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20400 							  sizeof(env->used_maps[0]),
20401 							  GFP_KERNEL);
20402 
20403 		if (!env->prog->aux->used_maps) {
20404 			ret = -ENOMEM;
20405 			goto err_release_maps;
20406 		}
20407 
20408 		memcpy(env->prog->aux->used_maps, env->used_maps,
20409 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20410 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20411 	}
20412 	if (env->used_btf_cnt) {
20413 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20414 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20415 							  sizeof(env->used_btfs[0]),
20416 							  GFP_KERNEL);
20417 		if (!env->prog->aux->used_btfs) {
20418 			ret = -ENOMEM;
20419 			goto err_release_maps;
20420 		}
20421 
20422 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20423 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20424 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20425 	}
20426 	if (env->used_map_cnt || env->used_btf_cnt) {
20427 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20428 		 * bpf_ld_imm64 instructions
20429 		 */
20430 		convert_pseudo_ld_imm64(env);
20431 	}
20432 
20433 	adjust_btf_func(env);
20434 
20435 err_release_maps:
20436 	if (!env->prog->aux->used_maps)
20437 		/* if we didn't copy map pointers into bpf_prog_info, release
20438 		 * them now. Otherwise free_used_maps() will release them.
20439 		 */
20440 		release_maps(env);
20441 	if (!env->prog->aux->used_btfs)
20442 		release_btfs(env);
20443 
20444 	/* extension progs temporarily inherit the attach_type of their targets
20445 	   for verification purposes, so set it back to zero before returning
20446 	 */
20447 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20448 		env->prog->expected_attach_type = 0;
20449 
20450 	*prog = env->prog;
20451 err_unlock:
20452 	if (!is_priv)
20453 		mutex_unlock(&bpf_verifier_lock);
20454 	vfree(env->insn_aux_data);
20455 err_free_env:
20456 	kfree(env);
20457 	return ret;
20458 }
20459