xref: /openbmc/linux/kernel/bpf/verifier.c (revision 3e212996d21f688f60bf8f6120a7816fcbf20104)
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() reorders entries by value, so b may no longer point
2803 		 * to the right entry after this
2804 		 */
2805 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2806 		     kfunc_btf_cmp_by_off, NULL);
2807 	} else {
2808 		btf = b->btf;
2809 	}
2810 
2811 	return btf;
2812 }
2813 
2814 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2815 {
2816 	if (!tab)
2817 		return;
2818 
2819 	while (tab->nr_descs--) {
2820 		module_put(tab->descs[tab->nr_descs].module);
2821 		btf_put(tab->descs[tab->nr_descs].btf);
2822 	}
2823 	kfree(tab);
2824 }
2825 
2826 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2827 {
2828 	if (offset) {
2829 		if (offset < 0) {
2830 			/* In the future, this can be allowed to increase limit
2831 			 * of fd index into fd_array, interpreted as u16.
2832 			 */
2833 			verbose(env, "negative offset disallowed for kernel module function call\n");
2834 			return ERR_PTR(-EINVAL);
2835 		}
2836 
2837 		return __find_kfunc_desc_btf(env, offset);
2838 	}
2839 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2840 }
2841 
2842 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2843 {
2844 	const struct btf_type *func, *func_proto;
2845 	struct bpf_kfunc_btf_tab *btf_tab;
2846 	struct bpf_kfunc_desc_tab *tab;
2847 	struct bpf_prog_aux *prog_aux;
2848 	struct bpf_kfunc_desc *desc;
2849 	const char *func_name;
2850 	struct btf *desc_btf;
2851 	unsigned long call_imm;
2852 	unsigned long addr;
2853 	int err;
2854 
2855 	prog_aux = env->prog->aux;
2856 	tab = prog_aux->kfunc_tab;
2857 	btf_tab = prog_aux->kfunc_btf_tab;
2858 	if (!tab) {
2859 		if (!btf_vmlinux) {
2860 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2861 			return -ENOTSUPP;
2862 		}
2863 
2864 		if (!env->prog->jit_requested) {
2865 			verbose(env, "JIT is required for calling kernel function\n");
2866 			return -ENOTSUPP;
2867 		}
2868 
2869 		if (!bpf_jit_supports_kfunc_call()) {
2870 			verbose(env, "JIT does not support calling kernel function\n");
2871 			return -ENOTSUPP;
2872 		}
2873 
2874 		if (!env->prog->gpl_compatible) {
2875 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2876 			return -EINVAL;
2877 		}
2878 
2879 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2880 		if (!tab)
2881 			return -ENOMEM;
2882 		prog_aux->kfunc_tab = tab;
2883 	}
2884 
2885 	/* func_id == 0 is always invalid, but instead of returning an error, be
2886 	 * conservative and wait until the code elimination pass before returning
2887 	 * error, so that invalid calls that get pruned out can be in BPF programs
2888 	 * loaded from userspace.  It is also required that offset be untouched
2889 	 * for such calls.
2890 	 */
2891 	if (!func_id && !offset)
2892 		return 0;
2893 
2894 	if (!btf_tab && offset) {
2895 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2896 		if (!btf_tab)
2897 			return -ENOMEM;
2898 		prog_aux->kfunc_btf_tab = btf_tab;
2899 	}
2900 
2901 	desc_btf = find_kfunc_desc_btf(env, offset);
2902 	if (IS_ERR(desc_btf)) {
2903 		verbose(env, "failed to find BTF for kernel function\n");
2904 		return PTR_ERR(desc_btf);
2905 	}
2906 
2907 	if (find_kfunc_desc(env->prog, func_id, offset))
2908 		return 0;
2909 
2910 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2911 		verbose(env, "too many different kernel function calls\n");
2912 		return -E2BIG;
2913 	}
2914 
2915 	func = btf_type_by_id(desc_btf, func_id);
2916 	if (!func || !btf_type_is_func(func)) {
2917 		verbose(env, "kernel btf_id %u is not a function\n",
2918 			func_id);
2919 		return -EINVAL;
2920 	}
2921 	func_proto = btf_type_by_id(desc_btf, func->type);
2922 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2923 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2924 			func_id);
2925 		return -EINVAL;
2926 	}
2927 
2928 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2929 	addr = kallsyms_lookup_name(func_name);
2930 	if (!addr) {
2931 		verbose(env, "cannot find address for kernel function %s\n",
2932 			func_name);
2933 		return -EINVAL;
2934 	}
2935 	specialize_kfunc(env, func_id, offset, &addr);
2936 
2937 	if (bpf_jit_supports_far_kfunc_call()) {
2938 		call_imm = func_id;
2939 	} else {
2940 		call_imm = BPF_CALL_IMM(addr);
2941 		/* Check whether the relative offset overflows desc->imm */
2942 		if ((unsigned long)(s32)call_imm != call_imm) {
2943 			verbose(env, "address of kernel function %s is out of range\n",
2944 				func_name);
2945 			return -EINVAL;
2946 		}
2947 	}
2948 
2949 	if (bpf_dev_bound_kfunc_id(func_id)) {
2950 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2951 		if (err)
2952 			return err;
2953 	}
2954 
2955 	desc = &tab->descs[tab->nr_descs++];
2956 	desc->func_id = func_id;
2957 	desc->imm = call_imm;
2958 	desc->offset = offset;
2959 	desc->addr = addr;
2960 	err = btf_distill_func_proto(&env->log, desc_btf,
2961 				     func_proto, func_name,
2962 				     &desc->func_model);
2963 	if (!err)
2964 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2965 		     kfunc_desc_cmp_by_id_off, NULL);
2966 	return err;
2967 }
2968 
2969 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2970 {
2971 	const struct bpf_kfunc_desc *d0 = a;
2972 	const struct bpf_kfunc_desc *d1 = b;
2973 
2974 	if (d0->imm != d1->imm)
2975 		return d0->imm < d1->imm ? -1 : 1;
2976 	if (d0->offset != d1->offset)
2977 		return d0->offset < d1->offset ? -1 : 1;
2978 	return 0;
2979 }
2980 
2981 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2982 {
2983 	struct bpf_kfunc_desc_tab *tab;
2984 
2985 	tab = prog->aux->kfunc_tab;
2986 	if (!tab)
2987 		return;
2988 
2989 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2990 	     kfunc_desc_cmp_by_imm_off, NULL);
2991 }
2992 
2993 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2994 {
2995 	return !!prog->aux->kfunc_tab;
2996 }
2997 
2998 const struct btf_func_model *
2999 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3000 			 const struct bpf_insn *insn)
3001 {
3002 	const struct bpf_kfunc_desc desc = {
3003 		.imm = insn->imm,
3004 		.offset = insn->off,
3005 	};
3006 	const struct bpf_kfunc_desc *res;
3007 	struct bpf_kfunc_desc_tab *tab;
3008 
3009 	tab = prog->aux->kfunc_tab;
3010 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3011 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3012 
3013 	return res ? &res->func_model : NULL;
3014 }
3015 
3016 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3017 {
3018 	struct bpf_subprog_info *subprog = env->subprog_info;
3019 	struct bpf_insn *insn = env->prog->insnsi;
3020 	int i, ret, insn_cnt = env->prog->len;
3021 
3022 	/* Add entry function. */
3023 	ret = add_subprog(env, 0);
3024 	if (ret)
3025 		return ret;
3026 
3027 	for (i = 0; i < insn_cnt; i++, insn++) {
3028 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3029 		    !bpf_pseudo_kfunc_call(insn))
3030 			continue;
3031 
3032 		if (!env->bpf_capable) {
3033 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3034 			return -EPERM;
3035 		}
3036 
3037 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3038 			ret = add_subprog(env, i + insn->imm + 1);
3039 		else
3040 			ret = add_kfunc_call(env, insn->imm, insn->off);
3041 
3042 		if (ret < 0)
3043 			return ret;
3044 	}
3045 
3046 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3047 	 * logic. 'subprog_cnt' should not be increased.
3048 	 */
3049 	subprog[env->subprog_cnt].start = insn_cnt;
3050 
3051 	if (env->log.level & BPF_LOG_LEVEL2)
3052 		for (i = 0; i < env->subprog_cnt; i++)
3053 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3054 
3055 	return 0;
3056 }
3057 
3058 static int check_subprogs(struct bpf_verifier_env *env)
3059 {
3060 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3061 	struct bpf_subprog_info *subprog = env->subprog_info;
3062 	struct bpf_insn *insn = env->prog->insnsi;
3063 	int insn_cnt = env->prog->len;
3064 
3065 	/* now check that all jumps are within the same subprog */
3066 	subprog_start = subprog[cur_subprog].start;
3067 	subprog_end = subprog[cur_subprog + 1].start;
3068 	for (i = 0; i < insn_cnt; i++) {
3069 		u8 code = insn[i].code;
3070 
3071 		if (code == (BPF_JMP | BPF_CALL) &&
3072 		    insn[i].src_reg == 0 &&
3073 		    insn[i].imm == BPF_FUNC_tail_call) {
3074 			subprog[cur_subprog].has_tail_call = true;
3075 			subprog[cur_subprog].tail_call_reachable = true;
3076 		}
3077 		if (BPF_CLASS(code) == BPF_LD &&
3078 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3079 			subprog[cur_subprog].has_ld_abs = true;
3080 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3081 			goto next;
3082 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3083 			goto next;
3084 		if (code == (BPF_JMP32 | BPF_JA))
3085 			off = i + insn[i].imm + 1;
3086 		else
3087 			off = i + insn[i].off + 1;
3088 		if (off < subprog_start || off >= subprog_end) {
3089 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3090 			return -EINVAL;
3091 		}
3092 next:
3093 		if (i == subprog_end - 1) {
3094 			/* to avoid fall-through from one subprog into another
3095 			 * the last insn of the subprog should be either exit
3096 			 * or unconditional jump back
3097 			 */
3098 			if (code != (BPF_JMP | BPF_EXIT) &&
3099 			    code != (BPF_JMP32 | BPF_JA) &&
3100 			    code != (BPF_JMP | BPF_JA)) {
3101 				verbose(env, "last insn is not an exit or jmp\n");
3102 				return -EINVAL;
3103 			}
3104 			subprog_start = subprog_end;
3105 			cur_subprog++;
3106 			if (cur_subprog < env->subprog_cnt)
3107 				subprog_end = subprog[cur_subprog + 1].start;
3108 		}
3109 	}
3110 	return 0;
3111 }
3112 
3113 /* Parentage chain of this register (or stack slot) should take care of all
3114  * issues like callee-saved registers, stack slot allocation time, etc.
3115  */
3116 static int mark_reg_read(struct bpf_verifier_env *env,
3117 			 const struct bpf_reg_state *state,
3118 			 struct bpf_reg_state *parent, u8 flag)
3119 {
3120 	bool writes = parent == state->parent; /* Observe write marks */
3121 	int cnt = 0;
3122 
3123 	while (parent) {
3124 		/* if read wasn't screened by an earlier write ... */
3125 		if (writes && state->live & REG_LIVE_WRITTEN)
3126 			break;
3127 		if (parent->live & REG_LIVE_DONE) {
3128 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3129 				reg_type_str(env, parent->type),
3130 				parent->var_off.value, parent->off);
3131 			return -EFAULT;
3132 		}
3133 		/* The first condition is more likely to be true than the
3134 		 * second, checked it first.
3135 		 */
3136 		if ((parent->live & REG_LIVE_READ) == flag ||
3137 		    parent->live & REG_LIVE_READ64)
3138 			/* The parentage chain never changes and
3139 			 * this parent was already marked as LIVE_READ.
3140 			 * There is no need to keep walking the chain again and
3141 			 * keep re-marking all parents as LIVE_READ.
3142 			 * This case happens when the same register is read
3143 			 * multiple times without writes into it in-between.
3144 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3145 			 * then no need to set the weak REG_LIVE_READ32.
3146 			 */
3147 			break;
3148 		/* ... then we depend on parent's value */
3149 		parent->live |= flag;
3150 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3151 		if (flag == REG_LIVE_READ64)
3152 			parent->live &= ~REG_LIVE_READ32;
3153 		state = parent;
3154 		parent = state->parent;
3155 		writes = true;
3156 		cnt++;
3157 	}
3158 
3159 	if (env->longest_mark_read_walk < cnt)
3160 		env->longest_mark_read_walk = cnt;
3161 	return 0;
3162 }
3163 
3164 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3165 {
3166 	struct bpf_func_state *state = func(env, reg);
3167 	int spi, ret;
3168 
3169 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3170 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3171 	 * check_kfunc_call.
3172 	 */
3173 	if (reg->type == CONST_PTR_TO_DYNPTR)
3174 		return 0;
3175 	spi = dynptr_get_spi(env, reg);
3176 	if (spi < 0)
3177 		return spi;
3178 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3179 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3180 	 * read.
3181 	 */
3182 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3183 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3184 	if (ret)
3185 		return ret;
3186 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3187 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3188 }
3189 
3190 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3191 			  int spi, int nr_slots)
3192 {
3193 	struct bpf_func_state *state = func(env, reg);
3194 	int err, i;
3195 
3196 	for (i = 0; i < nr_slots; i++) {
3197 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3198 
3199 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3200 		if (err)
3201 			return err;
3202 
3203 		mark_stack_slot_scratched(env, spi - i);
3204 	}
3205 
3206 	return 0;
3207 }
3208 
3209 /* This function is supposed to be used by the following 32-bit optimization
3210  * code only. It returns TRUE if the source or destination register operates
3211  * on 64-bit, otherwise return FALSE.
3212  */
3213 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3214 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3215 {
3216 	u8 code, class, op;
3217 
3218 	code = insn->code;
3219 	class = BPF_CLASS(code);
3220 	op = BPF_OP(code);
3221 	if (class == BPF_JMP) {
3222 		/* BPF_EXIT for "main" will reach here. Return TRUE
3223 		 * conservatively.
3224 		 */
3225 		if (op == BPF_EXIT)
3226 			return true;
3227 		if (op == BPF_CALL) {
3228 			/* BPF to BPF call will reach here because of marking
3229 			 * caller saved clobber with DST_OP_NO_MARK for which we
3230 			 * don't care the register def because they are anyway
3231 			 * marked as NOT_INIT already.
3232 			 */
3233 			if (insn->src_reg == BPF_PSEUDO_CALL)
3234 				return false;
3235 			/* Helper call will reach here because of arg type
3236 			 * check, conservatively return TRUE.
3237 			 */
3238 			if (t == SRC_OP)
3239 				return true;
3240 
3241 			return false;
3242 		}
3243 	}
3244 
3245 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3246 		return false;
3247 
3248 	if (class == BPF_ALU64 || class == BPF_JMP ||
3249 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3250 		return true;
3251 
3252 	if (class == BPF_ALU || class == BPF_JMP32)
3253 		return false;
3254 
3255 	if (class == BPF_LDX) {
3256 		if (t != SRC_OP)
3257 			return BPF_SIZE(code) == BPF_DW;
3258 		/* LDX source must be ptr. */
3259 		return true;
3260 	}
3261 
3262 	if (class == BPF_STX) {
3263 		/* BPF_STX (including atomic variants) has multiple source
3264 		 * operands, one of which is a ptr. Check whether the caller is
3265 		 * asking about it.
3266 		 */
3267 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3268 			return true;
3269 		return BPF_SIZE(code) == BPF_DW;
3270 	}
3271 
3272 	if (class == BPF_LD) {
3273 		u8 mode = BPF_MODE(code);
3274 
3275 		/* LD_IMM64 */
3276 		if (mode == BPF_IMM)
3277 			return true;
3278 
3279 		/* Both LD_IND and LD_ABS return 32-bit data. */
3280 		if (t != SRC_OP)
3281 			return  false;
3282 
3283 		/* Implicit ctx ptr. */
3284 		if (regno == BPF_REG_6)
3285 			return true;
3286 
3287 		/* Explicit source could be any width. */
3288 		return true;
3289 	}
3290 
3291 	if (class == BPF_ST)
3292 		/* The only source register for BPF_ST is a ptr. */
3293 		return true;
3294 
3295 	/* Conservatively return true at default. */
3296 	return true;
3297 }
3298 
3299 /* Return the regno defined by the insn, or -1. */
3300 static int insn_def_regno(const struct bpf_insn *insn)
3301 {
3302 	switch (BPF_CLASS(insn->code)) {
3303 	case BPF_JMP:
3304 	case BPF_JMP32:
3305 	case BPF_ST:
3306 		return -1;
3307 	case BPF_STX:
3308 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3309 		    (insn->imm & BPF_FETCH)) {
3310 			if (insn->imm == BPF_CMPXCHG)
3311 				return BPF_REG_0;
3312 			else
3313 				return insn->src_reg;
3314 		} else {
3315 			return -1;
3316 		}
3317 	default:
3318 		return insn->dst_reg;
3319 	}
3320 }
3321 
3322 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3323 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3324 {
3325 	int dst_reg = insn_def_regno(insn);
3326 
3327 	if (dst_reg == -1)
3328 		return false;
3329 
3330 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3331 }
3332 
3333 static void mark_insn_zext(struct bpf_verifier_env *env,
3334 			   struct bpf_reg_state *reg)
3335 {
3336 	s32 def_idx = reg->subreg_def;
3337 
3338 	if (def_idx == DEF_NOT_SUBREG)
3339 		return;
3340 
3341 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3342 	/* The dst will be zero extended, so won't be sub-register anymore. */
3343 	reg->subreg_def = DEF_NOT_SUBREG;
3344 }
3345 
3346 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3347 			   enum reg_arg_type t)
3348 {
3349 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3350 	struct bpf_reg_state *reg;
3351 	bool rw64;
3352 
3353 	if (regno >= MAX_BPF_REG) {
3354 		verbose(env, "R%d is invalid\n", regno);
3355 		return -EINVAL;
3356 	}
3357 
3358 	mark_reg_scratched(env, regno);
3359 
3360 	reg = &regs[regno];
3361 	rw64 = is_reg64(env, insn, regno, reg, t);
3362 	if (t == SRC_OP) {
3363 		/* check whether register used as source operand can be read */
3364 		if (reg->type == NOT_INIT) {
3365 			verbose(env, "R%d !read_ok\n", regno);
3366 			return -EACCES;
3367 		}
3368 		/* We don't need to worry about FP liveness because it's read-only */
3369 		if (regno == BPF_REG_FP)
3370 			return 0;
3371 
3372 		if (rw64)
3373 			mark_insn_zext(env, reg);
3374 
3375 		return mark_reg_read(env, reg, reg->parent,
3376 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3377 	} else {
3378 		/* check whether register used as dest operand can be written to */
3379 		if (regno == BPF_REG_FP) {
3380 			verbose(env, "frame pointer is read only\n");
3381 			return -EACCES;
3382 		}
3383 		reg->live |= REG_LIVE_WRITTEN;
3384 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3385 		if (t == DST_OP)
3386 			mark_reg_unknown(env, regs, regno);
3387 	}
3388 	return 0;
3389 }
3390 
3391 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3392 			 enum reg_arg_type t)
3393 {
3394 	struct bpf_verifier_state *vstate = env->cur_state;
3395 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3396 
3397 	return __check_reg_arg(env, state->regs, regno, t);
3398 }
3399 
3400 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3401 {
3402 	env->insn_aux_data[idx].jmp_point = true;
3403 }
3404 
3405 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3406 {
3407 	return env->insn_aux_data[insn_idx].jmp_point;
3408 }
3409 
3410 /* for any branch, call, exit record the history of jmps in the given state */
3411 static int push_jmp_history(struct bpf_verifier_env *env,
3412 			    struct bpf_verifier_state *cur)
3413 {
3414 	u32 cnt = cur->jmp_history_cnt;
3415 	struct bpf_idx_pair *p;
3416 	size_t alloc_size;
3417 
3418 	if (!is_jmp_point(env, env->insn_idx))
3419 		return 0;
3420 
3421 	cnt++;
3422 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3423 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3424 	if (!p)
3425 		return -ENOMEM;
3426 	p[cnt - 1].idx = env->insn_idx;
3427 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3428 	cur->jmp_history = p;
3429 	cur->jmp_history_cnt = cnt;
3430 	return 0;
3431 }
3432 
3433 /* Backtrack one insn at a time. If idx is not at the top of recorded
3434  * history then previous instruction came from straight line execution.
3435  * Return -ENOENT if we exhausted all instructions within given state.
3436  *
3437  * It's legal to have a bit of a looping with the same starting and ending
3438  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3439  * instruction index is the same as state's first_idx doesn't mean we are
3440  * done. If there is still some jump history left, we should keep going. We
3441  * need to take into account that we might have a jump history between given
3442  * state's parent and itself, due to checkpointing. In this case, we'll have
3443  * history entry recording a jump from last instruction of parent state and
3444  * first instruction of given state.
3445  */
3446 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3447 			     u32 *history)
3448 {
3449 	u32 cnt = *history;
3450 
3451 	if (i == st->first_insn_idx) {
3452 		if (cnt == 0)
3453 			return -ENOENT;
3454 		if (cnt == 1 && st->jmp_history[0].idx == i)
3455 			return -ENOENT;
3456 	}
3457 
3458 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3459 		i = st->jmp_history[cnt - 1].prev_idx;
3460 		(*history)--;
3461 	} else {
3462 		i--;
3463 	}
3464 	return i;
3465 }
3466 
3467 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3468 {
3469 	const struct btf_type *func;
3470 	struct btf *desc_btf;
3471 
3472 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3473 		return NULL;
3474 
3475 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3476 	if (IS_ERR(desc_btf))
3477 		return "<error>";
3478 
3479 	func = btf_type_by_id(desc_btf, insn->imm);
3480 	return btf_name_by_offset(desc_btf, func->name_off);
3481 }
3482 
3483 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3484 {
3485 	bt->frame = frame;
3486 }
3487 
3488 static inline void bt_reset(struct backtrack_state *bt)
3489 {
3490 	struct bpf_verifier_env *env = bt->env;
3491 
3492 	memset(bt, 0, sizeof(*bt));
3493 	bt->env = env;
3494 }
3495 
3496 static inline u32 bt_empty(struct backtrack_state *bt)
3497 {
3498 	u64 mask = 0;
3499 	int i;
3500 
3501 	for (i = 0; i <= bt->frame; i++)
3502 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3503 
3504 	return mask == 0;
3505 }
3506 
3507 static inline int bt_subprog_enter(struct backtrack_state *bt)
3508 {
3509 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3510 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3511 		WARN_ONCE(1, "verifier backtracking bug");
3512 		return -EFAULT;
3513 	}
3514 	bt->frame++;
3515 	return 0;
3516 }
3517 
3518 static inline int bt_subprog_exit(struct backtrack_state *bt)
3519 {
3520 	if (bt->frame == 0) {
3521 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3522 		WARN_ONCE(1, "verifier backtracking bug");
3523 		return -EFAULT;
3524 	}
3525 	bt->frame--;
3526 	return 0;
3527 }
3528 
3529 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3530 {
3531 	bt->reg_masks[frame] |= 1 << reg;
3532 }
3533 
3534 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3535 {
3536 	bt->reg_masks[frame] &= ~(1 << reg);
3537 }
3538 
3539 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3540 {
3541 	bt_set_frame_reg(bt, bt->frame, reg);
3542 }
3543 
3544 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3545 {
3546 	bt_clear_frame_reg(bt, bt->frame, reg);
3547 }
3548 
3549 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3550 {
3551 	bt->stack_masks[frame] |= 1ull << slot;
3552 }
3553 
3554 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3555 {
3556 	bt->stack_masks[frame] &= ~(1ull << slot);
3557 }
3558 
3559 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3560 {
3561 	bt_set_frame_slot(bt, bt->frame, slot);
3562 }
3563 
3564 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3565 {
3566 	bt_clear_frame_slot(bt, bt->frame, slot);
3567 }
3568 
3569 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3570 {
3571 	return bt->reg_masks[frame];
3572 }
3573 
3574 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3575 {
3576 	return bt->reg_masks[bt->frame];
3577 }
3578 
3579 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3580 {
3581 	return bt->stack_masks[frame];
3582 }
3583 
3584 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3585 {
3586 	return bt->stack_masks[bt->frame];
3587 }
3588 
3589 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3590 {
3591 	return bt->reg_masks[bt->frame] & (1 << reg);
3592 }
3593 
3594 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3595 {
3596 	return bt->stack_masks[bt->frame] & (1ull << slot);
3597 }
3598 
3599 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3600 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3601 {
3602 	DECLARE_BITMAP(mask, 64);
3603 	bool first = true;
3604 	int i, n;
3605 
3606 	buf[0] = '\0';
3607 
3608 	bitmap_from_u64(mask, reg_mask);
3609 	for_each_set_bit(i, mask, 32) {
3610 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3611 		first = false;
3612 		buf += n;
3613 		buf_sz -= n;
3614 		if (buf_sz < 0)
3615 			break;
3616 	}
3617 }
3618 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3619 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3620 {
3621 	DECLARE_BITMAP(mask, 64);
3622 	bool first = true;
3623 	int i, n;
3624 
3625 	buf[0] = '\0';
3626 
3627 	bitmap_from_u64(mask, stack_mask);
3628 	for_each_set_bit(i, mask, 64) {
3629 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3630 		first = false;
3631 		buf += n;
3632 		buf_sz -= n;
3633 		if (buf_sz < 0)
3634 			break;
3635 	}
3636 }
3637 
3638 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3639 
3640 /* For given verifier state backtrack_insn() is called from the last insn to
3641  * the first insn. Its purpose is to compute a bitmask of registers and
3642  * stack slots that needs precision in the parent verifier state.
3643  *
3644  * @idx is an index of the instruction we are currently processing;
3645  * @subseq_idx is an index of the subsequent instruction that:
3646  *   - *would be* executed next, if jump history is viewed in forward order;
3647  *   - *was* processed previously during backtracking.
3648  */
3649 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3650 			  struct backtrack_state *bt)
3651 {
3652 	const struct bpf_insn_cbs cbs = {
3653 		.cb_call	= disasm_kfunc_name,
3654 		.cb_print	= verbose,
3655 		.private_data	= env,
3656 	};
3657 	struct bpf_insn *insn = env->prog->insnsi + idx;
3658 	u8 class = BPF_CLASS(insn->code);
3659 	u8 opcode = BPF_OP(insn->code);
3660 	u8 mode = BPF_MODE(insn->code);
3661 	u32 dreg = insn->dst_reg;
3662 	u32 sreg = insn->src_reg;
3663 	u32 spi, i;
3664 
3665 	if (insn->code == 0)
3666 		return 0;
3667 	if (env->log.level & BPF_LOG_LEVEL2) {
3668 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3669 		verbose(env, "mark_precise: frame%d: regs=%s ",
3670 			bt->frame, env->tmp_str_buf);
3671 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3672 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3673 		verbose(env, "%d: ", idx);
3674 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3675 	}
3676 
3677 	if (class == BPF_ALU || class == BPF_ALU64) {
3678 		if (!bt_is_reg_set(bt, dreg))
3679 			return 0;
3680 		if (opcode == BPF_END || opcode == BPF_NEG) {
3681 			/* sreg is reserved and unused
3682 			 * dreg still need precision before this insn
3683 			 */
3684 			return 0;
3685 		} else if (opcode == BPF_MOV) {
3686 			if (BPF_SRC(insn->code) == BPF_X) {
3687 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3688 				 * dreg needs precision after this insn
3689 				 * sreg needs precision before this insn
3690 				 */
3691 				bt_clear_reg(bt, dreg);
3692 				if (sreg != BPF_REG_FP)
3693 					bt_set_reg(bt, sreg);
3694 			} else {
3695 				/* dreg = K
3696 				 * dreg needs precision after this insn.
3697 				 * Corresponding register is already marked
3698 				 * as precise=true in this verifier state.
3699 				 * No further markings in parent are necessary
3700 				 */
3701 				bt_clear_reg(bt, dreg);
3702 			}
3703 		} else {
3704 			if (BPF_SRC(insn->code) == BPF_X) {
3705 				/* dreg += sreg
3706 				 * both dreg and sreg need precision
3707 				 * before this insn
3708 				 */
3709 				if (sreg != BPF_REG_FP)
3710 					bt_set_reg(bt, sreg);
3711 			} /* else dreg += K
3712 			   * dreg still needs precision before this insn
3713 			   */
3714 		}
3715 	} else if (class == BPF_LDX) {
3716 		if (!bt_is_reg_set(bt, dreg))
3717 			return 0;
3718 		bt_clear_reg(bt, dreg);
3719 
3720 		/* scalars can only be spilled into stack w/o losing precision.
3721 		 * Load from any other memory can be zero extended.
3722 		 * The desire to keep that precision is already indicated
3723 		 * by 'precise' mark in corresponding register of this state.
3724 		 * No further tracking necessary.
3725 		 */
3726 		if (insn->src_reg != BPF_REG_FP)
3727 			return 0;
3728 
3729 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3730 		 * that [fp - off] slot contains scalar that needs to be
3731 		 * tracked with precision
3732 		 */
3733 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3734 		if (spi >= 64) {
3735 			verbose(env, "BUG spi %d\n", spi);
3736 			WARN_ONCE(1, "verifier backtracking bug");
3737 			return -EFAULT;
3738 		}
3739 		bt_set_slot(bt, spi);
3740 	} else if (class == BPF_STX || class == BPF_ST) {
3741 		if (bt_is_reg_set(bt, dreg))
3742 			/* stx & st shouldn't be using _scalar_ dst_reg
3743 			 * to access memory. It means backtracking
3744 			 * encountered a case of pointer subtraction.
3745 			 */
3746 			return -ENOTSUPP;
3747 		/* scalars can only be spilled into stack */
3748 		if (insn->dst_reg != BPF_REG_FP)
3749 			return 0;
3750 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3751 		if (spi >= 64) {
3752 			verbose(env, "BUG spi %d\n", spi);
3753 			WARN_ONCE(1, "verifier backtracking bug");
3754 			return -EFAULT;
3755 		}
3756 		if (!bt_is_slot_set(bt, spi))
3757 			return 0;
3758 		bt_clear_slot(bt, spi);
3759 		if (class == BPF_STX)
3760 			bt_set_reg(bt, sreg);
3761 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3762 		if (bpf_pseudo_call(insn)) {
3763 			int subprog_insn_idx, subprog;
3764 
3765 			subprog_insn_idx = idx + insn->imm + 1;
3766 			subprog = find_subprog(env, subprog_insn_idx);
3767 			if (subprog < 0)
3768 				return -EFAULT;
3769 
3770 			if (subprog_is_global(env, subprog)) {
3771 				/* check that jump history doesn't have any
3772 				 * extra instructions from subprog; the next
3773 				 * instruction after call to global subprog
3774 				 * should be literally next instruction in
3775 				 * caller program
3776 				 */
3777 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3778 				/* r1-r5 are invalidated after subprog call,
3779 				 * so for global func call it shouldn't be set
3780 				 * anymore
3781 				 */
3782 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3783 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3784 					WARN_ONCE(1, "verifier backtracking bug");
3785 					return -EFAULT;
3786 				}
3787 				/* global subprog always sets R0 */
3788 				bt_clear_reg(bt, BPF_REG_0);
3789 				return 0;
3790 			} else {
3791 				/* static subprog call instruction, which
3792 				 * means that we are exiting current subprog,
3793 				 * so only r1-r5 could be still requested as
3794 				 * precise, r0 and r6-r10 or any stack slot in
3795 				 * the current frame should be zero by now
3796 				 */
3797 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3798 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3799 					WARN_ONCE(1, "verifier backtracking bug");
3800 					return -EFAULT;
3801 				}
3802 				/* we don't track register spills perfectly,
3803 				 * so fallback to force-precise instead of failing */
3804 				if (bt_stack_mask(bt) != 0)
3805 					return -ENOTSUPP;
3806 				/* propagate r1-r5 to the caller */
3807 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3808 					if (bt_is_reg_set(bt, i)) {
3809 						bt_clear_reg(bt, i);
3810 						bt_set_frame_reg(bt, bt->frame - 1, i);
3811 					}
3812 				}
3813 				if (bt_subprog_exit(bt))
3814 					return -EFAULT;
3815 				return 0;
3816 			}
3817 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3818 			/* exit from callback subprog to callback-calling helper or
3819 			 * kfunc call. Use idx/subseq_idx check to discern it from
3820 			 * straight line code backtracking.
3821 			 * Unlike the subprog call handling above, we shouldn't
3822 			 * propagate precision of r1-r5 (if any requested), as they are
3823 			 * not actually arguments passed directly to callback subprogs
3824 			 */
3825 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3826 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3827 				WARN_ONCE(1, "verifier backtracking bug");
3828 				return -EFAULT;
3829 			}
3830 			if (bt_stack_mask(bt) != 0)
3831 				return -ENOTSUPP;
3832 			/* clear r1-r5 in callback subprog's mask */
3833 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3834 				bt_clear_reg(bt, i);
3835 			if (bt_subprog_exit(bt))
3836 				return -EFAULT;
3837 			return 0;
3838 		} else if (opcode == BPF_CALL) {
3839 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3840 			 * catch this error later. Make backtracking conservative
3841 			 * with ENOTSUPP.
3842 			 */
3843 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3844 				return -ENOTSUPP;
3845 			/* regular helper call sets R0 */
3846 			bt_clear_reg(bt, BPF_REG_0);
3847 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3848 				/* if backtracing was looking for registers R1-R5
3849 				 * they should have been found already.
3850 				 */
3851 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3852 				WARN_ONCE(1, "verifier backtracking bug");
3853 				return -EFAULT;
3854 			}
3855 		} else if (opcode == BPF_EXIT) {
3856 			bool r0_precise;
3857 
3858 			/* Backtracking to a nested function call, 'idx' is a part of
3859 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3860 			 * In case of a regular function call, instructions giving
3861 			 * precision to registers R1-R5 should have been found already.
3862 			 * In case of a callback, it is ok to have R1-R5 marked for
3863 			 * backtracking, as these registers are set by the function
3864 			 * invoking callback.
3865 			 */
3866 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3867 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3868 					bt_clear_reg(bt, i);
3869 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3870 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3871 				WARN_ONCE(1, "verifier backtracking bug");
3872 				return -EFAULT;
3873 			}
3874 
3875 			/* BPF_EXIT in subprog or callback always returns
3876 			 * right after the call instruction, so by checking
3877 			 * whether the instruction at subseq_idx-1 is subprog
3878 			 * call or not we can distinguish actual exit from
3879 			 * *subprog* from exit from *callback*. In the former
3880 			 * case, we need to propagate r0 precision, if
3881 			 * necessary. In the former we never do that.
3882 			 */
3883 			r0_precise = subseq_idx - 1 >= 0 &&
3884 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3885 				     bt_is_reg_set(bt, BPF_REG_0);
3886 
3887 			bt_clear_reg(bt, BPF_REG_0);
3888 			if (bt_subprog_enter(bt))
3889 				return -EFAULT;
3890 
3891 			if (r0_precise)
3892 				bt_set_reg(bt, BPF_REG_0);
3893 			/* r6-r9 and stack slots will stay set in caller frame
3894 			 * bitmasks until we return back from callee(s)
3895 			 */
3896 			return 0;
3897 		} else if (BPF_SRC(insn->code) == BPF_X) {
3898 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3899 				return 0;
3900 			/* dreg <cond> sreg
3901 			 * Both dreg and sreg need precision before
3902 			 * this insn. If only sreg was marked precise
3903 			 * before it would be equally necessary to
3904 			 * propagate it to dreg.
3905 			 */
3906 			bt_set_reg(bt, dreg);
3907 			bt_set_reg(bt, sreg);
3908 			 /* else dreg <cond> K
3909 			  * Only dreg still needs precision before
3910 			  * this insn, so for the K-based conditional
3911 			  * there is nothing new to be marked.
3912 			  */
3913 		}
3914 	} else if (class == BPF_LD) {
3915 		if (!bt_is_reg_set(bt, dreg))
3916 			return 0;
3917 		bt_clear_reg(bt, dreg);
3918 		/* It's ld_imm64 or ld_abs or ld_ind.
3919 		 * For ld_imm64 no further tracking of precision
3920 		 * into parent is necessary
3921 		 */
3922 		if (mode == BPF_IND || mode == BPF_ABS)
3923 			/* to be analyzed */
3924 			return -ENOTSUPP;
3925 	}
3926 	return 0;
3927 }
3928 
3929 /* the scalar precision tracking algorithm:
3930  * . at the start all registers have precise=false.
3931  * . scalar ranges are tracked as normal through alu and jmp insns.
3932  * . once precise value of the scalar register is used in:
3933  *   .  ptr + scalar alu
3934  *   . if (scalar cond K|scalar)
3935  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3936  *   backtrack through the verifier states and mark all registers and
3937  *   stack slots with spilled constants that these scalar regisers
3938  *   should be precise.
3939  * . during state pruning two registers (or spilled stack slots)
3940  *   are equivalent if both are not precise.
3941  *
3942  * Note the verifier cannot simply walk register parentage chain,
3943  * since many different registers and stack slots could have been
3944  * used to compute single precise scalar.
3945  *
3946  * The approach of starting with precise=true for all registers and then
3947  * backtrack to mark a register as not precise when the verifier detects
3948  * that program doesn't care about specific value (e.g., when helper
3949  * takes register as ARG_ANYTHING parameter) is not safe.
3950  *
3951  * It's ok to walk single parentage chain of the verifier states.
3952  * It's possible that this backtracking will go all the way till 1st insn.
3953  * All other branches will be explored for needing precision later.
3954  *
3955  * The backtracking needs to deal with cases like:
3956  *   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)
3957  * r9 -= r8
3958  * r5 = r9
3959  * if r5 > 0x79f goto pc+7
3960  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3961  * r5 += 1
3962  * ...
3963  * call bpf_perf_event_output#25
3964  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3965  *
3966  * and this case:
3967  * r6 = 1
3968  * call foo // uses callee's r6 inside to compute r0
3969  * r0 += r6
3970  * if r0 == 0 goto
3971  *
3972  * to track above reg_mask/stack_mask needs to be independent for each frame.
3973  *
3974  * Also if parent's curframe > frame where backtracking started,
3975  * the verifier need to mark registers in both frames, otherwise callees
3976  * may incorrectly prune callers. This is similar to
3977  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3978  *
3979  * For now backtracking falls back into conservative marking.
3980  */
3981 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3982 				     struct bpf_verifier_state *st)
3983 {
3984 	struct bpf_func_state *func;
3985 	struct bpf_reg_state *reg;
3986 	int i, j;
3987 
3988 	if (env->log.level & BPF_LOG_LEVEL2) {
3989 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3990 			st->curframe);
3991 	}
3992 
3993 	/* big hammer: mark all scalars precise in this path.
3994 	 * pop_stack may still get !precise scalars.
3995 	 * We also skip current state and go straight to first parent state,
3996 	 * because precision markings in current non-checkpointed state are
3997 	 * not needed. See why in the comment in __mark_chain_precision below.
3998 	 */
3999 	for (st = st->parent; st; st = st->parent) {
4000 		for (i = 0; i <= st->curframe; i++) {
4001 			func = st->frame[i];
4002 			for (j = 0; j < BPF_REG_FP; j++) {
4003 				reg = &func->regs[j];
4004 				if (reg->type != SCALAR_VALUE || reg->precise)
4005 					continue;
4006 				reg->precise = true;
4007 				if (env->log.level & BPF_LOG_LEVEL2) {
4008 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4009 						i, j);
4010 				}
4011 			}
4012 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4013 				if (!is_spilled_reg(&func->stack[j]))
4014 					continue;
4015 				reg = &func->stack[j].spilled_ptr;
4016 				if (reg->type != SCALAR_VALUE || reg->precise)
4017 					continue;
4018 				reg->precise = true;
4019 				if (env->log.level & BPF_LOG_LEVEL2) {
4020 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4021 						i, -(j + 1) * 8);
4022 				}
4023 			}
4024 		}
4025 	}
4026 }
4027 
4028 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4029 {
4030 	struct bpf_func_state *func;
4031 	struct bpf_reg_state *reg;
4032 	int i, j;
4033 
4034 	for (i = 0; i <= st->curframe; i++) {
4035 		func = st->frame[i];
4036 		for (j = 0; j < BPF_REG_FP; j++) {
4037 			reg = &func->regs[j];
4038 			if (reg->type != SCALAR_VALUE)
4039 				continue;
4040 			reg->precise = false;
4041 		}
4042 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4043 			if (!is_spilled_reg(&func->stack[j]))
4044 				continue;
4045 			reg = &func->stack[j].spilled_ptr;
4046 			if (reg->type != SCALAR_VALUE)
4047 				continue;
4048 			reg->precise = false;
4049 		}
4050 	}
4051 }
4052 
4053 static bool idset_contains(struct bpf_idset *s, u32 id)
4054 {
4055 	u32 i;
4056 
4057 	for (i = 0; i < s->count; ++i)
4058 		if (s->ids[i] == id)
4059 			return true;
4060 
4061 	return false;
4062 }
4063 
4064 static int idset_push(struct bpf_idset *s, u32 id)
4065 {
4066 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4067 		return -EFAULT;
4068 	s->ids[s->count++] = id;
4069 	return 0;
4070 }
4071 
4072 static void idset_reset(struct bpf_idset *s)
4073 {
4074 	s->count = 0;
4075 }
4076 
4077 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4078  * Mark all registers with these IDs as precise.
4079  */
4080 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4081 {
4082 	struct bpf_idset *precise_ids = &env->idset_scratch;
4083 	struct backtrack_state *bt = &env->bt;
4084 	struct bpf_func_state *func;
4085 	struct bpf_reg_state *reg;
4086 	DECLARE_BITMAP(mask, 64);
4087 	int i, fr;
4088 
4089 	idset_reset(precise_ids);
4090 
4091 	for (fr = bt->frame; fr >= 0; fr--) {
4092 		func = st->frame[fr];
4093 
4094 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4095 		for_each_set_bit(i, mask, 32) {
4096 			reg = &func->regs[i];
4097 			if (!reg->id || reg->type != SCALAR_VALUE)
4098 				continue;
4099 			if (idset_push(precise_ids, reg->id))
4100 				return -EFAULT;
4101 		}
4102 
4103 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4104 		for_each_set_bit(i, mask, 64) {
4105 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4106 				break;
4107 			if (!is_spilled_scalar_reg(&func->stack[i]))
4108 				continue;
4109 			reg = &func->stack[i].spilled_ptr;
4110 			if (!reg->id)
4111 				continue;
4112 			if (idset_push(precise_ids, reg->id))
4113 				return -EFAULT;
4114 		}
4115 	}
4116 
4117 	for (fr = 0; fr <= st->curframe; ++fr) {
4118 		func = st->frame[fr];
4119 
4120 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4121 			reg = &func->regs[i];
4122 			if (!reg->id)
4123 				continue;
4124 			if (!idset_contains(precise_ids, reg->id))
4125 				continue;
4126 			bt_set_frame_reg(bt, fr, i);
4127 		}
4128 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4129 			if (!is_spilled_scalar_reg(&func->stack[i]))
4130 				continue;
4131 			reg = &func->stack[i].spilled_ptr;
4132 			if (!reg->id)
4133 				continue;
4134 			if (!idset_contains(precise_ids, reg->id))
4135 				continue;
4136 			bt_set_frame_slot(bt, fr, i);
4137 		}
4138 	}
4139 
4140 	return 0;
4141 }
4142 
4143 /*
4144  * __mark_chain_precision() backtracks BPF program instruction sequence and
4145  * chain of verifier states making sure that register *regno* (if regno >= 0)
4146  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4147  * SCALARS, as well as any other registers and slots that contribute to
4148  * a tracked state of given registers/stack slots, depending on specific BPF
4149  * assembly instructions (see backtrack_insns() for exact instruction handling
4150  * logic). This backtracking relies on recorded jmp_history and is able to
4151  * traverse entire chain of parent states. This process ends only when all the
4152  * necessary registers/slots and their transitive dependencies are marked as
4153  * precise.
4154  *
4155  * One important and subtle aspect is that precise marks *do not matter* in
4156  * the currently verified state (current state). It is important to understand
4157  * why this is the case.
4158  *
4159  * First, note that current state is the state that is not yet "checkpointed",
4160  * i.e., it is not yet put into env->explored_states, and it has no children
4161  * states as well. It's ephemeral, and can end up either a) being discarded if
4162  * compatible explored state is found at some point or BPF_EXIT instruction is
4163  * reached or b) checkpointed and put into env->explored_states, branching out
4164  * into one or more children states.
4165  *
4166  * In the former case, precise markings in current state are completely
4167  * ignored by state comparison code (see regsafe() for details). Only
4168  * checkpointed ("old") state precise markings are important, and if old
4169  * state's register/slot is precise, regsafe() assumes current state's
4170  * register/slot as precise and checks value ranges exactly and precisely. If
4171  * states turn out to be compatible, current state's necessary precise
4172  * markings and any required parent states' precise markings are enforced
4173  * after the fact with propagate_precision() logic, after the fact. But it's
4174  * important to realize that in this case, even after marking current state
4175  * registers/slots as precise, we immediately discard current state. So what
4176  * actually matters is any of the precise markings propagated into current
4177  * state's parent states, which are always checkpointed (due to b) case above).
4178  * As such, for scenario a) it doesn't matter if current state has precise
4179  * markings set or not.
4180  *
4181  * Now, for the scenario b), checkpointing and forking into child(ren)
4182  * state(s). Note that before current state gets to checkpointing step, any
4183  * processed instruction always assumes precise SCALAR register/slot
4184  * knowledge: if precise value or range is useful to prune jump branch, BPF
4185  * verifier takes this opportunity enthusiastically. Similarly, when
4186  * register's value is used to calculate offset or memory address, exact
4187  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4188  * what we mentioned above about state comparison ignoring precise markings
4189  * during state comparison, BPF verifier ignores and also assumes precise
4190  * markings *at will* during instruction verification process. But as verifier
4191  * assumes precision, it also propagates any precision dependencies across
4192  * parent states, which are not yet finalized, so can be further restricted
4193  * based on new knowledge gained from restrictions enforced by their children
4194  * states. This is so that once those parent states are finalized, i.e., when
4195  * they have no more active children state, state comparison logic in
4196  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4197  * required for correctness.
4198  *
4199  * To build a bit more intuition, note also that once a state is checkpointed,
4200  * the path we took to get to that state is not important. This is crucial
4201  * property for state pruning. When state is checkpointed and finalized at
4202  * some instruction index, it can be correctly and safely used to "short
4203  * circuit" any *compatible* state that reaches exactly the same instruction
4204  * index. I.e., if we jumped to that instruction from a completely different
4205  * code path than original finalized state was derived from, it doesn't
4206  * matter, current state can be discarded because from that instruction
4207  * forward having a compatible state will ensure we will safely reach the
4208  * exit. States describe preconditions for further exploration, but completely
4209  * forget the history of how we got here.
4210  *
4211  * This also means that even if we needed precise SCALAR range to get to
4212  * finalized state, but from that point forward *that same* SCALAR register is
4213  * never used in a precise context (i.e., it's precise value is not needed for
4214  * correctness), it's correct and safe to mark such register as "imprecise"
4215  * (i.e., precise marking set to false). This is what we rely on when we do
4216  * not set precise marking in current state. If no child state requires
4217  * precision for any given SCALAR register, it's safe to dictate that it can
4218  * be imprecise. If any child state does require this register to be precise,
4219  * we'll mark it precise later retroactively during precise markings
4220  * propagation from child state to parent states.
4221  *
4222  * Skipping precise marking setting in current state is a mild version of
4223  * relying on the above observation. But we can utilize this property even
4224  * more aggressively by proactively forgetting any precise marking in the
4225  * current state (which we inherited from the parent state), right before we
4226  * checkpoint it and branch off into new child state. This is done by
4227  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4228  * finalized states which help in short circuiting more future states.
4229  */
4230 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4231 {
4232 	struct backtrack_state *bt = &env->bt;
4233 	struct bpf_verifier_state *st = env->cur_state;
4234 	int first_idx = st->first_insn_idx;
4235 	int last_idx = env->insn_idx;
4236 	int subseq_idx = -1;
4237 	struct bpf_func_state *func;
4238 	struct bpf_reg_state *reg;
4239 	bool skip_first = true;
4240 	int i, fr, err;
4241 
4242 	if (!env->bpf_capable)
4243 		return 0;
4244 
4245 	/* set frame number from which we are starting to backtrack */
4246 	bt_init(bt, env->cur_state->curframe);
4247 
4248 	/* Do sanity checks against current state of register and/or stack
4249 	 * slot, but don't set precise flag in current state, as precision
4250 	 * tracking in the current state is unnecessary.
4251 	 */
4252 	func = st->frame[bt->frame];
4253 	if (regno >= 0) {
4254 		reg = &func->regs[regno];
4255 		if (reg->type != SCALAR_VALUE) {
4256 			WARN_ONCE(1, "backtracing misuse");
4257 			return -EFAULT;
4258 		}
4259 		bt_set_reg(bt, regno);
4260 	}
4261 
4262 	if (bt_empty(bt))
4263 		return 0;
4264 
4265 	for (;;) {
4266 		DECLARE_BITMAP(mask, 64);
4267 		u32 history = st->jmp_history_cnt;
4268 
4269 		if (env->log.level & BPF_LOG_LEVEL2) {
4270 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4271 				bt->frame, last_idx, first_idx, subseq_idx);
4272 		}
4273 
4274 		/* If some register with scalar ID is marked as precise,
4275 		 * make sure that all registers sharing this ID are also precise.
4276 		 * This is needed to estimate effect of find_equal_scalars().
4277 		 * Do this at the last instruction of each state,
4278 		 * bpf_reg_state::id fields are valid for these instructions.
4279 		 *
4280 		 * Allows to track precision in situation like below:
4281 		 *
4282 		 *     r2 = unknown value
4283 		 *     ...
4284 		 *   --- state #0 ---
4285 		 *     ...
4286 		 *     r1 = r2                 // r1 and r2 now share the same ID
4287 		 *     ...
4288 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4289 		 *     ...
4290 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4291 		 *     ...
4292 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4293 		 *     r3 = r10
4294 		 *     r3 += r1                // need to mark both r1 and r2
4295 		 */
4296 		if (mark_precise_scalar_ids(env, st))
4297 			return -EFAULT;
4298 
4299 		if (last_idx < 0) {
4300 			/* we are at the entry into subprog, which
4301 			 * is expected for global funcs, but only if
4302 			 * requested precise registers are R1-R5
4303 			 * (which are global func's input arguments)
4304 			 */
4305 			if (st->curframe == 0 &&
4306 			    st->frame[0]->subprogno > 0 &&
4307 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4308 			    bt_stack_mask(bt) == 0 &&
4309 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4310 				bitmap_from_u64(mask, bt_reg_mask(bt));
4311 				for_each_set_bit(i, mask, 32) {
4312 					reg = &st->frame[0]->regs[i];
4313 					bt_clear_reg(bt, i);
4314 					if (reg->type == SCALAR_VALUE)
4315 						reg->precise = true;
4316 				}
4317 				return 0;
4318 			}
4319 
4320 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4321 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4322 			WARN_ONCE(1, "verifier backtracking bug");
4323 			return -EFAULT;
4324 		}
4325 
4326 		for (i = last_idx;;) {
4327 			if (skip_first) {
4328 				err = 0;
4329 				skip_first = false;
4330 			} else {
4331 				err = backtrack_insn(env, i, subseq_idx, bt);
4332 			}
4333 			if (err == -ENOTSUPP) {
4334 				mark_all_scalars_precise(env, env->cur_state);
4335 				bt_reset(bt);
4336 				return 0;
4337 			} else if (err) {
4338 				return err;
4339 			}
4340 			if (bt_empty(bt))
4341 				/* Found assignment(s) into tracked register in this state.
4342 				 * Since this state is already marked, just return.
4343 				 * Nothing to be tracked further in the parent state.
4344 				 */
4345 				return 0;
4346 			subseq_idx = i;
4347 			i = get_prev_insn_idx(st, i, &history);
4348 			if (i == -ENOENT)
4349 				break;
4350 			if (i >= env->prog->len) {
4351 				/* This can happen if backtracking reached insn 0
4352 				 * and there are still reg_mask or stack_mask
4353 				 * to backtrack.
4354 				 * It means the backtracking missed the spot where
4355 				 * particular register was initialized with a constant.
4356 				 */
4357 				verbose(env, "BUG backtracking idx %d\n", i);
4358 				WARN_ONCE(1, "verifier backtracking bug");
4359 				return -EFAULT;
4360 			}
4361 		}
4362 		st = st->parent;
4363 		if (!st)
4364 			break;
4365 
4366 		for (fr = bt->frame; fr >= 0; fr--) {
4367 			func = st->frame[fr];
4368 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4369 			for_each_set_bit(i, mask, 32) {
4370 				reg = &func->regs[i];
4371 				if (reg->type != SCALAR_VALUE) {
4372 					bt_clear_frame_reg(bt, fr, i);
4373 					continue;
4374 				}
4375 				if (reg->precise)
4376 					bt_clear_frame_reg(bt, fr, i);
4377 				else
4378 					reg->precise = true;
4379 			}
4380 
4381 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4382 			for_each_set_bit(i, mask, 64) {
4383 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4384 					/* the sequence of instructions:
4385 					 * 2: (bf) r3 = r10
4386 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4387 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4388 					 * doesn't contain jmps. It's backtracked
4389 					 * as a single block.
4390 					 * During backtracking insn 3 is not recognized as
4391 					 * stack access, so at the end of backtracking
4392 					 * stack slot fp-8 is still marked in stack_mask.
4393 					 * However the parent state may not have accessed
4394 					 * fp-8 and it's "unallocated" stack space.
4395 					 * In such case fallback to conservative.
4396 					 */
4397 					mark_all_scalars_precise(env, env->cur_state);
4398 					bt_reset(bt);
4399 					return 0;
4400 				}
4401 
4402 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4403 					bt_clear_frame_slot(bt, fr, i);
4404 					continue;
4405 				}
4406 				reg = &func->stack[i].spilled_ptr;
4407 				if (reg->precise)
4408 					bt_clear_frame_slot(bt, fr, i);
4409 				else
4410 					reg->precise = true;
4411 			}
4412 			if (env->log.level & BPF_LOG_LEVEL2) {
4413 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4414 					     bt_frame_reg_mask(bt, fr));
4415 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4416 					fr, env->tmp_str_buf);
4417 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4418 					       bt_frame_stack_mask(bt, fr));
4419 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4420 				print_verifier_state(env, func, true);
4421 			}
4422 		}
4423 
4424 		if (bt_empty(bt))
4425 			return 0;
4426 
4427 		subseq_idx = first_idx;
4428 		last_idx = st->last_insn_idx;
4429 		first_idx = st->first_insn_idx;
4430 	}
4431 
4432 	/* if we still have requested precise regs or slots, we missed
4433 	 * something (e.g., stack access through non-r10 register), so
4434 	 * fallback to marking all precise
4435 	 */
4436 	if (!bt_empty(bt)) {
4437 		mark_all_scalars_precise(env, env->cur_state);
4438 		bt_reset(bt);
4439 	}
4440 
4441 	return 0;
4442 }
4443 
4444 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4445 {
4446 	return __mark_chain_precision(env, regno);
4447 }
4448 
4449 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4450  * desired reg and stack masks across all relevant frames
4451  */
4452 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4453 {
4454 	return __mark_chain_precision(env, -1);
4455 }
4456 
4457 static bool is_spillable_regtype(enum bpf_reg_type type)
4458 {
4459 	switch (base_type(type)) {
4460 	case PTR_TO_MAP_VALUE:
4461 	case PTR_TO_STACK:
4462 	case PTR_TO_CTX:
4463 	case PTR_TO_PACKET:
4464 	case PTR_TO_PACKET_META:
4465 	case PTR_TO_PACKET_END:
4466 	case PTR_TO_FLOW_KEYS:
4467 	case CONST_PTR_TO_MAP:
4468 	case PTR_TO_SOCKET:
4469 	case PTR_TO_SOCK_COMMON:
4470 	case PTR_TO_TCP_SOCK:
4471 	case PTR_TO_XDP_SOCK:
4472 	case PTR_TO_BTF_ID:
4473 	case PTR_TO_BUF:
4474 	case PTR_TO_MEM:
4475 	case PTR_TO_FUNC:
4476 	case PTR_TO_MAP_KEY:
4477 		return true;
4478 	default:
4479 		return false;
4480 	}
4481 }
4482 
4483 /* Does this register contain a constant zero? */
4484 static bool register_is_null(struct bpf_reg_state *reg)
4485 {
4486 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4487 }
4488 
4489 static bool register_is_const(struct bpf_reg_state *reg)
4490 {
4491 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4492 }
4493 
4494 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4495 {
4496 	return tnum_is_unknown(reg->var_off) &&
4497 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4498 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4499 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4500 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4501 }
4502 
4503 static bool register_is_bounded(struct bpf_reg_state *reg)
4504 {
4505 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4506 }
4507 
4508 static bool __is_pointer_value(bool allow_ptr_leaks,
4509 			       const struct bpf_reg_state *reg)
4510 {
4511 	if (allow_ptr_leaks)
4512 		return false;
4513 
4514 	return reg->type != SCALAR_VALUE;
4515 }
4516 
4517 /* Copy src state preserving dst->parent and dst->live fields */
4518 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4519 {
4520 	struct bpf_reg_state *parent = dst->parent;
4521 	enum bpf_reg_liveness live = dst->live;
4522 
4523 	*dst = *src;
4524 	dst->parent = parent;
4525 	dst->live = live;
4526 }
4527 
4528 static void save_register_state(struct bpf_func_state *state,
4529 				int spi, struct bpf_reg_state *reg,
4530 				int size)
4531 {
4532 	int i;
4533 
4534 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4535 	if (size == BPF_REG_SIZE)
4536 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4537 
4538 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4539 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4540 
4541 	/* size < 8 bytes spill */
4542 	for (; i; i--)
4543 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4544 }
4545 
4546 static bool is_bpf_st_mem(struct bpf_insn *insn)
4547 {
4548 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4549 }
4550 
4551 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4552  * stack boundary and alignment are checked in check_mem_access()
4553  */
4554 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4555 				       /* stack frame we're writing to */
4556 				       struct bpf_func_state *state,
4557 				       int off, int size, int value_regno,
4558 				       int insn_idx)
4559 {
4560 	struct bpf_func_state *cur; /* state of the current function */
4561 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4562 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4563 	struct bpf_reg_state *reg = NULL;
4564 	u32 dst_reg = insn->dst_reg;
4565 
4566 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4567 	 * so it's aligned access and [off, off + size) are within stack limits
4568 	 */
4569 	if (!env->allow_ptr_leaks &&
4570 	    is_spilled_reg(&state->stack[spi]) &&
4571 	    size != BPF_REG_SIZE) {
4572 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4573 		return -EACCES;
4574 	}
4575 
4576 	cur = env->cur_state->frame[env->cur_state->curframe];
4577 	if (value_regno >= 0)
4578 		reg = &cur->regs[value_regno];
4579 	if (!env->bypass_spec_v4) {
4580 		bool sanitize = reg && is_spillable_regtype(reg->type);
4581 
4582 		for (i = 0; i < size; i++) {
4583 			u8 type = state->stack[spi].slot_type[i];
4584 
4585 			if (type != STACK_MISC && type != STACK_ZERO) {
4586 				sanitize = true;
4587 				break;
4588 			}
4589 		}
4590 
4591 		if (sanitize)
4592 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4593 	}
4594 
4595 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4596 	if (err)
4597 		return err;
4598 
4599 	mark_stack_slot_scratched(env, spi);
4600 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4601 	    !register_is_null(reg) && env->bpf_capable) {
4602 		if (dst_reg != BPF_REG_FP) {
4603 			/* The backtracking logic can only recognize explicit
4604 			 * stack slot address like [fp - 8]. Other spill of
4605 			 * scalar via different register has to be conservative.
4606 			 * Backtrack from here and mark all registers as precise
4607 			 * that contributed into 'reg' being a constant.
4608 			 */
4609 			err = mark_chain_precision(env, value_regno);
4610 			if (err)
4611 				return err;
4612 		}
4613 		save_register_state(state, spi, reg, size);
4614 		/* Break the relation on a narrowing spill. */
4615 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4616 			state->stack[spi].spilled_ptr.id = 0;
4617 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4618 		   insn->imm != 0 && env->bpf_capable) {
4619 		struct bpf_reg_state fake_reg = {};
4620 
4621 		__mark_reg_known(&fake_reg, insn->imm);
4622 		fake_reg.type = SCALAR_VALUE;
4623 		save_register_state(state, spi, &fake_reg, size);
4624 	} else if (reg && is_spillable_regtype(reg->type)) {
4625 		/* register containing pointer is being spilled into stack */
4626 		if (size != BPF_REG_SIZE) {
4627 			verbose_linfo(env, insn_idx, "; ");
4628 			verbose(env, "invalid size of register spill\n");
4629 			return -EACCES;
4630 		}
4631 		if (state != cur && reg->type == PTR_TO_STACK) {
4632 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4633 			return -EINVAL;
4634 		}
4635 		save_register_state(state, spi, reg, size);
4636 	} else {
4637 		u8 type = STACK_MISC;
4638 
4639 		/* regular write of data into stack destroys any spilled ptr */
4640 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4641 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4642 		if (is_stack_slot_special(&state->stack[spi]))
4643 			for (i = 0; i < BPF_REG_SIZE; i++)
4644 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4645 
4646 		/* only mark the slot as written if all 8 bytes were written
4647 		 * otherwise read propagation may incorrectly stop too soon
4648 		 * when stack slots are partially written.
4649 		 * This heuristic means that read propagation will be
4650 		 * conservative, since it will add reg_live_read marks
4651 		 * to stack slots all the way to first state when programs
4652 		 * writes+reads less than 8 bytes
4653 		 */
4654 		if (size == BPF_REG_SIZE)
4655 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4656 
4657 		/* when we zero initialize stack slots mark them as such */
4658 		if ((reg && register_is_null(reg)) ||
4659 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4660 			/* backtracking doesn't work for STACK_ZERO yet. */
4661 			err = mark_chain_precision(env, value_regno);
4662 			if (err)
4663 				return err;
4664 			type = STACK_ZERO;
4665 		}
4666 
4667 		/* Mark slots affected by this stack write. */
4668 		for (i = 0; i < size; i++)
4669 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4670 				type;
4671 	}
4672 	return 0;
4673 }
4674 
4675 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4676  * known to contain a variable offset.
4677  * This function checks whether the write is permitted and conservatively
4678  * tracks the effects of the write, considering that each stack slot in the
4679  * dynamic range is potentially written to.
4680  *
4681  * 'off' includes 'regno->off'.
4682  * 'value_regno' can be -1, meaning that an unknown value is being written to
4683  * the stack.
4684  *
4685  * Spilled pointers in range are not marked as written because we don't know
4686  * what's going to be actually written. This means that read propagation for
4687  * future reads cannot be terminated by this write.
4688  *
4689  * For privileged programs, uninitialized stack slots are considered
4690  * initialized by this write (even though we don't know exactly what offsets
4691  * are going to be written to). The idea is that we don't want the verifier to
4692  * reject future reads that access slots written to through variable offsets.
4693  */
4694 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4695 				     /* func where register points to */
4696 				     struct bpf_func_state *state,
4697 				     int ptr_regno, int off, int size,
4698 				     int value_regno, int insn_idx)
4699 {
4700 	struct bpf_func_state *cur; /* state of the current function */
4701 	int min_off, max_off;
4702 	int i, err;
4703 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4704 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4705 	bool writing_zero = false;
4706 	/* set if the fact that we're writing a zero is used to let any
4707 	 * stack slots remain STACK_ZERO
4708 	 */
4709 	bool zero_used = false;
4710 
4711 	cur = env->cur_state->frame[env->cur_state->curframe];
4712 	ptr_reg = &cur->regs[ptr_regno];
4713 	min_off = ptr_reg->smin_value + off;
4714 	max_off = ptr_reg->smax_value + off + size;
4715 	if (value_regno >= 0)
4716 		value_reg = &cur->regs[value_regno];
4717 	if ((value_reg && register_is_null(value_reg)) ||
4718 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4719 		writing_zero = true;
4720 
4721 	for (i = min_off; i < max_off; i++) {
4722 		int spi;
4723 
4724 		spi = __get_spi(i);
4725 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4726 		if (err)
4727 			return err;
4728 	}
4729 
4730 	/* Variable offset writes destroy any spilled pointers in range. */
4731 	for (i = min_off; i < max_off; i++) {
4732 		u8 new_type, *stype;
4733 		int slot, spi;
4734 
4735 		slot = -i - 1;
4736 		spi = slot / BPF_REG_SIZE;
4737 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4738 		mark_stack_slot_scratched(env, spi);
4739 
4740 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4741 			/* Reject the write if range we may write to has not
4742 			 * been initialized beforehand. If we didn't reject
4743 			 * here, the ptr status would be erased below (even
4744 			 * though not all slots are actually overwritten),
4745 			 * possibly opening the door to leaks.
4746 			 *
4747 			 * We do however catch STACK_INVALID case below, and
4748 			 * only allow reading possibly uninitialized memory
4749 			 * later for CAP_PERFMON, as the write may not happen to
4750 			 * that slot.
4751 			 */
4752 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4753 				insn_idx, i);
4754 			return -EINVAL;
4755 		}
4756 
4757 		/* Erase all spilled pointers. */
4758 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4759 
4760 		/* Update the slot type. */
4761 		new_type = STACK_MISC;
4762 		if (writing_zero && *stype == STACK_ZERO) {
4763 			new_type = STACK_ZERO;
4764 			zero_used = true;
4765 		}
4766 		/* If the slot is STACK_INVALID, we check whether it's OK to
4767 		 * pretend that it will be initialized by this write. The slot
4768 		 * might not actually be written to, and so if we mark it as
4769 		 * initialized future reads might leak uninitialized memory.
4770 		 * For privileged programs, we will accept such reads to slots
4771 		 * that may or may not be written because, if we're reject
4772 		 * them, the error would be too confusing.
4773 		 */
4774 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4775 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4776 					insn_idx, i);
4777 			return -EINVAL;
4778 		}
4779 		*stype = new_type;
4780 	}
4781 	if (zero_used) {
4782 		/* backtracking doesn't work for STACK_ZERO yet. */
4783 		err = mark_chain_precision(env, value_regno);
4784 		if (err)
4785 			return err;
4786 	}
4787 	return 0;
4788 }
4789 
4790 /* When register 'dst_regno' is assigned some values from stack[min_off,
4791  * max_off), we set the register's type according to the types of the
4792  * respective stack slots. If all the stack values are known to be zeros, then
4793  * so is the destination reg. Otherwise, the register is considered to be
4794  * SCALAR. This function does not deal with register filling; the caller must
4795  * ensure that all spilled registers in the stack range have been marked as
4796  * read.
4797  */
4798 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4799 				/* func where src register points to */
4800 				struct bpf_func_state *ptr_state,
4801 				int min_off, int max_off, int dst_regno)
4802 {
4803 	struct bpf_verifier_state *vstate = env->cur_state;
4804 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4805 	int i, slot, spi;
4806 	u8 *stype;
4807 	int zeros = 0;
4808 
4809 	for (i = min_off; i < max_off; i++) {
4810 		slot = -i - 1;
4811 		spi = slot / BPF_REG_SIZE;
4812 		mark_stack_slot_scratched(env, spi);
4813 		stype = ptr_state->stack[spi].slot_type;
4814 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4815 			break;
4816 		zeros++;
4817 	}
4818 	if (zeros == max_off - min_off) {
4819 		/* any access_size read into register is zero extended,
4820 		 * so the whole register == const_zero
4821 		 */
4822 		__mark_reg_const_zero(&state->regs[dst_regno]);
4823 		/* backtracking doesn't support STACK_ZERO yet,
4824 		 * so mark it precise here, so that later
4825 		 * backtracking can stop here.
4826 		 * Backtracking may not need this if this register
4827 		 * doesn't participate in pointer adjustment.
4828 		 * Forward propagation of precise flag is not
4829 		 * necessary either. This mark is only to stop
4830 		 * backtracking. Any register that contributed
4831 		 * to const 0 was marked precise before spill.
4832 		 */
4833 		state->regs[dst_regno].precise = true;
4834 	} else {
4835 		/* have read misc data from the stack */
4836 		mark_reg_unknown(env, state->regs, dst_regno);
4837 	}
4838 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4839 }
4840 
4841 /* Read the stack at 'off' and put the results into the register indicated by
4842  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4843  * spilled reg.
4844  *
4845  * 'dst_regno' can be -1, meaning that the read value is not going to a
4846  * register.
4847  *
4848  * The access is assumed to be within the current stack bounds.
4849  */
4850 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4851 				      /* func where src register points to */
4852 				      struct bpf_func_state *reg_state,
4853 				      int off, int size, int dst_regno)
4854 {
4855 	struct bpf_verifier_state *vstate = env->cur_state;
4856 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4857 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4858 	struct bpf_reg_state *reg;
4859 	u8 *stype, type;
4860 
4861 	stype = reg_state->stack[spi].slot_type;
4862 	reg = &reg_state->stack[spi].spilled_ptr;
4863 
4864 	mark_stack_slot_scratched(env, spi);
4865 
4866 	if (is_spilled_reg(&reg_state->stack[spi])) {
4867 		u8 spill_size = 1;
4868 
4869 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4870 			spill_size++;
4871 
4872 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4873 			if (reg->type != SCALAR_VALUE) {
4874 				verbose_linfo(env, env->insn_idx, "; ");
4875 				verbose(env, "invalid size of register fill\n");
4876 				return -EACCES;
4877 			}
4878 
4879 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4880 			if (dst_regno < 0)
4881 				return 0;
4882 
4883 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4884 				/* The earlier check_reg_arg() has decided the
4885 				 * subreg_def for this insn.  Save it first.
4886 				 */
4887 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4888 
4889 				copy_register_state(&state->regs[dst_regno], reg);
4890 				state->regs[dst_regno].subreg_def = subreg_def;
4891 			} else {
4892 				for (i = 0; i < size; i++) {
4893 					type = stype[(slot - i) % BPF_REG_SIZE];
4894 					if (type == STACK_SPILL)
4895 						continue;
4896 					if (type == STACK_MISC)
4897 						continue;
4898 					if (type == STACK_INVALID && env->allow_uninit_stack)
4899 						continue;
4900 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4901 						off, i, size);
4902 					return -EACCES;
4903 				}
4904 				mark_reg_unknown(env, state->regs, dst_regno);
4905 			}
4906 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4907 			return 0;
4908 		}
4909 
4910 		if (dst_regno >= 0) {
4911 			/* restore register state from stack */
4912 			copy_register_state(&state->regs[dst_regno], reg);
4913 			/* mark reg as written since spilled pointer state likely
4914 			 * has its liveness marks cleared by is_state_visited()
4915 			 * which resets stack/reg liveness for state transitions
4916 			 */
4917 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4918 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4919 			/* If dst_regno==-1, the caller is asking us whether
4920 			 * it is acceptable to use this value as a SCALAR_VALUE
4921 			 * (e.g. for XADD).
4922 			 * We must not allow unprivileged callers to do that
4923 			 * with spilled pointers.
4924 			 */
4925 			verbose(env, "leaking pointer from stack off %d\n",
4926 				off);
4927 			return -EACCES;
4928 		}
4929 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4930 	} else {
4931 		for (i = 0; i < size; i++) {
4932 			type = stype[(slot - i) % BPF_REG_SIZE];
4933 			if (type == STACK_MISC)
4934 				continue;
4935 			if (type == STACK_ZERO)
4936 				continue;
4937 			if (type == STACK_INVALID && env->allow_uninit_stack)
4938 				continue;
4939 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4940 				off, i, size);
4941 			return -EACCES;
4942 		}
4943 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4944 		if (dst_regno >= 0)
4945 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4946 	}
4947 	return 0;
4948 }
4949 
4950 enum bpf_access_src {
4951 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4952 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4953 };
4954 
4955 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4956 					 int regno, int off, int access_size,
4957 					 bool zero_size_allowed,
4958 					 enum bpf_access_src type,
4959 					 struct bpf_call_arg_meta *meta);
4960 
4961 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4962 {
4963 	return cur_regs(env) + regno;
4964 }
4965 
4966 /* Read the stack at 'ptr_regno + off' and put the result into the register
4967  * 'dst_regno'.
4968  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4969  * but not its variable offset.
4970  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4971  *
4972  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4973  * filling registers (i.e. reads of spilled register cannot be detected when
4974  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4975  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4976  * offset; for a fixed offset check_stack_read_fixed_off should be used
4977  * instead.
4978  */
4979 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4980 				    int ptr_regno, int off, int size, int dst_regno)
4981 {
4982 	/* The state of the source register. */
4983 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4984 	struct bpf_func_state *ptr_state = func(env, reg);
4985 	int err;
4986 	int min_off, max_off;
4987 
4988 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4989 	 */
4990 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4991 					    false, ACCESS_DIRECT, NULL);
4992 	if (err)
4993 		return err;
4994 
4995 	min_off = reg->smin_value + off;
4996 	max_off = reg->smax_value + off;
4997 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4998 	return 0;
4999 }
5000 
5001 /* check_stack_read dispatches to check_stack_read_fixed_off or
5002  * check_stack_read_var_off.
5003  *
5004  * The caller must ensure that the offset falls within the allocated stack
5005  * bounds.
5006  *
5007  * 'dst_regno' is a register which will receive the value from the stack. It
5008  * can be -1, meaning that the read value is not going to a register.
5009  */
5010 static int check_stack_read(struct bpf_verifier_env *env,
5011 			    int ptr_regno, int off, int size,
5012 			    int dst_regno)
5013 {
5014 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5015 	struct bpf_func_state *state = func(env, reg);
5016 	int err;
5017 	/* Some accesses are only permitted with a static offset. */
5018 	bool var_off = !tnum_is_const(reg->var_off);
5019 
5020 	/* The offset is required to be static when reads don't go to a
5021 	 * register, in order to not leak pointers (see
5022 	 * check_stack_read_fixed_off).
5023 	 */
5024 	if (dst_regno < 0 && var_off) {
5025 		char tn_buf[48];
5026 
5027 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5028 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5029 			tn_buf, off, size);
5030 		return -EACCES;
5031 	}
5032 	/* Variable offset is prohibited for unprivileged mode for simplicity
5033 	 * since it requires corresponding support in Spectre masking for stack
5034 	 * ALU. See also retrieve_ptr_limit(). The check in
5035 	 * check_stack_access_for_ptr_arithmetic() called by
5036 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5037 	 * with variable offsets, therefore no check is required here. Further,
5038 	 * just checking it here would be insufficient as speculative stack
5039 	 * writes could still lead to unsafe speculative behaviour.
5040 	 */
5041 	if (!var_off) {
5042 		off += reg->var_off.value;
5043 		err = check_stack_read_fixed_off(env, state, off, size,
5044 						 dst_regno);
5045 	} else {
5046 		/* Variable offset stack reads need more conservative handling
5047 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5048 		 * branch.
5049 		 */
5050 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5051 					       dst_regno);
5052 	}
5053 	return err;
5054 }
5055 
5056 
5057 /* check_stack_write dispatches to check_stack_write_fixed_off or
5058  * check_stack_write_var_off.
5059  *
5060  * 'ptr_regno' is the register used as a pointer into the stack.
5061  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5062  * 'value_regno' is the register whose value we're writing to the stack. It can
5063  * be -1, meaning that we're not writing from a register.
5064  *
5065  * The caller must ensure that the offset falls within the maximum stack size.
5066  */
5067 static int check_stack_write(struct bpf_verifier_env *env,
5068 			     int ptr_regno, int off, int size,
5069 			     int value_regno, int insn_idx)
5070 {
5071 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5072 	struct bpf_func_state *state = func(env, reg);
5073 	int err;
5074 
5075 	if (tnum_is_const(reg->var_off)) {
5076 		off += reg->var_off.value;
5077 		err = check_stack_write_fixed_off(env, state, off, size,
5078 						  value_regno, insn_idx);
5079 	} else {
5080 		/* Variable offset stack reads need more conservative handling
5081 		 * than fixed offset ones.
5082 		 */
5083 		err = check_stack_write_var_off(env, state,
5084 						ptr_regno, off, size,
5085 						value_regno, insn_idx);
5086 	}
5087 	return err;
5088 }
5089 
5090 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5091 				 int off, int size, enum bpf_access_type type)
5092 {
5093 	struct bpf_reg_state *regs = cur_regs(env);
5094 	struct bpf_map *map = regs[regno].map_ptr;
5095 	u32 cap = bpf_map_flags_to_cap(map);
5096 
5097 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5098 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5099 			map->value_size, off, size);
5100 		return -EACCES;
5101 	}
5102 
5103 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5104 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5105 			map->value_size, off, size);
5106 		return -EACCES;
5107 	}
5108 
5109 	return 0;
5110 }
5111 
5112 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5113 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5114 			      int off, int size, u32 mem_size,
5115 			      bool zero_size_allowed)
5116 {
5117 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5118 	struct bpf_reg_state *reg;
5119 
5120 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5121 		return 0;
5122 
5123 	reg = &cur_regs(env)[regno];
5124 	switch (reg->type) {
5125 	case PTR_TO_MAP_KEY:
5126 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5127 			mem_size, off, size);
5128 		break;
5129 	case PTR_TO_MAP_VALUE:
5130 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5131 			mem_size, off, size);
5132 		break;
5133 	case PTR_TO_PACKET:
5134 	case PTR_TO_PACKET_META:
5135 	case PTR_TO_PACKET_END:
5136 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5137 			off, size, regno, reg->id, off, mem_size);
5138 		break;
5139 	case PTR_TO_MEM:
5140 	default:
5141 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5142 			mem_size, off, size);
5143 	}
5144 
5145 	return -EACCES;
5146 }
5147 
5148 /* check read/write into a memory region with possible variable offset */
5149 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5150 				   int off, int size, u32 mem_size,
5151 				   bool zero_size_allowed)
5152 {
5153 	struct bpf_verifier_state *vstate = env->cur_state;
5154 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5155 	struct bpf_reg_state *reg = &state->regs[regno];
5156 	int err;
5157 
5158 	/* We may have adjusted the register pointing to memory region, so we
5159 	 * need to try adding each of min_value and max_value to off
5160 	 * to make sure our theoretical access will be safe.
5161 	 *
5162 	 * The minimum value is only important with signed
5163 	 * comparisons where we can't assume the floor of a
5164 	 * value is 0.  If we are using signed variables for our
5165 	 * index'es we need to make sure that whatever we use
5166 	 * will have a set floor within our range.
5167 	 */
5168 	if (reg->smin_value < 0 &&
5169 	    (reg->smin_value == S64_MIN ||
5170 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5171 	      reg->smin_value + off < 0)) {
5172 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5173 			regno);
5174 		return -EACCES;
5175 	}
5176 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5177 				 mem_size, zero_size_allowed);
5178 	if (err) {
5179 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5180 			regno);
5181 		return err;
5182 	}
5183 
5184 	/* If we haven't set a max value then we need to bail since we can't be
5185 	 * sure we won't do bad things.
5186 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5187 	 */
5188 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5189 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5190 			regno);
5191 		return -EACCES;
5192 	}
5193 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5194 				 mem_size, zero_size_allowed);
5195 	if (err) {
5196 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5197 			regno);
5198 		return err;
5199 	}
5200 
5201 	return 0;
5202 }
5203 
5204 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5205 			       const struct bpf_reg_state *reg, int regno,
5206 			       bool fixed_off_ok)
5207 {
5208 	/* Access to this pointer-typed register or passing it to a helper
5209 	 * is only allowed in its original, unmodified form.
5210 	 */
5211 
5212 	if (reg->off < 0) {
5213 		verbose(env, "negative offset %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 (!fixed_off_ok && reg->off) {
5219 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5220 			reg_type_str(env, reg->type), regno, reg->off);
5221 		return -EACCES;
5222 	}
5223 
5224 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5225 		char tn_buf[48];
5226 
5227 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5228 		verbose(env, "variable %s access var_off=%s disallowed\n",
5229 			reg_type_str(env, reg->type), tn_buf);
5230 		return -EACCES;
5231 	}
5232 
5233 	return 0;
5234 }
5235 
5236 int check_ptr_off_reg(struct bpf_verifier_env *env,
5237 		      const struct bpf_reg_state *reg, int regno)
5238 {
5239 	return __check_ptr_off_reg(env, reg, regno, false);
5240 }
5241 
5242 static int map_kptr_match_type(struct bpf_verifier_env *env,
5243 			       struct btf_field *kptr_field,
5244 			       struct bpf_reg_state *reg, u32 regno)
5245 {
5246 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5247 	int perm_flags;
5248 	const char *reg_name = "";
5249 
5250 	if (btf_is_kernel(reg->btf)) {
5251 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5252 
5253 		/* Only unreferenced case accepts untrusted pointers */
5254 		if (kptr_field->type == BPF_KPTR_UNREF)
5255 			perm_flags |= PTR_UNTRUSTED;
5256 	} else {
5257 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5258 	}
5259 
5260 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5261 		goto bad_type;
5262 
5263 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5264 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5265 
5266 	/* For ref_ptr case, release function check should ensure we get one
5267 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5268 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5269 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5270 	 * reg->off and reg->ref_obj_id are not needed here.
5271 	 */
5272 	if (__check_ptr_off_reg(env, reg, regno, true))
5273 		return -EACCES;
5274 
5275 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5276 	 * we also need to take into account the reg->off.
5277 	 *
5278 	 * We want to support cases like:
5279 	 *
5280 	 * struct foo {
5281 	 *         struct bar br;
5282 	 *         struct baz bz;
5283 	 * };
5284 	 *
5285 	 * struct foo *v;
5286 	 * v = func();	      // PTR_TO_BTF_ID
5287 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5288 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5289 	 *                    // first member type of struct after comparison fails
5290 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5291 	 *                    // to match type
5292 	 *
5293 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5294 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5295 	 * the struct to match type against first member of struct, i.e. reject
5296 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5297 	 * strict mode to true for type match.
5298 	 */
5299 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5300 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5301 				  kptr_field->type == BPF_KPTR_REF))
5302 		goto bad_type;
5303 	return 0;
5304 bad_type:
5305 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5306 		reg_type_str(env, reg->type), reg_name);
5307 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5308 	if (kptr_field->type == BPF_KPTR_UNREF)
5309 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5310 			targ_name);
5311 	else
5312 		verbose(env, "\n");
5313 	return -EINVAL;
5314 }
5315 
5316 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5317  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5318  */
5319 static bool in_rcu_cs(struct bpf_verifier_env *env)
5320 {
5321 	return env->cur_state->active_rcu_lock ||
5322 	       env->cur_state->active_lock.ptr ||
5323 	       !env->prog->aux->sleepable;
5324 }
5325 
5326 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5327 BTF_SET_START(rcu_protected_types)
5328 BTF_ID(struct, prog_test_ref_kfunc)
5329 BTF_ID(struct, cgroup)
5330 BTF_ID(struct, bpf_cpumask)
5331 BTF_ID(struct, task_struct)
5332 BTF_SET_END(rcu_protected_types)
5333 
5334 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5335 {
5336 	if (!btf_is_kernel(btf))
5337 		return false;
5338 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5339 }
5340 
5341 static bool rcu_safe_kptr(const struct btf_field *field)
5342 {
5343 	const struct btf_field_kptr *kptr = &field->kptr;
5344 
5345 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5346 }
5347 
5348 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5349 				 int value_regno, int insn_idx,
5350 				 struct btf_field *kptr_field)
5351 {
5352 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5353 	int class = BPF_CLASS(insn->code);
5354 	struct bpf_reg_state *val_reg;
5355 
5356 	/* Things we already checked for in check_map_access and caller:
5357 	 *  - Reject cases where variable offset may touch kptr
5358 	 *  - size of access (must be BPF_DW)
5359 	 *  - tnum_is_const(reg->var_off)
5360 	 *  - kptr_field->offset == off + reg->var_off.value
5361 	 */
5362 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5363 	if (BPF_MODE(insn->code) != BPF_MEM) {
5364 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5365 		return -EACCES;
5366 	}
5367 
5368 	/* We only allow loading referenced kptr, since it will be marked as
5369 	 * untrusted, similar to unreferenced kptr.
5370 	 */
5371 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5372 		verbose(env, "store to referenced kptr disallowed\n");
5373 		return -EACCES;
5374 	}
5375 
5376 	if (class == BPF_LDX) {
5377 		val_reg = reg_state(env, value_regno);
5378 		/* We can simply mark the value_regno receiving the pointer
5379 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5380 		 */
5381 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5382 				kptr_field->kptr.btf_id,
5383 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5384 				PTR_MAYBE_NULL | MEM_RCU :
5385 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5386 	} else if (class == BPF_STX) {
5387 		val_reg = reg_state(env, value_regno);
5388 		if (!register_is_null(val_reg) &&
5389 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5390 			return -EACCES;
5391 	} else if (class == BPF_ST) {
5392 		if (insn->imm) {
5393 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5394 				kptr_field->offset);
5395 			return -EACCES;
5396 		}
5397 	} else {
5398 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5399 		return -EACCES;
5400 	}
5401 	return 0;
5402 }
5403 
5404 /* check read/write into a map element with possible variable offset */
5405 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5406 			    int off, int size, bool zero_size_allowed,
5407 			    enum bpf_access_src src)
5408 {
5409 	struct bpf_verifier_state *vstate = env->cur_state;
5410 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5411 	struct bpf_reg_state *reg = &state->regs[regno];
5412 	struct bpf_map *map = reg->map_ptr;
5413 	struct btf_record *rec;
5414 	int err, i;
5415 
5416 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5417 				      zero_size_allowed);
5418 	if (err)
5419 		return err;
5420 
5421 	if (IS_ERR_OR_NULL(map->record))
5422 		return 0;
5423 	rec = map->record;
5424 	for (i = 0; i < rec->cnt; i++) {
5425 		struct btf_field *field = &rec->fields[i];
5426 		u32 p = field->offset;
5427 
5428 		/* If any part of a field  can be touched by load/store, reject
5429 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5430 		 * it is sufficient to check x1 < y2 && y1 < x2.
5431 		 */
5432 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5433 		    p < reg->umax_value + off + size) {
5434 			switch (field->type) {
5435 			case BPF_KPTR_UNREF:
5436 			case BPF_KPTR_REF:
5437 				if (src != ACCESS_DIRECT) {
5438 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5439 					return -EACCES;
5440 				}
5441 				if (!tnum_is_const(reg->var_off)) {
5442 					verbose(env, "kptr access cannot have variable offset\n");
5443 					return -EACCES;
5444 				}
5445 				if (p != off + reg->var_off.value) {
5446 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5447 						p, off + reg->var_off.value);
5448 					return -EACCES;
5449 				}
5450 				if (size != bpf_size_to_bytes(BPF_DW)) {
5451 					verbose(env, "kptr access size must be BPF_DW\n");
5452 					return -EACCES;
5453 				}
5454 				break;
5455 			default:
5456 				verbose(env, "%s cannot be accessed directly by load/store\n",
5457 					btf_field_type_name(field->type));
5458 				return -EACCES;
5459 			}
5460 		}
5461 	}
5462 	return 0;
5463 }
5464 
5465 #define MAX_PACKET_OFF 0xffff
5466 
5467 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5468 				       const struct bpf_call_arg_meta *meta,
5469 				       enum bpf_access_type t)
5470 {
5471 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5472 
5473 	switch (prog_type) {
5474 	/* Program types only with direct read access go here! */
5475 	case BPF_PROG_TYPE_LWT_IN:
5476 	case BPF_PROG_TYPE_LWT_OUT:
5477 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5478 	case BPF_PROG_TYPE_SK_REUSEPORT:
5479 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5480 	case BPF_PROG_TYPE_CGROUP_SKB:
5481 		if (t == BPF_WRITE)
5482 			return false;
5483 		fallthrough;
5484 
5485 	/* Program types with direct read + write access go here! */
5486 	case BPF_PROG_TYPE_SCHED_CLS:
5487 	case BPF_PROG_TYPE_SCHED_ACT:
5488 	case BPF_PROG_TYPE_XDP:
5489 	case BPF_PROG_TYPE_LWT_XMIT:
5490 	case BPF_PROG_TYPE_SK_SKB:
5491 	case BPF_PROG_TYPE_SK_MSG:
5492 		if (meta)
5493 			return meta->pkt_access;
5494 
5495 		env->seen_direct_write = true;
5496 		return true;
5497 
5498 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5499 		if (t == BPF_WRITE)
5500 			env->seen_direct_write = true;
5501 
5502 		return true;
5503 
5504 	default:
5505 		return false;
5506 	}
5507 }
5508 
5509 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5510 			       int size, bool zero_size_allowed)
5511 {
5512 	struct bpf_reg_state *regs = cur_regs(env);
5513 	struct bpf_reg_state *reg = &regs[regno];
5514 	int err;
5515 
5516 	/* We may have added a variable offset to the packet pointer; but any
5517 	 * reg->range we have comes after that.  We are only checking the fixed
5518 	 * offset.
5519 	 */
5520 
5521 	/* We don't allow negative numbers, because we aren't tracking enough
5522 	 * detail to prove they're safe.
5523 	 */
5524 	if (reg->smin_value < 0) {
5525 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5526 			regno);
5527 		return -EACCES;
5528 	}
5529 
5530 	err = reg->range < 0 ? -EINVAL :
5531 	      __check_mem_access(env, regno, off, size, reg->range,
5532 				 zero_size_allowed);
5533 	if (err) {
5534 		verbose(env, "R%d offset is outside of the packet\n", regno);
5535 		return err;
5536 	}
5537 
5538 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5539 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5540 	 * otherwise find_good_pkt_pointers would have refused to set range info
5541 	 * that __check_mem_access would have rejected this pkt access.
5542 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5543 	 */
5544 	env->prog->aux->max_pkt_offset =
5545 		max_t(u32, env->prog->aux->max_pkt_offset,
5546 		      off + reg->umax_value + size - 1);
5547 
5548 	return err;
5549 }
5550 
5551 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5552 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5553 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5554 			    struct btf **btf, u32 *btf_id)
5555 {
5556 	struct bpf_insn_access_aux info = {
5557 		.reg_type = *reg_type,
5558 		.log = &env->log,
5559 	};
5560 
5561 	if (env->ops->is_valid_access &&
5562 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5563 		/* A non zero info.ctx_field_size indicates that this field is a
5564 		 * candidate for later verifier transformation to load the whole
5565 		 * field and then apply a mask when accessed with a narrower
5566 		 * access than actual ctx access size. A zero info.ctx_field_size
5567 		 * will only allow for whole field access and rejects any other
5568 		 * type of narrower access.
5569 		 */
5570 		*reg_type = info.reg_type;
5571 
5572 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5573 			*btf = info.btf;
5574 			*btf_id = info.btf_id;
5575 		} else {
5576 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5577 		}
5578 		/* remember the offset of last byte accessed in ctx */
5579 		if (env->prog->aux->max_ctx_offset < off + size)
5580 			env->prog->aux->max_ctx_offset = off + size;
5581 		return 0;
5582 	}
5583 
5584 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5585 	return -EACCES;
5586 }
5587 
5588 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5589 				  int size)
5590 {
5591 	if (size < 0 || off < 0 ||
5592 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5593 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5594 			off, size);
5595 		return -EACCES;
5596 	}
5597 	return 0;
5598 }
5599 
5600 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5601 			     u32 regno, int off, int size,
5602 			     enum bpf_access_type t)
5603 {
5604 	struct bpf_reg_state *regs = cur_regs(env);
5605 	struct bpf_reg_state *reg = &regs[regno];
5606 	struct bpf_insn_access_aux info = {};
5607 	bool valid;
5608 
5609 	if (reg->smin_value < 0) {
5610 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5611 			regno);
5612 		return -EACCES;
5613 	}
5614 
5615 	switch (reg->type) {
5616 	case PTR_TO_SOCK_COMMON:
5617 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5618 		break;
5619 	case PTR_TO_SOCKET:
5620 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5621 		break;
5622 	case PTR_TO_TCP_SOCK:
5623 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5624 		break;
5625 	case PTR_TO_XDP_SOCK:
5626 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5627 		break;
5628 	default:
5629 		valid = false;
5630 	}
5631 
5632 
5633 	if (valid) {
5634 		env->insn_aux_data[insn_idx].ctx_field_size =
5635 			info.ctx_field_size;
5636 		return 0;
5637 	}
5638 
5639 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5640 		regno, reg_type_str(env, reg->type), off, size);
5641 
5642 	return -EACCES;
5643 }
5644 
5645 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5646 {
5647 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5648 }
5649 
5650 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5651 {
5652 	const struct bpf_reg_state *reg = reg_state(env, regno);
5653 
5654 	return reg->type == PTR_TO_CTX;
5655 }
5656 
5657 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5658 {
5659 	const struct bpf_reg_state *reg = reg_state(env, regno);
5660 
5661 	return type_is_sk_pointer(reg->type);
5662 }
5663 
5664 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5665 {
5666 	const struct bpf_reg_state *reg = reg_state(env, regno);
5667 
5668 	return type_is_pkt_pointer(reg->type);
5669 }
5670 
5671 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5672 {
5673 	const struct bpf_reg_state *reg = reg_state(env, regno);
5674 
5675 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5676 	return reg->type == PTR_TO_FLOW_KEYS;
5677 }
5678 
5679 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5680 #ifdef CONFIG_NET
5681 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5682 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5683 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5684 #endif
5685 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5686 };
5687 
5688 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5689 {
5690 	/* A referenced register is always trusted. */
5691 	if (reg->ref_obj_id)
5692 		return true;
5693 
5694 	/* Types listed in the reg2btf_ids are always trusted */
5695 	if (reg2btf_ids[base_type(reg->type)] &&
5696 	    !bpf_type_has_unsafe_modifiers(reg->type))
5697 		return true;
5698 
5699 	/* If a register is not referenced, it is trusted if it has the
5700 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5701 	 * other type modifiers may be safe, but we elect to take an opt-in
5702 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5703 	 * not.
5704 	 *
5705 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5706 	 * for whether a register is trusted.
5707 	 */
5708 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5709 	       !bpf_type_has_unsafe_modifiers(reg->type);
5710 }
5711 
5712 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5713 {
5714 	return reg->type & MEM_RCU;
5715 }
5716 
5717 static void clear_trusted_flags(enum bpf_type_flag *flag)
5718 {
5719 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5720 }
5721 
5722 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5723 				   const struct bpf_reg_state *reg,
5724 				   int off, int size, bool strict)
5725 {
5726 	struct tnum reg_off;
5727 	int ip_align;
5728 
5729 	/* Byte size accesses are always allowed. */
5730 	if (!strict || size == 1)
5731 		return 0;
5732 
5733 	/* For platforms that do not have a Kconfig enabling
5734 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5735 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5736 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5737 	 * to this code only in strict mode where we want to emulate
5738 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5739 	 * unconditional IP align value of '2'.
5740 	 */
5741 	ip_align = 2;
5742 
5743 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5744 	if (!tnum_is_aligned(reg_off, size)) {
5745 		char tn_buf[48];
5746 
5747 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5748 		verbose(env,
5749 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5750 			ip_align, tn_buf, reg->off, off, size);
5751 		return -EACCES;
5752 	}
5753 
5754 	return 0;
5755 }
5756 
5757 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5758 				       const struct bpf_reg_state *reg,
5759 				       const char *pointer_desc,
5760 				       int off, int size, bool strict)
5761 {
5762 	struct tnum reg_off;
5763 
5764 	/* Byte size accesses are always allowed. */
5765 	if (!strict || size == 1)
5766 		return 0;
5767 
5768 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5769 	if (!tnum_is_aligned(reg_off, size)) {
5770 		char tn_buf[48];
5771 
5772 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5773 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5774 			pointer_desc, tn_buf, reg->off, off, size);
5775 		return -EACCES;
5776 	}
5777 
5778 	return 0;
5779 }
5780 
5781 static int check_ptr_alignment(struct bpf_verifier_env *env,
5782 			       const struct bpf_reg_state *reg, int off,
5783 			       int size, bool strict_alignment_once)
5784 {
5785 	bool strict = env->strict_alignment || strict_alignment_once;
5786 	const char *pointer_desc = "";
5787 
5788 	switch (reg->type) {
5789 	case PTR_TO_PACKET:
5790 	case PTR_TO_PACKET_META:
5791 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5792 		 * right in front, treat it the very same way.
5793 		 */
5794 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5795 	case PTR_TO_FLOW_KEYS:
5796 		pointer_desc = "flow keys ";
5797 		break;
5798 	case PTR_TO_MAP_KEY:
5799 		pointer_desc = "key ";
5800 		break;
5801 	case PTR_TO_MAP_VALUE:
5802 		pointer_desc = "value ";
5803 		break;
5804 	case PTR_TO_CTX:
5805 		pointer_desc = "context ";
5806 		break;
5807 	case PTR_TO_STACK:
5808 		pointer_desc = "stack ";
5809 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5810 		 * and check_stack_read_fixed_off() relies on stack accesses being
5811 		 * aligned.
5812 		 */
5813 		strict = true;
5814 		break;
5815 	case PTR_TO_SOCKET:
5816 		pointer_desc = "sock ";
5817 		break;
5818 	case PTR_TO_SOCK_COMMON:
5819 		pointer_desc = "sock_common ";
5820 		break;
5821 	case PTR_TO_TCP_SOCK:
5822 		pointer_desc = "tcp_sock ";
5823 		break;
5824 	case PTR_TO_XDP_SOCK:
5825 		pointer_desc = "xdp_sock ";
5826 		break;
5827 	default:
5828 		break;
5829 	}
5830 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5831 					   strict);
5832 }
5833 
5834 /* starting from main bpf function walk all instructions of the function
5835  * and recursively walk all callees that given function can call.
5836  * Ignore jump and exit insns.
5837  * Since recursion is prevented by check_cfg() this algorithm
5838  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5839  */
5840 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5841 {
5842 	struct bpf_subprog_info *subprog = env->subprog_info;
5843 	struct bpf_insn *insn = env->prog->insnsi;
5844 	int depth = 0, frame = 0, i, subprog_end;
5845 	bool tail_call_reachable = false;
5846 	int ret_insn[MAX_CALL_FRAMES];
5847 	int ret_prog[MAX_CALL_FRAMES];
5848 	int j;
5849 
5850 	i = subprog[idx].start;
5851 process_func:
5852 	/* protect against potential stack overflow that might happen when
5853 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5854 	 * depth for such case down to 256 so that the worst case scenario
5855 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5856 	 * 8k).
5857 	 *
5858 	 * To get the idea what might happen, see an example:
5859 	 * func1 -> sub rsp, 128
5860 	 *  subfunc1 -> sub rsp, 256
5861 	 *  tailcall1 -> add rsp, 256
5862 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5863 	 *   subfunc2 -> sub rsp, 64
5864 	 *   subfunc22 -> sub rsp, 128
5865 	 *   tailcall2 -> add rsp, 128
5866 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5867 	 *
5868 	 * tailcall will unwind the current stack frame but it will not get rid
5869 	 * of caller's stack as shown on the example above.
5870 	 */
5871 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5872 		verbose(env,
5873 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5874 			depth);
5875 		return -EACCES;
5876 	}
5877 	/* round up to 32-bytes, since this is granularity
5878 	 * of interpreter stack size
5879 	 */
5880 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5881 	if (depth > MAX_BPF_STACK) {
5882 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5883 			frame + 1, depth);
5884 		return -EACCES;
5885 	}
5886 continue_func:
5887 	subprog_end = subprog[idx + 1].start;
5888 	for (; i < subprog_end; i++) {
5889 		int next_insn, sidx;
5890 
5891 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5892 			continue;
5893 		/* remember insn and function to return to */
5894 		ret_insn[frame] = i + 1;
5895 		ret_prog[frame] = idx;
5896 
5897 		/* find the callee */
5898 		next_insn = i + insn[i].imm + 1;
5899 		sidx = find_subprog(env, next_insn);
5900 		if (sidx < 0) {
5901 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5902 				  next_insn);
5903 			return -EFAULT;
5904 		}
5905 		if (subprog[sidx].is_async_cb) {
5906 			if (subprog[sidx].has_tail_call) {
5907 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5908 				return -EFAULT;
5909 			}
5910 			/* async callbacks don't increase bpf prog stack size unless called directly */
5911 			if (!bpf_pseudo_call(insn + i))
5912 				continue;
5913 		}
5914 		i = next_insn;
5915 		idx = sidx;
5916 
5917 		if (subprog[idx].has_tail_call)
5918 			tail_call_reachable = true;
5919 
5920 		frame++;
5921 		if (frame >= MAX_CALL_FRAMES) {
5922 			verbose(env, "the call stack of %d frames is too deep !\n",
5923 				frame);
5924 			return -E2BIG;
5925 		}
5926 		goto process_func;
5927 	}
5928 	/* if tail call got detected across bpf2bpf calls then mark each of the
5929 	 * currently present subprog frames as tail call reachable subprogs;
5930 	 * this info will be utilized by JIT so that we will be preserving the
5931 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5932 	 */
5933 	if (tail_call_reachable)
5934 		for (j = 0; j < frame; j++)
5935 			subprog[ret_prog[j]].tail_call_reachable = true;
5936 	if (subprog[0].tail_call_reachable)
5937 		env->prog->aux->tail_call_reachable = true;
5938 
5939 	/* end of for() loop means the last insn of the 'subprog'
5940 	 * was reached. Doesn't matter whether it was JA or EXIT
5941 	 */
5942 	if (frame == 0)
5943 		return 0;
5944 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5945 	frame--;
5946 	i = ret_insn[frame];
5947 	idx = ret_prog[frame];
5948 	goto continue_func;
5949 }
5950 
5951 static int check_max_stack_depth(struct bpf_verifier_env *env)
5952 {
5953 	struct bpf_subprog_info *si = env->subprog_info;
5954 	int ret;
5955 
5956 	for (int i = 0; i < env->subprog_cnt; i++) {
5957 		if (!i || si[i].is_async_cb) {
5958 			ret = check_max_stack_depth_subprog(env, i);
5959 			if (ret < 0)
5960 				return ret;
5961 		}
5962 		continue;
5963 	}
5964 	return 0;
5965 }
5966 
5967 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5968 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5969 				  const struct bpf_insn *insn, int idx)
5970 {
5971 	int start = idx + insn->imm + 1, subprog;
5972 
5973 	subprog = find_subprog(env, start);
5974 	if (subprog < 0) {
5975 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5976 			  start);
5977 		return -EFAULT;
5978 	}
5979 	return env->subprog_info[subprog].stack_depth;
5980 }
5981 #endif
5982 
5983 static int __check_buffer_access(struct bpf_verifier_env *env,
5984 				 const char *buf_info,
5985 				 const struct bpf_reg_state *reg,
5986 				 int regno, int off, int size)
5987 {
5988 	if (off < 0) {
5989 		verbose(env,
5990 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5991 			regno, buf_info, off, size);
5992 		return -EACCES;
5993 	}
5994 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5995 		char tn_buf[48];
5996 
5997 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5998 		verbose(env,
5999 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6000 			regno, off, tn_buf);
6001 		return -EACCES;
6002 	}
6003 
6004 	return 0;
6005 }
6006 
6007 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6008 				  const struct bpf_reg_state *reg,
6009 				  int regno, int off, int size)
6010 {
6011 	int err;
6012 
6013 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6014 	if (err)
6015 		return err;
6016 
6017 	if (off + size > env->prog->aux->max_tp_access)
6018 		env->prog->aux->max_tp_access = off + size;
6019 
6020 	return 0;
6021 }
6022 
6023 static int check_buffer_access(struct bpf_verifier_env *env,
6024 			       const struct bpf_reg_state *reg,
6025 			       int regno, int off, int size,
6026 			       bool zero_size_allowed,
6027 			       u32 *max_access)
6028 {
6029 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6030 	int err;
6031 
6032 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6033 	if (err)
6034 		return err;
6035 
6036 	if (off + size > *max_access)
6037 		*max_access = off + size;
6038 
6039 	return 0;
6040 }
6041 
6042 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6043 static void zext_32_to_64(struct bpf_reg_state *reg)
6044 {
6045 	reg->var_off = tnum_subreg(reg->var_off);
6046 	__reg_assign_32_into_64(reg);
6047 }
6048 
6049 /* truncate register to smaller size (in bytes)
6050  * must be called with size < BPF_REG_SIZE
6051  */
6052 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6053 {
6054 	u64 mask;
6055 
6056 	/* clear high bits in bit representation */
6057 	reg->var_off = tnum_cast(reg->var_off, size);
6058 
6059 	/* fix arithmetic bounds */
6060 	mask = ((u64)1 << (size * 8)) - 1;
6061 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6062 		reg->umin_value &= mask;
6063 		reg->umax_value &= mask;
6064 	} else {
6065 		reg->umin_value = 0;
6066 		reg->umax_value = mask;
6067 	}
6068 	reg->smin_value = reg->umin_value;
6069 	reg->smax_value = reg->umax_value;
6070 
6071 	/* If size is smaller than 32bit register the 32bit register
6072 	 * values are also truncated so we push 64-bit bounds into
6073 	 * 32-bit bounds. Above were truncated < 32-bits already.
6074 	 */
6075 	if (size >= 4)
6076 		return;
6077 	__reg_combine_64_into_32(reg);
6078 }
6079 
6080 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6081 {
6082 	if (size == 1) {
6083 		reg->smin_value = reg->s32_min_value = S8_MIN;
6084 		reg->smax_value = reg->s32_max_value = S8_MAX;
6085 	} else if (size == 2) {
6086 		reg->smin_value = reg->s32_min_value = S16_MIN;
6087 		reg->smax_value = reg->s32_max_value = S16_MAX;
6088 	} else {
6089 		/* size == 4 */
6090 		reg->smin_value = reg->s32_min_value = S32_MIN;
6091 		reg->smax_value = reg->s32_max_value = S32_MAX;
6092 	}
6093 	reg->umin_value = reg->u32_min_value = 0;
6094 	reg->umax_value = U64_MAX;
6095 	reg->u32_max_value = U32_MAX;
6096 	reg->var_off = tnum_unknown;
6097 }
6098 
6099 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6100 {
6101 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6102 	u64 top_smax_value, top_smin_value;
6103 	u64 num_bits = size * 8;
6104 
6105 	if (tnum_is_const(reg->var_off)) {
6106 		u64_cval = reg->var_off.value;
6107 		if (size == 1)
6108 			reg->var_off = tnum_const((s8)u64_cval);
6109 		else if (size == 2)
6110 			reg->var_off = tnum_const((s16)u64_cval);
6111 		else
6112 			/* size == 4 */
6113 			reg->var_off = tnum_const((s32)u64_cval);
6114 
6115 		u64_cval = reg->var_off.value;
6116 		reg->smax_value = reg->smin_value = u64_cval;
6117 		reg->umax_value = reg->umin_value = u64_cval;
6118 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6119 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6120 		return;
6121 	}
6122 
6123 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6124 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6125 
6126 	if (top_smax_value != top_smin_value)
6127 		goto out;
6128 
6129 	/* find the s64_min and s64_min after sign extension */
6130 	if (size == 1) {
6131 		init_s64_max = (s8)reg->smax_value;
6132 		init_s64_min = (s8)reg->smin_value;
6133 	} else if (size == 2) {
6134 		init_s64_max = (s16)reg->smax_value;
6135 		init_s64_min = (s16)reg->smin_value;
6136 	} else {
6137 		init_s64_max = (s32)reg->smax_value;
6138 		init_s64_min = (s32)reg->smin_value;
6139 	}
6140 
6141 	s64_max = max(init_s64_max, init_s64_min);
6142 	s64_min = min(init_s64_max, init_s64_min);
6143 
6144 	/* both of s64_max/s64_min positive or negative */
6145 	if ((s64_max >= 0) == (s64_min >= 0)) {
6146 		reg->smin_value = reg->s32_min_value = s64_min;
6147 		reg->smax_value = reg->s32_max_value = s64_max;
6148 		reg->umin_value = reg->u32_min_value = s64_min;
6149 		reg->umax_value = reg->u32_max_value = s64_max;
6150 		reg->var_off = tnum_range(s64_min, s64_max);
6151 		return;
6152 	}
6153 
6154 out:
6155 	set_sext64_default_val(reg, size);
6156 }
6157 
6158 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6159 {
6160 	if (size == 1) {
6161 		reg->s32_min_value = S8_MIN;
6162 		reg->s32_max_value = S8_MAX;
6163 	} else {
6164 		/* size == 2 */
6165 		reg->s32_min_value = S16_MIN;
6166 		reg->s32_max_value = S16_MAX;
6167 	}
6168 	reg->u32_min_value = 0;
6169 	reg->u32_max_value = U32_MAX;
6170 	reg->var_off = tnum_subreg(tnum_unknown);
6171 }
6172 
6173 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6174 {
6175 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6176 	u32 top_smax_value, top_smin_value;
6177 	u32 num_bits = size * 8;
6178 
6179 	if (tnum_is_const(reg->var_off)) {
6180 		u32_val = reg->var_off.value;
6181 		if (size == 1)
6182 			reg->var_off = tnum_const((s8)u32_val);
6183 		else
6184 			reg->var_off = tnum_const((s16)u32_val);
6185 
6186 		u32_val = reg->var_off.value;
6187 		reg->s32_min_value = reg->s32_max_value = u32_val;
6188 		reg->u32_min_value = reg->u32_max_value = u32_val;
6189 		return;
6190 	}
6191 
6192 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6193 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6194 
6195 	if (top_smax_value != top_smin_value)
6196 		goto out;
6197 
6198 	/* find the s32_min and s32_min after sign extension */
6199 	if (size == 1) {
6200 		init_s32_max = (s8)reg->s32_max_value;
6201 		init_s32_min = (s8)reg->s32_min_value;
6202 	} else {
6203 		/* size == 2 */
6204 		init_s32_max = (s16)reg->s32_max_value;
6205 		init_s32_min = (s16)reg->s32_min_value;
6206 	}
6207 	s32_max = max(init_s32_max, init_s32_min);
6208 	s32_min = min(init_s32_max, init_s32_min);
6209 
6210 	if ((s32_min >= 0) == (s32_max >= 0)) {
6211 		reg->s32_min_value = s32_min;
6212 		reg->s32_max_value = s32_max;
6213 		reg->u32_min_value = (u32)s32_min;
6214 		reg->u32_max_value = (u32)s32_max;
6215 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6216 		return;
6217 	}
6218 
6219 out:
6220 	set_sext32_default_val(reg, size);
6221 }
6222 
6223 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6224 {
6225 	/* A map is considered read-only if the following condition are true:
6226 	 *
6227 	 * 1) BPF program side cannot change any of the map content. The
6228 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6229 	 *    and was set at map creation time.
6230 	 * 2) The map value(s) have been initialized from user space by a
6231 	 *    loader and then "frozen", such that no new map update/delete
6232 	 *    operations from syscall side are possible for the rest of
6233 	 *    the map's lifetime from that point onwards.
6234 	 * 3) Any parallel/pending map update/delete operations from syscall
6235 	 *    side have been completed. Only after that point, it's safe to
6236 	 *    assume that map value(s) are immutable.
6237 	 */
6238 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6239 	       READ_ONCE(map->frozen) &&
6240 	       !bpf_map_write_active(map);
6241 }
6242 
6243 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6244 			       bool is_ldsx)
6245 {
6246 	void *ptr;
6247 	u64 addr;
6248 	int err;
6249 
6250 	err = map->ops->map_direct_value_addr(map, &addr, off);
6251 	if (err)
6252 		return err;
6253 	ptr = (void *)(long)addr + off;
6254 
6255 	switch (size) {
6256 	case sizeof(u8):
6257 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6258 		break;
6259 	case sizeof(u16):
6260 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6261 		break;
6262 	case sizeof(u32):
6263 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6264 		break;
6265 	case sizeof(u64):
6266 		*val = *(u64 *)ptr;
6267 		break;
6268 	default:
6269 		return -EINVAL;
6270 	}
6271 	return 0;
6272 }
6273 
6274 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6275 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6276 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6277 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6278 
6279 /*
6280  * Allow list few fields as RCU trusted or full trusted.
6281  * This logic doesn't allow mix tagging and will be removed once GCC supports
6282  * btf_type_tag.
6283  */
6284 
6285 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6286 BTF_TYPE_SAFE_RCU(struct task_struct) {
6287 	const cpumask_t *cpus_ptr;
6288 	struct css_set __rcu *cgroups;
6289 	struct task_struct __rcu *real_parent;
6290 	struct task_struct *group_leader;
6291 };
6292 
6293 BTF_TYPE_SAFE_RCU(struct cgroup) {
6294 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6295 	struct kernfs_node *kn;
6296 };
6297 
6298 BTF_TYPE_SAFE_RCU(struct css_set) {
6299 	struct cgroup *dfl_cgrp;
6300 };
6301 
6302 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6303 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6304 	struct file __rcu *exe_file;
6305 };
6306 
6307 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6308  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6309  */
6310 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6311 	struct sock *sk;
6312 };
6313 
6314 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6315 	struct sock *sk;
6316 };
6317 
6318 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6319 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6320 	struct seq_file *seq;
6321 };
6322 
6323 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6324 	struct bpf_iter_meta *meta;
6325 	struct task_struct *task;
6326 };
6327 
6328 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6329 	struct file *file;
6330 };
6331 
6332 BTF_TYPE_SAFE_TRUSTED(struct file) {
6333 	struct inode *f_inode;
6334 };
6335 
6336 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6337 	/* no negative dentry-s in places where bpf can see it */
6338 	struct inode *d_inode;
6339 };
6340 
6341 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6342 	struct sock *sk;
6343 };
6344 
6345 static bool type_is_rcu(struct bpf_verifier_env *env,
6346 			struct bpf_reg_state *reg,
6347 			const char *field_name, u32 btf_id)
6348 {
6349 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6350 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6351 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6352 
6353 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6354 }
6355 
6356 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6357 				struct bpf_reg_state *reg,
6358 				const char *field_name, u32 btf_id)
6359 {
6360 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6361 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6362 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6363 
6364 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6365 }
6366 
6367 static bool type_is_trusted(struct bpf_verifier_env *env,
6368 			    struct bpf_reg_state *reg,
6369 			    const char *field_name, u32 btf_id)
6370 {
6371 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6372 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6373 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6374 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6375 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6376 
6377 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6378 }
6379 
6380 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6381 				    struct bpf_reg_state *reg,
6382 				    const char *field_name, u32 btf_id)
6383 {
6384 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6385 
6386 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6387 					  "__safe_trusted_or_null");
6388 }
6389 
6390 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6391 				   struct bpf_reg_state *regs,
6392 				   int regno, int off, int size,
6393 				   enum bpf_access_type atype,
6394 				   int value_regno)
6395 {
6396 	struct bpf_reg_state *reg = regs + regno;
6397 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6398 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6399 	const char *field_name = NULL;
6400 	enum bpf_type_flag flag = 0;
6401 	u32 btf_id = 0;
6402 	int ret;
6403 
6404 	if (!env->allow_ptr_leaks) {
6405 		verbose(env,
6406 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6407 			tname);
6408 		return -EPERM;
6409 	}
6410 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6411 		verbose(env,
6412 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6413 			tname);
6414 		return -EINVAL;
6415 	}
6416 	if (off < 0) {
6417 		verbose(env,
6418 			"R%d is ptr_%s invalid negative access: off=%d\n",
6419 			regno, tname, off);
6420 		return -EACCES;
6421 	}
6422 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6423 		char tn_buf[48];
6424 
6425 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6426 		verbose(env,
6427 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6428 			regno, tname, off, tn_buf);
6429 		return -EACCES;
6430 	}
6431 
6432 	if (reg->type & MEM_USER) {
6433 		verbose(env,
6434 			"R%d is ptr_%s access user memory: off=%d\n",
6435 			regno, tname, off);
6436 		return -EACCES;
6437 	}
6438 
6439 	if (reg->type & MEM_PERCPU) {
6440 		verbose(env,
6441 			"R%d is ptr_%s access percpu memory: off=%d\n",
6442 			regno, tname, off);
6443 		return -EACCES;
6444 	}
6445 
6446 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6447 		if (!btf_is_kernel(reg->btf)) {
6448 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6449 			return -EFAULT;
6450 		}
6451 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6452 	} else {
6453 		/* Writes are permitted with default btf_struct_access for
6454 		 * program allocated objects (which always have ref_obj_id > 0),
6455 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6456 		 */
6457 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6458 			verbose(env, "only read is supported\n");
6459 			return -EACCES;
6460 		}
6461 
6462 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6463 		    !reg->ref_obj_id) {
6464 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6465 			return -EFAULT;
6466 		}
6467 
6468 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6469 	}
6470 
6471 	if (ret < 0)
6472 		return ret;
6473 
6474 	if (ret != PTR_TO_BTF_ID) {
6475 		/* just mark; */
6476 
6477 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6478 		/* If this is an untrusted pointer, all pointers formed by walking it
6479 		 * also inherit the untrusted flag.
6480 		 */
6481 		flag = PTR_UNTRUSTED;
6482 
6483 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6484 		/* By default any pointer obtained from walking a trusted pointer is no
6485 		 * longer trusted, unless the field being accessed has explicitly been
6486 		 * marked as inheriting its parent's state of trust (either full or RCU).
6487 		 * For example:
6488 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6489 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6490 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6491 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6492 		 *
6493 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6494 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6495 		 */
6496 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6497 			flag |= PTR_TRUSTED;
6498 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6499 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6500 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6501 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6502 				/* ignore __rcu tag and mark it MEM_RCU */
6503 				flag |= MEM_RCU;
6504 			} else if (flag & MEM_RCU ||
6505 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6506 				/* __rcu tagged pointers can be NULL */
6507 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6508 
6509 				/* We always trust them */
6510 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6511 				    flag & PTR_UNTRUSTED)
6512 					flag &= ~PTR_UNTRUSTED;
6513 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6514 				/* keep as-is */
6515 			} else {
6516 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6517 				clear_trusted_flags(&flag);
6518 			}
6519 		} else {
6520 			/*
6521 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6522 			 * aggressively mark as untrusted otherwise such
6523 			 * pointers will be plain PTR_TO_BTF_ID without flags
6524 			 * and will be allowed to be passed into helpers for
6525 			 * compat reasons.
6526 			 */
6527 			flag = PTR_UNTRUSTED;
6528 		}
6529 	} else {
6530 		/* Old compat. Deprecated */
6531 		clear_trusted_flags(&flag);
6532 	}
6533 
6534 	if (atype == BPF_READ && value_regno >= 0)
6535 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6536 
6537 	return 0;
6538 }
6539 
6540 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6541 				   struct bpf_reg_state *regs,
6542 				   int regno, int off, int size,
6543 				   enum bpf_access_type atype,
6544 				   int value_regno)
6545 {
6546 	struct bpf_reg_state *reg = regs + regno;
6547 	struct bpf_map *map = reg->map_ptr;
6548 	struct bpf_reg_state map_reg;
6549 	enum bpf_type_flag flag = 0;
6550 	const struct btf_type *t;
6551 	const char *tname;
6552 	u32 btf_id;
6553 	int ret;
6554 
6555 	if (!btf_vmlinux) {
6556 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6557 		return -ENOTSUPP;
6558 	}
6559 
6560 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6561 		verbose(env, "map_ptr access not supported for map type %d\n",
6562 			map->map_type);
6563 		return -ENOTSUPP;
6564 	}
6565 
6566 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6567 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6568 
6569 	if (!env->allow_ptr_leaks) {
6570 		verbose(env,
6571 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6572 			tname);
6573 		return -EPERM;
6574 	}
6575 
6576 	if (off < 0) {
6577 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6578 			regno, tname, off);
6579 		return -EACCES;
6580 	}
6581 
6582 	if (atype != BPF_READ) {
6583 		verbose(env, "only read from %s is supported\n", tname);
6584 		return -EACCES;
6585 	}
6586 
6587 	/* Simulate access to a PTR_TO_BTF_ID */
6588 	memset(&map_reg, 0, sizeof(map_reg));
6589 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6590 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6591 	if (ret < 0)
6592 		return ret;
6593 
6594 	if (value_regno >= 0)
6595 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6596 
6597 	return 0;
6598 }
6599 
6600 /* Check that the stack access at the given offset is within bounds. The
6601  * maximum valid offset is -1.
6602  *
6603  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6604  * -state->allocated_stack for reads.
6605  */
6606 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6607                                           s64 off,
6608                                           struct bpf_func_state *state,
6609                                           enum bpf_access_type t)
6610 {
6611 	int min_valid_off;
6612 
6613 	if (t == BPF_WRITE || env->allow_uninit_stack)
6614 		min_valid_off = -MAX_BPF_STACK;
6615 	else
6616 		min_valid_off = -state->allocated_stack;
6617 
6618 	if (off < min_valid_off || off > -1)
6619 		return -EACCES;
6620 	return 0;
6621 }
6622 
6623 /* Check that the stack access at 'regno + off' falls within the maximum stack
6624  * bounds.
6625  *
6626  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6627  */
6628 static int check_stack_access_within_bounds(
6629 		struct bpf_verifier_env *env,
6630 		int regno, int off, int access_size,
6631 		enum bpf_access_src src, enum bpf_access_type type)
6632 {
6633 	struct bpf_reg_state *regs = cur_regs(env);
6634 	struct bpf_reg_state *reg = regs + regno;
6635 	struct bpf_func_state *state = func(env, reg);
6636 	s64 min_off, max_off;
6637 	int err;
6638 	char *err_extra;
6639 
6640 	if (src == ACCESS_HELPER)
6641 		/* We don't know if helpers are reading or writing (or both). */
6642 		err_extra = " indirect access to";
6643 	else if (type == BPF_READ)
6644 		err_extra = " read from";
6645 	else
6646 		err_extra = " write to";
6647 
6648 	if (tnum_is_const(reg->var_off)) {
6649 		min_off = (s64)reg->var_off.value + off;
6650 		max_off = min_off + access_size;
6651 	} else {
6652 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6653 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6654 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6655 				err_extra, regno);
6656 			return -EACCES;
6657 		}
6658 		min_off = reg->smin_value + off;
6659 		max_off = reg->smax_value + off + access_size;
6660 	}
6661 
6662 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6663 	if (!err && max_off > 0)
6664 		err = -EINVAL; /* out of stack access into non-negative offsets */
6665 	if (!err && access_size < 0)
6666 		/* access_size should not be negative (or overflow an int); others checks
6667 		 * along the way should have prevented such an access.
6668 		 */
6669 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6670 
6671 	if (err) {
6672 		if (tnum_is_const(reg->var_off)) {
6673 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6674 				err_extra, regno, off, access_size);
6675 		} else {
6676 			char tn_buf[48];
6677 
6678 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6679 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6680 				err_extra, regno, tn_buf, access_size);
6681 		}
6682 		return err;
6683 	}
6684 
6685 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6686 }
6687 
6688 /* check whether memory at (regno + off) is accessible for t = (read | write)
6689  * if t==write, value_regno is a register which value is stored into memory
6690  * if t==read, value_regno is a register which will receive the value from memory
6691  * if t==write && value_regno==-1, some unknown value is stored into memory
6692  * if t==read && value_regno==-1, don't care what we read from memory
6693  */
6694 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6695 			    int off, int bpf_size, enum bpf_access_type t,
6696 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6697 {
6698 	struct bpf_reg_state *regs = cur_regs(env);
6699 	struct bpf_reg_state *reg = regs + regno;
6700 	int size, err = 0;
6701 
6702 	size = bpf_size_to_bytes(bpf_size);
6703 	if (size < 0)
6704 		return size;
6705 
6706 	/* alignment checks will add in reg->off themselves */
6707 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6708 	if (err)
6709 		return err;
6710 
6711 	/* for access checks, reg->off is just part of off */
6712 	off += reg->off;
6713 
6714 	if (reg->type == PTR_TO_MAP_KEY) {
6715 		if (t == BPF_WRITE) {
6716 			verbose(env, "write to change key R%d not allowed\n", regno);
6717 			return -EACCES;
6718 		}
6719 
6720 		err = check_mem_region_access(env, regno, off, size,
6721 					      reg->map_ptr->key_size, false);
6722 		if (err)
6723 			return err;
6724 		if (value_regno >= 0)
6725 			mark_reg_unknown(env, regs, value_regno);
6726 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6727 		struct btf_field *kptr_field = NULL;
6728 
6729 		if (t == BPF_WRITE && value_regno >= 0 &&
6730 		    is_pointer_value(env, value_regno)) {
6731 			verbose(env, "R%d leaks addr into map\n", value_regno);
6732 			return -EACCES;
6733 		}
6734 		err = check_map_access_type(env, regno, off, size, t);
6735 		if (err)
6736 			return err;
6737 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6738 		if (err)
6739 			return err;
6740 		if (tnum_is_const(reg->var_off))
6741 			kptr_field = btf_record_find(reg->map_ptr->record,
6742 						     off + reg->var_off.value, BPF_KPTR);
6743 		if (kptr_field) {
6744 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6745 		} else if (t == BPF_READ && value_regno >= 0) {
6746 			struct bpf_map *map = reg->map_ptr;
6747 
6748 			/* if map is read-only, track its contents as scalars */
6749 			if (tnum_is_const(reg->var_off) &&
6750 			    bpf_map_is_rdonly(map) &&
6751 			    map->ops->map_direct_value_addr) {
6752 				int map_off = off + reg->var_off.value;
6753 				u64 val = 0;
6754 
6755 				err = bpf_map_direct_read(map, map_off, size,
6756 							  &val, is_ldsx);
6757 				if (err)
6758 					return err;
6759 
6760 				regs[value_regno].type = SCALAR_VALUE;
6761 				__mark_reg_known(&regs[value_regno], val);
6762 			} else {
6763 				mark_reg_unknown(env, regs, value_regno);
6764 			}
6765 		}
6766 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6767 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6768 
6769 		if (type_may_be_null(reg->type)) {
6770 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6771 				reg_type_str(env, reg->type));
6772 			return -EACCES;
6773 		}
6774 
6775 		if (t == BPF_WRITE && rdonly_mem) {
6776 			verbose(env, "R%d cannot write into %s\n",
6777 				regno, reg_type_str(env, reg->type));
6778 			return -EACCES;
6779 		}
6780 
6781 		if (t == BPF_WRITE && value_regno >= 0 &&
6782 		    is_pointer_value(env, value_regno)) {
6783 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6784 			return -EACCES;
6785 		}
6786 
6787 		err = check_mem_region_access(env, regno, off, size,
6788 					      reg->mem_size, false);
6789 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6790 			mark_reg_unknown(env, regs, value_regno);
6791 	} else if (reg->type == PTR_TO_CTX) {
6792 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6793 		struct btf *btf = NULL;
6794 		u32 btf_id = 0;
6795 
6796 		if (t == BPF_WRITE && value_regno >= 0 &&
6797 		    is_pointer_value(env, value_regno)) {
6798 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6799 			return -EACCES;
6800 		}
6801 
6802 		err = check_ptr_off_reg(env, reg, regno);
6803 		if (err < 0)
6804 			return err;
6805 
6806 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6807 				       &btf_id);
6808 		if (err)
6809 			verbose_linfo(env, insn_idx, "; ");
6810 		if (!err && t == BPF_READ && value_regno >= 0) {
6811 			/* ctx access returns either a scalar, or a
6812 			 * PTR_TO_PACKET[_META,_END]. In the latter
6813 			 * case, we know the offset is zero.
6814 			 */
6815 			if (reg_type == SCALAR_VALUE) {
6816 				mark_reg_unknown(env, regs, value_regno);
6817 			} else {
6818 				mark_reg_known_zero(env, regs,
6819 						    value_regno);
6820 				if (type_may_be_null(reg_type))
6821 					regs[value_regno].id = ++env->id_gen;
6822 				/* A load of ctx field could have different
6823 				 * actual load size with the one encoded in the
6824 				 * insn. When the dst is PTR, it is for sure not
6825 				 * a sub-register.
6826 				 */
6827 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6828 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6829 					regs[value_regno].btf = btf;
6830 					regs[value_regno].btf_id = btf_id;
6831 				}
6832 			}
6833 			regs[value_regno].type = reg_type;
6834 		}
6835 
6836 	} else if (reg->type == PTR_TO_STACK) {
6837 		/* Basic bounds checks. */
6838 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6839 		if (err)
6840 			return err;
6841 
6842 		if (t == BPF_READ)
6843 			err = check_stack_read(env, regno, off, size,
6844 					       value_regno);
6845 		else
6846 			err = check_stack_write(env, regno, off, size,
6847 						value_regno, insn_idx);
6848 	} else if (reg_is_pkt_pointer(reg)) {
6849 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6850 			verbose(env, "cannot write into packet\n");
6851 			return -EACCES;
6852 		}
6853 		if (t == BPF_WRITE && value_regno >= 0 &&
6854 		    is_pointer_value(env, value_regno)) {
6855 			verbose(env, "R%d leaks addr into packet\n",
6856 				value_regno);
6857 			return -EACCES;
6858 		}
6859 		err = check_packet_access(env, regno, off, size, false);
6860 		if (!err && t == BPF_READ && value_regno >= 0)
6861 			mark_reg_unknown(env, regs, value_regno);
6862 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6863 		if (t == BPF_WRITE && value_regno >= 0 &&
6864 		    is_pointer_value(env, value_regno)) {
6865 			verbose(env, "R%d leaks addr into flow keys\n",
6866 				value_regno);
6867 			return -EACCES;
6868 		}
6869 
6870 		err = check_flow_keys_access(env, off, size);
6871 		if (!err && t == BPF_READ && value_regno >= 0)
6872 			mark_reg_unknown(env, regs, value_regno);
6873 	} else if (type_is_sk_pointer(reg->type)) {
6874 		if (t == BPF_WRITE) {
6875 			verbose(env, "R%d cannot write into %s\n",
6876 				regno, reg_type_str(env, reg->type));
6877 			return -EACCES;
6878 		}
6879 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6880 		if (!err && value_regno >= 0)
6881 			mark_reg_unknown(env, regs, value_regno);
6882 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6883 		err = check_tp_buffer_access(env, reg, regno, off, size);
6884 		if (!err && t == BPF_READ && value_regno >= 0)
6885 			mark_reg_unknown(env, regs, value_regno);
6886 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6887 		   !type_may_be_null(reg->type)) {
6888 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6889 					      value_regno);
6890 	} else if (reg->type == CONST_PTR_TO_MAP) {
6891 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6892 					      value_regno);
6893 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6894 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6895 		u32 *max_access;
6896 
6897 		if (rdonly_mem) {
6898 			if (t == BPF_WRITE) {
6899 				verbose(env, "R%d cannot write into %s\n",
6900 					regno, reg_type_str(env, reg->type));
6901 				return -EACCES;
6902 			}
6903 			max_access = &env->prog->aux->max_rdonly_access;
6904 		} else {
6905 			max_access = &env->prog->aux->max_rdwr_access;
6906 		}
6907 
6908 		err = check_buffer_access(env, reg, regno, off, size, false,
6909 					  max_access);
6910 
6911 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6912 			mark_reg_unknown(env, regs, value_regno);
6913 	} else {
6914 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6915 			reg_type_str(env, reg->type));
6916 		return -EACCES;
6917 	}
6918 
6919 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6920 	    regs[value_regno].type == SCALAR_VALUE) {
6921 		if (!is_ldsx)
6922 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6923 			coerce_reg_to_size(&regs[value_regno], size);
6924 		else
6925 			coerce_reg_to_size_sx(&regs[value_regno], size);
6926 	}
6927 	return err;
6928 }
6929 
6930 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6931 {
6932 	int load_reg;
6933 	int err;
6934 
6935 	switch (insn->imm) {
6936 	case BPF_ADD:
6937 	case BPF_ADD | BPF_FETCH:
6938 	case BPF_AND:
6939 	case BPF_AND | BPF_FETCH:
6940 	case BPF_OR:
6941 	case BPF_OR | BPF_FETCH:
6942 	case BPF_XOR:
6943 	case BPF_XOR | BPF_FETCH:
6944 	case BPF_XCHG:
6945 	case BPF_CMPXCHG:
6946 		break;
6947 	default:
6948 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6949 		return -EINVAL;
6950 	}
6951 
6952 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6953 		verbose(env, "invalid atomic operand size\n");
6954 		return -EINVAL;
6955 	}
6956 
6957 	/* check src1 operand */
6958 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6959 	if (err)
6960 		return err;
6961 
6962 	/* check src2 operand */
6963 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6964 	if (err)
6965 		return err;
6966 
6967 	if (insn->imm == BPF_CMPXCHG) {
6968 		/* Check comparison of R0 with memory location */
6969 		const u32 aux_reg = BPF_REG_0;
6970 
6971 		err = check_reg_arg(env, aux_reg, SRC_OP);
6972 		if (err)
6973 			return err;
6974 
6975 		if (is_pointer_value(env, aux_reg)) {
6976 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6977 			return -EACCES;
6978 		}
6979 	}
6980 
6981 	if (is_pointer_value(env, insn->src_reg)) {
6982 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6983 		return -EACCES;
6984 	}
6985 
6986 	if (is_ctx_reg(env, insn->dst_reg) ||
6987 	    is_pkt_reg(env, insn->dst_reg) ||
6988 	    is_flow_key_reg(env, insn->dst_reg) ||
6989 	    is_sk_reg(env, insn->dst_reg)) {
6990 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6991 			insn->dst_reg,
6992 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6993 		return -EACCES;
6994 	}
6995 
6996 	if (insn->imm & BPF_FETCH) {
6997 		if (insn->imm == BPF_CMPXCHG)
6998 			load_reg = BPF_REG_0;
6999 		else
7000 			load_reg = insn->src_reg;
7001 
7002 		/* check and record load of old value */
7003 		err = check_reg_arg(env, load_reg, DST_OP);
7004 		if (err)
7005 			return err;
7006 	} else {
7007 		/* This instruction accesses a memory location but doesn't
7008 		 * actually load it into a register.
7009 		 */
7010 		load_reg = -1;
7011 	}
7012 
7013 	/* Check whether we can read the memory, with second call for fetch
7014 	 * case to simulate the register fill.
7015 	 */
7016 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7017 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7018 	if (!err && load_reg >= 0)
7019 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7020 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7021 				       true, false);
7022 	if (err)
7023 		return err;
7024 
7025 	/* Check whether we can write into the same memory. */
7026 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7027 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7028 	if (err)
7029 		return err;
7030 
7031 	return 0;
7032 }
7033 
7034 /* When register 'regno' is used to read the stack (either directly or through
7035  * a helper function) make sure that it's within stack boundary and, depending
7036  * on the access type and privileges, that all elements of the stack are
7037  * initialized.
7038  *
7039  * 'off' includes 'regno->off', but not its dynamic part (if any).
7040  *
7041  * All registers that have been spilled on the stack in the slots within the
7042  * read offsets are marked as read.
7043  */
7044 static int check_stack_range_initialized(
7045 		struct bpf_verifier_env *env, int regno, int off,
7046 		int access_size, bool zero_size_allowed,
7047 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7048 {
7049 	struct bpf_reg_state *reg = reg_state(env, regno);
7050 	struct bpf_func_state *state = func(env, reg);
7051 	int err, min_off, max_off, i, j, slot, spi;
7052 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7053 	enum bpf_access_type bounds_check_type;
7054 	/* Some accesses can write anything into the stack, others are
7055 	 * read-only.
7056 	 */
7057 	bool clobber = false;
7058 
7059 	if (access_size == 0 && !zero_size_allowed) {
7060 		verbose(env, "invalid zero-sized read\n");
7061 		return -EACCES;
7062 	}
7063 
7064 	if (type == ACCESS_HELPER) {
7065 		/* The bounds checks for writes are more permissive than for
7066 		 * reads. However, if raw_mode is not set, we'll do extra
7067 		 * checks below.
7068 		 */
7069 		bounds_check_type = BPF_WRITE;
7070 		clobber = true;
7071 	} else {
7072 		bounds_check_type = BPF_READ;
7073 	}
7074 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7075 					       type, bounds_check_type);
7076 	if (err)
7077 		return err;
7078 
7079 
7080 	if (tnum_is_const(reg->var_off)) {
7081 		min_off = max_off = reg->var_off.value + off;
7082 	} else {
7083 		/* Variable offset is prohibited for unprivileged mode for
7084 		 * simplicity since it requires corresponding support in
7085 		 * Spectre masking for stack ALU.
7086 		 * See also retrieve_ptr_limit().
7087 		 */
7088 		if (!env->bypass_spec_v1) {
7089 			char tn_buf[48];
7090 
7091 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7092 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7093 				regno, err_extra, tn_buf);
7094 			return -EACCES;
7095 		}
7096 		/* Only initialized buffer on stack is allowed to be accessed
7097 		 * with variable offset. With uninitialized buffer it's hard to
7098 		 * guarantee that whole memory is marked as initialized on
7099 		 * helper return since specific bounds are unknown what may
7100 		 * cause uninitialized stack leaking.
7101 		 */
7102 		if (meta && meta->raw_mode)
7103 			meta = NULL;
7104 
7105 		min_off = reg->smin_value + off;
7106 		max_off = reg->smax_value + off;
7107 	}
7108 
7109 	if (meta && meta->raw_mode) {
7110 		/* Ensure we won't be overwriting dynptrs when simulating byte
7111 		 * by byte access in check_helper_call using meta.access_size.
7112 		 * This would be a problem if we have a helper in the future
7113 		 * which takes:
7114 		 *
7115 		 *	helper(uninit_mem, len, dynptr)
7116 		 *
7117 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7118 		 * may end up writing to dynptr itself when touching memory from
7119 		 * arg 1. This can be relaxed on a case by case basis for known
7120 		 * safe cases, but reject due to the possibilitiy of aliasing by
7121 		 * default.
7122 		 */
7123 		for (i = min_off; i < max_off + access_size; i++) {
7124 			int stack_off = -i - 1;
7125 
7126 			spi = __get_spi(i);
7127 			/* raw_mode may write past allocated_stack */
7128 			if (state->allocated_stack <= stack_off)
7129 				continue;
7130 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7131 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7132 				return -EACCES;
7133 			}
7134 		}
7135 		meta->access_size = access_size;
7136 		meta->regno = regno;
7137 		return 0;
7138 	}
7139 
7140 	for (i = min_off; i < max_off + access_size; i++) {
7141 		u8 *stype;
7142 
7143 		slot = -i - 1;
7144 		spi = slot / BPF_REG_SIZE;
7145 		if (state->allocated_stack <= slot) {
7146 			verbose(env, "verifier bug: allocated_stack too small");
7147 			return -EFAULT;
7148 		}
7149 
7150 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7151 		if (*stype == STACK_MISC)
7152 			goto mark;
7153 		if ((*stype == STACK_ZERO) ||
7154 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7155 			if (clobber) {
7156 				/* helper can write anything into the stack */
7157 				*stype = STACK_MISC;
7158 			}
7159 			goto mark;
7160 		}
7161 
7162 		if (is_spilled_reg(&state->stack[spi]) &&
7163 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7164 		     env->allow_ptr_leaks)) {
7165 			if (clobber) {
7166 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7167 				for (j = 0; j < BPF_REG_SIZE; j++)
7168 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7169 			}
7170 			goto mark;
7171 		}
7172 
7173 		if (tnum_is_const(reg->var_off)) {
7174 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7175 				err_extra, regno, min_off, i - min_off, access_size);
7176 		} else {
7177 			char tn_buf[48];
7178 
7179 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7180 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7181 				err_extra, regno, tn_buf, i - min_off, access_size);
7182 		}
7183 		return -EACCES;
7184 mark:
7185 		/* reading any byte out of 8-byte 'spill_slot' will cause
7186 		 * the whole slot to be marked as 'read'
7187 		 */
7188 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7189 			      state->stack[spi].spilled_ptr.parent,
7190 			      REG_LIVE_READ64);
7191 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7192 		 * be sure that whether stack slot is written to or not. Hence,
7193 		 * we must still conservatively propagate reads upwards even if
7194 		 * helper may write to the entire memory range.
7195 		 */
7196 	}
7197 	return 0;
7198 }
7199 
7200 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7201 				   int access_size, bool zero_size_allowed,
7202 				   struct bpf_call_arg_meta *meta)
7203 {
7204 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7205 	u32 *max_access;
7206 
7207 	switch (base_type(reg->type)) {
7208 	case PTR_TO_PACKET:
7209 	case PTR_TO_PACKET_META:
7210 		return check_packet_access(env, regno, reg->off, access_size,
7211 					   zero_size_allowed);
7212 	case PTR_TO_MAP_KEY:
7213 		if (meta && meta->raw_mode) {
7214 			verbose(env, "R%d cannot write into %s\n", regno,
7215 				reg_type_str(env, reg->type));
7216 			return -EACCES;
7217 		}
7218 		return check_mem_region_access(env, regno, reg->off, access_size,
7219 					       reg->map_ptr->key_size, false);
7220 	case PTR_TO_MAP_VALUE:
7221 		if (check_map_access_type(env, regno, reg->off, access_size,
7222 					  meta && meta->raw_mode ? BPF_WRITE :
7223 					  BPF_READ))
7224 			return -EACCES;
7225 		return check_map_access(env, regno, reg->off, access_size,
7226 					zero_size_allowed, ACCESS_HELPER);
7227 	case PTR_TO_MEM:
7228 		if (type_is_rdonly_mem(reg->type)) {
7229 			if (meta && meta->raw_mode) {
7230 				verbose(env, "R%d cannot write into %s\n", regno,
7231 					reg_type_str(env, reg->type));
7232 				return -EACCES;
7233 			}
7234 		}
7235 		return check_mem_region_access(env, regno, reg->off,
7236 					       access_size, reg->mem_size,
7237 					       zero_size_allowed);
7238 	case PTR_TO_BUF:
7239 		if (type_is_rdonly_mem(reg->type)) {
7240 			if (meta && meta->raw_mode) {
7241 				verbose(env, "R%d cannot write into %s\n", regno,
7242 					reg_type_str(env, reg->type));
7243 				return -EACCES;
7244 			}
7245 
7246 			max_access = &env->prog->aux->max_rdonly_access;
7247 		} else {
7248 			max_access = &env->prog->aux->max_rdwr_access;
7249 		}
7250 		return check_buffer_access(env, reg, regno, reg->off,
7251 					   access_size, zero_size_allowed,
7252 					   max_access);
7253 	case PTR_TO_STACK:
7254 		return check_stack_range_initialized(
7255 				env,
7256 				regno, reg->off, access_size,
7257 				zero_size_allowed, ACCESS_HELPER, meta);
7258 	case PTR_TO_BTF_ID:
7259 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7260 					       access_size, BPF_READ, -1);
7261 	case PTR_TO_CTX:
7262 		/* in case the function doesn't know how to access the context,
7263 		 * (because we are in a program of type SYSCALL for example), we
7264 		 * can not statically check its size.
7265 		 * Dynamically check it now.
7266 		 */
7267 		if (!env->ops->convert_ctx_access) {
7268 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7269 			int offset = access_size - 1;
7270 
7271 			/* Allow zero-byte read from PTR_TO_CTX */
7272 			if (access_size == 0)
7273 				return zero_size_allowed ? 0 : -EACCES;
7274 
7275 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7276 						atype, -1, false, false);
7277 		}
7278 
7279 		fallthrough;
7280 	default: /* scalar_value or invalid ptr */
7281 		/* Allow zero-byte read from NULL, regardless of pointer type */
7282 		if (zero_size_allowed && access_size == 0 &&
7283 		    register_is_null(reg))
7284 			return 0;
7285 
7286 		verbose(env, "R%d type=%s ", regno,
7287 			reg_type_str(env, reg->type));
7288 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7289 		return -EACCES;
7290 	}
7291 }
7292 
7293 static int check_mem_size_reg(struct bpf_verifier_env *env,
7294 			      struct bpf_reg_state *reg, u32 regno,
7295 			      bool zero_size_allowed,
7296 			      struct bpf_call_arg_meta *meta)
7297 {
7298 	int err;
7299 
7300 	/* This is used to refine r0 return value bounds for helpers
7301 	 * that enforce this value as an upper bound on return values.
7302 	 * See do_refine_retval_range() for helpers that can refine
7303 	 * the return value. C type of helper is u32 so we pull register
7304 	 * bound from umax_value however, if negative verifier errors
7305 	 * out. Only upper bounds can be learned because retval is an
7306 	 * int type and negative retvals are allowed.
7307 	 */
7308 	meta->msize_max_value = reg->umax_value;
7309 
7310 	/* The register is SCALAR_VALUE; the access check
7311 	 * happens using its boundaries.
7312 	 */
7313 	if (!tnum_is_const(reg->var_off))
7314 		/* For unprivileged variable accesses, disable raw
7315 		 * mode so that the program is required to
7316 		 * initialize all the memory that the helper could
7317 		 * just partially fill up.
7318 		 */
7319 		meta = NULL;
7320 
7321 	if (reg->smin_value < 0) {
7322 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7323 			regno);
7324 		return -EACCES;
7325 	}
7326 
7327 	if (reg->umin_value == 0) {
7328 		err = check_helper_mem_access(env, regno - 1, 0,
7329 					      zero_size_allowed,
7330 					      meta);
7331 		if (err)
7332 			return err;
7333 	}
7334 
7335 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7336 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7337 			regno);
7338 		return -EACCES;
7339 	}
7340 	err = check_helper_mem_access(env, regno - 1,
7341 				      reg->umax_value,
7342 				      zero_size_allowed, meta);
7343 	if (!err)
7344 		err = mark_chain_precision(env, regno);
7345 	return err;
7346 }
7347 
7348 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7349 		   u32 regno, u32 mem_size)
7350 {
7351 	bool may_be_null = type_may_be_null(reg->type);
7352 	struct bpf_reg_state saved_reg;
7353 	struct bpf_call_arg_meta meta;
7354 	int err;
7355 
7356 	if (register_is_null(reg))
7357 		return 0;
7358 
7359 	memset(&meta, 0, sizeof(meta));
7360 	/* Assuming that the register contains a value check if the memory
7361 	 * access is safe. Temporarily save and restore the register's state as
7362 	 * the conversion shouldn't be visible to a caller.
7363 	 */
7364 	if (may_be_null) {
7365 		saved_reg = *reg;
7366 		mark_ptr_not_null_reg(reg);
7367 	}
7368 
7369 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7370 	/* Check access for BPF_WRITE */
7371 	meta.raw_mode = true;
7372 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7373 
7374 	if (may_be_null)
7375 		*reg = saved_reg;
7376 
7377 	return err;
7378 }
7379 
7380 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7381 				    u32 regno)
7382 {
7383 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7384 	bool may_be_null = type_may_be_null(mem_reg->type);
7385 	struct bpf_reg_state saved_reg;
7386 	struct bpf_call_arg_meta meta;
7387 	int err;
7388 
7389 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7390 
7391 	memset(&meta, 0, sizeof(meta));
7392 
7393 	if (may_be_null) {
7394 		saved_reg = *mem_reg;
7395 		mark_ptr_not_null_reg(mem_reg);
7396 	}
7397 
7398 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7399 	/* Check access for BPF_WRITE */
7400 	meta.raw_mode = true;
7401 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7402 
7403 	if (may_be_null)
7404 		*mem_reg = saved_reg;
7405 	return err;
7406 }
7407 
7408 /* Implementation details:
7409  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7410  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7411  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7412  * Two separate bpf_obj_new will also have different reg->id.
7413  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7414  * clears reg->id after value_or_null->value transition, since the verifier only
7415  * cares about the range of access to valid map value pointer and doesn't care
7416  * about actual address of the map element.
7417  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7418  * reg->id > 0 after value_or_null->value transition. By doing so
7419  * two bpf_map_lookups will be considered two different pointers that
7420  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7421  * returned from bpf_obj_new.
7422  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7423  * dead-locks.
7424  * Since only one bpf_spin_lock is allowed the checks are simpler than
7425  * reg_is_refcounted() logic. The verifier needs to remember only
7426  * one spin_lock instead of array of acquired_refs.
7427  * cur_state->active_lock remembers which map value element or allocated
7428  * object got locked and clears it after bpf_spin_unlock.
7429  */
7430 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7431 			     bool is_lock)
7432 {
7433 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7434 	struct bpf_verifier_state *cur = env->cur_state;
7435 	bool is_const = tnum_is_const(reg->var_off);
7436 	u64 val = reg->var_off.value;
7437 	struct bpf_map *map = NULL;
7438 	struct btf *btf = NULL;
7439 	struct btf_record *rec;
7440 
7441 	if (!is_const) {
7442 		verbose(env,
7443 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7444 			regno);
7445 		return -EINVAL;
7446 	}
7447 	if (reg->type == PTR_TO_MAP_VALUE) {
7448 		map = reg->map_ptr;
7449 		if (!map->btf) {
7450 			verbose(env,
7451 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7452 				map->name);
7453 			return -EINVAL;
7454 		}
7455 	} else {
7456 		btf = reg->btf;
7457 	}
7458 
7459 	rec = reg_btf_record(reg);
7460 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7461 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7462 			map ? map->name : "kptr");
7463 		return -EINVAL;
7464 	}
7465 	if (rec->spin_lock_off != val + reg->off) {
7466 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7467 			val + reg->off, rec->spin_lock_off);
7468 		return -EINVAL;
7469 	}
7470 	if (is_lock) {
7471 		if (cur->active_lock.ptr) {
7472 			verbose(env,
7473 				"Locking two bpf_spin_locks are not allowed\n");
7474 			return -EINVAL;
7475 		}
7476 		if (map)
7477 			cur->active_lock.ptr = map;
7478 		else
7479 			cur->active_lock.ptr = btf;
7480 		cur->active_lock.id = reg->id;
7481 	} else {
7482 		void *ptr;
7483 
7484 		if (map)
7485 			ptr = map;
7486 		else
7487 			ptr = btf;
7488 
7489 		if (!cur->active_lock.ptr) {
7490 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7491 			return -EINVAL;
7492 		}
7493 		if (cur->active_lock.ptr != ptr ||
7494 		    cur->active_lock.id != reg->id) {
7495 			verbose(env, "bpf_spin_unlock of different lock\n");
7496 			return -EINVAL;
7497 		}
7498 
7499 		invalidate_non_owning_refs(env);
7500 
7501 		cur->active_lock.ptr = NULL;
7502 		cur->active_lock.id = 0;
7503 	}
7504 	return 0;
7505 }
7506 
7507 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7508 			      struct bpf_call_arg_meta *meta)
7509 {
7510 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7511 	bool is_const = tnum_is_const(reg->var_off);
7512 	struct bpf_map *map = reg->map_ptr;
7513 	u64 val = reg->var_off.value;
7514 
7515 	if (!is_const) {
7516 		verbose(env,
7517 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7518 			regno);
7519 		return -EINVAL;
7520 	}
7521 	if (!map->btf) {
7522 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7523 			map->name);
7524 		return -EINVAL;
7525 	}
7526 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7527 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7528 		return -EINVAL;
7529 	}
7530 	if (map->record->timer_off != val + reg->off) {
7531 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7532 			val + reg->off, map->record->timer_off);
7533 		return -EINVAL;
7534 	}
7535 	if (meta->map_ptr) {
7536 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7537 		return -EFAULT;
7538 	}
7539 	meta->map_uid = reg->map_uid;
7540 	meta->map_ptr = map;
7541 	return 0;
7542 }
7543 
7544 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7545 			     struct bpf_call_arg_meta *meta)
7546 {
7547 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7548 	struct bpf_map *map_ptr = reg->map_ptr;
7549 	struct btf_field *kptr_field;
7550 	u32 kptr_off;
7551 
7552 	if (!tnum_is_const(reg->var_off)) {
7553 		verbose(env,
7554 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7555 			regno);
7556 		return -EINVAL;
7557 	}
7558 	if (!map_ptr->btf) {
7559 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7560 			map_ptr->name);
7561 		return -EINVAL;
7562 	}
7563 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7564 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7565 		return -EINVAL;
7566 	}
7567 
7568 	meta->map_ptr = map_ptr;
7569 	kptr_off = reg->off + reg->var_off.value;
7570 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7571 	if (!kptr_field) {
7572 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7573 		return -EACCES;
7574 	}
7575 	if (kptr_field->type != BPF_KPTR_REF) {
7576 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7577 		return -EACCES;
7578 	}
7579 	meta->kptr_field = kptr_field;
7580 	return 0;
7581 }
7582 
7583 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7584  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7585  *
7586  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7587  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7588  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7589  *
7590  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7591  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7592  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7593  * mutate the view of the dynptr and also possibly destroy it. In the latter
7594  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7595  * memory that dynptr points to.
7596  *
7597  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7598  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7599  * readonly dynptr view yet, hence only the first case is tracked and checked.
7600  *
7601  * This is consistent with how C applies the const modifier to a struct object,
7602  * where the pointer itself inside bpf_dynptr becomes const but not what it
7603  * points to.
7604  *
7605  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7606  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7607  */
7608 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7609 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7610 {
7611 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7612 	int err;
7613 
7614 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7615 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7616 	 */
7617 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7618 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7619 		return -EFAULT;
7620 	}
7621 
7622 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7623 	 *		 constructing a mutable bpf_dynptr object.
7624 	 *
7625 	 *		 Currently, this is only possible with PTR_TO_STACK
7626 	 *		 pointing to a region of at least 16 bytes which doesn't
7627 	 *		 contain an existing bpf_dynptr.
7628 	 *
7629 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7630 	 *		 mutated or destroyed. However, the memory it points to
7631 	 *		 may be mutated.
7632 	 *
7633 	 *  None       - Points to a initialized dynptr that can be mutated and
7634 	 *		 destroyed, including mutation of the memory it points
7635 	 *		 to.
7636 	 */
7637 	if (arg_type & MEM_UNINIT) {
7638 		int i;
7639 
7640 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7641 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7642 			return -EINVAL;
7643 		}
7644 
7645 		/* we write BPF_DW bits (8 bytes) at a time */
7646 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7647 			err = check_mem_access(env, insn_idx, regno,
7648 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7649 			if (err)
7650 				return err;
7651 		}
7652 
7653 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7654 	} else /* MEM_RDONLY and None case from above */ {
7655 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7656 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7657 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7658 			return -EINVAL;
7659 		}
7660 
7661 		if (!is_dynptr_reg_valid_init(env, reg)) {
7662 			verbose(env,
7663 				"Expected an initialized dynptr as arg #%d\n",
7664 				regno);
7665 			return -EINVAL;
7666 		}
7667 
7668 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7669 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7670 			verbose(env,
7671 				"Expected a dynptr of type %s as arg #%d\n",
7672 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7673 			return -EINVAL;
7674 		}
7675 
7676 		err = mark_dynptr_read(env, reg);
7677 	}
7678 	return err;
7679 }
7680 
7681 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7682 {
7683 	struct bpf_func_state *state = func(env, reg);
7684 
7685 	return state->stack[spi].spilled_ptr.ref_obj_id;
7686 }
7687 
7688 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7689 {
7690 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7691 }
7692 
7693 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7694 {
7695 	return meta->kfunc_flags & KF_ITER_NEW;
7696 }
7697 
7698 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7699 {
7700 	return meta->kfunc_flags & KF_ITER_NEXT;
7701 }
7702 
7703 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7704 {
7705 	return meta->kfunc_flags & KF_ITER_DESTROY;
7706 }
7707 
7708 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7709 {
7710 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7711 	 * kfunc is iter state pointer
7712 	 */
7713 	return arg == 0 && is_iter_kfunc(meta);
7714 }
7715 
7716 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7717 			    struct bpf_kfunc_call_arg_meta *meta)
7718 {
7719 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7720 	const struct btf_type *t;
7721 	const struct btf_param *arg;
7722 	int spi, err, i, nr_slots;
7723 	u32 btf_id;
7724 
7725 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7726 	arg = &btf_params(meta->func_proto)[0];
7727 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7728 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7729 	nr_slots = t->size / BPF_REG_SIZE;
7730 
7731 	if (is_iter_new_kfunc(meta)) {
7732 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7733 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7734 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7735 				iter_type_str(meta->btf, btf_id), regno);
7736 			return -EINVAL;
7737 		}
7738 
7739 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7740 			err = check_mem_access(env, insn_idx, regno,
7741 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7742 			if (err)
7743 				return err;
7744 		}
7745 
7746 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7747 		if (err)
7748 			return err;
7749 	} else {
7750 		/* iter_next() or iter_destroy() expect initialized iter state*/
7751 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7752 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7753 				iter_type_str(meta->btf, btf_id), regno);
7754 			return -EINVAL;
7755 		}
7756 
7757 		spi = iter_get_spi(env, reg, nr_slots);
7758 		if (spi < 0)
7759 			return spi;
7760 
7761 		err = mark_iter_read(env, reg, spi, nr_slots);
7762 		if (err)
7763 			return err;
7764 
7765 		/* remember meta->iter info for process_iter_next_call() */
7766 		meta->iter.spi = spi;
7767 		meta->iter.frameno = reg->frameno;
7768 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7769 
7770 		if (is_iter_destroy_kfunc(meta)) {
7771 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7772 			if (err)
7773 				return err;
7774 		}
7775 	}
7776 
7777 	return 0;
7778 }
7779 
7780 /* Look for a previous loop entry at insn_idx: nearest parent state
7781  * stopped at insn_idx with callsites matching those in cur->frame.
7782  */
7783 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7784 						  struct bpf_verifier_state *cur,
7785 						  int insn_idx)
7786 {
7787 	struct bpf_verifier_state_list *sl;
7788 	struct bpf_verifier_state *st;
7789 
7790 	/* Explored states are pushed in stack order, most recent states come first */
7791 	sl = *explored_state(env, insn_idx);
7792 	for (; sl; sl = sl->next) {
7793 		/* If st->branches != 0 state is a part of current DFS verification path,
7794 		 * hence cur & st for a loop.
7795 		 */
7796 		st = &sl->state;
7797 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7798 		    st->dfs_depth < cur->dfs_depth)
7799 			return st;
7800 	}
7801 
7802 	return NULL;
7803 }
7804 
7805 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7806 static bool regs_exact(const struct bpf_reg_state *rold,
7807 		       const struct bpf_reg_state *rcur,
7808 		       struct bpf_idmap *idmap);
7809 
7810 static void maybe_widen_reg(struct bpf_verifier_env *env,
7811 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7812 			    struct bpf_idmap *idmap)
7813 {
7814 	if (rold->type != SCALAR_VALUE)
7815 		return;
7816 	if (rold->type != rcur->type)
7817 		return;
7818 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7819 		return;
7820 	__mark_reg_unknown(env, rcur);
7821 }
7822 
7823 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7824 				   struct bpf_verifier_state *old,
7825 				   struct bpf_verifier_state *cur)
7826 {
7827 	struct bpf_func_state *fold, *fcur;
7828 	int i, fr;
7829 
7830 	reset_idmap_scratch(env);
7831 	for (fr = old->curframe; fr >= 0; fr--) {
7832 		fold = old->frame[fr];
7833 		fcur = cur->frame[fr];
7834 
7835 		for (i = 0; i < MAX_BPF_REG; i++)
7836 			maybe_widen_reg(env,
7837 					&fold->regs[i],
7838 					&fcur->regs[i],
7839 					&env->idmap_scratch);
7840 
7841 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7842 			if (!is_spilled_reg(&fold->stack[i]) ||
7843 			    !is_spilled_reg(&fcur->stack[i]))
7844 				continue;
7845 
7846 			maybe_widen_reg(env,
7847 					&fold->stack[i].spilled_ptr,
7848 					&fcur->stack[i].spilled_ptr,
7849 					&env->idmap_scratch);
7850 		}
7851 	}
7852 	return 0;
7853 }
7854 
7855 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7856 						 struct bpf_kfunc_call_arg_meta *meta)
7857 {
7858 	int iter_frameno = meta->iter.frameno;
7859 	int iter_spi = meta->iter.spi;
7860 
7861 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7862 }
7863 
7864 /* process_iter_next_call() is called when verifier gets to iterator's next
7865  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7866  * to it as just "iter_next()" in comments below.
7867  *
7868  * BPF verifier relies on a crucial contract for any iter_next()
7869  * implementation: it should *eventually* return NULL, and once that happens
7870  * it should keep returning NULL. That is, once iterator exhausts elements to
7871  * iterate, it should never reset or spuriously return new elements.
7872  *
7873  * With the assumption of such contract, process_iter_next_call() simulates
7874  * a fork in the verifier state to validate loop logic correctness and safety
7875  * without having to simulate infinite amount of iterations.
7876  *
7877  * In current state, we first assume that iter_next() returned NULL and
7878  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7879  * conditions we should not form an infinite loop and should eventually reach
7880  * exit.
7881  *
7882  * Besides that, we also fork current state and enqueue it for later
7883  * verification. In a forked state we keep iterator state as ACTIVE
7884  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7885  * also bump iteration depth to prevent erroneous infinite loop detection
7886  * later on (see iter_active_depths_differ() comment for details). In this
7887  * state we assume that we'll eventually loop back to another iter_next()
7888  * calls (it could be in exactly same location or in some other instruction,
7889  * it doesn't matter, we don't make any unnecessary assumptions about this,
7890  * everything revolves around iterator state in a stack slot, not which
7891  * instruction is calling iter_next()). When that happens, we either will come
7892  * to iter_next() with equivalent state and can conclude that next iteration
7893  * will proceed in exactly the same way as we just verified, so it's safe to
7894  * assume that loop converges. If not, we'll go on another iteration
7895  * simulation with a different input state, until all possible starting states
7896  * are validated or we reach maximum number of instructions limit.
7897  *
7898  * This way, we will either exhaustively discover all possible input states
7899  * that iterator loop can start with and eventually will converge, or we'll
7900  * effectively regress into bounded loop simulation logic and either reach
7901  * maximum number of instructions if loop is not provably convergent, or there
7902  * is some statically known limit on number of iterations (e.g., if there is
7903  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7904  *
7905  * Iteration convergence logic in is_state_visited() relies on exact
7906  * states comparison, which ignores read and precision marks.
7907  * This is necessary because read and precision marks are not finalized
7908  * while in the loop. Exact comparison might preclude convergence for
7909  * simple programs like below:
7910  *
7911  *     i = 0;
7912  *     while(iter_next(&it))
7913  *       i++;
7914  *
7915  * At each iteration step i++ would produce a new distinct state and
7916  * eventually instruction processing limit would be reached.
7917  *
7918  * To avoid such behavior speculatively forget (widen) range for
7919  * imprecise scalar registers, if those registers were not precise at the
7920  * end of the previous iteration and do not match exactly.
7921  *
7922  * This is a conservative heuristic that allows to verify wide range of programs,
7923  * however it precludes verification of programs that conjure an
7924  * imprecise value on the first loop iteration and use it as precise on a second.
7925  * For example, the following safe program would fail to verify:
7926  *
7927  *     struct bpf_num_iter it;
7928  *     int arr[10];
7929  *     int i = 0, a = 0;
7930  *     bpf_iter_num_new(&it, 0, 10);
7931  *     while (bpf_iter_num_next(&it)) {
7932  *       if (a == 0) {
7933  *         a = 1;
7934  *         i = 7; // Because i changed verifier would forget
7935  *                // it's range on second loop entry.
7936  *       } else {
7937  *         arr[i] = 42; // This would fail to verify.
7938  *       }
7939  *     }
7940  *     bpf_iter_num_destroy(&it);
7941  */
7942 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7943 				  struct bpf_kfunc_call_arg_meta *meta)
7944 {
7945 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7946 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7947 	struct bpf_reg_state *cur_iter, *queued_iter;
7948 
7949 	BTF_TYPE_EMIT(struct bpf_iter);
7950 
7951 	cur_iter = get_iter_from_state(cur_st, meta);
7952 
7953 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7954 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7955 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7956 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7957 		return -EFAULT;
7958 	}
7959 
7960 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7961 		/* Because iter_next() call is a checkpoint is_state_visitied()
7962 		 * should guarantee parent state with same call sites and insn_idx.
7963 		 */
7964 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7965 		    !same_callsites(cur_st->parent, cur_st)) {
7966 			verbose(env, "bug: bad parent state for iter next call");
7967 			return -EFAULT;
7968 		}
7969 		/* Note cur_st->parent in the call below, it is necessary to skip
7970 		 * checkpoint created for cur_st by is_state_visited()
7971 		 * right at this instruction.
7972 		 */
7973 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7974 		/* branch out active iter state */
7975 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7976 		if (!queued_st)
7977 			return -ENOMEM;
7978 
7979 		queued_iter = get_iter_from_state(queued_st, meta);
7980 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7981 		queued_iter->iter.depth++;
7982 		if (prev_st)
7983 			widen_imprecise_scalars(env, prev_st, queued_st);
7984 
7985 		queued_fr = queued_st->frame[queued_st->curframe];
7986 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7987 	}
7988 
7989 	/* switch to DRAINED state, but keep the depth unchanged */
7990 	/* mark current iter state as drained and assume returned NULL */
7991 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7992 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7993 
7994 	return 0;
7995 }
7996 
7997 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7998 {
7999 	return type == ARG_CONST_SIZE ||
8000 	       type == ARG_CONST_SIZE_OR_ZERO;
8001 }
8002 
8003 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8004 {
8005 	return base_type(type) == ARG_PTR_TO_MEM &&
8006 	       type & MEM_UNINIT;
8007 }
8008 
8009 static bool arg_type_is_release(enum bpf_arg_type type)
8010 {
8011 	return type & OBJ_RELEASE;
8012 }
8013 
8014 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8015 {
8016 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8017 }
8018 
8019 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8020 				 const struct bpf_call_arg_meta *meta,
8021 				 enum bpf_arg_type *arg_type)
8022 {
8023 	if (!meta->map_ptr) {
8024 		/* kernel subsystem misconfigured verifier */
8025 		verbose(env, "invalid map_ptr to access map->type\n");
8026 		return -EACCES;
8027 	}
8028 
8029 	switch (meta->map_ptr->map_type) {
8030 	case BPF_MAP_TYPE_SOCKMAP:
8031 	case BPF_MAP_TYPE_SOCKHASH:
8032 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8033 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8034 		} else {
8035 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8036 			return -EINVAL;
8037 		}
8038 		break;
8039 	case BPF_MAP_TYPE_BLOOM_FILTER:
8040 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8041 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8042 		break;
8043 	default:
8044 		break;
8045 	}
8046 	return 0;
8047 }
8048 
8049 struct bpf_reg_types {
8050 	const enum bpf_reg_type types[10];
8051 	u32 *btf_id;
8052 };
8053 
8054 static const struct bpf_reg_types sock_types = {
8055 	.types = {
8056 		PTR_TO_SOCK_COMMON,
8057 		PTR_TO_SOCKET,
8058 		PTR_TO_TCP_SOCK,
8059 		PTR_TO_XDP_SOCK,
8060 	},
8061 };
8062 
8063 #ifdef CONFIG_NET
8064 static const struct bpf_reg_types btf_id_sock_common_types = {
8065 	.types = {
8066 		PTR_TO_SOCK_COMMON,
8067 		PTR_TO_SOCKET,
8068 		PTR_TO_TCP_SOCK,
8069 		PTR_TO_XDP_SOCK,
8070 		PTR_TO_BTF_ID,
8071 		PTR_TO_BTF_ID | PTR_TRUSTED,
8072 	},
8073 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8074 };
8075 #endif
8076 
8077 static const struct bpf_reg_types mem_types = {
8078 	.types = {
8079 		PTR_TO_STACK,
8080 		PTR_TO_PACKET,
8081 		PTR_TO_PACKET_META,
8082 		PTR_TO_MAP_KEY,
8083 		PTR_TO_MAP_VALUE,
8084 		PTR_TO_MEM,
8085 		PTR_TO_MEM | MEM_RINGBUF,
8086 		PTR_TO_BUF,
8087 		PTR_TO_BTF_ID | PTR_TRUSTED,
8088 	},
8089 };
8090 
8091 static const struct bpf_reg_types spin_lock_types = {
8092 	.types = {
8093 		PTR_TO_MAP_VALUE,
8094 		PTR_TO_BTF_ID | MEM_ALLOC,
8095 	}
8096 };
8097 
8098 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8099 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8100 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8101 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8102 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8103 static const struct bpf_reg_types btf_ptr_types = {
8104 	.types = {
8105 		PTR_TO_BTF_ID,
8106 		PTR_TO_BTF_ID | PTR_TRUSTED,
8107 		PTR_TO_BTF_ID | MEM_RCU,
8108 	},
8109 };
8110 static const struct bpf_reg_types percpu_btf_ptr_types = {
8111 	.types = {
8112 		PTR_TO_BTF_ID | MEM_PERCPU,
8113 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8114 	}
8115 };
8116 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8117 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8118 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8119 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8120 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8121 static const struct bpf_reg_types dynptr_types = {
8122 	.types = {
8123 		PTR_TO_STACK,
8124 		CONST_PTR_TO_DYNPTR,
8125 	}
8126 };
8127 
8128 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8129 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8130 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8131 	[ARG_CONST_SIZE]		= &scalar_types,
8132 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8133 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8134 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8135 	[ARG_PTR_TO_CTX]		= &context_types,
8136 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8137 #ifdef CONFIG_NET
8138 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8139 #endif
8140 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8141 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8142 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8143 	[ARG_PTR_TO_MEM]		= &mem_types,
8144 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8145 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8146 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8147 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8148 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8149 	[ARG_PTR_TO_TIMER]		= &timer_types,
8150 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8151 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8152 };
8153 
8154 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8155 			  enum bpf_arg_type arg_type,
8156 			  const u32 *arg_btf_id,
8157 			  struct bpf_call_arg_meta *meta)
8158 {
8159 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8160 	enum bpf_reg_type expected, type = reg->type;
8161 	const struct bpf_reg_types *compatible;
8162 	int i, j;
8163 
8164 	compatible = compatible_reg_types[base_type(arg_type)];
8165 	if (!compatible) {
8166 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8167 		return -EFAULT;
8168 	}
8169 
8170 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8171 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8172 	 *
8173 	 * Same for MAYBE_NULL:
8174 	 *
8175 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8176 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8177 	 *
8178 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8179 	 *
8180 	 * Therefore we fold these flags depending on the arg_type before comparison.
8181 	 */
8182 	if (arg_type & MEM_RDONLY)
8183 		type &= ~MEM_RDONLY;
8184 	if (arg_type & PTR_MAYBE_NULL)
8185 		type &= ~PTR_MAYBE_NULL;
8186 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8187 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8188 
8189 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8190 		type &= ~MEM_ALLOC;
8191 
8192 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8193 		expected = compatible->types[i];
8194 		if (expected == NOT_INIT)
8195 			break;
8196 
8197 		if (type == expected)
8198 			goto found;
8199 	}
8200 
8201 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8202 	for (j = 0; j + 1 < i; j++)
8203 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8204 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8205 	return -EACCES;
8206 
8207 found:
8208 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8209 		return 0;
8210 
8211 	if (compatible == &mem_types) {
8212 		if (!(arg_type & MEM_RDONLY)) {
8213 			verbose(env,
8214 				"%s() may write into memory pointed by R%d type=%s\n",
8215 				func_id_name(meta->func_id),
8216 				regno, reg_type_str(env, reg->type));
8217 			return -EACCES;
8218 		}
8219 		return 0;
8220 	}
8221 
8222 	switch ((int)reg->type) {
8223 	case PTR_TO_BTF_ID:
8224 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8225 	case PTR_TO_BTF_ID | MEM_RCU:
8226 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8227 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8228 	{
8229 		/* For bpf_sk_release, it needs to match against first member
8230 		 * 'struct sock_common', hence make an exception for it. This
8231 		 * allows bpf_sk_release to work for multiple socket types.
8232 		 */
8233 		bool strict_type_match = arg_type_is_release(arg_type) &&
8234 					 meta->func_id != BPF_FUNC_sk_release;
8235 
8236 		if (type_may_be_null(reg->type) &&
8237 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8238 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8239 			return -EACCES;
8240 		}
8241 
8242 		if (!arg_btf_id) {
8243 			if (!compatible->btf_id) {
8244 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8245 				return -EFAULT;
8246 			}
8247 			arg_btf_id = compatible->btf_id;
8248 		}
8249 
8250 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8251 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8252 				return -EACCES;
8253 		} else {
8254 			if (arg_btf_id == BPF_PTR_POISON) {
8255 				verbose(env, "verifier internal error:");
8256 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8257 					regno);
8258 				return -EACCES;
8259 			}
8260 
8261 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8262 						  btf_vmlinux, *arg_btf_id,
8263 						  strict_type_match)) {
8264 				verbose(env, "R%d is of type %s but %s is expected\n",
8265 					regno, btf_type_name(reg->btf, reg->btf_id),
8266 					btf_type_name(btf_vmlinux, *arg_btf_id));
8267 				return -EACCES;
8268 			}
8269 		}
8270 		break;
8271 	}
8272 	case PTR_TO_BTF_ID | MEM_ALLOC:
8273 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8274 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8275 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8276 			return -EFAULT;
8277 		}
8278 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8279 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8280 				return -EACCES;
8281 		}
8282 		break;
8283 	case PTR_TO_BTF_ID | MEM_PERCPU:
8284 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8285 		/* Handled by helper specific checks */
8286 		break;
8287 	default:
8288 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8289 		return -EFAULT;
8290 	}
8291 	return 0;
8292 }
8293 
8294 static struct btf_field *
8295 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8296 {
8297 	struct btf_field *field;
8298 	struct btf_record *rec;
8299 
8300 	rec = reg_btf_record(reg);
8301 	if (!rec)
8302 		return NULL;
8303 
8304 	field = btf_record_find(rec, off, fields);
8305 	if (!field)
8306 		return NULL;
8307 
8308 	return field;
8309 }
8310 
8311 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8312 			   const struct bpf_reg_state *reg, int regno,
8313 			   enum bpf_arg_type arg_type)
8314 {
8315 	u32 type = reg->type;
8316 
8317 	/* When referenced register is passed to release function, its fixed
8318 	 * offset must be 0.
8319 	 *
8320 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8321 	 * meta->release_regno.
8322 	 */
8323 	if (arg_type_is_release(arg_type)) {
8324 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8325 		 * may not directly point to the object being released, but to
8326 		 * dynptr pointing to such object, which might be at some offset
8327 		 * on the stack. In that case, we simply to fallback to the
8328 		 * default handling.
8329 		 */
8330 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8331 			return 0;
8332 
8333 		/* Doing check_ptr_off_reg check for the offset will catch this
8334 		 * because fixed_off_ok is false, but checking here allows us
8335 		 * to give the user a better error message.
8336 		 */
8337 		if (reg->off) {
8338 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8339 				regno);
8340 			return -EINVAL;
8341 		}
8342 		return __check_ptr_off_reg(env, reg, regno, false);
8343 	}
8344 
8345 	switch (type) {
8346 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8347 	case PTR_TO_STACK:
8348 	case PTR_TO_PACKET:
8349 	case PTR_TO_PACKET_META:
8350 	case PTR_TO_MAP_KEY:
8351 	case PTR_TO_MAP_VALUE:
8352 	case PTR_TO_MEM:
8353 	case PTR_TO_MEM | MEM_RDONLY:
8354 	case PTR_TO_MEM | MEM_RINGBUF:
8355 	case PTR_TO_BUF:
8356 	case PTR_TO_BUF | MEM_RDONLY:
8357 	case SCALAR_VALUE:
8358 		return 0;
8359 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8360 	 * fixed offset.
8361 	 */
8362 	case PTR_TO_BTF_ID:
8363 	case PTR_TO_BTF_ID | MEM_ALLOC:
8364 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8365 	case PTR_TO_BTF_ID | MEM_RCU:
8366 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8367 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8368 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8369 		 * its fixed offset must be 0. In the other cases, fixed offset
8370 		 * can be non-zero. This was already checked above. So pass
8371 		 * fixed_off_ok as true to allow fixed offset for all other
8372 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8373 		 * still need to do checks instead of returning.
8374 		 */
8375 		return __check_ptr_off_reg(env, reg, regno, true);
8376 	default:
8377 		return __check_ptr_off_reg(env, reg, regno, false);
8378 	}
8379 }
8380 
8381 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8382 						const struct bpf_func_proto *fn,
8383 						struct bpf_reg_state *regs)
8384 {
8385 	struct bpf_reg_state *state = NULL;
8386 	int i;
8387 
8388 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8389 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8390 			if (state) {
8391 				verbose(env, "verifier internal error: multiple dynptr args\n");
8392 				return NULL;
8393 			}
8394 			state = &regs[BPF_REG_1 + i];
8395 		}
8396 
8397 	if (!state)
8398 		verbose(env, "verifier internal error: no dynptr arg found\n");
8399 
8400 	return state;
8401 }
8402 
8403 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8404 {
8405 	struct bpf_func_state *state = func(env, reg);
8406 	int spi;
8407 
8408 	if (reg->type == CONST_PTR_TO_DYNPTR)
8409 		return reg->id;
8410 	spi = dynptr_get_spi(env, reg);
8411 	if (spi < 0)
8412 		return spi;
8413 	return state->stack[spi].spilled_ptr.id;
8414 }
8415 
8416 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8417 {
8418 	struct bpf_func_state *state = func(env, reg);
8419 	int spi;
8420 
8421 	if (reg->type == CONST_PTR_TO_DYNPTR)
8422 		return reg->ref_obj_id;
8423 	spi = dynptr_get_spi(env, reg);
8424 	if (spi < 0)
8425 		return spi;
8426 	return state->stack[spi].spilled_ptr.ref_obj_id;
8427 }
8428 
8429 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8430 					    struct bpf_reg_state *reg)
8431 {
8432 	struct bpf_func_state *state = func(env, reg);
8433 	int spi;
8434 
8435 	if (reg->type == CONST_PTR_TO_DYNPTR)
8436 		return reg->dynptr.type;
8437 
8438 	spi = __get_spi(reg->off);
8439 	if (spi < 0) {
8440 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8441 		return BPF_DYNPTR_TYPE_INVALID;
8442 	}
8443 
8444 	return state->stack[spi].spilled_ptr.dynptr.type;
8445 }
8446 
8447 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8448 			  struct bpf_call_arg_meta *meta,
8449 			  const struct bpf_func_proto *fn,
8450 			  int insn_idx)
8451 {
8452 	u32 regno = BPF_REG_1 + arg;
8453 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8454 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8455 	enum bpf_reg_type type = reg->type;
8456 	u32 *arg_btf_id = NULL;
8457 	int err = 0;
8458 
8459 	if (arg_type == ARG_DONTCARE)
8460 		return 0;
8461 
8462 	err = check_reg_arg(env, regno, SRC_OP);
8463 	if (err)
8464 		return err;
8465 
8466 	if (arg_type == ARG_ANYTHING) {
8467 		if (is_pointer_value(env, regno)) {
8468 			verbose(env, "R%d leaks addr into helper function\n",
8469 				regno);
8470 			return -EACCES;
8471 		}
8472 		return 0;
8473 	}
8474 
8475 	if (type_is_pkt_pointer(type) &&
8476 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8477 		verbose(env, "helper access to the packet is not allowed\n");
8478 		return -EACCES;
8479 	}
8480 
8481 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8482 		err = resolve_map_arg_type(env, meta, &arg_type);
8483 		if (err)
8484 			return err;
8485 	}
8486 
8487 	if (register_is_null(reg) && type_may_be_null(arg_type))
8488 		/* A NULL register has a SCALAR_VALUE type, so skip
8489 		 * type checking.
8490 		 */
8491 		goto skip_type_check;
8492 
8493 	/* arg_btf_id and arg_size are in a union. */
8494 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8495 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8496 		arg_btf_id = fn->arg_btf_id[arg];
8497 
8498 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8499 	if (err)
8500 		return err;
8501 
8502 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8503 	if (err)
8504 		return err;
8505 
8506 skip_type_check:
8507 	if (arg_type_is_release(arg_type)) {
8508 		if (arg_type_is_dynptr(arg_type)) {
8509 			struct bpf_func_state *state = func(env, reg);
8510 			int spi;
8511 
8512 			/* Only dynptr created on stack can be released, thus
8513 			 * the get_spi and stack state checks for spilled_ptr
8514 			 * should only be done before process_dynptr_func for
8515 			 * PTR_TO_STACK.
8516 			 */
8517 			if (reg->type == PTR_TO_STACK) {
8518 				spi = dynptr_get_spi(env, reg);
8519 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8520 					verbose(env, "arg %d is an unacquired reference\n", regno);
8521 					return -EINVAL;
8522 				}
8523 			} else {
8524 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8525 				return -EINVAL;
8526 			}
8527 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8528 			verbose(env, "R%d must be referenced when passed to release function\n",
8529 				regno);
8530 			return -EINVAL;
8531 		}
8532 		if (meta->release_regno) {
8533 			verbose(env, "verifier internal error: more than one release argument\n");
8534 			return -EFAULT;
8535 		}
8536 		meta->release_regno = regno;
8537 	}
8538 
8539 	if (reg->ref_obj_id) {
8540 		if (meta->ref_obj_id) {
8541 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8542 				regno, reg->ref_obj_id,
8543 				meta->ref_obj_id);
8544 			return -EFAULT;
8545 		}
8546 		meta->ref_obj_id = reg->ref_obj_id;
8547 	}
8548 
8549 	switch (base_type(arg_type)) {
8550 	case ARG_CONST_MAP_PTR:
8551 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8552 		if (meta->map_ptr) {
8553 			/* Use map_uid (which is unique id of inner map) to reject:
8554 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8555 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8556 			 * if (inner_map1 && inner_map2) {
8557 			 *     timer = bpf_map_lookup_elem(inner_map1);
8558 			 *     if (timer)
8559 			 *         // mismatch would have been allowed
8560 			 *         bpf_timer_init(timer, inner_map2);
8561 			 * }
8562 			 *
8563 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8564 			 */
8565 			if (meta->map_ptr != reg->map_ptr ||
8566 			    meta->map_uid != reg->map_uid) {
8567 				verbose(env,
8568 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8569 					meta->map_uid, reg->map_uid);
8570 				return -EINVAL;
8571 			}
8572 		}
8573 		meta->map_ptr = reg->map_ptr;
8574 		meta->map_uid = reg->map_uid;
8575 		break;
8576 	case ARG_PTR_TO_MAP_KEY:
8577 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8578 		 * check that [key, key + map->key_size) are within
8579 		 * stack limits and initialized
8580 		 */
8581 		if (!meta->map_ptr) {
8582 			/* in function declaration map_ptr must come before
8583 			 * map_key, so that it's verified and known before
8584 			 * we have to check map_key here. Otherwise it means
8585 			 * that kernel subsystem misconfigured verifier
8586 			 */
8587 			verbose(env, "invalid map_ptr to access map->key\n");
8588 			return -EACCES;
8589 		}
8590 		err = check_helper_mem_access(env, regno,
8591 					      meta->map_ptr->key_size, false,
8592 					      NULL);
8593 		break;
8594 	case ARG_PTR_TO_MAP_VALUE:
8595 		if (type_may_be_null(arg_type) && register_is_null(reg))
8596 			return 0;
8597 
8598 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8599 		 * check [value, value + map->value_size) validity
8600 		 */
8601 		if (!meta->map_ptr) {
8602 			/* kernel subsystem misconfigured verifier */
8603 			verbose(env, "invalid map_ptr to access map->value\n");
8604 			return -EACCES;
8605 		}
8606 		meta->raw_mode = arg_type & MEM_UNINIT;
8607 		err = check_helper_mem_access(env, regno,
8608 					      meta->map_ptr->value_size, false,
8609 					      meta);
8610 		break;
8611 	case ARG_PTR_TO_PERCPU_BTF_ID:
8612 		if (!reg->btf_id) {
8613 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8614 			return -EACCES;
8615 		}
8616 		meta->ret_btf = reg->btf;
8617 		meta->ret_btf_id = reg->btf_id;
8618 		break;
8619 	case ARG_PTR_TO_SPIN_LOCK:
8620 		if (in_rbtree_lock_required_cb(env)) {
8621 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8622 			return -EACCES;
8623 		}
8624 		if (meta->func_id == BPF_FUNC_spin_lock) {
8625 			err = process_spin_lock(env, regno, true);
8626 			if (err)
8627 				return err;
8628 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8629 			err = process_spin_lock(env, regno, false);
8630 			if (err)
8631 				return err;
8632 		} else {
8633 			verbose(env, "verifier internal error\n");
8634 			return -EFAULT;
8635 		}
8636 		break;
8637 	case ARG_PTR_TO_TIMER:
8638 		err = process_timer_func(env, regno, meta);
8639 		if (err)
8640 			return err;
8641 		break;
8642 	case ARG_PTR_TO_FUNC:
8643 		meta->subprogno = reg->subprogno;
8644 		break;
8645 	case ARG_PTR_TO_MEM:
8646 		/* The access to this pointer is only checked when we hit the
8647 		 * next is_mem_size argument below.
8648 		 */
8649 		meta->raw_mode = arg_type & MEM_UNINIT;
8650 		if (arg_type & MEM_FIXED_SIZE) {
8651 			err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
8652 			if (err)
8653 				return err;
8654 			if (arg_type & MEM_ALIGNED)
8655 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8656 		}
8657 		break;
8658 	case ARG_CONST_SIZE:
8659 		err = check_mem_size_reg(env, reg, regno, false, meta);
8660 		break;
8661 	case ARG_CONST_SIZE_OR_ZERO:
8662 		err = check_mem_size_reg(env, reg, regno, true, meta);
8663 		break;
8664 	case ARG_PTR_TO_DYNPTR:
8665 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8666 		if (err)
8667 			return err;
8668 		break;
8669 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8670 		if (!tnum_is_const(reg->var_off)) {
8671 			verbose(env, "R%d is not a known constant'\n",
8672 				regno);
8673 			return -EACCES;
8674 		}
8675 		meta->mem_size = reg->var_off.value;
8676 		err = mark_chain_precision(env, regno);
8677 		if (err)
8678 			return err;
8679 		break;
8680 	case ARG_PTR_TO_CONST_STR:
8681 	{
8682 		struct bpf_map *map = reg->map_ptr;
8683 		int map_off;
8684 		u64 map_addr;
8685 		char *str_ptr;
8686 
8687 		if (!bpf_map_is_rdonly(map)) {
8688 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8689 			return -EACCES;
8690 		}
8691 
8692 		if (!tnum_is_const(reg->var_off)) {
8693 			verbose(env, "R%d is not a constant address'\n", regno);
8694 			return -EACCES;
8695 		}
8696 
8697 		if (!map->ops->map_direct_value_addr) {
8698 			verbose(env, "no direct value access support for this map type\n");
8699 			return -EACCES;
8700 		}
8701 
8702 		err = check_map_access(env, regno, reg->off,
8703 				       map->value_size - reg->off, false,
8704 				       ACCESS_HELPER);
8705 		if (err)
8706 			return err;
8707 
8708 		map_off = reg->off + reg->var_off.value;
8709 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8710 		if (err) {
8711 			verbose(env, "direct value access on string failed\n");
8712 			return err;
8713 		}
8714 
8715 		str_ptr = (char *)(long)(map_addr);
8716 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8717 			verbose(env, "string is not zero-terminated\n");
8718 			return -EINVAL;
8719 		}
8720 		break;
8721 	}
8722 	case ARG_PTR_TO_KPTR:
8723 		err = process_kptr_func(env, regno, meta);
8724 		if (err)
8725 			return err;
8726 		break;
8727 	}
8728 
8729 	return err;
8730 }
8731 
8732 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8733 {
8734 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8735 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8736 
8737 	if (func_id != BPF_FUNC_map_update_elem &&
8738 	    func_id != BPF_FUNC_map_delete_elem)
8739 		return false;
8740 
8741 	/* It's not possible to get access to a locked struct sock in these
8742 	 * contexts, so updating is safe.
8743 	 */
8744 	switch (type) {
8745 	case BPF_PROG_TYPE_TRACING:
8746 		if (eatype == BPF_TRACE_ITER)
8747 			return true;
8748 		break;
8749 	case BPF_PROG_TYPE_SOCK_OPS:
8750 		/* map_update allowed only via dedicated helpers with event type checks */
8751 		if (func_id == BPF_FUNC_map_delete_elem)
8752 			return true;
8753 		break;
8754 	case BPF_PROG_TYPE_SOCKET_FILTER:
8755 	case BPF_PROG_TYPE_SCHED_CLS:
8756 	case BPF_PROG_TYPE_SCHED_ACT:
8757 	case BPF_PROG_TYPE_XDP:
8758 	case BPF_PROG_TYPE_SK_REUSEPORT:
8759 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8760 	case BPF_PROG_TYPE_SK_LOOKUP:
8761 		return true;
8762 	default:
8763 		break;
8764 	}
8765 
8766 	verbose(env, "cannot update sockmap in this context\n");
8767 	return false;
8768 }
8769 
8770 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8771 {
8772 	return env->prog->jit_requested &&
8773 	       bpf_jit_supports_subprog_tailcalls();
8774 }
8775 
8776 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8777 					struct bpf_map *map, int func_id)
8778 {
8779 	if (!map)
8780 		return 0;
8781 
8782 	/* We need a two way check, first is from map perspective ... */
8783 	switch (map->map_type) {
8784 	case BPF_MAP_TYPE_PROG_ARRAY:
8785 		if (func_id != BPF_FUNC_tail_call)
8786 			goto error;
8787 		break;
8788 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8789 		if (func_id != BPF_FUNC_perf_event_read &&
8790 		    func_id != BPF_FUNC_perf_event_output &&
8791 		    func_id != BPF_FUNC_skb_output &&
8792 		    func_id != BPF_FUNC_perf_event_read_value &&
8793 		    func_id != BPF_FUNC_xdp_output)
8794 			goto error;
8795 		break;
8796 	case BPF_MAP_TYPE_RINGBUF:
8797 		if (func_id != BPF_FUNC_ringbuf_output &&
8798 		    func_id != BPF_FUNC_ringbuf_reserve &&
8799 		    func_id != BPF_FUNC_ringbuf_query &&
8800 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8801 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8802 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8803 			goto error;
8804 		break;
8805 	case BPF_MAP_TYPE_USER_RINGBUF:
8806 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8807 			goto error;
8808 		break;
8809 	case BPF_MAP_TYPE_STACK_TRACE:
8810 		if (func_id != BPF_FUNC_get_stackid)
8811 			goto error;
8812 		break;
8813 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8814 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8815 		    func_id != BPF_FUNC_current_task_under_cgroup)
8816 			goto error;
8817 		break;
8818 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8819 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8820 		if (func_id != BPF_FUNC_get_local_storage)
8821 			goto error;
8822 		break;
8823 	case BPF_MAP_TYPE_DEVMAP:
8824 	case BPF_MAP_TYPE_DEVMAP_HASH:
8825 		if (func_id != BPF_FUNC_redirect_map &&
8826 		    func_id != BPF_FUNC_map_lookup_elem)
8827 			goto error;
8828 		break;
8829 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8830 	 * appear.
8831 	 */
8832 	case BPF_MAP_TYPE_CPUMAP:
8833 		if (func_id != BPF_FUNC_redirect_map)
8834 			goto error;
8835 		break;
8836 	case BPF_MAP_TYPE_XSKMAP:
8837 		if (func_id != BPF_FUNC_redirect_map &&
8838 		    func_id != BPF_FUNC_map_lookup_elem)
8839 			goto error;
8840 		break;
8841 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8842 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8843 		if (func_id != BPF_FUNC_map_lookup_elem)
8844 			goto error;
8845 		break;
8846 	case BPF_MAP_TYPE_SOCKMAP:
8847 		if (func_id != BPF_FUNC_sk_redirect_map &&
8848 		    func_id != BPF_FUNC_sock_map_update &&
8849 		    func_id != BPF_FUNC_msg_redirect_map &&
8850 		    func_id != BPF_FUNC_sk_select_reuseport &&
8851 		    func_id != BPF_FUNC_map_lookup_elem &&
8852 		    !may_update_sockmap(env, func_id))
8853 			goto error;
8854 		break;
8855 	case BPF_MAP_TYPE_SOCKHASH:
8856 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8857 		    func_id != BPF_FUNC_sock_hash_update &&
8858 		    func_id != BPF_FUNC_msg_redirect_hash &&
8859 		    func_id != BPF_FUNC_sk_select_reuseport &&
8860 		    func_id != BPF_FUNC_map_lookup_elem &&
8861 		    !may_update_sockmap(env, func_id))
8862 			goto error;
8863 		break;
8864 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8865 		if (func_id != BPF_FUNC_sk_select_reuseport)
8866 			goto error;
8867 		break;
8868 	case BPF_MAP_TYPE_QUEUE:
8869 	case BPF_MAP_TYPE_STACK:
8870 		if (func_id != BPF_FUNC_map_peek_elem &&
8871 		    func_id != BPF_FUNC_map_pop_elem &&
8872 		    func_id != BPF_FUNC_map_push_elem)
8873 			goto error;
8874 		break;
8875 	case BPF_MAP_TYPE_SK_STORAGE:
8876 		if (func_id != BPF_FUNC_sk_storage_get &&
8877 		    func_id != BPF_FUNC_sk_storage_delete &&
8878 		    func_id != BPF_FUNC_kptr_xchg)
8879 			goto error;
8880 		break;
8881 	case BPF_MAP_TYPE_INODE_STORAGE:
8882 		if (func_id != BPF_FUNC_inode_storage_get &&
8883 		    func_id != BPF_FUNC_inode_storage_delete &&
8884 		    func_id != BPF_FUNC_kptr_xchg)
8885 			goto error;
8886 		break;
8887 	case BPF_MAP_TYPE_TASK_STORAGE:
8888 		if (func_id != BPF_FUNC_task_storage_get &&
8889 		    func_id != BPF_FUNC_task_storage_delete &&
8890 		    func_id != BPF_FUNC_kptr_xchg)
8891 			goto error;
8892 		break;
8893 	case BPF_MAP_TYPE_CGRP_STORAGE:
8894 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8895 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8896 		    func_id != BPF_FUNC_kptr_xchg)
8897 			goto error;
8898 		break;
8899 	case BPF_MAP_TYPE_BLOOM_FILTER:
8900 		if (func_id != BPF_FUNC_map_peek_elem &&
8901 		    func_id != BPF_FUNC_map_push_elem)
8902 			goto error;
8903 		break;
8904 	default:
8905 		break;
8906 	}
8907 
8908 	/* ... and second from the function itself. */
8909 	switch (func_id) {
8910 	case BPF_FUNC_tail_call:
8911 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8912 			goto error;
8913 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8914 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8915 			return -EINVAL;
8916 		}
8917 		break;
8918 	case BPF_FUNC_perf_event_read:
8919 	case BPF_FUNC_perf_event_output:
8920 	case BPF_FUNC_perf_event_read_value:
8921 	case BPF_FUNC_skb_output:
8922 	case BPF_FUNC_xdp_output:
8923 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8924 			goto error;
8925 		break;
8926 	case BPF_FUNC_ringbuf_output:
8927 	case BPF_FUNC_ringbuf_reserve:
8928 	case BPF_FUNC_ringbuf_query:
8929 	case BPF_FUNC_ringbuf_reserve_dynptr:
8930 	case BPF_FUNC_ringbuf_submit_dynptr:
8931 	case BPF_FUNC_ringbuf_discard_dynptr:
8932 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8933 			goto error;
8934 		break;
8935 	case BPF_FUNC_user_ringbuf_drain:
8936 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8937 			goto error;
8938 		break;
8939 	case BPF_FUNC_get_stackid:
8940 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8941 			goto error;
8942 		break;
8943 	case BPF_FUNC_current_task_under_cgroup:
8944 	case BPF_FUNC_skb_under_cgroup:
8945 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8946 			goto error;
8947 		break;
8948 	case BPF_FUNC_redirect_map:
8949 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8950 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8951 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8952 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8953 			goto error;
8954 		break;
8955 	case BPF_FUNC_sk_redirect_map:
8956 	case BPF_FUNC_msg_redirect_map:
8957 	case BPF_FUNC_sock_map_update:
8958 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8959 			goto error;
8960 		break;
8961 	case BPF_FUNC_sk_redirect_hash:
8962 	case BPF_FUNC_msg_redirect_hash:
8963 	case BPF_FUNC_sock_hash_update:
8964 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8965 			goto error;
8966 		break;
8967 	case BPF_FUNC_get_local_storage:
8968 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8969 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8970 			goto error;
8971 		break;
8972 	case BPF_FUNC_sk_select_reuseport:
8973 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8974 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8975 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8976 			goto error;
8977 		break;
8978 	case BPF_FUNC_map_pop_elem:
8979 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8980 		    map->map_type != BPF_MAP_TYPE_STACK)
8981 			goto error;
8982 		break;
8983 	case BPF_FUNC_map_peek_elem:
8984 	case BPF_FUNC_map_push_elem:
8985 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8986 		    map->map_type != BPF_MAP_TYPE_STACK &&
8987 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8988 			goto error;
8989 		break;
8990 	case BPF_FUNC_map_lookup_percpu_elem:
8991 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8992 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8993 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8994 			goto error;
8995 		break;
8996 	case BPF_FUNC_sk_storage_get:
8997 	case BPF_FUNC_sk_storage_delete:
8998 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8999 			goto error;
9000 		break;
9001 	case BPF_FUNC_inode_storage_get:
9002 	case BPF_FUNC_inode_storage_delete:
9003 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9004 			goto error;
9005 		break;
9006 	case BPF_FUNC_task_storage_get:
9007 	case BPF_FUNC_task_storage_delete:
9008 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9009 			goto error;
9010 		break;
9011 	case BPF_FUNC_cgrp_storage_get:
9012 	case BPF_FUNC_cgrp_storage_delete:
9013 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9014 			goto error;
9015 		break;
9016 	default:
9017 		break;
9018 	}
9019 
9020 	return 0;
9021 error:
9022 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9023 		map->map_type, func_id_name(func_id), func_id);
9024 	return -EINVAL;
9025 }
9026 
9027 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9028 {
9029 	int count = 0;
9030 
9031 	if (arg_type_is_raw_mem(fn->arg1_type))
9032 		count++;
9033 	if (arg_type_is_raw_mem(fn->arg2_type))
9034 		count++;
9035 	if (arg_type_is_raw_mem(fn->arg3_type))
9036 		count++;
9037 	if (arg_type_is_raw_mem(fn->arg4_type))
9038 		count++;
9039 	if (arg_type_is_raw_mem(fn->arg5_type))
9040 		count++;
9041 
9042 	/* We only support one arg being in raw mode at the moment,
9043 	 * which is sufficient for the helper functions we have
9044 	 * right now.
9045 	 */
9046 	return count <= 1;
9047 }
9048 
9049 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9050 {
9051 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9052 	bool has_size = fn->arg_size[arg] != 0;
9053 	bool is_next_size = false;
9054 
9055 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9056 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9057 
9058 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9059 		return is_next_size;
9060 
9061 	return has_size == is_next_size || is_next_size == is_fixed;
9062 }
9063 
9064 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9065 {
9066 	/* bpf_xxx(..., buf, len) call will access 'len'
9067 	 * bytes from memory 'buf'. Both arg types need
9068 	 * to be paired, so make sure there's no buggy
9069 	 * helper function specification.
9070 	 */
9071 	if (arg_type_is_mem_size(fn->arg1_type) ||
9072 	    check_args_pair_invalid(fn, 0) ||
9073 	    check_args_pair_invalid(fn, 1) ||
9074 	    check_args_pair_invalid(fn, 2) ||
9075 	    check_args_pair_invalid(fn, 3) ||
9076 	    check_args_pair_invalid(fn, 4))
9077 		return false;
9078 
9079 	return true;
9080 }
9081 
9082 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9083 {
9084 	int i;
9085 
9086 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9087 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9088 			return !!fn->arg_btf_id[i];
9089 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9090 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9091 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9092 		    /* arg_btf_id and arg_size are in a union. */
9093 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9094 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9095 			return false;
9096 	}
9097 
9098 	return true;
9099 }
9100 
9101 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9102 {
9103 	return check_raw_mode_ok(fn) &&
9104 	       check_arg_pair_ok(fn) &&
9105 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9106 }
9107 
9108 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9109  * are now invalid, so turn them into unknown SCALAR_VALUE.
9110  *
9111  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9112  * since these slices point to packet data.
9113  */
9114 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9115 {
9116 	struct bpf_func_state *state;
9117 	struct bpf_reg_state *reg;
9118 
9119 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9120 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9121 			mark_reg_invalid(env, reg);
9122 	}));
9123 }
9124 
9125 enum {
9126 	AT_PKT_END = -1,
9127 	BEYOND_PKT_END = -2,
9128 };
9129 
9130 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9131 {
9132 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9133 	struct bpf_reg_state *reg = &state->regs[regn];
9134 
9135 	if (reg->type != PTR_TO_PACKET)
9136 		/* PTR_TO_PACKET_META is not supported yet */
9137 		return;
9138 
9139 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9140 	 * How far beyond pkt_end it goes is unknown.
9141 	 * if (!range_open) it's the case of pkt >= pkt_end
9142 	 * if (range_open) it's the case of pkt > pkt_end
9143 	 * hence this pointer is at least 1 byte bigger than pkt_end
9144 	 */
9145 	if (range_open)
9146 		reg->range = BEYOND_PKT_END;
9147 	else
9148 		reg->range = AT_PKT_END;
9149 }
9150 
9151 /* The pointer with the specified id has released its reference to kernel
9152  * resources. Identify all copies of the same pointer and clear the reference.
9153  */
9154 static int release_reference(struct bpf_verifier_env *env,
9155 			     int ref_obj_id)
9156 {
9157 	struct bpf_func_state *state;
9158 	struct bpf_reg_state *reg;
9159 	int err;
9160 
9161 	err = release_reference_state(cur_func(env), ref_obj_id);
9162 	if (err)
9163 		return err;
9164 
9165 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9166 		if (reg->ref_obj_id == ref_obj_id)
9167 			mark_reg_invalid(env, reg);
9168 	}));
9169 
9170 	return 0;
9171 }
9172 
9173 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9174 {
9175 	struct bpf_func_state *unused;
9176 	struct bpf_reg_state *reg;
9177 
9178 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9179 		if (type_is_non_owning_ref(reg->type))
9180 			mark_reg_invalid(env, reg);
9181 	}));
9182 }
9183 
9184 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9185 				    struct bpf_reg_state *regs)
9186 {
9187 	int i;
9188 
9189 	/* after the call registers r0 - r5 were scratched */
9190 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9191 		mark_reg_not_init(env, regs, caller_saved[i]);
9192 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9193 	}
9194 }
9195 
9196 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9197 				   struct bpf_func_state *caller,
9198 				   struct bpf_func_state *callee,
9199 				   int insn_idx);
9200 
9201 static int set_callee_state(struct bpf_verifier_env *env,
9202 			    struct bpf_func_state *caller,
9203 			    struct bpf_func_state *callee, int insn_idx);
9204 
9205 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9206 			    set_callee_state_fn set_callee_state_cb,
9207 			    struct bpf_verifier_state *state)
9208 {
9209 	struct bpf_func_state *caller, *callee;
9210 	int err;
9211 
9212 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9213 		verbose(env, "the call stack of %d frames is too deep\n",
9214 			state->curframe + 2);
9215 		return -E2BIG;
9216 	}
9217 
9218 	if (state->frame[state->curframe + 1]) {
9219 		verbose(env, "verifier bug. Frame %d already allocated\n",
9220 			state->curframe + 1);
9221 		return -EFAULT;
9222 	}
9223 
9224 	caller = state->frame[state->curframe];
9225 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9226 	if (!callee)
9227 		return -ENOMEM;
9228 	state->frame[state->curframe + 1] = callee;
9229 
9230 	/* callee cannot access r0, r6 - r9 for reading and has to write
9231 	 * into its own stack before reading from it.
9232 	 * callee can read/write into caller's stack
9233 	 */
9234 	init_func_state(env, callee,
9235 			/* remember the callsite, it will be used by bpf_exit */
9236 			callsite,
9237 			state->curframe + 1 /* frameno within this callchain */,
9238 			subprog /* subprog number within this prog */);
9239 	/* Transfer references to the callee */
9240 	err = copy_reference_state(callee, caller);
9241 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9242 	if (err)
9243 		goto err_out;
9244 
9245 	/* only increment it after check_reg_arg() finished */
9246 	state->curframe++;
9247 
9248 	return 0;
9249 
9250 err_out:
9251 	free_func_state(callee);
9252 	state->frame[state->curframe + 1] = NULL;
9253 	return err;
9254 }
9255 
9256 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9257 			      int insn_idx, int subprog,
9258 			      set_callee_state_fn set_callee_state_cb)
9259 {
9260 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9261 	struct bpf_func_state *caller, *callee;
9262 	int err;
9263 
9264 	caller = state->frame[state->curframe];
9265 	err = btf_check_subprog_call(env, subprog, caller->regs);
9266 	if (err == -EFAULT)
9267 		return err;
9268 
9269 	/* set_callee_state is used for direct subprog calls, but we are
9270 	 * interested in validating only BPF helpers that can call subprogs as
9271 	 * callbacks
9272 	 */
9273 	if (bpf_pseudo_kfunc_call(insn) &&
9274 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9275 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9276 			func_id_name(insn->imm), insn->imm);
9277 		return -EFAULT;
9278 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9279 		   !is_callback_calling_function(insn->imm)) { /* helper */
9280 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9281 			func_id_name(insn->imm), insn->imm);
9282 		return -EFAULT;
9283 	}
9284 
9285 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9286 	    insn->src_reg == 0 &&
9287 	    insn->imm == BPF_FUNC_timer_set_callback) {
9288 		struct bpf_verifier_state *async_cb;
9289 
9290 		/* there is no real recursion here. timer callbacks are async */
9291 		env->subprog_info[subprog].is_async_cb = true;
9292 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9293 					 insn_idx, subprog);
9294 		if (!async_cb)
9295 			return -EFAULT;
9296 		callee = async_cb->frame[0];
9297 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9298 
9299 		/* Convert bpf_timer_set_callback() args into timer callback args */
9300 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9301 		if (err)
9302 			return err;
9303 
9304 		return 0;
9305 	}
9306 
9307 	/* for callback functions enqueue entry to callback and
9308 	 * proceed with next instruction within current frame.
9309 	 */
9310 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9311 	if (!callback_state)
9312 		return -ENOMEM;
9313 
9314 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9315 			       callback_state);
9316 	if (err)
9317 		return err;
9318 
9319 	callback_state->callback_unroll_depth++;
9320 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9321 	caller->callback_depth = 0;
9322 	return 0;
9323 }
9324 
9325 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9326 			   int *insn_idx)
9327 {
9328 	struct bpf_verifier_state *state = env->cur_state;
9329 	struct bpf_func_state *caller;
9330 	int err, subprog, target_insn;
9331 
9332 	target_insn = *insn_idx + insn->imm + 1;
9333 	subprog = find_subprog(env, target_insn);
9334 	if (subprog < 0) {
9335 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9336 		return -EFAULT;
9337 	}
9338 
9339 	caller = state->frame[state->curframe];
9340 	err = btf_check_subprog_call(env, subprog, caller->regs);
9341 	if (err == -EFAULT)
9342 		return err;
9343 	if (subprog_is_global(env, subprog)) {
9344 		if (err) {
9345 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9346 			return err;
9347 		}
9348 
9349 		if (env->log.level & BPF_LOG_LEVEL)
9350 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9351 		clear_caller_saved_regs(env, caller->regs);
9352 
9353 		/* All global functions return a 64-bit SCALAR_VALUE */
9354 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9355 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9356 
9357 		/* continue with next insn after call */
9358 		return 0;
9359 	}
9360 
9361 	/* for regular function entry setup new frame and continue
9362 	 * from that frame.
9363 	 */
9364 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9365 	if (err)
9366 		return err;
9367 
9368 	clear_caller_saved_regs(env, caller->regs);
9369 
9370 	/* and go analyze first insn of the callee */
9371 	*insn_idx = env->subprog_info[subprog].start - 1;
9372 
9373 	if (env->log.level & BPF_LOG_LEVEL) {
9374 		verbose(env, "caller:\n");
9375 		print_verifier_state(env, caller, true);
9376 		verbose(env, "callee:\n");
9377 		print_verifier_state(env, state->frame[state->curframe], true);
9378 	}
9379 
9380 	return 0;
9381 }
9382 
9383 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9384 				   struct bpf_func_state *caller,
9385 				   struct bpf_func_state *callee)
9386 {
9387 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9388 	 *      void *callback_ctx, u64 flags);
9389 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9390 	 *      void *callback_ctx);
9391 	 */
9392 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9393 
9394 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9395 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9396 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9397 
9398 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9399 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9400 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9401 
9402 	/* pointer to stack or null */
9403 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9404 
9405 	/* unused */
9406 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9407 	return 0;
9408 }
9409 
9410 static int set_callee_state(struct bpf_verifier_env *env,
9411 			    struct bpf_func_state *caller,
9412 			    struct bpf_func_state *callee, int insn_idx)
9413 {
9414 	int i;
9415 
9416 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9417 	 * pointers, which connects us up to the liveness chain
9418 	 */
9419 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9420 		callee->regs[i] = caller->regs[i];
9421 	return 0;
9422 }
9423 
9424 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9425 				       struct bpf_func_state *caller,
9426 				       struct bpf_func_state *callee,
9427 				       int insn_idx)
9428 {
9429 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9430 	struct bpf_map *map;
9431 	int err;
9432 
9433 	if (bpf_map_ptr_poisoned(insn_aux)) {
9434 		verbose(env, "tail_call abusing map_ptr\n");
9435 		return -EINVAL;
9436 	}
9437 
9438 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9439 	if (!map->ops->map_set_for_each_callback_args ||
9440 	    !map->ops->map_for_each_callback) {
9441 		verbose(env, "callback function not allowed for map\n");
9442 		return -ENOTSUPP;
9443 	}
9444 
9445 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9446 	if (err)
9447 		return err;
9448 
9449 	callee->in_callback_fn = true;
9450 	callee->callback_ret_range = tnum_range(0, 1);
9451 	return 0;
9452 }
9453 
9454 static int set_loop_callback_state(struct bpf_verifier_env *env,
9455 				   struct bpf_func_state *caller,
9456 				   struct bpf_func_state *callee,
9457 				   int insn_idx)
9458 {
9459 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9460 	 *	    u64 flags);
9461 	 * callback_fn(u32 index, void *callback_ctx);
9462 	 */
9463 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9464 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9465 
9466 	/* unused */
9467 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9468 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9469 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9470 
9471 	callee->in_callback_fn = true;
9472 	callee->callback_ret_range = tnum_range(0, 1);
9473 	return 0;
9474 }
9475 
9476 static int set_timer_callback_state(struct bpf_verifier_env *env,
9477 				    struct bpf_func_state *caller,
9478 				    struct bpf_func_state *callee,
9479 				    int insn_idx)
9480 {
9481 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9482 
9483 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9484 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9485 	 */
9486 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9487 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9488 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9489 
9490 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9491 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9492 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9493 
9494 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9495 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9496 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9497 
9498 	/* unused */
9499 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9500 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9501 	callee->in_async_callback_fn = true;
9502 	callee->callback_ret_range = tnum_range(0, 1);
9503 	return 0;
9504 }
9505 
9506 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9507 				       struct bpf_func_state *caller,
9508 				       struct bpf_func_state *callee,
9509 				       int insn_idx)
9510 {
9511 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9512 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9513 	 * (callback_fn)(struct task_struct *task,
9514 	 *               struct vm_area_struct *vma, void *callback_ctx);
9515 	 */
9516 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9517 
9518 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9519 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9520 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9521 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9522 
9523 	/* pointer to stack or null */
9524 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9525 
9526 	/* unused */
9527 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9528 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9529 	callee->in_callback_fn = true;
9530 	callee->callback_ret_range = tnum_range(0, 1);
9531 	return 0;
9532 }
9533 
9534 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9535 					   struct bpf_func_state *caller,
9536 					   struct bpf_func_state *callee,
9537 					   int insn_idx)
9538 {
9539 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9540 	 *			  callback_ctx, u64 flags);
9541 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9542 	 */
9543 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9544 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9545 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9546 
9547 	/* unused */
9548 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9549 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9550 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9551 
9552 	callee->in_callback_fn = true;
9553 	callee->callback_ret_range = tnum_range(0, 1);
9554 	return 0;
9555 }
9556 
9557 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9558 					 struct bpf_func_state *caller,
9559 					 struct bpf_func_state *callee,
9560 					 int insn_idx)
9561 {
9562 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9563 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9564 	 *
9565 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9566 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9567 	 * by this point, so look at 'root'
9568 	 */
9569 	struct btf_field *field;
9570 
9571 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9572 				      BPF_RB_ROOT);
9573 	if (!field || !field->graph_root.value_btf_id)
9574 		return -EFAULT;
9575 
9576 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9577 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9578 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9579 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9580 
9581 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9582 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9583 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9584 	callee->in_callback_fn = true;
9585 	callee->callback_ret_range = tnum_range(0, 1);
9586 	return 0;
9587 }
9588 
9589 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9590 
9591 /* Are we currently verifying the callback for a rbtree helper that must
9592  * be called with lock held? If so, no need to complain about unreleased
9593  * lock
9594  */
9595 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9596 {
9597 	struct bpf_verifier_state *state = env->cur_state;
9598 	struct bpf_insn *insn = env->prog->insnsi;
9599 	struct bpf_func_state *callee;
9600 	int kfunc_btf_id;
9601 
9602 	if (!state->curframe)
9603 		return false;
9604 
9605 	callee = state->frame[state->curframe];
9606 
9607 	if (!callee->in_callback_fn)
9608 		return false;
9609 
9610 	kfunc_btf_id = insn[callee->callsite].imm;
9611 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9612 }
9613 
9614 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9615 {
9616 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9617 	struct bpf_func_state *caller, *callee;
9618 	struct bpf_reg_state *r0;
9619 	bool in_callback_fn;
9620 	int err;
9621 
9622 	callee = state->frame[state->curframe];
9623 	r0 = &callee->regs[BPF_REG_0];
9624 	if (r0->type == PTR_TO_STACK) {
9625 		/* technically it's ok to return caller's stack pointer
9626 		 * (or caller's caller's pointer) back to the caller,
9627 		 * since these pointers are valid. Only current stack
9628 		 * pointer will be invalid as soon as function exits,
9629 		 * but let's be conservative
9630 		 */
9631 		verbose(env, "cannot return stack pointer to the caller\n");
9632 		return -EINVAL;
9633 	}
9634 
9635 	caller = state->frame[state->curframe - 1];
9636 	if (callee->in_callback_fn) {
9637 		/* enforce R0 return value range [0, 1]. */
9638 		struct tnum range = callee->callback_ret_range;
9639 
9640 		if (r0->type != SCALAR_VALUE) {
9641 			verbose(env, "R0 not a scalar value\n");
9642 			return -EACCES;
9643 		}
9644 
9645 		/* we are going to rely on register's precise value */
9646 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9647 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9648 		if (err)
9649 			return err;
9650 
9651 		if (!tnum_in(range, r0->var_off)) {
9652 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9653 			return -EINVAL;
9654 		}
9655 		if (!calls_callback(env, callee->callsite)) {
9656 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9657 				*insn_idx, callee->callsite);
9658 			return -EFAULT;
9659 		}
9660 	} else {
9661 		/* return to the caller whatever r0 had in the callee */
9662 		caller->regs[BPF_REG_0] = *r0;
9663 	}
9664 
9665 	/* callback_fn frame should have released its own additions to parent's
9666 	 * reference state at this point, or check_reference_leak would
9667 	 * complain, hence it must be the same as the caller. There is no need
9668 	 * to copy it back.
9669 	 */
9670 	if (!callee->in_callback_fn) {
9671 		/* Transfer references to the caller */
9672 		err = copy_reference_state(caller, callee);
9673 		if (err)
9674 			return err;
9675 	}
9676 
9677 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9678 	 * there function call logic would reschedule callback visit. If iteration
9679 	 * converges is_state_visited() would prune that visit eventually.
9680 	 */
9681 	in_callback_fn = callee->in_callback_fn;
9682 	if (in_callback_fn)
9683 		*insn_idx = callee->callsite;
9684 	else
9685 		*insn_idx = callee->callsite + 1;
9686 
9687 	if (env->log.level & BPF_LOG_LEVEL) {
9688 		verbose(env, "returning from callee:\n");
9689 		print_verifier_state(env, callee, true);
9690 		verbose(env, "to caller at %d:\n", *insn_idx);
9691 		print_verifier_state(env, caller, true);
9692 	}
9693 	/* clear everything in the callee */
9694 	free_func_state(callee);
9695 	state->frame[state->curframe--] = NULL;
9696 
9697 	/* for callbacks widen imprecise scalars to make programs like below verify:
9698 	 *
9699 	 *   struct ctx { int i; }
9700 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9701 	 *   ...
9702 	 *   struct ctx = { .i = 0; }
9703 	 *   bpf_loop(100, cb, &ctx, 0);
9704 	 *
9705 	 * This is similar to what is done in process_iter_next_call() for open
9706 	 * coded iterators.
9707 	 */
9708 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9709 	if (prev_st) {
9710 		err = widen_imprecise_scalars(env, prev_st, state);
9711 		if (err)
9712 			return err;
9713 	}
9714 	return 0;
9715 }
9716 
9717 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9718 				   int func_id,
9719 				   struct bpf_call_arg_meta *meta)
9720 {
9721 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9722 
9723 	if (ret_type != RET_INTEGER)
9724 		return;
9725 
9726 	switch (func_id) {
9727 	case BPF_FUNC_get_stack:
9728 	case BPF_FUNC_get_task_stack:
9729 	case BPF_FUNC_probe_read_str:
9730 	case BPF_FUNC_probe_read_kernel_str:
9731 	case BPF_FUNC_probe_read_user_str:
9732 		ret_reg->smax_value = meta->msize_max_value;
9733 		ret_reg->s32_max_value = meta->msize_max_value;
9734 		ret_reg->smin_value = -MAX_ERRNO;
9735 		ret_reg->s32_min_value = -MAX_ERRNO;
9736 		reg_bounds_sync(ret_reg);
9737 		break;
9738 	case BPF_FUNC_get_smp_processor_id:
9739 		ret_reg->umax_value = nr_cpu_ids - 1;
9740 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9741 		ret_reg->smax_value = nr_cpu_ids - 1;
9742 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9743 		ret_reg->umin_value = 0;
9744 		ret_reg->u32_min_value = 0;
9745 		ret_reg->smin_value = 0;
9746 		ret_reg->s32_min_value = 0;
9747 		reg_bounds_sync(ret_reg);
9748 		break;
9749 	}
9750 }
9751 
9752 static int
9753 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9754 		int func_id, int insn_idx)
9755 {
9756 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9757 	struct bpf_map *map = meta->map_ptr;
9758 
9759 	if (func_id != BPF_FUNC_tail_call &&
9760 	    func_id != BPF_FUNC_map_lookup_elem &&
9761 	    func_id != BPF_FUNC_map_update_elem &&
9762 	    func_id != BPF_FUNC_map_delete_elem &&
9763 	    func_id != BPF_FUNC_map_push_elem &&
9764 	    func_id != BPF_FUNC_map_pop_elem &&
9765 	    func_id != BPF_FUNC_map_peek_elem &&
9766 	    func_id != BPF_FUNC_for_each_map_elem &&
9767 	    func_id != BPF_FUNC_redirect_map &&
9768 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9769 		return 0;
9770 
9771 	if (map == NULL) {
9772 		verbose(env, "kernel subsystem misconfigured verifier\n");
9773 		return -EINVAL;
9774 	}
9775 
9776 	/* In case of read-only, some additional restrictions
9777 	 * need to be applied in order to prevent altering the
9778 	 * state of the map from program side.
9779 	 */
9780 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9781 	    (func_id == BPF_FUNC_map_delete_elem ||
9782 	     func_id == BPF_FUNC_map_update_elem ||
9783 	     func_id == BPF_FUNC_map_push_elem ||
9784 	     func_id == BPF_FUNC_map_pop_elem)) {
9785 		verbose(env, "write into map forbidden\n");
9786 		return -EACCES;
9787 	}
9788 
9789 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9790 		bpf_map_ptr_store(aux, meta->map_ptr,
9791 				  !meta->map_ptr->bypass_spec_v1);
9792 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9793 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9794 				  !meta->map_ptr->bypass_spec_v1);
9795 	return 0;
9796 }
9797 
9798 static int
9799 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9800 		int func_id, int insn_idx)
9801 {
9802 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9803 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9804 	struct bpf_map *map = meta->map_ptr;
9805 	u64 val, max;
9806 	int err;
9807 
9808 	if (func_id != BPF_FUNC_tail_call)
9809 		return 0;
9810 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9811 		verbose(env, "kernel subsystem misconfigured verifier\n");
9812 		return -EINVAL;
9813 	}
9814 
9815 	reg = &regs[BPF_REG_3];
9816 	val = reg->var_off.value;
9817 	max = map->max_entries;
9818 
9819 	if (!(register_is_const(reg) && val < max)) {
9820 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9821 		return 0;
9822 	}
9823 
9824 	err = mark_chain_precision(env, BPF_REG_3);
9825 	if (err)
9826 		return err;
9827 	if (bpf_map_key_unseen(aux))
9828 		bpf_map_key_store(aux, val);
9829 	else if (!bpf_map_key_poisoned(aux) &&
9830 		  bpf_map_key_immediate(aux) != val)
9831 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9832 	return 0;
9833 }
9834 
9835 static int check_reference_leak(struct bpf_verifier_env *env)
9836 {
9837 	struct bpf_func_state *state = cur_func(env);
9838 	bool refs_lingering = false;
9839 	int i;
9840 
9841 	if (state->frameno && !state->in_callback_fn)
9842 		return 0;
9843 
9844 	for (i = 0; i < state->acquired_refs; i++) {
9845 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9846 			continue;
9847 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9848 			state->refs[i].id, state->refs[i].insn_idx);
9849 		refs_lingering = true;
9850 	}
9851 	return refs_lingering ? -EINVAL : 0;
9852 }
9853 
9854 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9855 				   struct bpf_reg_state *regs)
9856 {
9857 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9858 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9859 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9860 	struct bpf_bprintf_data data = {};
9861 	int err, fmt_map_off, num_args;
9862 	u64 fmt_addr;
9863 	char *fmt;
9864 
9865 	/* data must be an array of u64 */
9866 	if (data_len_reg->var_off.value % 8)
9867 		return -EINVAL;
9868 	num_args = data_len_reg->var_off.value / 8;
9869 
9870 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9871 	 * and map_direct_value_addr is set.
9872 	 */
9873 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9874 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9875 						  fmt_map_off);
9876 	if (err) {
9877 		verbose(env, "verifier bug\n");
9878 		return -EFAULT;
9879 	}
9880 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9881 
9882 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9883 	 * can focus on validating the format specifiers.
9884 	 */
9885 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9886 	if (err < 0)
9887 		verbose(env, "Invalid format string\n");
9888 
9889 	return err;
9890 }
9891 
9892 static int check_get_func_ip(struct bpf_verifier_env *env)
9893 {
9894 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9895 	int func_id = BPF_FUNC_get_func_ip;
9896 
9897 	if (type == BPF_PROG_TYPE_TRACING) {
9898 		if (!bpf_prog_has_trampoline(env->prog)) {
9899 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9900 				func_id_name(func_id), func_id);
9901 			return -ENOTSUPP;
9902 		}
9903 		return 0;
9904 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9905 		return 0;
9906 	}
9907 
9908 	verbose(env, "func %s#%d not supported for program type %d\n",
9909 		func_id_name(func_id), func_id, type);
9910 	return -ENOTSUPP;
9911 }
9912 
9913 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9914 {
9915 	return &env->insn_aux_data[env->insn_idx];
9916 }
9917 
9918 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9919 {
9920 	struct bpf_reg_state *regs = cur_regs(env);
9921 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9922 	bool reg_is_null = register_is_null(reg);
9923 
9924 	if (reg_is_null)
9925 		mark_chain_precision(env, BPF_REG_4);
9926 
9927 	return reg_is_null;
9928 }
9929 
9930 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9931 {
9932 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9933 
9934 	if (!state->initialized) {
9935 		state->initialized = 1;
9936 		state->fit_for_inline = loop_flag_is_zero(env);
9937 		state->callback_subprogno = subprogno;
9938 		return;
9939 	}
9940 
9941 	if (!state->fit_for_inline)
9942 		return;
9943 
9944 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9945 				 state->callback_subprogno == subprogno);
9946 }
9947 
9948 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9949 			     int *insn_idx_p)
9950 {
9951 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9952 	const struct bpf_func_proto *fn = NULL;
9953 	enum bpf_return_type ret_type;
9954 	enum bpf_type_flag ret_flag;
9955 	struct bpf_reg_state *regs;
9956 	struct bpf_call_arg_meta meta;
9957 	int insn_idx = *insn_idx_p;
9958 	bool changes_data;
9959 	int i, err, func_id;
9960 
9961 	/* find function prototype */
9962 	func_id = insn->imm;
9963 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9964 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9965 			func_id);
9966 		return -EINVAL;
9967 	}
9968 
9969 	if (env->ops->get_func_proto)
9970 		fn = env->ops->get_func_proto(func_id, env->prog);
9971 	if (!fn) {
9972 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9973 			func_id);
9974 		return -EINVAL;
9975 	}
9976 
9977 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9978 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9979 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9980 		return -EINVAL;
9981 	}
9982 
9983 	if (fn->allowed && !fn->allowed(env->prog)) {
9984 		verbose(env, "helper call is not allowed in probe\n");
9985 		return -EINVAL;
9986 	}
9987 
9988 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9989 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9990 		return -EINVAL;
9991 	}
9992 
9993 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9994 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9995 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9996 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9997 			func_id_name(func_id), func_id);
9998 		return -EINVAL;
9999 	}
10000 
10001 	memset(&meta, 0, sizeof(meta));
10002 	meta.pkt_access = fn->pkt_access;
10003 
10004 	err = check_func_proto(fn, func_id);
10005 	if (err) {
10006 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10007 			func_id_name(func_id), func_id);
10008 		return err;
10009 	}
10010 
10011 	if (env->cur_state->active_rcu_lock) {
10012 		if (fn->might_sleep) {
10013 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10014 				func_id_name(func_id), func_id);
10015 			return -EINVAL;
10016 		}
10017 
10018 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10019 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10020 	}
10021 
10022 	meta.func_id = func_id;
10023 	/* check args */
10024 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10025 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10026 		if (err)
10027 			return err;
10028 	}
10029 
10030 	err = record_func_map(env, &meta, func_id, insn_idx);
10031 	if (err)
10032 		return err;
10033 
10034 	err = record_func_key(env, &meta, func_id, insn_idx);
10035 	if (err)
10036 		return err;
10037 
10038 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10039 	 * is inferred from register state.
10040 	 */
10041 	for (i = 0; i < meta.access_size; i++) {
10042 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10043 				       BPF_WRITE, -1, false, false);
10044 		if (err)
10045 			return err;
10046 	}
10047 
10048 	regs = cur_regs(env);
10049 
10050 	if (meta.release_regno) {
10051 		err = -EINVAL;
10052 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10053 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10054 		 * is safe to do directly.
10055 		 */
10056 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10057 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10058 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10059 				return -EFAULT;
10060 			}
10061 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10062 		} else if (meta.ref_obj_id) {
10063 			err = release_reference(env, meta.ref_obj_id);
10064 		} else if (register_is_null(&regs[meta.release_regno])) {
10065 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10066 			 * released is NULL, which must be > R0.
10067 			 */
10068 			err = 0;
10069 		}
10070 		if (err) {
10071 			verbose(env, "func %s#%d reference has not been acquired before\n",
10072 				func_id_name(func_id), func_id);
10073 			return err;
10074 		}
10075 	}
10076 
10077 	switch (func_id) {
10078 	case BPF_FUNC_tail_call:
10079 		err = check_reference_leak(env);
10080 		if (err) {
10081 			verbose(env, "tail_call would lead to reference leak\n");
10082 			return err;
10083 		}
10084 		break;
10085 	case BPF_FUNC_get_local_storage:
10086 		/* check that flags argument in get_local_storage(map, flags) is 0,
10087 		 * this is required because get_local_storage() can't return an error.
10088 		 */
10089 		if (!register_is_null(&regs[BPF_REG_2])) {
10090 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10091 			return -EINVAL;
10092 		}
10093 		break;
10094 	case BPF_FUNC_for_each_map_elem:
10095 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10096 					 set_map_elem_callback_state);
10097 		break;
10098 	case BPF_FUNC_timer_set_callback:
10099 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10100 					 set_timer_callback_state);
10101 		break;
10102 	case BPF_FUNC_find_vma:
10103 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10104 					 set_find_vma_callback_state);
10105 		break;
10106 	case BPF_FUNC_snprintf:
10107 		err = check_bpf_snprintf_call(env, regs);
10108 		break;
10109 	case BPF_FUNC_loop:
10110 		update_loop_inline_state(env, meta.subprogno);
10111 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10112 		 * is finished, thus mark it precise.
10113 		 */
10114 		err = mark_chain_precision(env, BPF_REG_1);
10115 		if (err)
10116 			return err;
10117 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10118 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10119 						 set_loop_callback_state);
10120 		} else {
10121 			cur_func(env)->callback_depth = 0;
10122 			if (env->log.level & BPF_LOG_LEVEL2)
10123 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10124 					env->cur_state->curframe);
10125 		}
10126 		break;
10127 	case BPF_FUNC_dynptr_from_mem:
10128 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10129 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10130 				reg_type_str(env, regs[BPF_REG_1].type));
10131 			return -EACCES;
10132 		}
10133 		break;
10134 	case BPF_FUNC_set_retval:
10135 		if (prog_type == BPF_PROG_TYPE_LSM &&
10136 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10137 			if (!env->prog->aux->attach_func_proto->type) {
10138 				/* Make sure programs that attach to void
10139 				 * hooks don't try to modify return value.
10140 				 */
10141 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10142 				return -EINVAL;
10143 			}
10144 		}
10145 		break;
10146 	case BPF_FUNC_dynptr_data:
10147 	{
10148 		struct bpf_reg_state *reg;
10149 		int id, ref_obj_id;
10150 
10151 		reg = get_dynptr_arg_reg(env, fn, regs);
10152 		if (!reg)
10153 			return -EFAULT;
10154 
10155 
10156 		if (meta.dynptr_id) {
10157 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10158 			return -EFAULT;
10159 		}
10160 		if (meta.ref_obj_id) {
10161 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10162 			return -EFAULT;
10163 		}
10164 
10165 		id = dynptr_id(env, reg);
10166 		if (id < 0) {
10167 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10168 			return id;
10169 		}
10170 
10171 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10172 		if (ref_obj_id < 0) {
10173 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10174 			return ref_obj_id;
10175 		}
10176 
10177 		meta.dynptr_id = id;
10178 		meta.ref_obj_id = ref_obj_id;
10179 
10180 		break;
10181 	}
10182 	case BPF_FUNC_dynptr_write:
10183 	{
10184 		enum bpf_dynptr_type dynptr_type;
10185 		struct bpf_reg_state *reg;
10186 
10187 		reg = get_dynptr_arg_reg(env, fn, regs);
10188 		if (!reg)
10189 			return -EFAULT;
10190 
10191 		dynptr_type = dynptr_get_type(env, reg);
10192 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10193 			return -EFAULT;
10194 
10195 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10196 			/* this will trigger clear_all_pkt_pointers(), which will
10197 			 * invalidate all dynptr slices associated with the skb
10198 			 */
10199 			changes_data = true;
10200 
10201 		break;
10202 	}
10203 	case BPF_FUNC_user_ringbuf_drain:
10204 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10205 					 set_user_ringbuf_callback_state);
10206 		break;
10207 	}
10208 
10209 	if (err)
10210 		return err;
10211 
10212 	/* reset caller saved regs */
10213 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10214 		mark_reg_not_init(env, regs, caller_saved[i]);
10215 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10216 	}
10217 
10218 	/* helper call returns 64-bit value. */
10219 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10220 
10221 	/* update return register (already marked as written above) */
10222 	ret_type = fn->ret_type;
10223 	ret_flag = type_flag(ret_type);
10224 
10225 	switch (base_type(ret_type)) {
10226 	case RET_INTEGER:
10227 		/* sets type to SCALAR_VALUE */
10228 		mark_reg_unknown(env, regs, BPF_REG_0);
10229 		break;
10230 	case RET_VOID:
10231 		regs[BPF_REG_0].type = NOT_INIT;
10232 		break;
10233 	case RET_PTR_TO_MAP_VALUE:
10234 		/* There is no offset yet applied, variable or fixed */
10235 		mark_reg_known_zero(env, regs, BPF_REG_0);
10236 		/* remember map_ptr, so that check_map_access()
10237 		 * can check 'value_size' boundary of memory access
10238 		 * to map element returned from bpf_map_lookup_elem()
10239 		 */
10240 		if (meta.map_ptr == NULL) {
10241 			verbose(env,
10242 				"kernel subsystem misconfigured verifier\n");
10243 			return -EINVAL;
10244 		}
10245 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10246 		regs[BPF_REG_0].map_uid = meta.map_uid;
10247 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10248 		if (!type_may_be_null(ret_type) &&
10249 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10250 			regs[BPF_REG_0].id = ++env->id_gen;
10251 		}
10252 		break;
10253 	case RET_PTR_TO_SOCKET:
10254 		mark_reg_known_zero(env, regs, BPF_REG_0);
10255 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10256 		break;
10257 	case RET_PTR_TO_SOCK_COMMON:
10258 		mark_reg_known_zero(env, regs, BPF_REG_0);
10259 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10260 		break;
10261 	case RET_PTR_TO_TCP_SOCK:
10262 		mark_reg_known_zero(env, regs, BPF_REG_0);
10263 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10264 		break;
10265 	case RET_PTR_TO_MEM:
10266 		mark_reg_known_zero(env, regs, BPF_REG_0);
10267 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10268 		regs[BPF_REG_0].mem_size = meta.mem_size;
10269 		break;
10270 	case RET_PTR_TO_MEM_OR_BTF_ID:
10271 	{
10272 		const struct btf_type *t;
10273 
10274 		mark_reg_known_zero(env, regs, BPF_REG_0);
10275 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10276 		if (!btf_type_is_struct(t)) {
10277 			u32 tsize;
10278 			const struct btf_type *ret;
10279 			const char *tname;
10280 
10281 			/* resolve the type size of ksym. */
10282 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10283 			if (IS_ERR(ret)) {
10284 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10285 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10286 					tname, PTR_ERR(ret));
10287 				return -EINVAL;
10288 			}
10289 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10290 			regs[BPF_REG_0].mem_size = tsize;
10291 		} else {
10292 			/* MEM_RDONLY may be carried from ret_flag, but it
10293 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10294 			 * it will confuse the check of PTR_TO_BTF_ID in
10295 			 * check_mem_access().
10296 			 */
10297 			ret_flag &= ~MEM_RDONLY;
10298 
10299 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10300 			regs[BPF_REG_0].btf = meta.ret_btf;
10301 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10302 		}
10303 		break;
10304 	}
10305 	case RET_PTR_TO_BTF_ID:
10306 	{
10307 		struct btf *ret_btf;
10308 		int ret_btf_id;
10309 
10310 		mark_reg_known_zero(env, regs, BPF_REG_0);
10311 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10312 		if (func_id == BPF_FUNC_kptr_xchg) {
10313 			ret_btf = meta.kptr_field->kptr.btf;
10314 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10315 			if (!btf_is_kernel(ret_btf))
10316 				regs[BPF_REG_0].type |= MEM_ALLOC;
10317 		} else {
10318 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10319 				verbose(env, "verifier internal error:");
10320 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10321 					func_id_name(func_id));
10322 				return -EINVAL;
10323 			}
10324 			ret_btf = btf_vmlinux;
10325 			ret_btf_id = *fn->ret_btf_id;
10326 		}
10327 		if (ret_btf_id == 0) {
10328 			verbose(env, "invalid return type %u of func %s#%d\n",
10329 				base_type(ret_type), func_id_name(func_id),
10330 				func_id);
10331 			return -EINVAL;
10332 		}
10333 		regs[BPF_REG_0].btf = ret_btf;
10334 		regs[BPF_REG_0].btf_id = ret_btf_id;
10335 		break;
10336 	}
10337 	default:
10338 		verbose(env, "unknown return type %u of func %s#%d\n",
10339 			base_type(ret_type), func_id_name(func_id), func_id);
10340 		return -EINVAL;
10341 	}
10342 
10343 	if (type_may_be_null(regs[BPF_REG_0].type))
10344 		regs[BPF_REG_0].id = ++env->id_gen;
10345 
10346 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10347 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10348 			func_id_name(func_id), func_id);
10349 		return -EFAULT;
10350 	}
10351 
10352 	if (is_dynptr_ref_function(func_id))
10353 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10354 
10355 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10356 		/* For release_reference() */
10357 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10358 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10359 		int id = acquire_reference_state(env, insn_idx);
10360 
10361 		if (id < 0)
10362 			return id;
10363 		/* For mark_ptr_or_null_reg() */
10364 		regs[BPF_REG_0].id = id;
10365 		/* For release_reference() */
10366 		regs[BPF_REG_0].ref_obj_id = id;
10367 	}
10368 
10369 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10370 
10371 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10372 	if (err)
10373 		return err;
10374 
10375 	if ((func_id == BPF_FUNC_get_stack ||
10376 	     func_id == BPF_FUNC_get_task_stack) &&
10377 	    !env->prog->has_callchain_buf) {
10378 		const char *err_str;
10379 
10380 #ifdef CONFIG_PERF_EVENTS
10381 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10382 		err_str = "cannot get callchain buffer for func %s#%d\n";
10383 #else
10384 		err = -ENOTSUPP;
10385 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10386 #endif
10387 		if (err) {
10388 			verbose(env, err_str, func_id_name(func_id), func_id);
10389 			return err;
10390 		}
10391 
10392 		env->prog->has_callchain_buf = true;
10393 	}
10394 
10395 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10396 		env->prog->call_get_stack = true;
10397 
10398 	if (func_id == BPF_FUNC_get_func_ip) {
10399 		if (check_get_func_ip(env))
10400 			return -ENOTSUPP;
10401 		env->prog->call_get_func_ip = true;
10402 	}
10403 
10404 	if (changes_data)
10405 		clear_all_pkt_pointers(env);
10406 	return 0;
10407 }
10408 
10409 /* mark_btf_func_reg_size() is used when the reg size is determined by
10410  * the BTF func_proto's return value size and argument.
10411  */
10412 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10413 				   size_t reg_size)
10414 {
10415 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10416 
10417 	if (regno == BPF_REG_0) {
10418 		/* Function return value */
10419 		reg->live |= REG_LIVE_WRITTEN;
10420 		reg->subreg_def = reg_size == sizeof(u64) ?
10421 			DEF_NOT_SUBREG : env->insn_idx + 1;
10422 	} else {
10423 		/* Function argument */
10424 		if (reg_size == sizeof(u64)) {
10425 			mark_insn_zext(env, reg);
10426 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10427 		} else {
10428 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10429 		}
10430 	}
10431 }
10432 
10433 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10434 {
10435 	return meta->kfunc_flags & KF_ACQUIRE;
10436 }
10437 
10438 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10439 {
10440 	return meta->kfunc_flags & KF_RELEASE;
10441 }
10442 
10443 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10444 {
10445 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10446 }
10447 
10448 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10449 {
10450 	return meta->kfunc_flags & KF_SLEEPABLE;
10451 }
10452 
10453 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10454 {
10455 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10456 }
10457 
10458 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10459 {
10460 	return meta->kfunc_flags & KF_RCU;
10461 }
10462 
10463 static bool __kfunc_param_match_suffix(const struct btf *btf,
10464 				       const struct btf_param *arg,
10465 				       const char *suffix)
10466 {
10467 	int suffix_len = strlen(suffix), len;
10468 	const char *param_name;
10469 
10470 	/* In the future, this can be ported to use BTF tagging */
10471 	param_name = btf_name_by_offset(btf, arg->name_off);
10472 	if (str_is_empty(param_name))
10473 		return false;
10474 	len = strlen(param_name);
10475 	if (len < suffix_len)
10476 		return false;
10477 	param_name += len - suffix_len;
10478 	return !strncmp(param_name, suffix, suffix_len);
10479 }
10480 
10481 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10482 				  const struct btf_param *arg,
10483 				  const struct bpf_reg_state *reg)
10484 {
10485 	const struct btf_type *t;
10486 
10487 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10488 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10489 		return false;
10490 
10491 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10492 }
10493 
10494 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10495 					const struct btf_param *arg,
10496 					const struct bpf_reg_state *reg)
10497 {
10498 	const struct btf_type *t;
10499 
10500 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10501 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10502 		return false;
10503 
10504 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10505 }
10506 
10507 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10508 {
10509 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10510 }
10511 
10512 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10513 {
10514 	return __kfunc_param_match_suffix(btf, arg, "__k");
10515 }
10516 
10517 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10518 {
10519 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10520 }
10521 
10522 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10523 {
10524 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10525 }
10526 
10527 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10528 {
10529 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10530 }
10531 
10532 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10533 {
10534 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10535 }
10536 
10537 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10538 					  const struct btf_param *arg,
10539 					  const char *name)
10540 {
10541 	int len, target_len = strlen(name);
10542 	const char *param_name;
10543 
10544 	param_name = btf_name_by_offset(btf, arg->name_off);
10545 	if (str_is_empty(param_name))
10546 		return false;
10547 	len = strlen(param_name);
10548 	if (len != target_len)
10549 		return false;
10550 	if (strcmp(param_name, name))
10551 		return false;
10552 
10553 	return true;
10554 }
10555 
10556 enum {
10557 	KF_ARG_DYNPTR_ID,
10558 	KF_ARG_LIST_HEAD_ID,
10559 	KF_ARG_LIST_NODE_ID,
10560 	KF_ARG_RB_ROOT_ID,
10561 	KF_ARG_RB_NODE_ID,
10562 };
10563 
10564 BTF_ID_LIST(kf_arg_btf_ids)
10565 BTF_ID(struct, bpf_dynptr_kern)
10566 BTF_ID(struct, bpf_list_head)
10567 BTF_ID(struct, bpf_list_node)
10568 BTF_ID(struct, bpf_rb_root)
10569 BTF_ID(struct, bpf_rb_node)
10570 
10571 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10572 				    const struct btf_param *arg, int type)
10573 {
10574 	const struct btf_type *t;
10575 	u32 res_id;
10576 
10577 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10578 	if (!t)
10579 		return false;
10580 	if (!btf_type_is_ptr(t))
10581 		return false;
10582 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10583 	if (!t)
10584 		return false;
10585 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10586 }
10587 
10588 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10589 {
10590 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10591 }
10592 
10593 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10594 {
10595 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10596 }
10597 
10598 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10599 {
10600 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10601 }
10602 
10603 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10604 {
10605 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10606 }
10607 
10608 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10609 {
10610 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10611 }
10612 
10613 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10614 				  const struct btf_param *arg)
10615 {
10616 	const struct btf_type *t;
10617 
10618 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10619 	if (!t)
10620 		return false;
10621 
10622 	return true;
10623 }
10624 
10625 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10626 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10627 					const struct btf *btf,
10628 					const struct btf_type *t, int rec)
10629 {
10630 	const struct btf_type *member_type;
10631 	const struct btf_member *member;
10632 	u32 i;
10633 
10634 	if (!btf_type_is_struct(t))
10635 		return false;
10636 
10637 	for_each_member(i, t, member) {
10638 		const struct btf_array *array;
10639 
10640 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10641 		if (btf_type_is_struct(member_type)) {
10642 			if (rec >= 3) {
10643 				verbose(env, "max struct nesting depth exceeded\n");
10644 				return false;
10645 			}
10646 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10647 				return false;
10648 			continue;
10649 		}
10650 		if (btf_type_is_array(member_type)) {
10651 			array = btf_array(member_type);
10652 			if (!array->nelems)
10653 				return false;
10654 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10655 			if (!btf_type_is_scalar(member_type))
10656 				return false;
10657 			continue;
10658 		}
10659 		if (!btf_type_is_scalar(member_type))
10660 			return false;
10661 	}
10662 	return true;
10663 }
10664 
10665 enum kfunc_ptr_arg_type {
10666 	KF_ARG_PTR_TO_CTX,
10667 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10668 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10669 	KF_ARG_PTR_TO_DYNPTR,
10670 	KF_ARG_PTR_TO_ITER,
10671 	KF_ARG_PTR_TO_LIST_HEAD,
10672 	KF_ARG_PTR_TO_LIST_NODE,
10673 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10674 	KF_ARG_PTR_TO_MEM,
10675 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10676 	KF_ARG_PTR_TO_CALLBACK,
10677 	KF_ARG_PTR_TO_RB_ROOT,
10678 	KF_ARG_PTR_TO_RB_NODE,
10679 };
10680 
10681 enum special_kfunc_type {
10682 	KF_bpf_obj_new_impl,
10683 	KF_bpf_obj_drop_impl,
10684 	KF_bpf_refcount_acquire_impl,
10685 	KF_bpf_list_push_front_impl,
10686 	KF_bpf_list_push_back_impl,
10687 	KF_bpf_list_pop_front,
10688 	KF_bpf_list_pop_back,
10689 	KF_bpf_cast_to_kern_ctx,
10690 	KF_bpf_rdonly_cast,
10691 	KF_bpf_rcu_read_lock,
10692 	KF_bpf_rcu_read_unlock,
10693 	KF_bpf_rbtree_remove,
10694 	KF_bpf_rbtree_add_impl,
10695 	KF_bpf_rbtree_first,
10696 	KF_bpf_dynptr_from_skb,
10697 	KF_bpf_dynptr_from_xdp,
10698 	KF_bpf_dynptr_slice,
10699 	KF_bpf_dynptr_slice_rdwr,
10700 	KF_bpf_dynptr_clone,
10701 };
10702 
10703 BTF_SET_START(special_kfunc_set)
10704 BTF_ID(func, bpf_obj_new_impl)
10705 BTF_ID(func, bpf_obj_drop_impl)
10706 BTF_ID(func, bpf_refcount_acquire_impl)
10707 BTF_ID(func, bpf_list_push_front_impl)
10708 BTF_ID(func, bpf_list_push_back_impl)
10709 BTF_ID(func, bpf_list_pop_front)
10710 BTF_ID(func, bpf_list_pop_back)
10711 BTF_ID(func, bpf_cast_to_kern_ctx)
10712 BTF_ID(func, bpf_rdonly_cast)
10713 BTF_ID(func, bpf_rbtree_remove)
10714 BTF_ID(func, bpf_rbtree_add_impl)
10715 BTF_ID(func, bpf_rbtree_first)
10716 BTF_ID(func, bpf_dynptr_from_skb)
10717 BTF_ID(func, bpf_dynptr_from_xdp)
10718 BTF_ID(func, bpf_dynptr_slice)
10719 BTF_ID(func, bpf_dynptr_slice_rdwr)
10720 BTF_ID(func, bpf_dynptr_clone)
10721 BTF_SET_END(special_kfunc_set)
10722 
10723 BTF_ID_LIST(special_kfunc_list)
10724 BTF_ID(func, bpf_obj_new_impl)
10725 BTF_ID(func, bpf_obj_drop_impl)
10726 BTF_ID(func, bpf_refcount_acquire_impl)
10727 BTF_ID(func, bpf_list_push_front_impl)
10728 BTF_ID(func, bpf_list_push_back_impl)
10729 BTF_ID(func, bpf_list_pop_front)
10730 BTF_ID(func, bpf_list_pop_back)
10731 BTF_ID(func, bpf_cast_to_kern_ctx)
10732 BTF_ID(func, bpf_rdonly_cast)
10733 BTF_ID(func, bpf_rcu_read_lock)
10734 BTF_ID(func, bpf_rcu_read_unlock)
10735 BTF_ID(func, bpf_rbtree_remove)
10736 BTF_ID(func, bpf_rbtree_add_impl)
10737 BTF_ID(func, bpf_rbtree_first)
10738 BTF_ID(func, bpf_dynptr_from_skb)
10739 BTF_ID(func, bpf_dynptr_from_xdp)
10740 BTF_ID(func, bpf_dynptr_slice)
10741 BTF_ID(func, bpf_dynptr_slice_rdwr)
10742 BTF_ID(func, bpf_dynptr_clone)
10743 
10744 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10745 {
10746 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10747 	    meta->arg_owning_ref) {
10748 		return false;
10749 	}
10750 
10751 	return meta->kfunc_flags & KF_RET_NULL;
10752 }
10753 
10754 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10755 {
10756 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10757 }
10758 
10759 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10760 {
10761 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10762 }
10763 
10764 static enum kfunc_ptr_arg_type
10765 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10766 		       struct bpf_kfunc_call_arg_meta *meta,
10767 		       const struct btf_type *t, const struct btf_type *ref_t,
10768 		       const char *ref_tname, const struct btf_param *args,
10769 		       int argno, int nargs)
10770 {
10771 	u32 regno = argno + 1;
10772 	struct bpf_reg_state *regs = cur_regs(env);
10773 	struct bpf_reg_state *reg = &regs[regno];
10774 	bool arg_mem_size = false;
10775 
10776 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10777 		return KF_ARG_PTR_TO_CTX;
10778 
10779 	/* In this function, we verify the kfunc's BTF as per the argument type,
10780 	 * leaving the rest of the verification with respect to the register
10781 	 * type to our caller. When a set of conditions hold in the BTF type of
10782 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10783 	 */
10784 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10785 		return KF_ARG_PTR_TO_CTX;
10786 
10787 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10788 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10789 
10790 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10791 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10792 
10793 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10794 		return KF_ARG_PTR_TO_DYNPTR;
10795 
10796 	if (is_kfunc_arg_iter(meta, argno))
10797 		return KF_ARG_PTR_TO_ITER;
10798 
10799 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10800 		return KF_ARG_PTR_TO_LIST_HEAD;
10801 
10802 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10803 		return KF_ARG_PTR_TO_LIST_NODE;
10804 
10805 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10806 		return KF_ARG_PTR_TO_RB_ROOT;
10807 
10808 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10809 		return KF_ARG_PTR_TO_RB_NODE;
10810 
10811 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10812 		if (!btf_type_is_struct(ref_t)) {
10813 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10814 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10815 			return -EINVAL;
10816 		}
10817 		return KF_ARG_PTR_TO_BTF_ID;
10818 	}
10819 
10820 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10821 		return KF_ARG_PTR_TO_CALLBACK;
10822 
10823 
10824 	if (argno + 1 < nargs &&
10825 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10826 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10827 		arg_mem_size = true;
10828 
10829 	/* This is the catch all argument type of register types supported by
10830 	 * check_helper_mem_access. However, we only allow when argument type is
10831 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10832 	 * arg_mem_size is true, the pointer can be void *.
10833 	 */
10834 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10835 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10836 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10837 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10838 		return -EINVAL;
10839 	}
10840 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10841 }
10842 
10843 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10844 					struct bpf_reg_state *reg,
10845 					const struct btf_type *ref_t,
10846 					const char *ref_tname, u32 ref_id,
10847 					struct bpf_kfunc_call_arg_meta *meta,
10848 					int argno)
10849 {
10850 	const struct btf_type *reg_ref_t;
10851 	bool strict_type_match = false;
10852 	const struct btf *reg_btf;
10853 	const char *reg_ref_tname;
10854 	u32 reg_ref_id;
10855 
10856 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10857 		reg_btf = reg->btf;
10858 		reg_ref_id = reg->btf_id;
10859 	} else {
10860 		reg_btf = btf_vmlinux;
10861 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10862 	}
10863 
10864 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10865 	 * or releasing a reference, or are no-cast aliases. We do _not_
10866 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10867 	 * as we want to enable BPF programs to pass types that are bitwise
10868 	 * equivalent without forcing them to explicitly cast with something
10869 	 * like bpf_cast_to_kern_ctx().
10870 	 *
10871 	 * For example, say we had a type like the following:
10872 	 *
10873 	 * struct bpf_cpumask {
10874 	 *	cpumask_t cpumask;
10875 	 *	refcount_t usage;
10876 	 * };
10877 	 *
10878 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10879 	 * to a struct cpumask, so it would be safe to pass a struct
10880 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10881 	 *
10882 	 * The philosophy here is similar to how we allow scalars of different
10883 	 * types to be passed to kfuncs as long as the size is the same. The
10884 	 * only difference here is that we're simply allowing
10885 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10886 	 * resolve types.
10887 	 */
10888 	if (is_kfunc_acquire(meta) ||
10889 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10890 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10891 		strict_type_match = true;
10892 
10893 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10894 
10895 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10896 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10897 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10898 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10899 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10900 			btf_type_str(reg_ref_t), reg_ref_tname);
10901 		return -EINVAL;
10902 	}
10903 	return 0;
10904 }
10905 
10906 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10907 {
10908 	struct bpf_verifier_state *state = env->cur_state;
10909 	struct btf_record *rec = reg_btf_record(reg);
10910 
10911 	if (!state->active_lock.ptr) {
10912 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10913 		return -EFAULT;
10914 	}
10915 
10916 	if (type_flag(reg->type) & NON_OWN_REF) {
10917 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10918 		return -EFAULT;
10919 	}
10920 
10921 	reg->type |= NON_OWN_REF;
10922 	if (rec->refcount_off >= 0)
10923 		reg->type |= MEM_RCU;
10924 
10925 	return 0;
10926 }
10927 
10928 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10929 {
10930 	struct bpf_func_state *state, *unused;
10931 	struct bpf_reg_state *reg;
10932 	int i;
10933 
10934 	state = cur_func(env);
10935 
10936 	if (!ref_obj_id) {
10937 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10938 			     "owning -> non-owning conversion\n");
10939 		return -EFAULT;
10940 	}
10941 
10942 	for (i = 0; i < state->acquired_refs; i++) {
10943 		if (state->refs[i].id != ref_obj_id)
10944 			continue;
10945 
10946 		/* Clear ref_obj_id here so release_reference doesn't clobber
10947 		 * the whole reg
10948 		 */
10949 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10950 			if (reg->ref_obj_id == ref_obj_id) {
10951 				reg->ref_obj_id = 0;
10952 				ref_set_non_owning(env, reg);
10953 			}
10954 		}));
10955 		return 0;
10956 	}
10957 
10958 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10959 	return -EFAULT;
10960 }
10961 
10962 /* Implementation details:
10963  *
10964  * Each register points to some region of memory, which we define as an
10965  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10966  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10967  * allocation. The lock and the data it protects are colocated in the same
10968  * memory region.
10969  *
10970  * Hence, everytime a register holds a pointer value pointing to such
10971  * allocation, the verifier preserves a unique reg->id for it.
10972  *
10973  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10974  * bpf_spin_lock is called.
10975  *
10976  * To enable this, lock state in the verifier captures two values:
10977  *	active_lock.ptr = Register's type specific pointer
10978  *	active_lock.id  = A unique ID for each register pointer value
10979  *
10980  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10981  * supported register types.
10982  *
10983  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10984  * allocated objects is the reg->btf pointer.
10985  *
10986  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10987  * can establish the provenance of the map value statically for each distinct
10988  * lookup into such maps. They always contain a single map value hence unique
10989  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10990  *
10991  * So, in case of global variables, they use array maps with max_entries = 1,
10992  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10993  * into the same map value as max_entries is 1, as described above).
10994  *
10995  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10996  * outer map pointer (in verifier context), but each lookup into an inner map
10997  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10998  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10999  * will get different reg->id assigned to each lookup, hence different
11000  * active_lock.id.
11001  *
11002  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11003  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11004  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11005  */
11006 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11007 {
11008 	void *ptr;
11009 	u32 id;
11010 
11011 	switch ((int)reg->type) {
11012 	case PTR_TO_MAP_VALUE:
11013 		ptr = reg->map_ptr;
11014 		break;
11015 	case PTR_TO_BTF_ID | MEM_ALLOC:
11016 		ptr = reg->btf;
11017 		break;
11018 	default:
11019 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11020 		return -EFAULT;
11021 	}
11022 	id = reg->id;
11023 
11024 	if (!env->cur_state->active_lock.ptr)
11025 		return -EINVAL;
11026 	if (env->cur_state->active_lock.ptr != ptr ||
11027 	    env->cur_state->active_lock.id != id) {
11028 		verbose(env, "held lock and object are not in the same allocation\n");
11029 		return -EINVAL;
11030 	}
11031 	return 0;
11032 }
11033 
11034 static bool is_bpf_list_api_kfunc(u32 btf_id)
11035 {
11036 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11037 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11038 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11039 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11040 }
11041 
11042 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11043 {
11044 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11045 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11046 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11047 }
11048 
11049 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11050 {
11051 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11052 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11053 }
11054 
11055 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11056 {
11057 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11058 }
11059 
11060 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11061 {
11062 	return is_bpf_rbtree_api_kfunc(btf_id);
11063 }
11064 
11065 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11066 					  enum btf_field_type head_field_type,
11067 					  u32 kfunc_btf_id)
11068 {
11069 	bool ret;
11070 
11071 	switch (head_field_type) {
11072 	case BPF_LIST_HEAD:
11073 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11074 		break;
11075 	case BPF_RB_ROOT:
11076 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11077 		break;
11078 	default:
11079 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11080 			btf_field_type_name(head_field_type));
11081 		return false;
11082 	}
11083 
11084 	if (!ret)
11085 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11086 			btf_field_type_name(head_field_type));
11087 	return ret;
11088 }
11089 
11090 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11091 					  enum btf_field_type node_field_type,
11092 					  u32 kfunc_btf_id)
11093 {
11094 	bool ret;
11095 
11096 	switch (node_field_type) {
11097 	case BPF_LIST_NODE:
11098 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11099 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11100 		break;
11101 	case BPF_RB_NODE:
11102 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11103 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11104 		break;
11105 	default:
11106 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11107 			btf_field_type_name(node_field_type));
11108 		return false;
11109 	}
11110 
11111 	if (!ret)
11112 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11113 			btf_field_type_name(node_field_type));
11114 	return ret;
11115 }
11116 
11117 static int
11118 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11119 				   struct bpf_reg_state *reg, u32 regno,
11120 				   struct bpf_kfunc_call_arg_meta *meta,
11121 				   enum btf_field_type head_field_type,
11122 				   struct btf_field **head_field)
11123 {
11124 	const char *head_type_name;
11125 	struct btf_field *field;
11126 	struct btf_record *rec;
11127 	u32 head_off;
11128 
11129 	if (meta->btf != btf_vmlinux) {
11130 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11131 		return -EFAULT;
11132 	}
11133 
11134 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11135 		return -EFAULT;
11136 
11137 	head_type_name = btf_field_type_name(head_field_type);
11138 	if (!tnum_is_const(reg->var_off)) {
11139 		verbose(env,
11140 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11141 			regno, head_type_name);
11142 		return -EINVAL;
11143 	}
11144 
11145 	rec = reg_btf_record(reg);
11146 	head_off = reg->off + reg->var_off.value;
11147 	field = btf_record_find(rec, head_off, head_field_type);
11148 	if (!field) {
11149 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11150 		return -EINVAL;
11151 	}
11152 
11153 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11154 	if (check_reg_allocation_locked(env, reg)) {
11155 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11156 			rec->spin_lock_off, head_type_name);
11157 		return -EINVAL;
11158 	}
11159 
11160 	if (*head_field) {
11161 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11162 		return -EFAULT;
11163 	}
11164 	*head_field = field;
11165 	return 0;
11166 }
11167 
11168 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11169 					   struct bpf_reg_state *reg, u32 regno,
11170 					   struct bpf_kfunc_call_arg_meta *meta)
11171 {
11172 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11173 							  &meta->arg_list_head.field);
11174 }
11175 
11176 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11177 					     struct bpf_reg_state *reg, u32 regno,
11178 					     struct bpf_kfunc_call_arg_meta *meta)
11179 {
11180 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11181 							  &meta->arg_rbtree_root.field);
11182 }
11183 
11184 static int
11185 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11186 				   struct bpf_reg_state *reg, u32 regno,
11187 				   struct bpf_kfunc_call_arg_meta *meta,
11188 				   enum btf_field_type head_field_type,
11189 				   enum btf_field_type node_field_type,
11190 				   struct btf_field **node_field)
11191 {
11192 	const char *node_type_name;
11193 	const struct btf_type *et, *t;
11194 	struct btf_field *field;
11195 	u32 node_off;
11196 
11197 	if (meta->btf != btf_vmlinux) {
11198 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11199 		return -EFAULT;
11200 	}
11201 
11202 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11203 		return -EFAULT;
11204 
11205 	node_type_name = btf_field_type_name(node_field_type);
11206 	if (!tnum_is_const(reg->var_off)) {
11207 		verbose(env,
11208 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11209 			regno, node_type_name);
11210 		return -EINVAL;
11211 	}
11212 
11213 	node_off = reg->off + reg->var_off.value;
11214 	field = reg_find_field_offset(reg, node_off, node_field_type);
11215 	if (!field || field->offset != node_off) {
11216 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11217 		return -EINVAL;
11218 	}
11219 
11220 	field = *node_field;
11221 
11222 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11223 	t = btf_type_by_id(reg->btf, reg->btf_id);
11224 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11225 				  field->graph_root.value_btf_id, true)) {
11226 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11227 			"in struct %s, but arg is at offset=%d in struct %s\n",
11228 			btf_field_type_name(head_field_type),
11229 			btf_field_type_name(node_field_type),
11230 			field->graph_root.node_offset,
11231 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11232 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11233 		return -EINVAL;
11234 	}
11235 	meta->arg_btf = reg->btf;
11236 	meta->arg_btf_id = reg->btf_id;
11237 
11238 	if (node_off != field->graph_root.node_offset) {
11239 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11240 			node_off, btf_field_type_name(node_field_type),
11241 			field->graph_root.node_offset,
11242 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11243 		return -EINVAL;
11244 	}
11245 
11246 	return 0;
11247 }
11248 
11249 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11250 					   struct bpf_reg_state *reg, u32 regno,
11251 					   struct bpf_kfunc_call_arg_meta *meta)
11252 {
11253 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11254 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11255 						  &meta->arg_list_head.field);
11256 }
11257 
11258 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11259 					     struct bpf_reg_state *reg, u32 regno,
11260 					     struct bpf_kfunc_call_arg_meta *meta)
11261 {
11262 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11263 						  BPF_RB_ROOT, BPF_RB_NODE,
11264 						  &meta->arg_rbtree_root.field);
11265 }
11266 
11267 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11268 			    int insn_idx)
11269 {
11270 	const char *func_name = meta->func_name, *ref_tname;
11271 	const struct btf *btf = meta->btf;
11272 	const struct btf_param *args;
11273 	struct btf_record *rec;
11274 	u32 i, nargs;
11275 	int ret;
11276 
11277 	args = (const struct btf_param *)(meta->func_proto + 1);
11278 	nargs = btf_type_vlen(meta->func_proto);
11279 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11280 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11281 			MAX_BPF_FUNC_REG_ARGS);
11282 		return -EINVAL;
11283 	}
11284 
11285 	/* Check that BTF function arguments match actual types that the
11286 	 * verifier sees.
11287 	 */
11288 	for (i = 0; i < nargs; i++) {
11289 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11290 		const struct btf_type *t, *ref_t, *resolve_ret;
11291 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11292 		u32 regno = i + 1, ref_id, type_size;
11293 		bool is_ret_buf_sz = false;
11294 		int kf_arg_type;
11295 
11296 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11297 
11298 		if (is_kfunc_arg_ignore(btf, &args[i]))
11299 			continue;
11300 
11301 		if (btf_type_is_scalar(t)) {
11302 			if (reg->type != SCALAR_VALUE) {
11303 				verbose(env, "R%d is not a scalar\n", regno);
11304 				return -EINVAL;
11305 			}
11306 
11307 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11308 				if (meta->arg_constant.found) {
11309 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11310 					return -EFAULT;
11311 				}
11312 				if (!tnum_is_const(reg->var_off)) {
11313 					verbose(env, "R%d must be a known constant\n", regno);
11314 					return -EINVAL;
11315 				}
11316 				ret = mark_chain_precision(env, regno);
11317 				if (ret < 0)
11318 					return ret;
11319 				meta->arg_constant.found = true;
11320 				meta->arg_constant.value = reg->var_off.value;
11321 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11322 				meta->r0_rdonly = true;
11323 				is_ret_buf_sz = true;
11324 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11325 				is_ret_buf_sz = true;
11326 			}
11327 
11328 			if (is_ret_buf_sz) {
11329 				if (meta->r0_size) {
11330 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11331 					return -EINVAL;
11332 				}
11333 
11334 				if (!tnum_is_const(reg->var_off)) {
11335 					verbose(env, "R%d is not a const\n", regno);
11336 					return -EINVAL;
11337 				}
11338 
11339 				meta->r0_size = reg->var_off.value;
11340 				ret = mark_chain_precision(env, regno);
11341 				if (ret)
11342 					return ret;
11343 			}
11344 			continue;
11345 		}
11346 
11347 		if (!btf_type_is_ptr(t)) {
11348 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11349 			return -EINVAL;
11350 		}
11351 
11352 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11353 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11354 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11355 			return -EACCES;
11356 		}
11357 
11358 		if (reg->ref_obj_id) {
11359 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11360 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11361 					regno, reg->ref_obj_id,
11362 					meta->ref_obj_id);
11363 				return -EFAULT;
11364 			}
11365 			meta->ref_obj_id = reg->ref_obj_id;
11366 			if (is_kfunc_release(meta))
11367 				meta->release_regno = regno;
11368 		}
11369 
11370 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11371 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11372 
11373 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11374 		if (kf_arg_type < 0)
11375 			return kf_arg_type;
11376 
11377 		switch (kf_arg_type) {
11378 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11379 		case KF_ARG_PTR_TO_BTF_ID:
11380 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11381 				break;
11382 
11383 			if (!is_trusted_reg(reg)) {
11384 				if (!is_kfunc_rcu(meta)) {
11385 					verbose(env, "R%d must be referenced or trusted\n", regno);
11386 					return -EINVAL;
11387 				}
11388 				if (!is_rcu_reg(reg)) {
11389 					verbose(env, "R%d must be a rcu pointer\n", regno);
11390 					return -EINVAL;
11391 				}
11392 			}
11393 
11394 			fallthrough;
11395 		case KF_ARG_PTR_TO_CTX:
11396 			/* Trusted arguments have the same offset checks as release arguments */
11397 			arg_type |= OBJ_RELEASE;
11398 			break;
11399 		case KF_ARG_PTR_TO_DYNPTR:
11400 		case KF_ARG_PTR_TO_ITER:
11401 		case KF_ARG_PTR_TO_LIST_HEAD:
11402 		case KF_ARG_PTR_TO_LIST_NODE:
11403 		case KF_ARG_PTR_TO_RB_ROOT:
11404 		case KF_ARG_PTR_TO_RB_NODE:
11405 		case KF_ARG_PTR_TO_MEM:
11406 		case KF_ARG_PTR_TO_MEM_SIZE:
11407 		case KF_ARG_PTR_TO_CALLBACK:
11408 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11409 			/* Trusted by default */
11410 			break;
11411 		default:
11412 			WARN_ON_ONCE(1);
11413 			return -EFAULT;
11414 		}
11415 
11416 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11417 			arg_type |= OBJ_RELEASE;
11418 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11419 		if (ret < 0)
11420 			return ret;
11421 
11422 		switch (kf_arg_type) {
11423 		case KF_ARG_PTR_TO_CTX:
11424 			if (reg->type != PTR_TO_CTX) {
11425 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11426 				return -EINVAL;
11427 			}
11428 
11429 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11430 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11431 				if (ret < 0)
11432 					return -EINVAL;
11433 				meta->ret_btf_id  = ret;
11434 			}
11435 			break;
11436 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11437 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11438 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11439 				return -EINVAL;
11440 			}
11441 			if (!reg->ref_obj_id) {
11442 				verbose(env, "allocated object must be referenced\n");
11443 				return -EINVAL;
11444 			}
11445 			if (meta->btf == btf_vmlinux &&
11446 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11447 				meta->arg_btf = reg->btf;
11448 				meta->arg_btf_id = reg->btf_id;
11449 			}
11450 			break;
11451 		case KF_ARG_PTR_TO_DYNPTR:
11452 		{
11453 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11454 			int clone_ref_obj_id = 0;
11455 
11456 			if (reg->type != PTR_TO_STACK &&
11457 			    reg->type != CONST_PTR_TO_DYNPTR) {
11458 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11459 				return -EINVAL;
11460 			}
11461 
11462 			if (reg->type == CONST_PTR_TO_DYNPTR)
11463 				dynptr_arg_type |= MEM_RDONLY;
11464 
11465 			if (is_kfunc_arg_uninit(btf, &args[i]))
11466 				dynptr_arg_type |= MEM_UNINIT;
11467 
11468 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11469 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11470 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11471 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11472 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11473 				   (dynptr_arg_type & MEM_UNINIT)) {
11474 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11475 
11476 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11477 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11478 					return -EFAULT;
11479 				}
11480 
11481 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11482 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11483 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11484 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11485 					return -EFAULT;
11486 				}
11487 			}
11488 
11489 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11490 			if (ret < 0)
11491 				return ret;
11492 
11493 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11494 				int id = dynptr_id(env, reg);
11495 
11496 				if (id < 0) {
11497 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11498 					return id;
11499 				}
11500 				meta->initialized_dynptr.id = id;
11501 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11502 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11503 			}
11504 
11505 			break;
11506 		}
11507 		case KF_ARG_PTR_TO_ITER:
11508 			ret = process_iter_arg(env, regno, insn_idx, meta);
11509 			if (ret < 0)
11510 				return ret;
11511 			break;
11512 		case KF_ARG_PTR_TO_LIST_HEAD:
11513 			if (reg->type != PTR_TO_MAP_VALUE &&
11514 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11515 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11516 				return -EINVAL;
11517 			}
11518 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11519 				verbose(env, "allocated object must be referenced\n");
11520 				return -EINVAL;
11521 			}
11522 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11523 			if (ret < 0)
11524 				return ret;
11525 			break;
11526 		case KF_ARG_PTR_TO_RB_ROOT:
11527 			if (reg->type != PTR_TO_MAP_VALUE &&
11528 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11529 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11530 				return -EINVAL;
11531 			}
11532 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11533 				verbose(env, "allocated object must be referenced\n");
11534 				return -EINVAL;
11535 			}
11536 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11537 			if (ret < 0)
11538 				return ret;
11539 			break;
11540 		case KF_ARG_PTR_TO_LIST_NODE:
11541 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11542 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11543 				return -EINVAL;
11544 			}
11545 			if (!reg->ref_obj_id) {
11546 				verbose(env, "allocated object must be referenced\n");
11547 				return -EINVAL;
11548 			}
11549 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11550 			if (ret < 0)
11551 				return ret;
11552 			break;
11553 		case KF_ARG_PTR_TO_RB_NODE:
11554 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11555 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11556 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11557 					return -EINVAL;
11558 				}
11559 				if (in_rbtree_lock_required_cb(env)) {
11560 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11561 					return -EINVAL;
11562 				}
11563 			} else {
11564 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11565 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11566 					return -EINVAL;
11567 				}
11568 				if (!reg->ref_obj_id) {
11569 					verbose(env, "allocated object must be referenced\n");
11570 					return -EINVAL;
11571 				}
11572 			}
11573 
11574 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11575 			if (ret < 0)
11576 				return ret;
11577 			break;
11578 		case KF_ARG_PTR_TO_BTF_ID:
11579 			/* Only base_type is checked, further checks are done here */
11580 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11581 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11582 			    !reg2btf_ids[base_type(reg->type)]) {
11583 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11584 				verbose(env, "expected %s or socket\n",
11585 					reg_type_str(env, base_type(reg->type) |
11586 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11587 				return -EINVAL;
11588 			}
11589 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11590 			if (ret < 0)
11591 				return ret;
11592 			break;
11593 		case KF_ARG_PTR_TO_MEM:
11594 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11595 			if (IS_ERR(resolve_ret)) {
11596 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11597 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11598 				return -EINVAL;
11599 			}
11600 			ret = check_mem_reg(env, reg, regno, type_size);
11601 			if (ret < 0)
11602 				return ret;
11603 			break;
11604 		case KF_ARG_PTR_TO_MEM_SIZE:
11605 		{
11606 			struct bpf_reg_state *buff_reg = &regs[regno];
11607 			const struct btf_param *buff_arg = &args[i];
11608 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11609 			const struct btf_param *size_arg = &args[i + 1];
11610 
11611 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11612 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11613 				if (ret < 0) {
11614 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11615 					return ret;
11616 				}
11617 			}
11618 
11619 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11620 				if (meta->arg_constant.found) {
11621 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11622 					return -EFAULT;
11623 				}
11624 				if (!tnum_is_const(size_reg->var_off)) {
11625 					verbose(env, "R%d must be a known constant\n", regno + 1);
11626 					return -EINVAL;
11627 				}
11628 				meta->arg_constant.found = true;
11629 				meta->arg_constant.value = size_reg->var_off.value;
11630 			}
11631 
11632 			/* Skip next '__sz' or '__szk' argument */
11633 			i++;
11634 			break;
11635 		}
11636 		case KF_ARG_PTR_TO_CALLBACK:
11637 			if (reg->type != PTR_TO_FUNC) {
11638 				verbose(env, "arg%d expected pointer to func\n", i);
11639 				return -EINVAL;
11640 			}
11641 			meta->subprogno = reg->subprogno;
11642 			break;
11643 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11644 			if (!type_is_ptr_alloc_obj(reg->type)) {
11645 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11646 				return -EINVAL;
11647 			}
11648 			if (!type_is_non_owning_ref(reg->type))
11649 				meta->arg_owning_ref = true;
11650 
11651 			rec = reg_btf_record(reg);
11652 			if (!rec) {
11653 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11654 				return -EFAULT;
11655 			}
11656 
11657 			if (rec->refcount_off < 0) {
11658 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11659 				return -EINVAL;
11660 			}
11661 
11662 			meta->arg_btf = reg->btf;
11663 			meta->arg_btf_id = reg->btf_id;
11664 			break;
11665 		}
11666 	}
11667 
11668 	if (is_kfunc_release(meta) && !meta->release_regno) {
11669 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11670 			func_name);
11671 		return -EINVAL;
11672 	}
11673 
11674 	return 0;
11675 }
11676 
11677 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11678 			    struct bpf_insn *insn,
11679 			    struct bpf_kfunc_call_arg_meta *meta,
11680 			    const char **kfunc_name)
11681 {
11682 	const struct btf_type *func, *func_proto;
11683 	u32 func_id, *kfunc_flags;
11684 	const char *func_name;
11685 	struct btf *desc_btf;
11686 
11687 	if (kfunc_name)
11688 		*kfunc_name = NULL;
11689 
11690 	if (!insn->imm)
11691 		return -EINVAL;
11692 
11693 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11694 	if (IS_ERR(desc_btf))
11695 		return PTR_ERR(desc_btf);
11696 
11697 	func_id = insn->imm;
11698 	func = btf_type_by_id(desc_btf, func_id);
11699 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11700 	if (kfunc_name)
11701 		*kfunc_name = func_name;
11702 	func_proto = btf_type_by_id(desc_btf, func->type);
11703 
11704 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11705 	if (!kfunc_flags) {
11706 		return -EACCES;
11707 	}
11708 
11709 	memset(meta, 0, sizeof(*meta));
11710 	meta->btf = desc_btf;
11711 	meta->func_id = func_id;
11712 	meta->kfunc_flags = *kfunc_flags;
11713 	meta->func_proto = func_proto;
11714 	meta->func_name = func_name;
11715 
11716 	return 0;
11717 }
11718 
11719 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11720 			    int *insn_idx_p)
11721 {
11722 	const struct btf_type *t, *ptr_type;
11723 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11724 	struct bpf_reg_state *regs = cur_regs(env);
11725 	const char *func_name, *ptr_type_name;
11726 	bool sleepable, rcu_lock, rcu_unlock;
11727 	struct bpf_kfunc_call_arg_meta meta;
11728 	struct bpf_insn_aux_data *insn_aux;
11729 	int err, insn_idx = *insn_idx_p;
11730 	const struct btf_param *args;
11731 	const struct btf_type *ret_t;
11732 	struct btf *desc_btf;
11733 
11734 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11735 	if (!insn->imm)
11736 		return 0;
11737 
11738 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11739 	if (err == -EACCES && func_name)
11740 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11741 	if (err)
11742 		return err;
11743 	desc_btf = meta.btf;
11744 	insn_aux = &env->insn_aux_data[insn_idx];
11745 
11746 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11747 
11748 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11749 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11750 		return -EACCES;
11751 	}
11752 
11753 	sleepable = is_kfunc_sleepable(&meta);
11754 	if (sleepable && !env->prog->aux->sleepable) {
11755 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11756 		return -EACCES;
11757 	}
11758 
11759 	/* Check the arguments */
11760 	err = check_kfunc_args(env, &meta, insn_idx);
11761 	if (err < 0)
11762 		return err;
11763 
11764 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11765 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11766 					 set_rbtree_add_callback_state);
11767 		if (err) {
11768 			verbose(env, "kfunc %s#%d failed callback verification\n",
11769 				func_name, meta.func_id);
11770 			return err;
11771 		}
11772 	}
11773 
11774 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11775 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11776 
11777 	if (env->cur_state->active_rcu_lock) {
11778 		struct bpf_func_state *state;
11779 		struct bpf_reg_state *reg;
11780 
11781 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11782 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11783 			return -EACCES;
11784 		}
11785 
11786 		if (rcu_lock) {
11787 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11788 			return -EINVAL;
11789 		} else if (rcu_unlock) {
11790 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11791 				if (reg->type & MEM_RCU) {
11792 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11793 					reg->type |= PTR_UNTRUSTED;
11794 				}
11795 			}));
11796 			env->cur_state->active_rcu_lock = false;
11797 		} else if (sleepable) {
11798 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11799 			return -EACCES;
11800 		}
11801 	} else if (rcu_lock) {
11802 		env->cur_state->active_rcu_lock = true;
11803 	} else if (rcu_unlock) {
11804 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11805 		return -EINVAL;
11806 	}
11807 
11808 	/* In case of release function, we get register number of refcounted
11809 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11810 	 */
11811 	if (meta.release_regno) {
11812 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11813 		if (err) {
11814 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11815 				func_name, meta.func_id);
11816 			return err;
11817 		}
11818 	}
11819 
11820 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11821 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11822 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11823 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11824 		insn_aux->insert_off = regs[BPF_REG_2].off;
11825 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11826 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11827 		if (err) {
11828 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11829 				func_name, meta.func_id);
11830 			return err;
11831 		}
11832 
11833 		err = release_reference(env, release_ref_obj_id);
11834 		if (err) {
11835 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11836 				func_name, meta.func_id);
11837 			return err;
11838 		}
11839 	}
11840 
11841 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11842 		mark_reg_not_init(env, regs, caller_saved[i]);
11843 
11844 	/* Check return type */
11845 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11846 
11847 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11848 		/* Only exception is bpf_obj_new_impl */
11849 		if (meta.btf != btf_vmlinux ||
11850 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11851 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11852 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11853 			return -EINVAL;
11854 		}
11855 	}
11856 
11857 	if (btf_type_is_scalar(t)) {
11858 		mark_reg_unknown(env, regs, BPF_REG_0);
11859 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11860 	} else if (btf_type_is_ptr(t)) {
11861 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11862 
11863 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11864 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11865 				struct btf *ret_btf;
11866 				u32 ret_btf_id;
11867 
11868 				if (unlikely(!bpf_global_ma_set))
11869 					return -ENOMEM;
11870 
11871 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11872 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11873 					return -EINVAL;
11874 				}
11875 
11876 				ret_btf = env->prog->aux->btf;
11877 				ret_btf_id = meta.arg_constant.value;
11878 
11879 				/* This may be NULL due to user not supplying a BTF */
11880 				if (!ret_btf) {
11881 					verbose(env, "bpf_obj_new requires prog BTF\n");
11882 					return -EINVAL;
11883 				}
11884 
11885 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11886 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11887 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11888 					return -EINVAL;
11889 				}
11890 
11891 				mark_reg_known_zero(env, regs, BPF_REG_0);
11892 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11893 				regs[BPF_REG_0].btf = ret_btf;
11894 				regs[BPF_REG_0].btf_id = ret_btf_id;
11895 
11896 				insn_aux->obj_new_size = ret_t->size;
11897 				insn_aux->kptr_struct_meta =
11898 					btf_find_struct_meta(ret_btf, ret_btf_id);
11899 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11900 				mark_reg_known_zero(env, regs, BPF_REG_0);
11901 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11902 				regs[BPF_REG_0].btf = meta.arg_btf;
11903 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11904 
11905 				insn_aux->kptr_struct_meta =
11906 					btf_find_struct_meta(meta.arg_btf,
11907 							     meta.arg_btf_id);
11908 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11909 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11910 				struct btf_field *field = meta.arg_list_head.field;
11911 
11912 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11913 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11914 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11915 				struct btf_field *field = meta.arg_rbtree_root.field;
11916 
11917 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11918 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11919 				mark_reg_known_zero(env, regs, BPF_REG_0);
11920 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11921 				regs[BPF_REG_0].btf = desc_btf;
11922 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11923 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11924 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11925 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11926 					verbose(env,
11927 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11928 					return -EINVAL;
11929 				}
11930 
11931 				mark_reg_known_zero(env, regs, BPF_REG_0);
11932 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11933 				regs[BPF_REG_0].btf = desc_btf;
11934 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11935 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11936 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11937 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11938 
11939 				mark_reg_known_zero(env, regs, BPF_REG_0);
11940 
11941 				if (!meta.arg_constant.found) {
11942 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11943 					return -EFAULT;
11944 				}
11945 
11946 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11947 
11948 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11949 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11950 
11951 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11952 					regs[BPF_REG_0].type |= MEM_RDONLY;
11953 				} else {
11954 					/* this will set env->seen_direct_write to true */
11955 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11956 						verbose(env, "the prog does not allow writes to packet data\n");
11957 						return -EINVAL;
11958 					}
11959 				}
11960 
11961 				if (!meta.initialized_dynptr.id) {
11962 					verbose(env, "verifier internal error: no dynptr id\n");
11963 					return -EFAULT;
11964 				}
11965 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11966 
11967 				/* we don't need to set BPF_REG_0's ref obj id
11968 				 * because packet slices are not refcounted (see
11969 				 * dynptr_type_refcounted)
11970 				 */
11971 			} else {
11972 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11973 					meta.func_name);
11974 				return -EFAULT;
11975 			}
11976 		} else if (!__btf_type_is_struct(ptr_type)) {
11977 			if (!meta.r0_size) {
11978 				__u32 sz;
11979 
11980 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11981 					meta.r0_size = sz;
11982 					meta.r0_rdonly = true;
11983 				}
11984 			}
11985 			if (!meta.r0_size) {
11986 				ptr_type_name = btf_name_by_offset(desc_btf,
11987 								   ptr_type->name_off);
11988 				verbose(env,
11989 					"kernel function %s returns pointer type %s %s is not supported\n",
11990 					func_name,
11991 					btf_type_str(ptr_type),
11992 					ptr_type_name);
11993 				return -EINVAL;
11994 			}
11995 
11996 			mark_reg_known_zero(env, regs, BPF_REG_0);
11997 			regs[BPF_REG_0].type = PTR_TO_MEM;
11998 			regs[BPF_REG_0].mem_size = meta.r0_size;
11999 
12000 			if (meta.r0_rdonly)
12001 				regs[BPF_REG_0].type |= MEM_RDONLY;
12002 
12003 			/* Ensures we don't access the memory after a release_reference() */
12004 			if (meta.ref_obj_id)
12005 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12006 		} else {
12007 			mark_reg_known_zero(env, regs, BPF_REG_0);
12008 			regs[BPF_REG_0].btf = desc_btf;
12009 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12010 			regs[BPF_REG_0].btf_id = ptr_type_id;
12011 
12012 			if (is_iter_next_kfunc(&meta)) {
12013 				struct bpf_reg_state *cur_iter;
12014 
12015 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12016 
12017 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12018 					regs[BPF_REG_0].type |= MEM_RCU;
12019 				else
12020 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12021 			}
12022 		}
12023 
12024 		if (is_kfunc_ret_null(&meta)) {
12025 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12026 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12027 			regs[BPF_REG_0].id = ++env->id_gen;
12028 		}
12029 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12030 		if (is_kfunc_acquire(&meta)) {
12031 			int id = acquire_reference_state(env, insn_idx);
12032 
12033 			if (id < 0)
12034 				return id;
12035 			if (is_kfunc_ret_null(&meta))
12036 				regs[BPF_REG_0].id = id;
12037 			regs[BPF_REG_0].ref_obj_id = id;
12038 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12039 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12040 		}
12041 
12042 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12043 			regs[BPF_REG_0].id = ++env->id_gen;
12044 	} else if (btf_type_is_void(t)) {
12045 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12046 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12047 				insn_aux->kptr_struct_meta =
12048 					btf_find_struct_meta(meta.arg_btf,
12049 							     meta.arg_btf_id);
12050 			}
12051 		}
12052 	}
12053 
12054 	nargs = btf_type_vlen(meta.func_proto);
12055 	args = (const struct btf_param *)(meta.func_proto + 1);
12056 	for (i = 0; i < nargs; i++) {
12057 		u32 regno = i + 1;
12058 
12059 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12060 		if (btf_type_is_ptr(t))
12061 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12062 		else
12063 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12064 			mark_btf_func_reg_size(env, regno, t->size);
12065 	}
12066 
12067 	if (is_iter_next_kfunc(&meta)) {
12068 		err = process_iter_next_call(env, insn_idx, &meta);
12069 		if (err)
12070 			return err;
12071 	}
12072 
12073 	return 0;
12074 }
12075 
12076 static bool signed_add_overflows(s64 a, s64 b)
12077 {
12078 	/* Do the add in u64, where overflow is well-defined */
12079 	s64 res = (s64)((u64)a + (u64)b);
12080 
12081 	if (b < 0)
12082 		return res > a;
12083 	return res < a;
12084 }
12085 
12086 static bool signed_add32_overflows(s32 a, s32 b)
12087 {
12088 	/* Do the add in u32, where overflow is well-defined */
12089 	s32 res = (s32)((u32)a + (u32)b);
12090 
12091 	if (b < 0)
12092 		return res > a;
12093 	return res < a;
12094 }
12095 
12096 static bool signed_sub_overflows(s64 a, s64 b)
12097 {
12098 	/* Do the sub in u64, where overflow is well-defined */
12099 	s64 res = (s64)((u64)a - (u64)b);
12100 
12101 	if (b < 0)
12102 		return res < a;
12103 	return res > a;
12104 }
12105 
12106 static bool signed_sub32_overflows(s32 a, s32 b)
12107 {
12108 	/* Do the sub in u32, where overflow is well-defined */
12109 	s32 res = (s32)((u32)a - (u32)b);
12110 
12111 	if (b < 0)
12112 		return res < a;
12113 	return res > a;
12114 }
12115 
12116 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12117 				  const struct bpf_reg_state *reg,
12118 				  enum bpf_reg_type type)
12119 {
12120 	bool known = tnum_is_const(reg->var_off);
12121 	s64 val = reg->var_off.value;
12122 	s64 smin = reg->smin_value;
12123 
12124 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12125 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12126 			reg_type_str(env, type), val);
12127 		return false;
12128 	}
12129 
12130 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12131 		verbose(env, "%s pointer offset %d is not allowed\n",
12132 			reg_type_str(env, type), reg->off);
12133 		return false;
12134 	}
12135 
12136 	if (smin == S64_MIN) {
12137 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12138 			reg_type_str(env, type));
12139 		return false;
12140 	}
12141 
12142 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12143 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12144 			smin, reg_type_str(env, type));
12145 		return false;
12146 	}
12147 
12148 	return true;
12149 }
12150 
12151 enum {
12152 	REASON_BOUNDS	= -1,
12153 	REASON_TYPE	= -2,
12154 	REASON_PATHS	= -3,
12155 	REASON_LIMIT	= -4,
12156 	REASON_STACK	= -5,
12157 };
12158 
12159 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12160 			      u32 *alu_limit, bool mask_to_left)
12161 {
12162 	u32 max = 0, ptr_limit = 0;
12163 
12164 	switch (ptr_reg->type) {
12165 	case PTR_TO_STACK:
12166 		/* Offset 0 is out-of-bounds, but acceptable start for the
12167 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12168 		 * offset where we would need to deal with min/max bounds is
12169 		 * currently prohibited for unprivileged.
12170 		 */
12171 		max = MAX_BPF_STACK + mask_to_left;
12172 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12173 		break;
12174 	case PTR_TO_MAP_VALUE:
12175 		max = ptr_reg->map_ptr->value_size;
12176 		ptr_limit = (mask_to_left ?
12177 			     ptr_reg->smin_value :
12178 			     ptr_reg->umax_value) + ptr_reg->off;
12179 		break;
12180 	default:
12181 		return REASON_TYPE;
12182 	}
12183 
12184 	if (ptr_limit >= max)
12185 		return REASON_LIMIT;
12186 	*alu_limit = ptr_limit;
12187 	return 0;
12188 }
12189 
12190 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12191 				    const struct bpf_insn *insn)
12192 {
12193 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12194 }
12195 
12196 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12197 				       u32 alu_state, u32 alu_limit)
12198 {
12199 	/* If we arrived here from different branches with different
12200 	 * state or limits to sanitize, then this won't work.
12201 	 */
12202 	if (aux->alu_state &&
12203 	    (aux->alu_state != alu_state ||
12204 	     aux->alu_limit != alu_limit))
12205 		return REASON_PATHS;
12206 
12207 	/* Corresponding fixup done in do_misc_fixups(). */
12208 	aux->alu_state = alu_state;
12209 	aux->alu_limit = alu_limit;
12210 	return 0;
12211 }
12212 
12213 static int sanitize_val_alu(struct bpf_verifier_env *env,
12214 			    struct bpf_insn *insn)
12215 {
12216 	struct bpf_insn_aux_data *aux = cur_aux(env);
12217 
12218 	if (can_skip_alu_sanitation(env, insn))
12219 		return 0;
12220 
12221 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12222 }
12223 
12224 static bool sanitize_needed(u8 opcode)
12225 {
12226 	return opcode == BPF_ADD || opcode == BPF_SUB;
12227 }
12228 
12229 struct bpf_sanitize_info {
12230 	struct bpf_insn_aux_data aux;
12231 	bool mask_to_left;
12232 };
12233 
12234 static struct bpf_verifier_state *
12235 sanitize_speculative_path(struct bpf_verifier_env *env,
12236 			  const struct bpf_insn *insn,
12237 			  u32 next_idx, u32 curr_idx)
12238 {
12239 	struct bpf_verifier_state *branch;
12240 	struct bpf_reg_state *regs;
12241 
12242 	branch = push_stack(env, next_idx, curr_idx, true);
12243 	if (branch && insn) {
12244 		regs = branch->frame[branch->curframe]->regs;
12245 		if (BPF_SRC(insn->code) == BPF_K) {
12246 			mark_reg_unknown(env, regs, insn->dst_reg);
12247 		} else if (BPF_SRC(insn->code) == BPF_X) {
12248 			mark_reg_unknown(env, regs, insn->dst_reg);
12249 			mark_reg_unknown(env, regs, insn->src_reg);
12250 		}
12251 	}
12252 	return branch;
12253 }
12254 
12255 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12256 			    struct bpf_insn *insn,
12257 			    const struct bpf_reg_state *ptr_reg,
12258 			    const struct bpf_reg_state *off_reg,
12259 			    struct bpf_reg_state *dst_reg,
12260 			    struct bpf_sanitize_info *info,
12261 			    const bool commit_window)
12262 {
12263 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12264 	struct bpf_verifier_state *vstate = env->cur_state;
12265 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12266 	bool off_is_neg = off_reg->smin_value < 0;
12267 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12268 	u8 opcode = BPF_OP(insn->code);
12269 	u32 alu_state, alu_limit;
12270 	struct bpf_reg_state tmp;
12271 	bool ret;
12272 	int err;
12273 
12274 	if (can_skip_alu_sanitation(env, insn))
12275 		return 0;
12276 
12277 	/* We already marked aux for masking from non-speculative
12278 	 * paths, thus we got here in the first place. We only care
12279 	 * to explore bad access from here.
12280 	 */
12281 	if (vstate->speculative)
12282 		goto do_sim;
12283 
12284 	if (!commit_window) {
12285 		if (!tnum_is_const(off_reg->var_off) &&
12286 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12287 			return REASON_BOUNDS;
12288 
12289 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12290 				     (opcode == BPF_SUB && !off_is_neg);
12291 	}
12292 
12293 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12294 	if (err < 0)
12295 		return err;
12296 
12297 	if (commit_window) {
12298 		/* In commit phase we narrow the masking window based on
12299 		 * the observed pointer move after the simulated operation.
12300 		 */
12301 		alu_state = info->aux.alu_state;
12302 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12303 	} else {
12304 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12305 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12306 		alu_state |= ptr_is_dst_reg ?
12307 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12308 
12309 		/* Limit pruning on unknown scalars to enable deep search for
12310 		 * potential masking differences from other program paths.
12311 		 */
12312 		if (!off_is_imm)
12313 			env->explore_alu_limits = true;
12314 	}
12315 
12316 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12317 	if (err < 0)
12318 		return err;
12319 do_sim:
12320 	/* If we're in commit phase, we're done here given we already
12321 	 * pushed the truncated dst_reg into the speculative verification
12322 	 * stack.
12323 	 *
12324 	 * Also, when register is a known constant, we rewrite register-based
12325 	 * operation to immediate-based, and thus do not need masking (and as
12326 	 * a consequence, do not need to simulate the zero-truncation either).
12327 	 */
12328 	if (commit_window || off_is_imm)
12329 		return 0;
12330 
12331 	/* Simulate and find potential out-of-bounds access under
12332 	 * speculative execution from truncation as a result of
12333 	 * masking when off was not within expected range. If off
12334 	 * sits in dst, then we temporarily need to move ptr there
12335 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12336 	 * for cases where we use K-based arithmetic in one direction
12337 	 * and truncated reg-based in the other in order to explore
12338 	 * bad access.
12339 	 */
12340 	if (!ptr_is_dst_reg) {
12341 		tmp = *dst_reg;
12342 		copy_register_state(dst_reg, ptr_reg);
12343 	}
12344 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12345 					env->insn_idx);
12346 	if (!ptr_is_dst_reg && ret)
12347 		*dst_reg = tmp;
12348 	return !ret ? REASON_STACK : 0;
12349 }
12350 
12351 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12352 {
12353 	struct bpf_verifier_state *vstate = env->cur_state;
12354 
12355 	/* If we simulate paths under speculation, we don't update the
12356 	 * insn as 'seen' such that when we verify unreachable paths in
12357 	 * the non-speculative domain, sanitize_dead_code() can still
12358 	 * rewrite/sanitize them.
12359 	 */
12360 	if (!vstate->speculative)
12361 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12362 }
12363 
12364 static int sanitize_err(struct bpf_verifier_env *env,
12365 			const struct bpf_insn *insn, int reason,
12366 			const struct bpf_reg_state *off_reg,
12367 			const struct bpf_reg_state *dst_reg)
12368 {
12369 	static const char *err = "pointer arithmetic with it prohibited for !root";
12370 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12371 	u32 dst = insn->dst_reg, src = insn->src_reg;
12372 
12373 	switch (reason) {
12374 	case REASON_BOUNDS:
12375 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12376 			off_reg == dst_reg ? dst : src, err);
12377 		break;
12378 	case REASON_TYPE:
12379 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12380 			off_reg == dst_reg ? src : dst, err);
12381 		break;
12382 	case REASON_PATHS:
12383 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12384 			dst, op, err);
12385 		break;
12386 	case REASON_LIMIT:
12387 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12388 			dst, op, err);
12389 		break;
12390 	case REASON_STACK:
12391 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12392 			dst, err);
12393 		break;
12394 	default:
12395 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12396 			reason);
12397 		break;
12398 	}
12399 
12400 	return -EACCES;
12401 }
12402 
12403 /* check that stack access falls within stack limits and that 'reg' doesn't
12404  * have a variable offset.
12405  *
12406  * Variable offset is prohibited for unprivileged mode for simplicity since it
12407  * requires corresponding support in Spectre masking for stack ALU.  See also
12408  * retrieve_ptr_limit().
12409  *
12410  *
12411  * 'off' includes 'reg->off'.
12412  */
12413 static int check_stack_access_for_ptr_arithmetic(
12414 				struct bpf_verifier_env *env,
12415 				int regno,
12416 				const struct bpf_reg_state *reg,
12417 				int off)
12418 {
12419 	if (!tnum_is_const(reg->var_off)) {
12420 		char tn_buf[48];
12421 
12422 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12423 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12424 			regno, tn_buf, off);
12425 		return -EACCES;
12426 	}
12427 
12428 	if (off >= 0 || off < -MAX_BPF_STACK) {
12429 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12430 			"prohibited for !root; off=%d\n", regno, off);
12431 		return -EACCES;
12432 	}
12433 
12434 	return 0;
12435 }
12436 
12437 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12438 				 const struct bpf_insn *insn,
12439 				 const struct bpf_reg_state *dst_reg)
12440 {
12441 	u32 dst = insn->dst_reg;
12442 
12443 	/* For unprivileged we require that resulting offset must be in bounds
12444 	 * in order to be able to sanitize access later on.
12445 	 */
12446 	if (env->bypass_spec_v1)
12447 		return 0;
12448 
12449 	switch (dst_reg->type) {
12450 	case PTR_TO_STACK:
12451 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12452 					dst_reg->off + dst_reg->var_off.value))
12453 			return -EACCES;
12454 		break;
12455 	case PTR_TO_MAP_VALUE:
12456 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12457 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12458 				"prohibited for !root\n", dst);
12459 			return -EACCES;
12460 		}
12461 		break;
12462 	default:
12463 		break;
12464 	}
12465 
12466 	return 0;
12467 }
12468 
12469 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12470  * Caller should also handle BPF_MOV case separately.
12471  * If we return -EACCES, caller may want to try again treating pointer as a
12472  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12473  */
12474 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12475 				   struct bpf_insn *insn,
12476 				   const struct bpf_reg_state *ptr_reg,
12477 				   const struct bpf_reg_state *off_reg)
12478 {
12479 	struct bpf_verifier_state *vstate = env->cur_state;
12480 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12481 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12482 	bool known = tnum_is_const(off_reg->var_off);
12483 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12484 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12485 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12486 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12487 	struct bpf_sanitize_info info = {};
12488 	u8 opcode = BPF_OP(insn->code);
12489 	u32 dst = insn->dst_reg;
12490 	int ret;
12491 
12492 	dst_reg = &regs[dst];
12493 
12494 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12495 	    smin_val > smax_val || umin_val > umax_val) {
12496 		/* Taint dst register if offset had invalid bounds derived from
12497 		 * e.g. dead branches.
12498 		 */
12499 		__mark_reg_unknown(env, dst_reg);
12500 		return 0;
12501 	}
12502 
12503 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12504 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12505 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12506 			__mark_reg_unknown(env, dst_reg);
12507 			return 0;
12508 		}
12509 
12510 		verbose(env,
12511 			"R%d 32-bit pointer arithmetic prohibited\n",
12512 			dst);
12513 		return -EACCES;
12514 	}
12515 
12516 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12517 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12518 			dst, reg_type_str(env, ptr_reg->type));
12519 		return -EACCES;
12520 	}
12521 
12522 	switch (base_type(ptr_reg->type)) {
12523 	case PTR_TO_FLOW_KEYS:
12524 		if (known)
12525 			break;
12526 		fallthrough;
12527 	case CONST_PTR_TO_MAP:
12528 		/* smin_val represents the known value */
12529 		if (known && smin_val == 0 && opcode == BPF_ADD)
12530 			break;
12531 		fallthrough;
12532 	case PTR_TO_PACKET_END:
12533 	case PTR_TO_SOCKET:
12534 	case PTR_TO_SOCK_COMMON:
12535 	case PTR_TO_TCP_SOCK:
12536 	case PTR_TO_XDP_SOCK:
12537 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12538 			dst, reg_type_str(env, ptr_reg->type));
12539 		return -EACCES;
12540 	default:
12541 		break;
12542 	}
12543 
12544 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12545 	 * The id may be overwritten later if we create a new variable offset.
12546 	 */
12547 	dst_reg->type = ptr_reg->type;
12548 	dst_reg->id = ptr_reg->id;
12549 
12550 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12551 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12552 		return -EINVAL;
12553 
12554 	/* pointer types do not carry 32-bit bounds at the moment. */
12555 	__mark_reg32_unbounded(dst_reg);
12556 
12557 	if (sanitize_needed(opcode)) {
12558 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12559 				       &info, false);
12560 		if (ret < 0)
12561 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12562 	}
12563 
12564 	switch (opcode) {
12565 	case BPF_ADD:
12566 		/* We can take a fixed offset as long as it doesn't overflow
12567 		 * the s32 'off' field
12568 		 */
12569 		if (known && (ptr_reg->off + smin_val ==
12570 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12571 			/* pointer += K.  Accumulate it into fixed offset */
12572 			dst_reg->smin_value = smin_ptr;
12573 			dst_reg->smax_value = smax_ptr;
12574 			dst_reg->umin_value = umin_ptr;
12575 			dst_reg->umax_value = umax_ptr;
12576 			dst_reg->var_off = ptr_reg->var_off;
12577 			dst_reg->off = ptr_reg->off + smin_val;
12578 			dst_reg->raw = ptr_reg->raw;
12579 			break;
12580 		}
12581 		/* A new variable offset is created.  Note that off_reg->off
12582 		 * == 0, since it's a scalar.
12583 		 * dst_reg gets the pointer type and since some positive
12584 		 * integer value was added to the pointer, give it a new 'id'
12585 		 * if it's a PTR_TO_PACKET.
12586 		 * this creates a new 'base' pointer, off_reg (variable) gets
12587 		 * added into the variable offset, and we copy the fixed offset
12588 		 * from ptr_reg.
12589 		 */
12590 		if (signed_add_overflows(smin_ptr, smin_val) ||
12591 		    signed_add_overflows(smax_ptr, smax_val)) {
12592 			dst_reg->smin_value = S64_MIN;
12593 			dst_reg->smax_value = S64_MAX;
12594 		} else {
12595 			dst_reg->smin_value = smin_ptr + smin_val;
12596 			dst_reg->smax_value = smax_ptr + smax_val;
12597 		}
12598 		if (umin_ptr + umin_val < umin_ptr ||
12599 		    umax_ptr + umax_val < umax_ptr) {
12600 			dst_reg->umin_value = 0;
12601 			dst_reg->umax_value = U64_MAX;
12602 		} else {
12603 			dst_reg->umin_value = umin_ptr + umin_val;
12604 			dst_reg->umax_value = umax_ptr + umax_val;
12605 		}
12606 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12607 		dst_reg->off = ptr_reg->off;
12608 		dst_reg->raw = ptr_reg->raw;
12609 		if (reg_is_pkt_pointer(ptr_reg)) {
12610 			dst_reg->id = ++env->id_gen;
12611 			/* something was added to pkt_ptr, set range to zero */
12612 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12613 		}
12614 		break;
12615 	case BPF_SUB:
12616 		if (dst_reg == off_reg) {
12617 			/* scalar -= pointer.  Creates an unknown scalar */
12618 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12619 				dst);
12620 			return -EACCES;
12621 		}
12622 		/* We don't allow subtraction from FP, because (according to
12623 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12624 		 * be able to deal with it.
12625 		 */
12626 		if (ptr_reg->type == PTR_TO_STACK) {
12627 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12628 				dst);
12629 			return -EACCES;
12630 		}
12631 		if (known && (ptr_reg->off - smin_val ==
12632 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12633 			/* pointer -= K.  Subtract it from fixed offset */
12634 			dst_reg->smin_value = smin_ptr;
12635 			dst_reg->smax_value = smax_ptr;
12636 			dst_reg->umin_value = umin_ptr;
12637 			dst_reg->umax_value = umax_ptr;
12638 			dst_reg->var_off = ptr_reg->var_off;
12639 			dst_reg->id = ptr_reg->id;
12640 			dst_reg->off = ptr_reg->off - smin_val;
12641 			dst_reg->raw = ptr_reg->raw;
12642 			break;
12643 		}
12644 		/* A new variable offset is created.  If the subtrahend is known
12645 		 * nonnegative, then any reg->range we had before is still good.
12646 		 */
12647 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12648 		    signed_sub_overflows(smax_ptr, smin_val)) {
12649 			/* Overflow possible, we know nothing */
12650 			dst_reg->smin_value = S64_MIN;
12651 			dst_reg->smax_value = S64_MAX;
12652 		} else {
12653 			dst_reg->smin_value = smin_ptr - smax_val;
12654 			dst_reg->smax_value = smax_ptr - smin_val;
12655 		}
12656 		if (umin_ptr < umax_val) {
12657 			/* Overflow possible, we know nothing */
12658 			dst_reg->umin_value = 0;
12659 			dst_reg->umax_value = U64_MAX;
12660 		} else {
12661 			/* Cannot overflow (as long as bounds are consistent) */
12662 			dst_reg->umin_value = umin_ptr - umax_val;
12663 			dst_reg->umax_value = umax_ptr - umin_val;
12664 		}
12665 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12666 		dst_reg->off = ptr_reg->off;
12667 		dst_reg->raw = ptr_reg->raw;
12668 		if (reg_is_pkt_pointer(ptr_reg)) {
12669 			dst_reg->id = ++env->id_gen;
12670 			/* something was added to pkt_ptr, set range to zero */
12671 			if (smin_val < 0)
12672 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12673 		}
12674 		break;
12675 	case BPF_AND:
12676 	case BPF_OR:
12677 	case BPF_XOR:
12678 		/* bitwise ops on pointers are troublesome, prohibit. */
12679 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12680 			dst, bpf_alu_string[opcode >> 4]);
12681 		return -EACCES;
12682 	default:
12683 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12684 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12685 			dst, bpf_alu_string[opcode >> 4]);
12686 		return -EACCES;
12687 	}
12688 
12689 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12690 		return -EINVAL;
12691 	reg_bounds_sync(dst_reg);
12692 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12693 		return -EACCES;
12694 	if (sanitize_needed(opcode)) {
12695 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12696 				       &info, true);
12697 		if (ret < 0)
12698 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12699 	}
12700 
12701 	return 0;
12702 }
12703 
12704 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12705 				 struct bpf_reg_state *src_reg)
12706 {
12707 	s32 smin_val = src_reg->s32_min_value;
12708 	s32 smax_val = src_reg->s32_max_value;
12709 	u32 umin_val = src_reg->u32_min_value;
12710 	u32 umax_val = src_reg->u32_max_value;
12711 
12712 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12713 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12714 		dst_reg->s32_min_value = S32_MIN;
12715 		dst_reg->s32_max_value = S32_MAX;
12716 	} else {
12717 		dst_reg->s32_min_value += smin_val;
12718 		dst_reg->s32_max_value += smax_val;
12719 	}
12720 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12721 	    dst_reg->u32_max_value + umax_val < umax_val) {
12722 		dst_reg->u32_min_value = 0;
12723 		dst_reg->u32_max_value = U32_MAX;
12724 	} else {
12725 		dst_reg->u32_min_value += umin_val;
12726 		dst_reg->u32_max_value += umax_val;
12727 	}
12728 }
12729 
12730 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12731 			       struct bpf_reg_state *src_reg)
12732 {
12733 	s64 smin_val = src_reg->smin_value;
12734 	s64 smax_val = src_reg->smax_value;
12735 	u64 umin_val = src_reg->umin_value;
12736 	u64 umax_val = src_reg->umax_value;
12737 
12738 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12739 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12740 		dst_reg->smin_value = S64_MIN;
12741 		dst_reg->smax_value = S64_MAX;
12742 	} else {
12743 		dst_reg->smin_value += smin_val;
12744 		dst_reg->smax_value += smax_val;
12745 	}
12746 	if (dst_reg->umin_value + umin_val < umin_val ||
12747 	    dst_reg->umax_value + umax_val < umax_val) {
12748 		dst_reg->umin_value = 0;
12749 		dst_reg->umax_value = U64_MAX;
12750 	} else {
12751 		dst_reg->umin_value += umin_val;
12752 		dst_reg->umax_value += umax_val;
12753 	}
12754 }
12755 
12756 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12757 				 struct bpf_reg_state *src_reg)
12758 {
12759 	s32 smin_val = src_reg->s32_min_value;
12760 	s32 smax_val = src_reg->s32_max_value;
12761 	u32 umin_val = src_reg->u32_min_value;
12762 	u32 umax_val = src_reg->u32_max_value;
12763 
12764 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12765 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12766 		/* Overflow possible, we know nothing */
12767 		dst_reg->s32_min_value = S32_MIN;
12768 		dst_reg->s32_max_value = S32_MAX;
12769 	} else {
12770 		dst_reg->s32_min_value -= smax_val;
12771 		dst_reg->s32_max_value -= smin_val;
12772 	}
12773 	if (dst_reg->u32_min_value < umax_val) {
12774 		/* Overflow possible, we know nothing */
12775 		dst_reg->u32_min_value = 0;
12776 		dst_reg->u32_max_value = U32_MAX;
12777 	} else {
12778 		/* Cannot overflow (as long as bounds are consistent) */
12779 		dst_reg->u32_min_value -= umax_val;
12780 		dst_reg->u32_max_value -= umin_val;
12781 	}
12782 }
12783 
12784 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12785 			       struct bpf_reg_state *src_reg)
12786 {
12787 	s64 smin_val = src_reg->smin_value;
12788 	s64 smax_val = src_reg->smax_value;
12789 	u64 umin_val = src_reg->umin_value;
12790 	u64 umax_val = src_reg->umax_value;
12791 
12792 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12793 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12794 		/* Overflow possible, we know nothing */
12795 		dst_reg->smin_value = S64_MIN;
12796 		dst_reg->smax_value = S64_MAX;
12797 	} else {
12798 		dst_reg->smin_value -= smax_val;
12799 		dst_reg->smax_value -= smin_val;
12800 	}
12801 	if (dst_reg->umin_value < umax_val) {
12802 		/* Overflow possible, we know nothing */
12803 		dst_reg->umin_value = 0;
12804 		dst_reg->umax_value = U64_MAX;
12805 	} else {
12806 		/* Cannot overflow (as long as bounds are consistent) */
12807 		dst_reg->umin_value -= umax_val;
12808 		dst_reg->umax_value -= umin_val;
12809 	}
12810 }
12811 
12812 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12813 				 struct bpf_reg_state *src_reg)
12814 {
12815 	s32 smin_val = src_reg->s32_min_value;
12816 	u32 umin_val = src_reg->u32_min_value;
12817 	u32 umax_val = src_reg->u32_max_value;
12818 
12819 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12820 		/* Ain't nobody got time to multiply that sign */
12821 		__mark_reg32_unbounded(dst_reg);
12822 		return;
12823 	}
12824 	/* Both values are positive, so we can work with unsigned and
12825 	 * copy the result to signed (unless it exceeds S32_MAX).
12826 	 */
12827 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12828 		/* Potential overflow, we know nothing */
12829 		__mark_reg32_unbounded(dst_reg);
12830 		return;
12831 	}
12832 	dst_reg->u32_min_value *= umin_val;
12833 	dst_reg->u32_max_value *= umax_val;
12834 	if (dst_reg->u32_max_value > S32_MAX) {
12835 		/* Overflow possible, we know nothing */
12836 		dst_reg->s32_min_value = S32_MIN;
12837 		dst_reg->s32_max_value = S32_MAX;
12838 	} else {
12839 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12840 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12841 	}
12842 }
12843 
12844 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12845 			       struct bpf_reg_state *src_reg)
12846 {
12847 	s64 smin_val = src_reg->smin_value;
12848 	u64 umin_val = src_reg->umin_value;
12849 	u64 umax_val = src_reg->umax_value;
12850 
12851 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12852 		/* Ain't nobody got time to multiply that sign */
12853 		__mark_reg64_unbounded(dst_reg);
12854 		return;
12855 	}
12856 	/* Both values are positive, so we can work with unsigned and
12857 	 * copy the result to signed (unless it exceeds S64_MAX).
12858 	 */
12859 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12860 		/* Potential overflow, we know nothing */
12861 		__mark_reg64_unbounded(dst_reg);
12862 		return;
12863 	}
12864 	dst_reg->umin_value *= umin_val;
12865 	dst_reg->umax_value *= umax_val;
12866 	if (dst_reg->umax_value > S64_MAX) {
12867 		/* Overflow possible, we know nothing */
12868 		dst_reg->smin_value = S64_MIN;
12869 		dst_reg->smax_value = S64_MAX;
12870 	} else {
12871 		dst_reg->smin_value = dst_reg->umin_value;
12872 		dst_reg->smax_value = dst_reg->umax_value;
12873 	}
12874 }
12875 
12876 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12877 				 struct bpf_reg_state *src_reg)
12878 {
12879 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12880 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12881 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12882 	s32 smin_val = src_reg->s32_min_value;
12883 	u32 umax_val = src_reg->u32_max_value;
12884 
12885 	if (src_known && dst_known) {
12886 		__mark_reg32_known(dst_reg, var32_off.value);
12887 		return;
12888 	}
12889 
12890 	/* We get our minimum from the var_off, since that's inherently
12891 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12892 	 */
12893 	dst_reg->u32_min_value = var32_off.value;
12894 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12895 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12896 		/* Lose signed bounds when ANDing negative numbers,
12897 		 * ain't nobody got time for that.
12898 		 */
12899 		dst_reg->s32_min_value = S32_MIN;
12900 		dst_reg->s32_max_value = S32_MAX;
12901 	} else {
12902 		/* ANDing two positives gives a positive, so safe to
12903 		 * cast result into s64.
12904 		 */
12905 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12906 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12907 	}
12908 }
12909 
12910 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12911 			       struct bpf_reg_state *src_reg)
12912 {
12913 	bool src_known = tnum_is_const(src_reg->var_off);
12914 	bool dst_known = tnum_is_const(dst_reg->var_off);
12915 	s64 smin_val = src_reg->smin_value;
12916 	u64 umax_val = src_reg->umax_value;
12917 
12918 	if (src_known && dst_known) {
12919 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12920 		return;
12921 	}
12922 
12923 	/* We get our minimum from the var_off, since that's inherently
12924 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12925 	 */
12926 	dst_reg->umin_value = dst_reg->var_off.value;
12927 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12928 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12929 		/* Lose signed bounds when ANDing negative numbers,
12930 		 * ain't nobody got time for that.
12931 		 */
12932 		dst_reg->smin_value = S64_MIN;
12933 		dst_reg->smax_value = S64_MAX;
12934 	} else {
12935 		/* ANDing two positives gives a positive, so safe to
12936 		 * cast result into s64.
12937 		 */
12938 		dst_reg->smin_value = dst_reg->umin_value;
12939 		dst_reg->smax_value = dst_reg->umax_value;
12940 	}
12941 	/* We may learn something more from the var_off */
12942 	__update_reg_bounds(dst_reg);
12943 }
12944 
12945 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12946 				struct bpf_reg_state *src_reg)
12947 {
12948 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12949 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12950 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12951 	s32 smin_val = src_reg->s32_min_value;
12952 	u32 umin_val = src_reg->u32_min_value;
12953 
12954 	if (src_known && dst_known) {
12955 		__mark_reg32_known(dst_reg, var32_off.value);
12956 		return;
12957 	}
12958 
12959 	/* We get our maximum from the var_off, and our minimum is the
12960 	 * maximum of the operands' minima
12961 	 */
12962 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12963 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12964 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12965 		/* Lose signed bounds when ORing negative numbers,
12966 		 * ain't nobody got time for that.
12967 		 */
12968 		dst_reg->s32_min_value = S32_MIN;
12969 		dst_reg->s32_max_value = S32_MAX;
12970 	} else {
12971 		/* ORing two positives gives a positive, so safe to
12972 		 * cast result into s64.
12973 		 */
12974 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12975 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12976 	}
12977 }
12978 
12979 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12980 			      struct bpf_reg_state *src_reg)
12981 {
12982 	bool src_known = tnum_is_const(src_reg->var_off);
12983 	bool dst_known = tnum_is_const(dst_reg->var_off);
12984 	s64 smin_val = src_reg->smin_value;
12985 	u64 umin_val = src_reg->umin_value;
12986 
12987 	if (src_known && dst_known) {
12988 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12989 		return;
12990 	}
12991 
12992 	/* We get our maximum from the var_off, and our minimum is the
12993 	 * maximum of the operands' minima
12994 	 */
12995 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12996 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12997 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12998 		/* Lose signed bounds when ORing negative numbers,
12999 		 * ain't nobody got time for that.
13000 		 */
13001 		dst_reg->smin_value = S64_MIN;
13002 		dst_reg->smax_value = S64_MAX;
13003 	} else {
13004 		/* ORing two positives gives a positive, so safe to
13005 		 * cast result into s64.
13006 		 */
13007 		dst_reg->smin_value = dst_reg->umin_value;
13008 		dst_reg->smax_value = dst_reg->umax_value;
13009 	}
13010 	/* We may learn something more from the var_off */
13011 	__update_reg_bounds(dst_reg);
13012 }
13013 
13014 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13015 				 struct bpf_reg_state *src_reg)
13016 {
13017 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13018 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13019 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13020 	s32 smin_val = src_reg->s32_min_value;
13021 
13022 	if (src_known && dst_known) {
13023 		__mark_reg32_known(dst_reg, var32_off.value);
13024 		return;
13025 	}
13026 
13027 	/* We get both minimum and maximum from the var32_off. */
13028 	dst_reg->u32_min_value = var32_off.value;
13029 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13030 
13031 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13032 		/* XORing two positive sign numbers gives a positive,
13033 		 * so safe to cast u32 result into s32.
13034 		 */
13035 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13036 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13037 	} else {
13038 		dst_reg->s32_min_value = S32_MIN;
13039 		dst_reg->s32_max_value = S32_MAX;
13040 	}
13041 }
13042 
13043 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13044 			       struct bpf_reg_state *src_reg)
13045 {
13046 	bool src_known = tnum_is_const(src_reg->var_off);
13047 	bool dst_known = tnum_is_const(dst_reg->var_off);
13048 	s64 smin_val = src_reg->smin_value;
13049 
13050 	if (src_known && dst_known) {
13051 		/* dst_reg->var_off.value has been updated earlier */
13052 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13053 		return;
13054 	}
13055 
13056 	/* We get both minimum and maximum from the var_off. */
13057 	dst_reg->umin_value = dst_reg->var_off.value;
13058 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13059 
13060 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13061 		/* XORing two positive sign numbers gives a positive,
13062 		 * so safe to cast u64 result into s64.
13063 		 */
13064 		dst_reg->smin_value = dst_reg->umin_value;
13065 		dst_reg->smax_value = dst_reg->umax_value;
13066 	} else {
13067 		dst_reg->smin_value = S64_MIN;
13068 		dst_reg->smax_value = S64_MAX;
13069 	}
13070 
13071 	__update_reg_bounds(dst_reg);
13072 }
13073 
13074 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13075 				   u64 umin_val, u64 umax_val)
13076 {
13077 	/* We lose all sign bit information (except what we can pick
13078 	 * up from var_off)
13079 	 */
13080 	dst_reg->s32_min_value = S32_MIN;
13081 	dst_reg->s32_max_value = S32_MAX;
13082 	/* If we might shift our top bit out, then we know nothing */
13083 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13084 		dst_reg->u32_min_value = 0;
13085 		dst_reg->u32_max_value = U32_MAX;
13086 	} else {
13087 		dst_reg->u32_min_value <<= umin_val;
13088 		dst_reg->u32_max_value <<= umax_val;
13089 	}
13090 }
13091 
13092 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13093 				 struct bpf_reg_state *src_reg)
13094 {
13095 	u32 umax_val = src_reg->u32_max_value;
13096 	u32 umin_val = src_reg->u32_min_value;
13097 	/* u32 alu operation will zext upper bits */
13098 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13099 
13100 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13101 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13102 	/* Not required but being careful mark reg64 bounds as unknown so
13103 	 * that we are forced to pick them up from tnum and zext later and
13104 	 * if some path skips this step we are still safe.
13105 	 */
13106 	__mark_reg64_unbounded(dst_reg);
13107 	__update_reg32_bounds(dst_reg);
13108 }
13109 
13110 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13111 				   u64 umin_val, u64 umax_val)
13112 {
13113 	/* Special case <<32 because it is a common compiler pattern to sign
13114 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13115 	 * positive we know this shift will also be positive so we can track
13116 	 * bounds correctly. Otherwise we lose all sign bit information except
13117 	 * what we can pick up from var_off. Perhaps we can generalize this
13118 	 * later to shifts of any length.
13119 	 */
13120 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13121 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13122 	else
13123 		dst_reg->smax_value = S64_MAX;
13124 
13125 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13126 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13127 	else
13128 		dst_reg->smin_value = S64_MIN;
13129 
13130 	/* If we might shift our top bit out, then we know nothing */
13131 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13132 		dst_reg->umin_value = 0;
13133 		dst_reg->umax_value = U64_MAX;
13134 	} else {
13135 		dst_reg->umin_value <<= umin_val;
13136 		dst_reg->umax_value <<= umax_val;
13137 	}
13138 }
13139 
13140 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13141 			       struct bpf_reg_state *src_reg)
13142 {
13143 	u64 umax_val = src_reg->umax_value;
13144 	u64 umin_val = src_reg->umin_value;
13145 
13146 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13147 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13148 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13149 
13150 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13151 	/* We may learn something more from the var_off */
13152 	__update_reg_bounds(dst_reg);
13153 }
13154 
13155 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13156 				 struct bpf_reg_state *src_reg)
13157 {
13158 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13159 	u32 umax_val = src_reg->u32_max_value;
13160 	u32 umin_val = src_reg->u32_min_value;
13161 
13162 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13163 	 * be negative, then either:
13164 	 * 1) src_reg might be zero, so the sign bit of the result is
13165 	 *    unknown, so we lose our signed bounds
13166 	 * 2) it's known negative, thus the unsigned bounds capture the
13167 	 *    signed bounds
13168 	 * 3) the signed bounds cross zero, so they tell us nothing
13169 	 *    about the result
13170 	 * If the value in dst_reg is known nonnegative, then again the
13171 	 * unsigned bounds capture the signed bounds.
13172 	 * Thus, in all cases it suffices to blow away our signed bounds
13173 	 * and rely on inferring new ones from the unsigned bounds and
13174 	 * var_off of the result.
13175 	 */
13176 	dst_reg->s32_min_value = S32_MIN;
13177 	dst_reg->s32_max_value = S32_MAX;
13178 
13179 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13180 	dst_reg->u32_min_value >>= umax_val;
13181 	dst_reg->u32_max_value >>= umin_val;
13182 
13183 	__mark_reg64_unbounded(dst_reg);
13184 	__update_reg32_bounds(dst_reg);
13185 }
13186 
13187 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13188 			       struct bpf_reg_state *src_reg)
13189 {
13190 	u64 umax_val = src_reg->umax_value;
13191 	u64 umin_val = src_reg->umin_value;
13192 
13193 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13194 	 * be negative, then either:
13195 	 * 1) src_reg might be zero, so the sign bit of the result is
13196 	 *    unknown, so we lose our signed bounds
13197 	 * 2) it's known negative, thus the unsigned bounds capture the
13198 	 *    signed bounds
13199 	 * 3) the signed bounds cross zero, so they tell us nothing
13200 	 *    about the result
13201 	 * If the value in dst_reg is known nonnegative, then again the
13202 	 * unsigned bounds capture the signed bounds.
13203 	 * Thus, in all cases it suffices to blow away our signed bounds
13204 	 * and rely on inferring new ones from the unsigned bounds and
13205 	 * var_off of the result.
13206 	 */
13207 	dst_reg->smin_value = S64_MIN;
13208 	dst_reg->smax_value = S64_MAX;
13209 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13210 	dst_reg->umin_value >>= umax_val;
13211 	dst_reg->umax_value >>= umin_val;
13212 
13213 	/* Its not easy to operate on alu32 bounds here because it depends
13214 	 * on bits being shifted in. Take easy way out and mark unbounded
13215 	 * so we can recalculate later from tnum.
13216 	 */
13217 	__mark_reg32_unbounded(dst_reg);
13218 	__update_reg_bounds(dst_reg);
13219 }
13220 
13221 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13222 				  struct bpf_reg_state *src_reg)
13223 {
13224 	u64 umin_val = src_reg->u32_min_value;
13225 
13226 	/* Upon reaching here, src_known is true and
13227 	 * umax_val is equal to umin_val.
13228 	 */
13229 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13230 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13231 
13232 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13233 
13234 	/* blow away the dst_reg umin_value/umax_value and rely on
13235 	 * dst_reg var_off to refine the result.
13236 	 */
13237 	dst_reg->u32_min_value = 0;
13238 	dst_reg->u32_max_value = U32_MAX;
13239 
13240 	__mark_reg64_unbounded(dst_reg);
13241 	__update_reg32_bounds(dst_reg);
13242 }
13243 
13244 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13245 				struct bpf_reg_state *src_reg)
13246 {
13247 	u64 umin_val = src_reg->umin_value;
13248 
13249 	/* Upon reaching here, src_known is true and umax_val is equal
13250 	 * to umin_val.
13251 	 */
13252 	dst_reg->smin_value >>= umin_val;
13253 	dst_reg->smax_value >>= umin_val;
13254 
13255 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13256 
13257 	/* blow away the dst_reg umin_value/umax_value and rely on
13258 	 * dst_reg var_off to refine the result.
13259 	 */
13260 	dst_reg->umin_value = 0;
13261 	dst_reg->umax_value = U64_MAX;
13262 
13263 	/* Its not easy to operate on alu32 bounds here because it depends
13264 	 * on bits being shifted in from upper 32-bits. Take easy way out
13265 	 * and mark unbounded so we can recalculate later from tnum.
13266 	 */
13267 	__mark_reg32_unbounded(dst_reg);
13268 	__update_reg_bounds(dst_reg);
13269 }
13270 
13271 /* WARNING: This function does calculations on 64-bit values, but the actual
13272  * execution may occur on 32-bit values. Therefore, things like bitshifts
13273  * need extra checks in the 32-bit case.
13274  */
13275 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13276 				      struct bpf_insn *insn,
13277 				      struct bpf_reg_state *dst_reg,
13278 				      struct bpf_reg_state src_reg)
13279 {
13280 	struct bpf_reg_state *regs = cur_regs(env);
13281 	u8 opcode = BPF_OP(insn->code);
13282 	bool src_known;
13283 	s64 smin_val, smax_val;
13284 	u64 umin_val, umax_val;
13285 	s32 s32_min_val, s32_max_val;
13286 	u32 u32_min_val, u32_max_val;
13287 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13288 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13289 	int ret;
13290 
13291 	smin_val = src_reg.smin_value;
13292 	smax_val = src_reg.smax_value;
13293 	umin_val = src_reg.umin_value;
13294 	umax_val = src_reg.umax_value;
13295 
13296 	s32_min_val = src_reg.s32_min_value;
13297 	s32_max_val = src_reg.s32_max_value;
13298 	u32_min_val = src_reg.u32_min_value;
13299 	u32_max_val = src_reg.u32_max_value;
13300 
13301 	if (alu32) {
13302 		src_known = tnum_subreg_is_const(src_reg.var_off);
13303 		if ((src_known &&
13304 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13305 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13306 			/* Taint dst register if offset had invalid bounds
13307 			 * derived from e.g. dead branches.
13308 			 */
13309 			__mark_reg_unknown(env, dst_reg);
13310 			return 0;
13311 		}
13312 	} else {
13313 		src_known = tnum_is_const(src_reg.var_off);
13314 		if ((src_known &&
13315 		     (smin_val != smax_val || umin_val != umax_val)) ||
13316 		    smin_val > smax_val || umin_val > umax_val) {
13317 			/* Taint dst register if offset had invalid bounds
13318 			 * derived from e.g. dead branches.
13319 			 */
13320 			__mark_reg_unknown(env, dst_reg);
13321 			return 0;
13322 		}
13323 	}
13324 
13325 	if (!src_known &&
13326 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13327 		__mark_reg_unknown(env, dst_reg);
13328 		return 0;
13329 	}
13330 
13331 	if (sanitize_needed(opcode)) {
13332 		ret = sanitize_val_alu(env, insn);
13333 		if (ret < 0)
13334 			return sanitize_err(env, insn, ret, NULL, NULL);
13335 	}
13336 
13337 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13338 	 * There are two classes of instructions: The first class we track both
13339 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13340 	 * greatest amount of precision when alu operations are mixed with jmp32
13341 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13342 	 * and BPF_OR. This is possible because these ops have fairly easy to
13343 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13344 	 * See alu32 verifier tests for examples. The second class of
13345 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13346 	 * with regards to tracking sign/unsigned bounds because the bits may
13347 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13348 	 * the reg unbounded in the subreg bound space and use the resulting
13349 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13350 	 */
13351 	switch (opcode) {
13352 	case BPF_ADD:
13353 		scalar32_min_max_add(dst_reg, &src_reg);
13354 		scalar_min_max_add(dst_reg, &src_reg);
13355 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13356 		break;
13357 	case BPF_SUB:
13358 		scalar32_min_max_sub(dst_reg, &src_reg);
13359 		scalar_min_max_sub(dst_reg, &src_reg);
13360 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13361 		break;
13362 	case BPF_MUL:
13363 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13364 		scalar32_min_max_mul(dst_reg, &src_reg);
13365 		scalar_min_max_mul(dst_reg, &src_reg);
13366 		break;
13367 	case BPF_AND:
13368 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13369 		scalar32_min_max_and(dst_reg, &src_reg);
13370 		scalar_min_max_and(dst_reg, &src_reg);
13371 		break;
13372 	case BPF_OR:
13373 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13374 		scalar32_min_max_or(dst_reg, &src_reg);
13375 		scalar_min_max_or(dst_reg, &src_reg);
13376 		break;
13377 	case BPF_XOR:
13378 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13379 		scalar32_min_max_xor(dst_reg, &src_reg);
13380 		scalar_min_max_xor(dst_reg, &src_reg);
13381 		break;
13382 	case BPF_LSH:
13383 		if (umax_val >= insn_bitness) {
13384 			/* Shifts greater than 31 or 63 are undefined.
13385 			 * This includes shifts by a negative number.
13386 			 */
13387 			mark_reg_unknown(env, regs, insn->dst_reg);
13388 			break;
13389 		}
13390 		if (alu32)
13391 			scalar32_min_max_lsh(dst_reg, &src_reg);
13392 		else
13393 			scalar_min_max_lsh(dst_reg, &src_reg);
13394 		break;
13395 	case BPF_RSH:
13396 		if (umax_val >= insn_bitness) {
13397 			/* Shifts greater than 31 or 63 are undefined.
13398 			 * This includes shifts by a negative number.
13399 			 */
13400 			mark_reg_unknown(env, regs, insn->dst_reg);
13401 			break;
13402 		}
13403 		if (alu32)
13404 			scalar32_min_max_rsh(dst_reg, &src_reg);
13405 		else
13406 			scalar_min_max_rsh(dst_reg, &src_reg);
13407 		break;
13408 	case BPF_ARSH:
13409 		if (umax_val >= insn_bitness) {
13410 			/* Shifts greater than 31 or 63 are undefined.
13411 			 * This includes shifts by a negative number.
13412 			 */
13413 			mark_reg_unknown(env, regs, insn->dst_reg);
13414 			break;
13415 		}
13416 		if (alu32)
13417 			scalar32_min_max_arsh(dst_reg, &src_reg);
13418 		else
13419 			scalar_min_max_arsh(dst_reg, &src_reg);
13420 		break;
13421 	default:
13422 		mark_reg_unknown(env, regs, insn->dst_reg);
13423 		break;
13424 	}
13425 
13426 	/* ALU32 ops are zero extended into 64bit register */
13427 	if (alu32)
13428 		zext_32_to_64(dst_reg);
13429 	reg_bounds_sync(dst_reg);
13430 	return 0;
13431 }
13432 
13433 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13434  * and var_off.
13435  */
13436 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13437 				   struct bpf_insn *insn)
13438 {
13439 	struct bpf_verifier_state *vstate = env->cur_state;
13440 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13441 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13442 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13443 	u8 opcode = BPF_OP(insn->code);
13444 	int err;
13445 
13446 	dst_reg = &regs[insn->dst_reg];
13447 	src_reg = NULL;
13448 	if (dst_reg->type != SCALAR_VALUE)
13449 		ptr_reg = dst_reg;
13450 	else
13451 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13452 		 * incorrectly propagated into other registers by find_equal_scalars()
13453 		 */
13454 		dst_reg->id = 0;
13455 	if (BPF_SRC(insn->code) == BPF_X) {
13456 		src_reg = &regs[insn->src_reg];
13457 		if (src_reg->type != SCALAR_VALUE) {
13458 			if (dst_reg->type != SCALAR_VALUE) {
13459 				/* Combining two pointers by any ALU op yields
13460 				 * an arbitrary scalar. Disallow all math except
13461 				 * pointer subtraction
13462 				 */
13463 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13464 					mark_reg_unknown(env, regs, insn->dst_reg);
13465 					return 0;
13466 				}
13467 				verbose(env, "R%d pointer %s pointer prohibited\n",
13468 					insn->dst_reg,
13469 					bpf_alu_string[opcode >> 4]);
13470 				return -EACCES;
13471 			} else {
13472 				/* scalar += pointer
13473 				 * This is legal, but we have to reverse our
13474 				 * src/dest handling in computing the range
13475 				 */
13476 				err = mark_chain_precision(env, insn->dst_reg);
13477 				if (err)
13478 					return err;
13479 				return adjust_ptr_min_max_vals(env, insn,
13480 							       src_reg, dst_reg);
13481 			}
13482 		} else if (ptr_reg) {
13483 			/* pointer += scalar */
13484 			err = mark_chain_precision(env, insn->src_reg);
13485 			if (err)
13486 				return err;
13487 			return adjust_ptr_min_max_vals(env, insn,
13488 						       dst_reg, src_reg);
13489 		} else if (dst_reg->precise) {
13490 			/* if dst_reg is precise, src_reg should be precise as well */
13491 			err = mark_chain_precision(env, insn->src_reg);
13492 			if (err)
13493 				return err;
13494 		}
13495 	} else {
13496 		/* Pretend the src is a reg with a known value, since we only
13497 		 * need to be able to read from this state.
13498 		 */
13499 		off_reg.type = SCALAR_VALUE;
13500 		__mark_reg_known(&off_reg, insn->imm);
13501 		src_reg = &off_reg;
13502 		if (ptr_reg) /* pointer += K */
13503 			return adjust_ptr_min_max_vals(env, insn,
13504 						       ptr_reg, src_reg);
13505 	}
13506 
13507 	/* Got here implies adding two SCALAR_VALUEs */
13508 	if (WARN_ON_ONCE(ptr_reg)) {
13509 		print_verifier_state(env, state, true);
13510 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13511 		return -EINVAL;
13512 	}
13513 	if (WARN_ON(!src_reg)) {
13514 		print_verifier_state(env, state, true);
13515 		verbose(env, "verifier internal error: no src_reg\n");
13516 		return -EINVAL;
13517 	}
13518 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13519 }
13520 
13521 /* check validity of 32-bit and 64-bit arithmetic operations */
13522 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13523 {
13524 	struct bpf_reg_state *regs = cur_regs(env);
13525 	u8 opcode = BPF_OP(insn->code);
13526 	int err;
13527 
13528 	if (opcode == BPF_END || opcode == BPF_NEG) {
13529 		if (opcode == BPF_NEG) {
13530 			if (BPF_SRC(insn->code) != BPF_K ||
13531 			    insn->src_reg != BPF_REG_0 ||
13532 			    insn->off != 0 || insn->imm != 0) {
13533 				verbose(env, "BPF_NEG uses reserved fields\n");
13534 				return -EINVAL;
13535 			}
13536 		} else {
13537 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13538 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13539 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13540 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13541 				verbose(env, "BPF_END uses reserved fields\n");
13542 				return -EINVAL;
13543 			}
13544 		}
13545 
13546 		/* check src operand */
13547 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13548 		if (err)
13549 			return err;
13550 
13551 		if (is_pointer_value(env, insn->dst_reg)) {
13552 			verbose(env, "R%d pointer arithmetic prohibited\n",
13553 				insn->dst_reg);
13554 			return -EACCES;
13555 		}
13556 
13557 		/* check dest operand */
13558 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13559 		if (err)
13560 			return err;
13561 
13562 	} else if (opcode == BPF_MOV) {
13563 
13564 		if (BPF_SRC(insn->code) == BPF_X) {
13565 			if (insn->imm != 0) {
13566 				verbose(env, "BPF_MOV uses reserved fields\n");
13567 				return -EINVAL;
13568 			}
13569 
13570 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13571 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13572 					verbose(env, "BPF_MOV uses reserved fields\n");
13573 					return -EINVAL;
13574 				}
13575 			} else {
13576 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13577 				    insn->off != 32) {
13578 					verbose(env, "BPF_MOV uses reserved fields\n");
13579 					return -EINVAL;
13580 				}
13581 			}
13582 
13583 			/* check src operand */
13584 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13585 			if (err)
13586 				return err;
13587 		} else {
13588 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13589 				verbose(env, "BPF_MOV uses reserved fields\n");
13590 				return -EINVAL;
13591 			}
13592 		}
13593 
13594 		/* check dest operand, mark as required later */
13595 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13596 		if (err)
13597 			return err;
13598 
13599 		if (BPF_SRC(insn->code) == BPF_X) {
13600 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13601 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13602 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13603 				       !tnum_is_const(src_reg->var_off);
13604 
13605 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13606 				if (insn->off == 0) {
13607 					/* case: R1 = R2
13608 					 * copy register state to dest reg
13609 					 */
13610 					if (need_id)
13611 						/* Assign src and dst registers the same ID
13612 						 * that will be used by find_equal_scalars()
13613 						 * to propagate min/max range.
13614 						 */
13615 						src_reg->id = ++env->id_gen;
13616 					copy_register_state(dst_reg, src_reg);
13617 					dst_reg->live |= REG_LIVE_WRITTEN;
13618 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13619 				} else {
13620 					/* case: R1 = (s8, s16 s32)R2 */
13621 					if (is_pointer_value(env, insn->src_reg)) {
13622 						verbose(env,
13623 							"R%d sign-extension part of pointer\n",
13624 							insn->src_reg);
13625 						return -EACCES;
13626 					} else if (src_reg->type == SCALAR_VALUE) {
13627 						bool no_sext;
13628 
13629 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13630 						if (no_sext && need_id)
13631 							src_reg->id = ++env->id_gen;
13632 						copy_register_state(dst_reg, src_reg);
13633 						if (!no_sext)
13634 							dst_reg->id = 0;
13635 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13636 						dst_reg->live |= REG_LIVE_WRITTEN;
13637 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13638 					} else {
13639 						mark_reg_unknown(env, regs, insn->dst_reg);
13640 					}
13641 				}
13642 			} else {
13643 				/* R1 = (u32) R2 */
13644 				if (is_pointer_value(env, insn->src_reg)) {
13645 					verbose(env,
13646 						"R%d partial copy of pointer\n",
13647 						insn->src_reg);
13648 					return -EACCES;
13649 				} else if (src_reg->type == SCALAR_VALUE) {
13650 					if (insn->off == 0) {
13651 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13652 
13653 						if (is_src_reg_u32 && need_id)
13654 							src_reg->id = ++env->id_gen;
13655 						copy_register_state(dst_reg, src_reg);
13656 						/* Make sure ID is cleared if src_reg is not in u32
13657 						 * range otherwise dst_reg min/max could be incorrectly
13658 						 * propagated into src_reg by find_equal_scalars()
13659 						 */
13660 						if (!is_src_reg_u32)
13661 							dst_reg->id = 0;
13662 						dst_reg->live |= REG_LIVE_WRITTEN;
13663 						dst_reg->subreg_def = env->insn_idx + 1;
13664 					} else {
13665 						/* case: W1 = (s8, s16)W2 */
13666 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13667 
13668 						if (no_sext && need_id)
13669 							src_reg->id = ++env->id_gen;
13670 						copy_register_state(dst_reg, src_reg);
13671 						if (!no_sext)
13672 							dst_reg->id = 0;
13673 						dst_reg->live |= REG_LIVE_WRITTEN;
13674 						dst_reg->subreg_def = env->insn_idx + 1;
13675 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13676 					}
13677 				} else {
13678 					mark_reg_unknown(env, regs,
13679 							 insn->dst_reg);
13680 				}
13681 				zext_32_to_64(dst_reg);
13682 				reg_bounds_sync(dst_reg);
13683 			}
13684 		} else {
13685 			/* case: R = imm
13686 			 * remember the value we stored into this reg
13687 			 */
13688 			/* clear any state __mark_reg_known doesn't set */
13689 			mark_reg_unknown(env, regs, insn->dst_reg);
13690 			regs[insn->dst_reg].type = SCALAR_VALUE;
13691 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13692 				__mark_reg_known(regs + insn->dst_reg,
13693 						 insn->imm);
13694 			} else {
13695 				__mark_reg_known(regs + insn->dst_reg,
13696 						 (u32)insn->imm);
13697 			}
13698 		}
13699 
13700 	} else if (opcode > BPF_END) {
13701 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13702 		return -EINVAL;
13703 
13704 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13705 
13706 		if (BPF_SRC(insn->code) == BPF_X) {
13707 			if (insn->imm != 0 || insn->off > 1 ||
13708 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13709 				verbose(env, "BPF_ALU uses reserved fields\n");
13710 				return -EINVAL;
13711 			}
13712 			/* check src1 operand */
13713 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13714 			if (err)
13715 				return err;
13716 		} else {
13717 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13718 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13719 				verbose(env, "BPF_ALU uses reserved fields\n");
13720 				return -EINVAL;
13721 			}
13722 		}
13723 
13724 		/* check src2 operand */
13725 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13726 		if (err)
13727 			return err;
13728 
13729 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13730 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13731 			verbose(env, "div by zero\n");
13732 			return -EINVAL;
13733 		}
13734 
13735 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13736 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13737 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13738 
13739 			if (insn->imm < 0 || insn->imm >= size) {
13740 				verbose(env, "invalid shift %d\n", insn->imm);
13741 				return -EINVAL;
13742 			}
13743 		}
13744 
13745 		/* check dest operand */
13746 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13747 		if (err)
13748 			return err;
13749 
13750 		return adjust_reg_min_max_vals(env, insn);
13751 	}
13752 
13753 	return 0;
13754 }
13755 
13756 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13757 				   struct bpf_reg_state *dst_reg,
13758 				   enum bpf_reg_type type,
13759 				   bool range_right_open)
13760 {
13761 	struct bpf_func_state *state;
13762 	struct bpf_reg_state *reg;
13763 	int new_range;
13764 
13765 	if (dst_reg->off < 0 ||
13766 	    (dst_reg->off == 0 && range_right_open))
13767 		/* This doesn't give us any range */
13768 		return;
13769 
13770 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13771 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13772 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13773 		 * than pkt_end, but that's because it's also less than pkt.
13774 		 */
13775 		return;
13776 
13777 	new_range = dst_reg->off;
13778 	if (range_right_open)
13779 		new_range++;
13780 
13781 	/* Examples for register markings:
13782 	 *
13783 	 * pkt_data in dst register:
13784 	 *
13785 	 *   r2 = r3;
13786 	 *   r2 += 8;
13787 	 *   if (r2 > pkt_end) goto <handle exception>
13788 	 *   <access okay>
13789 	 *
13790 	 *   r2 = r3;
13791 	 *   r2 += 8;
13792 	 *   if (r2 < pkt_end) goto <access okay>
13793 	 *   <handle exception>
13794 	 *
13795 	 *   Where:
13796 	 *     r2 == dst_reg, pkt_end == src_reg
13797 	 *     r2=pkt(id=n,off=8,r=0)
13798 	 *     r3=pkt(id=n,off=0,r=0)
13799 	 *
13800 	 * pkt_data in src register:
13801 	 *
13802 	 *   r2 = r3;
13803 	 *   r2 += 8;
13804 	 *   if (pkt_end >= r2) goto <access okay>
13805 	 *   <handle exception>
13806 	 *
13807 	 *   r2 = r3;
13808 	 *   r2 += 8;
13809 	 *   if (pkt_end <= r2) goto <handle exception>
13810 	 *   <access okay>
13811 	 *
13812 	 *   Where:
13813 	 *     pkt_end == dst_reg, r2 == src_reg
13814 	 *     r2=pkt(id=n,off=8,r=0)
13815 	 *     r3=pkt(id=n,off=0,r=0)
13816 	 *
13817 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13818 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13819 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13820 	 * the check.
13821 	 */
13822 
13823 	/* If our ids match, then we must have the same max_value.  And we
13824 	 * don't care about the other reg's fixed offset, since if it's too big
13825 	 * the range won't allow anything.
13826 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13827 	 */
13828 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13829 		if (reg->type == type && reg->id == dst_reg->id)
13830 			/* keep the maximum range already checked */
13831 			reg->range = max(reg->range, new_range);
13832 	}));
13833 }
13834 
13835 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13836 {
13837 	struct tnum subreg = tnum_subreg(reg->var_off);
13838 	s32 sval = (s32)val;
13839 
13840 	switch (opcode) {
13841 	case BPF_JEQ:
13842 		if (tnum_is_const(subreg))
13843 			return !!tnum_equals_const(subreg, val);
13844 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13845 			return 0;
13846 		break;
13847 	case BPF_JNE:
13848 		if (tnum_is_const(subreg))
13849 			return !tnum_equals_const(subreg, val);
13850 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13851 			return 1;
13852 		break;
13853 	case BPF_JSET:
13854 		if ((~subreg.mask & subreg.value) & val)
13855 			return 1;
13856 		if (!((subreg.mask | subreg.value) & val))
13857 			return 0;
13858 		break;
13859 	case BPF_JGT:
13860 		if (reg->u32_min_value > val)
13861 			return 1;
13862 		else if (reg->u32_max_value <= val)
13863 			return 0;
13864 		break;
13865 	case BPF_JSGT:
13866 		if (reg->s32_min_value > sval)
13867 			return 1;
13868 		else if (reg->s32_max_value <= sval)
13869 			return 0;
13870 		break;
13871 	case BPF_JLT:
13872 		if (reg->u32_max_value < val)
13873 			return 1;
13874 		else if (reg->u32_min_value >= val)
13875 			return 0;
13876 		break;
13877 	case BPF_JSLT:
13878 		if (reg->s32_max_value < sval)
13879 			return 1;
13880 		else if (reg->s32_min_value >= sval)
13881 			return 0;
13882 		break;
13883 	case BPF_JGE:
13884 		if (reg->u32_min_value >= val)
13885 			return 1;
13886 		else if (reg->u32_max_value < val)
13887 			return 0;
13888 		break;
13889 	case BPF_JSGE:
13890 		if (reg->s32_min_value >= sval)
13891 			return 1;
13892 		else if (reg->s32_max_value < sval)
13893 			return 0;
13894 		break;
13895 	case BPF_JLE:
13896 		if (reg->u32_max_value <= val)
13897 			return 1;
13898 		else if (reg->u32_min_value > val)
13899 			return 0;
13900 		break;
13901 	case BPF_JSLE:
13902 		if (reg->s32_max_value <= sval)
13903 			return 1;
13904 		else if (reg->s32_min_value > sval)
13905 			return 0;
13906 		break;
13907 	}
13908 
13909 	return -1;
13910 }
13911 
13912 
13913 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13914 {
13915 	s64 sval = (s64)val;
13916 
13917 	switch (opcode) {
13918 	case BPF_JEQ:
13919 		if (tnum_is_const(reg->var_off))
13920 			return !!tnum_equals_const(reg->var_off, val);
13921 		else if (val < reg->umin_value || val > reg->umax_value)
13922 			return 0;
13923 		break;
13924 	case BPF_JNE:
13925 		if (tnum_is_const(reg->var_off))
13926 			return !tnum_equals_const(reg->var_off, val);
13927 		else if (val < reg->umin_value || val > reg->umax_value)
13928 			return 1;
13929 		break;
13930 	case BPF_JSET:
13931 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13932 			return 1;
13933 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13934 			return 0;
13935 		break;
13936 	case BPF_JGT:
13937 		if (reg->umin_value > val)
13938 			return 1;
13939 		else if (reg->umax_value <= val)
13940 			return 0;
13941 		break;
13942 	case BPF_JSGT:
13943 		if (reg->smin_value > sval)
13944 			return 1;
13945 		else if (reg->smax_value <= sval)
13946 			return 0;
13947 		break;
13948 	case BPF_JLT:
13949 		if (reg->umax_value < val)
13950 			return 1;
13951 		else if (reg->umin_value >= val)
13952 			return 0;
13953 		break;
13954 	case BPF_JSLT:
13955 		if (reg->smax_value < sval)
13956 			return 1;
13957 		else if (reg->smin_value >= sval)
13958 			return 0;
13959 		break;
13960 	case BPF_JGE:
13961 		if (reg->umin_value >= val)
13962 			return 1;
13963 		else if (reg->umax_value < val)
13964 			return 0;
13965 		break;
13966 	case BPF_JSGE:
13967 		if (reg->smin_value >= sval)
13968 			return 1;
13969 		else if (reg->smax_value < sval)
13970 			return 0;
13971 		break;
13972 	case BPF_JLE:
13973 		if (reg->umax_value <= val)
13974 			return 1;
13975 		else if (reg->umin_value > val)
13976 			return 0;
13977 		break;
13978 	case BPF_JSLE:
13979 		if (reg->smax_value <= sval)
13980 			return 1;
13981 		else if (reg->smin_value > sval)
13982 			return 0;
13983 		break;
13984 	}
13985 
13986 	return -1;
13987 }
13988 
13989 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13990  * and return:
13991  *  1 - branch will be taken and "goto target" will be executed
13992  *  0 - branch will not be taken and fall-through to next insn
13993  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13994  *      range [0,10]
13995  */
13996 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13997 			   bool is_jmp32)
13998 {
13999 	if (__is_pointer_value(false, reg)) {
14000 		if (!reg_not_null(reg))
14001 			return -1;
14002 
14003 		/* If pointer is valid tests against zero will fail so we can
14004 		 * use this to direct branch taken.
14005 		 */
14006 		if (val != 0)
14007 			return -1;
14008 
14009 		switch (opcode) {
14010 		case BPF_JEQ:
14011 			return 0;
14012 		case BPF_JNE:
14013 			return 1;
14014 		default:
14015 			return -1;
14016 		}
14017 	}
14018 
14019 	if (is_jmp32)
14020 		return is_branch32_taken(reg, val, opcode);
14021 	return is_branch64_taken(reg, val, opcode);
14022 }
14023 
14024 static int flip_opcode(u32 opcode)
14025 {
14026 	/* How can we transform "a <op> b" into "b <op> a"? */
14027 	static const u8 opcode_flip[16] = {
14028 		/* these stay the same */
14029 		[BPF_JEQ  >> 4] = BPF_JEQ,
14030 		[BPF_JNE  >> 4] = BPF_JNE,
14031 		[BPF_JSET >> 4] = BPF_JSET,
14032 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14033 		[BPF_JGE  >> 4] = BPF_JLE,
14034 		[BPF_JGT  >> 4] = BPF_JLT,
14035 		[BPF_JLE  >> 4] = BPF_JGE,
14036 		[BPF_JLT  >> 4] = BPF_JGT,
14037 		[BPF_JSGE >> 4] = BPF_JSLE,
14038 		[BPF_JSGT >> 4] = BPF_JSLT,
14039 		[BPF_JSLE >> 4] = BPF_JSGE,
14040 		[BPF_JSLT >> 4] = BPF_JSGT
14041 	};
14042 	return opcode_flip[opcode >> 4];
14043 }
14044 
14045 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14046 				   struct bpf_reg_state *src_reg,
14047 				   u8 opcode)
14048 {
14049 	struct bpf_reg_state *pkt;
14050 
14051 	if (src_reg->type == PTR_TO_PACKET_END) {
14052 		pkt = dst_reg;
14053 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14054 		pkt = src_reg;
14055 		opcode = flip_opcode(opcode);
14056 	} else {
14057 		return -1;
14058 	}
14059 
14060 	if (pkt->range >= 0)
14061 		return -1;
14062 
14063 	switch (opcode) {
14064 	case BPF_JLE:
14065 		/* pkt <= pkt_end */
14066 		fallthrough;
14067 	case BPF_JGT:
14068 		/* pkt > pkt_end */
14069 		if (pkt->range == BEYOND_PKT_END)
14070 			/* pkt has at last one extra byte beyond pkt_end */
14071 			return opcode == BPF_JGT;
14072 		break;
14073 	case BPF_JLT:
14074 		/* pkt < pkt_end */
14075 		fallthrough;
14076 	case BPF_JGE:
14077 		/* pkt >= pkt_end */
14078 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14079 			return opcode == BPF_JGE;
14080 		break;
14081 	}
14082 	return -1;
14083 }
14084 
14085 /* Adjusts the register min/max values in the case that the dst_reg is the
14086  * variable register that we are working on, and src_reg is a constant or we're
14087  * simply doing a BPF_K check.
14088  * In JEQ/JNE cases we also adjust the var_off values.
14089  */
14090 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14091 			    struct bpf_reg_state *false_reg,
14092 			    u64 val, u32 val32,
14093 			    u8 opcode, bool is_jmp32)
14094 {
14095 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14096 	struct tnum false_64off = false_reg->var_off;
14097 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14098 	struct tnum true_64off = true_reg->var_off;
14099 	s64 sval = (s64)val;
14100 	s32 sval32 = (s32)val32;
14101 
14102 	/* If the dst_reg is a pointer, we can't learn anything about its
14103 	 * variable offset from the compare (unless src_reg were a pointer into
14104 	 * the same object, but we don't bother with that.
14105 	 * Since false_reg and true_reg have the same type by construction, we
14106 	 * only need to check one of them for pointerness.
14107 	 */
14108 	if (__is_pointer_value(false, false_reg))
14109 		return;
14110 
14111 	switch (opcode) {
14112 	/* JEQ/JNE comparison doesn't change the register equivalence.
14113 	 *
14114 	 * r1 = r2;
14115 	 * if (r1 == 42) goto label;
14116 	 * ...
14117 	 * label: // here both r1 and r2 are known to be 42.
14118 	 *
14119 	 * Hence when marking register as known preserve it's ID.
14120 	 */
14121 	case BPF_JEQ:
14122 		if (is_jmp32) {
14123 			__mark_reg32_known(true_reg, val32);
14124 			true_32off = tnum_subreg(true_reg->var_off);
14125 		} else {
14126 			___mark_reg_known(true_reg, val);
14127 			true_64off = true_reg->var_off;
14128 		}
14129 		break;
14130 	case BPF_JNE:
14131 		if (is_jmp32) {
14132 			__mark_reg32_known(false_reg, val32);
14133 			false_32off = tnum_subreg(false_reg->var_off);
14134 		} else {
14135 			___mark_reg_known(false_reg, val);
14136 			false_64off = false_reg->var_off;
14137 		}
14138 		break;
14139 	case BPF_JSET:
14140 		if (is_jmp32) {
14141 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14142 			if (is_power_of_2(val32))
14143 				true_32off = tnum_or(true_32off,
14144 						     tnum_const(val32));
14145 		} else {
14146 			false_64off = tnum_and(false_64off, tnum_const(~val));
14147 			if (is_power_of_2(val))
14148 				true_64off = tnum_or(true_64off,
14149 						     tnum_const(val));
14150 		}
14151 		break;
14152 	case BPF_JGE:
14153 	case BPF_JGT:
14154 	{
14155 		if (is_jmp32) {
14156 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14157 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14158 
14159 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14160 						       false_umax);
14161 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14162 						      true_umin);
14163 		} else {
14164 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14165 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14166 
14167 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14168 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14169 		}
14170 		break;
14171 	}
14172 	case BPF_JSGE:
14173 	case BPF_JSGT:
14174 	{
14175 		if (is_jmp32) {
14176 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14177 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14178 
14179 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14180 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14181 		} else {
14182 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14183 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14184 
14185 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14186 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14187 		}
14188 		break;
14189 	}
14190 	case BPF_JLE:
14191 	case BPF_JLT:
14192 	{
14193 		if (is_jmp32) {
14194 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14195 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14196 
14197 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14198 						       false_umin);
14199 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14200 						      true_umax);
14201 		} else {
14202 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14203 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14204 
14205 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14206 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14207 		}
14208 		break;
14209 	}
14210 	case BPF_JSLE:
14211 	case BPF_JSLT:
14212 	{
14213 		if (is_jmp32) {
14214 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14215 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14216 
14217 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14218 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14219 		} else {
14220 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14221 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14222 
14223 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14224 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14225 		}
14226 		break;
14227 	}
14228 	default:
14229 		return;
14230 	}
14231 
14232 	if (is_jmp32) {
14233 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14234 					     tnum_subreg(false_32off));
14235 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14236 					    tnum_subreg(true_32off));
14237 		__reg_combine_32_into_64(false_reg);
14238 		__reg_combine_32_into_64(true_reg);
14239 	} else {
14240 		false_reg->var_off = false_64off;
14241 		true_reg->var_off = true_64off;
14242 		__reg_combine_64_into_32(false_reg);
14243 		__reg_combine_64_into_32(true_reg);
14244 	}
14245 }
14246 
14247 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14248  * the variable reg.
14249  */
14250 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14251 				struct bpf_reg_state *false_reg,
14252 				u64 val, u32 val32,
14253 				u8 opcode, bool is_jmp32)
14254 {
14255 	opcode = flip_opcode(opcode);
14256 	/* This uses zero as "not present in table"; luckily the zero opcode,
14257 	 * BPF_JA, can't get here.
14258 	 */
14259 	if (opcode)
14260 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14261 }
14262 
14263 /* Regs are known to be equal, so intersect their min/max/var_off */
14264 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14265 				  struct bpf_reg_state *dst_reg)
14266 {
14267 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14268 							dst_reg->umin_value);
14269 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14270 							dst_reg->umax_value);
14271 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14272 							dst_reg->smin_value);
14273 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14274 							dst_reg->smax_value);
14275 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14276 							     dst_reg->var_off);
14277 	reg_bounds_sync(src_reg);
14278 	reg_bounds_sync(dst_reg);
14279 }
14280 
14281 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14282 				struct bpf_reg_state *true_dst,
14283 				struct bpf_reg_state *false_src,
14284 				struct bpf_reg_state *false_dst,
14285 				u8 opcode)
14286 {
14287 	switch (opcode) {
14288 	case BPF_JEQ:
14289 		__reg_combine_min_max(true_src, true_dst);
14290 		break;
14291 	case BPF_JNE:
14292 		__reg_combine_min_max(false_src, false_dst);
14293 		break;
14294 	}
14295 }
14296 
14297 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14298 				 struct bpf_reg_state *reg, u32 id,
14299 				 bool is_null)
14300 {
14301 	if (type_may_be_null(reg->type) && reg->id == id &&
14302 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14303 		/* Old offset (both fixed and variable parts) should have been
14304 		 * known-zero, because we don't allow pointer arithmetic on
14305 		 * pointers that might be NULL. If we see this happening, don't
14306 		 * convert the register.
14307 		 *
14308 		 * But in some cases, some helpers that return local kptrs
14309 		 * advance offset for the returned pointer. In those cases, it
14310 		 * is fine to expect to see reg->off.
14311 		 */
14312 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14313 			return;
14314 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14315 		    WARN_ON_ONCE(reg->off))
14316 			return;
14317 
14318 		if (is_null) {
14319 			reg->type = SCALAR_VALUE;
14320 			/* We don't need id and ref_obj_id from this point
14321 			 * onwards anymore, thus we should better reset it,
14322 			 * so that state pruning has chances to take effect.
14323 			 */
14324 			reg->id = 0;
14325 			reg->ref_obj_id = 0;
14326 
14327 			return;
14328 		}
14329 
14330 		mark_ptr_not_null_reg(reg);
14331 
14332 		if (!reg_may_point_to_spin_lock(reg)) {
14333 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14334 			 * in release_reference().
14335 			 *
14336 			 * reg->id is still used by spin_lock ptr. Other
14337 			 * than spin_lock ptr type, reg->id can be reset.
14338 			 */
14339 			reg->id = 0;
14340 		}
14341 	}
14342 }
14343 
14344 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14345  * be folded together at some point.
14346  */
14347 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14348 				  bool is_null)
14349 {
14350 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14351 	struct bpf_reg_state *regs = state->regs, *reg;
14352 	u32 ref_obj_id = regs[regno].ref_obj_id;
14353 	u32 id = regs[regno].id;
14354 
14355 	if (ref_obj_id && ref_obj_id == id && is_null)
14356 		/* regs[regno] is in the " == NULL" branch.
14357 		 * No one could have freed the reference state before
14358 		 * doing the NULL check.
14359 		 */
14360 		WARN_ON_ONCE(release_reference_state(state, id));
14361 
14362 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14363 		mark_ptr_or_null_reg(state, reg, id, is_null);
14364 	}));
14365 }
14366 
14367 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14368 				   struct bpf_reg_state *dst_reg,
14369 				   struct bpf_reg_state *src_reg,
14370 				   struct bpf_verifier_state *this_branch,
14371 				   struct bpf_verifier_state *other_branch)
14372 {
14373 	if (BPF_SRC(insn->code) != BPF_X)
14374 		return false;
14375 
14376 	/* Pointers are always 64-bit. */
14377 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14378 		return false;
14379 
14380 	switch (BPF_OP(insn->code)) {
14381 	case BPF_JGT:
14382 		if ((dst_reg->type == PTR_TO_PACKET &&
14383 		     src_reg->type == PTR_TO_PACKET_END) ||
14384 		    (dst_reg->type == PTR_TO_PACKET_META &&
14385 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14386 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14387 			find_good_pkt_pointers(this_branch, dst_reg,
14388 					       dst_reg->type, false);
14389 			mark_pkt_end(other_branch, insn->dst_reg, true);
14390 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14391 			    src_reg->type == PTR_TO_PACKET) ||
14392 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14393 			    src_reg->type == PTR_TO_PACKET_META)) {
14394 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14395 			find_good_pkt_pointers(other_branch, src_reg,
14396 					       src_reg->type, true);
14397 			mark_pkt_end(this_branch, insn->src_reg, false);
14398 		} else {
14399 			return false;
14400 		}
14401 		break;
14402 	case BPF_JLT:
14403 		if ((dst_reg->type == PTR_TO_PACKET &&
14404 		     src_reg->type == PTR_TO_PACKET_END) ||
14405 		    (dst_reg->type == PTR_TO_PACKET_META &&
14406 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14407 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14408 			find_good_pkt_pointers(other_branch, dst_reg,
14409 					       dst_reg->type, true);
14410 			mark_pkt_end(this_branch, insn->dst_reg, false);
14411 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14412 			    src_reg->type == PTR_TO_PACKET) ||
14413 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14414 			    src_reg->type == PTR_TO_PACKET_META)) {
14415 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14416 			find_good_pkt_pointers(this_branch, src_reg,
14417 					       src_reg->type, false);
14418 			mark_pkt_end(other_branch, insn->src_reg, true);
14419 		} else {
14420 			return false;
14421 		}
14422 		break;
14423 	case BPF_JGE:
14424 		if ((dst_reg->type == PTR_TO_PACKET &&
14425 		     src_reg->type == PTR_TO_PACKET_END) ||
14426 		    (dst_reg->type == PTR_TO_PACKET_META &&
14427 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14428 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14429 			find_good_pkt_pointers(this_branch, dst_reg,
14430 					       dst_reg->type, true);
14431 			mark_pkt_end(other_branch, insn->dst_reg, false);
14432 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14433 			    src_reg->type == PTR_TO_PACKET) ||
14434 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14435 			    src_reg->type == PTR_TO_PACKET_META)) {
14436 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14437 			find_good_pkt_pointers(other_branch, src_reg,
14438 					       src_reg->type, false);
14439 			mark_pkt_end(this_branch, insn->src_reg, true);
14440 		} else {
14441 			return false;
14442 		}
14443 		break;
14444 	case BPF_JLE:
14445 		if ((dst_reg->type == PTR_TO_PACKET &&
14446 		     src_reg->type == PTR_TO_PACKET_END) ||
14447 		    (dst_reg->type == PTR_TO_PACKET_META &&
14448 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14449 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14450 			find_good_pkt_pointers(other_branch, dst_reg,
14451 					       dst_reg->type, false);
14452 			mark_pkt_end(this_branch, insn->dst_reg, true);
14453 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14454 			    src_reg->type == PTR_TO_PACKET) ||
14455 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14456 			    src_reg->type == PTR_TO_PACKET_META)) {
14457 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14458 			find_good_pkt_pointers(this_branch, src_reg,
14459 					       src_reg->type, true);
14460 			mark_pkt_end(other_branch, insn->src_reg, false);
14461 		} else {
14462 			return false;
14463 		}
14464 		break;
14465 	default:
14466 		return false;
14467 	}
14468 
14469 	return true;
14470 }
14471 
14472 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14473 			       struct bpf_reg_state *known_reg)
14474 {
14475 	struct bpf_func_state *state;
14476 	struct bpf_reg_state *reg;
14477 
14478 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14479 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14480 			copy_register_state(reg, known_reg);
14481 	}));
14482 }
14483 
14484 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14485 			     struct bpf_insn *insn, int *insn_idx)
14486 {
14487 	struct bpf_verifier_state *this_branch = env->cur_state;
14488 	struct bpf_verifier_state *other_branch;
14489 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14490 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14491 	struct bpf_reg_state *eq_branch_regs;
14492 	u8 opcode = BPF_OP(insn->code);
14493 	bool is_jmp32;
14494 	int pred = -1;
14495 	int err;
14496 
14497 	/* Only conditional jumps are expected to reach here. */
14498 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14499 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14500 		return -EINVAL;
14501 	}
14502 
14503 	/* check src2 operand */
14504 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14505 	if (err)
14506 		return err;
14507 
14508 	dst_reg = &regs[insn->dst_reg];
14509 	if (BPF_SRC(insn->code) == BPF_X) {
14510 		if (insn->imm != 0) {
14511 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14512 			return -EINVAL;
14513 		}
14514 
14515 		/* check src1 operand */
14516 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14517 		if (err)
14518 			return err;
14519 
14520 		src_reg = &regs[insn->src_reg];
14521 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14522 		    is_pointer_value(env, insn->src_reg)) {
14523 			verbose(env, "R%d pointer comparison prohibited\n",
14524 				insn->src_reg);
14525 			return -EACCES;
14526 		}
14527 	} else {
14528 		if (insn->src_reg != BPF_REG_0) {
14529 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14530 			return -EINVAL;
14531 		}
14532 	}
14533 
14534 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14535 
14536 	if (BPF_SRC(insn->code) == BPF_K) {
14537 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14538 	} else if (src_reg->type == SCALAR_VALUE &&
14539 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14540 		pred = is_branch_taken(dst_reg,
14541 				       tnum_subreg(src_reg->var_off).value,
14542 				       opcode,
14543 				       is_jmp32);
14544 	} else if (src_reg->type == SCALAR_VALUE &&
14545 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14546 		pred = is_branch_taken(dst_reg,
14547 				       src_reg->var_off.value,
14548 				       opcode,
14549 				       is_jmp32);
14550 	} else if (dst_reg->type == SCALAR_VALUE &&
14551 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14552 		pred = is_branch_taken(src_reg,
14553 				       tnum_subreg(dst_reg->var_off).value,
14554 				       flip_opcode(opcode),
14555 				       is_jmp32);
14556 	} else if (dst_reg->type == SCALAR_VALUE &&
14557 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14558 		pred = is_branch_taken(src_reg,
14559 				       dst_reg->var_off.value,
14560 				       flip_opcode(opcode),
14561 				       is_jmp32);
14562 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14563 		   reg_is_pkt_pointer_any(src_reg) &&
14564 		   !is_jmp32) {
14565 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14566 	}
14567 
14568 	if (pred >= 0) {
14569 		/* If we get here with a dst_reg pointer type it is because
14570 		 * above is_branch_taken() special cased the 0 comparison.
14571 		 */
14572 		if (!__is_pointer_value(false, dst_reg))
14573 			err = mark_chain_precision(env, insn->dst_reg);
14574 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14575 		    !__is_pointer_value(false, src_reg))
14576 			err = mark_chain_precision(env, insn->src_reg);
14577 		if (err)
14578 			return err;
14579 	}
14580 
14581 	if (pred == 1) {
14582 		/* Only follow the goto, ignore fall-through. If needed, push
14583 		 * the fall-through branch for simulation under speculative
14584 		 * execution.
14585 		 */
14586 		if (!env->bypass_spec_v1 &&
14587 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14588 					       *insn_idx))
14589 			return -EFAULT;
14590 		if (env->log.level & BPF_LOG_LEVEL)
14591 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14592 		*insn_idx += insn->off;
14593 		return 0;
14594 	} else if (pred == 0) {
14595 		/* Only follow the fall-through branch, since that's where the
14596 		 * program will go. If needed, push the goto branch for
14597 		 * simulation under speculative execution.
14598 		 */
14599 		if (!env->bypass_spec_v1 &&
14600 		    !sanitize_speculative_path(env, insn,
14601 					       *insn_idx + insn->off + 1,
14602 					       *insn_idx))
14603 			return -EFAULT;
14604 		if (env->log.level & BPF_LOG_LEVEL)
14605 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14606 		return 0;
14607 	}
14608 
14609 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14610 				  false);
14611 	if (!other_branch)
14612 		return -EFAULT;
14613 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14614 
14615 	/* detect if we are comparing against a constant value so we can adjust
14616 	 * our min/max values for our dst register.
14617 	 * this is only legit if both are scalars (or pointers to the same
14618 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14619 	 * because otherwise the different base pointers mean the offsets aren't
14620 	 * comparable.
14621 	 */
14622 	if (BPF_SRC(insn->code) == BPF_X) {
14623 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14624 
14625 		if (dst_reg->type == SCALAR_VALUE &&
14626 		    src_reg->type == SCALAR_VALUE) {
14627 			if (tnum_is_const(src_reg->var_off) ||
14628 			    (is_jmp32 &&
14629 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14630 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14631 						dst_reg,
14632 						src_reg->var_off.value,
14633 						tnum_subreg(src_reg->var_off).value,
14634 						opcode, is_jmp32);
14635 			else if (tnum_is_const(dst_reg->var_off) ||
14636 				 (is_jmp32 &&
14637 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14638 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14639 						    src_reg,
14640 						    dst_reg->var_off.value,
14641 						    tnum_subreg(dst_reg->var_off).value,
14642 						    opcode, is_jmp32);
14643 			else if (!is_jmp32 &&
14644 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14645 				/* Comparing for equality, we can combine knowledge */
14646 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14647 						    &other_branch_regs[insn->dst_reg],
14648 						    src_reg, dst_reg, opcode);
14649 			if (src_reg->id &&
14650 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14651 				find_equal_scalars(this_branch, src_reg);
14652 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14653 			}
14654 
14655 		}
14656 	} else if (dst_reg->type == SCALAR_VALUE) {
14657 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14658 					dst_reg, insn->imm, (u32)insn->imm,
14659 					opcode, is_jmp32);
14660 	}
14661 
14662 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14663 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14664 		find_equal_scalars(this_branch, dst_reg);
14665 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14666 	}
14667 
14668 	/* if one pointer register is compared to another pointer
14669 	 * register check if PTR_MAYBE_NULL could be lifted.
14670 	 * E.g. register A - maybe null
14671 	 *      register B - not null
14672 	 * for JNE A, B, ... - A is not null in the false branch;
14673 	 * for JEQ A, B, ... - A is not null in the true branch.
14674 	 *
14675 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14676 	 * not need to be null checked by the BPF program, i.e.,
14677 	 * could be null even without PTR_MAYBE_NULL marking, so
14678 	 * only propagate nullness when neither reg is that type.
14679 	 */
14680 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14681 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14682 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14683 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14684 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14685 		eq_branch_regs = NULL;
14686 		switch (opcode) {
14687 		case BPF_JEQ:
14688 			eq_branch_regs = other_branch_regs;
14689 			break;
14690 		case BPF_JNE:
14691 			eq_branch_regs = regs;
14692 			break;
14693 		default:
14694 			/* do nothing */
14695 			break;
14696 		}
14697 		if (eq_branch_regs) {
14698 			if (type_may_be_null(src_reg->type))
14699 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14700 			else
14701 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14702 		}
14703 	}
14704 
14705 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14706 	 * NOTE: these optimizations below are related with pointer comparison
14707 	 *       which will never be JMP32.
14708 	 */
14709 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14710 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14711 	    type_may_be_null(dst_reg->type)) {
14712 		/* Mark all identical registers in each branch as either
14713 		 * safe or unknown depending R == 0 or R != 0 conditional.
14714 		 */
14715 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14716 				      opcode == BPF_JNE);
14717 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14718 				      opcode == BPF_JEQ);
14719 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14720 					   this_branch, other_branch) &&
14721 		   is_pointer_value(env, insn->dst_reg)) {
14722 		verbose(env, "R%d pointer comparison prohibited\n",
14723 			insn->dst_reg);
14724 		return -EACCES;
14725 	}
14726 	if (env->log.level & BPF_LOG_LEVEL)
14727 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14728 	return 0;
14729 }
14730 
14731 /* verify BPF_LD_IMM64 instruction */
14732 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14733 {
14734 	struct bpf_insn_aux_data *aux = cur_aux(env);
14735 	struct bpf_reg_state *regs = cur_regs(env);
14736 	struct bpf_reg_state *dst_reg;
14737 	struct bpf_map *map;
14738 	int err;
14739 
14740 	if (BPF_SIZE(insn->code) != BPF_DW) {
14741 		verbose(env, "invalid BPF_LD_IMM insn\n");
14742 		return -EINVAL;
14743 	}
14744 	if (insn->off != 0) {
14745 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14746 		return -EINVAL;
14747 	}
14748 
14749 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14750 	if (err)
14751 		return err;
14752 
14753 	dst_reg = &regs[insn->dst_reg];
14754 	if (insn->src_reg == 0) {
14755 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14756 
14757 		dst_reg->type = SCALAR_VALUE;
14758 		__mark_reg_known(&regs[insn->dst_reg], imm);
14759 		return 0;
14760 	}
14761 
14762 	/* All special src_reg cases are listed below. From this point onwards
14763 	 * we either succeed and assign a corresponding dst_reg->type after
14764 	 * zeroing the offset, or fail and reject the program.
14765 	 */
14766 	mark_reg_known_zero(env, regs, insn->dst_reg);
14767 
14768 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14769 		dst_reg->type = aux->btf_var.reg_type;
14770 		switch (base_type(dst_reg->type)) {
14771 		case PTR_TO_MEM:
14772 			dst_reg->mem_size = aux->btf_var.mem_size;
14773 			break;
14774 		case PTR_TO_BTF_ID:
14775 			dst_reg->btf = aux->btf_var.btf;
14776 			dst_reg->btf_id = aux->btf_var.btf_id;
14777 			break;
14778 		default:
14779 			verbose(env, "bpf verifier is misconfigured\n");
14780 			return -EFAULT;
14781 		}
14782 		return 0;
14783 	}
14784 
14785 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14786 		struct bpf_prog_aux *aux = env->prog->aux;
14787 		u32 subprogno = find_subprog(env,
14788 					     env->insn_idx + insn->imm + 1);
14789 
14790 		if (!aux->func_info) {
14791 			verbose(env, "missing btf func_info\n");
14792 			return -EINVAL;
14793 		}
14794 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14795 			verbose(env, "callback function not static\n");
14796 			return -EINVAL;
14797 		}
14798 
14799 		dst_reg->type = PTR_TO_FUNC;
14800 		dst_reg->subprogno = subprogno;
14801 		return 0;
14802 	}
14803 
14804 	map = env->used_maps[aux->map_index];
14805 	dst_reg->map_ptr = map;
14806 
14807 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14808 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14809 		dst_reg->type = PTR_TO_MAP_VALUE;
14810 		dst_reg->off = aux->map_off;
14811 		WARN_ON_ONCE(map->max_entries != 1);
14812 		/* We want reg->id to be same (0) as map_value is not distinct */
14813 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14814 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14815 		dst_reg->type = CONST_PTR_TO_MAP;
14816 	} else {
14817 		verbose(env, "bpf verifier is misconfigured\n");
14818 		return -EINVAL;
14819 	}
14820 
14821 	return 0;
14822 }
14823 
14824 static bool may_access_skb(enum bpf_prog_type type)
14825 {
14826 	switch (type) {
14827 	case BPF_PROG_TYPE_SOCKET_FILTER:
14828 	case BPF_PROG_TYPE_SCHED_CLS:
14829 	case BPF_PROG_TYPE_SCHED_ACT:
14830 		return true;
14831 	default:
14832 		return false;
14833 	}
14834 }
14835 
14836 /* verify safety of LD_ABS|LD_IND instructions:
14837  * - they can only appear in the programs where ctx == skb
14838  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14839  *   preserve R6-R9, and store return value into R0
14840  *
14841  * Implicit input:
14842  *   ctx == skb == R6 == CTX
14843  *
14844  * Explicit input:
14845  *   SRC == any register
14846  *   IMM == 32-bit immediate
14847  *
14848  * Output:
14849  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14850  */
14851 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14852 {
14853 	struct bpf_reg_state *regs = cur_regs(env);
14854 	static const int ctx_reg = BPF_REG_6;
14855 	u8 mode = BPF_MODE(insn->code);
14856 	int i, err;
14857 
14858 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14859 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14860 		return -EINVAL;
14861 	}
14862 
14863 	if (!env->ops->gen_ld_abs) {
14864 		verbose(env, "bpf verifier is misconfigured\n");
14865 		return -EINVAL;
14866 	}
14867 
14868 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14869 	    BPF_SIZE(insn->code) == BPF_DW ||
14870 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14871 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14872 		return -EINVAL;
14873 	}
14874 
14875 	/* check whether implicit source operand (register R6) is readable */
14876 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14877 	if (err)
14878 		return err;
14879 
14880 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14881 	 * gen_ld_abs() may terminate the program at runtime, leading to
14882 	 * reference leak.
14883 	 */
14884 	err = check_reference_leak(env);
14885 	if (err) {
14886 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14887 		return err;
14888 	}
14889 
14890 	if (env->cur_state->active_lock.ptr) {
14891 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14892 		return -EINVAL;
14893 	}
14894 
14895 	if (env->cur_state->active_rcu_lock) {
14896 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14897 		return -EINVAL;
14898 	}
14899 
14900 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14901 		verbose(env,
14902 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14903 		return -EINVAL;
14904 	}
14905 
14906 	if (mode == BPF_IND) {
14907 		/* check explicit source operand */
14908 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14909 		if (err)
14910 			return err;
14911 	}
14912 
14913 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14914 	if (err < 0)
14915 		return err;
14916 
14917 	/* reset caller saved regs to unreadable */
14918 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14919 		mark_reg_not_init(env, regs, caller_saved[i]);
14920 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14921 	}
14922 
14923 	/* mark destination R0 register as readable, since it contains
14924 	 * the value fetched from the packet.
14925 	 * Already marked as written above.
14926 	 */
14927 	mark_reg_unknown(env, regs, BPF_REG_0);
14928 	/* ld_abs load up to 32-bit skb data. */
14929 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14930 	return 0;
14931 }
14932 
14933 static int check_return_code(struct bpf_verifier_env *env)
14934 {
14935 	struct tnum enforce_attach_type_range = tnum_unknown;
14936 	const struct bpf_prog *prog = env->prog;
14937 	struct bpf_reg_state *reg;
14938 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14939 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14940 	int err;
14941 	struct bpf_func_state *frame = env->cur_state->frame[0];
14942 	const bool is_subprog = frame->subprogno;
14943 
14944 	/* LSM and struct_ops func-ptr's return type could be "void" */
14945 	if (!is_subprog) {
14946 		switch (prog_type) {
14947 		case BPF_PROG_TYPE_LSM:
14948 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14949 				/* See below, can be 0 or 0-1 depending on hook. */
14950 				break;
14951 			fallthrough;
14952 		case BPF_PROG_TYPE_STRUCT_OPS:
14953 			if (!prog->aux->attach_func_proto->type)
14954 				return 0;
14955 			break;
14956 		default:
14957 			break;
14958 		}
14959 	}
14960 
14961 	/* eBPF calling convention is such that R0 is used
14962 	 * to return the value from eBPF program.
14963 	 * Make sure that it's readable at this time
14964 	 * of bpf_exit, which means that program wrote
14965 	 * something into it earlier
14966 	 */
14967 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14968 	if (err)
14969 		return err;
14970 
14971 	if (is_pointer_value(env, BPF_REG_0)) {
14972 		verbose(env, "R0 leaks addr as return value\n");
14973 		return -EACCES;
14974 	}
14975 
14976 	reg = cur_regs(env) + BPF_REG_0;
14977 
14978 	if (frame->in_async_callback_fn) {
14979 		/* enforce return zero from async callbacks like timer */
14980 		if (reg->type != SCALAR_VALUE) {
14981 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14982 				reg_type_str(env, reg->type));
14983 			return -EINVAL;
14984 		}
14985 
14986 		if (!tnum_in(const_0, reg->var_off)) {
14987 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14988 			return -EINVAL;
14989 		}
14990 		return 0;
14991 	}
14992 
14993 	if (is_subprog) {
14994 		if (reg->type != SCALAR_VALUE) {
14995 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14996 				reg_type_str(env, reg->type));
14997 			return -EINVAL;
14998 		}
14999 		return 0;
15000 	}
15001 
15002 	switch (prog_type) {
15003 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15004 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15005 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15006 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15007 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15008 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15009 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15010 			range = tnum_range(1, 1);
15011 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15012 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15013 			range = tnum_range(0, 3);
15014 		break;
15015 	case BPF_PROG_TYPE_CGROUP_SKB:
15016 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15017 			range = tnum_range(0, 3);
15018 			enforce_attach_type_range = tnum_range(2, 3);
15019 		}
15020 		break;
15021 	case BPF_PROG_TYPE_CGROUP_SOCK:
15022 	case BPF_PROG_TYPE_SOCK_OPS:
15023 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15024 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15025 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15026 		break;
15027 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15028 		if (!env->prog->aux->attach_btf_id)
15029 			return 0;
15030 		range = tnum_const(0);
15031 		break;
15032 	case BPF_PROG_TYPE_TRACING:
15033 		switch (env->prog->expected_attach_type) {
15034 		case BPF_TRACE_FENTRY:
15035 		case BPF_TRACE_FEXIT:
15036 			range = tnum_const(0);
15037 			break;
15038 		case BPF_TRACE_RAW_TP:
15039 		case BPF_MODIFY_RETURN:
15040 			return 0;
15041 		case BPF_TRACE_ITER:
15042 			break;
15043 		default:
15044 			return -ENOTSUPP;
15045 		}
15046 		break;
15047 	case BPF_PROG_TYPE_SK_LOOKUP:
15048 		range = tnum_range(SK_DROP, SK_PASS);
15049 		break;
15050 
15051 	case BPF_PROG_TYPE_LSM:
15052 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15053 			/* Regular BPF_PROG_TYPE_LSM programs can return
15054 			 * any value.
15055 			 */
15056 			return 0;
15057 		}
15058 		if (!env->prog->aux->attach_func_proto->type) {
15059 			/* Make sure programs that attach to void
15060 			 * hooks don't try to modify return value.
15061 			 */
15062 			range = tnum_range(1, 1);
15063 		}
15064 		break;
15065 
15066 	case BPF_PROG_TYPE_NETFILTER:
15067 		range = tnum_range(NF_DROP, NF_ACCEPT);
15068 		break;
15069 	case BPF_PROG_TYPE_EXT:
15070 		/* freplace program can return anything as its return value
15071 		 * depends on the to-be-replaced kernel func or bpf program.
15072 		 */
15073 	default:
15074 		return 0;
15075 	}
15076 
15077 	if (reg->type != SCALAR_VALUE) {
15078 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15079 			reg_type_str(env, reg->type));
15080 		return -EINVAL;
15081 	}
15082 
15083 	if (!tnum_in(range, reg->var_off)) {
15084 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15085 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15086 		    prog_type == BPF_PROG_TYPE_LSM &&
15087 		    !prog->aux->attach_func_proto->type)
15088 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15089 		return -EINVAL;
15090 	}
15091 
15092 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15093 	    tnum_in(enforce_attach_type_range, reg->var_off))
15094 		env->prog->enforce_expected_attach_type = 1;
15095 	return 0;
15096 }
15097 
15098 /* non-recursive DFS pseudo code
15099  * 1  procedure DFS-iterative(G,v):
15100  * 2      label v as discovered
15101  * 3      let S be a stack
15102  * 4      S.push(v)
15103  * 5      while S is not empty
15104  * 6            t <- S.peek()
15105  * 7            if t is what we're looking for:
15106  * 8                return t
15107  * 9            for all edges e in G.adjacentEdges(t) do
15108  * 10               if edge e is already labelled
15109  * 11                   continue with the next edge
15110  * 12               w <- G.adjacentVertex(t,e)
15111  * 13               if vertex w is not discovered and not explored
15112  * 14                   label e as tree-edge
15113  * 15                   label w as discovered
15114  * 16                   S.push(w)
15115  * 17                   continue at 5
15116  * 18               else if vertex w is discovered
15117  * 19                   label e as back-edge
15118  * 20               else
15119  * 21                   // vertex w is explored
15120  * 22                   label e as forward- or cross-edge
15121  * 23           label t as explored
15122  * 24           S.pop()
15123  *
15124  * convention:
15125  * 0x10 - discovered
15126  * 0x11 - discovered and fall-through edge labelled
15127  * 0x12 - discovered and fall-through and branch edges labelled
15128  * 0x20 - explored
15129  */
15130 
15131 enum {
15132 	DISCOVERED = 0x10,
15133 	EXPLORED = 0x20,
15134 	FALLTHROUGH = 1,
15135 	BRANCH = 2,
15136 };
15137 
15138 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15139 {
15140 	env->insn_aux_data[idx].prune_point = true;
15141 }
15142 
15143 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15144 {
15145 	return env->insn_aux_data[insn_idx].prune_point;
15146 }
15147 
15148 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15149 {
15150 	env->insn_aux_data[idx].force_checkpoint = true;
15151 }
15152 
15153 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15154 {
15155 	return env->insn_aux_data[insn_idx].force_checkpoint;
15156 }
15157 
15158 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15159 {
15160 	env->insn_aux_data[idx].calls_callback = true;
15161 }
15162 
15163 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15164 {
15165 	return env->insn_aux_data[insn_idx].calls_callback;
15166 }
15167 
15168 enum {
15169 	DONE_EXPLORING = 0,
15170 	KEEP_EXPLORING = 1,
15171 };
15172 
15173 /* t, w, e - match pseudo-code above:
15174  * t - index of current instruction
15175  * w - next instruction
15176  * e - edge
15177  */
15178 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15179 {
15180 	int *insn_stack = env->cfg.insn_stack;
15181 	int *insn_state = env->cfg.insn_state;
15182 
15183 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15184 		return DONE_EXPLORING;
15185 
15186 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15187 		return DONE_EXPLORING;
15188 
15189 	if (w < 0 || w >= env->prog->len) {
15190 		verbose_linfo(env, t, "%d: ", t);
15191 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15192 		return -EINVAL;
15193 	}
15194 
15195 	if (e == BRANCH) {
15196 		/* mark branch target for state pruning */
15197 		mark_prune_point(env, w);
15198 		mark_jmp_point(env, w);
15199 	}
15200 
15201 	if (insn_state[w] == 0) {
15202 		/* tree-edge */
15203 		insn_state[t] = DISCOVERED | e;
15204 		insn_state[w] = DISCOVERED;
15205 		if (env->cfg.cur_stack >= env->prog->len)
15206 			return -E2BIG;
15207 		insn_stack[env->cfg.cur_stack++] = w;
15208 		return KEEP_EXPLORING;
15209 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15210 		if (env->bpf_capable)
15211 			return DONE_EXPLORING;
15212 		verbose_linfo(env, t, "%d: ", t);
15213 		verbose_linfo(env, w, "%d: ", w);
15214 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15215 		return -EINVAL;
15216 	} else if (insn_state[w] == EXPLORED) {
15217 		/* forward- or cross-edge */
15218 		insn_state[t] = DISCOVERED | e;
15219 	} else {
15220 		verbose(env, "insn state internal bug\n");
15221 		return -EFAULT;
15222 	}
15223 	return DONE_EXPLORING;
15224 }
15225 
15226 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15227 				struct bpf_verifier_env *env,
15228 				bool visit_callee)
15229 {
15230 	int ret, insn_sz;
15231 
15232 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15233 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15234 	if (ret)
15235 		return ret;
15236 
15237 	mark_prune_point(env, t + insn_sz);
15238 	/* when we exit from subprog, we need to record non-linear history */
15239 	mark_jmp_point(env, t + insn_sz);
15240 
15241 	if (visit_callee) {
15242 		mark_prune_point(env, t);
15243 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15244 	}
15245 	return ret;
15246 }
15247 
15248 /* Visits the instruction at index t and returns one of the following:
15249  *  < 0 - an error occurred
15250  *  DONE_EXPLORING - the instruction was fully explored
15251  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15252  */
15253 static int visit_insn(int t, struct bpf_verifier_env *env)
15254 {
15255 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15256 	int ret, off, insn_sz;
15257 
15258 	if (bpf_pseudo_func(insn))
15259 		return visit_func_call_insn(t, insns, env, true);
15260 
15261 	/* All non-branch instructions have a single fall-through edge. */
15262 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15263 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15264 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15265 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15266 	}
15267 
15268 	switch (BPF_OP(insn->code)) {
15269 	case BPF_EXIT:
15270 		return DONE_EXPLORING;
15271 
15272 	case BPF_CALL:
15273 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15274 			/* Mark this call insn as a prune point to trigger
15275 			 * is_state_visited() check before call itself is
15276 			 * processed by __check_func_call(). Otherwise new
15277 			 * async state will be pushed for further exploration.
15278 			 */
15279 			mark_prune_point(env, t);
15280 		/* For functions that invoke callbacks it is not known how many times
15281 		 * callback would be called. Verifier models callback calling functions
15282 		 * by repeatedly visiting callback bodies and returning to origin call
15283 		 * instruction.
15284 		 * In order to stop such iteration verifier needs to identify when a
15285 		 * state identical some state from a previous iteration is reached.
15286 		 * Check below forces creation of checkpoint before callback calling
15287 		 * instruction to allow search for such identical states.
15288 		 */
15289 		if (is_sync_callback_calling_insn(insn)) {
15290 			mark_calls_callback(env, t);
15291 			mark_force_checkpoint(env, t);
15292 			mark_prune_point(env, t);
15293 			mark_jmp_point(env, t);
15294 		}
15295 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15296 			struct bpf_kfunc_call_arg_meta meta;
15297 
15298 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15299 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15300 				mark_prune_point(env, t);
15301 				/* Checking and saving state checkpoints at iter_next() call
15302 				 * is crucial for fast convergence of open-coded iterator loop
15303 				 * logic, so we need to force it. If we don't do that,
15304 				 * is_state_visited() might skip saving a checkpoint, causing
15305 				 * unnecessarily long sequence of not checkpointed
15306 				 * instructions and jumps, leading to exhaustion of jump
15307 				 * history buffer, and potentially other undesired outcomes.
15308 				 * It is expected that with correct open-coded iterators
15309 				 * convergence will happen quickly, so we don't run a risk of
15310 				 * exhausting memory.
15311 				 */
15312 				mark_force_checkpoint(env, t);
15313 			}
15314 		}
15315 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15316 
15317 	case BPF_JA:
15318 		if (BPF_SRC(insn->code) != BPF_K)
15319 			return -EINVAL;
15320 
15321 		if (BPF_CLASS(insn->code) == BPF_JMP)
15322 			off = insn->off;
15323 		else
15324 			off = insn->imm;
15325 
15326 		/* unconditional jump with single edge */
15327 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15328 		if (ret)
15329 			return ret;
15330 
15331 		mark_prune_point(env, t + off + 1);
15332 		mark_jmp_point(env, t + off + 1);
15333 
15334 		return ret;
15335 
15336 	default:
15337 		/* conditional jump with two edges */
15338 		mark_prune_point(env, t);
15339 
15340 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15341 		if (ret)
15342 			return ret;
15343 
15344 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15345 	}
15346 }
15347 
15348 /* non-recursive depth-first-search to detect loops in BPF program
15349  * loop == back-edge in directed graph
15350  */
15351 static int check_cfg(struct bpf_verifier_env *env)
15352 {
15353 	int insn_cnt = env->prog->len;
15354 	int *insn_stack, *insn_state;
15355 	int ret = 0;
15356 	int i;
15357 
15358 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15359 	if (!insn_state)
15360 		return -ENOMEM;
15361 
15362 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15363 	if (!insn_stack) {
15364 		kvfree(insn_state);
15365 		return -ENOMEM;
15366 	}
15367 
15368 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15369 	insn_stack[0] = 0; /* 0 is the first instruction */
15370 	env->cfg.cur_stack = 1;
15371 
15372 	while (env->cfg.cur_stack > 0) {
15373 		int t = insn_stack[env->cfg.cur_stack - 1];
15374 
15375 		ret = visit_insn(t, env);
15376 		switch (ret) {
15377 		case DONE_EXPLORING:
15378 			insn_state[t] = EXPLORED;
15379 			env->cfg.cur_stack--;
15380 			break;
15381 		case KEEP_EXPLORING:
15382 			break;
15383 		default:
15384 			if (ret > 0) {
15385 				verbose(env, "visit_insn internal bug\n");
15386 				ret = -EFAULT;
15387 			}
15388 			goto err_free;
15389 		}
15390 	}
15391 
15392 	if (env->cfg.cur_stack < 0) {
15393 		verbose(env, "pop stack internal bug\n");
15394 		ret = -EFAULT;
15395 		goto err_free;
15396 	}
15397 
15398 	for (i = 0; i < insn_cnt; i++) {
15399 		struct bpf_insn *insn = &env->prog->insnsi[i];
15400 
15401 		if (insn_state[i] != EXPLORED) {
15402 			verbose(env, "unreachable insn %d\n", i);
15403 			ret = -EINVAL;
15404 			goto err_free;
15405 		}
15406 		if (bpf_is_ldimm64(insn)) {
15407 			if (insn_state[i + 1] != 0) {
15408 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15409 				ret = -EINVAL;
15410 				goto err_free;
15411 			}
15412 			i++; /* skip second half of ldimm64 */
15413 		}
15414 	}
15415 	ret = 0; /* cfg looks good */
15416 
15417 err_free:
15418 	kvfree(insn_state);
15419 	kvfree(insn_stack);
15420 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15421 	return ret;
15422 }
15423 
15424 static int check_abnormal_return(struct bpf_verifier_env *env)
15425 {
15426 	int i;
15427 
15428 	for (i = 1; i < env->subprog_cnt; i++) {
15429 		if (env->subprog_info[i].has_ld_abs) {
15430 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15431 			return -EINVAL;
15432 		}
15433 		if (env->subprog_info[i].has_tail_call) {
15434 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15435 			return -EINVAL;
15436 		}
15437 	}
15438 	return 0;
15439 }
15440 
15441 /* The minimum supported BTF func info size */
15442 #define MIN_BPF_FUNCINFO_SIZE	8
15443 #define MAX_FUNCINFO_REC_SIZE	252
15444 
15445 static int check_btf_func(struct bpf_verifier_env *env,
15446 			  const union bpf_attr *attr,
15447 			  bpfptr_t uattr)
15448 {
15449 	const struct btf_type *type, *func_proto, *ret_type;
15450 	u32 i, nfuncs, urec_size, min_size;
15451 	u32 krec_size = sizeof(struct bpf_func_info);
15452 	struct bpf_func_info *krecord;
15453 	struct bpf_func_info_aux *info_aux = NULL;
15454 	struct bpf_prog *prog;
15455 	const struct btf *btf;
15456 	bpfptr_t urecord;
15457 	u32 prev_offset = 0;
15458 	bool scalar_return;
15459 	int ret = -ENOMEM;
15460 
15461 	nfuncs = attr->func_info_cnt;
15462 	if (!nfuncs) {
15463 		if (check_abnormal_return(env))
15464 			return -EINVAL;
15465 		return 0;
15466 	}
15467 
15468 	if (nfuncs != env->subprog_cnt) {
15469 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15470 		return -EINVAL;
15471 	}
15472 
15473 	urec_size = attr->func_info_rec_size;
15474 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15475 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15476 	    urec_size % sizeof(u32)) {
15477 		verbose(env, "invalid func info rec size %u\n", urec_size);
15478 		return -EINVAL;
15479 	}
15480 
15481 	prog = env->prog;
15482 	btf = prog->aux->btf;
15483 
15484 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15485 	min_size = min_t(u32, krec_size, urec_size);
15486 
15487 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15488 	if (!krecord)
15489 		return -ENOMEM;
15490 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15491 	if (!info_aux)
15492 		goto err_free;
15493 
15494 	for (i = 0; i < nfuncs; i++) {
15495 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15496 		if (ret) {
15497 			if (ret == -E2BIG) {
15498 				verbose(env, "nonzero tailing record in func info");
15499 				/* set the size kernel expects so loader can zero
15500 				 * out the rest of the record.
15501 				 */
15502 				if (copy_to_bpfptr_offset(uattr,
15503 							  offsetof(union bpf_attr, func_info_rec_size),
15504 							  &min_size, sizeof(min_size)))
15505 					ret = -EFAULT;
15506 			}
15507 			goto err_free;
15508 		}
15509 
15510 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15511 			ret = -EFAULT;
15512 			goto err_free;
15513 		}
15514 
15515 		/* check insn_off */
15516 		ret = -EINVAL;
15517 		if (i == 0) {
15518 			if (krecord[i].insn_off) {
15519 				verbose(env,
15520 					"nonzero insn_off %u for the first func info record",
15521 					krecord[i].insn_off);
15522 				goto err_free;
15523 			}
15524 		} else if (krecord[i].insn_off <= prev_offset) {
15525 			verbose(env,
15526 				"same or smaller insn offset (%u) than previous func info record (%u)",
15527 				krecord[i].insn_off, prev_offset);
15528 			goto err_free;
15529 		}
15530 
15531 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15532 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15533 			goto err_free;
15534 		}
15535 
15536 		/* check type_id */
15537 		type = btf_type_by_id(btf, krecord[i].type_id);
15538 		if (!type || !btf_type_is_func(type)) {
15539 			verbose(env, "invalid type id %d in func info",
15540 				krecord[i].type_id);
15541 			goto err_free;
15542 		}
15543 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15544 
15545 		func_proto = btf_type_by_id(btf, type->type);
15546 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15547 			/* btf_func_check() already verified it during BTF load */
15548 			goto err_free;
15549 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15550 		scalar_return =
15551 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15552 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15553 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15554 			goto err_free;
15555 		}
15556 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15557 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15558 			goto err_free;
15559 		}
15560 
15561 		prev_offset = krecord[i].insn_off;
15562 		bpfptr_add(&urecord, urec_size);
15563 	}
15564 
15565 	prog->aux->func_info = krecord;
15566 	prog->aux->func_info_cnt = nfuncs;
15567 	prog->aux->func_info_aux = info_aux;
15568 	return 0;
15569 
15570 err_free:
15571 	kvfree(krecord);
15572 	kfree(info_aux);
15573 	return ret;
15574 }
15575 
15576 static void adjust_btf_func(struct bpf_verifier_env *env)
15577 {
15578 	struct bpf_prog_aux *aux = env->prog->aux;
15579 	int i;
15580 
15581 	if (!aux->func_info)
15582 		return;
15583 
15584 	for (i = 0; i < env->subprog_cnt; i++)
15585 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15586 }
15587 
15588 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15589 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15590 
15591 static int check_btf_line(struct bpf_verifier_env *env,
15592 			  const union bpf_attr *attr,
15593 			  bpfptr_t uattr)
15594 {
15595 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15596 	struct bpf_subprog_info *sub;
15597 	struct bpf_line_info *linfo;
15598 	struct bpf_prog *prog;
15599 	const struct btf *btf;
15600 	bpfptr_t ulinfo;
15601 	int err;
15602 
15603 	nr_linfo = attr->line_info_cnt;
15604 	if (!nr_linfo)
15605 		return 0;
15606 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15607 		return -EINVAL;
15608 
15609 	rec_size = attr->line_info_rec_size;
15610 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15611 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15612 	    rec_size & (sizeof(u32) - 1))
15613 		return -EINVAL;
15614 
15615 	/* Need to zero it in case the userspace may
15616 	 * pass in a smaller bpf_line_info object.
15617 	 */
15618 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15619 			 GFP_KERNEL | __GFP_NOWARN);
15620 	if (!linfo)
15621 		return -ENOMEM;
15622 
15623 	prog = env->prog;
15624 	btf = prog->aux->btf;
15625 
15626 	s = 0;
15627 	sub = env->subprog_info;
15628 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15629 	expected_size = sizeof(struct bpf_line_info);
15630 	ncopy = min_t(u32, expected_size, rec_size);
15631 	for (i = 0; i < nr_linfo; i++) {
15632 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15633 		if (err) {
15634 			if (err == -E2BIG) {
15635 				verbose(env, "nonzero tailing record in line_info");
15636 				if (copy_to_bpfptr_offset(uattr,
15637 							  offsetof(union bpf_attr, line_info_rec_size),
15638 							  &expected_size, sizeof(expected_size)))
15639 					err = -EFAULT;
15640 			}
15641 			goto err_free;
15642 		}
15643 
15644 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15645 			err = -EFAULT;
15646 			goto err_free;
15647 		}
15648 
15649 		/*
15650 		 * Check insn_off to ensure
15651 		 * 1) strictly increasing AND
15652 		 * 2) bounded by prog->len
15653 		 *
15654 		 * The linfo[0].insn_off == 0 check logically falls into
15655 		 * the later "missing bpf_line_info for func..." case
15656 		 * because the first linfo[0].insn_off must be the
15657 		 * first sub also and the first sub must have
15658 		 * subprog_info[0].start == 0.
15659 		 */
15660 		if ((i && linfo[i].insn_off <= prev_offset) ||
15661 		    linfo[i].insn_off >= prog->len) {
15662 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15663 				i, linfo[i].insn_off, prev_offset,
15664 				prog->len);
15665 			err = -EINVAL;
15666 			goto err_free;
15667 		}
15668 
15669 		if (!prog->insnsi[linfo[i].insn_off].code) {
15670 			verbose(env,
15671 				"Invalid insn code at line_info[%u].insn_off\n",
15672 				i);
15673 			err = -EINVAL;
15674 			goto err_free;
15675 		}
15676 
15677 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15678 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15679 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15680 			err = -EINVAL;
15681 			goto err_free;
15682 		}
15683 
15684 		if (s != env->subprog_cnt) {
15685 			if (linfo[i].insn_off == sub[s].start) {
15686 				sub[s].linfo_idx = i;
15687 				s++;
15688 			} else if (sub[s].start < linfo[i].insn_off) {
15689 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15690 				err = -EINVAL;
15691 				goto err_free;
15692 			}
15693 		}
15694 
15695 		prev_offset = linfo[i].insn_off;
15696 		bpfptr_add(&ulinfo, rec_size);
15697 	}
15698 
15699 	if (s != env->subprog_cnt) {
15700 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15701 			env->subprog_cnt - s, s);
15702 		err = -EINVAL;
15703 		goto err_free;
15704 	}
15705 
15706 	prog->aux->linfo = linfo;
15707 	prog->aux->nr_linfo = nr_linfo;
15708 
15709 	return 0;
15710 
15711 err_free:
15712 	kvfree(linfo);
15713 	return err;
15714 }
15715 
15716 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15717 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15718 
15719 static int check_core_relo(struct bpf_verifier_env *env,
15720 			   const union bpf_attr *attr,
15721 			   bpfptr_t uattr)
15722 {
15723 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15724 	struct bpf_core_relo core_relo = {};
15725 	struct bpf_prog *prog = env->prog;
15726 	const struct btf *btf = prog->aux->btf;
15727 	struct bpf_core_ctx ctx = {
15728 		.log = &env->log,
15729 		.btf = btf,
15730 	};
15731 	bpfptr_t u_core_relo;
15732 	int err;
15733 
15734 	nr_core_relo = attr->core_relo_cnt;
15735 	if (!nr_core_relo)
15736 		return 0;
15737 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15738 		return -EINVAL;
15739 
15740 	rec_size = attr->core_relo_rec_size;
15741 	if (rec_size < MIN_CORE_RELO_SIZE ||
15742 	    rec_size > MAX_CORE_RELO_SIZE ||
15743 	    rec_size % sizeof(u32))
15744 		return -EINVAL;
15745 
15746 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15747 	expected_size = sizeof(struct bpf_core_relo);
15748 	ncopy = min_t(u32, expected_size, rec_size);
15749 
15750 	/* Unlike func_info and line_info, copy and apply each CO-RE
15751 	 * relocation record one at a time.
15752 	 */
15753 	for (i = 0; i < nr_core_relo; i++) {
15754 		/* future proofing when sizeof(bpf_core_relo) changes */
15755 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15756 		if (err) {
15757 			if (err == -E2BIG) {
15758 				verbose(env, "nonzero tailing record in core_relo");
15759 				if (copy_to_bpfptr_offset(uattr,
15760 							  offsetof(union bpf_attr, core_relo_rec_size),
15761 							  &expected_size, sizeof(expected_size)))
15762 					err = -EFAULT;
15763 			}
15764 			break;
15765 		}
15766 
15767 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15768 			err = -EFAULT;
15769 			break;
15770 		}
15771 
15772 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15773 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15774 				i, core_relo.insn_off, prog->len);
15775 			err = -EINVAL;
15776 			break;
15777 		}
15778 
15779 		err = bpf_core_apply(&ctx, &core_relo, i,
15780 				     &prog->insnsi[core_relo.insn_off / 8]);
15781 		if (err)
15782 			break;
15783 		bpfptr_add(&u_core_relo, rec_size);
15784 	}
15785 	return err;
15786 }
15787 
15788 static int check_btf_info(struct bpf_verifier_env *env,
15789 			  const union bpf_attr *attr,
15790 			  bpfptr_t uattr)
15791 {
15792 	struct btf *btf;
15793 	int err;
15794 
15795 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15796 		if (check_abnormal_return(env))
15797 			return -EINVAL;
15798 		return 0;
15799 	}
15800 
15801 	btf = btf_get_by_fd(attr->prog_btf_fd);
15802 	if (IS_ERR(btf))
15803 		return PTR_ERR(btf);
15804 	if (btf_is_kernel(btf)) {
15805 		btf_put(btf);
15806 		return -EACCES;
15807 	}
15808 	env->prog->aux->btf = btf;
15809 
15810 	err = check_btf_func(env, attr, uattr);
15811 	if (err)
15812 		return err;
15813 
15814 	err = check_btf_line(env, attr, uattr);
15815 	if (err)
15816 		return err;
15817 
15818 	err = check_core_relo(env, attr, uattr);
15819 	if (err)
15820 		return err;
15821 
15822 	return 0;
15823 }
15824 
15825 /* check %cur's range satisfies %old's */
15826 static bool range_within(struct bpf_reg_state *old,
15827 			 struct bpf_reg_state *cur)
15828 {
15829 	return old->umin_value <= cur->umin_value &&
15830 	       old->umax_value >= cur->umax_value &&
15831 	       old->smin_value <= cur->smin_value &&
15832 	       old->smax_value >= cur->smax_value &&
15833 	       old->u32_min_value <= cur->u32_min_value &&
15834 	       old->u32_max_value >= cur->u32_max_value &&
15835 	       old->s32_min_value <= cur->s32_min_value &&
15836 	       old->s32_max_value >= cur->s32_max_value;
15837 }
15838 
15839 /* If in the old state two registers had the same id, then they need to have
15840  * the same id in the new state as well.  But that id could be different from
15841  * the old state, so we need to track the mapping from old to new ids.
15842  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15843  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15844  * regs with a different old id could still have new id 9, we don't care about
15845  * that.
15846  * So we look through our idmap to see if this old id has been seen before.  If
15847  * so, we require the new id to match; otherwise, we add the id pair to the map.
15848  */
15849 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15850 {
15851 	struct bpf_id_pair *map = idmap->map;
15852 	unsigned int i;
15853 
15854 	/* either both IDs should be set or both should be zero */
15855 	if (!!old_id != !!cur_id)
15856 		return false;
15857 
15858 	if (old_id == 0) /* cur_id == 0 as well */
15859 		return true;
15860 
15861 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15862 		if (!map[i].old) {
15863 			/* Reached an empty slot; haven't seen this id before */
15864 			map[i].old = old_id;
15865 			map[i].cur = cur_id;
15866 			return true;
15867 		}
15868 		if (map[i].old == old_id)
15869 			return map[i].cur == cur_id;
15870 		if (map[i].cur == cur_id)
15871 			return false;
15872 	}
15873 	/* We ran out of idmap slots, which should be impossible */
15874 	WARN_ON_ONCE(1);
15875 	return false;
15876 }
15877 
15878 /* Similar to check_ids(), but allocate a unique temporary ID
15879  * for 'old_id' or 'cur_id' of zero.
15880  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15881  */
15882 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15883 {
15884 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15885 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15886 
15887 	return check_ids(old_id, cur_id, idmap);
15888 }
15889 
15890 static void clean_func_state(struct bpf_verifier_env *env,
15891 			     struct bpf_func_state *st)
15892 {
15893 	enum bpf_reg_liveness live;
15894 	int i, j;
15895 
15896 	for (i = 0; i < BPF_REG_FP; i++) {
15897 		live = st->regs[i].live;
15898 		/* liveness must not touch this register anymore */
15899 		st->regs[i].live |= REG_LIVE_DONE;
15900 		if (!(live & REG_LIVE_READ))
15901 			/* since the register is unused, clear its state
15902 			 * to make further comparison simpler
15903 			 */
15904 			__mark_reg_not_init(env, &st->regs[i]);
15905 	}
15906 
15907 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15908 		live = st->stack[i].spilled_ptr.live;
15909 		/* liveness must not touch this stack slot anymore */
15910 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15911 		if (!(live & REG_LIVE_READ)) {
15912 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15913 			for (j = 0; j < BPF_REG_SIZE; j++)
15914 				st->stack[i].slot_type[j] = STACK_INVALID;
15915 		}
15916 	}
15917 }
15918 
15919 static void clean_verifier_state(struct bpf_verifier_env *env,
15920 				 struct bpf_verifier_state *st)
15921 {
15922 	int i;
15923 
15924 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15925 		/* all regs in this state in all frames were already marked */
15926 		return;
15927 
15928 	for (i = 0; i <= st->curframe; i++)
15929 		clean_func_state(env, st->frame[i]);
15930 }
15931 
15932 /* the parentage chains form a tree.
15933  * the verifier states are added to state lists at given insn and
15934  * pushed into state stack for future exploration.
15935  * when the verifier reaches bpf_exit insn some of the verifer states
15936  * stored in the state lists have their final liveness state already,
15937  * but a lot of states will get revised from liveness point of view when
15938  * the verifier explores other branches.
15939  * Example:
15940  * 1: r0 = 1
15941  * 2: if r1 == 100 goto pc+1
15942  * 3: r0 = 2
15943  * 4: exit
15944  * when the verifier reaches exit insn the register r0 in the state list of
15945  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15946  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15947  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15948  *
15949  * Since the verifier pushes the branch states as it sees them while exploring
15950  * the program the condition of walking the branch instruction for the second
15951  * time means that all states below this branch were already explored and
15952  * their final liveness marks are already propagated.
15953  * Hence when the verifier completes the search of state list in is_state_visited()
15954  * we can call this clean_live_states() function to mark all liveness states
15955  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15956  * will not be used.
15957  * This function also clears the registers and stack for states that !READ
15958  * to simplify state merging.
15959  *
15960  * Important note here that walking the same branch instruction in the callee
15961  * doesn't meant that the states are DONE. The verifier has to compare
15962  * the callsites
15963  */
15964 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15965 			      struct bpf_verifier_state *cur)
15966 {
15967 	struct bpf_verifier_state_list *sl;
15968 
15969 	sl = *explored_state(env, insn);
15970 	while (sl) {
15971 		if (sl->state.branches)
15972 			goto next;
15973 		if (sl->state.insn_idx != insn ||
15974 		    !same_callsites(&sl->state, cur))
15975 			goto next;
15976 		clean_verifier_state(env, &sl->state);
15977 next:
15978 		sl = sl->next;
15979 	}
15980 }
15981 
15982 static bool regs_exact(const struct bpf_reg_state *rold,
15983 		       const struct bpf_reg_state *rcur,
15984 		       struct bpf_idmap *idmap)
15985 {
15986 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15987 	       check_ids(rold->id, rcur->id, idmap) &&
15988 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15989 }
15990 
15991 /* Returns true if (rold safe implies rcur safe) */
15992 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15993 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15994 {
15995 	if (exact)
15996 		return regs_exact(rold, rcur, idmap);
15997 
15998 	if (!(rold->live & REG_LIVE_READ))
15999 		/* explored state didn't use this */
16000 		return true;
16001 	if (rold->type == NOT_INIT)
16002 		/* explored state can't have used this */
16003 		return true;
16004 	if (rcur->type == NOT_INIT)
16005 		return false;
16006 
16007 	/* Enforce that register types have to match exactly, including their
16008 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16009 	 * rule.
16010 	 *
16011 	 * One can make a point that using a pointer register as unbounded
16012 	 * SCALAR would be technically acceptable, but this could lead to
16013 	 * pointer leaks because scalars are allowed to leak while pointers
16014 	 * are not. We could make this safe in special cases if root is
16015 	 * calling us, but it's probably not worth the hassle.
16016 	 *
16017 	 * Also, register types that are *not* MAYBE_NULL could technically be
16018 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16019 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16020 	 * to the same map).
16021 	 * However, if the old MAYBE_NULL register then got NULL checked,
16022 	 * doing so could have affected others with the same id, and we can't
16023 	 * check for that because we lost the id when we converted to
16024 	 * a non-MAYBE_NULL variant.
16025 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16026 	 * non-MAYBE_NULL registers as well.
16027 	 */
16028 	if (rold->type != rcur->type)
16029 		return false;
16030 
16031 	switch (base_type(rold->type)) {
16032 	case SCALAR_VALUE:
16033 		if (env->explore_alu_limits) {
16034 			/* explore_alu_limits disables tnum_in() and range_within()
16035 			 * logic and requires everything to be strict
16036 			 */
16037 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16038 			       check_scalar_ids(rold->id, rcur->id, idmap);
16039 		}
16040 		if (!rold->precise)
16041 			return true;
16042 		/* Why check_ids() for scalar registers?
16043 		 *
16044 		 * Consider the following BPF code:
16045 		 *   1: r6 = ... unbound scalar, ID=a ...
16046 		 *   2: r7 = ... unbound scalar, ID=b ...
16047 		 *   3: if (r6 > r7) goto +1
16048 		 *   4: r6 = r7
16049 		 *   5: if (r6 > X) goto ...
16050 		 *   6: ... memory operation using r7 ...
16051 		 *
16052 		 * First verification path is [1-6]:
16053 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16054 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16055 		 *   r7 <= X, because r6 and r7 share same id.
16056 		 * Next verification path is [1-4, 6].
16057 		 *
16058 		 * Instruction (6) would be reached in two states:
16059 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16060 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16061 		 *
16062 		 * Use check_ids() to distinguish these states.
16063 		 * ---
16064 		 * Also verify that new value satisfies old value range knowledge.
16065 		 */
16066 		return range_within(rold, rcur) &&
16067 		       tnum_in(rold->var_off, rcur->var_off) &&
16068 		       check_scalar_ids(rold->id, rcur->id, idmap);
16069 	case PTR_TO_MAP_KEY:
16070 	case PTR_TO_MAP_VALUE:
16071 	case PTR_TO_MEM:
16072 	case PTR_TO_BUF:
16073 	case PTR_TO_TP_BUFFER:
16074 		/* If the new min/max/var_off satisfy the old ones and
16075 		 * everything else matches, we are OK.
16076 		 */
16077 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16078 		       range_within(rold, rcur) &&
16079 		       tnum_in(rold->var_off, rcur->var_off) &&
16080 		       check_ids(rold->id, rcur->id, idmap) &&
16081 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16082 	case PTR_TO_PACKET_META:
16083 	case PTR_TO_PACKET:
16084 		/* We must have at least as much range as the old ptr
16085 		 * did, so that any accesses which were safe before are
16086 		 * still safe.  This is true even if old range < old off,
16087 		 * since someone could have accessed through (ptr - k), or
16088 		 * even done ptr -= k in a register, to get a safe access.
16089 		 */
16090 		if (rold->range > rcur->range)
16091 			return false;
16092 		/* If the offsets don't match, we can't trust our alignment;
16093 		 * nor can we be sure that we won't fall out of range.
16094 		 */
16095 		if (rold->off != rcur->off)
16096 			return false;
16097 		/* id relations must be preserved */
16098 		if (!check_ids(rold->id, rcur->id, idmap))
16099 			return false;
16100 		/* new val must satisfy old val knowledge */
16101 		return range_within(rold, rcur) &&
16102 		       tnum_in(rold->var_off, rcur->var_off);
16103 	case PTR_TO_STACK:
16104 		/* two stack pointers are equal only if they're pointing to
16105 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16106 		 */
16107 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16108 	default:
16109 		return regs_exact(rold, rcur, idmap);
16110 	}
16111 }
16112 
16113 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16114 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16115 {
16116 	int i, spi;
16117 
16118 	/* walk slots of the explored stack and ignore any additional
16119 	 * slots in the current stack, since explored(safe) state
16120 	 * didn't use them
16121 	 */
16122 	for (i = 0; i < old->allocated_stack; i++) {
16123 		struct bpf_reg_state *old_reg, *cur_reg;
16124 
16125 		spi = i / BPF_REG_SIZE;
16126 
16127 		if (exact &&
16128 		    (i >= cur->allocated_stack ||
16129 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16130 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16131 			return false;
16132 
16133 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16134 			i += BPF_REG_SIZE - 1;
16135 			/* explored state didn't use this */
16136 			continue;
16137 		}
16138 
16139 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16140 			continue;
16141 
16142 		if (env->allow_uninit_stack &&
16143 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16144 			continue;
16145 
16146 		/* explored stack has more populated slots than current stack
16147 		 * and these slots were used
16148 		 */
16149 		if (i >= cur->allocated_stack)
16150 			return false;
16151 
16152 		/* if old state was safe with misc data in the stack
16153 		 * it will be safe with zero-initialized stack.
16154 		 * The opposite is not true
16155 		 */
16156 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16157 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16158 			continue;
16159 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16160 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16161 			/* Ex: old explored (safe) state has STACK_SPILL in
16162 			 * this stack slot, but current has STACK_MISC ->
16163 			 * this verifier states are not equivalent,
16164 			 * return false to continue verification of this path
16165 			 */
16166 			return false;
16167 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16168 			continue;
16169 		/* Both old and cur are having same slot_type */
16170 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16171 		case STACK_SPILL:
16172 			/* when explored and current stack slot are both storing
16173 			 * spilled registers, check that stored pointers types
16174 			 * are the same as well.
16175 			 * Ex: explored safe path could have stored
16176 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16177 			 * but current path has stored:
16178 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16179 			 * such verifier states are not equivalent.
16180 			 * return false to continue verification of this path
16181 			 */
16182 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16183 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16184 				return false;
16185 			break;
16186 		case STACK_DYNPTR:
16187 			old_reg = &old->stack[spi].spilled_ptr;
16188 			cur_reg = &cur->stack[spi].spilled_ptr;
16189 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16190 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16191 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16192 				return false;
16193 			break;
16194 		case STACK_ITER:
16195 			old_reg = &old->stack[spi].spilled_ptr;
16196 			cur_reg = &cur->stack[spi].spilled_ptr;
16197 			/* iter.depth is not compared between states as it
16198 			 * doesn't matter for correctness and would otherwise
16199 			 * prevent convergence; we maintain it only to prevent
16200 			 * infinite loop check triggering, see
16201 			 * iter_active_depths_differ()
16202 			 */
16203 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16204 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16205 			    old_reg->iter.state != cur_reg->iter.state ||
16206 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16207 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16208 				return false;
16209 			break;
16210 		case STACK_MISC:
16211 		case STACK_ZERO:
16212 		case STACK_INVALID:
16213 			continue;
16214 		/* Ensure that new unhandled slot types return false by default */
16215 		default:
16216 			return false;
16217 		}
16218 	}
16219 	return true;
16220 }
16221 
16222 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16223 		    struct bpf_idmap *idmap)
16224 {
16225 	int i;
16226 
16227 	if (old->acquired_refs != cur->acquired_refs)
16228 		return false;
16229 
16230 	for (i = 0; i < old->acquired_refs; i++) {
16231 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16232 			return false;
16233 	}
16234 
16235 	return true;
16236 }
16237 
16238 /* compare two verifier states
16239  *
16240  * all states stored in state_list are known to be valid, since
16241  * verifier reached 'bpf_exit' instruction through them
16242  *
16243  * this function is called when verifier exploring different branches of
16244  * execution popped from the state stack. If it sees an old state that has
16245  * more strict register state and more strict stack state then this execution
16246  * branch doesn't need to be explored further, since verifier already
16247  * concluded that more strict state leads to valid finish.
16248  *
16249  * Therefore two states are equivalent if register state is more conservative
16250  * and explored stack state is more conservative than the current one.
16251  * Example:
16252  *       explored                   current
16253  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16254  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16255  *
16256  * In other words if current stack state (one being explored) has more
16257  * valid slots than old one that already passed validation, it means
16258  * the verifier can stop exploring and conclude that current state is valid too
16259  *
16260  * Similarly with registers. If explored state has register type as invalid
16261  * whereas register type in current state is meaningful, it means that
16262  * the current state will reach 'bpf_exit' instruction safely
16263  */
16264 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16265 			      struct bpf_func_state *cur, bool exact)
16266 {
16267 	int i;
16268 
16269 	if (old->callback_depth > cur->callback_depth)
16270 		return false;
16271 
16272 	for (i = 0; i < MAX_BPF_REG; i++)
16273 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16274 			     &env->idmap_scratch, exact))
16275 			return false;
16276 
16277 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16278 		return false;
16279 
16280 	if (!refsafe(old, cur, &env->idmap_scratch))
16281 		return false;
16282 
16283 	return true;
16284 }
16285 
16286 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16287 {
16288 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16289 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16290 }
16291 
16292 static bool states_equal(struct bpf_verifier_env *env,
16293 			 struct bpf_verifier_state *old,
16294 			 struct bpf_verifier_state *cur,
16295 			 bool exact)
16296 {
16297 	int i;
16298 
16299 	if (old->curframe != cur->curframe)
16300 		return false;
16301 
16302 	reset_idmap_scratch(env);
16303 
16304 	/* Verification state from speculative execution simulation
16305 	 * must never prune a non-speculative execution one.
16306 	 */
16307 	if (old->speculative && !cur->speculative)
16308 		return false;
16309 
16310 	if (old->active_lock.ptr != cur->active_lock.ptr)
16311 		return false;
16312 
16313 	/* Old and cur active_lock's have to be either both present
16314 	 * or both absent.
16315 	 */
16316 	if (!!old->active_lock.id != !!cur->active_lock.id)
16317 		return false;
16318 
16319 	if (old->active_lock.id &&
16320 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16321 		return false;
16322 
16323 	if (old->active_rcu_lock != cur->active_rcu_lock)
16324 		return false;
16325 
16326 	/* for states to be equal callsites have to be the same
16327 	 * and all frame states need to be equivalent
16328 	 */
16329 	for (i = 0; i <= old->curframe; i++) {
16330 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16331 			return false;
16332 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16333 			return false;
16334 	}
16335 	return true;
16336 }
16337 
16338 /* Return 0 if no propagation happened. Return negative error code if error
16339  * happened. Otherwise, return the propagated bit.
16340  */
16341 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16342 				  struct bpf_reg_state *reg,
16343 				  struct bpf_reg_state *parent_reg)
16344 {
16345 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16346 	u8 flag = reg->live & REG_LIVE_READ;
16347 	int err;
16348 
16349 	/* When comes here, read flags of PARENT_REG or REG could be any of
16350 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16351 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16352 	 */
16353 	if (parent_flag == REG_LIVE_READ64 ||
16354 	    /* Or if there is no read flag from REG. */
16355 	    !flag ||
16356 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16357 	    parent_flag == flag)
16358 		return 0;
16359 
16360 	err = mark_reg_read(env, reg, parent_reg, flag);
16361 	if (err)
16362 		return err;
16363 
16364 	return flag;
16365 }
16366 
16367 /* A write screens off any subsequent reads; but write marks come from the
16368  * straight-line code between a state and its parent.  When we arrive at an
16369  * equivalent state (jump target or such) we didn't arrive by the straight-line
16370  * code, so read marks in the state must propagate to the parent regardless
16371  * of the state's write marks. That's what 'parent == state->parent' comparison
16372  * in mark_reg_read() is for.
16373  */
16374 static int propagate_liveness(struct bpf_verifier_env *env,
16375 			      const struct bpf_verifier_state *vstate,
16376 			      struct bpf_verifier_state *vparent)
16377 {
16378 	struct bpf_reg_state *state_reg, *parent_reg;
16379 	struct bpf_func_state *state, *parent;
16380 	int i, frame, err = 0;
16381 
16382 	if (vparent->curframe != vstate->curframe) {
16383 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16384 		     vparent->curframe, vstate->curframe);
16385 		return -EFAULT;
16386 	}
16387 	/* Propagate read liveness of registers... */
16388 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16389 	for (frame = 0; frame <= vstate->curframe; frame++) {
16390 		parent = vparent->frame[frame];
16391 		state = vstate->frame[frame];
16392 		parent_reg = parent->regs;
16393 		state_reg = state->regs;
16394 		/* We don't need to worry about FP liveness, it's read-only */
16395 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16396 			err = propagate_liveness_reg(env, &state_reg[i],
16397 						     &parent_reg[i]);
16398 			if (err < 0)
16399 				return err;
16400 			if (err == REG_LIVE_READ64)
16401 				mark_insn_zext(env, &parent_reg[i]);
16402 		}
16403 
16404 		/* Propagate stack slots. */
16405 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16406 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16407 			parent_reg = &parent->stack[i].spilled_ptr;
16408 			state_reg = &state->stack[i].spilled_ptr;
16409 			err = propagate_liveness_reg(env, state_reg,
16410 						     parent_reg);
16411 			if (err < 0)
16412 				return err;
16413 		}
16414 	}
16415 	return 0;
16416 }
16417 
16418 /* find precise scalars in the previous equivalent state and
16419  * propagate them into the current state
16420  */
16421 static int propagate_precision(struct bpf_verifier_env *env,
16422 			       const struct bpf_verifier_state *old)
16423 {
16424 	struct bpf_reg_state *state_reg;
16425 	struct bpf_func_state *state;
16426 	int i, err = 0, fr;
16427 	bool first;
16428 
16429 	for (fr = old->curframe; fr >= 0; fr--) {
16430 		state = old->frame[fr];
16431 		state_reg = state->regs;
16432 		first = true;
16433 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16434 			if (state_reg->type != SCALAR_VALUE ||
16435 			    !state_reg->precise ||
16436 			    !(state_reg->live & REG_LIVE_READ))
16437 				continue;
16438 			if (env->log.level & BPF_LOG_LEVEL2) {
16439 				if (first)
16440 					verbose(env, "frame %d: propagating r%d", fr, i);
16441 				else
16442 					verbose(env, ",r%d", i);
16443 			}
16444 			bt_set_frame_reg(&env->bt, fr, i);
16445 			first = false;
16446 		}
16447 
16448 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16449 			if (!is_spilled_reg(&state->stack[i]))
16450 				continue;
16451 			state_reg = &state->stack[i].spilled_ptr;
16452 			if (state_reg->type != SCALAR_VALUE ||
16453 			    !state_reg->precise ||
16454 			    !(state_reg->live & REG_LIVE_READ))
16455 				continue;
16456 			if (env->log.level & BPF_LOG_LEVEL2) {
16457 				if (first)
16458 					verbose(env, "frame %d: propagating fp%d",
16459 						fr, (-i - 1) * BPF_REG_SIZE);
16460 				else
16461 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16462 			}
16463 			bt_set_frame_slot(&env->bt, fr, i);
16464 			first = false;
16465 		}
16466 		if (!first)
16467 			verbose(env, "\n");
16468 	}
16469 
16470 	err = mark_chain_precision_batch(env);
16471 	if (err < 0)
16472 		return err;
16473 
16474 	return 0;
16475 }
16476 
16477 static bool states_maybe_looping(struct bpf_verifier_state *old,
16478 				 struct bpf_verifier_state *cur)
16479 {
16480 	struct bpf_func_state *fold, *fcur;
16481 	int i, fr = cur->curframe;
16482 
16483 	if (old->curframe != fr)
16484 		return false;
16485 
16486 	fold = old->frame[fr];
16487 	fcur = cur->frame[fr];
16488 	for (i = 0; i < MAX_BPF_REG; i++)
16489 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16490 			   offsetof(struct bpf_reg_state, parent)))
16491 			return false;
16492 	return true;
16493 }
16494 
16495 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16496 {
16497 	return env->insn_aux_data[insn_idx].is_iter_next;
16498 }
16499 
16500 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16501  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16502  * states to match, which otherwise would look like an infinite loop. So while
16503  * iter_next() calls are taken care of, we still need to be careful and
16504  * prevent erroneous and too eager declaration of "ininite loop", when
16505  * iterators are involved.
16506  *
16507  * Here's a situation in pseudo-BPF assembly form:
16508  *
16509  *   0: again:                          ; set up iter_next() call args
16510  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16511  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16512  *   3:   if r0 == 0 goto done
16513  *   4:   ... something useful here ...
16514  *   5:   goto again                    ; another iteration
16515  *   6: done:
16516  *   7:   r1 = &it
16517  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16518  *   9:   exit
16519  *
16520  * This is a typical loop. Let's assume that we have a prune point at 1:,
16521  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16522  * again`, assuming other heuristics don't get in a way).
16523  *
16524  * When we first time come to 1:, let's say we have some state X. We proceed
16525  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16526  * Now we come back to validate that forked ACTIVE state. We proceed through
16527  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16528  * are converging. But the problem is that we don't know that yet, as this
16529  * convergence has to happen at iter_next() call site only. So if nothing is
16530  * done, at 1: verifier will use bounded loop logic and declare infinite
16531  * looping (and would be *technically* correct, if not for iterator's
16532  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16533  * don't want that. So what we do in process_iter_next_call() when we go on
16534  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16535  * a different iteration. So when we suspect an infinite loop, we additionally
16536  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16537  * pretend we are not looping and wait for next iter_next() call.
16538  *
16539  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16540  * loop, because that would actually mean infinite loop, as DRAINED state is
16541  * "sticky", and so we'll keep returning into the same instruction with the
16542  * same state (at least in one of possible code paths).
16543  *
16544  * This approach allows to keep infinite loop heuristic even in the face of
16545  * active iterator. E.g., C snippet below is and will be detected as
16546  * inifintely looping:
16547  *
16548  *   struct bpf_iter_num it;
16549  *   int *p, x;
16550  *
16551  *   bpf_iter_num_new(&it, 0, 10);
16552  *   while ((p = bpf_iter_num_next(&t))) {
16553  *       x = p;
16554  *       while (x--) {} // <<-- infinite loop here
16555  *   }
16556  *
16557  */
16558 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16559 {
16560 	struct bpf_reg_state *slot, *cur_slot;
16561 	struct bpf_func_state *state;
16562 	int i, fr;
16563 
16564 	for (fr = old->curframe; fr >= 0; fr--) {
16565 		state = old->frame[fr];
16566 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16567 			if (state->stack[i].slot_type[0] != STACK_ITER)
16568 				continue;
16569 
16570 			slot = &state->stack[i].spilled_ptr;
16571 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16572 				continue;
16573 
16574 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16575 			if (cur_slot->iter.depth != slot->iter.depth)
16576 				return true;
16577 		}
16578 	}
16579 	return false;
16580 }
16581 
16582 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16583 {
16584 	struct bpf_verifier_state_list *new_sl;
16585 	struct bpf_verifier_state_list *sl, **pprev;
16586 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16587 	int i, j, n, err, states_cnt = 0;
16588 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16589 	bool add_new_state = force_new_state;
16590 	bool force_exact;
16591 
16592 	/* bpf progs typically have pruning point every 4 instructions
16593 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16594 	 * Do not add new state for future pruning if the verifier hasn't seen
16595 	 * at least 2 jumps and at least 8 instructions.
16596 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16597 	 * In tests that amounts to up to 50% reduction into total verifier
16598 	 * memory consumption and 20% verifier time speedup.
16599 	 */
16600 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16601 	    env->insn_processed - env->prev_insn_processed >= 8)
16602 		add_new_state = true;
16603 
16604 	pprev = explored_state(env, insn_idx);
16605 	sl = *pprev;
16606 
16607 	clean_live_states(env, insn_idx, cur);
16608 
16609 	while (sl) {
16610 		states_cnt++;
16611 		if (sl->state.insn_idx != insn_idx)
16612 			goto next;
16613 
16614 		if (sl->state.branches) {
16615 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16616 
16617 			if (frame->in_async_callback_fn &&
16618 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16619 				/* Different async_entry_cnt means that the verifier is
16620 				 * processing another entry into async callback.
16621 				 * Seeing the same state is not an indication of infinite
16622 				 * loop or infinite recursion.
16623 				 * But finding the same state doesn't mean that it's safe
16624 				 * to stop processing the current state. The previous state
16625 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16626 				 * Checking in_async_callback_fn alone is not enough either.
16627 				 * Since the verifier still needs to catch infinite loops
16628 				 * inside async callbacks.
16629 				 */
16630 				goto skip_inf_loop_check;
16631 			}
16632 			/* BPF open-coded iterators loop detection is special.
16633 			 * states_maybe_looping() logic is too simplistic in detecting
16634 			 * states that *might* be equivalent, because it doesn't know
16635 			 * about ID remapping, so don't even perform it.
16636 			 * See process_iter_next_call() and iter_active_depths_differ()
16637 			 * for overview of the logic. When current and one of parent
16638 			 * states are detected as equivalent, it's a good thing: we prove
16639 			 * convergence and can stop simulating further iterations.
16640 			 * It's safe to assume that iterator loop will finish, taking into
16641 			 * account iter_next() contract of eventually returning
16642 			 * sticky NULL result.
16643 			 *
16644 			 * Note, that states have to be compared exactly in this case because
16645 			 * read and precision marks might not be finalized inside the loop.
16646 			 * E.g. as in the program below:
16647 			 *
16648 			 *     1. r7 = -16
16649 			 *     2. r6 = bpf_get_prandom_u32()
16650 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16651 			 *     4.   if (r6 != 42) {
16652 			 *     5.     r7 = -32
16653 			 *     6.     r6 = bpf_get_prandom_u32()
16654 			 *     7.     continue
16655 			 *     8.   }
16656 			 *     9.   r0 = r10
16657 			 *    10.   r0 += r7
16658 			 *    11.   r8 = *(u64 *)(r0 + 0)
16659 			 *    12.   r6 = bpf_get_prandom_u32()
16660 			 *    13. }
16661 			 *
16662 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16663 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16664 			 * not have read or precision mark for r7 yet, thus inexact states
16665 			 * comparison would discard current state with r7=-32
16666 			 * => unsafe memory access at 11 would not be caught.
16667 			 */
16668 			if (is_iter_next_insn(env, insn_idx)) {
16669 				if (states_equal(env, &sl->state, cur, true)) {
16670 					struct bpf_func_state *cur_frame;
16671 					struct bpf_reg_state *iter_state, *iter_reg;
16672 					int spi;
16673 
16674 					cur_frame = cur->frame[cur->curframe];
16675 					/* btf_check_iter_kfuncs() enforces that
16676 					 * iter state pointer is always the first arg
16677 					 */
16678 					iter_reg = &cur_frame->regs[BPF_REG_1];
16679 					/* current state is valid due to states_equal(),
16680 					 * so we can assume valid iter and reg state,
16681 					 * no need for extra (re-)validations
16682 					 */
16683 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16684 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16685 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16686 						update_loop_entry(cur, &sl->state);
16687 						goto hit;
16688 					}
16689 				}
16690 				goto skip_inf_loop_check;
16691 			}
16692 			if (calls_callback(env, insn_idx)) {
16693 				if (states_equal(env, &sl->state, cur, true))
16694 					goto hit;
16695 				goto skip_inf_loop_check;
16696 			}
16697 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16698 			if (states_maybe_looping(&sl->state, cur) &&
16699 			    states_equal(env, &sl->state, cur, false) &&
16700 			    !iter_active_depths_differ(&sl->state, cur) &&
16701 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16702 				verbose_linfo(env, insn_idx, "; ");
16703 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16704 				verbose(env, "cur state:");
16705 				print_verifier_state(env, cur->frame[cur->curframe], true);
16706 				verbose(env, "old state:");
16707 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16708 				return -EINVAL;
16709 			}
16710 			/* if the verifier is processing a loop, avoid adding new state
16711 			 * too often, since different loop iterations have distinct
16712 			 * states and may not help future pruning.
16713 			 * This threshold shouldn't be too low to make sure that
16714 			 * a loop with large bound will be rejected quickly.
16715 			 * The most abusive loop will be:
16716 			 * r1 += 1
16717 			 * if r1 < 1000000 goto pc-2
16718 			 * 1M insn_procssed limit / 100 == 10k peak states.
16719 			 * This threshold shouldn't be too high either, since states
16720 			 * at the end of the loop are likely to be useful in pruning.
16721 			 */
16722 skip_inf_loop_check:
16723 			if (!force_new_state &&
16724 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16725 			    env->insn_processed - env->prev_insn_processed < 100)
16726 				add_new_state = false;
16727 			goto miss;
16728 		}
16729 		/* If sl->state is a part of a loop and this loop's entry is a part of
16730 		 * current verification path then states have to be compared exactly.
16731 		 * 'force_exact' is needed to catch the following case:
16732 		 *
16733 		 *                initial     Here state 'succ' was processed first,
16734 		 *                  |         it was eventually tracked to produce a
16735 		 *                  V         state identical to 'hdr'.
16736 		 *     .---------> hdr        All branches from 'succ' had been explored
16737 		 *     |            |         and thus 'succ' has its .branches == 0.
16738 		 *     |            V
16739 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16740 		 *     |    |       |         to the same instruction + callsites.
16741 		 *     |    V       V         In such case it is necessary to check
16742 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16743 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16744 		 *     |    V       V         same loop exact flag has to be set.
16745 		 *     |   succ <- cur        To check if that is the case, verify
16746 		 *     |    |                 if loop entry of 'succ' is in current
16747 		 *     |    V                 DFS path.
16748 		 *     |   ...
16749 		 *     |    |
16750 		 *     '----'
16751 		 *
16752 		 * Additional details are in the comment before get_loop_entry().
16753 		 */
16754 		loop_entry = get_loop_entry(&sl->state);
16755 		force_exact = loop_entry && loop_entry->branches > 0;
16756 		if (states_equal(env, &sl->state, cur, force_exact)) {
16757 			if (force_exact)
16758 				update_loop_entry(cur, loop_entry);
16759 hit:
16760 			sl->hit_cnt++;
16761 			/* reached equivalent register/stack state,
16762 			 * prune the search.
16763 			 * Registers read by the continuation are read by us.
16764 			 * If we have any write marks in env->cur_state, they
16765 			 * will prevent corresponding reads in the continuation
16766 			 * from reaching our parent (an explored_state).  Our
16767 			 * own state will get the read marks recorded, but
16768 			 * they'll be immediately forgotten as we're pruning
16769 			 * this state and will pop a new one.
16770 			 */
16771 			err = propagate_liveness(env, &sl->state, cur);
16772 
16773 			/* if previous state reached the exit with precision and
16774 			 * current state is equivalent to it (except precsion marks)
16775 			 * the precision needs to be propagated back in
16776 			 * the current state.
16777 			 */
16778 			err = err ? : push_jmp_history(env, cur);
16779 			err = err ? : propagate_precision(env, &sl->state);
16780 			if (err)
16781 				return err;
16782 			return 1;
16783 		}
16784 miss:
16785 		/* when new state is not going to be added do not increase miss count.
16786 		 * Otherwise several loop iterations will remove the state
16787 		 * recorded earlier. The goal of these heuristics is to have
16788 		 * states from some iterations of the loop (some in the beginning
16789 		 * and some at the end) to help pruning.
16790 		 */
16791 		if (add_new_state)
16792 			sl->miss_cnt++;
16793 		/* heuristic to determine whether this state is beneficial
16794 		 * to keep checking from state equivalence point of view.
16795 		 * Higher numbers increase max_states_per_insn and verification time,
16796 		 * but do not meaningfully decrease insn_processed.
16797 		 * 'n' controls how many times state could miss before eviction.
16798 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16799 		 * too early would hinder iterator convergence.
16800 		 */
16801 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16802 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16803 			/* the state is unlikely to be useful. Remove it to
16804 			 * speed up verification
16805 			 */
16806 			*pprev = sl->next;
16807 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16808 			    !sl->state.used_as_loop_entry) {
16809 				u32 br = sl->state.branches;
16810 
16811 				WARN_ONCE(br,
16812 					  "BUG live_done but branches_to_explore %d\n",
16813 					  br);
16814 				free_verifier_state(&sl->state, false);
16815 				kfree(sl);
16816 				env->peak_states--;
16817 			} else {
16818 				/* cannot free this state, since parentage chain may
16819 				 * walk it later. Add it for free_list instead to
16820 				 * be freed at the end of verification
16821 				 */
16822 				sl->next = env->free_list;
16823 				env->free_list = sl;
16824 			}
16825 			sl = *pprev;
16826 			continue;
16827 		}
16828 next:
16829 		pprev = &sl->next;
16830 		sl = *pprev;
16831 	}
16832 
16833 	if (env->max_states_per_insn < states_cnt)
16834 		env->max_states_per_insn = states_cnt;
16835 
16836 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16837 		return 0;
16838 
16839 	if (!add_new_state)
16840 		return 0;
16841 
16842 	/* There were no equivalent states, remember the current one.
16843 	 * Technically the current state is not proven to be safe yet,
16844 	 * but it will either reach outer most bpf_exit (which means it's safe)
16845 	 * or it will be rejected. When there are no loops the verifier won't be
16846 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16847 	 * again on the way to bpf_exit.
16848 	 * When looping the sl->state.branches will be > 0 and this state
16849 	 * will not be considered for equivalence until branches == 0.
16850 	 */
16851 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16852 	if (!new_sl)
16853 		return -ENOMEM;
16854 	env->total_states++;
16855 	env->peak_states++;
16856 	env->prev_jmps_processed = env->jmps_processed;
16857 	env->prev_insn_processed = env->insn_processed;
16858 
16859 	/* forget precise markings we inherited, see __mark_chain_precision */
16860 	if (env->bpf_capable)
16861 		mark_all_scalars_imprecise(env, cur);
16862 
16863 	/* add new state to the head of linked list */
16864 	new = &new_sl->state;
16865 	err = copy_verifier_state(new, cur);
16866 	if (err) {
16867 		free_verifier_state(new, false);
16868 		kfree(new_sl);
16869 		return err;
16870 	}
16871 	new->insn_idx = insn_idx;
16872 	WARN_ONCE(new->branches != 1,
16873 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16874 
16875 	cur->parent = new;
16876 	cur->first_insn_idx = insn_idx;
16877 	cur->dfs_depth = new->dfs_depth + 1;
16878 	clear_jmp_history(cur);
16879 	new_sl->next = *explored_state(env, insn_idx);
16880 	*explored_state(env, insn_idx) = new_sl;
16881 	/* connect new state to parentage chain. Current frame needs all
16882 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16883 	 * to the stack implicitly by JITs) so in callers' frames connect just
16884 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16885 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16886 	 * from callee with its full parentage chain, anyway.
16887 	 */
16888 	/* clear write marks in current state: the writes we did are not writes
16889 	 * our child did, so they don't screen off its reads from us.
16890 	 * (There are no read marks in current state, because reads always mark
16891 	 * their parent and current state never has children yet.  Only
16892 	 * explored_states can get read marks.)
16893 	 */
16894 	for (j = 0; j <= cur->curframe; j++) {
16895 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16896 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16897 		for (i = 0; i < BPF_REG_FP; i++)
16898 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16899 	}
16900 
16901 	/* all stack frames are accessible from callee, clear them all */
16902 	for (j = 0; j <= cur->curframe; j++) {
16903 		struct bpf_func_state *frame = cur->frame[j];
16904 		struct bpf_func_state *newframe = new->frame[j];
16905 
16906 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16907 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16908 			frame->stack[i].spilled_ptr.parent =
16909 						&newframe->stack[i].spilled_ptr;
16910 		}
16911 	}
16912 	return 0;
16913 }
16914 
16915 /* Return true if it's OK to have the same insn return a different type. */
16916 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16917 {
16918 	switch (base_type(type)) {
16919 	case PTR_TO_CTX:
16920 	case PTR_TO_SOCKET:
16921 	case PTR_TO_SOCK_COMMON:
16922 	case PTR_TO_TCP_SOCK:
16923 	case PTR_TO_XDP_SOCK:
16924 	case PTR_TO_BTF_ID:
16925 		return false;
16926 	default:
16927 		return true;
16928 	}
16929 }
16930 
16931 /* If an instruction was previously used with particular pointer types, then we
16932  * need to be careful to avoid cases such as the below, where it may be ok
16933  * for one branch accessing the pointer, but not ok for the other branch:
16934  *
16935  * R1 = sock_ptr
16936  * goto X;
16937  * ...
16938  * R1 = some_other_valid_ptr;
16939  * goto X;
16940  * ...
16941  * R2 = *(u32 *)(R1 + 0);
16942  */
16943 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16944 {
16945 	return src != prev && (!reg_type_mismatch_ok(src) ||
16946 			       !reg_type_mismatch_ok(prev));
16947 }
16948 
16949 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16950 			     bool allow_trust_missmatch)
16951 {
16952 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16953 
16954 	if (*prev_type == NOT_INIT) {
16955 		/* Saw a valid insn
16956 		 * dst_reg = *(u32 *)(src_reg + off)
16957 		 * save type to validate intersecting paths
16958 		 */
16959 		*prev_type = type;
16960 	} else if (reg_type_mismatch(type, *prev_type)) {
16961 		/* Abuser program is trying to use the same insn
16962 		 * dst_reg = *(u32*) (src_reg + off)
16963 		 * with different pointer types:
16964 		 * src_reg == ctx in one branch and
16965 		 * src_reg == stack|map in some other branch.
16966 		 * Reject it.
16967 		 */
16968 		if (allow_trust_missmatch &&
16969 		    base_type(type) == PTR_TO_BTF_ID &&
16970 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16971 			/*
16972 			 * Have to support a use case when one path through
16973 			 * the program yields TRUSTED pointer while another
16974 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16975 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16976 			 */
16977 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16978 		} else {
16979 			verbose(env, "same insn cannot be used with different pointers\n");
16980 			return -EINVAL;
16981 		}
16982 	}
16983 
16984 	return 0;
16985 }
16986 
16987 static int do_check(struct bpf_verifier_env *env)
16988 {
16989 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16990 	struct bpf_verifier_state *state = env->cur_state;
16991 	struct bpf_insn *insns = env->prog->insnsi;
16992 	struct bpf_reg_state *regs;
16993 	int insn_cnt = env->prog->len;
16994 	bool do_print_state = false;
16995 	int prev_insn_idx = -1;
16996 
16997 	for (;;) {
16998 		struct bpf_insn *insn;
16999 		u8 class;
17000 		int err;
17001 
17002 		env->prev_insn_idx = prev_insn_idx;
17003 		if (env->insn_idx >= insn_cnt) {
17004 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17005 				env->insn_idx, insn_cnt);
17006 			return -EFAULT;
17007 		}
17008 
17009 		insn = &insns[env->insn_idx];
17010 		class = BPF_CLASS(insn->code);
17011 
17012 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17013 			verbose(env,
17014 				"BPF program is too large. Processed %d insn\n",
17015 				env->insn_processed);
17016 			return -E2BIG;
17017 		}
17018 
17019 		state->last_insn_idx = env->prev_insn_idx;
17020 
17021 		if (is_prune_point(env, env->insn_idx)) {
17022 			err = is_state_visited(env, env->insn_idx);
17023 			if (err < 0)
17024 				return err;
17025 			if (err == 1) {
17026 				/* found equivalent state, can prune the search */
17027 				if (env->log.level & BPF_LOG_LEVEL) {
17028 					if (do_print_state)
17029 						verbose(env, "\nfrom %d to %d%s: safe\n",
17030 							env->prev_insn_idx, env->insn_idx,
17031 							env->cur_state->speculative ?
17032 							" (speculative execution)" : "");
17033 					else
17034 						verbose(env, "%d: safe\n", env->insn_idx);
17035 				}
17036 				goto process_bpf_exit;
17037 			}
17038 		}
17039 
17040 		if (is_jmp_point(env, env->insn_idx)) {
17041 			err = push_jmp_history(env, state);
17042 			if (err)
17043 				return err;
17044 		}
17045 
17046 		if (signal_pending(current))
17047 			return -EAGAIN;
17048 
17049 		if (need_resched())
17050 			cond_resched();
17051 
17052 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17053 			verbose(env, "\nfrom %d to %d%s:",
17054 				env->prev_insn_idx, env->insn_idx,
17055 				env->cur_state->speculative ?
17056 				" (speculative execution)" : "");
17057 			print_verifier_state(env, state->frame[state->curframe], true);
17058 			do_print_state = false;
17059 		}
17060 
17061 		if (env->log.level & BPF_LOG_LEVEL) {
17062 			const struct bpf_insn_cbs cbs = {
17063 				.cb_call	= disasm_kfunc_name,
17064 				.cb_print	= verbose,
17065 				.private_data	= env,
17066 			};
17067 
17068 			if (verifier_state_scratched(env))
17069 				print_insn_state(env, state->frame[state->curframe]);
17070 
17071 			verbose_linfo(env, env->insn_idx, "; ");
17072 			env->prev_log_pos = env->log.end_pos;
17073 			verbose(env, "%d: ", env->insn_idx);
17074 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17075 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17076 			env->prev_log_pos = env->log.end_pos;
17077 		}
17078 
17079 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17080 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17081 							   env->prev_insn_idx);
17082 			if (err)
17083 				return err;
17084 		}
17085 
17086 		regs = cur_regs(env);
17087 		sanitize_mark_insn_seen(env);
17088 		prev_insn_idx = env->insn_idx;
17089 
17090 		if (class == BPF_ALU || class == BPF_ALU64) {
17091 			err = check_alu_op(env, insn);
17092 			if (err)
17093 				return err;
17094 
17095 		} else if (class == BPF_LDX) {
17096 			enum bpf_reg_type src_reg_type;
17097 
17098 			/* check for reserved fields is already done */
17099 
17100 			/* check src operand */
17101 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17102 			if (err)
17103 				return err;
17104 
17105 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17106 			if (err)
17107 				return err;
17108 
17109 			src_reg_type = regs[insn->src_reg].type;
17110 
17111 			/* check that memory (src_reg + off) is readable,
17112 			 * the state of dst_reg will be updated by this func
17113 			 */
17114 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17115 					       insn->off, BPF_SIZE(insn->code),
17116 					       BPF_READ, insn->dst_reg, false,
17117 					       BPF_MODE(insn->code) == BPF_MEMSX);
17118 			if (err)
17119 				return err;
17120 
17121 			err = save_aux_ptr_type(env, src_reg_type, true);
17122 			if (err)
17123 				return err;
17124 		} else if (class == BPF_STX) {
17125 			enum bpf_reg_type dst_reg_type;
17126 
17127 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17128 				err = check_atomic(env, env->insn_idx, insn);
17129 				if (err)
17130 					return err;
17131 				env->insn_idx++;
17132 				continue;
17133 			}
17134 
17135 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17136 				verbose(env, "BPF_STX uses reserved fields\n");
17137 				return -EINVAL;
17138 			}
17139 
17140 			/* check src1 operand */
17141 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17142 			if (err)
17143 				return err;
17144 			/* check src2 operand */
17145 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17146 			if (err)
17147 				return err;
17148 
17149 			dst_reg_type = regs[insn->dst_reg].type;
17150 
17151 			/* check that memory (dst_reg + off) is writeable */
17152 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17153 					       insn->off, BPF_SIZE(insn->code),
17154 					       BPF_WRITE, insn->src_reg, false, false);
17155 			if (err)
17156 				return err;
17157 
17158 			err = save_aux_ptr_type(env, dst_reg_type, false);
17159 			if (err)
17160 				return err;
17161 		} else if (class == BPF_ST) {
17162 			enum bpf_reg_type dst_reg_type;
17163 
17164 			if (BPF_MODE(insn->code) != BPF_MEM ||
17165 			    insn->src_reg != BPF_REG_0) {
17166 				verbose(env, "BPF_ST uses reserved fields\n");
17167 				return -EINVAL;
17168 			}
17169 			/* check src operand */
17170 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17171 			if (err)
17172 				return err;
17173 
17174 			dst_reg_type = regs[insn->dst_reg].type;
17175 
17176 			/* check that memory (dst_reg + off) is writeable */
17177 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17178 					       insn->off, BPF_SIZE(insn->code),
17179 					       BPF_WRITE, -1, false, false);
17180 			if (err)
17181 				return err;
17182 
17183 			err = save_aux_ptr_type(env, dst_reg_type, false);
17184 			if (err)
17185 				return err;
17186 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17187 			u8 opcode = BPF_OP(insn->code);
17188 
17189 			env->jmps_processed++;
17190 			if (opcode == BPF_CALL) {
17191 				if (BPF_SRC(insn->code) != BPF_K ||
17192 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17193 				     && insn->off != 0) ||
17194 				    (insn->src_reg != BPF_REG_0 &&
17195 				     insn->src_reg != BPF_PSEUDO_CALL &&
17196 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17197 				    insn->dst_reg != BPF_REG_0 ||
17198 				    class == BPF_JMP32) {
17199 					verbose(env, "BPF_CALL uses reserved fields\n");
17200 					return -EINVAL;
17201 				}
17202 
17203 				if (env->cur_state->active_lock.ptr) {
17204 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17205 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17206 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17207 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17208 						verbose(env, "function calls are not allowed while holding a lock\n");
17209 						return -EINVAL;
17210 					}
17211 				}
17212 				if (insn->src_reg == BPF_PSEUDO_CALL)
17213 					err = check_func_call(env, insn, &env->insn_idx);
17214 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17215 					err = check_kfunc_call(env, insn, &env->insn_idx);
17216 				else
17217 					err = check_helper_call(env, insn, &env->insn_idx);
17218 				if (err)
17219 					return err;
17220 
17221 				mark_reg_scratched(env, BPF_REG_0);
17222 			} else if (opcode == BPF_JA) {
17223 				if (BPF_SRC(insn->code) != BPF_K ||
17224 				    insn->src_reg != BPF_REG_0 ||
17225 				    insn->dst_reg != BPF_REG_0 ||
17226 				    (class == BPF_JMP && insn->imm != 0) ||
17227 				    (class == BPF_JMP32 && insn->off != 0)) {
17228 					verbose(env, "BPF_JA uses reserved fields\n");
17229 					return -EINVAL;
17230 				}
17231 
17232 				if (class == BPF_JMP)
17233 					env->insn_idx += insn->off + 1;
17234 				else
17235 					env->insn_idx += insn->imm + 1;
17236 				continue;
17237 
17238 			} else if (opcode == BPF_EXIT) {
17239 				if (BPF_SRC(insn->code) != BPF_K ||
17240 				    insn->imm != 0 ||
17241 				    insn->src_reg != BPF_REG_0 ||
17242 				    insn->dst_reg != BPF_REG_0 ||
17243 				    class == BPF_JMP32) {
17244 					verbose(env, "BPF_EXIT uses reserved fields\n");
17245 					return -EINVAL;
17246 				}
17247 
17248 				if (env->cur_state->active_lock.ptr &&
17249 				    !in_rbtree_lock_required_cb(env)) {
17250 					verbose(env, "bpf_spin_unlock is missing\n");
17251 					return -EINVAL;
17252 				}
17253 
17254 				if (env->cur_state->active_rcu_lock &&
17255 				    !in_rbtree_lock_required_cb(env)) {
17256 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17257 					return -EINVAL;
17258 				}
17259 
17260 				/* We must do check_reference_leak here before
17261 				 * prepare_func_exit to handle the case when
17262 				 * state->curframe > 0, it may be a callback
17263 				 * function, for which reference_state must
17264 				 * match caller reference state when it exits.
17265 				 */
17266 				err = check_reference_leak(env);
17267 				if (err)
17268 					return err;
17269 
17270 				if (state->curframe) {
17271 					/* exit from nested function */
17272 					err = prepare_func_exit(env, &env->insn_idx);
17273 					if (err)
17274 						return err;
17275 					do_print_state = true;
17276 					continue;
17277 				}
17278 
17279 				err = check_return_code(env);
17280 				if (err)
17281 					return err;
17282 process_bpf_exit:
17283 				mark_verifier_state_scratched(env);
17284 				update_branch_counts(env, env->cur_state);
17285 				err = pop_stack(env, &prev_insn_idx,
17286 						&env->insn_idx, pop_log);
17287 				if (err < 0) {
17288 					if (err != -ENOENT)
17289 						return err;
17290 					break;
17291 				} else {
17292 					do_print_state = true;
17293 					continue;
17294 				}
17295 			} else {
17296 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17297 				if (err)
17298 					return err;
17299 			}
17300 		} else if (class == BPF_LD) {
17301 			u8 mode = BPF_MODE(insn->code);
17302 
17303 			if (mode == BPF_ABS || mode == BPF_IND) {
17304 				err = check_ld_abs(env, insn);
17305 				if (err)
17306 					return err;
17307 
17308 			} else if (mode == BPF_IMM) {
17309 				err = check_ld_imm(env, insn);
17310 				if (err)
17311 					return err;
17312 
17313 				env->insn_idx++;
17314 				sanitize_mark_insn_seen(env);
17315 			} else {
17316 				verbose(env, "invalid BPF_LD mode\n");
17317 				return -EINVAL;
17318 			}
17319 		} else {
17320 			verbose(env, "unknown insn class %d\n", class);
17321 			return -EINVAL;
17322 		}
17323 
17324 		env->insn_idx++;
17325 	}
17326 
17327 	return 0;
17328 }
17329 
17330 static int find_btf_percpu_datasec(struct btf *btf)
17331 {
17332 	const struct btf_type *t;
17333 	const char *tname;
17334 	int i, n;
17335 
17336 	/*
17337 	 * Both vmlinux and module each have their own ".data..percpu"
17338 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17339 	 * types to look at only module's own BTF types.
17340 	 */
17341 	n = btf_nr_types(btf);
17342 	if (btf_is_module(btf))
17343 		i = btf_nr_types(btf_vmlinux);
17344 	else
17345 		i = 1;
17346 
17347 	for(; i < n; i++) {
17348 		t = btf_type_by_id(btf, i);
17349 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17350 			continue;
17351 
17352 		tname = btf_name_by_offset(btf, t->name_off);
17353 		if (!strcmp(tname, ".data..percpu"))
17354 			return i;
17355 	}
17356 
17357 	return -ENOENT;
17358 }
17359 
17360 /* replace pseudo btf_id with kernel symbol address */
17361 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17362 			       struct bpf_insn *insn,
17363 			       struct bpf_insn_aux_data *aux)
17364 {
17365 	const struct btf_var_secinfo *vsi;
17366 	const struct btf_type *datasec;
17367 	struct btf_mod_pair *btf_mod;
17368 	const struct btf_type *t;
17369 	const char *sym_name;
17370 	bool percpu = false;
17371 	u32 type, id = insn->imm;
17372 	struct btf *btf;
17373 	s32 datasec_id;
17374 	u64 addr;
17375 	int i, btf_fd, err;
17376 
17377 	btf_fd = insn[1].imm;
17378 	if (btf_fd) {
17379 		btf = btf_get_by_fd(btf_fd);
17380 		if (IS_ERR(btf)) {
17381 			verbose(env, "invalid module BTF object FD specified.\n");
17382 			return -EINVAL;
17383 		}
17384 	} else {
17385 		if (!btf_vmlinux) {
17386 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17387 			return -EINVAL;
17388 		}
17389 		btf = btf_vmlinux;
17390 		btf_get(btf);
17391 	}
17392 
17393 	t = btf_type_by_id(btf, id);
17394 	if (!t) {
17395 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17396 		err = -ENOENT;
17397 		goto err_put;
17398 	}
17399 
17400 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17401 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17402 		err = -EINVAL;
17403 		goto err_put;
17404 	}
17405 
17406 	sym_name = btf_name_by_offset(btf, t->name_off);
17407 	addr = kallsyms_lookup_name(sym_name);
17408 	if (!addr) {
17409 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17410 			sym_name);
17411 		err = -ENOENT;
17412 		goto err_put;
17413 	}
17414 	insn[0].imm = (u32)addr;
17415 	insn[1].imm = addr >> 32;
17416 
17417 	if (btf_type_is_func(t)) {
17418 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17419 		aux->btf_var.mem_size = 0;
17420 		goto check_btf;
17421 	}
17422 
17423 	datasec_id = find_btf_percpu_datasec(btf);
17424 	if (datasec_id > 0) {
17425 		datasec = btf_type_by_id(btf, datasec_id);
17426 		for_each_vsi(i, datasec, vsi) {
17427 			if (vsi->type == id) {
17428 				percpu = true;
17429 				break;
17430 			}
17431 		}
17432 	}
17433 
17434 	type = t->type;
17435 	t = btf_type_skip_modifiers(btf, type, NULL);
17436 	if (percpu) {
17437 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17438 		aux->btf_var.btf = btf;
17439 		aux->btf_var.btf_id = type;
17440 	} else if (!btf_type_is_struct(t)) {
17441 		const struct btf_type *ret;
17442 		const char *tname;
17443 		u32 tsize;
17444 
17445 		/* resolve the type size of ksym. */
17446 		ret = btf_resolve_size(btf, t, &tsize);
17447 		if (IS_ERR(ret)) {
17448 			tname = btf_name_by_offset(btf, t->name_off);
17449 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17450 				tname, PTR_ERR(ret));
17451 			err = -EINVAL;
17452 			goto err_put;
17453 		}
17454 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17455 		aux->btf_var.mem_size = tsize;
17456 	} else {
17457 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17458 		aux->btf_var.btf = btf;
17459 		aux->btf_var.btf_id = type;
17460 	}
17461 check_btf:
17462 	/* check whether we recorded this BTF (and maybe module) already */
17463 	for (i = 0; i < env->used_btf_cnt; i++) {
17464 		if (env->used_btfs[i].btf == btf) {
17465 			btf_put(btf);
17466 			return 0;
17467 		}
17468 	}
17469 
17470 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17471 		err = -E2BIG;
17472 		goto err_put;
17473 	}
17474 
17475 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17476 	btf_mod->btf = btf;
17477 	btf_mod->module = NULL;
17478 
17479 	/* if we reference variables from kernel module, bump its refcount */
17480 	if (btf_is_module(btf)) {
17481 		btf_mod->module = btf_try_get_module(btf);
17482 		if (!btf_mod->module) {
17483 			err = -ENXIO;
17484 			goto err_put;
17485 		}
17486 	}
17487 
17488 	env->used_btf_cnt++;
17489 
17490 	return 0;
17491 err_put:
17492 	btf_put(btf);
17493 	return err;
17494 }
17495 
17496 static bool is_tracing_prog_type(enum bpf_prog_type type)
17497 {
17498 	switch (type) {
17499 	case BPF_PROG_TYPE_KPROBE:
17500 	case BPF_PROG_TYPE_TRACEPOINT:
17501 	case BPF_PROG_TYPE_PERF_EVENT:
17502 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17503 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17504 		return true;
17505 	default:
17506 		return false;
17507 	}
17508 }
17509 
17510 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17511 					struct bpf_map *map,
17512 					struct bpf_prog *prog)
17513 
17514 {
17515 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17516 
17517 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17518 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17519 		if (is_tracing_prog_type(prog_type)) {
17520 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17521 			return -EINVAL;
17522 		}
17523 	}
17524 
17525 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17526 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17527 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17528 			return -EINVAL;
17529 		}
17530 
17531 		if (is_tracing_prog_type(prog_type)) {
17532 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17533 			return -EINVAL;
17534 		}
17535 	}
17536 
17537 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17538 		if (is_tracing_prog_type(prog_type)) {
17539 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17540 			return -EINVAL;
17541 		}
17542 	}
17543 
17544 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17545 	    !bpf_offload_prog_map_match(prog, map)) {
17546 		verbose(env, "offload device mismatch between prog and map\n");
17547 		return -EINVAL;
17548 	}
17549 
17550 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17551 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17552 		return -EINVAL;
17553 	}
17554 
17555 	if (prog->aux->sleepable)
17556 		switch (map->map_type) {
17557 		case BPF_MAP_TYPE_HASH:
17558 		case BPF_MAP_TYPE_LRU_HASH:
17559 		case BPF_MAP_TYPE_ARRAY:
17560 		case BPF_MAP_TYPE_PERCPU_HASH:
17561 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17562 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17563 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17564 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17565 		case BPF_MAP_TYPE_RINGBUF:
17566 		case BPF_MAP_TYPE_USER_RINGBUF:
17567 		case BPF_MAP_TYPE_INODE_STORAGE:
17568 		case BPF_MAP_TYPE_SK_STORAGE:
17569 		case BPF_MAP_TYPE_TASK_STORAGE:
17570 		case BPF_MAP_TYPE_CGRP_STORAGE:
17571 			break;
17572 		default:
17573 			verbose(env,
17574 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17575 			return -EINVAL;
17576 		}
17577 
17578 	return 0;
17579 }
17580 
17581 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17582 {
17583 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17584 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17585 }
17586 
17587 /* find and rewrite pseudo imm in ld_imm64 instructions:
17588  *
17589  * 1. if it accesses map FD, replace it with actual map pointer.
17590  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17591  *
17592  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17593  */
17594 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17595 {
17596 	struct bpf_insn *insn = env->prog->insnsi;
17597 	int insn_cnt = env->prog->len;
17598 	int i, j, err;
17599 
17600 	err = bpf_prog_calc_tag(env->prog);
17601 	if (err)
17602 		return err;
17603 
17604 	for (i = 0; i < insn_cnt; i++, insn++) {
17605 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17606 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17607 		    insn->imm != 0)) {
17608 			verbose(env, "BPF_LDX uses reserved fields\n");
17609 			return -EINVAL;
17610 		}
17611 
17612 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17613 			struct bpf_insn_aux_data *aux;
17614 			struct bpf_map *map;
17615 			struct fd f;
17616 			u64 addr;
17617 			u32 fd;
17618 
17619 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17620 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17621 			    insn[1].off != 0) {
17622 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17623 				return -EINVAL;
17624 			}
17625 
17626 			if (insn[0].src_reg == 0)
17627 				/* valid generic load 64-bit imm */
17628 				goto next_insn;
17629 
17630 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17631 				aux = &env->insn_aux_data[i];
17632 				err = check_pseudo_btf_id(env, insn, aux);
17633 				if (err)
17634 					return err;
17635 				goto next_insn;
17636 			}
17637 
17638 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17639 				aux = &env->insn_aux_data[i];
17640 				aux->ptr_type = PTR_TO_FUNC;
17641 				goto next_insn;
17642 			}
17643 
17644 			/* In final convert_pseudo_ld_imm64() step, this is
17645 			 * converted into regular 64-bit imm load insn.
17646 			 */
17647 			switch (insn[0].src_reg) {
17648 			case BPF_PSEUDO_MAP_VALUE:
17649 			case BPF_PSEUDO_MAP_IDX_VALUE:
17650 				break;
17651 			case BPF_PSEUDO_MAP_FD:
17652 			case BPF_PSEUDO_MAP_IDX:
17653 				if (insn[1].imm == 0)
17654 					break;
17655 				fallthrough;
17656 			default:
17657 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17658 				return -EINVAL;
17659 			}
17660 
17661 			switch (insn[0].src_reg) {
17662 			case BPF_PSEUDO_MAP_IDX_VALUE:
17663 			case BPF_PSEUDO_MAP_IDX:
17664 				if (bpfptr_is_null(env->fd_array)) {
17665 					verbose(env, "fd_idx without fd_array is invalid\n");
17666 					return -EPROTO;
17667 				}
17668 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17669 							    insn[0].imm * sizeof(fd),
17670 							    sizeof(fd)))
17671 					return -EFAULT;
17672 				break;
17673 			default:
17674 				fd = insn[0].imm;
17675 				break;
17676 			}
17677 
17678 			f = fdget(fd);
17679 			map = __bpf_map_get(f);
17680 			if (IS_ERR(map)) {
17681 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17682 				return PTR_ERR(map);
17683 			}
17684 
17685 			err = check_map_prog_compatibility(env, map, env->prog);
17686 			if (err) {
17687 				fdput(f);
17688 				return err;
17689 			}
17690 
17691 			aux = &env->insn_aux_data[i];
17692 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17693 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17694 				addr = (unsigned long)map;
17695 			} else {
17696 				u32 off = insn[1].imm;
17697 
17698 				if (off >= BPF_MAX_VAR_OFF) {
17699 					verbose(env, "direct value offset of %u is not allowed\n", off);
17700 					fdput(f);
17701 					return -EINVAL;
17702 				}
17703 
17704 				if (!map->ops->map_direct_value_addr) {
17705 					verbose(env, "no direct value access support for this map type\n");
17706 					fdput(f);
17707 					return -EINVAL;
17708 				}
17709 
17710 				err = map->ops->map_direct_value_addr(map, &addr, off);
17711 				if (err) {
17712 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17713 						map->value_size, off);
17714 					fdput(f);
17715 					return err;
17716 				}
17717 
17718 				aux->map_off = off;
17719 				addr += off;
17720 			}
17721 
17722 			insn[0].imm = (u32)addr;
17723 			insn[1].imm = addr >> 32;
17724 
17725 			/* check whether we recorded this map already */
17726 			for (j = 0; j < env->used_map_cnt; j++) {
17727 				if (env->used_maps[j] == map) {
17728 					aux->map_index = j;
17729 					fdput(f);
17730 					goto next_insn;
17731 				}
17732 			}
17733 
17734 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17735 				fdput(f);
17736 				return -E2BIG;
17737 			}
17738 
17739 			if (env->prog->aux->sleepable)
17740 				atomic64_inc(&map->sleepable_refcnt);
17741 			/* hold the map. If the program is rejected by verifier,
17742 			 * the map will be released by release_maps() or it
17743 			 * will be used by the valid program until it's unloaded
17744 			 * and all maps are released in bpf_free_used_maps()
17745 			 */
17746 			bpf_map_inc(map);
17747 
17748 			aux->map_index = env->used_map_cnt;
17749 			env->used_maps[env->used_map_cnt++] = map;
17750 
17751 			if (bpf_map_is_cgroup_storage(map) &&
17752 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17753 				verbose(env, "only one cgroup storage of each type is allowed\n");
17754 				fdput(f);
17755 				return -EBUSY;
17756 			}
17757 
17758 			fdput(f);
17759 next_insn:
17760 			insn++;
17761 			i++;
17762 			continue;
17763 		}
17764 
17765 		/* Basic sanity check before we invest more work here. */
17766 		if (!bpf_opcode_in_insntable(insn->code)) {
17767 			verbose(env, "unknown opcode %02x\n", insn->code);
17768 			return -EINVAL;
17769 		}
17770 	}
17771 
17772 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17773 	 * 'struct bpf_map *' into a register instead of user map_fd.
17774 	 * These pointers will be used later by verifier to validate map access.
17775 	 */
17776 	return 0;
17777 }
17778 
17779 /* drop refcnt of maps used by the rejected program */
17780 static void release_maps(struct bpf_verifier_env *env)
17781 {
17782 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17783 			     env->used_map_cnt);
17784 }
17785 
17786 /* drop refcnt of maps used by the rejected program */
17787 static void release_btfs(struct bpf_verifier_env *env)
17788 {
17789 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17790 			     env->used_btf_cnt);
17791 }
17792 
17793 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17794 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17795 {
17796 	struct bpf_insn *insn = env->prog->insnsi;
17797 	int insn_cnt = env->prog->len;
17798 	int i;
17799 
17800 	for (i = 0; i < insn_cnt; i++, insn++) {
17801 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17802 			continue;
17803 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17804 			continue;
17805 		insn->src_reg = 0;
17806 	}
17807 }
17808 
17809 /* single env->prog->insni[off] instruction was replaced with the range
17810  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17811  * [0, off) and [off, end) to new locations, so the patched range stays zero
17812  */
17813 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17814 				 struct bpf_insn_aux_data *new_data,
17815 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17816 {
17817 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17818 	struct bpf_insn *insn = new_prog->insnsi;
17819 	u32 old_seen = old_data[off].seen;
17820 	u32 prog_len;
17821 	int i;
17822 
17823 	/* aux info at OFF always needs adjustment, no matter fast path
17824 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17825 	 * original insn at old prog.
17826 	 */
17827 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17828 
17829 	if (cnt == 1)
17830 		return;
17831 	prog_len = new_prog->len;
17832 
17833 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17834 	memcpy(new_data + off + cnt - 1, old_data + off,
17835 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17836 	for (i = off; i < off + cnt - 1; i++) {
17837 		/* Expand insni[off]'s seen count to the patched range. */
17838 		new_data[i].seen = old_seen;
17839 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17840 	}
17841 	env->insn_aux_data = new_data;
17842 	vfree(old_data);
17843 }
17844 
17845 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17846 {
17847 	int i;
17848 
17849 	if (len == 1)
17850 		return;
17851 	/* NOTE: fake 'exit' subprog should be updated as well. */
17852 	for (i = 0; i <= env->subprog_cnt; i++) {
17853 		if (env->subprog_info[i].start <= off)
17854 			continue;
17855 		env->subprog_info[i].start += len - 1;
17856 	}
17857 }
17858 
17859 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17860 {
17861 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17862 	int i, sz = prog->aux->size_poke_tab;
17863 	struct bpf_jit_poke_descriptor *desc;
17864 
17865 	for (i = 0; i < sz; i++) {
17866 		desc = &tab[i];
17867 		if (desc->insn_idx <= off)
17868 			continue;
17869 		desc->insn_idx += len - 1;
17870 	}
17871 }
17872 
17873 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17874 					    const struct bpf_insn *patch, u32 len)
17875 {
17876 	struct bpf_prog *new_prog;
17877 	struct bpf_insn_aux_data *new_data = NULL;
17878 
17879 	if (len > 1) {
17880 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17881 					      sizeof(struct bpf_insn_aux_data)));
17882 		if (!new_data)
17883 			return NULL;
17884 	}
17885 
17886 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17887 	if (IS_ERR(new_prog)) {
17888 		if (PTR_ERR(new_prog) == -ERANGE)
17889 			verbose(env,
17890 				"insn %d cannot be patched due to 16-bit range\n",
17891 				env->insn_aux_data[off].orig_idx);
17892 		vfree(new_data);
17893 		return NULL;
17894 	}
17895 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17896 	adjust_subprog_starts(env, off, len);
17897 	adjust_poke_descs(new_prog, off, len);
17898 	return new_prog;
17899 }
17900 
17901 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17902 					      u32 off, u32 cnt)
17903 {
17904 	int i, j;
17905 
17906 	/* find first prog starting at or after off (first to remove) */
17907 	for (i = 0; i < env->subprog_cnt; i++)
17908 		if (env->subprog_info[i].start >= off)
17909 			break;
17910 	/* find first prog starting at or after off + cnt (first to stay) */
17911 	for (j = i; j < env->subprog_cnt; j++)
17912 		if (env->subprog_info[j].start >= off + cnt)
17913 			break;
17914 	/* if j doesn't start exactly at off + cnt, we are just removing
17915 	 * the front of previous prog
17916 	 */
17917 	if (env->subprog_info[j].start != off + cnt)
17918 		j--;
17919 
17920 	if (j > i) {
17921 		struct bpf_prog_aux *aux = env->prog->aux;
17922 		int move;
17923 
17924 		/* move fake 'exit' subprog as well */
17925 		move = env->subprog_cnt + 1 - j;
17926 
17927 		memmove(env->subprog_info + i,
17928 			env->subprog_info + j,
17929 			sizeof(*env->subprog_info) * move);
17930 		env->subprog_cnt -= j - i;
17931 
17932 		/* remove func_info */
17933 		if (aux->func_info) {
17934 			move = aux->func_info_cnt - j;
17935 
17936 			memmove(aux->func_info + i,
17937 				aux->func_info + j,
17938 				sizeof(*aux->func_info) * move);
17939 			aux->func_info_cnt -= j - i;
17940 			/* func_info->insn_off is set after all code rewrites,
17941 			 * in adjust_btf_func() - no need to adjust
17942 			 */
17943 		}
17944 	} else {
17945 		/* convert i from "first prog to remove" to "first to adjust" */
17946 		if (env->subprog_info[i].start == off)
17947 			i++;
17948 	}
17949 
17950 	/* update fake 'exit' subprog as well */
17951 	for (; i <= env->subprog_cnt; i++)
17952 		env->subprog_info[i].start -= cnt;
17953 
17954 	return 0;
17955 }
17956 
17957 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17958 				      u32 cnt)
17959 {
17960 	struct bpf_prog *prog = env->prog;
17961 	u32 i, l_off, l_cnt, nr_linfo;
17962 	struct bpf_line_info *linfo;
17963 
17964 	nr_linfo = prog->aux->nr_linfo;
17965 	if (!nr_linfo)
17966 		return 0;
17967 
17968 	linfo = prog->aux->linfo;
17969 
17970 	/* find first line info to remove, count lines to be removed */
17971 	for (i = 0; i < nr_linfo; i++)
17972 		if (linfo[i].insn_off >= off)
17973 			break;
17974 
17975 	l_off = i;
17976 	l_cnt = 0;
17977 	for (; i < nr_linfo; i++)
17978 		if (linfo[i].insn_off < off + cnt)
17979 			l_cnt++;
17980 		else
17981 			break;
17982 
17983 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17984 	 * last removed linfo.  prog is already modified, so prog->len == off
17985 	 * means no live instructions after (tail of the program was removed).
17986 	 */
17987 	if (prog->len != off && l_cnt &&
17988 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17989 		l_cnt--;
17990 		linfo[--i].insn_off = off + cnt;
17991 	}
17992 
17993 	/* remove the line info which refer to the removed instructions */
17994 	if (l_cnt) {
17995 		memmove(linfo + l_off, linfo + i,
17996 			sizeof(*linfo) * (nr_linfo - i));
17997 
17998 		prog->aux->nr_linfo -= l_cnt;
17999 		nr_linfo = prog->aux->nr_linfo;
18000 	}
18001 
18002 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18003 	for (i = l_off; i < nr_linfo; i++)
18004 		linfo[i].insn_off -= cnt;
18005 
18006 	/* fix up all subprogs (incl. 'exit') which start >= off */
18007 	for (i = 0; i <= env->subprog_cnt; i++)
18008 		if (env->subprog_info[i].linfo_idx > l_off) {
18009 			/* program may have started in the removed region but
18010 			 * may not be fully removed
18011 			 */
18012 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18013 				env->subprog_info[i].linfo_idx -= l_cnt;
18014 			else
18015 				env->subprog_info[i].linfo_idx = l_off;
18016 		}
18017 
18018 	return 0;
18019 }
18020 
18021 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18022 {
18023 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18024 	unsigned int orig_prog_len = env->prog->len;
18025 	int err;
18026 
18027 	if (bpf_prog_is_offloaded(env->prog->aux))
18028 		bpf_prog_offload_remove_insns(env, off, cnt);
18029 
18030 	err = bpf_remove_insns(env->prog, off, cnt);
18031 	if (err)
18032 		return err;
18033 
18034 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18035 	if (err)
18036 		return err;
18037 
18038 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18039 	if (err)
18040 		return err;
18041 
18042 	memmove(aux_data + off,	aux_data + off + cnt,
18043 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18044 
18045 	return 0;
18046 }
18047 
18048 /* The verifier does more data flow analysis than llvm and will not
18049  * explore branches that are dead at run time. Malicious programs can
18050  * have dead code too. Therefore replace all dead at-run-time code
18051  * with 'ja -1'.
18052  *
18053  * Just nops are not optimal, e.g. if they would sit at the end of the
18054  * program and through another bug we would manage to jump there, then
18055  * we'd execute beyond program memory otherwise. Returning exception
18056  * code also wouldn't work since we can have subprogs where the dead
18057  * code could be located.
18058  */
18059 static void sanitize_dead_code(struct bpf_verifier_env *env)
18060 {
18061 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18062 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18063 	struct bpf_insn *insn = env->prog->insnsi;
18064 	const int insn_cnt = env->prog->len;
18065 	int i;
18066 
18067 	for (i = 0; i < insn_cnt; i++) {
18068 		if (aux_data[i].seen)
18069 			continue;
18070 		memcpy(insn + i, &trap, sizeof(trap));
18071 		aux_data[i].zext_dst = false;
18072 	}
18073 }
18074 
18075 static bool insn_is_cond_jump(u8 code)
18076 {
18077 	u8 op;
18078 
18079 	op = BPF_OP(code);
18080 	if (BPF_CLASS(code) == BPF_JMP32)
18081 		return op != BPF_JA;
18082 
18083 	if (BPF_CLASS(code) != BPF_JMP)
18084 		return false;
18085 
18086 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18087 }
18088 
18089 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18090 {
18091 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18092 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18093 	struct bpf_insn *insn = env->prog->insnsi;
18094 	const int insn_cnt = env->prog->len;
18095 	int i;
18096 
18097 	for (i = 0; i < insn_cnt; i++, insn++) {
18098 		if (!insn_is_cond_jump(insn->code))
18099 			continue;
18100 
18101 		if (!aux_data[i + 1].seen)
18102 			ja.off = insn->off;
18103 		else if (!aux_data[i + 1 + insn->off].seen)
18104 			ja.off = 0;
18105 		else
18106 			continue;
18107 
18108 		if (bpf_prog_is_offloaded(env->prog->aux))
18109 			bpf_prog_offload_replace_insn(env, i, &ja);
18110 
18111 		memcpy(insn, &ja, sizeof(ja));
18112 	}
18113 }
18114 
18115 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18116 {
18117 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18118 	int insn_cnt = env->prog->len;
18119 	int i, err;
18120 
18121 	for (i = 0; i < insn_cnt; i++) {
18122 		int j;
18123 
18124 		j = 0;
18125 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18126 			j++;
18127 		if (!j)
18128 			continue;
18129 
18130 		err = verifier_remove_insns(env, i, j);
18131 		if (err)
18132 			return err;
18133 		insn_cnt = env->prog->len;
18134 	}
18135 
18136 	return 0;
18137 }
18138 
18139 static int opt_remove_nops(struct bpf_verifier_env *env)
18140 {
18141 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18142 	struct bpf_insn *insn = env->prog->insnsi;
18143 	int insn_cnt = env->prog->len;
18144 	int i, err;
18145 
18146 	for (i = 0; i < insn_cnt; i++) {
18147 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18148 			continue;
18149 
18150 		err = verifier_remove_insns(env, i, 1);
18151 		if (err)
18152 			return err;
18153 		insn_cnt--;
18154 		i--;
18155 	}
18156 
18157 	return 0;
18158 }
18159 
18160 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18161 					 const union bpf_attr *attr)
18162 {
18163 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18164 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18165 	int i, patch_len, delta = 0, len = env->prog->len;
18166 	struct bpf_insn *insns = env->prog->insnsi;
18167 	struct bpf_prog *new_prog;
18168 	bool rnd_hi32;
18169 
18170 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18171 	zext_patch[1] = BPF_ZEXT_REG(0);
18172 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18173 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18174 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18175 	for (i = 0; i < len; i++) {
18176 		int adj_idx = i + delta;
18177 		struct bpf_insn insn;
18178 		int load_reg;
18179 
18180 		insn = insns[adj_idx];
18181 		load_reg = insn_def_regno(&insn);
18182 		if (!aux[adj_idx].zext_dst) {
18183 			u8 code, class;
18184 			u32 imm_rnd;
18185 
18186 			if (!rnd_hi32)
18187 				continue;
18188 
18189 			code = insn.code;
18190 			class = BPF_CLASS(code);
18191 			if (load_reg == -1)
18192 				continue;
18193 
18194 			/* NOTE: arg "reg" (the fourth one) is only used for
18195 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18196 			 *       here.
18197 			 */
18198 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18199 				if (class == BPF_LD &&
18200 				    BPF_MODE(code) == BPF_IMM)
18201 					i++;
18202 				continue;
18203 			}
18204 
18205 			/* ctx load could be transformed into wider load. */
18206 			if (class == BPF_LDX &&
18207 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18208 				continue;
18209 
18210 			imm_rnd = get_random_u32();
18211 			rnd_hi32_patch[0] = insn;
18212 			rnd_hi32_patch[1].imm = imm_rnd;
18213 			rnd_hi32_patch[3].dst_reg = load_reg;
18214 			patch = rnd_hi32_patch;
18215 			patch_len = 4;
18216 			goto apply_patch_buffer;
18217 		}
18218 
18219 		/* Add in an zero-extend instruction if a) the JIT has requested
18220 		 * it or b) it's a CMPXCHG.
18221 		 *
18222 		 * The latter is because: BPF_CMPXCHG always loads a value into
18223 		 * R0, therefore always zero-extends. However some archs'
18224 		 * equivalent instruction only does this load when the
18225 		 * comparison is successful. This detail of CMPXCHG is
18226 		 * orthogonal to the general zero-extension behaviour of the
18227 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18228 		 */
18229 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18230 			continue;
18231 
18232 		/* Zero-extension is done by the caller. */
18233 		if (bpf_pseudo_kfunc_call(&insn))
18234 			continue;
18235 
18236 		if (WARN_ON(load_reg == -1)) {
18237 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18238 			return -EFAULT;
18239 		}
18240 
18241 		zext_patch[0] = insn;
18242 		zext_patch[1].dst_reg = load_reg;
18243 		zext_patch[1].src_reg = load_reg;
18244 		patch = zext_patch;
18245 		patch_len = 2;
18246 apply_patch_buffer:
18247 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18248 		if (!new_prog)
18249 			return -ENOMEM;
18250 		env->prog = new_prog;
18251 		insns = new_prog->insnsi;
18252 		aux = env->insn_aux_data;
18253 		delta += patch_len - 1;
18254 	}
18255 
18256 	return 0;
18257 }
18258 
18259 /* convert load instructions that access fields of a context type into a
18260  * sequence of instructions that access fields of the underlying structure:
18261  *     struct __sk_buff    -> struct sk_buff
18262  *     struct bpf_sock_ops -> struct sock
18263  */
18264 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18265 {
18266 	const struct bpf_verifier_ops *ops = env->ops;
18267 	int i, cnt, size, ctx_field_size, delta = 0;
18268 	const int insn_cnt = env->prog->len;
18269 	struct bpf_insn insn_buf[16], *insn;
18270 	u32 target_size, size_default, off;
18271 	struct bpf_prog *new_prog;
18272 	enum bpf_access_type type;
18273 	bool is_narrower_load;
18274 
18275 	if (ops->gen_prologue || env->seen_direct_write) {
18276 		if (!ops->gen_prologue) {
18277 			verbose(env, "bpf verifier is misconfigured\n");
18278 			return -EINVAL;
18279 		}
18280 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18281 					env->prog);
18282 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18283 			verbose(env, "bpf verifier is misconfigured\n");
18284 			return -EINVAL;
18285 		} else if (cnt) {
18286 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18287 			if (!new_prog)
18288 				return -ENOMEM;
18289 
18290 			env->prog = new_prog;
18291 			delta += cnt - 1;
18292 		}
18293 	}
18294 
18295 	if (bpf_prog_is_offloaded(env->prog->aux))
18296 		return 0;
18297 
18298 	insn = env->prog->insnsi + delta;
18299 
18300 	for (i = 0; i < insn_cnt; i++, insn++) {
18301 		bpf_convert_ctx_access_t convert_ctx_access;
18302 		u8 mode;
18303 
18304 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18305 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18306 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18307 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18308 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18309 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18310 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18311 			type = BPF_READ;
18312 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18313 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18314 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18315 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18316 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18317 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18318 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18319 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18320 			type = BPF_WRITE;
18321 		} else {
18322 			continue;
18323 		}
18324 
18325 		if (type == BPF_WRITE &&
18326 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18327 			struct bpf_insn patch[] = {
18328 				*insn,
18329 				BPF_ST_NOSPEC(),
18330 			};
18331 
18332 			cnt = ARRAY_SIZE(patch);
18333 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18334 			if (!new_prog)
18335 				return -ENOMEM;
18336 
18337 			delta    += cnt - 1;
18338 			env->prog = new_prog;
18339 			insn      = new_prog->insnsi + i + delta;
18340 			continue;
18341 		}
18342 
18343 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18344 		case PTR_TO_CTX:
18345 			if (!ops->convert_ctx_access)
18346 				continue;
18347 			convert_ctx_access = ops->convert_ctx_access;
18348 			break;
18349 		case PTR_TO_SOCKET:
18350 		case PTR_TO_SOCK_COMMON:
18351 			convert_ctx_access = bpf_sock_convert_ctx_access;
18352 			break;
18353 		case PTR_TO_TCP_SOCK:
18354 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18355 			break;
18356 		case PTR_TO_XDP_SOCK:
18357 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18358 			break;
18359 		case PTR_TO_BTF_ID:
18360 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18361 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18362 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18363 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18364 		 * any faults for loads into such types. BPF_WRITE is disallowed
18365 		 * for this case.
18366 		 */
18367 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18368 			if (type == BPF_READ) {
18369 				if (BPF_MODE(insn->code) == BPF_MEM)
18370 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18371 						     BPF_SIZE((insn)->code);
18372 				else
18373 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18374 						     BPF_SIZE((insn)->code);
18375 				env->prog->aux->num_exentries++;
18376 			}
18377 			continue;
18378 		default:
18379 			continue;
18380 		}
18381 
18382 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18383 		size = BPF_LDST_BYTES(insn);
18384 		mode = BPF_MODE(insn->code);
18385 
18386 		/* If the read access is a narrower load of the field,
18387 		 * convert to a 4/8-byte load, to minimum program type specific
18388 		 * convert_ctx_access changes. If conversion is successful,
18389 		 * we will apply proper mask to the result.
18390 		 */
18391 		is_narrower_load = size < ctx_field_size;
18392 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18393 		off = insn->off;
18394 		if (is_narrower_load) {
18395 			u8 size_code;
18396 
18397 			if (type == BPF_WRITE) {
18398 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18399 				return -EINVAL;
18400 			}
18401 
18402 			size_code = BPF_H;
18403 			if (ctx_field_size == 4)
18404 				size_code = BPF_W;
18405 			else if (ctx_field_size == 8)
18406 				size_code = BPF_DW;
18407 
18408 			insn->off = off & ~(size_default - 1);
18409 			insn->code = BPF_LDX | BPF_MEM | size_code;
18410 		}
18411 
18412 		target_size = 0;
18413 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18414 					 &target_size);
18415 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18416 		    (ctx_field_size && !target_size)) {
18417 			verbose(env, "bpf verifier is misconfigured\n");
18418 			return -EINVAL;
18419 		}
18420 
18421 		if (is_narrower_load && size < target_size) {
18422 			u8 shift = bpf_ctx_narrow_access_offset(
18423 				off, size, size_default) * 8;
18424 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18425 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18426 				return -EINVAL;
18427 			}
18428 			if (ctx_field_size <= 4) {
18429 				if (shift)
18430 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18431 									insn->dst_reg,
18432 									shift);
18433 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18434 								(1 << size * 8) - 1);
18435 			} else {
18436 				if (shift)
18437 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18438 									insn->dst_reg,
18439 									shift);
18440 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18441 								(1ULL << size * 8) - 1);
18442 			}
18443 		}
18444 		if (mode == BPF_MEMSX)
18445 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18446 						       insn->dst_reg, insn->dst_reg,
18447 						       size * 8, 0);
18448 
18449 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18450 		if (!new_prog)
18451 			return -ENOMEM;
18452 
18453 		delta += cnt - 1;
18454 
18455 		/* keep walking new program and skip insns we just inserted */
18456 		env->prog = new_prog;
18457 		insn      = new_prog->insnsi + i + delta;
18458 	}
18459 
18460 	return 0;
18461 }
18462 
18463 static int jit_subprogs(struct bpf_verifier_env *env)
18464 {
18465 	struct bpf_prog *prog = env->prog, **func, *tmp;
18466 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18467 	struct bpf_map *map_ptr;
18468 	struct bpf_insn *insn;
18469 	void *old_bpf_func;
18470 	int err, num_exentries;
18471 
18472 	if (env->subprog_cnt <= 1)
18473 		return 0;
18474 
18475 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18476 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18477 			continue;
18478 
18479 		/* Upon error here we cannot fall back to interpreter but
18480 		 * need a hard reject of the program. Thus -EFAULT is
18481 		 * propagated in any case.
18482 		 */
18483 		subprog = find_subprog(env, i + insn->imm + 1);
18484 		if (subprog < 0) {
18485 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18486 				  i + insn->imm + 1);
18487 			return -EFAULT;
18488 		}
18489 		/* temporarily remember subprog id inside insn instead of
18490 		 * aux_data, since next loop will split up all insns into funcs
18491 		 */
18492 		insn->off = subprog;
18493 		/* remember original imm in case JIT fails and fallback
18494 		 * to interpreter will be needed
18495 		 */
18496 		env->insn_aux_data[i].call_imm = insn->imm;
18497 		/* point imm to __bpf_call_base+1 from JITs point of view */
18498 		insn->imm = 1;
18499 		if (bpf_pseudo_func(insn))
18500 			/* jit (e.g. x86_64) may emit fewer instructions
18501 			 * if it learns a u32 imm is the same as a u64 imm.
18502 			 * Force a non zero here.
18503 			 */
18504 			insn[1].imm = 1;
18505 	}
18506 
18507 	err = bpf_prog_alloc_jited_linfo(prog);
18508 	if (err)
18509 		goto out_undo_insn;
18510 
18511 	err = -ENOMEM;
18512 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18513 	if (!func)
18514 		goto out_undo_insn;
18515 
18516 	for (i = 0; i < env->subprog_cnt; i++) {
18517 		subprog_start = subprog_end;
18518 		subprog_end = env->subprog_info[i + 1].start;
18519 
18520 		len = subprog_end - subprog_start;
18521 		/* bpf_prog_run() doesn't call subprogs directly,
18522 		 * hence main prog stats include the runtime of subprogs.
18523 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18524 		 * func[i]->stats will never be accessed and stays NULL
18525 		 */
18526 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18527 		if (!func[i])
18528 			goto out_free;
18529 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18530 		       len * sizeof(struct bpf_insn));
18531 		func[i]->type = prog->type;
18532 		func[i]->len = len;
18533 		if (bpf_prog_calc_tag(func[i]))
18534 			goto out_free;
18535 		func[i]->is_func = 1;
18536 		func[i]->aux->func_idx = i;
18537 		/* Below members will be freed only at prog->aux */
18538 		func[i]->aux->btf = prog->aux->btf;
18539 		func[i]->aux->func_info = prog->aux->func_info;
18540 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18541 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18542 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18543 
18544 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18545 			struct bpf_jit_poke_descriptor *poke;
18546 
18547 			poke = &prog->aux->poke_tab[j];
18548 			if (poke->insn_idx < subprog_end &&
18549 			    poke->insn_idx >= subprog_start)
18550 				poke->aux = func[i]->aux;
18551 		}
18552 
18553 		func[i]->aux->name[0] = 'F';
18554 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18555 		func[i]->jit_requested = 1;
18556 		func[i]->blinding_requested = prog->blinding_requested;
18557 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18558 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18559 		func[i]->aux->linfo = prog->aux->linfo;
18560 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18561 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18562 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18563 		num_exentries = 0;
18564 		insn = func[i]->insnsi;
18565 		for (j = 0; j < func[i]->len; j++, insn++) {
18566 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18567 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18568 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18569 				num_exentries++;
18570 		}
18571 		func[i]->aux->num_exentries = num_exentries;
18572 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18573 		func[i] = bpf_int_jit_compile(func[i]);
18574 		if (!func[i]->jited) {
18575 			err = -ENOTSUPP;
18576 			goto out_free;
18577 		}
18578 		cond_resched();
18579 	}
18580 
18581 	/* at this point all bpf functions were successfully JITed
18582 	 * now populate all bpf_calls with correct addresses and
18583 	 * run last pass of JIT
18584 	 */
18585 	for (i = 0; i < env->subprog_cnt; i++) {
18586 		insn = func[i]->insnsi;
18587 		for (j = 0; j < func[i]->len; j++, insn++) {
18588 			if (bpf_pseudo_func(insn)) {
18589 				subprog = insn->off;
18590 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18591 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18592 				continue;
18593 			}
18594 			if (!bpf_pseudo_call(insn))
18595 				continue;
18596 			subprog = insn->off;
18597 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18598 		}
18599 
18600 		/* we use the aux data to keep a list of the start addresses
18601 		 * of the JITed images for each function in the program
18602 		 *
18603 		 * for some architectures, such as powerpc64, the imm field
18604 		 * might not be large enough to hold the offset of the start
18605 		 * address of the callee's JITed image from __bpf_call_base
18606 		 *
18607 		 * in such cases, we can lookup the start address of a callee
18608 		 * by using its subprog id, available from the off field of
18609 		 * the call instruction, as an index for this list
18610 		 */
18611 		func[i]->aux->func = func;
18612 		func[i]->aux->func_cnt = env->subprog_cnt;
18613 	}
18614 	for (i = 0; i < env->subprog_cnt; i++) {
18615 		old_bpf_func = func[i]->bpf_func;
18616 		tmp = bpf_int_jit_compile(func[i]);
18617 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18618 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18619 			err = -ENOTSUPP;
18620 			goto out_free;
18621 		}
18622 		cond_resched();
18623 	}
18624 
18625 	/* finally lock prog and jit images for all functions and
18626 	 * populate kallsysm. Begin at the first subprogram, since
18627 	 * bpf_prog_load will add the kallsyms for the main program.
18628 	 */
18629 	for (i = 1; i < env->subprog_cnt; i++) {
18630 		bpf_prog_lock_ro(func[i]);
18631 		bpf_prog_kallsyms_add(func[i]);
18632 	}
18633 
18634 	/* Last step: make now unused interpreter insns from main
18635 	 * prog consistent for later dump requests, so they can
18636 	 * later look the same as if they were interpreted only.
18637 	 */
18638 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18639 		if (bpf_pseudo_func(insn)) {
18640 			insn[0].imm = env->insn_aux_data[i].call_imm;
18641 			insn[1].imm = insn->off;
18642 			insn->off = 0;
18643 			continue;
18644 		}
18645 		if (!bpf_pseudo_call(insn))
18646 			continue;
18647 		insn->off = env->insn_aux_data[i].call_imm;
18648 		subprog = find_subprog(env, i + insn->off + 1);
18649 		insn->imm = subprog;
18650 	}
18651 
18652 	prog->jited = 1;
18653 	prog->bpf_func = func[0]->bpf_func;
18654 	prog->jited_len = func[0]->jited_len;
18655 	prog->aux->extable = func[0]->aux->extable;
18656 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18657 	prog->aux->func = func;
18658 	prog->aux->func_cnt = env->subprog_cnt;
18659 	bpf_prog_jit_attempt_done(prog);
18660 	return 0;
18661 out_free:
18662 	/* We failed JIT'ing, so at this point we need to unregister poke
18663 	 * descriptors from subprogs, so that kernel is not attempting to
18664 	 * patch it anymore as we're freeing the subprog JIT memory.
18665 	 */
18666 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18667 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18668 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18669 	}
18670 	/* At this point we're guaranteed that poke descriptors are not
18671 	 * live anymore. We can just unlink its descriptor table as it's
18672 	 * released with the main prog.
18673 	 */
18674 	for (i = 0; i < env->subprog_cnt; i++) {
18675 		if (!func[i])
18676 			continue;
18677 		func[i]->aux->poke_tab = NULL;
18678 		bpf_jit_free(func[i]);
18679 	}
18680 	kfree(func);
18681 out_undo_insn:
18682 	/* cleanup main prog to be interpreted */
18683 	prog->jit_requested = 0;
18684 	prog->blinding_requested = 0;
18685 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18686 		if (!bpf_pseudo_call(insn))
18687 			continue;
18688 		insn->off = 0;
18689 		insn->imm = env->insn_aux_data[i].call_imm;
18690 	}
18691 	bpf_prog_jit_attempt_done(prog);
18692 	return err;
18693 }
18694 
18695 static int fixup_call_args(struct bpf_verifier_env *env)
18696 {
18697 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18698 	struct bpf_prog *prog = env->prog;
18699 	struct bpf_insn *insn = prog->insnsi;
18700 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18701 	int i, depth;
18702 #endif
18703 	int err = 0;
18704 
18705 	if (env->prog->jit_requested &&
18706 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18707 		err = jit_subprogs(env);
18708 		if (err == 0)
18709 			return 0;
18710 		if (err == -EFAULT)
18711 			return err;
18712 	}
18713 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18714 	if (has_kfunc_call) {
18715 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18716 		return -EINVAL;
18717 	}
18718 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18719 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18720 		 * have to be rejected, since interpreter doesn't support them yet.
18721 		 */
18722 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18723 		return -EINVAL;
18724 	}
18725 	for (i = 0; i < prog->len; i++, insn++) {
18726 		if (bpf_pseudo_func(insn)) {
18727 			/* When JIT fails the progs with callback calls
18728 			 * have to be rejected, since interpreter doesn't support them yet.
18729 			 */
18730 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18731 			return -EINVAL;
18732 		}
18733 
18734 		if (!bpf_pseudo_call(insn))
18735 			continue;
18736 		depth = get_callee_stack_depth(env, insn, i);
18737 		if (depth < 0)
18738 			return depth;
18739 		bpf_patch_call_args(insn, depth);
18740 	}
18741 	err = 0;
18742 #endif
18743 	return err;
18744 }
18745 
18746 /* replace a generic kfunc with a specialized version if necessary */
18747 static void specialize_kfunc(struct bpf_verifier_env *env,
18748 			     u32 func_id, u16 offset, unsigned long *addr)
18749 {
18750 	struct bpf_prog *prog = env->prog;
18751 	bool seen_direct_write;
18752 	void *xdp_kfunc;
18753 	bool is_rdonly;
18754 
18755 	if (bpf_dev_bound_kfunc_id(func_id)) {
18756 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18757 		if (xdp_kfunc) {
18758 			*addr = (unsigned long)xdp_kfunc;
18759 			return;
18760 		}
18761 		/* fallback to default kfunc when not supported by netdev */
18762 	}
18763 
18764 	if (offset)
18765 		return;
18766 
18767 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18768 		seen_direct_write = env->seen_direct_write;
18769 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18770 
18771 		if (is_rdonly)
18772 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18773 
18774 		/* restore env->seen_direct_write to its original value, since
18775 		 * may_access_direct_pkt_data mutates it
18776 		 */
18777 		env->seen_direct_write = seen_direct_write;
18778 	}
18779 }
18780 
18781 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18782 					    u16 struct_meta_reg,
18783 					    u16 node_offset_reg,
18784 					    struct bpf_insn *insn,
18785 					    struct bpf_insn *insn_buf,
18786 					    int *cnt)
18787 {
18788 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18789 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18790 
18791 	insn_buf[0] = addr[0];
18792 	insn_buf[1] = addr[1];
18793 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18794 	insn_buf[3] = *insn;
18795 	*cnt = 4;
18796 }
18797 
18798 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18799 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18800 {
18801 	const struct bpf_kfunc_desc *desc;
18802 
18803 	if (!insn->imm) {
18804 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18805 		return -EINVAL;
18806 	}
18807 
18808 	*cnt = 0;
18809 
18810 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18811 	 * __bpf_call_base, unless the JIT needs to call functions that are
18812 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18813 	 */
18814 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18815 	if (!desc) {
18816 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18817 			insn->imm);
18818 		return -EFAULT;
18819 	}
18820 
18821 	if (!bpf_jit_supports_far_kfunc_call())
18822 		insn->imm = BPF_CALL_IMM(desc->addr);
18823 	if (insn->off)
18824 		return 0;
18825 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18826 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18827 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18828 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18829 
18830 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18831 		insn_buf[1] = addr[0];
18832 		insn_buf[2] = addr[1];
18833 		insn_buf[3] = *insn;
18834 		*cnt = 4;
18835 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18836 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18837 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18838 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18839 
18840 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18841 		    !kptr_struct_meta) {
18842 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18843 				insn_idx);
18844 			return -EFAULT;
18845 		}
18846 
18847 		insn_buf[0] = addr[0];
18848 		insn_buf[1] = addr[1];
18849 		insn_buf[2] = *insn;
18850 		*cnt = 3;
18851 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18852 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18853 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18854 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18855 		int struct_meta_reg = BPF_REG_3;
18856 		int node_offset_reg = BPF_REG_4;
18857 
18858 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18859 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18860 			struct_meta_reg = BPF_REG_4;
18861 			node_offset_reg = BPF_REG_5;
18862 		}
18863 
18864 		if (!kptr_struct_meta) {
18865 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18866 				insn_idx);
18867 			return -EFAULT;
18868 		}
18869 
18870 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18871 						node_offset_reg, insn, insn_buf, cnt);
18872 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18873 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18874 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18875 		*cnt = 1;
18876 	}
18877 	return 0;
18878 }
18879 
18880 /* Do various post-verification rewrites in a single program pass.
18881  * These rewrites simplify JIT and interpreter implementations.
18882  */
18883 static int do_misc_fixups(struct bpf_verifier_env *env)
18884 {
18885 	struct bpf_prog *prog = env->prog;
18886 	enum bpf_attach_type eatype = prog->expected_attach_type;
18887 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18888 	struct bpf_insn *insn = prog->insnsi;
18889 	const struct bpf_func_proto *fn;
18890 	const int insn_cnt = prog->len;
18891 	const struct bpf_map_ops *ops;
18892 	struct bpf_insn_aux_data *aux;
18893 	struct bpf_insn insn_buf[16];
18894 	struct bpf_prog *new_prog;
18895 	struct bpf_map *map_ptr;
18896 	int i, ret, cnt, delta = 0;
18897 
18898 	for (i = 0; i < insn_cnt; i++, insn++) {
18899 		/* Make divide-by-zero exceptions impossible. */
18900 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18901 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18902 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18903 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18904 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18905 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18906 			struct bpf_insn *patchlet;
18907 			struct bpf_insn chk_and_div[] = {
18908 				/* [R,W]x div 0 -> 0 */
18909 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18910 					     BPF_JNE | BPF_K, insn->src_reg,
18911 					     0, 2, 0),
18912 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18913 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18914 				*insn,
18915 			};
18916 			struct bpf_insn chk_and_mod[] = {
18917 				/* [R,W]x mod 0 -> [R,W]x */
18918 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18919 					     BPF_JEQ | BPF_K, insn->src_reg,
18920 					     0, 1 + (is64 ? 0 : 1), 0),
18921 				*insn,
18922 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18923 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18924 			};
18925 
18926 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18927 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18928 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18929 
18930 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18931 			if (!new_prog)
18932 				return -ENOMEM;
18933 
18934 			delta    += cnt - 1;
18935 			env->prog = prog = new_prog;
18936 			insn      = new_prog->insnsi + i + delta;
18937 			continue;
18938 		}
18939 
18940 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18941 		if (BPF_CLASS(insn->code) == BPF_LD &&
18942 		    (BPF_MODE(insn->code) == BPF_ABS ||
18943 		     BPF_MODE(insn->code) == BPF_IND)) {
18944 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18945 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18946 				verbose(env, "bpf verifier is misconfigured\n");
18947 				return -EINVAL;
18948 			}
18949 
18950 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18951 			if (!new_prog)
18952 				return -ENOMEM;
18953 
18954 			delta    += cnt - 1;
18955 			env->prog = prog = new_prog;
18956 			insn      = new_prog->insnsi + i + delta;
18957 			continue;
18958 		}
18959 
18960 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18961 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18962 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18963 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18964 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18965 			struct bpf_insn *patch = &insn_buf[0];
18966 			bool issrc, isneg, isimm;
18967 			u32 off_reg;
18968 
18969 			aux = &env->insn_aux_data[i + delta];
18970 			if (!aux->alu_state ||
18971 			    aux->alu_state == BPF_ALU_NON_POINTER)
18972 				continue;
18973 
18974 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18975 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18976 				BPF_ALU_SANITIZE_SRC;
18977 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18978 
18979 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18980 			if (isimm) {
18981 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18982 			} else {
18983 				if (isneg)
18984 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18985 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18986 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18987 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18988 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18989 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18990 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18991 			}
18992 			if (!issrc)
18993 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18994 			insn->src_reg = BPF_REG_AX;
18995 			if (isneg)
18996 				insn->code = insn->code == code_add ?
18997 					     code_sub : code_add;
18998 			*patch++ = *insn;
18999 			if (issrc && isneg && !isimm)
19000 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19001 			cnt = patch - insn_buf;
19002 
19003 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19004 			if (!new_prog)
19005 				return -ENOMEM;
19006 
19007 			delta    += cnt - 1;
19008 			env->prog = prog = new_prog;
19009 			insn      = new_prog->insnsi + i + delta;
19010 			continue;
19011 		}
19012 
19013 		if (insn->code != (BPF_JMP | BPF_CALL))
19014 			continue;
19015 		if (insn->src_reg == BPF_PSEUDO_CALL)
19016 			continue;
19017 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19018 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19019 			if (ret)
19020 				return ret;
19021 			if (cnt == 0)
19022 				continue;
19023 
19024 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19025 			if (!new_prog)
19026 				return -ENOMEM;
19027 
19028 			delta	 += cnt - 1;
19029 			env->prog = prog = new_prog;
19030 			insn	  = new_prog->insnsi + i + delta;
19031 			continue;
19032 		}
19033 
19034 		if (insn->imm == BPF_FUNC_get_route_realm)
19035 			prog->dst_needed = 1;
19036 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19037 			bpf_user_rnd_init_once();
19038 		if (insn->imm == BPF_FUNC_override_return)
19039 			prog->kprobe_override = 1;
19040 		if (insn->imm == BPF_FUNC_tail_call) {
19041 			/* If we tail call into other programs, we
19042 			 * cannot make any assumptions since they can
19043 			 * be replaced dynamically during runtime in
19044 			 * the program array.
19045 			 */
19046 			prog->cb_access = 1;
19047 			if (!allow_tail_call_in_subprogs(env))
19048 				prog->aux->stack_depth = MAX_BPF_STACK;
19049 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19050 
19051 			/* mark bpf_tail_call as different opcode to avoid
19052 			 * conditional branch in the interpreter for every normal
19053 			 * call and to prevent accidental JITing by JIT compiler
19054 			 * that doesn't support bpf_tail_call yet
19055 			 */
19056 			insn->imm = 0;
19057 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19058 
19059 			aux = &env->insn_aux_data[i + delta];
19060 			if (env->bpf_capable && !prog->blinding_requested &&
19061 			    prog->jit_requested &&
19062 			    !bpf_map_key_poisoned(aux) &&
19063 			    !bpf_map_ptr_poisoned(aux) &&
19064 			    !bpf_map_ptr_unpriv(aux)) {
19065 				struct bpf_jit_poke_descriptor desc = {
19066 					.reason = BPF_POKE_REASON_TAIL_CALL,
19067 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19068 					.tail_call.key = bpf_map_key_immediate(aux),
19069 					.insn_idx = i + delta,
19070 				};
19071 
19072 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19073 				if (ret < 0) {
19074 					verbose(env, "adding tail call poke descriptor failed\n");
19075 					return ret;
19076 				}
19077 
19078 				insn->imm = ret + 1;
19079 				continue;
19080 			}
19081 
19082 			if (!bpf_map_ptr_unpriv(aux))
19083 				continue;
19084 
19085 			/* instead of changing every JIT dealing with tail_call
19086 			 * emit two extra insns:
19087 			 * if (index >= max_entries) goto out;
19088 			 * index &= array->index_mask;
19089 			 * to avoid out-of-bounds cpu speculation
19090 			 */
19091 			if (bpf_map_ptr_poisoned(aux)) {
19092 				verbose(env, "tail_call abusing map_ptr\n");
19093 				return -EINVAL;
19094 			}
19095 
19096 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19097 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19098 						  map_ptr->max_entries, 2);
19099 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19100 						    container_of(map_ptr,
19101 								 struct bpf_array,
19102 								 map)->index_mask);
19103 			insn_buf[2] = *insn;
19104 			cnt = 3;
19105 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19106 			if (!new_prog)
19107 				return -ENOMEM;
19108 
19109 			delta    += cnt - 1;
19110 			env->prog = prog = new_prog;
19111 			insn      = new_prog->insnsi + i + delta;
19112 			continue;
19113 		}
19114 
19115 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19116 			/* The verifier will process callback_fn as many times as necessary
19117 			 * with different maps and the register states prepared by
19118 			 * set_timer_callback_state will be accurate.
19119 			 *
19120 			 * The following use case is valid:
19121 			 *   map1 is shared by prog1, prog2, prog3.
19122 			 *   prog1 calls bpf_timer_init for some map1 elements
19123 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19124 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19125 			 *   prog3 calls bpf_timer_start for some map1 elements.
19126 			 *     Those that were not both bpf_timer_init-ed and
19127 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19128 			 */
19129 			struct bpf_insn ld_addrs[2] = {
19130 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19131 			};
19132 
19133 			insn_buf[0] = ld_addrs[0];
19134 			insn_buf[1] = ld_addrs[1];
19135 			insn_buf[2] = *insn;
19136 			cnt = 3;
19137 
19138 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19139 			if (!new_prog)
19140 				return -ENOMEM;
19141 
19142 			delta    += cnt - 1;
19143 			env->prog = prog = new_prog;
19144 			insn      = new_prog->insnsi + i + delta;
19145 			goto patch_call_imm;
19146 		}
19147 
19148 		if (is_storage_get_function(insn->imm)) {
19149 			if (!env->prog->aux->sleepable ||
19150 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19151 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19152 			else
19153 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19154 			insn_buf[1] = *insn;
19155 			cnt = 2;
19156 
19157 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19158 			if (!new_prog)
19159 				return -ENOMEM;
19160 
19161 			delta += cnt - 1;
19162 			env->prog = prog = new_prog;
19163 			insn = new_prog->insnsi + i + delta;
19164 			goto patch_call_imm;
19165 		}
19166 
19167 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19168 		 * and other inlining handlers are currently limited to 64 bit
19169 		 * only.
19170 		 */
19171 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19172 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19173 		     insn->imm == BPF_FUNC_map_update_elem ||
19174 		     insn->imm == BPF_FUNC_map_delete_elem ||
19175 		     insn->imm == BPF_FUNC_map_push_elem   ||
19176 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19177 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19178 		     insn->imm == BPF_FUNC_redirect_map    ||
19179 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19180 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19181 			aux = &env->insn_aux_data[i + delta];
19182 			if (bpf_map_ptr_poisoned(aux))
19183 				goto patch_call_imm;
19184 
19185 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19186 			ops = map_ptr->ops;
19187 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19188 			    ops->map_gen_lookup) {
19189 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19190 				if (cnt == -EOPNOTSUPP)
19191 					goto patch_map_ops_generic;
19192 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19193 					verbose(env, "bpf verifier is misconfigured\n");
19194 					return -EINVAL;
19195 				}
19196 
19197 				new_prog = bpf_patch_insn_data(env, i + delta,
19198 							       insn_buf, cnt);
19199 				if (!new_prog)
19200 					return -ENOMEM;
19201 
19202 				delta    += cnt - 1;
19203 				env->prog = prog = new_prog;
19204 				insn      = new_prog->insnsi + i + delta;
19205 				continue;
19206 			}
19207 
19208 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19209 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19210 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19211 				     (long (*)(struct bpf_map *map, void *key))NULL));
19212 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19213 				     (long (*)(struct bpf_map *map, void *key, void *value,
19214 					      u64 flags))NULL));
19215 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19216 				     (long (*)(struct bpf_map *map, void *value,
19217 					      u64 flags))NULL));
19218 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19219 				     (long (*)(struct bpf_map *map, void *value))NULL));
19220 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19221 				     (long (*)(struct bpf_map *map, void *value))NULL));
19222 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19223 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19224 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19225 				     (long (*)(struct bpf_map *map,
19226 					      bpf_callback_t callback_fn,
19227 					      void *callback_ctx,
19228 					      u64 flags))NULL));
19229 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19230 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19231 
19232 patch_map_ops_generic:
19233 			switch (insn->imm) {
19234 			case BPF_FUNC_map_lookup_elem:
19235 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19236 				continue;
19237 			case BPF_FUNC_map_update_elem:
19238 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19239 				continue;
19240 			case BPF_FUNC_map_delete_elem:
19241 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19242 				continue;
19243 			case BPF_FUNC_map_push_elem:
19244 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19245 				continue;
19246 			case BPF_FUNC_map_pop_elem:
19247 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19248 				continue;
19249 			case BPF_FUNC_map_peek_elem:
19250 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19251 				continue;
19252 			case BPF_FUNC_redirect_map:
19253 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19254 				continue;
19255 			case BPF_FUNC_for_each_map_elem:
19256 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19257 				continue;
19258 			case BPF_FUNC_map_lookup_percpu_elem:
19259 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19260 				continue;
19261 			}
19262 
19263 			goto patch_call_imm;
19264 		}
19265 
19266 		/* Implement bpf_jiffies64 inline. */
19267 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19268 		    insn->imm == BPF_FUNC_jiffies64) {
19269 			struct bpf_insn ld_jiffies_addr[2] = {
19270 				BPF_LD_IMM64(BPF_REG_0,
19271 					     (unsigned long)&jiffies),
19272 			};
19273 
19274 			insn_buf[0] = ld_jiffies_addr[0];
19275 			insn_buf[1] = ld_jiffies_addr[1];
19276 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19277 						  BPF_REG_0, 0);
19278 			cnt = 3;
19279 
19280 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19281 						       cnt);
19282 			if (!new_prog)
19283 				return -ENOMEM;
19284 
19285 			delta    += cnt - 1;
19286 			env->prog = prog = new_prog;
19287 			insn      = new_prog->insnsi + i + delta;
19288 			continue;
19289 		}
19290 
19291 		/* Implement bpf_get_func_arg inline. */
19292 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19293 		    insn->imm == BPF_FUNC_get_func_arg) {
19294 			/* Load nr_args from ctx - 8 */
19295 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19296 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19297 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19298 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19299 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19300 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19301 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19302 			insn_buf[7] = BPF_JMP_A(1);
19303 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19304 			cnt = 9;
19305 
19306 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19307 			if (!new_prog)
19308 				return -ENOMEM;
19309 
19310 			delta    += cnt - 1;
19311 			env->prog = prog = new_prog;
19312 			insn      = new_prog->insnsi + i + delta;
19313 			continue;
19314 		}
19315 
19316 		/* Implement bpf_get_func_ret inline. */
19317 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19318 		    insn->imm == BPF_FUNC_get_func_ret) {
19319 			if (eatype == BPF_TRACE_FEXIT ||
19320 			    eatype == BPF_MODIFY_RETURN) {
19321 				/* Load nr_args from ctx - 8 */
19322 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19323 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19324 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19325 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19326 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19327 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19328 				cnt = 6;
19329 			} else {
19330 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19331 				cnt = 1;
19332 			}
19333 
19334 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19335 			if (!new_prog)
19336 				return -ENOMEM;
19337 
19338 			delta    += cnt - 1;
19339 			env->prog = prog = new_prog;
19340 			insn      = new_prog->insnsi + i + delta;
19341 			continue;
19342 		}
19343 
19344 		/* Implement get_func_arg_cnt inline. */
19345 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19346 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19347 			/* Load nr_args from ctx - 8 */
19348 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19349 
19350 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19351 			if (!new_prog)
19352 				return -ENOMEM;
19353 
19354 			env->prog = prog = new_prog;
19355 			insn      = new_prog->insnsi + i + delta;
19356 			continue;
19357 		}
19358 
19359 		/* Implement bpf_get_func_ip inline. */
19360 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19361 		    insn->imm == BPF_FUNC_get_func_ip) {
19362 			/* Load IP address from ctx - 16 */
19363 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19364 
19365 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19366 			if (!new_prog)
19367 				return -ENOMEM;
19368 
19369 			env->prog = prog = new_prog;
19370 			insn      = new_prog->insnsi + i + delta;
19371 			continue;
19372 		}
19373 
19374 patch_call_imm:
19375 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19376 		/* all functions that have prototype and verifier allowed
19377 		 * programs to call them, must be real in-kernel functions
19378 		 */
19379 		if (!fn->func) {
19380 			verbose(env,
19381 				"kernel subsystem misconfigured func %s#%d\n",
19382 				func_id_name(insn->imm), insn->imm);
19383 			return -EFAULT;
19384 		}
19385 		insn->imm = fn->func - __bpf_call_base;
19386 	}
19387 
19388 	/* Since poke tab is now finalized, publish aux to tracker. */
19389 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19390 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19391 		if (!map_ptr->ops->map_poke_track ||
19392 		    !map_ptr->ops->map_poke_untrack ||
19393 		    !map_ptr->ops->map_poke_run) {
19394 			verbose(env, "bpf verifier is misconfigured\n");
19395 			return -EINVAL;
19396 		}
19397 
19398 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19399 		if (ret < 0) {
19400 			verbose(env, "tracking tail call prog failed\n");
19401 			return ret;
19402 		}
19403 	}
19404 
19405 	sort_kfunc_descs_by_imm_off(env->prog);
19406 
19407 	return 0;
19408 }
19409 
19410 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19411 					int position,
19412 					s32 stack_base,
19413 					u32 callback_subprogno,
19414 					u32 *cnt)
19415 {
19416 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19417 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19418 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19419 	int reg_loop_max = BPF_REG_6;
19420 	int reg_loop_cnt = BPF_REG_7;
19421 	int reg_loop_ctx = BPF_REG_8;
19422 
19423 	struct bpf_prog *new_prog;
19424 	u32 callback_start;
19425 	u32 call_insn_offset;
19426 	s32 callback_offset;
19427 
19428 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19429 	 * be careful to modify this code in sync.
19430 	 */
19431 	struct bpf_insn insn_buf[] = {
19432 		/* Return error and jump to the end of the patch if
19433 		 * expected number of iterations is too big.
19434 		 */
19435 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19436 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19437 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19438 		/* spill R6, R7, R8 to use these as loop vars */
19439 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19440 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19441 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19442 		/* initialize loop vars */
19443 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19444 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19445 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19446 		/* loop header,
19447 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19448 		 */
19449 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19450 		/* callback call,
19451 		 * correct callback offset would be set after patching
19452 		 */
19453 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19454 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19455 		BPF_CALL_REL(0),
19456 		/* increment loop counter */
19457 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19458 		/* jump to loop header if callback returned 0 */
19459 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19460 		/* return value of bpf_loop,
19461 		 * set R0 to the number of iterations
19462 		 */
19463 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19464 		/* restore original values of R6, R7, R8 */
19465 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19466 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19467 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19468 	};
19469 
19470 	*cnt = ARRAY_SIZE(insn_buf);
19471 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19472 	if (!new_prog)
19473 		return new_prog;
19474 
19475 	/* callback start is known only after patching */
19476 	callback_start = env->subprog_info[callback_subprogno].start;
19477 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19478 	call_insn_offset = position + 12;
19479 	callback_offset = callback_start - call_insn_offset - 1;
19480 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19481 
19482 	return new_prog;
19483 }
19484 
19485 static bool is_bpf_loop_call(struct bpf_insn *insn)
19486 {
19487 	return insn->code == (BPF_JMP | BPF_CALL) &&
19488 		insn->src_reg == 0 &&
19489 		insn->imm == BPF_FUNC_loop;
19490 }
19491 
19492 /* For all sub-programs in the program (including main) check
19493  * insn_aux_data to see if there are bpf_loop calls that require
19494  * inlining. If such calls are found the calls are replaced with a
19495  * sequence of instructions produced by `inline_bpf_loop` function and
19496  * subprog stack_depth is increased by the size of 3 registers.
19497  * This stack space is used to spill values of the R6, R7, R8.  These
19498  * registers are used to store the loop bound, counter and context
19499  * variables.
19500  */
19501 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19502 {
19503 	struct bpf_subprog_info *subprogs = env->subprog_info;
19504 	int i, cur_subprog = 0, cnt, delta = 0;
19505 	struct bpf_insn *insn = env->prog->insnsi;
19506 	int insn_cnt = env->prog->len;
19507 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19508 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19509 	u16 stack_depth_extra = 0;
19510 
19511 	for (i = 0; i < insn_cnt; i++, insn++) {
19512 		struct bpf_loop_inline_state *inline_state =
19513 			&env->insn_aux_data[i + delta].loop_inline_state;
19514 
19515 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19516 			struct bpf_prog *new_prog;
19517 
19518 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19519 			new_prog = inline_bpf_loop(env,
19520 						   i + delta,
19521 						   -(stack_depth + stack_depth_extra),
19522 						   inline_state->callback_subprogno,
19523 						   &cnt);
19524 			if (!new_prog)
19525 				return -ENOMEM;
19526 
19527 			delta     += cnt - 1;
19528 			env->prog  = new_prog;
19529 			insn       = new_prog->insnsi + i + delta;
19530 		}
19531 
19532 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19533 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19534 			cur_subprog++;
19535 			stack_depth = subprogs[cur_subprog].stack_depth;
19536 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19537 			stack_depth_extra = 0;
19538 		}
19539 	}
19540 
19541 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19542 
19543 	return 0;
19544 }
19545 
19546 static void free_states(struct bpf_verifier_env *env)
19547 {
19548 	struct bpf_verifier_state_list *sl, *sln;
19549 	int i;
19550 
19551 	sl = env->free_list;
19552 	while (sl) {
19553 		sln = sl->next;
19554 		free_verifier_state(&sl->state, false);
19555 		kfree(sl);
19556 		sl = sln;
19557 	}
19558 	env->free_list = NULL;
19559 
19560 	if (!env->explored_states)
19561 		return;
19562 
19563 	for (i = 0; i < state_htab_size(env); i++) {
19564 		sl = env->explored_states[i];
19565 
19566 		while (sl) {
19567 			sln = sl->next;
19568 			free_verifier_state(&sl->state, false);
19569 			kfree(sl);
19570 			sl = sln;
19571 		}
19572 		env->explored_states[i] = NULL;
19573 	}
19574 }
19575 
19576 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19577 {
19578 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19579 	struct bpf_verifier_state *state;
19580 	struct bpf_reg_state *regs;
19581 	int ret, i;
19582 
19583 	env->prev_linfo = NULL;
19584 	env->pass_cnt++;
19585 
19586 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19587 	if (!state)
19588 		return -ENOMEM;
19589 	state->curframe = 0;
19590 	state->speculative = false;
19591 	state->branches = 1;
19592 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19593 	if (!state->frame[0]) {
19594 		kfree(state);
19595 		return -ENOMEM;
19596 	}
19597 	env->cur_state = state;
19598 	init_func_state(env, state->frame[0],
19599 			BPF_MAIN_FUNC /* callsite */,
19600 			0 /* frameno */,
19601 			subprog);
19602 	state->first_insn_idx = env->subprog_info[subprog].start;
19603 	state->last_insn_idx = -1;
19604 
19605 	regs = state->frame[state->curframe]->regs;
19606 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19607 		ret = btf_prepare_func_args(env, subprog, regs);
19608 		if (ret)
19609 			goto out;
19610 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19611 			if (regs[i].type == PTR_TO_CTX)
19612 				mark_reg_known_zero(env, regs, i);
19613 			else if (regs[i].type == SCALAR_VALUE)
19614 				mark_reg_unknown(env, regs, i);
19615 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19616 				const u32 mem_size = regs[i].mem_size;
19617 
19618 				mark_reg_known_zero(env, regs, i);
19619 				regs[i].mem_size = mem_size;
19620 				regs[i].id = ++env->id_gen;
19621 			}
19622 		}
19623 	} else {
19624 		/* 1st arg to a function */
19625 		regs[BPF_REG_1].type = PTR_TO_CTX;
19626 		mark_reg_known_zero(env, regs, BPF_REG_1);
19627 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19628 		if (ret == -EFAULT)
19629 			/* unlikely verifier bug. abort.
19630 			 * ret == 0 and ret < 0 are sadly acceptable for
19631 			 * main() function due to backward compatibility.
19632 			 * Like socket filter program may be written as:
19633 			 * int bpf_prog(struct pt_regs *ctx)
19634 			 * and never dereference that ctx in the program.
19635 			 * 'struct pt_regs' is a type mismatch for socket
19636 			 * filter that should be using 'struct __sk_buff'.
19637 			 */
19638 			goto out;
19639 	}
19640 
19641 	ret = do_check(env);
19642 out:
19643 	/* check for NULL is necessary, since cur_state can be freed inside
19644 	 * do_check() under memory pressure.
19645 	 */
19646 	if (env->cur_state) {
19647 		free_verifier_state(env->cur_state, true);
19648 		env->cur_state = NULL;
19649 	}
19650 	while (!pop_stack(env, NULL, NULL, false));
19651 	if (!ret && pop_log)
19652 		bpf_vlog_reset(&env->log, 0);
19653 	free_states(env);
19654 	return ret;
19655 }
19656 
19657 /* Verify all global functions in a BPF program one by one based on their BTF.
19658  * All global functions must pass verification. Otherwise the whole program is rejected.
19659  * Consider:
19660  * int bar(int);
19661  * int foo(int f)
19662  * {
19663  *    return bar(f);
19664  * }
19665  * int bar(int b)
19666  * {
19667  *    ...
19668  * }
19669  * foo() will be verified first for R1=any_scalar_value. During verification it
19670  * will be assumed that bar() already verified successfully and call to bar()
19671  * from foo() will be checked for type match only. Later bar() will be verified
19672  * independently to check that it's safe for R1=any_scalar_value.
19673  */
19674 static int do_check_subprogs(struct bpf_verifier_env *env)
19675 {
19676 	struct bpf_prog_aux *aux = env->prog->aux;
19677 	int i, ret;
19678 
19679 	if (!aux->func_info)
19680 		return 0;
19681 
19682 	for (i = 1; i < env->subprog_cnt; i++) {
19683 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19684 			continue;
19685 		env->insn_idx = env->subprog_info[i].start;
19686 		WARN_ON_ONCE(env->insn_idx == 0);
19687 		ret = do_check_common(env, i);
19688 		if (ret) {
19689 			return ret;
19690 		} else if (env->log.level & BPF_LOG_LEVEL) {
19691 			verbose(env,
19692 				"Func#%d is safe for any args that match its prototype\n",
19693 				i);
19694 		}
19695 	}
19696 	return 0;
19697 }
19698 
19699 static int do_check_main(struct bpf_verifier_env *env)
19700 {
19701 	int ret;
19702 
19703 	env->insn_idx = 0;
19704 	ret = do_check_common(env, 0);
19705 	if (!ret)
19706 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19707 	return ret;
19708 }
19709 
19710 
19711 static void print_verification_stats(struct bpf_verifier_env *env)
19712 {
19713 	int i;
19714 
19715 	if (env->log.level & BPF_LOG_STATS) {
19716 		verbose(env, "verification time %lld usec\n",
19717 			div_u64(env->verification_time, 1000));
19718 		verbose(env, "stack depth ");
19719 		for (i = 0; i < env->subprog_cnt; i++) {
19720 			u32 depth = env->subprog_info[i].stack_depth;
19721 
19722 			verbose(env, "%d", depth);
19723 			if (i + 1 < env->subprog_cnt)
19724 				verbose(env, "+");
19725 		}
19726 		verbose(env, "\n");
19727 	}
19728 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19729 		"total_states %d peak_states %d mark_read %d\n",
19730 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19731 		env->max_states_per_insn, env->total_states,
19732 		env->peak_states, env->longest_mark_read_walk);
19733 }
19734 
19735 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19736 {
19737 	const struct btf_type *t, *func_proto;
19738 	const struct bpf_struct_ops *st_ops;
19739 	const struct btf_member *member;
19740 	struct bpf_prog *prog = env->prog;
19741 	u32 btf_id, member_idx;
19742 	const char *mname;
19743 
19744 	if (!prog->gpl_compatible) {
19745 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19746 		return -EINVAL;
19747 	}
19748 
19749 	btf_id = prog->aux->attach_btf_id;
19750 	st_ops = bpf_struct_ops_find(btf_id);
19751 	if (!st_ops) {
19752 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19753 			btf_id);
19754 		return -ENOTSUPP;
19755 	}
19756 
19757 	t = st_ops->type;
19758 	member_idx = prog->expected_attach_type;
19759 	if (member_idx >= btf_type_vlen(t)) {
19760 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19761 			member_idx, st_ops->name);
19762 		return -EINVAL;
19763 	}
19764 
19765 	member = &btf_type_member(t)[member_idx];
19766 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19767 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19768 					       NULL);
19769 	if (!func_proto) {
19770 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19771 			mname, member_idx, st_ops->name);
19772 		return -EINVAL;
19773 	}
19774 
19775 	if (st_ops->check_member) {
19776 		int err = st_ops->check_member(t, member, prog);
19777 
19778 		if (err) {
19779 			verbose(env, "attach to unsupported member %s of struct %s\n",
19780 				mname, st_ops->name);
19781 			return err;
19782 		}
19783 	}
19784 
19785 	prog->aux->attach_func_proto = func_proto;
19786 	prog->aux->attach_func_name = mname;
19787 	env->ops = st_ops->verifier_ops;
19788 
19789 	return 0;
19790 }
19791 #define SECURITY_PREFIX "security_"
19792 
19793 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19794 {
19795 	if (within_error_injection_list(addr) ||
19796 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19797 		return 0;
19798 
19799 	return -EINVAL;
19800 }
19801 
19802 /* list of non-sleepable functions that are otherwise on
19803  * ALLOW_ERROR_INJECTION list
19804  */
19805 BTF_SET_START(btf_non_sleepable_error_inject)
19806 /* Three functions below can be called from sleepable and non-sleepable context.
19807  * Assume non-sleepable from bpf safety point of view.
19808  */
19809 BTF_ID(func, __filemap_add_folio)
19810 BTF_ID(func, should_fail_alloc_page)
19811 BTF_ID(func, should_failslab)
19812 BTF_SET_END(btf_non_sleepable_error_inject)
19813 
19814 static int check_non_sleepable_error_inject(u32 btf_id)
19815 {
19816 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19817 }
19818 
19819 int bpf_check_attach_target(struct bpf_verifier_log *log,
19820 			    const struct bpf_prog *prog,
19821 			    const struct bpf_prog *tgt_prog,
19822 			    u32 btf_id,
19823 			    struct bpf_attach_target_info *tgt_info)
19824 {
19825 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19826 	const char prefix[] = "btf_trace_";
19827 	int ret = 0, subprog = -1, i;
19828 	const struct btf_type *t;
19829 	bool conservative = true;
19830 	const char *tname;
19831 	struct btf *btf;
19832 	long addr = 0;
19833 	struct module *mod = NULL;
19834 
19835 	if (!btf_id) {
19836 		bpf_log(log, "Tracing programs must provide btf_id\n");
19837 		return -EINVAL;
19838 	}
19839 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19840 	if (!btf) {
19841 		bpf_log(log,
19842 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19843 		return -EINVAL;
19844 	}
19845 	t = btf_type_by_id(btf, btf_id);
19846 	if (!t) {
19847 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19848 		return -EINVAL;
19849 	}
19850 	tname = btf_name_by_offset(btf, t->name_off);
19851 	if (!tname) {
19852 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19853 		return -EINVAL;
19854 	}
19855 	if (tgt_prog) {
19856 		struct bpf_prog_aux *aux = tgt_prog->aux;
19857 
19858 		if (bpf_prog_is_dev_bound(prog->aux) &&
19859 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19860 			bpf_log(log, "Target program bound device mismatch");
19861 			return -EINVAL;
19862 		}
19863 
19864 		for (i = 0; i < aux->func_info_cnt; i++)
19865 			if (aux->func_info[i].type_id == btf_id) {
19866 				subprog = i;
19867 				break;
19868 			}
19869 		if (subprog == -1) {
19870 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19871 			return -EINVAL;
19872 		}
19873 		conservative = aux->func_info_aux[subprog].unreliable;
19874 		if (prog_extension) {
19875 			if (conservative) {
19876 				bpf_log(log,
19877 					"Cannot replace static functions\n");
19878 				return -EINVAL;
19879 			}
19880 			if (!prog->jit_requested) {
19881 				bpf_log(log,
19882 					"Extension programs should be JITed\n");
19883 				return -EINVAL;
19884 			}
19885 		}
19886 		if (!tgt_prog->jited) {
19887 			bpf_log(log, "Can attach to only JITed progs\n");
19888 			return -EINVAL;
19889 		}
19890 		if (tgt_prog->type == prog->type) {
19891 			/* Cannot fentry/fexit another fentry/fexit program.
19892 			 * Cannot attach program extension to another extension.
19893 			 * It's ok to attach fentry/fexit to extension program.
19894 			 */
19895 			bpf_log(log, "Cannot recursively attach\n");
19896 			return -EINVAL;
19897 		}
19898 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19899 		    prog_extension &&
19900 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19901 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19902 			/* Program extensions can extend all program types
19903 			 * except fentry/fexit. The reason is the following.
19904 			 * The fentry/fexit programs are used for performance
19905 			 * analysis, stats and can be attached to any program
19906 			 * type except themselves. When extension program is
19907 			 * replacing XDP function it is necessary to allow
19908 			 * performance analysis of all functions. Both original
19909 			 * XDP program and its program extension. Hence
19910 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19911 			 * allowed. If extending of fentry/fexit was allowed it
19912 			 * would be possible to create long call chain
19913 			 * fentry->extension->fentry->extension beyond
19914 			 * reasonable stack size. Hence extending fentry is not
19915 			 * allowed.
19916 			 */
19917 			bpf_log(log, "Cannot extend fentry/fexit\n");
19918 			return -EINVAL;
19919 		}
19920 	} else {
19921 		if (prog_extension) {
19922 			bpf_log(log, "Cannot replace kernel functions\n");
19923 			return -EINVAL;
19924 		}
19925 	}
19926 
19927 	switch (prog->expected_attach_type) {
19928 	case BPF_TRACE_RAW_TP:
19929 		if (tgt_prog) {
19930 			bpf_log(log,
19931 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19932 			return -EINVAL;
19933 		}
19934 		if (!btf_type_is_typedef(t)) {
19935 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19936 				btf_id);
19937 			return -EINVAL;
19938 		}
19939 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19940 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19941 				btf_id, tname);
19942 			return -EINVAL;
19943 		}
19944 		tname += sizeof(prefix) - 1;
19945 		t = btf_type_by_id(btf, t->type);
19946 		if (!btf_type_is_ptr(t))
19947 			/* should never happen in valid vmlinux build */
19948 			return -EINVAL;
19949 		t = btf_type_by_id(btf, t->type);
19950 		if (!btf_type_is_func_proto(t))
19951 			/* should never happen in valid vmlinux build */
19952 			return -EINVAL;
19953 
19954 		break;
19955 	case BPF_TRACE_ITER:
19956 		if (!btf_type_is_func(t)) {
19957 			bpf_log(log, "attach_btf_id %u is not a function\n",
19958 				btf_id);
19959 			return -EINVAL;
19960 		}
19961 		t = btf_type_by_id(btf, t->type);
19962 		if (!btf_type_is_func_proto(t))
19963 			return -EINVAL;
19964 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19965 		if (ret)
19966 			return ret;
19967 		break;
19968 	default:
19969 		if (!prog_extension)
19970 			return -EINVAL;
19971 		fallthrough;
19972 	case BPF_MODIFY_RETURN:
19973 	case BPF_LSM_MAC:
19974 	case BPF_LSM_CGROUP:
19975 	case BPF_TRACE_FENTRY:
19976 	case BPF_TRACE_FEXIT:
19977 		if (!btf_type_is_func(t)) {
19978 			bpf_log(log, "attach_btf_id %u is not a function\n",
19979 				btf_id);
19980 			return -EINVAL;
19981 		}
19982 		if (prog_extension &&
19983 		    btf_check_type_match(log, prog, btf, t))
19984 			return -EINVAL;
19985 		t = btf_type_by_id(btf, t->type);
19986 		if (!btf_type_is_func_proto(t))
19987 			return -EINVAL;
19988 
19989 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19990 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19991 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19992 			return -EINVAL;
19993 
19994 		if (tgt_prog && conservative)
19995 			t = NULL;
19996 
19997 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19998 		if (ret < 0)
19999 			return ret;
20000 
20001 		if (tgt_prog) {
20002 			if (subprog == 0)
20003 				addr = (long) tgt_prog->bpf_func;
20004 			else
20005 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20006 		} else {
20007 			if (btf_is_module(btf)) {
20008 				mod = btf_try_get_module(btf);
20009 				if (mod)
20010 					addr = find_kallsyms_symbol_value(mod, tname);
20011 				else
20012 					addr = 0;
20013 			} else {
20014 				addr = kallsyms_lookup_name(tname);
20015 			}
20016 			if (!addr) {
20017 				module_put(mod);
20018 				bpf_log(log,
20019 					"The address of function %s cannot be found\n",
20020 					tname);
20021 				return -ENOENT;
20022 			}
20023 		}
20024 
20025 		if (prog->aux->sleepable) {
20026 			ret = -EINVAL;
20027 			switch (prog->type) {
20028 			case BPF_PROG_TYPE_TRACING:
20029 
20030 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20031 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20032 				 */
20033 				if (!check_non_sleepable_error_inject(btf_id) &&
20034 				    within_error_injection_list(addr))
20035 					ret = 0;
20036 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20037 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20038 				 */
20039 				else {
20040 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20041 										prog);
20042 
20043 					if (flags && (*flags & KF_SLEEPABLE))
20044 						ret = 0;
20045 				}
20046 				break;
20047 			case BPF_PROG_TYPE_LSM:
20048 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20049 				 * Only some of them are sleepable.
20050 				 */
20051 				if (bpf_lsm_is_sleepable_hook(btf_id))
20052 					ret = 0;
20053 				break;
20054 			default:
20055 				break;
20056 			}
20057 			if (ret) {
20058 				module_put(mod);
20059 				bpf_log(log, "%s is not sleepable\n", tname);
20060 				return ret;
20061 			}
20062 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20063 			if (tgt_prog) {
20064 				module_put(mod);
20065 				bpf_log(log, "can't modify return codes of BPF programs\n");
20066 				return -EINVAL;
20067 			}
20068 			ret = -EINVAL;
20069 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20070 			    !check_attach_modify_return(addr, tname))
20071 				ret = 0;
20072 			if (ret) {
20073 				module_put(mod);
20074 				bpf_log(log, "%s() is not modifiable\n", tname);
20075 				return ret;
20076 			}
20077 		}
20078 
20079 		break;
20080 	}
20081 	tgt_info->tgt_addr = addr;
20082 	tgt_info->tgt_name = tname;
20083 	tgt_info->tgt_type = t;
20084 	tgt_info->tgt_mod = mod;
20085 	return 0;
20086 }
20087 
20088 BTF_SET_START(btf_id_deny)
20089 BTF_ID_UNUSED
20090 #ifdef CONFIG_SMP
20091 BTF_ID(func, migrate_disable)
20092 BTF_ID(func, migrate_enable)
20093 #endif
20094 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20095 BTF_ID(func, rcu_read_unlock_strict)
20096 #endif
20097 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20098 BTF_ID(func, preempt_count_add)
20099 BTF_ID(func, preempt_count_sub)
20100 #endif
20101 #ifdef CONFIG_PREEMPT_RCU
20102 BTF_ID(func, __rcu_read_lock)
20103 BTF_ID(func, __rcu_read_unlock)
20104 #endif
20105 BTF_SET_END(btf_id_deny)
20106 
20107 static bool can_be_sleepable(struct bpf_prog *prog)
20108 {
20109 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20110 		switch (prog->expected_attach_type) {
20111 		case BPF_TRACE_FENTRY:
20112 		case BPF_TRACE_FEXIT:
20113 		case BPF_MODIFY_RETURN:
20114 		case BPF_TRACE_ITER:
20115 			return true;
20116 		default:
20117 			return false;
20118 		}
20119 	}
20120 	return prog->type == BPF_PROG_TYPE_LSM ||
20121 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20122 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20123 }
20124 
20125 static int check_attach_btf_id(struct bpf_verifier_env *env)
20126 {
20127 	struct bpf_prog *prog = env->prog;
20128 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20129 	struct bpf_attach_target_info tgt_info = {};
20130 	u32 btf_id = prog->aux->attach_btf_id;
20131 	struct bpf_trampoline *tr;
20132 	int ret;
20133 	u64 key;
20134 
20135 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20136 		if (prog->aux->sleepable)
20137 			/* attach_btf_id checked to be zero already */
20138 			return 0;
20139 		verbose(env, "Syscall programs can only be sleepable\n");
20140 		return -EINVAL;
20141 	}
20142 
20143 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20144 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20145 		return -EINVAL;
20146 	}
20147 
20148 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20149 		return check_struct_ops_btf_id(env);
20150 
20151 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20152 	    prog->type != BPF_PROG_TYPE_LSM &&
20153 	    prog->type != BPF_PROG_TYPE_EXT)
20154 		return 0;
20155 
20156 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20157 	if (ret)
20158 		return ret;
20159 
20160 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20161 		/* to make freplace equivalent to their targets, they need to
20162 		 * inherit env->ops and expected_attach_type for the rest of the
20163 		 * verification
20164 		 */
20165 		env->ops = bpf_verifier_ops[tgt_prog->type];
20166 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20167 	}
20168 
20169 	/* store info about the attachment target that will be used later */
20170 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20171 	prog->aux->attach_func_name = tgt_info.tgt_name;
20172 	prog->aux->mod = tgt_info.tgt_mod;
20173 
20174 	if (tgt_prog) {
20175 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20176 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20177 	}
20178 
20179 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20180 		prog->aux->attach_btf_trace = true;
20181 		return 0;
20182 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20183 		if (!bpf_iter_prog_supported(prog))
20184 			return -EINVAL;
20185 		return 0;
20186 	}
20187 
20188 	if (prog->type == BPF_PROG_TYPE_LSM) {
20189 		ret = bpf_lsm_verify_prog(&env->log, prog);
20190 		if (ret < 0)
20191 			return ret;
20192 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20193 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20194 		return -EINVAL;
20195 	}
20196 
20197 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20198 	tr = bpf_trampoline_get(key, &tgt_info);
20199 	if (!tr)
20200 		return -ENOMEM;
20201 
20202 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20203 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20204 
20205 	prog->aux->dst_trampoline = tr;
20206 	return 0;
20207 }
20208 
20209 struct btf *bpf_get_btf_vmlinux(void)
20210 {
20211 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20212 		mutex_lock(&bpf_verifier_lock);
20213 		if (!btf_vmlinux)
20214 			btf_vmlinux = btf_parse_vmlinux();
20215 		mutex_unlock(&bpf_verifier_lock);
20216 	}
20217 	return btf_vmlinux;
20218 }
20219 
20220 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20221 {
20222 	u64 start_time = ktime_get_ns();
20223 	struct bpf_verifier_env *env;
20224 	int i, len, ret = -EINVAL, err;
20225 	u32 log_true_size;
20226 	bool is_priv;
20227 
20228 	/* no program is valid */
20229 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20230 		return -EINVAL;
20231 
20232 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20233 	 * allocate/free it every time bpf_check() is called
20234 	 */
20235 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20236 	if (!env)
20237 		return -ENOMEM;
20238 
20239 	env->bt.env = env;
20240 
20241 	len = (*prog)->len;
20242 	env->insn_aux_data =
20243 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20244 	ret = -ENOMEM;
20245 	if (!env->insn_aux_data)
20246 		goto err_free_env;
20247 	for (i = 0; i < len; i++)
20248 		env->insn_aux_data[i].orig_idx = i;
20249 	env->prog = *prog;
20250 	env->ops = bpf_verifier_ops[env->prog->type];
20251 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20252 	is_priv = bpf_capable();
20253 
20254 	bpf_get_btf_vmlinux();
20255 
20256 	/* grab the mutex to protect few globals used by verifier */
20257 	if (!is_priv)
20258 		mutex_lock(&bpf_verifier_lock);
20259 
20260 	/* user could have requested verbose verifier output
20261 	 * and supplied buffer to store the verification trace
20262 	 */
20263 	ret = bpf_vlog_init(&env->log, attr->log_level,
20264 			    (char __user *) (unsigned long) attr->log_buf,
20265 			    attr->log_size);
20266 	if (ret)
20267 		goto err_unlock;
20268 
20269 	mark_verifier_state_clean(env);
20270 
20271 	if (IS_ERR(btf_vmlinux)) {
20272 		/* Either gcc or pahole or kernel are broken. */
20273 		verbose(env, "in-kernel BTF is malformed\n");
20274 		ret = PTR_ERR(btf_vmlinux);
20275 		goto skip_full_check;
20276 	}
20277 
20278 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20279 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20280 		env->strict_alignment = true;
20281 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20282 		env->strict_alignment = false;
20283 
20284 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20285 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20286 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20287 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20288 	env->bpf_capable = bpf_capable();
20289 
20290 	if (is_priv)
20291 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20292 
20293 	env->explored_states = kvcalloc(state_htab_size(env),
20294 				       sizeof(struct bpf_verifier_state_list *),
20295 				       GFP_USER);
20296 	ret = -ENOMEM;
20297 	if (!env->explored_states)
20298 		goto skip_full_check;
20299 
20300 	ret = add_subprog_and_kfunc(env);
20301 	if (ret < 0)
20302 		goto skip_full_check;
20303 
20304 	ret = check_subprogs(env);
20305 	if (ret < 0)
20306 		goto skip_full_check;
20307 
20308 	ret = check_btf_info(env, attr, uattr);
20309 	if (ret < 0)
20310 		goto skip_full_check;
20311 
20312 	ret = check_attach_btf_id(env);
20313 	if (ret)
20314 		goto skip_full_check;
20315 
20316 	ret = resolve_pseudo_ldimm64(env);
20317 	if (ret < 0)
20318 		goto skip_full_check;
20319 
20320 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20321 		ret = bpf_prog_offload_verifier_prep(env->prog);
20322 		if (ret)
20323 			goto skip_full_check;
20324 	}
20325 
20326 	ret = check_cfg(env);
20327 	if (ret < 0)
20328 		goto skip_full_check;
20329 
20330 	ret = do_check_subprogs(env);
20331 	ret = ret ?: do_check_main(env);
20332 
20333 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20334 		ret = bpf_prog_offload_finalize(env);
20335 
20336 skip_full_check:
20337 	kvfree(env->explored_states);
20338 
20339 	if (ret == 0)
20340 		ret = check_max_stack_depth(env);
20341 
20342 	/* instruction rewrites happen after this point */
20343 	if (ret == 0)
20344 		ret = optimize_bpf_loop(env);
20345 
20346 	if (is_priv) {
20347 		if (ret == 0)
20348 			opt_hard_wire_dead_code_branches(env);
20349 		if (ret == 0)
20350 			ret = opt_remove_dead_code(env);
20351 		if (ret == 0)
20352 			ret = opt_remove_nops(env);
20353 	} else {
20354 		if (ret == 0)
20355 			sanitize_dead_code(env);
20356 	}
20357 
20358 	if (ret == 0)
20359 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20360 		ret = convert_ctx_accesses(env);
20361 
20362 	if (ret == 0)
20363 		ret = do_misc_fixups(env);
20364 
20365 	/* do 32-bit optimization after insn patching has done so those patched
20366 	 * insns could be handled correctly.
20367 	 */
20368 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20369 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20370 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20371 								     : false;
20372 	}
20373 
20374 	if (ret == 0)
20375 		ret = fixup_call_args(env);
20376 
20377 	env->verification_time = ktime_get_ns() - start_time;
20378 	print_verification_stats(env);
20379 	env->prog->aux->verified_insns = env->insn_processed;
20380 
20381 	/* preserve original error even if log finalization is successful */
20382 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20383 	if (err)
20384 		ret = err;
20385 
20386 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20387 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20388 				  &log_true_size, sizeof(log_true_size))) {
20389 		ret = -EFAULT;
20390 		goto err_release_maps;
20391 	}
20392 
20393 	if (ret)
20394 		goto err_release_maps;
20395 
20396 	if (env->used_map_cnt) {
20397 		/* if program passed verifier, update used_maps in bpf_prog_info */
20398 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20399 							  sizeof(env->used_maps[0]),
20400 							  GFP_KERNEL);
20401 
20402 		if (!env->prog->aux->used_maps) {
20403 			ret = -ENOMEM;
20404 			goto err_release_maps;
20405 		}
20406 
20407 		memcpy(env->prog->aux->used_maps, env->used_maps,
20408 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20409 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20410 	}
20411 	if (env->used_btf_cnt) {
20412 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20413 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20414 							  sizeof(env->used_btfs[0]),
20415 							  GFP_KERNEL);
20416 		if (!env->prog->aux->used_btfs) {
20417 			ret = -ENOMEM;
20418 			goto err_release_maps;
20419 		}
20420 
20421 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20422 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20423 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20424 	}
20425 	if (env->used_map_cnt || env->used_btf_cnt) {
20426 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20427 		 * bpf_ld_imm64 instructions
20428 		 */
20429 		convert_pseudo_ld_imm64(env);
20430 	}
20431 
20432 	adjust_btf_func(env);
20433 
20434 err_release_maps:
20435 	if (!env->prog->aux->used_maps)
20436 		/* if we didn't copy map pointers into bpf_prog_info, release
20437 		 * them now. Otherwise free_used_maps() will release them.
20438 		 */
20439 		release_maps(env);
20440 	if (!env->prog->aux->used_btfs)
20441 		release_btfs(env);
20442 
20443 	/* extension progs temporarily inherit the attach_type of their targets
20444 	   for verification purposes, so set it back to zero before returning
20445 	 */
20446 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20447 		env->prog->expected_attach_type = 0;
20448 
20449 	*prog = env->prog;
20450 err_unlock:
20451 	if (!is_priv)
20452 		mutex_unlock(&bpf_verifier_lock);
20453 	vfree(env->insn_aux_data);
20454 err_free_env:
20455 	kfree(env);
20456 	return ret;
20457 }
20458