xref: /openbmc/linux/kernel/bpf/verifier.c (revision d4c52c6a)
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->s32_min_value = reg->smin_value = s64_min;
6147 		reg->s32_max_value = reg->smax_value = s64_max;
6148 		reg->u32_min_value = reg->umin_value = s64_min;
6149 		reg->u32_max_value = reg->umax_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, enum bpf_access_type access_type,
7202 				   bool zero_size_allowed,
7203 				   struct bpf_call_arg_meta *meta)
7204 {
7205 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7206 	u32 *max_access;
7207 
7208 	switch (base_type(reg->type)) {
7209 	case PTR_TO_PACKET:
7210 	case PTR_TO_PACKET_META:
7211 		return check_packet_access(env, regno, reg->off, access_size,
7212 					   zero_size_allowed);
7213 	case PTR_TO_MAP_KEY:
7214 		if (access_type == BPF_WRITE) {
7215 			verbose(env, "R%d cannot write into %s\n", regno,
7216 				reg_type_str(env, reg->type));
7217 			return -EACCES;
7218 		}
7219 		return check_mem_region_access(env, regno, reg->off, access_size,
7220 					       reg->map_ptr->key_size, false);
7221 	case PTR_TO_MAP_VALUE:
7222 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7223 			return -EACCES;
7224 		return check_map_access(env, regno, reg->off, access_size,
7225 					zero_size_allowed, ACCESS_HELPER);
7226 	case PTR_TO_MEM:
7227 		if (type_is_rdonly_mem(reg->type)) {
7228 			if (access_type == BPF_WRITE) {
7229 				verbose(env, "R%d cannot write into %s\n", regno,
7230 					reg_type_str(env, reg->type));
7231 				return -EACCES;
7232 			}
7233 		}
7234 		return check_mem_region_access(env, regno, reg->off,
7235 					       access_size, reg->mem_size,
7236 					       zero_size_allowed);
7237 	case PTR_TO_BUF:
7238 		if (type_is_rdonly_mem(reg->type)) {
7239 			if (access_type == BPF_WRITE) {
7240 				verbose(env, "R%d cannot write into %s\n", regno,
7241 					reg_type_str(env, reg->type));
7242 				return -EACCES;
7243 			}
7244 
7245 			max_access = &env->prog->aux->max_rdonly_access;
7246 		} else {
7247 			max_access = &env->prog->aux->max_rdwr_access;
7248 		}
7249 		return check_buffer_access(env, reg, regno, reg->off,
7250 					   access_size, zero_size_allowed,
7251 					   max_access);
7252 	case PTR_TO_STACK:
7253 		return check_stack_range_initialized(
7254 				env,
7255 				regno, reg->off, access_size,
7256 				zero_size_allowed, ACCESS_HELPER, meta);
7257 	case PTR_TO_BTF_ID:
7258 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7259 					       access_size, BPF_READ, -1);
7260 	case PTR_TO_CTX:
7261 		/* in case the function doesn't know how to access the context,
7262 		 * (because we are in a program of type SYSCALL for example), we
7263 		 * can not statically check its size.
7264 		 * Dynamically check it now.
7265 		 */
7266 		if (!env->ops->convert_ctx_access) {
7267 			int offset = access_size - 1;
7268 
7269 			/* Allow zero-byte read from PTR_TO_CTX */
7270 			if (access_size == 0)
7271 				return zero_size_allowed ? 0 : -EACCES;
7272 
7273 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7274 						access_type, -1, false, false);
7275 		}
7276 
7277 		fallthrough;
7278 	default: /* scalar_value or invalid ptr */
7279 		/* Allow zero-byte read from NULL, regardless of pointer type */
7280 		if (zero_size_allowed && access_size == 0 &&
7281 		    register_is_null(reg))
7282 			return 0;
7283 
7284 		verbose(env, "R%d type=%s ", regno,
7285 			reg_type_str(env, reg->type));
7286 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7287 		return -EACCES;
7288 	}
7289 }
7290 
7291 static int check_mem_size_reg(struct bpf_verifier_env *env,
7292 			      struct bpf_reg_state *reg, u32 regno,
7293 			      enum bpf_access_type access_type,
7294 			      bool zero_size_allowed,
7295 			      struct bpf_call_arg_meta *meta)
7296 {
7297 	int err;
7298 
7299 	/* This is used to refine r0 return value bounds for helpers
7300 	 * that enforce this value as an upper bound on return values.
7301 	 * See do_refine_retval_range() for helpers that can refine
7302 	 * the return value. C type of helper is u32 so we pull register
7303 	 * bound from umax_value however, if negative verifier errors
7304 	 * out. Only upper bounds can be learned because retval is an
7305 	 * int type and negative retvals are allowed.
7306 	 */
7307 	meta->msize_max_value = reg->umax_value;
7308 
7309 	/* The register is SCALAR_VALUE; the access check happens using
7310 	 * its boundaries. For unprivileged variable accesses, disable
7311 	 * raw mode so that the program is required to initialize all
7312 	 * the memory that the helper could just partially fill up.
7313 	 */
7314 	if (!tnum_is_const(reg->var_off))
7315 		meta = NULL;
7316 
7317 	if (reg->smin_value < 0) {
7318 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7319 			regno);
7320 		return -EACCES;
7321 	}
7322 
7323 	if (reg->umin_value == 0 && !zero_size_allowed) {
7324 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7325 			regno, reg->umin_value, reg->umax_value);
7326 		return -EACCES;
7327 	}
7328 
7329 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7330 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7331 			regno);
7332 		return -EACCES;
7333 	}
7334 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7335 				      access_type, zero_size_allowed, meta);
7336 	if (!err)
7337 		err = mark_chain_precision(env, regno);
7338 	return err;
7339 }
7340 
7341 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7342 		   u32 regno, u32 mem_size)
7343 {
7344 	bool may_be_null = type_may_be_null(reg->type);
7345 	struct bpf_reg_state saved_reg;
7346 	int err;
7347 
7348 	if (register_is_null(reg))
7349 		return 0;
7350 
7351 	/* Assuming that the register contains a value check if the memory
7352 	 * access is safe. Temporarily save and restore the register's state as
7353 	 * the conversion shouldn't be visible to a caller.
7354 	 */
7355 	if (may_be_null) {
7356 		saved_reg = *reg;
7357 		mark_ptr_not_null_reg(reg);
7358 	}
7359 
7360 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7361 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7362 
7363 	if (may_be_null)
7364 		*reg = saved_reg;
7365 
7366 	return err;
7367 }
7368 
7369 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7370 				    u32 regno)
7371 {
7372 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7373 	bool may_be_null = type_may_be_null(mem_reg->type);
7374 	struct bpf_reg_state saved_reg;
7375 	struct bpf_call_arg_meta meta;
7376 	int err;
7377 
7378 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7379 
7380 	memset(&meta, 0, sizeof(meta));
7381 
7382 	if (may_be_null) {
7383 		saved_reg = *mem_reg;
7384 		mark_ptr_not_null_reg(mem_reg);
7385 	}
7386 
7387 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7388 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7389 
7390 	if (may_be_null)
7391 		*mem_reg = saved_reg;
7392 
7393 	return err;
7394 }
7395 
7396 /* Implementation details:
7397  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7398  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7399  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7400  * Two separate bpf_obj_new will also have different reg->id.
7401  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7402  * clears reg->id after value_or_null->value transition, since the verifier only
7403  * cares about the range of access to valid map value pointer and doesn't care
7404  * about actual address of the map element.
7405  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7406  * reg->id > 0 after value_or_null->value transition. By doing so
7407  * two bpf_map_lookups will be considered two different pointers that
7408  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7409  * returned from bpf_obj_new.
7410  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7411  * dead-locks.
7412  * Since only one bpf_spin_lock is allowed the checks are simpler than
7413  * reg_is_refcounted() logic. The verifier needs to remember only
7414  * one spin_lock instead of array of acquired_refs.
7415  * cur_state->active_lock remembers which map value element or allocated
7416  * object got locked and clears it after bpf_spin_unlock.
7417  */
7418 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7419 			     bool is_lock)
7420 {
7421 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7422 	struct bpf_verifier_state *cur = env->cur_state;
7423 	bool is_const = tnum_is_const(reg->var_off);
7424 	u64 val = reg->var_off.value;
7425 	struct bpf_map *map = NULL;
7426 	struct btf *btf = NULL;
7427 	struct btf_record *rec;
7428 
7429 	if (!is_const) {
7430 		verbose(env,
7431 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7432 			regno);
7433 		return -EINVAL;
7434 	}
7435 	if (reg->type == PTR_TO_MAP_VALUE) {
7436 		map = reg->map_ptr;
7437 		if (!map->btf) {
7438 			verbose(env,
7439 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7440 				map->name);
7441 			return -EINVAL;
7442 		}
7443 	} else {
7444 		btf = reg->btf;
7445 	}
7446 
7447 	rec = reg_btf_record(reg);
7448 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7449 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7450 			map ? map->name : "kptr");
7451 		return -EINVAL;
7452 	}
7453 	if (rec->spin_lock_off != val + reg->off) {
7454 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7455 			val + reg->off, rec->spin_lock_off);
7456 		return -EINVAL;
7457 	}
7458 	if (is_lock) {
7459 		if (cur->active_lock.ptr) {
7460 			verbose(env,
7461 				"Locking two bpf_spin_locks are not allowed\n");
7462 			return -EINVAL;
7463 		}
7464 		if (map)
7465 			cur->active_lock.ptr = map;
7466 		else
7467 			cur->active_lock.ptr = btf;
7468 		cur->active_lock.id = reg->id;
7469 	} else {
7470 		void *ptr;
7471 
7472 		if (map)
7473 			ptr = map;
7474 		else
7475 			ptr = btf;
7476 
7477 		if (!cur->active_lock.ptr) {
7478 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7479 			return -EINVAL;
7480 		}
7481 		if (cur->active_lock.ptr != ptr ||
7482 		    cur->active_lock.id != reg->id) {
7483 			verbose(env, "bpf_spin_unlock of different lock\n");
7484 			return -EINVAL;
7485 		}
7486 
7487 		invalidate_non_owning_refs(env);
7488 
7489 		cur->active_lock.ptr = NULL;
7490 		cur->active_lock.id = 0;
7491 	}
7492 	return 0;
7493 }
7494 
7495 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7496 			      struct bpf_call_arg_meta *meta)
7497 {
7498 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7499 	bool is_const = tnum_is_const(reg->var_off);
7500 	struct bpf_map *map = reg->map_ptr;
7501 	u64 val = reg->var_off.value;
7502 
7503 	if (!is_const) {
7504 		verbose(env,
7505 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7506 			regno);
7507 		return -EINVAL;
7508 	}
7509 	if (!map->btf) {
7510 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7511 			map->name);
7512 		return -EINVAL;
7513 	}
7514 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7515 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7516 		return -EINVAL;
7517 	}
7518 	if (map->record->timer_off != val + reg->off) {
7519 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7520 			val + reg->off, map->record->timer_off);
7521 		return -EINVAL;
7522 	}
7523 	if (meta->map_ptr) {
7524 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7525 		return -EFAULT;
7526 	}
7527 	meta->map_uid = reg->map_uid;
7528 	meta->map_ptr = map;
7529 	return 0;
7530 }
7531 
7532 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7533 			     struct bpf_call_arg_meta *meta)
7534 {
7535 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7536 	struct bpf_map *map_ptr = reg->map_ptr;
7537 	struct btf_field *kptr_field;
7538 	u32 kptr_off;
7539 
7540 	if (!tnum_is_const(reg->var_off)) {
7541 		verbose(env,
7542 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7543 			regno);
7544 		return -EINVAL;
7545 	}
7546 	if (!map_ptr->btf) {
7547 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7548 			map_ptr->name);
7549 		return -EINVAL;
7550 	}
7551 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7552 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7553 		return -EINVAL;
7554 	}
7555 
7556 	meta->map_ptr = map_ptr;
7557 	kptr_off = reg->off + reg->var_off.value;
7558 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7559 	if (!kptr_field) {
7560 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7561 		return -EACCES;
7562 	}
7563 	if (kptr_field->type != BPF_KPTR_REF) {
7564 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7565 		return -EACCES;
7566 	}
7567 	meta->kptr_field = kptr_field;
7568 	return 0;
7569 }
7570 
7571 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7572  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7573  *
7574  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7575  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7576  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7577  *
7578  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7579  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7580  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7581  * mutate the view of the dynptr and also possibly destroy it. In the latter
7582  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7583  * memory that dynptr points to.
7584  *
7585  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7586  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7587  * readonly dynptr view yet, hence only the first case is tracked and checked.
7588  *
7589  * This is consistent with how C applies the const modifier to a struct object,
7590  * where the pointer itself inside bpf_dynptr becomes const but not what it
7591  * points to.
7592  *
7593  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7594  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7595  */
7596 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7597 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7598 {
7599 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7600 	int err;
7601 
7602 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7603 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7604 	 */
7605 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7606 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7607 		return -EFAULT;
7608 	}
7609 
7610 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7611 	 *		 constructing a mutable bpf_dynptr object.
7612 	 *
7613 	 *		 Currently, this is only possible with PTR_TO_STACK
7614 	 *		 pointing to a region of at least 16 bytes which doesn't
7615 	 *		 contain an existing bpf_dynptr.
7616 	 *
7617 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7618 	 *		 mutated or destroyed. However, the memory it points to
7619 	 *		 may be mutated.
7620 	 *
7621 	 *  None       - Points to a initialized dynptr that can be mutated and
7622 	 *		 destroyed, including mutation of the memory it points
7623 	 *		 to.
7624 	 */
7625 	if (arg_type & MEM_UNINIT) {
7626 		int i;
7627 
7628 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7629 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7630 			return -EINVAL;
7631 		}
7632 
7633 		/* we write BPF_DW bits (8 bytes) at a time */
7634 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7635 			err = check_mem_access(env, insn_idx, regno,
7636 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7637 			if (err)
7638 				return err;
7639 		}
7640 
7641 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7642 	} else /* MEM_RDONLY and None case from above */ {
7643 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7644 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7645 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7646 			return -EINVAL;
7647 		}
7648 
7649 		if (!is_dynptr_reg_valid_init(env, reg)) {
7650 			verbose(env,
7651 				"Expected an initialized dynptr as arg #%d\n",
7652 				regno);
7653 			return -EINVAL;
7654 		}
7655 
7656 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7657 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7658 			verbose(env,
7659 				"Expected a dynptr of type %s as arg #%d\n",
7660 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7661 			return -EINVAL;
7662 		}
7663 
7664 		err = mark_dynptr_read(env, reg);
7665 	}
7666 	return err;
7667 }
7668 
7669 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7670 {
7671 	struct bpf_func_state *state = func(env, reg);
7672 
7673 	return state->stack[spi].spilled_ptr.ref_obj_id;
7674 }
7675 
7676 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7677 {
7678 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7679 }
7680 
7681 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7682 {
7683 	return meta->kfunc_flags & KF_ITER_NEW;
7684 }
7685 
7686 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7687 {
7688 	return meta->kfunc_flags & KF_ITER_NEXT;
7689 }
7690 
7691 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7692 {
7693 	return meta->kfunc_flags & KF_ITER_DESTROY;
7694 }
7695 
7696 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7697 {
7698 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7699 	 * kfunc is iter state pointer
7700 	 */
7701 	return arg == 0 && is_iter_kfunc(meta);
7702 }
7703 
7704 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7705 			    struct bpf_kfunc_call_arg_meta *meta)
7706 {
7707 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7708 	const struct btf_type *t;
7709 	const struct btf_param *arg;
7710 	int spi, err, i, nr_slots;
7711 	u32 btf_id;
7712 
7713 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7714 	arg = &btf_params(meta->func_proto)[0];
7715 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7716 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7717 	nr_slots = t->size / BPF_REG_SIZE;
7718 
7719 	if (is_iter_new_kfunc(meta)) {
7720 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7721 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7722 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7723 				iter_type_str(meta->btf, btf_id), regno);
7724 			return -EINVAL;
7725 		}
7726 
7727 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7728 			err = check_mem_access(env, insn_idx, regno,
7729 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7730 			if (err)
7731 				return err;
7732 		}
7733 
7734 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7735 		if (err)
7736 			return err;
7737 	} else {
7738 		/* iter_next() or iter_destroy() expect initialized iter state*/
7739 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7740 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7741 				iter_type_str(meta->btf, btf_id), regno);
7742 			return -EINVAL;
7743 		}
7744 
7745 		spi = iter_get_spi(env, reg, nr_slots);
7746 		if (spi < 0)
7747 			return spi;
7748 
7749 		err = mark_iter_read(env, reg, spi, nr_slots);
7750 		if (err)
7751 			return err;
7752 
7753 		/* remember meta->iter info for process_iter_next_call() */
7754 		meta->iter.spi = spi;
7755 		meta->iter.frameno = reg->frameno;
7756 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7757 
7758 		if (is_iter_destroy_kfunc(meta)) {
7759 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7760 			if (err)
7761 				return err;
7762 		}
7763 	}
7764 
7765 	return 0;
7766 }
7767 
7768 /* Look for a previous loop entry at insn_idx: nearest parent state
7769  * stopped at insn_idx with callsites matching those in cur->frame.
7770  */
7771 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7772 						  struct bpf_verifier_state *cur,
7773 						  int insn_idx)
7774 {
7775 	struct bpf_verifier_state_list *sl;
7776 	struct bpf_verifier_state *st;
7777 
7778 	/* Explored states are pushed in stack order, most recent states come first */
7779 	sl = *explored_state(env, insn_idx);
7780 	for (; sl; sl = sl->next) {
7781 		/* If st->branches != 0 state is a part of current DFS verification path,
7782 		 * hence cur & st for a loop.
7783 		 */
7784 		st = &sl->state;
7785 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7786 		    st->dfs_depth < cur->dfs_depth)
7787 			return st;
7788 	}
7789 
7790 	return NULL;
7791 }
7792 
7793 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7794 static bool regs_exact(const struct bpf_reg_state *rold,
7795 		       const struct bpf_reg_state *rcur,
7796 		       struct bpf_idmap *idmap);
7797 
7798 static void maybe_widen_reg(struct bpf_verifier_env *env,
7799 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7800 			    struct bpf_idmap *idmap)
7801 {
7802 	if (rold->type != SCALAR_VALUE)
7803 		return;
7804 	if (rold->type != rcur->type)
7805 		return;
7806 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7807 		return;
7808 	__mark_reg_unknown(env, rcur);
7809 }
7810 
7811 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7812 				   struct bpf_verifier_state *old,
7813 				   struct bpf_verifier_state *cur)
7814 {
7815 	struct bpf_func_state *fold, *fcur;
7816 	int i, fr;
7817 
7818 	reset_idmap_scratch(env);
7819 	for (fr = old->curframe; fr >= 0; fr--) {
7820 		fold = old->frame[fr];
7821 		fcur = cur->frame[fr];
7822 
7823 		for (i = 0; i < MAX_BPF_REG; i++)
7824 			maybe_widen_reg(env,
7825 					&fold->regs[i],
7826 					&fcur->regs[i],
7827 					&env->idmap_scratch);
7828 
7829 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7830 			if (!is_spilled_reg(&fold->stack[i]) ||
7831 			    !is_spilled_reg(&fcur->stack[i]))
7832 				continue;
7833 
7834 			maybe_widen_reg(env,
7835 					&fold->stack[i].spilled_ptr,
7836 					&fcur->stack[i].spilled_ptr,
7837 					&env->idmap_scratch);
7838 		}
7839 	}
7840 	return 0;
7841 }
7842 
7843 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7844 						 struct bpf_kfunc_call_arg_meta *meta)
7845 {
7846 	int iter_frameno = meta->iter.frameno;
7847 	int iter_spi = meta->iter.spi;
7848 
7849 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7850 }
7851 
7852 /* process_iter_next_call() is called when verifier gets to iterator's next
7853  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7854  * to it as just "iter_next()" in comments below.
7855  *
7856  * BPF verifier relies on a crucial contract for any iter_next()
7857  * implementation: it should *eventually* return NULL, and once that happens
7858  * it should keep returning NULL. That is, once iterator exhausts elements to
7859  * iterate, it should never reset or spuriously return new elements.
7860  *
7861  * With the assumption of such contract, process_iter_next_call() simulates
7862  * a fork in the verifier state to validate loop logic correctness and safety
7863  * without having to simulate infinite amount of iterations.
7864  *
7865  * In current state, we first assume that iter_next() returned NULL and
7866  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7867  * conditions we should not form an infinite loop and should eventually reach
7868  * exit.
7869  *
7870  * Besides that, we also fork current state and enqueue it for later
7871  * verification. In a forked state we keep iterator state as ACTIVE
7872  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7873  * also bump iteration depth to prevent erroneous infinite loop detection
7874  * later on (see iter_active_depths_differ() comment for details). In this
7875  * state we assume that we'll eventually loop back to another iter_next()
7876  * calls (it could be in exactly same location or in some other instruction,
7877  * it doesn't matter, we don't make any unnecessary assumptions about this,
7878  * everything revolves around iterator state in a stack slot, not which
7879  * instruction is calling iter_next()). When that happens, we either will come
7880  * to iter_next() with equivalent state and can conclude that next iteration
7881  * will proceed in exactly the same way as we just verified, so it's safe to
7882  * assume that loop converges. If not, we'll go on another iteration
7883  * simulation with a different input state, until all possible starting states
7884  * are validated or we reach maximum number of instructions limit.
7885  *
7886  * This way, we will either exhaustively discover all possible input states
7887  * that iterator loop can start with and eventually will converge, or we'll
7888  * effectively regress into bounded loop simulation logic and either reach
7889  * maximum number of instructions if loop is not provably convergent, or there
7890  * is some statically known limit on number of iterations (e.g., if there is
7891  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7892  *
7893  * Iteration convergence logic in is_state_visited() relies on exact
7894  * states comparison, which ignores read and precision marks.
7895  * This is necessary because read and precision marks are not finalized
7896  * while in the loop. Exact comparison might preclude convergence for
7897  * simple programs like below:
7898  *
7899  *     i = 0;
7900  *     while(iter_next(&it))
7901  *       i++;
7902  *
7903  * At each iteration step i++ would produce a new distinct state and
7904  * eventually instruction processing limit would be reached.
7905  *
7906  * To avoid such behavior speculatively forget (widen) range for
7907  * imprecise scalar registers, if those registers were not precise at the
7908  * end of the previous iteration and do not match exactly.
7909  *
7910  * This is a conservative heuristic that allows to verify wide range of programs,
7911  * however it precludes verification of programs that conjure an
7912  * imprecise value on the first loop iteration and use it as precise on a second.
7913  * For example, the following safe program would fail to verify:
7914  *
7915  *     struct bpf_num_iter it;
7916  *     int arr[10];
7917  *     int i = 0, a = 0;
7918  *     bpf_iter_num_new(&it, 0, 10);
7919  *     while (bpf_iter_num_next(&it)) {
7920  *       if (a == 0) {
7921  *         a = 1;
7922  *         i = 7; // Because i changed verifier would forget
7923  *                // it's range on second loop entry.
7924  *       } else {
7925  *         arr[i] = 42; // This would fail to verify.
7926  *       }
7927  *     }
7928  *     bpf_iter_num_destroy(&it);
7929  */
7930 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7931 				  struct bpf_kfunc_call_arg_meta *meta)
7932 {
7933 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7934 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7935 	struct bpf_reg_state *cur_iter, *queued_iter;
7936 
7937 	BTF_TYPE_EMIT(struct bpf_iter);
7938 
7939 	cur_iter = get_iter_from_state(cur_st, meta);
7940 
7941 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7942 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7943 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7944 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7945 		return -EFAULT;
7946 	}
7947 
7948 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7949 		/* Because iter_next() call is a checkpoint is_state_visitied()
7950 		 * should guarantee parent state with same call sites and insn_idx.
7951 		 */
7952 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7953 		    !same_callsites(cur_st->parent, cur_st)) {
7954 			verbose(env, "bug: bad parent state for iter next call");
7955 			return -EFAULT;
7956 		}
7957 		/* Note cur_st->parent in the call below, it is necessary to skip
7958 		 * checkpoint created for cur_st by is_state_visited()
7959 		 * right at this instruction.
7960 		 */
7961 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7962 		/* branch out active iter state */
7963 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7964 		if (!queued_st)
7965 			return -ENOMEM;
7966 
7967 		queued_iter = get_iter_from_state(queued_st, meta);
7968 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7969 		queued_iter->iter.depth++;
7970 		if (prev_st)
7971 			widen_imprecise_scalars(env, prev_st, queued_st);
7972 
7973 		queued_fr = queued_st->frame[queued_st->curframe];
7974 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7975 	}
7976 
7977 	/* switch to DRAINED state, but keep the depth unchanged */
7978 	/* mark current iter state as drained and assume returned NULL */
7979 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7980 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7981 
7982 	return 0;
7983 }
7984 
7985 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7986 {
7987 	return type == ARG_CONST_SIZE ||
7988 	       type == ARG_CONST_SIZE_OR_ZERO;
7989 }
7990 
7991 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7992 {
7993 	return base_type(type) == ARG_PTR_TO_MEM &&
7994 	       type & MEM_UNINIT;
7995 }
7996 
7997 static bool arg_type_is_release(enum bpf_arg_type type)
7998 {
7999 	return type & OBJ_RELEASE;
8000 }
8001 
8002 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8003 {
8004 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8005 }
8006 
8007 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8008 				 const struct bpf_call_arg_meta *meta,
8009 				 enum bpf_arg_type *arg_type)
8010 {
8011 	if (!meta->map_ptr) {
8012 		/* kernel subsystem misconfigured verifier */
8013 		verbose(env, "invalid map_ptr to access map->type\n");
8014 		return -EACCES;
8015 	}
8016 
8017 	switch (meta->map_ptr->map_type) {
8018 	case BPF_MAP_TYPE_SOCKMAP:
8019 	case BPF_MAP_TYPE_SOCKHASH:
8020 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8021 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8022 		} else {
8023 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8024 			return -EINVAL;
8025 		}
8026 		break;
8027 	case BPF_MAP_TYPE_BLOOM_FILTER:
8028 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8029 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8030 		break;
8031 	default:
8032 		break;
8033 	}
8034 	return 0;
8035 }
8036 
8037 struct bpf_reg_types {
8038 	const enum bpf_reg_type types[10];
8039 	u32 *btf_id;
8040 };
8041 
8042 static const struct bpf_reg_types sock_types = {
8043 	.types = {
8044 		PTR_TO_SOCK_COMMON,
8045 		PTR_TO_SOCKET,
8046 		PTR_TO_TCP_SOCK,
8047 		PTR_TO_XDP_SOCK,
8048 	},
8049 };
8050 
8051 #ifdef CONFIG_NET
8052 static const struct bpf_reg_types btf_id_sock_common_types = {
8053 	.types = {
8054 		PTR_TO_SOCK_COMMON,
8055 		PTR_TO_SOCKET,
8056 		PTR_TO_TCP_SOCK,
8057 		PTR_TO_XDP_SOCK,
8058 		PTR_TO_BTF_ID,
8059 		PTR_TO_BTF_ID | PTR_TRUSTED,
8060 	},
8061 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8062 };
8063 #endif
8064 
8065 static const struct bpf_reg_types mem_types = {
8066 	.types = {
8067 		PTR_TO_STACK,
8068 		PTR_TO_PACKET,
8069 		PTR_TO_PACKET_META,
8070 		PTR_TO_MAP_KEY,
8071 		PTR_TO_MAP_VALUE,
8072 		PTR_TO_MEM,
8073 		PTR_TO_MEM | MEM_RINGBUF,
8074 		PTR_TO_BUF,
8075 		PTR_TO_BTF_ID | PTR_TRUSTED,
8076 	},
8077 };
8078 
8079 static const struct bpf_reg_types spin_lock_types = {
8080 	.types = {
8081 		PTR_TO_MAP_VALUE,
8082 		PTR_TO_BTF_ID | MEM_ALLOC,
8083 	}
8084 };
8085 
8086 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8087 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8088 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8089 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8090 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8091 static const struct bpf_reg_types btf_ptr_types = {
8092 	.types = {
8093 		PTR_TO_BTF_ID,
8094 		PTR_TO_BTF_ID | PTR_TRUSTED,
8095 		PTR_TO_BTF_ID | MEM_RCU,
8096 	},
8097 };
8098 static const struct bpf_reg_types percpu_btf_ptr_types = {
8099 	.types = {
8100 		PTR_TO_BTF_ID | MEM_PERCPU,
8101 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8102 	}
8103 };
8104 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8105 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8106 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8107 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8108 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8109 static const struct bpf_reg_types dynptr_types = {
8110 	.types = {
8111 		PTR_TO_STACK,
8112 		CONST_PTR_TO_DYNPTR,
8113 	}
8114 };
8115 
8116 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8117 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8118 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8119 	[ARG_CONST_SIZE]		= &scalar_types,
8120 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8121 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8122 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8123 	[ARG_PTR_TO_CTX]		= &context_types,
8124 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8125 #ifdef CONFIG_NET
8126 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8127 #endif
8128 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8129 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8130 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8131 	[ARG_PTR_TO_MEM]		= &mem_types,
8132 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8133 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8134 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8135 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8136 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8137 	[ARG_PTR_TO_TIMER]		= &timer_types,
8138 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8139 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8140 };
8141 
8142 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8143 			  enum bpf_arg_type arg_type,
8144 			  const u32 *arg_btf_id,
8145 			  struct bpf_call_arg_meta *meta)
8146 {
8147 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8148 	enum bpf_reg_type expected, type = reg->type;
8149 	const struct bpf_reg_types *compatible;
8150 	int i, j;
8151 
8152 	compatible = compatible_reg_types[base_type(arg_type)];
8153 	if (!compatible) {
8154 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8155 		return -EFAULT;
8156 	}
8157 
8158 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8159 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8160 	 *
8161 	 * Same for MAYBE_NULL:
8162 	 *
8163 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8164 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8165 	 *
8166 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8167 	 *
8168 	 * Therefore we fold these flags depending on the arg_type before comparison.
8169 	 */
8170 	if (arg_type & MEM_RDONLY)
8171 		type &= ~MEM_RDONLY;
8172 	if (arg_type & PTR_MAYBE_NULL)
8173 		type &= ~PTR_MAYBE_NULL;
8174 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8175 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8176 
8177 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8178 		type &= ~MEM_ALLOC;
8179 
8180 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8181 		expected = compatible->types[i];
8182 		if (expected == NOT_INIT)
8183 			break;
8184 
8185 		if (type == expected)
8186 			goto found;
8187 	}
8188 
8189 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8190 	for (j = 0; j + 1 < i; j++)
8191 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8192 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8193 	return -EACCES;
8194 
8195 found:
8196 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8197 		return 0;
8198 
8199 	if (compatible == &mem_types) {
8200 		if (!(arg_type & MEM_RDONLY)) {
8201 			verbose(env,
8202 				"%s() may write into memory pointed by R%d type=%s\n",
8203 				func_id_name(meta->func_id),
8204 				regno, reg_type_str(env, reg->type));
8205 			return -EACCES;
8206 		}
8207 		return 0;
8208 	}
8209 
8210 	switch ((int)reg->type) {
8211 	case PTR_TO_BTF_ID:
8212 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8213 	case PTR_TO_BTF_ID | MEM_RCU:
8214 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8215 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8216 	{
8217 		/* For bpf_sk_release, it needs to match against first member
8218 		 * 'struct sock_common', hence make an exception for it. This
8219 		 * allows bpf_sk_release to work for multiple socket types.
8220 		 */
8221 		bool strict_type_match = arg_type_is_release(arg_type) &&
8222 					 meta->func_id != BPF_FUNC_sk_release;
8223 
8224 		if (type_may_be_null(reg->type) &&
8225 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8226 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8227 			return -EACCES;
8228 		}
8229 
8230 		if (!arg_btf_id) {
8231 			if (!compatible->btf_id) {
8232 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8233 				return -EFAULT;
8234 			}
8235 			arg_btf_id = compatible->btf_id;
8236 		}
8237 
8238 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8239 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8240 				return -EACCES;
8241 		} else {
8242 			if (arg_btf_id == BPF_PTR_POISON) {
8243 				verbose(env, "verifier internal error:");
8244 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8245 					regno);
8246 				return -EACCES;
8247 			}
8248 
8249 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8250 						  btf_vmlinux, *arg_btf_id,
8251 						  strict_type_match)) {
8252 				verbose(env, "R%d is of type %s but %s is expected\n",
8253 					regno, btf_type_name(reg->btf, reg->btf_id),
8254 					btf_type_name(btf_vmlinux, *arg_btf_id));
8255 				return -EACCES;
8256 			}
8257 		}
8258 		break;
8259 	}
8260 	case PTR_TO_BTF_ID | MEM_ALLOC:
8261 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8262 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8263 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8264 			return -EFAULT;
8265 		}
8266 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8267 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8268 				return -EACCES;
8269 		}
8270 		break;
8271 	case PTR_TO_BTF_ID | MEM_PERCPU:
8272 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8273 		/* Handled by helper specific checks */
8274 		break;
8275 	default:
8276 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8277 		return -EFAULT;
8278 	}
8279 	return 0;
8280 }
8281 
8282 static struct btf_field *
8283 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8284 {
8285 	struct btf_field *field;
8286 	struct btf_record *rec;
8287 
8288 	rec = reg_btf_record(reg);
8289 	if (!rec)
8290 		return NULL;
8291 
8292 	field = btf_record_find(rec, off, fields);
8293 	if (!field)
8294 		return NULL;
8295 
8296 	return field;
8297 }
8298 
8299 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8300 			   const struct bpf_reg_state *reg, int regno,
8301 			   enum bpf_arg_type arg_type)
8302 {
8303 	u32 type = reg->type;
8304 
8305 	/* When referenced register is passed to release function, its fixed
8306 	 * offset must be 0.
8307 	 *
8308 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8309 	 * meta->release_regno.
8310 	 */
8311 	if (arg_type_is_release(arg_type)) {
8312 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8313 		 * may not directly point to the object being released, but to
8314 		 * dynptr pointing to such object, which might be at some offset
8315 		 * on the stack. In that case, we simply to fallback to the
8316 		 * default handling.
8317 		 */
8318 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8319 			return 0;
8320 
8321 		/* Doing check_ptr_off_reg check for the offset will catch this
8322 		 * because fixed_off_ok is false, but checking here allows us
8323 		 * to give the user a better error message.
8324 		 */
8325 		if (reg->off) {
8326 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8327 				regno);
8328 			return -EINVAL;
8329 		}
8330 		return __check_ptr_off_reg(env, reg, regno, false);
8331 	}
8332 
8333 	switch (type) {
8334 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8335 	case PTR_TO_STACK:
8336 	case PTR_TO_PACKET:
8337 	case PTR_TO_PACKET_META:
8338 	case PTR_TO_MAP_KEY:
8339 	case PTR_TO_MAP_VALUE:
8340 	case PTR_TO_MEM:
8341 	case PTR_TO_MEM | MEM_RDONLY:
8342 	case PTR_TO_MEM | MEM_RINGBUF:
8343 	case PTR_TO_BUF:
8344 	case PTR_TO_BUF | MEM_RDONLY:
8345 	case SCALAR_VALUE:
8346 		return 0;
8347 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8348 	 * fixed offset.
8349 	 */
8350 	case PTR_TO_BTF_ID:
8351 	case PTR_TO_BTF_ID | MEM_ALLOC:
8352 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8353 	case PTR_TO_BTF_ID | MEM_RCU:
8354 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8355 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8356 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8357 		 * its fixed offset must be 0. In the other cases, fixed offset
8358 		 * can be non-zero. This was already checked above. So pass
8359 		 * fixed_off_ok as true to allow fixed offset for all other
8360 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8361 		 * still need to do checks instead of returning.
8362 		 */
8363 		return __check_ptr_off_reg(env, reg, regno, true);
8364 	default:
8365 		return __check_ptr_off_reg(env, reg, regno, false);
8366 	}
8367 }
8368 
8369 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8370 						const struct bpf_func_proto *fn,
8371 						struct bpf_reg_state *regs)
8372 {
8373 	struct bpf_reg_state *state = NULL;
8374 	int i;
8375 
8376 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8377 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8378 			if (state) {
8379 				verbose(env, "verifier internal error: multiple dynptr args\n");
8380 				return NULL;
8381 			}
8382 			state = &regs[BPF_REG_1 + i];
8383 		}
8384 
8385 	if (!state)
8386 		verbose(env, "verifier internal error: no dynptr arg found\n");
8387 
8388 	return state;
8389 }
8390 
8391 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8392 {
8393 	struct bpf_func_state *state = func(env, reg);
8394 	int spi;
8395 
8396 	if (reg->type == CONST_PTR_TO_DYNPTR)
8397 		return reg->id;
8398 	spi = dynptr_get_spi(env, reg);
8399 	if (spi < 0)
8400 		return spi;
8401 	return state->stack[spi].spilled_ptr.id;
8402 }
8403 
8404 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8405 {
8406 	struct bpf_func_state *state = func(env, reg);
8407 	int spi;
8408 
8409 	if (reg->type == CONST_PTR_TO_DYNPTR)
8410 		return reg->ref_obj_id;
8411 	spi = dynptr_get_spi(env, reg);
8412 	if (spi < 0)
8413 		return spi;
8414 	return state->stack[spi].spilled_ptr.ref_obj_id;
8415 }
8416 
8417 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8418 					    struct bpf_reg_state *reg)
8419 {
8420 	struct bpf_func_state *state = func(env, reg);
8421 	int spi;
8422 
8423 	if (reg->type == CONST_PTR_TO_DYNPTR)
8424 		return reg->dynptr.type;
8425 
8426 	spi = __get_spi(reg->off);
8427 	if (spi < 0) {
8428 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8429 		return BPF_DYNPTR_TYPE_INVALID;
8430 	}
8431 
8432 	return state->stack[spi].spilled_ptr.dynptr.type;
8433 }
8434 
8435 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8436 			  struct bpf_call_arg_meta *meta,
8437 			  const struct bpf_func_proto *fn,
8438 			  int insn_idx)
8439 {
8440 	u32 regno = BPF_REG_1 + arg;
8441 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8442 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8443 	enum bpf_reg_type type = reg->type;
8444 	u32 *arg_btf_id = NULL;
8445 	int err = 0;
8446 
8447 	if (arg_type == ARG_DONTCARE)
8448 		return 0;
8449 
8450 	err = check_reg_arg(env, regno, SRC_OP);
8451 	if (err)
8452 		return err;
8453 
8454 	if (arg_type == ARG_ANYTHING) {
8455 		if (is_pointer_value(env, regno)) {
8456 			verbose(env, "R%d leaks addr into helper function\n",
8457 				regno);
8458 			return -EACCES;
8459 		}
8460 		return 0;
8461 	}
8462 
8463 	if (type_is_pkt_pointer(type) &&
8464 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8465 		verbose(env, "helper access to the packet is not allowed\n");
8466 		return -EACCES;
8467 	}
8468 
8469 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8470 		err = resolve_map_arg_type(env, meta, &arg_type);
8471 		if (err)
8472 			return err;
8473 	}
8474 
8475 	if (register_is_null(reg) && type_may_be_null(arg_type))
8476 		/* A NULL register has a SCALAR_VALUE type, so skip
8477 		 * type checking.
8478 		 */
8479 		goto skip_type_check;
8480 
8481 	/* arg_btf_id and arg_size are in a union. */
8482 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8483 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8484 		arg_btf_id = fn->arg_btf_id[arg];
8485 
8486 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8487 	if (err)
8488 		return err;
8489 
8490 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8491 	if (err)
8492 		return err;
8493 
8494 skip_type_check:
8495 	if (arg_type_is_release(arg_type)) {
8496 		if (arg_type_is_dynptr(arg_type)) {
8497 			struct bpf_func_state *state = func(env, reg);
8498 			int spi;
8499 
8500 			/* Only dynptr created on stack can be released, thus
8501 			 * the get_spi and stack state checks for spilled_ptr
8502 			 * should only be done before process_dynptr_func for
8503 			 * PTR_TO_STACK.
8504 			 */
8505 			if (reg->type == PTR_TO_STACK) {
8506 				spi = dynptr_get_spi(env, reg);
8507 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8508 					verbose(env, "arg %d is an unacquired reference\n", regno);
8509 					return -EINVAL;
8510 				}
8511 			} else {
8512 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8513 				return -EINVAL;
8514 			}
8515 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8516 			verbose(env, "R%d must be referenced when passed to release function\n",
8517 				regno);
8518 			return -EINVAL;
8519 		}
8520 		if (meta->release_regno) {
8521 			verbose(env, "verifier internal error: more than one release argument\n");
8522 			return -EFAULT;
8523 		}
8524 		meta->release_regno = regno;
8525 	}
8526 
8527 	if (reg->ref_obj_id) {
8528 		if (meta->ref_obj_id) {
8529 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8530 				regno, reg->ref_obj_id,
8531 				meta->ref_obj_id);
8532 			return -EFAULT;
8533 		}
8534 		meta->ref_obj_id = reg->ref_obj_id;
8535 	}
8536 
8537 	switch (base_type(arg_type)) {
8538 	case ARG_CONST_MAP_PTR:
8539 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8540 		if (meta->map_ptr) {
8541 			/* Use map_uid (which is unique id of inner map) to reject:
8542 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8543 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8544 			 * if (inner_map1 && inner_map2) {
8545 			 *     timer = bpf_map_lookup_elem(inner_map1);
8546 			 *     if (timer)
8547 			 *         // mismatch would have been allowed
8548 			 *         bpf_timer_init(timer, inner_map2);
8549 			 * }
8550 			 *
8551 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8552 			 */
8553 			if (meta->map_ptr != reg->map_ptr ||
8554 			    meta->map_uid != reg->map_uid) {
8555 				verbose(env,
8556 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8557 					meta->map_uid, reg->map_uid);
8558 				return -EINVAL;
8559 			}
8560 		}
8561 		meta->map_ptr = reg->map_ptr;
8562 		meta->map_uid = reg->map_uid;
8563 		break;
8564 	case ARG_PTR_TO_MAP_KEY:
8565 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8566 		 * check that [key, key + map->key_size) are within
8567 		 * stack limits and initialized
8568 		 */
8569 		if (!meta->map_ptr) {
8570 			/* in function declaration map_ptr must come before
8571 			 * map_key, so that it's verified and known before
8572 			 * we have to check map_key here. Otherwise it means
8573 			 * that kernel subsystem misconfigured verifier
8574 			 */
8575 			verbose(env, "invalid map_ptr to access map->key\n");
8576 			return -EACCES;
8577 		}
8578 		err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
8579 					      BPF_READ, false, NULL);
8580 		break;
8581 	case ARG_PTR_TO_MAP_VALUE:
8582 		if (type_may_be_null(arg_type) && register_is_null(reg))
8583 			return 0;
8584 
8585 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8586 		 * check [value, value + map->value_size) validity
8587 		 */
8588 		if (!meta->map_ptr) {
8589 			/* kernel subsystem misconfigured verifier */
8590 			verbose(env, "invalid map_ptr to access map->value\n");
8591 			return -EACCES;
8592 		}
8593 		meta->raw_mode = arg_type & MEM_UNINIT;
8594 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
8595 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8596 					      false, meta);
8597 		break;
8598 	case ARG_PTR_TO_PERCPU_BTF_ID:
8599 		if (!reg->btf_id) {
8600 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8601 			return -EACCES;
8602 		}
8603 		meta->ret_btf = reg->btf;
8604 		meta->ret_btf_id = reg->btf_id;
8605 		break;
8606 	case ARG_PTR_TO_SPIN_LOCK:
8607 		if (in_rbtree_lock_required_cb(env)) {
8608 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8609 			return -EACCES;
8610 		}
8611 		if (meta->func_id == BPF_FUNC_spin_lock) {
8612 			err = process_spin_lock(env, regno, true);
8613 			if (err)
8614 				return err;
8615 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8616 			err = process_spin_lock(env, regno, false);
8617 			if (err)
8618 				return err;
8619 		} else {
8620 			verbose(env, "verifier internal error\n");
8621 			return -EFAULT;
8622 		}
8623 		break;
8624 	case ARG_PTR_TO_TIMER:
8625 		err = process_timer_func(env, regno, meta);
8626 		if (err)
8627 			return err;
8628 		break;
8629 	case ARG_PTR_TO_FUNC:
8630 		meta->subprogno = reg->subprogno;
8631 		break;
8632 	case ARG_PTR_TO_MEM:
8633 		/* The access to this pointer is only checked when we hit the
8634 		 * next is_mem_size argument below.
8635 		 */
8636 		meta->raw_mode = arg_type & MEM_UNINIT;
8637 		if (arg_type & MEM_FIXED_SIZE) {
8638 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
8639 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8640 						      false, meta);
8641 			if (err)
8642 				return err;
8643 			if (arg_type & MEM_ALIGNED)
8644 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8645 		}
8646 		break;
8647 	case ARG_CONST_SIZE:
8648 		err = check_mem_size_reg(env, reg, regno,
8649 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8650 					 BPF_WRITE : BPF_READ,
8651 					 false, meta);
8652 		break;
8653 	case ARG_CONST_SIZE_OR_ZERO:
8654 		err = check_mem_size_reg(env, reg, regno,
8655 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8656 					 BPF_WRITE : BPF_READ,
8657 					 true, meta);
8658 		break;
8659 	case ARG_PTR_TO_DYNPTR:
8660 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8661 		if (err)
8662 			return err;
8663 		break;
8664 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8665 		if (!tnum_is_const(reg->var_off)) {
8666 			verbose(env, "R%d is not a known constant'\n",
8667 				regno);
8668 			return -EACCES;
8669 		}
8670 		meta->mem_size = reg->var_off.value;
8671 		err = mark_chain_precision(env, regno);
8672 		if (err)
8673 			return err;
8674 		break;
8675 	case ARG_PTR_TO_CONST_STR:
8676 	{
8677 		struct bpf_map *map = reg->map_ptr;
8678 		int map_off;
8679 		u64 map_addr;
8680 		char *str_ptr;
8681 
8682 		if (!bpf_map_is_rdonly(map)) {
8683 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8684 			return -EACCES;
8685 		}
8686 
8687 		if (!tnum_is_const(reg->var_off)) {
8688 			verbose(env, "R%d is not a constant address'\n", regno);
8689 			return -EACCES;
8690 		}
8691 
8692 		if (!map->ops->map_direct_value_addr) {
8693 			verbose(env, "no direct value access support for this map type\n");
8694 			return -EACCES;
8695 		}
8696 
8697 		err = check_map_access(env, regno, reg->off,
8698 				       map->value_size - reg->off, false,
8699 				       ACCESS_HELPER);
8700 		if (err)
8701 			return err;
8702 
8703 		map_off = reg->off + reg->var_off.value;
8704 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8705 		if (err) {
8706 			verbose(env, "direct value access on string failed\n");
8707 			return err;
8708 		}
8709 
8710 		str_ptr = (char *)(long)(map_addr);
8711 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8712 			verbose(env, "string is not zero-terminated\n");
8713 			return -EINVAL;
8714 		}
8715 		break;
8716 	}
8717 	case ARG_PTR_TO_KPTR:
8718 		err = process_kptr_func(env, regno, meta);
8719 		if (err)
8720 			return err;
8721 		break;
8722 	}
8723 
8724 	return err;
8725 }
8726 
8727 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8728 {
8729 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8730 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8731 
8732 	if (func_id != BPF_FUNC_map_update_elem &&
8733 	    func_id != BPF_FUNC_map_delete_elem)
8734 		return false;
8735 
8736 	/* It's not possible to get access to a locked struct sock in these
8737 	 * contexts, so updating is safe.
8738 	 */
8739 	switch (type) {
8740 	case BPF_PROG_TYPE_TRACING:
8741 		if (eatype == BPF_TRACE_ITER)
8742 			return true;
8743 		break;
8744 	case BPF_PROG_TYPE_SOCK_OPS:
8745 		/* map_update allowed only via dedicated helpers with event type checks */
8746 		if (func_id == BPF_FUNC_map_delete_elem)
8747 			return true;
8748 		break;
8749 	case BPF_PROG_TYPE_SOCKET_FILTER:
8750 	case BPF_PROG_TYPE_SCHED_CLS:
8751 	case BPF_PROG_TYPE_SCHED_ACT:
8752 	case BPF_PROG_TYPE_XDP:
8753 	case BPF_PROG_TYPE_SK_REUSEPORT:
8754 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8755 	case BPF_PROG_TYPE_SK_LOOKUP:
8756 		return true;
8757 	default:
8758 		break;
8759 	}
8760 
8761 	verbose(env, "cannot update sockmap in this context\n");
8762 	return false;
8763 }
8764 
8765 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8766 {
8767 	return env->prog->jit_requested &&
8768 	       bpf_jit_supports_subprog_tailcalls();
8769 }
8770 
8771 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8772 					struct bpf_map *map, int func_id)
8773 {
8774 	if (!map)
8775 		return 0;
8776 
8777 	/* We need a two way check, first is from map perspective ... */
8778 	switch (map->map_type) {
8779 	case BPF_MAP_TYPE_PROG_ARRAY:
8780 		if (func_id != BPF_FUNC_tail_call)
8781 			goto error;
8782 		break;
8783 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8784 		if (func_id != BPF_FUNC_perf_event_read &&
8785 		    func_id != BPF_FUNC_perf_event_output &&
8786 		    func_id != BPF_FUNC_skb_output &&
8787 		    func_id != BPF_FUNC_perf_event_read_value &&
8788 		    func_id != BPF_FUNC_xdp_output)
8789 			goto error;
8790 		break;
8791 	case BPF_MAP_TYPE_RINGBUF:
8792 		if (func_id != BPF_FUNC_ringbuf_output &&
8793 		    func_id != BPF_FUNC_ringbuf_reserve &&
8794 		    func_id != BPF_FUNC_ringbuf_query &&
8795 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8796 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8797 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8798 			goto error;
8799 		break;
8800 	case BPF_MAP_TYPE_USER_RINGBUF:
8801 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8802 			goto error;
8803 		break;
8804 	case BPF_MAP_TYPE_STACK_TRACE:
8805 		if (func_id != BPF_FUNC_get_stackid)
8806 			goto error;
8807 		break;
8808 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8809 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8810 		    func_id != BPF_FUNC_current_task_under_cgroup)
8811 			goto error;
8812 		break;
8813 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8814 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8815 		if (func_id != BPF_FUNC_get_local_storage)
8816 			goto error;
8817 		break;
8818 	case BPF_MAP_TYPE_DEVMAP:
8819 	case BPF_MAP_TYPE_DEVMAP_HASH:
8820 		if (func_id != BPF_FUNC_redirect_map &&
8821 		    func_id != BPF_FUNC_map_lookup_elem)
8822 			goto error;
8823 		break;
8824 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8825 	 * appear.
8826 	 */
8827 	case BPF_MAP_TYPE_CPUMAP:
8828 		if (func_id != BPF_FUNC_redirect_map)
8829 			goto error;
8830 		break;
8831 	case BPF_MAP_TYPE_XSKMAP:
8832 		if (func_id != BPF_FUNC_redirect_map &&
8833 		    func_id != BPF_FUNC_map_lookup_elem)
8834 			goto error;
8835 		break;
8836 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8837 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8838 		if (func_id != BPF_FUNC_map_lookup_elem)
8839 			goto error;
8840 		break;
8841 	case BPF_MAP_TYPE_SOCKMAP:
8842 		if (func_id != BPF_FUNC_sk_redirect_map &&
8843 		    func_id != BPF_FUNC_sock_map_update &&
8844 		    func_id != BPF_FUNC_msg_redirect_map &&
8845 		    func_id != BPF_FUNC_sk_select_reuseport &&
8846 		    func_id != BPF_FUNC_map_lookup_elem &&
8847 		    !may_update_sockmap(env, func_id))
8848 			goto error;
8849 		break;
8850 	case BPF_MAP_TYPE_SOCKHASH:
8851 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8852 		    func_id != BPF_FUNC_sock_hash_update &&
8853 		    func_id != BPF_FUNC_msg_redirect_hash &&
8854 		    func_id != BPF_FUNC_sk_select_reuseport &&
8855 		    func_id != BPF_FUNC_map_lookup_elem &&
8856 		    !may_update_sockmap(env, func_id))
8857 			goto error;
8858 		break;
8859 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8860 		if (func_id != BPF_FUNC_sk_select_reuseport)
8861 			goto error;
8862 		break;
8863 	case BPF_MAP_TYPE_QUEUE:
8864 	case BPF_MAP_TYPE_STACK:
8865 		if (func_id != BPF_FUNC_map_peek_elem &&
8866 		    func_id != BPF_FUNC_map_pop_elem &&
8867 		    func_id != BPF_FUNC_map_push_elem)
8868 			goto error;
8869 		break;
8870 	case BPF_MAP_TYPE_SK_STORAGE:
8871 		if (func_id != BPF_FUNC_sk_storage_get &&
8872 		    func_id != BPF_FUNC_sk_storage_delete &&
8873 		    func_id != BPF_FUNC_kptr_xchg)
8874 			goto error;
8875 		break;
8876 	case BPF_MAP_TYPE_INODE_STORAGE:
8877 		if (func_id != BPF_FUNC_inode_storage_get &&
8878 		    func_id != BPF_FUNC_inode_storage_delete &&
8879 		    func_id != BPF_FUNC_kptr_xchg)
8880 			goto error;
8881 		break;
8882 	case BPF_MAP_TYPE_TASK_STORAGE:
8883 		if (func_id != BPF_FUNC_task_storage_get &&
8884 		    func_id != BPF_FUNC_task_storage_delete &&
8885 		    func_id != BPF_FUNC_kptr_xchg)
8886 			goto error;
8887 		break;
8888 	case BPF_MAP_TYPE_CGRP_STORAGE:
8889 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8890 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8891 		    func_id != BPF_FUNC_kptr_xchg)
8892 			goto error;
8893 		break;
8894 	case BPF_MAP_TYPE_BLOOM_FILTER:
8895 		if (func_id != BPF_FUNC_map_peek_elem &&
8896 		    func_id != BPF_FUNC_map_push_elem)
8897 			goto error;
8898 		break;
8899 	default:
8900 		break;
8901 	}
8902 
8903 	/* ... and second from the function itself. */
8904 	switch (func_id) {
8905 	case BPF_FUNC_tail_call:
8906 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8907 			goto error;
8908 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8909 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8910 			return -EINVAL;
8911 		}
8912 		break;
8913 	case BPF_FUNC_perf_event_read:
8914 	case BPF_FUNC_perf_event_output:
8915 	case BPF_FUNC_perf_event_read_value:
8916 	case BPF_FUNC_skb_output:
8917 	case BPF_FUNC_xdp_output:
8918 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8919 			goto error;
8920 		break;
8921 	case BPF_FUNC_ringbuf_output:
8922 	case BPF_FUNC_ringbuf_reserve:
8923 	case BPF_FUNC_ringbuf_query:
8924 	case BPF_FUNC_ringbuf_reserve_dynptr:
8925 	case BPF_FUNC_ringbuf_submit_dynptr:
8926 	case BPF_FUNC_ringbuf_discard_dynptr:
8927 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8928 			goto error;
8929 		break;
8930 	case BPF_FUNC_user_ringbuf_drain:
8931 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8932 			goto error;
8933 		break;
8934 	case BPF_FUNC_get_stackid:
8935 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8936 			goto error;
8937 		break;
8938 	case BPF_FUNC_current_task_under_cgroup:
8939 	case BPF_FUNC_skb_under_cgroup:
8940 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8941 			goto error;
8942 		break;
8943 	case BPF_FUNC_redirect_map:
8944 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8945 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8946 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8947 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8948 			goto error;
8949 		break;
8950 	case BPF_FUNC_sk_redirect_map:
8951 	case BPF_FUNC_msg_redirect_map:
8952 	case BPF_FUNC_sock_map_update:
8953 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8954 			goto error;
8955 		break;
8956 	case BPF_FUNC_sk_redirect_hash:
8957 	case BPF_FUNC_msg_redirect_hash:
8958 	case BPF_FUNC_sock_hash_update:
8959 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8960 			goto error;
8961 		break;
8962 	case BPF_FUNC_get_local_storage:
8963 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8964 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8965 			goto error;
8966 		break;
8967 	case BPF_FUNC_sk_select_reuseport:
8968 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8969 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8970 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8971 			goto error;
8972 		break;
8973 	case BPF_FUNC_map_pop_elem:
8974 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8975 		    map->map_type != BPF_MAP_TYPE_STACK)
8976 			goto error;
8977 		break;
8978 	case BPF_FUNC_map_peek_elem:
8979 	case BPF_FUNC_map_push_elem:
8980 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8981 		    map->map_type != BPF_MAP_TYPE_STACK &&
8982 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8983 			goto error;
8984 		break;
8985 	case BPF_FUNC_map_lookup_percpu_elem:
8986 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8987 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8988 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8989 			goto error;
8990 		break;
8991 	case BPF_FUNC_sk_storage_get:
8992 	case BPF_FUNC_sk_storage_delete:
8993 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8994 			goto error;
8995 		break;
8996 	case BPF_FUNC_inode_storage_get:
8997 	case BPF_FUNC_inode_storage_delete:
8998 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8999 			goto error;
9000 		break;
9001 	case BPF_FUNC_task_storage_get:
9002 	case BPF_FUNC_task_storage_delete:
9003 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9004 			goto error;
9005 		break;
9006 	case BPF_FUNC_cgrp_storage_get:
9007 	case BPF_FUNC_cgrp_storage_delete:
9008 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9009 			goto error;
9010 		break;
9011 	default:
9012 		break;
9013 	}
9014 
9015 	return 0;
9016 error:
9017 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9018 		map->map_type, func_id_name(func_id), func_id);
9019 	return -EINVAL;
9020 }
9021 
9022 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9023 {
9024 	int count = 0;
9025 
9026 	if (arg_type_is_raw_mem(fn->arg1_type))
9027 		count++;
9028 	if (arg_type_is_raw_mem(fn->arg2_type))
9029 		count++;
9030 	if (arg_type_is_raw_mem(fn->arg3_type))
9031 		count++;
9032 	if (arg_type_is_raw_mem(fn->arg4_type))
9033 		count++;
9034 	if (arg_type_is_raw_mem(fn->arg5_type))
9035 		count++;
9036 
9037 	/* We only support one arg being in raw mode at the moment,
9038 	 * which is sufficient for the helper functions we have
9039 	 * right now.
9040 	 */
9041 	return count <= 1;
9042 }
9043 
9044 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9045 {
9046 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9047 	bool has_size = fn->arg_size[arg] != 0;
9048 	bool is_next_size = false;
9049 
9050 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9051 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9052 
9053 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9054 		return is_next_size;
9055 
9056 	return has_size == is_next_size || is_next_size == is_fixed;
9057 }
9058 
9059 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9060 {
9061 	/* bpf_xxx(..., buf, len) call will access 'len'
9062 	 * bytes from memory 'buf'. Both arg types need
9063 	 * to be paired, so make sure there's no buggy
9064 	 * helper function specification.
9065 	 */
9066 	if (arg_type_is_mem_size(fn->arg1_type) ||
9067 	    check_args_pair_invalid(fn, 0) ||
9068 	    check_args_pair_invalid(fn, 1) ||
9069 	    check_args_pair_invalid(fn, 2) ||
9070 	    check_args_pair_invalid(fn, 3) ||
9071 	    check_args_pair_invalid(fn, 4))
9072 		return false;
9073 
9074 	return true;
9075 }
9076 
9077 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9078 {
9079 	int i;
9080 
9081 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9082 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9083 			return !!fn->arg_btf_id[i];
9084 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9085 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9086 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9087 		    /* arg_btf_id and arg_size are in a union. */
9088 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9089 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9090 			return false;
9091 	}
9092 
9093 	return true;
9094 }
9095 
9096 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9097 {
9098 	return check_raw_mode_ok(fn) &&
9099 	       check_arg_pair_ok(fn) &&
9100 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9101 }
9102 
9103 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9104  * are now invalid, so turn them into unknown SCALAR_VALUE.
9105  *
9106  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9107  * since these slices point to packet data.
9108  */
9109 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9110 {
9111 	struct bpf_func_state *state;
9112 	struct bpf_reg_state *reg;
9113 
9114 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9115 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9116 			mark_reg_invalid(env, reg);
9117 	}));
9118 }
9119 
9120 enum {
9121 	AT_PKT_END = -1,
9122 	BEYOND_PKT_END = -2,
9123 };
9124 
9125 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9126 {
9127 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9128 	struct bpf_reg_state *reg = &state->regs[regn];
9129 
9130 	if (reg->type != PTR_TO_PACKET)
9131 		/* PTR_TO_PACKET_META is not supported yet */
9132 		return;
9133 
9134 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9135 	 * How far beyond pkt_end it goes is unknown.
9136 	 * if (!range_open) it's the case of pkt >= pkt_end
9137 	 * if (range_open) it's the case of pkt > pkt_end
9138 	 * hence this pointer is at least 1 byte bigger than pkt_end
9139 	 */
9140 	if (range_open)
9141 		reg->range = BEYOND_PKT_END;
9142 	else
9143 		reg->range = AT_PKT_END;
9144 }
9145 
9146 /* The pointer with the specified id has released its reference to kernel
9147  * resources. Identify all copies of the same pointer and clear the reference.
9148  */
9149 static int release_reference(struct bpf_verifier_env *env,
9150 			     int ref_obj_id)
9151 {
9152 	struct bpf_func_state *state;
9153 	struct bpf_reg_state *reg;
9154 	int err;
9155 
9156 	err = release_reference_state(cur_func(env), ref_obj_id);
9157 	if (err)
9158 		return err;
9159 
9160 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9161 		if (reg->ref_obj_id == ref_obj_id)
9162 			mark_reg_invalid(env, reg);
9163 	}));
9164 
9165 	return 0;
9166 }
9167 
9168 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9169 {
9170 	struct bpf_func_state *unused;
9171 	struct bpf_reg_state *reg;
9172 
9173 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9174 		if (type_is_non_owning_ref(reg->type))
9175 			mark_reg_invalid(env, reg);
9176 	}));
9177 }
9178 
9179 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9180 				    struct bpf_reg_state *regs)
9181 {
9182 	int i;
9183 
9184 	/* after the call registers r0 - r5 were scratched */
9185 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9186 		mark_reg_not_init(env, regs, caller_saved[i]);
9187 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9188 	}
9189 }
9190 
9191 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9192 				   struct bpf_func_state *caller,
9193 				   struct bpf_func_state *callee,
9194 				   int insn_idx);
9195 
9196 static int set_callee_state(struct bpf_verifier_env *env,
9197 			    struct bpf_func_state *caller,
9198 			    struct bpf_func_state *callee, int insn_idx);
9199 
9200 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9201 			    set_callee_state_fn set_callee_state_cb,
9202 			    struct bpf_verifier_state *state)
9203 {
9204 	struct bpf_func_state *caller, *callee;
9205 	int err;
9206 
9207 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9208 		verbose(env, "the call stack of %d frames is too deep\n",
9209 			state->curframe + 2);
9210 		return -E2BIG;
9211 	}
9212 
9213 	if (state->frame[state->curframe + 1]) {
9214 		verbose(env, "verifier bug. Frame %d already allocated\n",
9215 			state->curframe + 1);
9216 		return -EFAULT;
9217 	}
9218 
9219 	caller = state->frame[state->curframe];
9220 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9221 	if (!callee)
9222 		return -ENOMEM;
9223 	state->frame[state->curframe + 1] = callee;
9224 
9225 	/* callee cannot access r0, r6 - r9 for reading and has to write
9226 	 * into its own stack before reading from it.
9227 	 * callee can read/write into caller's stack
9228 	 */
9229 	init_func_state(env, callee,
9230 			/* remember the callsite, it will be used by bpf_exit */
9231 			callsite,
9232 			state->curframe + 1 /* frameno within this callchain */,
9233 			subprog /* subprog number within this prog */);
9234 	/* Transfer references to the callee */
9235 	err = copy_reference_state(callee, caller);
9236 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9237 	if (err)
9238 		goto err_out;
9239 
9240 	/* only increment it after check_reg_arg() finished */
9241 	state->curframe++;
9242 
9243 	return 0;
9244 
9245 err_out:
9246 	free_func_state(callee);
9247 	state->frame[state->curframe + 1] = NULL;
9248 	return err;
9249 }
9250 
9251 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9252 			      int insn_idx, int subprog,
9253 			      set_callee_state_fn set_callee_state_cb)
9254 {
9255 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9256 	struct bpf_func_state *caller, *callee;
9257 	int err;
9258 
9259 	caller = state->frame[state->curframe];
9260 	err = btf_check_subprog_call(env, subprog, caller->regs);
9261 	if (err == -EFAULT)
9262 		return err;
9263 
9264 	/* set_callee_state is used for direct subprog calls, but we are
9265 	 * interested in validating only BPF helpers that can call subprogs as
9266 	 * callbacks
9267 	 */
9268 	if (bpf_pseudo_kfunc_call(insn) &&
9269 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9270 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9271 			func_id_name(insn->imm), insn->imm);
9272 		return -EFAULT;
9273 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9274 		   !is_callback_calling_function(insn->imm)) { /* helper */
9275 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9276 			func_id_name(insn->imm), insn->imm);
9277 		return -EFAULT;
9278 	}
9279 
9280 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9281 	    insn->src_reg == 0 &&
9282 	    insn->imm == BPF_FUNC_timer_set_callback) {
9283 		struct bpf_verifier_state *async_cb;
9284 
9285 		/* there is no real recursion here. timer callbacks are async */
9286 		env->subprog_info[subprog].is_async_cb = true;
9287 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9288 					 insn_idx, subprog);
9289 		if (!async_cb)
9290 			return -EFAULT;
9291 		callee = async_cb->frame[0];
9292 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9293 
9294 		/* Convert bpf_timer_set_callback() args into timer callback args */
9295 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9296 		if (err)
9297 			return err;
9298 
9299 		return 0;
9300 	}
9301 
9302 	/* for callback functions enqueue entry to callback and
9303 	 * proceed with next instruction within current frame.
9304 	 */
9305 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9306 	if (!callback_state)
9307 		return -ENOMEM;
9308 
9309 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9310 			       callback_state);
9311 	if (err)
9312 		return err;
9313 
9314 	callback_state->callback_unroll_depth++;
9315 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9316 	caller->callback_depth = 0;
9317 	return 0;
9318 }
9319 
9320 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9321 			   int *insn_idx)
9322 {
9323 	struct bpf_verifier_state *state = env->cur_state;
9324 	struct bpf_func_state *caller;
9325 	int err, subprog, target_insn;
9326 
9327 	target_insn = *insn_idx + insn->imm + 1;
9328 	subprog = find_subprog(env, target_insn);
9329 	if (subprog < 0) {
9330 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9331 		return -EFAULT;
9332 	}
9333 
9334 	caller = state->frame[state->curframe];
9335 	err = btf_check_subprog_call(env, subprog, caller->regs);
9336 	if (err == -EFAULT)
9337 		return err;
9338 	if (subprog_is_global(env, subprog)) {
9339 		if (err) {
9340 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9341 			return err;
9342 		}
9343 
9344 		if (env->log.level & BPF_LOG_LEVEL)
9345 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9346 		clear_caller_saved_regs(env, caller->regs);
9347 
9348 		/* All global functions return a 64-bit SCALAR_VALUE */
9349 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9350 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9351 
9352 		/* continue with next insn after call */
9353 		return 0;
9354 	}
9355 
9356 	/* for regular function entry setup new frame and continue
9357 	 * from that frame.
9358 	 */
9359 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9360 	if (err)
9361 		return err;
9362 
9363 	clear_caller_saved_regs(env, caller->regs);
9364 
9365 	/* and go analyze first insn of the callee */
9366 	*insn_idx = env->subprog_info[subprog].start - 1;
9367 
9368 	if (env->log.level & BPF_LOG_LEVEL) {
9369 		verbose(env, "caller:\n");
9370 		print_verifier_state(env, caller, true);
9371 		verbose(env, "callee:\n");
9372 		print_verifier_state(env, state->frame[state->curframe], true);
9373 	}
9374 
9375 	return 0;
9376 }
9377 
9378 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9379 				   struct bpf_func_state *caller,
9380 				   struct bpf_func_state *callee)
9381 {
9382 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9383 	 *      void *callback_ctx, u64 flags);
9384 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9385 	 *      void *callback_ctx);
9386 	 */
9387 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9388 
9389 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9390 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9391 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9392 
9393 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9394 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9395 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9396 
9397 	/* pointer to stack or null */
9398 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9399 
9400 	/* unused */
9401 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9402 	return 0;
9403 }
9404 
9405 static int set_callee_state(struct bpf_verifier_env *env,
9406 			    struct bpf_func_state *caller,
9407 			    struct bpf_func_state *callee, int insn_idx)
9408 {
9409 	int i;
9410 
9411 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9412 	 * pointers, which connects us up to the liveness chain
9413 	 */
9414 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9415 		callee->regs[i] = caller->regs[i];
9416 	return 0;
9417 }
9418 
9419 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9420 				       struct bpf_func_state *caller,
9421 				       struct bpf_func_state *callee,
9422 				       int insn_idx)
9423 {
9424 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9425 	struct bpf_map *map;
9426 	int err;
9427 
9428 	if (bpf_map_ptr_poisoned(insn_aux)) {
9429 		verbose(env, "tail_call abusing map_ptr\n");
9430 		return -EINVAL;
9431 	}
9432 
9433 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9434 	if (!map->ops->map_set_for_each_callback_args ||
9435 	    !map->ops->map_for_each_callback) {
9436 		verbose(env, "callback function not allowed for map\n");
9437 		return -ENOTSUPP;
9438 	}
9439 
9440 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9441 	if (err)
9442 		return err;
9443 
9444 	callee->in_callback_fn = true;
9445 	callee->callback_ret_range = tnum_range(0, 1);
9446 	return 0;
9447 }
9448 
9449 static int set_loop_callback_state(struct bpf_verifier_env *env,
9450 				   struct bpf_func_state *caller,
9451 				   struct bpf_func_state *callee,
9452 				   int insn_idx)
9453 {
9454 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9455 	 *	    u64 flags);
9456 	 * callback_fn(u32 index, void *callback_ctx);
9457 	 */
9458 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9459 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9460 
9461 	/* unused */
9462 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9463 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9464 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9465 
9466 	callee->in_callback_fn = true;
9467 	callee->callback_ret_range = tnum_range(0, 1);
9468 	return 0;
9469 }
9470 
9471 static int set_timer_callback_state(struct bpf_verifier_env *env,
9472 				    struct bpf_func_state *caller,
9473 				    struct bpf_func_state *callee,
9474 				    int insn_idx)
9475 {
9476 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9477 
9478 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9479 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9480 	 */
9481 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9482 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9483 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9484 
9485 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9486 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9487 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9488 
9489 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9490 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9491 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9492 
9493 	/* unused */
9494 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9495 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9496 	callee->in_async_callback_fn = true;
9497 	callee->callback_ret_range = tnum_range(0, 1);
9498 	return 0;
9499 }
9500 
9501 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9502 				       struct bpf_func_state *caller,
9503 				       struct bpf_func_state *callee,
9504 				       int insn_idx)
9505 {
9506 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9507 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9508 	 * (callback_fn)(struct task_struct *task,
9509 	 *               struct vm_area_struct *vma, void *callback_ctx);
9510 	 */
9511 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9512 
9513 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9514 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9515 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9516 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9517 
9518 	/* pointer to stack or null */
9519 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9520 
9521 	/* unused */
9522 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9523 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9524 	callee->in_callback_fn = true;
9525 	callee->callback_ret_range = tnum_range(0, 1);
9526 	return 0;
9527 }
9528 
9529 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9530 					   struct bpf_func_state *caller,
9531 					   struct bpf_func_state *callee,
9532 					   int insn_idx)
9533 {
9534 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9535 	 *			  callback_ctx, u64 flags);
9536 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9537 	 */
9538 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9539 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9540 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9541 
9542 	/* unused */
9543 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9544 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9545 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9546 
9547 	callee->in_callback_fn = true;
9548 	callee->callback_ret_range = tnum_range(0, 1);
9549 	return 0;
9550 }
9551 
9552 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9553 					 struct bpf_func_state *caller,
9554 					 struct bpf_func_state *callee,
9555 					 int insn_idx)
9556 {
9557 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9558 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9559 	 *
9560 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9561 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9562 	 * by this point, so look at 'root'
9563 	 */
9564 	struct btf_field *field;
9565 
9566 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9567 				      BPF_RB_ROOT);
9568 	if (!field || !field->graph_root.value_btf_id)
9569 		return -EFAULT;
9570 
9571 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9572 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9573 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9574 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9575 
9576 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9577 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9578 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9579 	callee->in_callback_fn = true;
9580 	callee->callback_ret_range = tnum_range(0, 1);
9581 	return 0;
9582 }
9583 
9584 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9585 
9586 /* Are we currently verifying the callback for a rbtree helper that must
9587  * be called with lock held? If so, no need to complain about unreleased
9588  * lock
9589  */
9590 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9591 {
9592 	struct bpf_verifier_state *state = env->cur_state;
9593 	struct bpf_insn *insn = env->prog->insnsi;
9594 	struct bpf_func_state *callee;
9595 	int kfunc_btf_id;
9596 
9597 	if (!state->curframe)
9598 		return false;
9599 
9600 	callee = state->frame[state->curframe];
9601 
9602 	if (!callee->in_callback_fn)
9603 		return false;
9604 
9605 	kfunc_btf_id = insn[callee->callsite].imm;
9606 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9607 }
9608 
9609 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9610 {
9611 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9612 	struct bpf_func_state *caller, *callee;
9613 	struct bpf_reg_state *r0;
9614 	bool in_callback_fn;
9615 	int err;
9616 
9617 	callee = state->frame[state->curframe];
9618 	r0 = &callee->regs[BPF_REG_0];
9619 	if (r0->type == PTR_TO_STACK) {
9620 		/* technically it's ok to return caller's stack pointer
9621 		 * (or caller's caller's pointer) back to the caller,
9622 		 * since these pointers are valid. Only current stack
9623 		 * pointer will be invalid as soon as function exits,
9624 		 * but let's be conservative
9625 		 */
9626 		verbose(env, "cannot return stack pointer to the caller\n");
9627 		return -EINVAL;
9628 	}
9629 
9630 	caller = state->frame[state->curframe - 1];
9631 	if (callee->in_callback_fn) {
9632 		/* enforce R0 return value range [0, 1]. */
9633 		struct tnum range = callee->callback_ret_range;
9634 
9635 		if (r0->type != SCALAR_VALUE) {
9636 			verbose(env, "R0 not a scalar value\n");
9637 			return -EACCES;
9638 		}
9639 
9640 		/* we are going to rely on register's precise value */
9641 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9642 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9643 		if (err)
9644 			return err;
9645 
9646 		if (!tnum_in(range, r0->var_off)) {
9647 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9648 			return -EINVAL;
9649 		}
9650 		if (!calls_callback(env, callee->callsite)) {
9651 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9652 				*insn_idx, callee->callsite);
9653 			return -EFAULT;
9654 		}
9655 	} else {
9656 		/* return to the caller whatever r0 had in the callee */
9657 		caller->regs[BPF_REG_0] = *r0;
9658 	}
9659 
9660 	/* callback_fn frame should have released its own additions to parent's
9661 	 * reference state at this point, or check_reference_leak would
9662 	 * complain, hence it must be the same as the caller. There is no need
9663 	 * to copy it back.
9664 	 */
9665 	if (!callee->in_callback_fn) {
9666 		/* Transfer references to the caller */
9667 		err = copy_reference_state(caller, callee);
9668 		if (err)
9669 			return err;
9670 	}
9671 
9672 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9673 	 * there function call logic would reschedule callback visit. If iteration
9674 	 * converges is_state_visited() would prune that visit eventually.
9675 	 */
9676 	in_callback_fn = callee->in_callback_fn;
9677 	if (in_callback_fn)
9678 		*insn_idx = callee->callsite;
9679 	else
9680 		*insn_idx = callee->callsite + 1;
9681 
9682 	if (env->log.level & BPF_LOG_LEVEL) {
9683 		verbose(env, "returning from callee:\n");
9684 		print_verifier_state(env, callee, true);
9685 		verbose(env, "to caller at %d:\n", *insn_idx);
9686 		print_verifier_state(env, caller, true);
9687 	}
9688 	/* clear everything in the callee */
9689 	free_func_state(callee);
9690 	state->frame[state->curframe--] = NULL;
9691 
9692 	/* for callbacks widen imprecise scalars to make programs like below verify:
9693 	 *
9694 	 *   struct ctx { int i; }
9695 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9696 	 *   ...
9697 	 *   struct ctx = { .i = 0; }
9698 	 *   bpf_loop(100, cb, &ctx, 0);
9699 	 *
9700 	 * This is similar to what is done in process_iter_next_call() for open
9701 	 * coded iterators.
9702 	 */
9703 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9704 	if (prev_st) {
9705 		err = widen_imprecise_scalars(env, prev_st, state);
9706 		if (err)
9707 			return err;
9708 	}
9709 	return 0;
9710 }
9711 
9712 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9713 				   int func_id,
9714 				   struct bpf_call_arg_meta *meta)
9715 {
9716 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9717 
9718 	if (ret_type != RET_INTEGER)
9719 		return;
9720 
9721 	switch (func_id) {
9722 	case BPF_FUNC_get_stack:
9723 	case BPF_FUNC_get_task_stack:
9724 	case BPF_FUNC_probe_read_str:
9725 	case BPF_FUNC_probe_read_kernel_str:
9726 	case BPF_FUNC_probe_read_user_str:
9727 		ret_reg->smax_value = meta->msize_max_value;
9728 		ret_reg->s32_max_value = meta->msize_max_value;
9729 		ret_reg->smin_value = -MAX_ERRNO;
9730 		ret_reg->s32_min_value = -MAX_ERRNO;
9731 		reg_bounds_sync(ret_reg);
9732 		break;
9733 	case BPF_FUNC_get_smp_processor_id:
9734 		ret_reg->umax_value = nr_cpu_ids - 1;
9735 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9736 		ret_reg->smax_value = nr_cpu_ids - 1;
9737 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9738 		ret_reg->umin_value = 0;
9739 		ret_reg->u32_min_value = 0;
9740 		ret_reg->smin_value = 0;
9741 		ret_reg->s32_min_value = 0;
9742 		reg_bounds_sync(ret_reg);
9743 		break;
9744 	}
9745 }
9746 
9747 static int
9748 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9749 		int func_id, int insn_idx)
9750 {
9751 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9752 	struct bpf_map *map = meta->map_ptr;
9753 
9754 	if (func_id != BPF_FUNC_tail_call &&
9755 	    func_id != BPF_FUNC_map_lookup_elem &&
9756 	    func_id != BPF_FUNC_map_update_elem &&
9757 	    func_id != BPF_FUNC_map_delete_elem &&
9758 	    func_id != BPF_FUNC_map_push_elem &&
9759 	    func_id != BPF_FUNC_map_pop_elem &&
9760 	    func_id != BPF_FUNC_map_peek_elem &&
9761 	    func_id != BPF_FUNC_for_each_map_elem &&
9762 	    func_id != BPF_FUNC_redirect_map &&
9763 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9764 		return 0;
9765 
9766 	if (map == NULL) {
9767 		verbose(env, "kernel subsystem misconfigured verifier\n");
9768 		return -EINVAL;
9769 	}
9770 
9771 	/* In case of read-only, some additional restrictions
9772 	 * need to be applied in order to prevent altering the
9773 	 * state of the map from program side.
9774 	 */
9775 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9776 	    (func_id == BPF_FUNC_map_delete_elem ||
9777 	     func_id == BPF_FUNC_map_update_elem ||
9778 	     func_id == BPF_FUNC_map_push_elem ||
9779 	     func_id == BPF_FUNC_map_pop_elem)) {
9780 		verbose(env, "write into map forbidden\n");
9781 		return -EACCES;
9782 	}
9783 
9784 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9785 		bpf_map_ptr_store(aux, meta->map_ptr,
9786 				  !meta->map_ptr->bypass_spec_v1);
9787 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9788 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9789 				  !meta->map_ptr->bypass_spec_v1);
9790 	return 0;
9791 }
9792 
9793 static int
9794 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9795 		int func_id, int insn_idx)
9796 {
9797 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9798 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9799 	struct bpf_map *map = meta->map_ptr;
9800 	u64 val, max;
9801 	int err;
9802 
9803 	if (func_id != BPF_FUNC_tail_call)
9804 		return 0;
9805 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9806 		verbose(env, "kernel subsystem misconfigured verifier\n");
9807 		return -EINVAL;
9808 	}
9809 
9810 	reg = &regs[BPF_REG_3];
9811 	val = reg->var_off.value;
9812 	max = map->max_entries;
9813 
9814 	if (!(register_is_const(reg) && val < max)) {
9815 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9816 		return 0;
9817 	}
9818 
9819 	err = mark_chain_precision(env, BPF_REG_3);
9820 	if (err)
9821 		return err;
9822 	if (bpf_map_key_unseen(aux))
9823 		bpf_map_key_store(aux, val);
9824 	else if (!bpf_map_key_poisoned(aux) &&
9825 		  bpf_map_key_immediate(aux) != val)
9826 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9827 	return 0;
9828 }
9829 
9830 static int check_reference_leak(struct bpf_verifier_env *env)
9831 {
9832 	struct bpf_func_state *state = cur_func(env);
9833 	bool refs_lingering = false;
9834 	int i;
9835 
9836 	if (state->frameno && !state->in_callback_fn)
9837 		return 0;
9838 
9839 	for (i = 0; i < state->acquired_refs; i++) {
9840 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9841 			continue;
9842 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9843 			state->refs[i].id, state->refs[i].insn_idx);
9844 		refs_lingering = true;
9845 	}
9846 	return refs_lingering ? -EINVAL : 0;
9847 }
9848 
9849 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9850 				   struct bpf_reg_state *regs)
9851 {
9852 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9853 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9854 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9855 	struct bpf_bprintf_data data = {};
9856 	int err, fmt_map_off, num_args;
9857 	u64 fmt_addr;
9858 	char *fmt;
9859 
9860 	/* data must be an array of u64 */
9861 	if (data_len_reg->var_off.value % 8)
9862 		return -EINVAL;
9863 	num_args = data_len_reg->var_off.value / 8;
9864 
9865 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9866 	 * and map_direct_value_addr is set.
9867 	 */
9868 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9869 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9870 						  fmt_map_off);
9871 	if (err) {
9872 		verbose(env, "verifier bug\n");
9873 		return -EFAULT;
9874 	}
9875 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9876 
9877 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9878 	 * can focus on validating the format specifiers.
9879 	 */
9880 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9881 	if (err < 0)
9882 		verbose(env, "Invalid format string\n");
9883 
9884 	return err;
9885 }
9886 
9887 static int check_get_func_ip(struct bpf_verifier_env *env)
9888 {
9889 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9890 	int func_id = BPF_FUNC_get_func_ip;
9891 
9892 	if (type == BPF_PROG_TYPE_TRACING) {
9893 		if (!bpf_prog_has_trampoline(env->prog)) {
9894 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9895 				func_id_name(func_id), func_id);
9896 			return -ENOTSUPP;
9897 		}
9898 		return 0;
9899 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9900 		return 0;
9901 	}
9902 
9903 	verbose(env, "func %s#%d not supported for program type %d\n",
9904 		func_id_name(func_id), func_id, type);
9905 	return -ENOTSUPP;
9906 }
9907 
9908 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9909 {
9910 	return &env->insn_aux_data[env->insn_idx];
9911 }
9912 
9913 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9914 {
9915 	struct bpf_reg_state *regs = cur_regs(env);
9916 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9917 	bool reg_is_null = register_is_null(reg);
9918 
9919 	if (reg_is_null)
9920 		mark_chain_precision(env, BPF_REG_4);
9921 
9922 	return reg_is_null;
9923 }
9924 
9925 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9926 {
9927 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9928 
9929 	if (!state->initialized) {
9930 		state->initialized = 1;
9931 		state->fit_for_inline = loop_flag_is_zero(env);
9932 		state->callback_subprogno = subprogno;
9933 		return;
9934 	}
9935 
9936 	if (!state->fit_for_inline)
9937 		return;
9938 
9939 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9940 				 state->callback_subprogno == subprogno);
9941 }
9942 
9943 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9944 			     int *insn_idx_p)
9945 {
9946 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9947 	const struct bpf_func_proto *fn = NULL;
9948 	enum bpf_return_type ret_type;
9949 	enum bpf_type_flag ret_flag;
9950 	struct bpf_reg_state *regs;
9951 	struct bpf_call_arg_meta meta;
9952 	int insn_idx = *insn_idx_p;
9953 	bool changes_data;
9954 	int i, err, func_id;
9955 
9956 	/* find function prototype */
9957 	func_id = insn->imm;
9958 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9959 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9960 			func_id);
9961 		return -EINVAL;
9962 	}
9963 
9964 	if (env->ops->get_func_proto)
9965 		fn = env->ops->get_func_proto(func_id, env->prog);
9966 	if (!fn) {
9967 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9968 			func_id);
9969 		return -EINVAL;
9970 	}
9971 
9972 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9973 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9974 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9975 		return -EINVAL;
9976 	}
9977 
9978 	if (fn->allowed && !fn->allowed(env->prog)) {
9979 		verbose(env, "helper call is not allowed in probe\n");
9980 		return -EINVAL;
9981 	}
9982 
9983 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9984 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9985 		return -EINVAL;
9986 	}
9987 
9988 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9989 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9990 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9991 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9992 			func_id_name(func_id), func_id);
9993 		return -EINVAL;
9994 	}
9995 
9996 	memset(&meta, 0, sizeof(meta));
9997 	meta.pkt_access = fn->pkt_access;
9998 
9999 	err = check_func_proto(fn, func_id);
10000 	if (err) {
10001 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10002 			func_id_name(func_id), func_id);
10003 		return err;
10004 	}
10005 
10006 	if (env->cur_state->active_rcu_lock) {
10007 		if (fn->might_sleep) {
10008 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10009 				func_id_name(func_id), func_id);
10010 			return -EINVAL;
10011 		}
10012 
10013 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10014 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10015 	}
10016 
10017 	meta.func_id = func_id;
10018 	/* check args */
10019 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10020 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10021 		if (err)
10022 			return err;
10023 	}
10024 
10025 	err = record_func_map(env, &meta, func_id, insn_idx);
10026 	if (err)
10027 		return err;
10028 
10029 	err = record_func_key(env, &meta, func_id, insn_idx);
10030 	if (err)
10031 		return err;
10032 
10033 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10034 	 * is inferred from register state.
10035 	 */
10036 	for (i = 0; i < meta.access_size; i++) {
10037 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10038 				       BPF_WRITE, -1, false, false);
10039 		if (err)
10040 			return err;
10041 	}
10042 
10043 	regs = cur_regs(env);
10044 
10045 	if (meta.release_regno) {
10046 		err = -EINVAL;
10047 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10048 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10049 		 * is safe to do directly.
10050 		 */
10051 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10052 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10053 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10054 				return -EFAULT;
10055 			}
10056 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10057 		} else if (meta.ref_obj_id) {
10058 			err = release_reference(env, meta.ref_obj_id);
10059 		} else if (register_is_null(&regs[meta.release_regno])) {
10060 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10061 			 * released is NULL, which must be > R0.
10062 			 */
10063 			err = 0;
10064 		}
10065 		if (err) {
10066 			verbose(env, "func %s#%d reference has not been acquired before\n",
10067 				func_id_name(func_id), func_id);
10068 			return err;
10069 		}
10070 	}
10071 
10072 	switch (func_id) {
10073 	case BPF_FUNC_tail_call:
10074 		err = check_reference_leak(env);
10075 		if (err) {
10076 			verbose(env, "tail_call would lead to reference leak\n");
10077 			return err;
10078 		}
10079 		break;
10080 	case BPF_FUNC_get_local_storage:
10081 		/* check that flags argument in get_local_storage(map, flags) is 0,
10082 		 * this is required because get_local_storage() can't return an error.
10083 		 */
10084 		if (!register_is_null(&regs[BPF_REG_2])) {
10085 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10086 			return -EINVAL;
10087 		}
10088 		break;
10089 	case BPF_FUNC_for_each_map_elem:
10090 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10091 					 set_map_elem_callback_state);
10092 		break;
10093 	case BPF_FUNC_timer_set_callback:
10094 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10095 					 set_timer_callback_state);
10096 		break;
10097 	case BPF_FUNC_find_vma:
10098 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10099 					 set_find_vma_callback_state);
10100 		break;
10101 	case BPF_FUNC_snprintf:
10102 		err = check_bpf_snprintf_call(env, regs);
10103 		break;
10104 	case BPF_FUNC_loop:
10105 		update_loop_inline_state(env, meta.subprogno);
10106 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10107 		 * is finished, thus mark it precise.
10108 		 */
10109 		err = mark_chain_precision(env, BPF_REG_1);
10110 		if (err)
10111 			return err;
10112 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10113 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10114 						 set_loop_callback_state);
10115 		} else {
10116 			cur_func(env)->callback_depth = 0;
10117 			if (env->log.level & BPF_LOG_LEVEL2)
10118 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10119 					env->cur_state->curframe);
10120 		}
10121 		break;
10122 	case BPF_FUNC_dynptr_from_mem:
10123 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10124 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10125 				reg_type_str(env, regs[BPF_REG_1].type));
10126 			return -EACCES;
10127 		}
10128 		break;
10129 	case BPF_FUNC_set_retval:
10130 		if (prog_type == BPF_PROG_TYPE_LSM &&
10131 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10132 			if (!env->prog->aux->attach_func_proto->type) {
10133 				/* Make sure programs that attach to void
10134 				 * hooks don't try to modify return value.
10135 				 */
10136 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10137 				return -EINVAL;
10138 			}
10139 		}
10140 		break;
10141 	case BPF_FUNC_dynptr_data:
10142 	{
10143 		struct bpf_reg_state *reg;
10144 		int id, ref_obj_id;
10145 
10146 		reg = get_dynptr_arg_reg(env, fn, regs);
10147 		if (!reg)
10148 			return -EFAULT;
10149 
10150 
10151 		if (meta.dynptr_id) {
10152 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10153 			return -EFAULT;
10154 		}
10155 		if (meta.ref_obj_id) {
10156 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10157 			return -EFAULT;
10158 		}
10159 
10160 		id = dynptr_id(env, reg);
10161 		if (id < 0) {
10162 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10163 			return id;
10164 		}
10165 
10166 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10167 		if (ref_obj_id < 0) {
10168 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10169 			return ref_obj_id;
10170 		}
10171 
10172 		meta.dynptr_id = id;
10173 		meta.ref_obj_id = ref_obj_id;
10174 
10175 		break;
10176 	}
10177 	case BPF_FUNC_dynptr_write:
10178 	{
10179 		enum bpf_dynptr_type dynptr_type;
10180 		struct bpf_reg_state *reg;
10181 
10182 		reg = get_dynptr_arg_reg(env, fn, regs);
10183 		if (!reg)
10184 			return -EFAULT;
10185 
10186 		dynptr_type = dynptr_get_type(env, reg);
10187 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10188 			return -EFAULT;
10189 
10190 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10191 			/* this will trigger clear_all_pkt_pointers(), which will
10192 			 * invalidate all dynptr slices associated with the skb
10193 			 */
10194 			changes_data = true;
10195 
10196 		break;
10197 	}
10198 	case BPF_FUNC_user_ringbuf_drain:
10199 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10200 					 set_user_ringbuf_callback_state);
10201 		break;
10202 	}
10203 
10204 	if (err)
10205 		return err;
10206 
10207 	/* reset caller saved regs */
10208 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10209 		mark_reg_not_init(env, regs, caller_saved[i]);
10210 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10211 	}
10212 
10213 	/* helper call returns 64-bit value. */
10214 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10215 
10216 	/* update return register (already marked as written above) */
10217 	ret_type = fn->ret_type;
10218 	ret_flag = type_flag(ret_type);
10219 
10220 	switch (base_type(ret_type)) {
10221 	case RET_INTEGER:
10222 		/* sets type to SCALAR_VALUE */
10223 		mark_reg_unknown(env, regs, BPF_REG_0);
10224 		break;
10225 	case RET_VOID:
10226 		regs[BPF_REG_0].type = NOT_INIT;
10227 		break;
10228 	case RET_PTR_TO_MAP_VALUE:
10229 		/* There is no offset yet applied, variable or fixed */
10230 		mark_reg_known_zero(env, regs, BPF_REG_0);
10231 		/* remember map_ptr, so that check_map_access()
10232 		 * can check 'value_size' boundary of memory access
10233 		 * to map element returned from bpf_map_lookup_elem()
10234 		 */
10235 		if (meta.map_ptr == NULL) {
10236 			verbose(env,
10237 				"kernel subsystem misconfigured verifier\n");
10238 			return -EINVAL;
10239 		}
10240 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10241 		regs[BPF_REG_0].map_uid = meta.map_uid;
10242 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10243 		if (!type_may_be_null(ret_type) &&
10244 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10245 			regs[BPF_REG_0].id = ++env->id_gen;
10246 		}
10247 		break;
10248 	case RET_PTR_TO_SOCKET:
10249 		mark_reg_known_zero(env, regs, BPF_REG_0);
10250 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10251 		break;
10252 	case RET_PTR_TO_SOCK_COMMON:
10253 		mark_reg_known_zero(env, regs, BPF_REG_0);
10254 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10255 		break;
10256 	case RET_PTR_TO_TCP_SOCK:
10257 		mark_reg_known_zero(env, regs, BPF_REG_0);
10258 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10259 		break;
10260 	case RET_PTR_TO_MEM:
10261 		mark_reg_known_zero(env, regs, BPF_REG_0);
10262 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10263 		regs[BPF_REG_0].mem_size = meta.mem_size;
10264 		break;
10265 	case RET_PTR_TO_MEM_OR_BTF_ID:
10266 	{
10267 		const struct btf_type *t;
10268 
10269 		mark_reg_known_zero(env, regs, BPF_REG_0);
10270 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10271 		if (!btf_type_is_struct(t)) {
10272 			u32 tsize;
10273 			const struct btf_type *ret;
10274 			const char *tname;
10275 
10276 			/* resolve the type size of ksym. */
10277 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10278 			if (IS_ERR(ret)) {
10279 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10280 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10281 					tname, PTR_ERR(ret));
10282 				return -EINVAL;
10283 			}
10284 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10285 			regs[BPF_REG_0].mem_size = tsize;
10286 		} else {
10287 			/* MEM_RDONLY may be carried from ret_flag, but it
10288 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10289 			 * it will confuse the check of PTR_TO_BTF_ID in
10290 			 * check_mem_access().
10291 			 */
10292 			ret_flag &= ~MEM_RDONLY;
10293 
10294 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10295 			regs[BPF_REG_0].btf = meta.ret_btf;
10296 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10297 		}
10298 		break;
10299 	}
10300 	case RET_PTR_TO_BTF_ID:
10301 	{
10302 		struct btf *ret_btf;
10303 		int ret_btf_id;
10304 
10305 		mark_reg_known_zero(env, regs, BPF_REG_0);
10306 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10307 		if (func_id == BPF_FUNC_kptr_xchg) {
10308 			ret_btf = meta.kptr_field->kptr.btf;
10309 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10310 			if (!btf_is_kernel(ret_btf))
10311 				regs[BPF_REG_0].type |= MEM_ALLOC;
10312 		} else {
10313 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10314 				verbose(env, "verifier internal error:");
10315 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10316 					func_id_name(func_id));
10317 				return -EINVAL;
10318 			}
10319 			ret_btf = btf_vmlinux;
10320 			ret_btf_id = *fn->ret_btf_id;
10321 		}
10322 		if (ret_btf_id == 0) {
10323 			verbose(env, "invalid return type %u of func %s#%d\n",
10324 				base_type(ret_type), func_id_name(func_id),
10325 				func_id);
10326 			return -EINVAL;
10327 		}
10328 		regs[BPF_REG_0].btf = ret_btf;
10329 		regs[BPF_REG_0].btf_id = ret_btf_id;
10330 		break;
10331 	}
10332 	default:
10333 		verbose(env, "unknown return type %u of func %s#%d\n",
10334 			base_type(ret_type), func_id_name(func_id), func_id);
10335 		return -EINVAL;
10336 	}
10337 
10338 	if (type_may_be_null(regs[BPF_REG_0].type))
10339 		regs[BPF_REG_0].id = ++env->id_gen;
10340 
10341 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10342 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10343 			func_id_name(func_id), func_id);
10344 		return -EFAULT;
10345 	}
10346 
10347 	if (is_dynptr_ref_function(func_id))
10348 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10349 
10350 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10351 		/* For release_reference() */
10352 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10353 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10354 		int id = acquire_reference_state(env, insn_idx);
10355 
10356 		if (id < 0)
10357 			return id;
10358 		/* For mark_ptr_or_null_reg() */
10359 		regs[BPF_REG_0].id = id;
10360 		/* For release_reference() */
10361 		regs[BPF_REG_0].ref_obj_id = id;
10362 	}
10363 
10364 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10365 
10366 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10367 	if (err)
10368 		return err;
10369 
10370 	if ((func_id == BPF_FUNC_get_stack ||
10371 	     func_id == BPF_FUNC_get_task_stack) &&
10372 	    !env->prog->has_callchain_buf) {
10373 		const char *err_str;
10374 
10375 #ifdef CONFIG_PERF_EVENTS
10376 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10377 		err_str = "cannot get callchain buffer for func %s#%d\n";
10378 #else
10379 		err = -ENOTSUPP;
10380 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10381 #endif
10382 		if (err) {
10383 			verbose(env, err_str, func_id_name(func_id), func_id);
10384 			return err;
10385 		}
10386 
10387 		env->prog->has_callchain_buf = true;
10388 	}
10389 
10390 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10391 		env->prog->call_get_stack = true;
10392 
10393 	if (func_id == BPF_FUNC_get_func_ip) {
10394 		if (check_get_func_ip(env))
10395 			return -ENOTSUPP;
10396 		env->prog->call_get_func_ip = true;
10397 	}
10398 
10399 	if (changes_data)
10400 		clear_all_pkt_pointers(env);
10401 	return 0;
10402 }
10403 
10404 /* mark_btf_func_reg_size() is used when the reg size is determined by
10405  * the BTF func_proto's return value size and argument.
10406  */
10407 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10408 				   size_t reg_size)
10409 {
10410 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10411 
10412 	if (regno == BPF_REG_0) {
10413 		/* Function return value */
10414 		reg->live |= REG_LIVE_WRITTEN;
10415 		reg->subreg_def = reg_size == sizeof(u64) ?
10416 			DEF_NOT_SUBREG : env->insn_idx + 1;
10417 	} else {
10418 		/* Function argument */
10419 		if (reg_size == sizeof(u64)) {
10420 			mark_insn_zext(env, reg);
10421 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10422 		} else {
10423 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10424 		}
10425 	}
10426 }
10427 
10428 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10429 {
10430 	return meta->kfunc_flags & KF_ACQUIRE;
10431 }
10432 
10433 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10434 {
10435 	return meta->kfunc_flags & KF_RELEASE;
10436 }
10437 
10438 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10439 {
10440 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10441 }
10442 
10443 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10444 {
10445 	return meta->kfunc_flags & KF_SLEEPABLE;
10446 }
10447 
10448 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10449 {
10450 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10451 }
10452 
10453 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10454 {
10455 	return meta->kfunc_flags & KF_RCU;
10456 }
10457 
10458 static bool __kfunc_param_match_suffix(const struct btf *btf,
10459 				       const struct btf_param *arg,
10460 				       const char *suffix)
10461 {
10462 	int suffix_len = strlen(suffix), len;
10463 	const char *param_name;
10464 
10465 	/* In the future, this can be ported to use BTF tagging */
10466 	param_name = btf_name_by_offset(btf, arg->name_off);
10467 	if (str_is_empty(param_name))
10468 		return false;
10469 	len = strlen(param_name);
10470 	if (len < suffix_len)
10471 		return false;
10472 	param_name += len - suffix_len;
10473 	return !strncmp(param_name, suffix, suffix_len);
10474 }
10475 
10476 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10477 				  const struct btf_param *arg,
10478 				  const struct bpf_reg_state *reg)
10479 {
10480 	const struct btf_type *t;
10481 
10482 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10483 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10484 		return false;
10485 
10486 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10487 }
10488 
10489 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10490 					const struct btf_param *arg,
10491 					const struct bpf_reg_state *reg)
10492 {
10493 	const struct btf_type *t;
10494 
10495 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10496 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10497 		return false;
10498 
10499 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10500 }
10501 
10502 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10503 {
10504 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10505 }
10506 
10507 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10508 {
10509 	return __kfunc_param_match_suffix(btf, arg, "__k");
10510 }
10511 
10512 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10513 {
10514 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10515 }
10516 
10517 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10518 {
10519 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10520 }
10521 
10522 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10523 {
10524 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10525 }
10526 
10527 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10528 {
10529 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10530 }
10531 
10532 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10533 					  const struct btf_param *arg,
10534 					  const char *name)
10535 {
10536 	int len, target_len = strlen(name);
10537 	const char *param_name;
10538 
10539 	param_name = btf_name_by_offset(btf, arg->name_off);
10540 	if (str_is_empty(param_name))
10541 		return false;
10542 	len = strlen(param_name);
10543 	if (len != target_len)
10544 		return false;
10545 	if (strcmp(param_name, name))
10546 		return false;
10547 
10548 	return true;
10549 }
10550 
10551 enum {
10552 	KF_ARG_DYNPTR_ID,
10553 	KF_ARG_LIST_HEAD_ID,
10554 	KF_ARG_LIST_NODE_ID,
10555 	KF_ARG_RB_ROOT_ID,
10556 	KF_ARG_RB_NODE_ID,
10557 };
10558 
10559 BTF_ID_LIST(kf_arg_btf_ids)
10560 BTF_ID(struct, bpf_dynptr_kern)
10561 BTF_ID(struct, bpf_list_head)
10562 BTF_ID(struct, bpf_list_node)
10563 BTF_ID(struct, bpf_rb_root)
10564 BTF_ID(struct, bpf_rb_node)
10565 
10566 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10567 				    const struct btf_param *arg, int type)
10568 {
10569 	const struct btf_type *t;
10570 	u32 res_id;
10571 
10572 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10573 	if (!t)
10574 		return false;
10575 	if (!btf_type_is_ptr(t))
10576 		return false;
10577 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10578 	if (!t)
10579 		return false;
10580 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10581 }
10582 
10583 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10584 {
10585 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10586 }
10587 
10588 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10589 {
10590 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10591 }
10592 
10593 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10594 {
10595 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10596 }
10597 
10598 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10599 {
10600 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10601 }
10602 
10603 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10604 {
10605 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10606 }
10607 
10608 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10609 				  const struct btf_param *arg)
10610 {
10611 	const struct btf_type *t;
10612 
10613 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10614 	if (!t)
10615 		return false;
10616 
10617 	return true;
10618 }
10619 
10620 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10621 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10622 					const struct btf *btf,
10623 					const struct btf_type *t, int rec)
10624 {
10625 	const struct btf_type *member_type;
10626 	const struct btf_member *member;
10627 	u32 i;
10628 
10629 	if (!btf_type_is_struct(t))
10630 		return false;
10631 
10632 	for_each_member(i, t, member) {
10633 		const struct btf_array *array;
10634 
10635 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10636 		if (btf_type_is_struct(member_type)) {
10637 			if (rec >= 3) {
10638 				verbose(env, "max struct nesting depth exceeded\n");
10639 				return false;
10640 			}
10641 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10642 				return false;
10643 			continue;
10644 		}
10645 		if (btf_type_is_array(member_type)) {
10646 			array = btf_array(member_type);
10647 			if (!array->nelems)
10648 				return false;
10649 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10650 			if (!btf_type_is_scalar(member_type))
10651 				return false;
10652 			continue;
10653 		}
10654 		if (!btf_type_is_scalar(member_type))
10655 			return false;
10656 	}
10657 	return true;
10658 }
10659 
10660 enum kfunc_ptr_arg_type {
10661 	KF_ARG_PTR_TO_CTX,
10662 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10663 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10664 	KF_ARG_PTR_TO_DYNPTR,
10665 	KF_ARG_PTR_TO_ITER,
10666 	KF_ARG_PTR_TO_LIST_HEAD,
10667 	KF_ARG_PTR_TO_LIST_NODE,
10668 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10669 	KF_ARG_PTR_TO_MEM,
10670 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10671 	KF_ARG_PTR_TO_CALLBACK,
10672 	KF_ARG_PTR_TO_RB_ROOT,
10673 	KF_ARG_PTR_TO_RB_NODE,
10674 };
10675 
10676 enum special_kfunc_type {
10677 	KF_bpf_obj_new_impl,
10678 	KF_bpf_obj_drop_impl,
10679 	KF_bpf_refcount_acquire_impl,
10680 	KF_bpf_list_push_front_impl,
10681 	KF_bpf_list_push_back_impl,
10682 	KF_bpf_list_pop_front,
10683 	KF_bpf_list_pop_back,
10684 	KF_bpf_cast_to_kern_ctx,
10685 	KF_bpf_rdonly_cast,
10686 	KF_bpf_rcu_read_lock,
10687 	KF_bpf_rcu_read_unlock,
10688 	KF_bpf_rbtree_remove,
10689 	KF_bpf_rbtree_add_impl,
10690 	KF_bpf_rbtree_first,
10691 	KF_bpf_dynptr_from_skb,
10692 	KF_bpf_dynptr_from_xdp,
10693 	KF_bpf_dynptr_slice,
10694 	KF_bpf_dynptr_slice_rdwr,
10695 	KF_bpf_dynptr_clone,
10696 };
10697 
10698 BTF_SET_START(special_kfunc_set)
10699 BTF_ID(func, bpf_obj_new_impl)
10700 BTF_ID(func, bpf_obj_drop_impl)
10701 BTF_ID(func, bpf_refcount_acquire_impl)
10702 BTF_ID(func, bpf_list_push_front_impl)
10703 BTF_ID(func, bpf_list_push_back_impl)
10704 BTF_ID(func, bpf_list_pop_front)
10705 BTF_ID(func, bpf_list_pop_back)
10706 BTF_ID(func, bpf_cast_to_kern_ctx)
10707 BTF_ID(func, bpf_rdonly_cast)
10708 BTF_ID(func, bpf_rbtree_remove)
10709 BTF_ID(func, bpf_rbtree_add_impl)
10710 BTF_ID(func, bpf_rbtree_first)
10711 BTF_ID(func, bpf_dynptr_from_skb)
10712 BTF_ID(func, bpf_dynptr_from_xdp)
10713 BTF_ID(func, bpf_dynptr_slice)
10714 BTF_ID(func, bpf_dynptr_slice_rdwr)
10715 BTF_ID(func, bpf_dynptr_clone)
10716 BTF_SET_END(special_kfunc_set)
10717 
10718 BTF_ID_LIST(special_kfunc_list)
10719 BTF_ID(func, bpf_obj_new_impl)
10720 BTF_ID(func, bpf_obj_drop_impl)
10721 BTF_ID(func, bpf_refcount_acquire_impl)
10722 BTF_ID(func, bpf_list_push_front_impl)
10723 BTF_ID(func, bpf_list_push_back_impl)
10724 BTF_ID(func, bpf_list_pop_front)
10725 BTF_ID(func, bpf_list_pop_back)
10726 BTF_ID(func, bpf_cast_to_kern_ctx)
10727 BTF_ID(func, bpf_rdonly_cast)
10728 BTF_ID(func, bpf_rcu_read_lock)
10729 BTF_ID(func, bpf_rcu_read_unlock)
10730 BTF_ID(func, bpf_rbtree_remove)
10731 BTF_ID(func, bpf_rbtree_add_impl)
10732 BTF_ID(func, bpf_rbtree_first)
10733 BTF_ID(func, bpf_dynptr_from_skb)
10734 BTF_ID(func, bpf_dynptr_from_xdp)
10735 BTF_ID(func, bpf_dynptr_slice)
10736 BTF_ID(func, bpf_dynptr_slice_rdwr)
10737 BTF_ID(func, bpf_dynptr_clone)
10738 
10739 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10740 {
10741 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10742 	    meta->arg_owning_ref) {
10743 		return false;
10744 	}
10745 
10746 	return meta->kfunc_flags & KF_RET_NULL;
10747 }
10748 
10749 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10750 {
10751 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10752 }
10753 
10754 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10755 {
10756 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10757 }
10758 
10759 static enum kfunc_ptr_arg_type
10760 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10761 		       struct bpf_kfunc_call_arg_meta *meta,
10762 		       const struct btf_type *t, const struct btf_type *ref_t,
10763 		       const char *ref_tname, const struct btf_param *args,
10764 		       int argno, int nargs)
10765 {
10766 	u32 regno = argno + 1;
10767 	struct bpf_reg_state *regs = cur_regs(env);
10768 	struct bpf_reg_state *reg = &regs[regno];
10769 	bool arg_mem_size = false;
10770 
10771 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10772 		return KF_ARG_PTR_TO_CTX;
10773 
10774 	/* In this function, we verify the kfunc's BTF as per the argument type,
10775 	 * leaving the rest of the verification with respect to the register
10776 	 * type to our caller. When a set of conditions hold in the BTF type of
10777 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10778 	 */
10779 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10780 		return KF_ARG_PTR_TO_CTX;
10781 
10782 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10783 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10784 
10785 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10786 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10787 
10788 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10789 		return KF_ARG_PTR_TO_DYNPTR;
10790 
10791 	if (is_kfunc_arg_iter(meta, argno))
10792 		return KF_ARG_PTR_TO_ITER;
10793 
10794 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10795 		return KF_ARG_PTR_TO_LIST_HEAD;
10796 
10797 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10798 		return KF_ARG_PTR_TO_LIST_NODE;
10799 
10800 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10801 		return KF_ARG_PTR_TO_RB_ROOT;
10802 
10803 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10804 		return KF_ARG_PTR_TO_RB_NODE;
10805 
10806 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10807 		if (!btf_type_is_struct(ref_t)) {
10808 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10809 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10810 			return -EINVAL;
10811 		}
10812 		return KF_ARG_PTR_TO_BTF_ID;
10813 	}
10814 
10815 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10816 		return KF_ARG_PTR_TO_CALLBACK;
10817 
10818 
10819 	if (argno + 1 < nargs &&
10820 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10821 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10822 		arg_mem_size = true;
10823 
10824 	/* This is the catch all argument type of register types supported by
10825 	 * check_helper_mem_access. However, we only allow when argument type is
10826 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10827 	 * arg_mem_size is true, the pointer can be void *.
10828 	 */
10829 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10830 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10831 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10832 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10833 		return -EINVAL;
10834 	}
10835 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10836 }
10837 
10838 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10839 					struct bpf_reg_state *reg,
10840 					const struct btf_type *ref_t,
10841 					const char *ref_tname, u32 ref_id,
10842 					struct bpf_kfunc_call_arg_meta *meta,
10843 					int argno)
10844 {
10845 	const struct btf_type *reg_ref_t;
10846 	bool strict_type_match = false;
10847 	const struct btf *reg_btf;
10848 	const char *reg_ref_tname;
10849 	u32 reg_ref_id;
10850 
10851 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10852 		reg_btf = reg->btf;
10853 		reg_ref_id = reg->btf_id;
10854 	} else {
10855 		reg_btf = btf_vmlinux;
10856 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10857 	}
10858 
10859 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10860 	 * or releasing a reference, or are no-cast aliases. We do _not_
10861 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10862 	 * as we want to enable BPF programs to pass types that are bitwise
10863 	 * equivalent without forcing them to explicitly cast with something
10864 	 * like bpf_cast_to_kern_ctx().
10865 	 *
10866 	 * For example, say we had a type like the following:
10867 	 *
10868 	 * struct bpf_cpumask {
10869 	 *	cpumask_t cpumask;
10870 	 *	refcount_t usage;
10871 	 * };
10872 	 *
10873 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10874 	 * to a struct cpumask, so it would be safe to pass a struct
10875 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10876 	 *
10877 	 * The philosophy here is similar to how we allow scalars of different
10878 	 * types to be passed to kfuncs as long as the size is the same. The
10879 	 * only difference here is that we're simply allowing
10880 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10881 	 * resolve types.
10882 	 */
10883 	if (is_kfunc_acquire(meta) ||
10884 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10885 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10886 		strict_type_match = true;
10887 
10888 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10889 
10890 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10891 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10892 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10893 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10894 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10895 			btf_type_str(reg_ref_t), reg_ref_tname);
10896 		return -EINVAL;
10897 	}
10898 	return 0;
10899 }
10900 
10901 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10902 {
10903 	struct bpf_verifier_state *state = env->cur_state;
10904 	struct btf_record *rec = reg_btf_record(reg);
10905 
10906 	if (!state->active_lock.ptr) {
10907 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10908 		return -EFAULT;
10909 	}
10910 
10911 	if (type_flag(reg->type) & NON_OWN_REF) {
10912 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10913 		return -EFAULT;
10914 	}
10915 
10916 	reg->type |= NON_OWN_REF;
10917 	if (rec->refcount_off >= 0)
10918 		reg->type |= MEM_RCU;
10919 
10920 	return 0;
10921 }
10922 
10923 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10924 {
10925 	struct bpf_func_state *state, *unused;
10926 	struct bpf_reg_state *reg;
10927 	int i;
10928 
10929 	state = cur_func(env);
10930 
10931 	if (!ref_obj_id) {
10932 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10933 			     "owning -> non-owning conversion\n");
10934 		return -EFAULT;
10935 	}
10936 
10937 	for (i = 0; i < state->acquired_refs; i++) {
10938 		if (state->refs[i].id != ref_obj_id)
10939 			continue;
10940 
10941 		/* Clear ref_obj_id here so release_reference doesn't clobber
10942 		 * the whole reg
10943 		 */
10944 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10945 			if (reg->ref_obj_id == ref_obj_id) {
10946 				reg->ref_obj_id = 0;
10947 				ref_set_non_owning(env, reg);
10948 			}
10949 		}));
10950 		return 0;
10951 	}
10952 
10953 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10954 	return -EFAULT;
10955 }
10956 
10957 /* Implementation details:
10958  *
10959  * Each register points to some region of memory, which we define as an
10960  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10961  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10962  * allocation. The lock and the data it protects are colocated in the same
10963  * memory region.
10964  *
10965  * Hence, everytime a register holds a pointer value pointing to such
10966  * allocation, the verifier preserves a unique reg->id for it.
10967  *
10968  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10969  * bpf_spin_lock is called.
10970  *
10971  * To enable this, lock state in the verifier captures two values:
10972  *	active_lock.ptr = Register's type specific pointer
10973  *	active_lock.id  = A unique ID for each register pointer value
10974  *
10975  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10976  * supported register types.
10977  *
10978  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10979  * allocated objects is the reg->btf pointer.
10980  *
10981  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10982  * can establish the provenance of the map value statically for each distinct
10983  * lookup into such maps. They always contain a single map value hence unique
10984  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10985  *
10986  * So, in case of global variables, they use array maps with max_entries = 1,
10987  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10988  * into the same map value as max_entries is 1, as described above).
10989  *
10990  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10991  * outer map pointer (in verifier context), but each lookup into an inner map
10992  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10993  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10994  * will get different reg->id assigned to each lookup, hence different
10995  * active_lock.id.
10996  *
10997  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10998  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10999  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11000  */
11001 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11002 {
11003 	void *ptr;
11004 	u32 id;
11005 
11006 	switch ((int)reg->type) {
11007 	case PTR_TO_MAP_VALUE:
11008 		ptr = reg->map_ptr;
11009 		break;
11010 	case PTR_TO_BTF_ID | MEM_ALLOC:
11011 		ptr = reg->btf;
11012 		break;
11013 	default:
11014 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11015 		return -EFAULT;
11016 	}
11017 	id = reg->id;
11018 
11019 	if (!env->cur_state->active_lock.ptr)
11020 		return -EINVAL;
11021 	if (env->cur_state->active_lock.ptr != ptr ||
11022 	    env->cur_state->active_lock.id != id) {
11023 		verbose(env, "held lock and object are not in the same allocation\n");
11024 		return -EINVAL;
11025 	}
11026 	return 0;
11027 }
11028 
11029 static bool is_bpf_list_api_kfunc(u32 btf_id)
11030 {
11031 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11032 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11033 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11034 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11035 }
11036 
11037 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11038 {
11039 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11040 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11041 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11042 }
11043 
11044 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11045 {
11046 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11047 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11048 }
11049 
11050 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11051 {
11052 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11053 }
11054 
11055 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11056 {
11057 	return is_bpf_rbtree_api_kfunc(btf_id);
11058 }
11059 
11060 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11061 					  enum btf_field_type head_field_type,
11062 					  u32 kfunc_btf_id)
11063 {
11064 	bool ret;
11065 
11066 	switch (head_field_type) {
11067 	case BPF_LIST_HEAD:
11068 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11069 		break;
11070 	case BPF_RB_ROOT:
11071 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11072 		break;
11073 	default:
11074 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11075 			btf_field_type_name(head_field_type));
11076 		return false;
11077 	}
11078 
11079 	if (!ret)
11080 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11081 			btf_field_type_name(head_field_type));
11082 	return ret;
11083 }
11084 
11085 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11086 					  enum btf_field_type node_field_type,
11087 					  u32 kfunc_btf_id)
11088 {
11089 	bool ret;
11090 
11091 	switch (node_field_type) {
11092 	case BPF_LIST_NODE:
11093 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11094 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11095 		break;
11096 	case BPF_RB_NODE:
11097 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11098 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11099 		break;
11100 	default:
11101 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11102 			btf_field_type_name(node_field_type));
11103 		return false;
11104 	}
11105 
11106 	if (!ret)
11107 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11108 			btf_field_type_name(node_field_type));
11109 	return ret;
11110 }
11111 
11112 static int
11113 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11114 				   struct bpf_reg_state *reg, u32 regno,
11115 				   struct bpf_kfunc_call_arg_meta *meta,
11116 				   enum btf_field_type head_field_type,
11117 				   struct btf_field **head_field)
11118 {
11119 	const char *head_type_name;
11120 	struct btf_field *field;
11121 	struct btf_record *rec;
11122 	u32 head_off;
11123 
11124 	if (meta->btf != btf_vmlinux) {
11125 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11126 		return -EFAULT;
11127 	}
11128 
11129 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11130 		return -EFAULT;
11131 
11132 	head_type_name = btf_field_type_name(head_field_type);
11133 	if (!tnum_is_const(reg->var_off)) {
11134 		verbose(env,
11135 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11136 			regno, head_type_name);
11137 		return -EINVAL;
11138 	}
11139 
11140 	rec = reg_btf_record(reg);
11141 	head_off = reg->off + reg->var_off.value;
11142 	field = btf_record_find(rec, head_off, head_field_type);
11143 	if (!field) {
11144 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11145 		return -EINVAL;
11146 	}
11147 
11148 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11149 	if (check_reg_allocation_locked(env, reg)) {
11150 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11151 			rec->spin_lock_off, head_type_name);
11152 		return -EINVAL;
11153 	}
11154 
11155 	if (*head_field) {
11156 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11157 		return -EFAULT;
11158 	}
11159 	*head_field = field;
11160 	return 0;
11161 }
11162 
11163 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11164 					   struct bpf_reg_state *reg, u32 regno,
11165 					   struct bpf_kfunc_call_arg_meta *meta)
11166 {
11167 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11168 							  &meta->arg_list_head.field);
11169 }
11170 
11171 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11172 					     struct bpf_reg_state *reg, u32 regno,
11173 					     struct bpf_kfunc_call_arg_meta *meta)
11174 {
11175 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11176 							  &meta->arg_rbtree_root.field);
11177 }
11178 
11179 static int
11180 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11181 				   struct bpf_reg_state *reg, u32 regno,
11182 				   struct bpf_kfunc_call_arg_meta *meta,
11183 				   enum btf_field_type head_field_type,
11184 				   enum btf_field_type node_field_type,
11185 				   struct btf_field **node_field)
11186 {
11187 	const char *node_type_name;
11188 	const struct btf_type *et, *t;
11189 	struct btf_field *field;
11190 	u32 node_off;
11191 
11192 	if (meta->btf != btf_vmlinux) {
11193 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11194 		return -EFAULT;
11195 	}
11196 
11197 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11198 		return -EFAULT;
11199 
11200 	node_type_name = btf_field_type_name(node_field_type);
11201 	if (!tnum_is_const(reg->var_off)) {
11202 		verbose(env,
11203 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11204 			regno, node_type_name);
11205 		return -EINVAL;
11206 	}
11207 
11208 	node_off = reg->off + reg->var_off.value;
11209 	field = reg_find_field_offset(reg, node_off, node_field_type);
11210 	if (!field || field->offset != node_off) {
11211 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11212 		return -EINVAL;
11213 	}
11214 
11215 	field = *node_field;
11216 
11217 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11218 	t = btf_type_by_id(reg->btf, reg->btf_id);
11219 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11220 				  field->graph_root.value_btf_id, true)) {
11221 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11222 			"in struct %s, but arg is at offset=%d in struct %s\n",
11223 			btf_field_type_name(head_field_type),
11224 			btf_field_type_name(node_field_type),
11225 			field->graph_root.node_offset,
11226 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11227 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11228 		return -EINVAL;
11229 	}
11230 	meta->arg_btf = reg->btf;
11231 	meta->arg_btf_id = reg->btf_id;
11232 
11233 	if (node_off != field->graph_root.node_offset) {
11234 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11235 			node_off, btf_field_type_name(node_field_type),
11236 			field->graph_root.node_offset,
11237 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11238 		return -EINVAL;
11239 	}
11240 
11241 	return 0;
11242 }
11243 
11244 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11245 					   struct bpf_reg_state *reg, u32 regno,
11246 					   struct bpf_kfunc_call_arg_meta *meta)
11247 {
11248 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11249 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11250 						  &meta->arg_list_head.field);
11251 }
11252 
11253 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11254 					     struct bpf_reg_state *reg, u32 regno,
11255 					     struct bpf_kfunc_call_arg_meta *meta)
11256 {
11257 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11258 						  BPF_RB_ROOT, BPF_RB_NODE,
11259 						  &meta->arg_rbtree_root.field);
11260 }
11261 
11262 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11263 			    int insn_idx)
11264 {
11265 	const char *func_name = meta->func_name, *ref_tname;
11266 	const struct btf *btf = meta->btf;
11267 	const struct btf_param *args;
11268 	struct btf_record *rec;
11269 	u32 i, nargs;
11270 	int ret;
11271 
11272 	args = (const struct btf_param *)(meta->func_proto + 1);
11273 	nargs = btf_type_vlen(meta->func_proto);
11274 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11275 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11276 			MAX_BPF_FUNC_REG_ARGS);
11277 		return -EINVAL;
11278 	}
11279 
11280 	/* Check that BTF function arguments match actual types that the
11281 	 * verifier sees.
11282 	 */
11283 	for (i = 0; i < nargs; i++) {
11284 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11285 		const struct btf_type *t, *ref_t, *resolve_ret;
11286 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11287 		u32 regno = i + 1, ref_id, type_size;
11288 		bool is_ret_buf_sz = false;
11289 		int kf_arg_type;
11290 
11291 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11292 
11293 		if (is_kfunc_arg_ignore(btf, &args[i]))
11294 			continue;
11295 
11296 		if (btf_type_is_scalar(t)) {
11297 			if (reg->type != SCALAR_VALUE) {
11298 				verbose(env, "R%d is not a scalar\n", regno);
11299 				return -EINVAL;
11300 			}
11301 
11302 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11303 				if (meta->arg_constant.found) {
11304 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11305 					return -EFAULT;
11306 				}
11307 				if (!tnum_is_const(reg->var_off)) {
11308 					verbose(env, "R%d must be a known constant\n", regno);
11309 					return -EINVAL;
11310 				}
11311 				ret = mark_chain_precision(env, regno);
11312 				if (ret < 0)
11313 					return ret;
11314 				meta->arg_constant.found = true;
11315 				meta->arg_constant.value = reg->var_off.value;
11316 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11317 				meta->r0_rdonly = true;
11318 				is_ret_buf_sz = true;
11319 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11320 				is_ret_buf_sz = true;
11321 			}
11322 
11323 			if (is_ret_buf_sz) {
11324 				if (meta->r0_size) {
11325 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11326 					return -EINVAL;
11327 				}
11328 
11329 				if (!tnum_is_const(reg->var_off)) {
11330 					verbose(env, "R%d is not a const\n", regno);
11331 					return -EINVAL;
11332 				}
11333 
11334 				meta->r0_size = reg->var_off.value;
11335 				ret = mark_chain_precision(env, regno);
11336 				if (ret)
11337 					return ret;
11338 			}
11339 			continue;
11340 		}
11341 
11342 		if (!btf_type_is_ptr(t)) {
11343 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11344 			return -EINVAL;
11345 		}
11346 
11347 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11348 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11349 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11350 			return -EACCES;
11351 		}
11352 
11353 		if (reg->ref_obj_id) {
11354 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11355 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11356 					regno, reg->ref_obj_id,
11357 					meta->ref_obj_id);
11358 				return -EFAULT;
11359 			}
11360 			meta->ref_obj_id = reg->ref_obj_id;
11361 			if (is_kfunc_release(meta))
11362 				meta->release_regno = regno;
11363 		}
11364 
11365 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11366 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11367 
11368 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11369 		if (kf_arg_type < 0)
11370 			return kf_arg_type;
11371 
11372 		switch (kf_arg_type) {
11373 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11374 		case KF_ARG_PTR_TO_BTF_ID:
11375 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11376 				break;
11377 
11378 			if (!is_trusted_reg(reg)) {
11379 				if (!is_kfunc_rcu(meta)) {
11380 					verbose(env, "R%d must be referenced or trusted\n", regno);
11381 					return -EINVAL;
11382 				}
11383 				if (!is_rcu_reg(reg)) {
11384 					verbose(env, "R%d must be a rcu pointer\n", regno);
11385 					return -EINVAL;
11386 				}
11387 			}
11388 
11389 			fallthrough;
11390 		case KF_ARG_PTR_TO_CTX:
11391 			/* Trusted arguments have the same offset checks as release arguments */
11392 			arg_type |= OBJ_RELEASE;
11393 			break;
11394 		case KF_ARG_PTR_TO_DYNPTR:
11395 		case KF_ARG_PTR_TO_ITER:
11396 		case KF_ARG_PTR_TO_LIST_HEAD:
11397 		case KF_ARG_PTR_TO_LIST_NODE:
11398 		case KF_ARG_PTR_TO_RB_ROOT:
11399 		case KF_ARG_PTR_TO_RB_NODE:
11400 		case KF_ARG_PTR_TO_MEM:
11401 		case KF_ARG_PTR_TO_MEM_SIZE:
11402 		case KF_ARG_PTR_TO_CALLBACK:
11403 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11404 			/* Trusted by default */
11405 			break;
11406 		default:
11407 			WARN_ON_ONCE(1);
11408 			return -EFAULT;
11409 		}
11410 
11411 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11412 			arg_type |= OBJ_RELEASE;
11413 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11414 		if (ret < 0)
11415 			return ret;
11416 
11417 		switch (kf_arg_type) {
11418 		case KF_ARG_PTR_TO_CTX:
11419 			if (reg->type != PTR_TO_CTX) {
11420 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11421 				return -EINVAL;
11422 			}
11423 
11424 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11425 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11426 				if (ret < 0)
11427 					return -EINVAL;
11428 				meta->ret_btf_id  = ret;
11429 			}
11430 			break;
11431 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11432 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11433 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11434 				return -EINVAL;
11435 			}
11436 			if (!reg->ref_obj_id) {
11437 				verbose(env, "allocated object must be referenced\n");
11438 				return -EINVAL;
11439 			}
11440 			if (meta->btf == btf_vmlinux &&
11441 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11442 				meta->arg_btf = reg->btf;
11443 				meta->arg_btf_id = reg->btf_id;
11444 			}
11445 			break;
11446 		case KF_ARG_PTR_TO_DYNPTR:
11447 		{
11448 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11449 			int clone_ref_obj_id = 0;
11450 
11451 			if (reg->type != PTR_TO_STACK &&
11452 			    reg->type != CONST_PTR_TO_DYNPTR) {
11453 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11454 				return -EINVAL;
11455 			}
11456 
11457 			if (reg->type == CONST_PTR_TO_DYNPTR)
11458 				dynptr_arg_type |= MEM_RDONLY;
11459 
11460 			if (is_kfunc_arg_uninit(btf, &args[i]))
11461 				dynptr_arg_type |= MEM_UNINIT;
11462 
11463 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11464 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11465 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11466 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11467 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11468 				   (dynptr_arg_type & MEM_UNINIT)) {
11469 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11470 
11471 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11472 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11473 					return -EFAULT;
11474 				}
11475 
11476 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11477 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11478 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11479 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11480 					return -EFAULT;
11481 				}
11482 			}
11483 
11484 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11485 			if (ret < 0)
11486 				return ret;
11487 
11488 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11489 				int id = dynptr_id(env, reg);
11490 
11491 				if (id < 0) {
11492 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11493 					return id;
11494 				}
11495 				meta->initialized_dynptr.id = id;
11496 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11497 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11498 			}
11499 
11500 			break;
11501 		}
11502 		case KF_ARG_PTR_TO_ITER:
11503 			ret = process_iter_arg(env, regno, insn_idx, meta);
11504 			if (ret < 0)
11505 				return ret;
11506 			break;
11507 		case KF_ARG_PTR_TO_LIST_HEAD:
11508 			if (reg->type != PTR_TO_MAP_VALUE &&
11509 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11510 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11511 				return -EINVAL;
11512 			}
11513 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11514 				verbose(env, "allocated object must be referenced\n");
11515 				return -EINVAL;
11516 			}
11517 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11518 			if (ret < 0)
11519 				return ret;
11520 			break;
11521 		case KF_ARG_PTR_TO_RB_ROOT:
11522 			if (reg->type != PTR_TO_MAP_VALUE &&
11523 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11524 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11525 				return -EINVAL;
11526 			}
11527 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11528 				verbose(env, "allocated object must be referenced\n");
11529 				return -EINVAL;
11530 			}
11531 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11532 			if (ret < 0)
11533 				return ret;
11534 			break;
11535 		case KF_ARG_PTR_TO_LIST_NODE:
11536 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11537 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11538 				return -EINVAL;
11539 			}
11540 			if (!reg->ref_obj_id) {
11541 				verbose(env, "allocated object must be referenced\n");
11542 				return -EINVAL;
11543 			}
11544 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11545 			if (ret < 0)
11546 				return ret;
11547 			break;
11548 		case KF_ARG_PTR_TO_RB_NODE:
11549 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11550 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11551 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11552 					return -EINVAL;
11553 				}
11554 				if (in_rbtree_lock_required_cb(env)) {
11555 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11556 					return -EINVAL;
11557 				}
11558 			} else {
11559 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11560 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11561 					return -EINVAL;
11562 				}
11563 				if (!reg->ref_obj_id) {
11564 					verbose(env, "allocated object must be referenced\n");
11565 					return -EINVAL;
11566 				}
11567 			}
11568 
11569 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11570 			if (ret < 0)
11571 				return ret;
11572 			break;
11573 		case KF_ARG_PTR_TO_BTF_ID:
11574 			/* Only base_type is checked, further checks are done here */
11575 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11576 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11577 			    !reg2btf_ids[base_type(reg->type)]) {
11578 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11579 				verbose(env, "expected %s or socket\n",
11580 					reg_type_str(env, base_type(reg->type) |
11581 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11582 				return -EINVAL;
11583 			}
11584 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11585 			if (ret < 0)
11586 				return ret;
11587 			break;
11588 		case KF_ARG_PTR_TO_MEM:
11589 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11590 			if (IS_ERR(resolve_ret)) {
11591 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11592 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11593 				return -EINVAL;
11594 			}
11595 			ret = check_mem_reg(env, reg, regno, type_size);
11596 			if (ret < 0)
11597 				return ret;
11598 			break;
11599 		case KF_ARG_PTR_TO_MEM_SIZE:
11600 		{
11601 			struct bpf_reg_state *buff_reg = &regs[regno];
11602 			const struct btf_param *buff_arg = &args[i];
11603 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11604 			const struct btf_param *size_arg = &args[i + 1];
11605 
11606 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11607 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11608 				if (ret < 0) {
11609 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11610 					return ret;
11611 				}
11612 			}
11613 
11614 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11615 				if (meta->arg_constant.found) {
11616 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11617 					return -EFAULT;
11618 				}
11619 				if (!tnum_is_const(size_reg->var_off)) {
11620 					verbose(env, "R%d must be a known constant\n", regno + 1);
11621 					return -EINVAL;
11622 				}
11623 				meta->arg_constant.found = true;
11624 				meta->arg_constant.value = size_reg->var_off.value;
11625 			}
11626 
11627 			/* Skip next '__sz' or '__szk' argument */
11628 			i++;
11629 			break;
11630 		}
11631 		case KF_ARG_PTR_TO_CALLBACK:
11632 			if (reg->type != PTR_TO_FUNC) {
11633 				verbose(env, "arg%d expected pointer to func\n", i);
11634 				return -EINVAL;
11635 			}
11636 			meta->subprogno = reg->subprogno;
11637 			break;
11638 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11639 			if (!type_is_ptr_alloc_obj(reg->type)) {
11640 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11641 				return -EINVAL;
11642 			}
11643 			if (!type_is_non_owning_ref(reg->type))
11644 				meta->arg_owning_ref = true;
11645 
11646 			rec = reg_btf_record(reg);
11647 			if (!rec) {
11648 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11649 				return -EFAULT;
11650 			}
11651 
11652 			if (rec->refcount_off < 0) {
11653 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11654 				return -EINVAL;
11655 			}
11656 
11657 			meta->arg_btf = reg->btf;
11658 			meta->arg_btf_id = reg->btf_id;
11659 			break;
11660 		}
11661 	}
11662 
11663 	if (is_kfunc_release(meta) && !meta->release_regno) {
11664 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11665 			func_name);
11666 		return -EINVAL;
11667 	}
11668 
11669 	return 0;
11670 }
11671 
11672 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11673 			    struct bpf_insn *insn,
11674 			    struct bpf_kfunc_call_arg_meta *meta,
11675 			    const char **kfunc_name)
11676 {
11677 	const struct btf_type *func, *func_proto;
11678 	u32 func_id, *kfunc_flags;
11679 	const char *func_name;
11680 	struct btf *desc_btf;
11681 
11682 	if (kfunc_name)
11683 		*kfunc_name = NULL;
11684 
11685 	if (!insn->imm)
11686 		return -EINVAL;
11687 
11688 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11689 	if (IS_ERR(desc_btf))
11690 		return PTR_ERR(desc_btf);
11691 
11692 	func_id = insn->imm;
11693 	func = btf_type_by_id(desc_btf, func_id);
11694 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11695 	if (kfunc_name)
11696 		*kfunc_name = func_name;
11697 	func_proto = btf_type_by_id(desc_btf, func->type);
11698 
11699 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11700 	if (!kfunc_flags) {
11701 		return -EACCES;
11702 	}
11703 
11704 	memset(meta, 0, sizeof(*meta));
11705 	meta->btf = desc_btf;
11706 	meta->func_id = func_id;
11707 	meta->kfunc_flags = *kfunc_flags;
11708 	meta->func_proto = func_proto;
11709 	meta->func_name = func_name;
11710 
11711 	return 0;
11712 }
11713 
11714 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11715 			    int *insn_idx_p)
11716 {
11717 	const struct btf_type *t, *ptr_type;
11718 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11719 	struct bpf_reg_state *regs = cur_regs(env);
11720 	const char *func_name, *ptr_type_name;
11721 	bool sleepable, rcu_lock, rcu_unlock;
11722 	struct bpf_kfunc_call_arg_meta meta;
11723 	struct bpf_insn_aux_data *insn_aux;
11724 	int err, insn_idx = *insn_idx_p;
11725 	const struct btf_param *args;
11726 	const struct btf_type *ret_t;
11727 	struct btf *desc_btf;
11728 
11729 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11730 	if (!insn->imm)
11731 		return 0;
11732 
11733 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11734 	if (err == -EACCES && func_name)
11735 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11736 	if (err)
11737 		return err;
11738 	desc_btf = meta.btf;
11739 	insn_aux = &env->insn_aux_data[insn_idx];
11740 
11741 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11742 
11743 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11744 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11745 		return -EACCES;
11746 	}
11747 
11748 	sleepable = is_kfunc_sleepable(&meta);
11749 	if (sleepable && !env->prog->aux->sleepable) {
11750 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11751 		return -EACCES;
11752 	}
11753 
11754 	/* Check the arguments */
11755 	err = check_kfunc_args(env, &meta, insn_idx);
11756 	if (err < 0)
11757 		return err;
11758 
11759 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11760 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11761 					 set_rbtree_add_callback_state);
11762 		if (err) {
11763 			verbose(env, "kfunc %s#%d failed callback verification\n",
11764 				func_name, meta.func_id);
11765 			return err;
11766 		}
11767 	}
11768 
11769 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11770 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11771 
11772 	if (env->cur_state->active_rcu_lock) {
11773 		struct bpf_func_state *state;
11774 		struct bpf_reg_state *reg;
11775 
11776 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11777 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11778 			return -EACCES;
11779 		}
11780 
11781 		if (rcu_lock) {
11782 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11783 			return -EINVAL;
11784 		} else if (rcu_unlock) {
11785 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11786 				if (reg->type & MEM_RCU) {
11787 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11788 					reg->type |= PTR_UNTRUSTED;
11789 				}
11790 			}));
11791 			env->cur_state->active_rcu_lock = false;
11792 		} else if (sleepable) {
11793 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11794 			return -EACCES;
11795 		}
11796 	} else if (rcu_lock) {
11797 		env->cur_state->active_rcu_lock = true;
11798 	} else if (rcu_unlock) {
11799 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11800 		return -EINVAL;
11801 	}
11802 
11803 	/* In case of release function, we get register number of refcounted
11804 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11805 	 */
11806 	if (meta.release_regno) {
11807 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11808 		if (err) {
11809 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11810 				func_name, meta.func_id);
11811 			return err;
11812 		}
11813 	}
11814 
11815 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11816 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11817 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11818 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11819 		insn_aux->insert_off = regs[BPF_REG_2].off;
11820 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11821 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11822 		if (err) {
11823 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11824 				func_name, meta.func_id);
11825 			return err;
11826 		}
11827 
11828 		err = release_reference(env, release_ref_obj_id);
11829 		if (err) {
11830 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11831 				func_name, meta.func_id);
11832 			return err;
11833 		}
11834 	}
11835 
11836 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11837 		mark_reg_not_init(env, regs, caller_saved[i]);
11838 
11839 	/* Check return type */
11840 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11841 
11842 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11843 		/* Only exception is bpf_obj_new_impl */
11844 		if (meta.btf != btf_vmlinux ||
11845 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11846 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11847 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11848 			return -EINVAL;
11849 		}
11850 	}
11851 
11852 	if (btf_type_is_scalar(t)) {
11853 		mark_reg_unknown(env, regs, BPF_REG_0);
11854 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11855 	} else if (btf_type_is_ptr(t)) {
11856 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11857 
11858 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11859 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11860 				struct btf *ret_btf;
11861 				u32 ret_btf_id;
11862 
11863 				if (unlikely(!bpf_global_ma_set))
11864 					return -ENOMEM;
11865 
11866 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11867 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11868 					return -EINVAL;
11869 				}
11870 
11871 				ret_btf = env->prog->aux->btf;
11872 				ret_btf_id = meta.arg_constant.value;
11873 
11874 				/* This may be NULL due to user not supplying a BTF */
11875 				if (!ret_btf) {
11876 					verbose(env, "bpf_obj_new requires prog BTF\n");
11877 					return -EINVAL;
11878 				}
11879 
11880 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11881 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11882 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11883 					return -EINVAL;
11884 				}
11885 
11886 				mark_reg_known_zero(env, regs, BPF_REG_0);
11887 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11888 				regs[BPF_REG_0].btf = ret_btf;
11889 				regs[BPF_REG_0].btf_id = ret_btf_id;
11890 
11891 				insn_aux->obj_new_size = ret_t->size;
11892 				insn_aux->kptr_struct_meta =
11893 					btf_find_struct_meta(ret_btf, ret_btf_id);
11894 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11895 				mark_reg_known_zero(env, regs, BPF_REG_0);
11896 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11897 				regs[BPF_REG_0].btf = meta.arg_btf;
11898 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11899 
11900 				insn_aux->kptr_struct_meta =
11901 					btf_find_struct_meta(meta.arg_btf,
11902 							     meta.arg_btf_id);
11903 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11904 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11905 				struct btf_field *field = meta.arg_list_head.field;
11906 
11907 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11908 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11909 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11910 				struct btf_field *field = meta.arg_rbtree_root.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_cast_to_kern_ctx]) {
11914 				mark_reg_known_zero(env, regs, BPF_REG_0);
11915 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11916 				regs[BPF_REG_0].btf = desc_btf;
11917 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11918 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11919 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11920 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11921 					verbose(env,
11922 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11923 					return -EINVAL;
11924 				}
11925 
11926 				mark_reg_known_zero(env, regs, BPF_REG_0);
11927 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11928 				regs[BPF_REG_0].btf = desc_btf;
11929 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11930 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11931 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11932 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11933 
11934 				mark_reg_known_zero(env, regs, BPF_REG_0);
11935 
11936 				if (!meta.arg_constant.found) {
11937 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11938 					return -EFAULT;
11939 				}
11940 
11941 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11942 
11943 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11944 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11945 
11946 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11947 					regs[BPF_REG_0].type |= MEM_RDONLY;
11948 				} else {
11949 					/* this will set env->seen_direct_write to true */
11950 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11951 						verbose(env, "the prog does not allow writes to packet data\n");
11952 						return -EINVAL;
11953 					}
11954 				}
11955 
11956 				if (!meta.initialized_dynptr.id) {
11957 					verbose(env, "verifier internal error: no dynptr id\n");
11958 					return -EFAULT;
11959 				}
11960 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11961 
11962 				/* we don't need to set BPF_REG_0's ref obj id
11963 				 * because packet slices are not refcounted (see
11964 				 * dynptr_type_refcounted)
11965 				 */
11966 			} else {
11967 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11968 					meta.func_name);
11969 				return -EFAULT;
11970 			}
11971 		} else if (!__btf_type_is_struct(ptr_type)) {
11972 			if (!meta.r0_size) {
11973 				__u32 sz;
11974 
11975 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11976 					meta.r0_size = sz;
11977 					meta.r0_rdonly = true;
11978 				}
11979 			}
11980 			if (!meta.r0_size) {
11981 				ptr_type_name = btf_name_by_offset(desc_btf,
11982 								   ptr_type->name_off);
11983 				verbose(env,
11984 					"kernel function %s returns pointer type %s %s is not supported\n",
11985 					func_name,
11986 					btf_type_str(ptr_type),
11987 					ptr_type_name);
11988 				return -EINVAL;
11989 			}
11990 
11991 			mark_reg_known_zero(env, regs, BPF_REG_0);
11992 			regs[BPF_REG_0].type = PTR_TO_MEM;
11993 			regs[BPF_REG_0].mem_size = meta.r0_size;
11994 
11995 			if (meta.r0_rdonly)
11996 				regs[BPF_REG_0].type |= MEM_RDONLY;
11997 
11998 			/* Ensures we don't access the memory after a release_reference() */
11999 			if (meta.ref_obj_id)
12000 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12001 		} else {
12002 			mark_reg_known_zero(env, regs, BPF_REG_0);
12003 			regs[BPF_REG_0].btf = desc_btf;
12004 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12005 			regs[BPF_REG_0].btf_id = ptr_type_id;
12006 
12007 			if (is_iter_next_kfunc(&meta)) {
12008 				struct bpf_reg_state *cur_iter;
12009 
12010 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12011 
12012 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12013 					regs[BPF_REG_0].type |= MEM_RCU;
12014 				else
12015 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12016 			}
12017 		}
12018 
12019 		if (is_kfunc_ret_null(&meta)) {
12020 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12021 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12022 			regs[BPF_REG_0].id = ++env->id_gen;
12023 		}
12024 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12025 		if (is_kfunc_acquire(&meta)) {
12026 			int id = acquire_reference_state(env, insn_idx);
12027 
12028 			if (id < 0)
12029 				return id;
12030 			if (is_kfunc_ret_null(&meta))
12031 				regs[BPF_REG_0].id = id;
12032 			regs[BPF_REG_0].ref_obj_id = id;
12033 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12034 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12035 		}
12036 
12037 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12038 			regs[BPF_REG_0].id = ++env->id_gen;
12039 	} else if (btf_type_is_void(t)) {
12040 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12041 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12042 				insn_aux->kptr_struct_meta =
12043 					btf_find_struct_meta(meta.arg_btf,
12044 							     meta.arg_btf_id);
12045 			}
12046 		}
12047 	}
12048 
12049 	nargs = btf_type_vlen(meta.func_proto);
12050 	args = (const struct btf_param *)(meta.func_proto + 1);
12051 	for (i = 0; i < nargs; i++) {
12052 		u32 regno = i + 1;
12053 
12054 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12055 		if (btf_type_is_ptr(t))
12056 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12057 		else
12058 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12059 			mark_btf_func_reg_size(env, regno, t->size);
12060 	}
12061 
12062 	if (is_iter_next_kfunc(&meta)) {
12063 		err = process_iter_next_call(env, insn_idx, &meta);
12064 		if (err)
12065 			return err;
12066 	}
12067 
12068 	return 0;
12069 }
12070 
12071 static bool signed_add_overflows(s64 a, s64 b)
12072 {
12073 	/* Do the add in u64, where overflow is well-defined */
12074 	s64 res = (s64)((u64)a + (u64)b);
12075 
12076 	if (b < 0)
12077 		return res > a;
12078 	return res < a;
12079 }
12080 
12081 static bool signed_add32_overflows(s32 a, s32 b)
12082 {
12083 	/* Do the add in u32, where overflow is well-defined */
12084 	s32 res = (s32)((u32)a + (u32)b);
12085 
12086 	if (b < 0)
12087 		return res > a;
12088 	return res < a;
12089 }
12090 
12091 static bool signed_sub_overflows(s64 a, s64 b)
12092 {
12093 	/* Do the sub in u64, where overflow is well-defined */
12094 	s64 res = (s64)((u64)a - (u64)b);
12095 
12096 	if (b < 0)
12097 		return res < a;
12098 	return res > a;
12099 }
12100 
12101 static bool signed_sub32_overflows(s32 a, s32 b)
12102 {
12103 	/* Do the sub in u32, where overflow is well-defined */
12104 	s32 res = (s32)((u32)a - (u32)b);
12105 
12106 	if (b < 0)
12107 		return res < a;
12108 	return res > a;
12109 }
12110 
12111 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12112 				  const struct bpf_reg_state *reg,
12113 				  enum bpf_reg_type type)
12114 {
12115 	bool known = tnum_is_const(reg->var_off);
12116 	s64 val = reg->var_off.value;
12117 	s64 smin = reg->smin_value;
12118 
12119 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12120 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12121 			reg_type_str(env, type), val);
12122 		return false;
12123 	}
12124 
12125 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12126 		verbose(env, "%s pointer offset %d is not allowed\n",
12127 			reg_type_str(env, type), reg->off);
12128 		return false;
12129 	}
12130 
12131 	if (smin == S64_MIN) {
12132 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12133 			reg_type_str(env, type));
12134 		return false;
12135 	}
12136 
12137 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12138 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12139 			smin, reg_type_str(env, type));
12140 		return false;
12141 	}
12142 
12143 	return true;
12144 }
12145 
12146 enum {
12147 	REASON_BOUNDS	= -1,
12148 	REASON_TYPE	= -2,
12149 	REASON_PATHS	= -3,
12150 	REASON_LIMIT	= -4,
12151 	REASON_STACK	= -5,
12152 };
12153 
12154 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12155 			      u32 *alu_limit, bool mask_to_left)
12156 {
12157 	u32 max = 0, ptr_limit = 0;
12158 
12159 	switch (ptr_reg->type) {
12160 	case PTR_TO_STACK:
12161 		/* Offset 0 is out-of-bounds, but acceptable start for the
12162 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12163 		 * offset where we would need to deal with min/max bounds is
12164 		 * currently prohibited for unprivileged.
12165 		 */
12166 		max = MAX_BPF_STACK + mask_to_left;
12167 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12168 		break;
12169 	case PTR_TO_MAP_VALUE:
12170 		max = ptr_reg->map_ptr->value_size;
12171 		ptr_limit = (mask_to_left ?
12172 			     ptr_reg->smin_value :
12173 			     ptr_reg->umax_value) + ptr_reg->off;
12174 		break;
12175 	default:
12176 		return REASON_TYPE;
12177 	}
12178 
12179 	if (ptr_limit >= max)
12180 		return REASON_LIMIT;
12181 	*alu_limit = ptr_limit;
12182 	return 0;
12183 }
12184 
12185 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12186 				    const struct bpf_insn *insn)
12187 {
12188 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12189 }
12190 
12191 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12192 				       u32 alu_state, u32 alu_limit)
12193 {
12194 	/* If we arrived here from different branches with different
12195 	 * state or limits to sanitize, then this won't work.
12196 	 */
12197 	if (aux->alu_state &&
12198 	    (aux->alu_state != alu_state ||
12199 	     aux->alu_limit != alu_limit))
12200 		return REASON_PATHS;
12201 
12202 	/* Corresponding fixup done in do_misc_fixups(). */
12203 	aux->alu_state = alu_state;
12204 	aux->alu_limit = alu_limit;
12205 	return 0;
12206 }
12207 
12208 static int sanitize_val_alu(struct bpf_verifier_env *env,
12209 			    struct bpf_insn *insn)
12210 {
12211 	struct bpf_insn_aux_data *aux = cur_aux(env);
12212 
12213 	if (can_skip_alu_sanitation(env, insn))
12214 		return 0;
12215 
12216 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12217 }
12218 
12219 static bool sanitize_needed(u8 opcode)
12220 {
12221 	return opcode == BPF_ADD || opcode == BPF_SUB;
12222 }
12223 
12224 struct bpf_sanitize_info {
12225 	struct bpf_insn_aux_data aux;
12226 	bool mask_to_left;
12227 };
12228 
12229 static struct bpf_verifier_state *
12230 sanitize_speculative_path(struct bpf_verifier_env *env,
12231 			  const struct bpf_insn *insn,
12232 			  u32 next_idx, u32 curr_idx)
12233 {
12234 	struct bpf_verifier_state *branch;
12235 	struct bpf_reg_state *regs;
12236 
12237 	branch = push_stack(env, next_idx, curr_idx, true);
12238 	if (branch && insn) {
12239 		regs = branch->frame[branch->curframe]->regs;
12240 		if (BPF_SRC(insn->code) == BPF_K) {
12241 			mark_reg_unknown(env, regs, insn->dst_reg);
12242 		} else if (BPF_SRC(insn->code) == BPF_X) {
12243 			mark_reg_unknown(env, regs, insn->dst_reg);
12244 			mark_reg_unknown(env, regs, insn->src_reg);
12245 		}
12246 	}
12247 	return branch;
12248 }
12249 
12250 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12251 			    struct bpf_insn *insn,
12252 			    const struct bpf_reg_state *ptr_reg,
12253 			    const struct bpf_reg_state *off_reg,
12254 			    struct bpf_reg_state *dst_reg,
12255 			    struct bpf_sanitize_info *info,
12256 			    const bool commit_window)
12257 {
12258 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12259 	struct bpf_verifier_state *vstate = env->cur_state;
12260 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12261 	bool off_is_neg = off_reg->smin_value < 0;
12262 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12263 	u8 opcode = BPF_OP(insn->code);
12264 	u32 alu_state, alu_limit;
12265 	struct bpf_reg_state tmp;
12266 	bool ret;
12267 	int err;
12268 
12269 	if (can_skip_alu_sanitation(env, insn))
12270 		return 0;
12271 
12272 	/* We already marked aux for masking from non-speculative
12273 	 * paths, thus we got here in the first place. We only care
12274 	 * to explore bad access from here.
12275 	 */
12276 	if (vstate->speculative)
12277 		goto do_sim;
12278 
12279 	if (!commit_window) {
12280 		if (!tnum_is_const(off_reg->var_off) &&
12281 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12282 			return REASON_BOUNDS;
12283 
12284 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12285 				     (opcode == BPF_SUB && !off_is_neg);
12286 	}
12287 
12288 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12289 	if (err < 0)
12290 		return err;
12291 
12292 	if (commit_window) {
12293 		/* In commit phase we narrow the masking window based on
12294 		 * the observed pointer move after the simulated operation.
12295 		 */
12296 		alu_state = info->aux.alu_state;
12297 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12298 	} else {
12299 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12300 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12301 		alu_state |= ptr_is_dst_reg ?
12302 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12303 
12304 		/* Limit pruning on unknown scalars to enable deep search for
12305 		 * potential masking differences from other program paths.
12306 		 */
12307 		if (!off_is_imm)
12308 			env->explore_alu_limits = true;
12309 	}
12310 
12311 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12312 	if (err < 0)
12313 		return err;
12314 do_sim:
12315 	/* If we're in commit phase, we're done here given we already
12316 	 * pushed the truncated dst_reg into the speculative verification
12317 	 * stack.
12318 	 *
12319 	 * Also, when register is a known constant, we rewrite register-based
12320 	 * operation to immediate-based, and thus do not need masking (and as
12321 	 * a consequence, do not need to simulate the zero-truncation either).
12322 	 */
12323 	if (commit_window || off_is_imm)
12324 		return 0;
12325 
12326 	/* Simulate and find potential out-of-bounds access under
12327 	 * speculative execution from truncation as a result of
12328 	 * masking when off was not within expected range. If off
12329 	 * sits in dst, then we temporarily need to move ptr there
12330 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12331 	 * for cases where we use K-based arithmetic in one direction
12332 	 * and truncated reg-based in the other in order to explore
12333 	 * bad access.
12334 	 */
12335 	if (!ptr_is_dst_reg) {
12336 		tmp = *dst_reg;
12337 		copy_register_state(dst_reg, ptr_reg);
12338 	}
12339 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12340 					env->insn_idx);
12341 	if (!ptr_is_dst_reg && ret)
12342 		*dst_reg = tmp;
12343 	return !ret ? REASON_STACK : 0;
12344 }
12345 
12346 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12347 {
12348 	struct bpf_verifier_state *vstate = env->cur_state;
12349 
12350 	/* If we simulate paths under speculation, we don't update the
12351 	 * insn as 'seen' such that when we verify unreachable paths in
12352 	 * the non-speculative domain, sanitize_dead_code() can still
12353 	 * rewrite/sanitize them.
12354 	 */
12355 	if (!vstate->speculative)
12356 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12357 }
12358 
12359 static int sanitize_err(struct bpf_verifier_env *env,
12360 			const struct bpf_insn *insn, int reason,
12361 			const struct bpf_reg_state *off_reg,
12362 			const struct bpf_reg_state *dst_reg)
12363 {
12364 	static const char *err = "pointer arithmetic with it prohibited for !root";
12365 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12366 	u32 dst = insn->dst_reg, src = insn->src_reg;
12367 
12368 	switch (reason) {
12369 	case REASON_BOUNDS:
12370 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12371 			off_reg == dst_reg ? dst : src, err);
12372 		break;
12373 	case REASON_TYPE:
12374 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12375 			off_reg == dst_reg ? src : dst, err);
12376 		break;
12377 	case REASON_PATHS:
12378 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12379 			dst, op, err);
12380 		break;
12381 	case REASON_LIMIT:
12382 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12383 			dst, op, err);
12384 		break;
12385 	case REASON_STACK:
12386 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12387 			dst, err);
12388 		break;
12389 	default:
12390 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12391 			reason);
12392 		break;
12393 	}
12394 
12395 	return -EACCES;
12396 }
12397 
12398 /* check that stack access falls within stack limits and that 'reg' doesn't
12399  * have a variable offset.
12400  *
12401  * Variable offset is prohibited for unprivileged mode for simplicity since it
12402  * requires corresponding support in Spectre masking for stack ALU.  See also
12403  * retrieve_ptr_limit().
12404  *
12405  *
12406  * 'off' includes 'reg->off'.
12407  */
12408 static int check_stack_access_for_ptr_arithmetic(
12409 				struct bpf_verifier_env *env,
12410 				int regno,
12411 				const struct bpf_reg_state *reg,
12412 				int off)
12413 {
12414 	if (!tnum_is_const(reg->var_off)) {
12415 		char tn_buf[48];
12416 
12417 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12418 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12419 			regno, tn_buf, off);
12420 		return -EACCES;
12421 	}
12422 
12423 	if (off >= 0 || off < -MAX_BPF_STACK) {
12424 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12425 			"prohibited for !root; off=%d\n", regno, off);
12426 		return -EACCES;
12427 	}
12428 
12429 	return 0;
12430 }
12431 
12432 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12433 				 const struct bpf_insn *insn,
12434 				 const struct bpf_reg_state *dst_reg)
12435 {
12436 	u32 dst = insn->dst_reg;
12437 
12438 	/* For unprivileged we require that resulting offset must be in bounds
12439 	 * in order to be able to sanitize access later on.
12440 	 */
12441 	if (env->bypass_spec_v1)
12442 		return 0;
12443 
12444 	switch (dst_reg->type) {
12445 	case PTR_TO_STACK:
12446 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12447 					dst_reg->off + dst_reg->var_off.value))
12448 			return -EACCES;
12449 		break;
12450 	case PTR_TO_MAP_VALUE:
12451 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12452 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12453 				"prohibited for !root\n", dst);
12454 			return -EACCES;
12455 		}
12456 		break;
12457 	default:
12458 		break;
12459 	}
12460 
12461 	return 0;
12462 }
12463 
12464 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12465  * Caller should also handle BPF_MOV case separately.
12466  * If we return -EACCES, caller may want to try again treating pointer as a
12467  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12468  */
12469 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12470 				   struct bpf_insn *insn,
12471 				   const struct bpf_reg_state *ptr_reg,
12472 				   const struct bpf_reg_state *off_reg)
12473 {
12474 	struct bpf_verifier_state *vstate = env->cur_state;
12475 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12476 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12477 	bool known = tnum_is_const(off_reg->var_off);
12478 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12479 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12480 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12481 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12482 	struct bpf_sanitize_info info = {};
12483 	u8 opcode = BPF_OP(insn->code);
12484 	u32 dst = insn->dst_reg;
12485 	int ret;
12486 
12487 	dst_reg = &regs[dst];
12488 
12489 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12490 	    smin_val > smax_val || umin_val > umax_val) {
12491 		/* Taint dst register if offset had invalid bounds derived from
12492 		 * e.g. dead branches.
12493 		 */
12494 		__mark_reg_unknown(env, dst_reg);
12495 		return 0;
12496 	}
12497 
12498 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12499 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12500 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12501 			__mark_reg_unknown(env, dst_reg);
12502 			return 0;
12503 		}
12504 
12505 		verbose(env,
12506 			"R%d 32-bit pointer arithmetic prohibited\n",
12507 			dst);
12508 		return -EACCES;
12509 	}
12510 
12511 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12512 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12513 			dst, reg_type_str(env, ptr_reg->type));
12514 		return -EACCES;
12515 	}
12516 
12517 	switch (base_type(ptr_reg->type)) {
12518 	case PTR_TO_FLOW_KEYS:
12519 		if (known)
12520 			break;
12521 		fallthrough;
12522 	case CONST_PTR_TO_MAP:
12523 		/* smin_val represents the known value */
12524 		if (known && smin_val == 0 && opcode == BPF_ADD)
12525 			break;
12526 		fallthrough;
12527 	case PTR_TO_PACKET_END:
12528 	case PTR_TO_SOCKET:
12529 	case PTR_TO_SOCK_COMMON:
12530 	case PTR_TO_TCP_SOCK:
12531 	case PTR_TO_XDP_SOCK:
12532 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12533 			dst, reg_type_str(env, ptr_reg->type));
12534 		return -EACCES;
12535 	default:
12536 		break;
12537 	}
12538 
12539 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12540 	 * The id may be overwritten later if we create a new variable offset.
12541 	 */
12542 	dst_reg->type = ptr_reg->type;
12543 	dst_reg->id = ptr_reg->id;
12544 
12545 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12546 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12547 		return -EINVAL;
12548 
12549 	/* pointer types do not carry 32-bit bounds at the moment. */
12550 	__mark_reg32_unbounded(dst_reg);
12551 
12552 	if (sanitize_needed(opcode)) {
12553 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12554 				       &info, false);
12555 		if (ret < 0)
12556 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12557 	}
12558 
12559 	switch (opcode) {
12560 	case BPF_ADD:
12561 		/* We can take a fixed offset as long as it doesn't overflow
12562 		 * the s32 'off' field
12563 		 */
12564 		if (known && (ptr_reg->off + smin_val ==
12565 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12566 			/* pointer += K.  Accumulate it into fixed offset */
12567 			dst_reg->smin_value = smin_ptr;
12568 			dst_reg->smax_value = smax_ptr;
12569 			dst_reg->umin_value = umin_ptr;
12570 			dst_reg->umax_value = umax_ptr;
12571 			dst_reg->var_off = ptr_reg->var_off;
12572 			dst_reg->off = ptr_reg->off + smin_val;
12573 			dst_reg->raw = ptr_reg->raw;
12574 			break;
12575 		}
12576 		/* A new variable offset is created.  Note that off_reg->off
12577 		 * == 0, since it's a scalar.
12578 		 * dst_reg gets the pointer type and since some positive
12579 		 * integer value was added to the pointer, give it a new 'id'
12580 		 * if it's a PTR_TO_PACKET.
12581 		 * this creates a new 'base' pointer, off_reg (variable) gets
12582 		 * added into the variable offset, and we copy the fixed offset
12583 		 * from ptr_reg.
12584 		 */
12585 		if (signed_add_overflows(smin_ptr, smin_val) ||
12586 		    signed_add_overflows(smax_ptr, smax_val)) {
12587 			dst_reg->smin_value = S64_MIN;
12588 			dst_reg->smax_value = S64_MAX;
12589 		} else {
12590 			dst_reg->smin_value = smin_ptr + smin_val;
12591 			dst_reg->smax_value = smax_ptr + smax_val;
12592 		}
12593 		if (umin_ptr + umin_val < umin_ptr ||
12594 		    umax_ptr + umax_val < umax_ptr) {
12595 			dst_reg->umin_value = 0;
12596 			dst_reg->umax_value = U64_MAX;
12597 		} else {
12598 			dst_reg->umin_value = umin_ptr + umin_val;
12599 			dst_reg->umax_value = umax_ptr + umax_val;
12600 		}
12601 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12602 		dst_reg->off = ptr_reg->off;
12603 		dst_reg->raw = ptr_reg->raw;
12604 		if (reg_is_pkt_pointer(ptr_reg)) {
12605 			dst_reg->id = ++env->id_gen;
12606 			/* something was added to pkt_ptr, set range to zero */
12607 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12608 		}
12609 		break;
12610 	case BPF_SUB:
12611 		if (dst_reg == off_reg) {
12612 			/* scalar -= pointer.  Creates an unknown scalar */
12613 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12614 				dst);
12615 			return -EACCES;
12616 		}
12617 		/* We don't allow subtraction from FP, because (according to
12618 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12619 		 * be able to deal with it.
12620 		 */
12621 		if (ptr_reg->type == PTR_TO_STACK) {
12622 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12623 				dst);
12624 			return -EACCES;
12625 		}
12626 		if (known && (ptr_reg->off - smin_val ==
12627 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12628 			/* pointer -= K.  Subtract it from fixed offset */
12629 			dst_reg->smin_value = smin_ptr;
12630 			dst_reg->smax_value = smax_ptr;
12631 			dst_reg->umin_value = umin_ptr;
12632 			dst_reg->umax_value = umax_ptr;
12633 			dst_reg->var_off = ptr_reg->var_off;
12634 			dst_reg->id = ptr_reg->id;
12635 			dst_reg->off = ptr_reg->off - smin_val;
12636 			dst_reg->raw = ptr_reg->raw;
12637 			break;
12638 		}
12639 		/* A new variable offset is created.  If the subtrahend is known
12640 		 * nonnegative, then any reg->range we had before is still good.
12641 		 */
12642 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12643 		    signed_sub_overflows(smax_ptr, smin_val)) {
12644 			/* Overflow possible, we know nothing */
12645 			dst_reg->smin_value = S64_MIN;
12646 			dst_reg->smax_value = S64_MAX;
12647 		} else {
12648 			dst_reg->smin_value = smin_ptr - smax_val;
12649 			dst_reg->smax_value = smax_ptr - smin_val;
12650 		}
12651 		if (umin_ptr < umax_val) {
12652 			/* Overflow possible, we know nothing */
12653 			dst_reg->umin_value = 0;
12654 			dst_reg->umax_value = U64_MAX;
12655 		} else {
12656 			/* Cannot overflow (as long as bounds are consistent) */
12657 			dst_reg->umin_value = umin_ptr - umax_val;
12658 			dst_reg->umax_value = umax_ptr - umin_val;
12659 		}
12660 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12661 		dst_reg->off = ptr_reg->off;
12662 		dst_reg->raw = ptr_reg->raw;
12663 		if (reg_is_pkt_pointer(ptr_reg)) {
12664 			dst_reg->id = ++env->id_gen;
12665 			/* something was added to pkt_ptr, set range to zero */
12666 			if (smin_val < 0)
12667 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12668 		}
12669 		break;
12670 	case BPF_AND:
12671 	case BPF_OR:
12672 	case BPF_XOR:
12673 		/* bitwise ops on pointers are troublesome, prohibit. */
12674 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12675 			dst, bpf_alu_string[opcode >> 4]);
12676 		return -EACCES;
12677 	default:
12678 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12679 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12680 			dst, bpf_alu_string[opcode >> 4]);
12681 		return -EACCES;
12682 	}
12683 
12684 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12685 		return -EINVAL;
12686 	reg_bounds_sync(dst_reg);
12687 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12688 		return -EACCES;
12689 	if (sanitize_needed(opcode)) {
12690 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12691 				       &info, true);
12692 		if (ret < 0)
12693 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12694 	}
12695 
12696 	return 0;
12697 }
12698 
12699 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12700 				 struct bpf_reg_state *src_reg)
12701 {
12702 	s32 smin_val = src_reg->s32_min_value;
12703 	s32 smax_val = src_reg->s32_max_value;
12704 	u32 umin_val = src_reg->u32_min_value;
12705 	u32 umax_val = src_reg->u32_max_value;
12706 
12707 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12708 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12709 		dst_reg->s32_min_value = S32_MIN;
12710 		dst_reg->s32_max_value = S32_MAX;
12711 	} else {
12712 		dst_reg->s32_min_value += smin_val;
12713 		dst_reg->s32_max_value += smax_val;
12714 	}
12715 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12716 	    dst_reg->u32_max_value + umax_val < umax_val) {
12717 		dst_reg->u32_min_value = 0;
12718 		dst_reg->u32_max_value = U32_MAX;
12719 	} else {
12720 		dst_reg->u32_min_value += umin_val;
12721 		dst_reg->u32_max_value += umax_val;
12722 	}
12723 }
12724 
12725 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12726 			       struct bpf_reg_state *src_reg)
12727 {
12728 	s64 smin_val = src_reg->smin_value;
12729 	s64 smax_val = src_reg->smax_value;
12730 	u64 umin_val = src_reg->umin_value;
12731 	u64 umax_val = src_reg->umax_value;
12732 
12733 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12734 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12735 		dst_reg->smin_value = S64_MIN;
12736 		dst_reg->smax_value = S64_MAX;
12737 	} else {
12738 		dst_reg->smin_value += smin_val;
12739 		dst_reg->smax_value += smax_val;
12740 	}
12741 	if (dst_reg->umin_value + umin_val < umin_val ||
12742 	    dst_reg->umax_value + umax_val < umax_val) {
12743 		dst_reg->umin_value = 0;
12744 		dst_reg->umax_value = U64_MAX;
12745 	} else {
12746 		dst_reg->umin_value += umin_val;
12747 		dst_reg->umax_value += umax_val;
12748 	}
12749 }
12750 
12751 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12752 				 struct bpf_reg_state *src_reg)
12753 {
12754 	s32 smin_val = src_reg->s32_min_value;
12755 	s32 smax_val = src_reg->s32_max_value;
12756 	u32 umin_val = src_reg->u32_min_value;
12757 	u32 umax_val = src_reg->u32_max_value;
12758 
12759 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12760 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12761 		/* Overflow possible, we know nothing */
12762 		dst_reg->s32_min_value = S32_MIN;
12763 		dst_reg->s32_max_value = S32_MAX;
12764 	} else {
12765 		dst_reg->s32_min_value -= smax_val;
12766 		dst_reg->s32_max_value -= smin_val;
12767 	}
12768 	if (dst_reg->u32_min_value < umax_val) {
12769 		/* Overflow possible, we know nothing */
12770 		dst_reg->u32_min_value = 0;
12771 		dst_reg->u32_max_value = U32_MAX;
12772 	} else {
12773 		/* Cannot overflow (as long as bounds are consistent) */
12774 		dst_reg->u32_min_value -= umax_val;
12775 		dst_reg->u32_max_value -= umin_val;
12776 	}
12777 }
12778 
12779 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12780 			       struct bpf_reg_state *src_reg)
12781 {
12782 	s64 smin_val = src_reg->smin_value;
12783 	s64 smax_val = src_reg->smax_value;
12784 	u64 umin_val = src_reg->umin_value;
12785 	u64 umax_val = src_reg->umax_value;
12786 
12787 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12788 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12789 		/* Overflow possible, we know nothing */
12790 		dst_reg->smin_value = S64_MIN;
12791 		dst_reg->smax_value = S64_MAX;
12792 	} else {
12793 		dst_reg->smin_value -= smax_val;
12794 		dst_reg->smax_value -= smin_val;
12795 	}
12796 	if (dst_reg->umin_value < umax_val) {
12797 		/* Overflow possible, we know nothing */
12798 		dst_reg->umin_value = 0;
12799 		dst_reg->umax_value = U64_MAX;
12800 	} else {
12801 		/* Cannot overflow (as long as bounds are consistent) */
12802 		dst_reg->umin_value -= umax_val;
12803 		dst_reg->umax_value -= umin_val;
12804 	}
12805 }
12806 
12807 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12808 				 struct bpf_reg_state *src_reg)
12809 {
12810 	s32 smin_val = src_reg->s32_min_value;
12811 	u32 umin_val = src_reg->u32_min_value;
12812 	u32 umax_val = src_reg->u32_max_value;
12813 
12814 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12815 		/* Ain't nobody got time to multiply that sign */
12816 		__mark_reg32_unbounded(dst_reg);
12817 		return;
12818 	}
12819 	/* Both values are positive, so we can work with unsigned and
12820 	 * copy the result to signed (unless it exceeds S32_MAX).
12821 	 */
12822 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12823 		/* Potential overflow, we know nothing */
12824 		__mark_reg32_unbounded(dst_reg);
12825 		return;
12826 	}
12827 	dst_reg->u32_min_value *= umin_val;
12828 	dst_reg->u32_max_value *= umax_val;
12829 	if (dst_reg->u32_max_value > S32_MAX) {
12830 		/* Overflow possible, we know nothing */
12831 		dst_reg->s32_min_value = S32_MIN;
12832 		dst_reg->s32_max_value = S32_MAX;
12833 	} else {
12834 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12835 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12836 	}
12837 }
12838 
12839 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12840 			       struct bpf_reg_state *src_reg)
12841 {
12842 	s64 smin_val = src_reg->smin_value;
12843 	u64 umin_val = src_reg->umin_value;
12844 	u64 umax_val = src_reg->umax_value;
12845 
12846 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12847 		/* Ain't nobody got time to multiply that sign */
12848 		__mark_reg64_unbounded(dst_reg);
12849 		return;
12850 	}
12851 	/* Both values are positive, so we can work with unsigned and
12852 	 * copy the result to signed (unless it exceeds S64_MAX).
12853 	 */
12854 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12855 		/* Potential overflow, we know nothing */
12856 		__mark_reg64_unbounded(dst_reg);
12857 		return;
12858 	}
12859 	dst_reg->umin_value *= umin_val;
12860 	dst_reg->umax_value *= umax_val;
12861 	if (dst_reg->umax_value > S64_MAX) {
12862 		/* Overflow possible, we know nothing */
12863 		dst_reg->smin_value = S64_MIN;
12864 		dst_reg->smax_value = S64_MAX;
12865 	} else {
12866 		dst_reg->smin_value = dst_reg->umin_value;
12867 		dst_reg->smax_value = dst_reg->umax_value;
12868 	}
12869 }
12870 
12871 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12872 				 struct bpf_reg_state *src_reg)
12873 {
12874 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12875 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12876 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12877 	s32 smin_val = src_reg->s32_min_value;
12878 	u32 umax_val = src_reg->u32_max_value;
12879 
12880 	if (src_known && dst_known) {
12881 		__mark_reg32_known(dst_reg, var32_off.value);
12882 		return;
12883 	}
12884 
12885 	/* We get our minimum from the var_off, since that's inherently
12886 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12887 	 */
12888 	dst_reg->u32_min_value = var32_off.value;
12889 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12890 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12891 		/* Lose signed bounds when ANDing negative numbers,
12892 		 * ain't nobody got time for that.
12893 		 */
12894 		dst_reg->s32_min_value = S32_MIN;
12895 		dst_reg->s32_max_value = S32_MAX;
12896 	} else {
12897 		/* ANDing two positives gives a positive, so safe to
12898 		 * cast result into s64.
12899 		 */
12900 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12901 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12902 	}
12903 }
12904 
12905 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12906 			       struct bpf_reg_state *src_reg)
12907 {
12908 	bool src_known = tnum_is_const(src_reg->var_off);
12909 	bool dst_known = tnum_is_const(dst_reg->var_off);
12910 	s64 smin_val = src_reg->smin_value;
12911 	u64 umax_val = src_reg->umax_value;
12912 
12913 	if (src_known && dst_known) {
12914 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12915 		return;
12916 	}
12917 
12918 	/* We get our minimum from the var_off, since that's inherently
12919 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12920 	 */
12921 	dst_reg->umin_value = dst_reg->var_off.value;
12922 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12923 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12924 		/* Lose signed bounds when ANDing negative numbers,
12925 		 * ain't nobody got time for that.
12926 		 */
12927 		dst_reg->smin_value = S64_MIN;
12928 		dst_reg->smax_value = S64_MAX;
12929 	} else {
12930 		/* ANDing two positives gives a positive, so safe to
12931 		 * cast result into s64.
12932 		 */
12933 		dst_reg->smin_value = dst_reg->umin_value;
12934 		dst_reg->smax_value = dst_reg->umax_value;
12935 	}
12936 	/* We may learn something more from the var_off */
12937 	__update_reg_bounds(dst_reg);
12938 }
12939 
12940 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12941 				struct bpf_reg_state *src_reg)
12942 {
12943 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12944 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12945 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12946 	s32 smin_val = src_reg->s32_min_value;
12947 	u32 umin_val = src_reg->u32_min_value;
12948 
12949 	if (src_known && dst_known) {
12950 		__mark_reg32_known(dst_reg, var32_off.value);
12951 		return;
12952 	}
12953 
12954 	/* We get our maximum from the var_off, and our minimum is the
12955 	 * maximum of the operands' minima
12956 	 */
12957 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12958 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12959 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12960 		/* Lose signed bounds when ORing negative numbers,
12961 		 * ain't nobody got time for that.
12962 		 */
12963 		dst_reg->s32_min_value = S32_MIN;
12964 		dst_reg->s32_max_value = S32_MAX;
12965 	} else {
12966 		/* ORing two positives gives a positive, so safe to
12967 		 * cast result into s64.
12968 		 */
12969 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12970 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12971 	}
12972 }
12973 
12974 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12975 			      struct bpf_reg_state *src_reg)
12976 {
12977 	bool src_known = tnum_is_const(src_reg->var_off);
12978 	bool dst_known = tnum_is_const(dst_reg->var_off);
12979 	s64 smin_val = src_reg->smin_value;
12980 	u64 umin_val = src_reg->umin_value;
12981 
12982 	if (src_known && dst_known) {
12983 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12984 		return;
12985 	}
12986 
12987 	/* We get our maximum from the var_off, and our minimum is the
12988 	 * maximum of the operands' minima
12989 	 */
12990 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12991 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12992 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12993 		/* Lose signed bounds when ORing negative numbers,
12994 		 * ain't nobody got time for that.
12995 		 */
12996 		dst_reg->smin_value = S64_MIN;
12997 		dst_reg->smax_value = S64_MAX;
12998 	} else {
12999 		/* ORing two positives gives a positive, so safe to
13000 		 * cast result into s64.
13001 		 */
13002 		dst_reg->smin_value = dst_reg->umin_value;
13003 		dst_reg->smax_value = dst_reg->umax_value;
13004 	}
13005 	/* We may learn something more from the var_off */
13006 	__update_reg_bounds(dst_reg);
13007 }
13008 
13009 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13010 				 struct bpf_reg_state *src_reg)
13011 {
13012 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13013 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13014 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13015 	s32 smin_val = src_reg->s32_min_value;
13016 
13017 	if (src_known && dst_known) {
13018 		__mark_reg32_known(dst_reg, var32_off.value);
13019 		return;
13020 	}
13021 
13022 	/* We get both minimum and maximum from the var32_off. */
13023 	dst_reg->u32_min_value = var32_off.value;
13024 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13025 
13026 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13027 		/* XORing two positive sign numbers gives a positive,
13028 		 * so safe to cast u32 result into s32.
13029 		 */
13030 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13031 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13032 	} else {
13033 		dst_reg->s32_min_value = S32_MIN;
13034 		dst_reg->s32_max_value = S32_MAX;
13035 	}
13036 }
13037 
13038 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13039 			       struct bpf_reg_state *src_reg)
13040 {
13041 	bool src_known = tnum_is_const(src_reg->var_off);
13042 	bool dst_known = tnum_is_const(dst_reg->var_off);
13043 	s64 smin_val = src_reg->smin_value;
13044 
13045 	if (src_known && dst_known) {
13046 		/* dst_reg->var_off.value has been updated earlier */
13047 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13048 		return;
13049 	}
13050 
13051 	/* We get both minimum and maximum from the var_off. */
13052 	dst_reg->umin_value = dst_reg->var_off.value;
13053 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13054 
13055 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13056 		/* XORing two positive sign numbers gives a positive,
13057 		 * so safe to cast u64 result into s64.
13058 		 */
13059 		dst_reg->smin_value = dst_reg->umin_value;
13060 		dst_reg->smax_value = dst_reg->umax_value;
13061 	} else {
13062 		dst_reg->smin_value = S64_MIN;
13063 		dst_reg->smax_value = S64_MAX;
13064 	}
13065 
13066 	__update_reg_bounds(dst_reg);
13067 }
13068 
13069 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13070 				   u64 umin_val, u64 umax_val)
13071 {
13072 	/* We lose all sign bit information (except what we can pick
13073 	 * up from var_off)
13074 	 */
13075 	dst_reg->s32_min_value = S32_MIN;
13076 	dst_reg->s32_max_value = S32_MAX;
13077 	/* If we might shift our top bit out, then we know nothing */
13078 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13079 		dst_reg->u32_min_value = 0;
13080 		dst_reg->u32_max_value = U32_MAX;
13081 	} else {
13082 		dst_reg->u32_min_value <<= umin_val;
13083 		dst_reg->u32_max_value <<= umax_val;
13084 	}
13085 }
13086 
13087 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13088 				 struct bpf_reg_state *src_reg)
13089 {
13090 	u32 umax_val = src_reg->u32_max_value;
13091 	u32 umin_val = src_reg->u32_min_value;
13092 	/* u32 alu operation will zext upper bits */
13093 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13094 
13095 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13096 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13097 	/* Not required but being careful mark reg64 bounds as unknown so
13098 	 * that we are forced to pick them up from tnum and zext later and
13099 	 * if some path skips this step we are still safe.
13100 	 */
13101 	__mark_reg64_unbounded(dst_reg);
13102 	__update_reg32_bounds(dst_reg);
13103 }
13104 
13105 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13106 				   u64 umin_val, u64 umax_val)
13107 {
13108 	/* Special case <<32 because it is a common compiler pattern to sign
13109 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13110 	 * positive we know this shift will also be positive so we can track
13111 	 * bounds correctly. Otherwise we lose all sign bit information except
13112 	 * what we can pick up from var_off. Perhaps we can generalize this
13113 	 * later to shifts of any length.
13114 	 */
13115 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13116 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13117 	else
13118 		dst_reg->smax_value = S64_MAX;
13119 
13120 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13121 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13122 	else
13123 		dst_reg->smin_value = S64_MIN;
13124 
13125 	/* If we might shift our top bit out, then we know nothing */
13126 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13127 		dst_reg->umin_value = 0;
13128 		dst_reg->umax_value = U64_MAX;
13129 	} else {
13130 		dst_reg->umin_value <<= umin_val;
13131 		dst_reg->umax_value <<= umax_val;
13132 	}
13133 }
13134 
13135 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13136 			       struct bpf_reg_state *src_reg)
13137 {
13138 	u64 umax_val = src_reg->umax_value;
13139 	u64 umin_val = src_reg->umin_value;
13140 
13141 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13142 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13143 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13144 
13145 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13146 	/* We may learn something more from the var_off */
13147 	__update_reg_bounds(dst_reg);
13148 }
13149 
13150 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13151 				 struct bpf_reg_state *src_reg)
13152 {
13153 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13154 	u32 umax_val = src_reg->u32_max_value;
13155 	u32 umin_val = src_reg->u32_min_value;
13156 
13157 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13158 	 * be negative, then either:
13159 	 * 1) src_reg might be zero, so the sign bit of the result is
13160 	 *    unknown, so we lose our signed bounds
13161 	 * 2) it's known negative, thus the unsigned bounds capture the
13162 	 *    signed bounds
13163 	 * 3) the signed bounds cross zero, so they tell us nothing
13164 	 *    about the result
13165 	 * If the value in dst_reg is known nonnegative, then again the
13166 	 * unsigned bounds capture the signed bounds.
13167 	 * Thus, in all cases it suffices to blow away our signed bounds
13168 	 * and rely on inferring new ones from the unsigned bounds and
13169 	 * var_off of the result.
13170 	 */
13171 	dst_reg->s32_min_value = S32_MIN;
13172 	dst_reg->s32_max_value = S32_MAX;
13173 
13174 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13175 	dst_reg->u32_min_value >>= umax_val;
13176 	dst_reg->u32_max_value >>= umin_val;
13177 
13178 	__mark_reg64_unbounded(dst_reg);
13179 	__update_reg32_bounds(dst_reg);
13180 }
13181 
13182 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13183 			       struct bpf_reg_state *src_reg)
13184 {
13185 	u64 umax_val = src_reg->umax_value;
13186 	u64 umin_val = src_reg->umin_value;
13187 
13188 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13189 	 * be negative, then either:
13190 	 * 1) src_reg might be zero, so the sign bit of the result is
13191 	 *    unknown, so we lose our signed bounds
13192 	 * 2) it's known negative, thus the unsigned bounds capture the
13193 	 *    signed bounds
13194 	 * 3) the signed bounds cross zero, so they tell us nothing
13195 	 *    about the result
13196 	 * If the value in dst_reg is known nonnegative, then again the
13197 	 * unsigned bounds capture the signed bounds.
13198 	 * Thus, in all cases it suffices to blow away our signed bounds
13199 	 * and rely on inferring new ones from the unsigned bounds and
13200 	 * var_off of the result.
13201 	 */
13202 	dst_reg->smin_value = S64_MIN;
13203 	dst_reg->smax_value = S64_MAX;
13204 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13205 	dst_reg->umin_value >>= umax_val;
13206 	dst_reg->umax_value >>= umin_val;
13207 
13208 	/* Its not easy to operate on alu32 bounds here because it depends
13209 	 * on bits being shifted in. Take easy way out and mark unbounded
13210 	 * so we can recalculate later from tnum.
13211 	 */
13212 	__mark_reg32_unbounded(dst_reg);
13213 	__update_reg_bounds(dst_reg);
13214 }
13215 
13216 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13217 				  struct bpf_reg_state *src_reg)
13218 {
13219 	u64 umin_val = src_reg->u32_min_value;
13220 
13221 	/* Upon reaching here, src_known is true and
13222 	 * umax_val is equal to umin_val.
13223 	 */
13224 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13225 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13226 
13227 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13228 
13229 	/* blow away the dst_reg umin_value/umax_value and rely on
13230 	 * dst_reg var_off to refine the result.
13231 	 */
13232 	dst_reg->u32_min_value = 0;
13233 	dst_reg->u32_max_value = U32_MAX;
13234 
13235 	__mark_reg64_unbounded(dst_reg);
13236 	__update_reg32_bounds(dst_reg);
13237 }
13238 
13239 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13240 				struct bpf_reg_state *src_reg)
13241 {
13242 	u64 umin_val = src_reg->umin_value;
13243 
13244 	/* Upon reaching here, src_known is true and umax_val is equal
13245 	 * to umin_val.
13246 	 */
13247 	dst_reg->smin_value >>= umin_val;
13248 	dst_reg->smax_value >>= umin_val;
13249 
13250 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13251 
13252 	/* blow away the dst_reg umin_value/umax_value and rely on
13253 	 * dst_reg var_off to refine the result.
13254 	 */
13255 	dst_reg->umin_value = 0;
13256 	dst_reg->umax_value = U64_MAX;
13257 
13258 	/* Its not easy to operate on alu32 bounds here because it depends
13259 	 * on bits being shifted in from upper 32-bits. Take easy way out
13260 	 * and mark unbounded so we can recalculate later from tnum.
13261 	 */
13262 	__mark_reg32_unbounded(dst_reg);
13263 	__update_reg_bounds(dst_reg);
13264 }
13265 
13266 /* WARNING: This function does calculations on 64-bit values, but the actual
13267  * execution may occur on 32-bit values. Therefore, things like bitshifts
13268  * need extra checks in the 32-bit case.
13269  */
13270 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13271 				      struct bpf_insn *insn,
13272 				      struct bpf_reg_state *dst_reg,
13273 				      struct bpf_reg_state src_reg)
13274 {
13275 	struct bpf_reg_state *regs = cur_regs(env);
13276 	u8 opcode = BPF_OP(insn->code);
13277 	bool src_known;
13278 	s64 smin_val, smax_val;
13279 	u64 umin_val, umax_val;
13280 	s32 s32_min_val, s32_max_val;
13281 	u32 u32_min_val, u32_max_val;
13282 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13283 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13284 	int ret;
13285 
13286 	smin_val = src_reg.smin_value;
13287 	smax_val = src_reg.smax_value;
13288 	umin_val = src_reg.umin_value;
13289 	umax_val = src_reg.umax_value;
13290 
13291 	s32_min_val = src_reg.s32_min_value;
13292 	s32_max_val = src_reg.s32_max_value;
13293 	u32_min_val = src_reg.u32_min_value;
13294 	u32_max_val = src_reg.u32_max_value;
13295 
13296 	if (alu32) {
13297 		src_known = tnum_subreg_is_const(src_reg.var_off);
13298 		if ((src_known &&
13299 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13300 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13301 			/* Taint dst register if offset had invalid bounds
13302 			 * derived from e.g. dead branches.
13303 			 */
13304 			__mark_reg_unknown(env, dst_reg);
13305 			return 0;
13306 		}
13307 	} else {
13308 		src_known = tnum_is_const(src_reg.var_off);
13309 		if ((src_known &&
13310 		     (smin_val != smax_val || umin_val != umax_val)) ||
13311 		    smin_val > smax_val || umin_val > umax_val) {
13312 			/* Taint dst register if offset had invalid bounds
13313 			 * derived from e.g. dead branches.
13314 			 */
13315 			__mark_reg_unknown(env, dst_reg);
13316 			return 0;
13317 		}
13318 	}
13319 
13320 	if (!src_known &&
13321 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13322 		__mark_reg_unknown(env, dst_reg);
13323 		return 0;
13324 	}
13325 
13326 	if (sanitize_needed(opcode)) {
13327 		ret = sanitize_val_alu(env, insn);
13328 		if (ret < 0)
13329 			return sanitize_err(env, insn, ret, NULL, NULL);
13330 	}
13331 
13332 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13333 	 * There are two classes of instructions: The first class we track both
13334 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13335 	 * greatest amount of precision when alu operations are mixed with jmp32
13336 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13337 	 * and BPF_OR. This is possible because these ops have fairly easy to
13338 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13339 	 * See alu32 verifier tests for examples. The second class of
13340 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13341 	 * with regards to tracking sign/unsigned bounds because the bits may
13342 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13343 	 * the reg unbounded in the subreg bound space and use the resulting
13344 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13345 	 */
13346 	switch (opcode) {
13347 	case BPF_ADD:
13348 		scalar32_min_max_add(dst_reg, &src_reg);
13349 		scalar_min_max_add(dst_reg, &src_reg);
13350 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13351 		break;
13352 	case BPF_SUB:
13353 		scalar32_min_max_sub(dst_reg, &src_reg);
13354 		scalar_min_max_sub(dst_reg, &src_reg);
13355 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13356 		break;
13357 	case BPF_MUL:
13358 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13359 		scalar32_min_max_mul(dst_reg, &src_reg);
13360 		scalar_min_max_mul(dst_reg, &src_reg);
13361 		break;
13362 	case BPF_AND:
13363 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13364 		scalar32_min_max_and(dst_reg, &src_reg);
13365 		scalar_min_max_and(dst_reg, &src_reg);
13366 		break;
13367 	case BPF_OR:
13368 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13369 		scalar32_min_max_or(dst_reg, &src_reg);
13370 		scalar_min_max_or(dst_reg, &src_reg);
13371 		break;
13372 	case BPF_XOR:
13373 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13374 		scalar32_min_max_xor(dst_reg, &src_reg);
13375 		scalar_min_max_xor(dst_reg, &src_reg);
13376 		break;
13377 	case BPF_LSH:
13378 		if (umax_val >= insn_bitness) {
13379 			/* Shifts greater than 31 or 63 are undefined.
13380 			 * This includes shifts by a negative number.
13381 			 */
13382 			mark_reg_unknown(env, regs, insn->dst_reg);
13383 			break;
13384 		}
13385 		if (alu32)
13386 			scalar32_min_max_lsh(dst_reg, &src_reg);
13387 		else
13388 			scalar_min_max_lsh(dst_reg, &src_reg);
13389 		break;
13390 	case BPF_RSH:
13391 		if (umax_val >= insn_bitness) {
13392 			/* Shifts greater than 31 or 63 are undefined.
13393 			 * This includes shifts by a negative number.
13394 			 */
13395 			mark_reg_unknown(env, regs, insn->dst_reg);
13396 			break;
13397 		}
13398 		if (alu32)
13399 			scalar32_min_max_rsh(dst_reg, &src_reg);
13400 		else
13401 			scalar_min_max_rsh(dst_reg, &src_reg);
13402 		break;
13403 	case BPF_ARSH:
13404 		if (umax_val >= insn_bitness) {
13405 			/* Shifts greater than 31 or 63 are undefined.
13406 			 * This includes shifts by a negative number.
13407 			 */
13408 			mark_reg_unknown(env, regs, insn->dst_reg);
13409 			break;
13410 		}
13411 		if (alu32)
13412 			scalar32_min_max_arsh(dst_reg, &src_reg);
13413 		else
13414 			scalar_min_max_arsh(dst_reg, &src_reg);
13415 		break;
13416 	default:
13417 		mark_reg_unknown(env, regs, insn->dst_reg);
13418 		break;
13419 	}
13420 
13421 	/* ALU32 ops are zero extended into 64bit register */
13422 	if (alu32)
13423 		zext_32_to_64(dst_reg);
13424 	reg_bounds_sync(dst_reg);
13425 	return 0;
13426 }
13427 
13428 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13429  * and var_off.
13430  */
13431 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13432 				   struct bpf_insn *insn)
13433 {
13434 	struct bpf_verifier_state *vstate = env->cur_state;
13435 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13436 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13437 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13438 	u8 opcode = BPF_OP(insn->code);
13439 	int err;
13440 
13441 	dst_reg = &regs[insn->dst_reg];
13442 	src_reg = NULL;
13443 	if (dst_reg->type != SCALAR_VALUE)
13444 		ptr_reg = dst_reg;
13445 	else
13446 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13447 		 * incorrectly propagated into other registers by find_equal_scalars()
13448 		 */
13449 		dst_reg->id = 0;
13450 	if (BPF_SRC(insn->code) == BPF_X) {
13451 		src_reg = &regs[insn->src_reg];
13452 		if (src_reg->type != SCALAR_VALUE) {
13453 			if (dst_reg->type != SCALAR_VALUE) {
13454 				/* Combining two pointers by any ALU op yields
13455 				 * an arbitrary scalar. Disallow all math except
13456 				 * pointer subtraction
13457 				 */
13458 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13459 					mark_reg_unknown(env, regs, insn->dst_reg);
13460 					return 0;
13461 				}
13462 				verbose(env, "R%d pointer %s pointer prohibited\n",
13463 					insn->dst_reg,
13464 					bpf_alu_string[opcode >> 4]);
13465 				return -EACCES;
13466 			} else {
13467 				/* scalar += pointer
13468 				 * This is legal, but we have to reverse our
13469 				 * src/dest handling in computing the range
13470 				 */
13471 				err = mark_chain_precision(env, insn->dst_reg);
13472 				if (err)
13473 					return err;
13474 				return adjust_ptr_min_max_vals(env, insn,
13475 							       src_reg, dst_reg);
13476 			}
13477 		} else if (ptr_reg) {
13478 			/* pointer += scalar */
13479 			err = mark_chain_precision(env, insn->src_reg);
13480 			if (err)
13481 				return err;
13482 			return adjust_ptr_min_max_vals(env, insn,
13483 						       dst_reg, src_reg);
13484 		} else if (dst_reg->precise) {
13485 			/* if dst_reg is precise, src_reg should be precise as well */
13486 			err = mark_chain_precision(env, insn->src_reg);
13487 			if (err)
13488 				return err;
13489 		}
13490 	} else {
13491 		/* Pretend the src is a reg with a known value, since we only
13492 		 * need to be able to read from this state.
13493 		 */
13494 		off_reg.type = SCALAR_VALUE;
13495 		__mark_reg_known(&off_reg, insn->imm);
13496 		src_reg = &off_reg;
13497 		if (ptr_reg) /* pointer += K */
13498 			return adjust_ptr_min_max_vals(env, insn,
13499 						       ptr_reg, src_reg);
13500 	}
13501 
13502 	/* Got here implies adding two SCALAR_VALUEs */
13503 	if (WARN_ON_ONCE(ptr_reg)) {
13504 		print_verifier_state(env, state, true);
13505 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13506 		return -EINVAL;
13507 	}
13508 	if (WARN_ON(!src_reg)) {
13509 		print_verifier_state(env, state, true);
13510 		verbose(env, "verifier internal error: no src_reg\n");
13511 		return -EINVAL;
13512 	}
13513 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13514 }
13515 
13516 /* check validity of 32-bit and 64-bit arithmetic operations */
13517 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13518 {
13519 	struct bpf_reg_state *regs = cur_regs(env);
13520 	u8 opcode = BPF_OP(insn->code);
13521 	int err;
13522 
13523 	if (opcode == BPF_END || opcode == BPF_NEG) {
13524 		if (opcode == BPF_NEG) {
13525 			if (BPF_SRC(insn->code) != BPF_K ||
13526 			    insn->src_reg != BPF_REG_0 ||
13527 			    insn->off != 0 || insn->imm != 0) {
13528 				verbose(env, "BPF_NEG uses reserved fields\n");
13529 				return -EINVAL;
13530 			}
13531 		} else {
13532 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13533 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13534 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13535 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13536 				verbose(env, "BPF_END uses reserved fields\n");
13537 				return -EINVAL;
13538 			}
13539 		}
13540 
13541 		/* check src operand */
13542 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13543 		if (err)
13544 			return err;
13545 
13546 		if (is_pointer_value(env, insn->dst_reg)) {
13547 			verbose(env, "R%d pointer arithmetic prohibited\n",
13548 				insn->dst_reg);
13549 			return -EACCES;
13550 		}
13551 
13552 		/* check dest operand */
13553 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13554 		if (err)
13555 			return err;
13556 
13557 	} else if (opcode == BPF_MOV) {
13558 
13559 		if (BPF_SRC(insn->code) == BPF_X) {
13560 			if (insn->imm != 0) {
13561 				verbose(env, "BPF_MOV uses reserved fields\n");
13562 				return -EINVAL;
13563 			}
13564 
13565 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13566 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13567 					verbose(env, "BPF_MOV uses reserved fields\n");
13568 					return -EINVAL;
13569 				}
13570 			} else {
13571 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13572 				    insn->off != 32) {
13573 					verbose(env, "BPF_MOV uses reserved fields\n");
13574 					return -EINVAL;
13575 				}
13576 			}
13577 
13578 			/* check src operand */
13579 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13580 			if (err)
13581 				return err;
13582 		} else {
13583 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13584 				verbose(env, "BPF_MOV uses reserved fields\n");
13585 				return -EINVAL;
13586 			}
13587 		}
13588 
13589 		/* check dest operand, mark as required later */
13590 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13591 		if (err)
13592 			return err;
13593 
13594 		if (BPF_SRC(insn->code) == BPF_X) {
13595 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13596 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13597 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13598 				       !tnum_is_const(src_reg->var_off);
13599 
13600 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13601 				if (insn->off == 0) {
13602 					/* case: R1 = R2
13603 					 * copy register state to dest reg
13604 					 */
13605 					if (need_id)
13606 						/* Assign src and dst registers the same ID
13607 						 * that will be used by find_equal_scalars()
13608 						 * to propagate min/max range.
13609 						 */
13610 						src_reg->id = ++env->id_gen;
13611 					copy_register_state(dst_reg, src_reg);
13612 					dst_reg->live |= REG_LIVE_WRITTEN;
13613 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13614 				} else {
13615 					/* case: R1 = (s8, s16 s32)R2 */
13616 					if (is_pointer_value(env, insn->src_reg)) {
13617 						verbose(env,
13618 							"R%d sign-extension part of pointer\n",
13619 							insn->src_reg);
13620 						return -EACCES;
13621 					} else if (src_reg->type == SCALAR_VALUE) {
13622 						bool no_sext;
13623 
13624 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13625 						if (no_sext && need_id)
13626 							src_reg->id = ++env->id_gen;
13627 						copy_register_state(dst_reg, src_reg);
13628 						if (!no_sext)
13629 							dst_reg->id = 0;
13630 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13631 						dst_reg->live |= REG_LIVE_WRITTEN;
13632 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13633 					} else {
13634 						mark_reg_unknown(env, regs, insn->dst_reg);
13635 					}
13636 				}
13637 			} else {
13638 				/* R1 = (u32) R2 */
13639 				if (is_pointer_value(env, insn->src_reg)) {
13640 					verbose(env,
13641 						"R%d partial copy of pointer\n",
13642 						insn->src_reg);
13643 					return -EACCES;
13644 				} else if (src_reg->type == SCALAR_VALUE) {
13645 					if (insn->off == 0) {
13646 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13647 
13648 						if (is_src_reg_u32 && need_id)
13649 							src_reg->id = ++env->id_gen;
13650 						copy_register_state(dst_reg, src_reg);
13651 						/* Make sure ID is cleared if src_reg is not in u32
13652 						 * range otherwise dst_reg min/max could be incorrectly
13653 						 * propagated into src_reg by find_equal_scalars()
13654 						 */
13655 						if (!is_src_reg_u32)
13656 							dst_reg->id = 0;
13657 						dst_reg->live |= REG_LIVE_WRITTEN;
13658 						dst_reg->subreg_def = env->insn_idx + 1;
13659 					} else {
13660 						/* case: W1 = (s8, s16)W2 */
13661 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13662 
13663 						if (no_sext && need_id)
13664 							src_reg->id = ++env->id_gen;
13665 						copy_register_state(dst_reg, src_reg);
13666 						if (!no_sext)
13667 							dst_reg->id = 0;
13668 						dst_reg->live |= REG_LIVE_WRITTEN;
13669 						dst_reg->subreg_def = env->insn_idx + 1;
13670 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13671 					}
13672 				} else {
13673 					mark_reg_unknown(env, regs,
13674 							 insn->dst_reg);
13675 				}
13676 				zext_32_to_64(dst_reg);
13677 				reg_bounds_sync(dst_reg);
13678 			}
13679 		} else {
13680 			/* case: R = imm
13681 			 * remember the value we stored into this reg
13682 			 */
13683 			/* clear any state __mark_reg_known doesn't set */
13684 			mark_reg_unknown(env, regs, insn->dst_reg);
13685 			regs[insn->dst_reg].type = SCALAR_VALUE;
13686 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13687 				__mark_reg_known(regs + insn->dst_reg,
13688 						 insn->imm);
13689 			} else {
13690 				__mark_reg_known(regs + insn->dst_reg,
13691 						 (u32)insn->imm);
13692 			}
13693 		}
13694 
13695 	} else if (opcode > BPF_END) {
13696 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13697 		return -EINVAL;
13698 
13699 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13700 
13701 		if (BPF_SRC(insn->code) == BPF_X) {
13702 			if (insn->imm != 0 || insn->off > 1 ||
13703 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13704 				verbose(env, "BPF_ALU uses reserved fields\n");
13705 				return -EINVAL;
13706 			}
13707 			/* check src1 operand */
13708 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13709 			if (err)
13710 				return err;
13711 		} else {
13712 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13713 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13714 				verbose(env, "BPF_ALU uses reserved fields\n");
13715 				return -EINVAL;
13716 			}
13717 		}
13718 
13719 		/* check src2 operand */
13720 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13721 		if (err)
13722 			return err;
13723 
13724 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13725 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13726 			verbose(env, "div by zero\n");
13727 			return -EINVAL;
13728 		}
13729 
13730 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13731 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13732 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13733 
13734 			if (insn->imm < 0 || insn->imm >= size) {
13735 				verbose(env, "invalid shift %d\n", insn->imm);
13736 				return -EINVAL;
13737 			}
13738 		}
13739 
13740 		/* check dest operand */
13741 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13742 		if (err)
13743 			return err;
13744 
13745 		return adjust_reg_min_max_vals(env, insn);
13746 	}
13747 
13748 	return 0;
13749 }
13750 
13751 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13752 				   struct bpf_reg_state *dst_reg,
13753 				   enum bpf_reg_type type,
13754 				   bool range_right_open)
13755 {
13756 	struct bpf_func_state *state;
13757 	struct bpf_reg_state *reg;
13758 	int new_range;
13759 
13760 	if (dst_reg->off < 0 ||
13761 	    (dst_reg->off == 0 && range_right_open))
13762 		/* This doesn't give us any range */
13763 		return;
13764 
13765 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13766 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13767 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13768 		 * than pkt_end, but that's because it's also less than pkt.
13769 		 */
13770 		return;
13771 
13772 	new_range = dst_reg->off;
13773 	if (range_right_open)
13774 		new_range++;
13775 
13776 	/* Examples for register markings:
13777 	 *
13778 	 * pkt_data in dst register:
13779 	 *
13780 	 *   r2 = r3;
13781 	 *   r2 += 8;
13782 	 *   if (r2 > pkt_end) goto <handle exception>
13783 	 *   <access okay>
13784 	 *
13785 	 *   r2 = r3;
13786 	 *   r2 += 8;
13787 	 *   if (r2 < pkt_end) goto <access okay>
13788 	 *   <handle exception>
13789 	 *
13790 	 *   Where:
13791 	 *     r2 == dst_reg, pkt_end == src_reg
13792 	 *     r2=pkt(id=n,off=8,r=0)
13793 	 *     r3=pkt(id=n,off=0,r=0)
13794 	 *
13795 	 * pkt_data in src register:
13796 	 *
13797 	 *   r2 = r3;
13798 	 *   r2 += 8;
13799 	 *   if (pkt_end >= r2) goto <access okay>
13800 	 *   <handle exception>
13801 	 *
13802 	 *   r2 = r3;
13803 	 *   r2 += 8;
13804 	 *   if (pkt_end <= r2) goto <handle exception>
13805 	 *   <access okay>
13806 	 *
13807 	 *   Where:
13808 	 *     pkt_end == dst_reg, r2 == src_reg
13809 	 *     r2=pkt(id=n,off=8,r=0)
13810 	 *     r3=pkt(id=n,off=0,r=0)
13811 	 *
13812 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13813 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13814 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13815 	 * the check.
13816 	 */
13817 
13818 	/* If our ids match, then we must have the same max_value.  And we
13819 	 * don't care about the other reg's fixed offset, since if it's too big
13820 	 * the range won't allow anything.
13821 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13822 	 */
13823 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13824 		if (reg->type == type && reg->id == dst_reg->id)
13825 			/* keep the maximum range already checked */
13826 			reg->range = max(reg->range, new_range);
13827 	}));
13828 }
13829 
13830 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13831 {
13832 	struct tnum subreg = tnum_subreg(reg->var_off);
13833 	s32 sval = (s32)val;
13834 
13835 	switch (opcode) {
13836 	case BPF_JEQ:
13837 		if (tnum_is_const(subreg))
13838 			return !!tnum_equals_const(subreg, val);
13839 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13840 			return 0;
13841 		break;
13842 	case BPF_JNE:
13843 		if (tnum_is_const(subreg))
13844 			return !tnum_equals_const(subreg, val);
13845 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13846 			return 1;
13847 		break;
13848 	case BPF_JSET:
13849 		if ((~subreg.mask & subreg.value) & val)
13850 			return 1;
13851 		if (!((subreg.mask | subreg.value) & val))
13852 			return 0;
13853 		break;
13854 	case BPF_JGT:
13855 		if (reg->u32_min_value > val)
13856 			return 1;
13857 		else if (reg->u32_max_value <= val)
13858 			return 0;
13859 		break;
13860 	case BPF_JSGT:
13861 		if (reg->s32_min_value > sval)
13862 			return 1;
13863 		else if (reg->s32_max_value <= sval)
13864 			return 0;
13865 		break;
13866 	case BPF_JLT:
13867 		if (reg->u32_max_value < val)
13868 			return 1;
13869 		else if (reg->u32_min_value >= val)
13870 			return 0;
13871 		break;
13872 	case BPF_JSLT:
13873 		if (reg->s32_max_value < sval)
13874 			return 1;
13875 		else if (reg->s32_min_value >= sval)
13876 			return 0;
13877 		break;
13878 	case BPF_JGE:
13879 		if (reg->u32_min_value >= val)
13880 			return 1;
13881 		else if (reg->u32_max_value < val)
13882 			return 0;
13883 		break;
13884 	case BPF_JSGE:
13885 		if (reg->s32_min_value >= sval)
13886 			return 1;
13887 		else if (reg->s32_max_value < sval)
13888 			return 0;
13889 		break;
13890 	case BPF_JLE:
13891 		if (reg->u32_max_value <= val)
13892 			return 1;
13893 		else if (reg->u32_min_value > val)
13894 			return 0;
13895 		break;
13896 	case BPF_JSLE:
13897 		if (reg->s32_max_value <= sval)
13898 			return 1;
13899 		else if (reg->s32_min_value > sval)
13900 			return 0;
13901 		break;
13902 	}
13903 
13904 	return -1;
13905 }
13906 
13907 
13908 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13909 {
13910 	s64 sval = (s64)val;
13911 
13912 	switch (opcode) {
13913 	case BPF_JEQ:
13914 		if (tnum_is_const(reg->var_off))
13915 			return !!tnum_equals_const(reg->var_off, val);
13916 		else if (val < reg->umin_value || val > reg->umax_value)
13917 			return 0;
13918 		break;
13919 	case BPF_JNE:
13920 		if (tnum_is_const(reg->var_off))
13921 			return !tnum_equals_const(reg->var_off, val);
13922 		else if (val < reg->umin_value || val > reg->umax_value)
13923 			return 1;
13924 		break;
13925 	case BPF_JSET:
13926 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13927 			return 1;
13928 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13929 			return 0;
13930 		break;
13931 	case BPF_JGT:
13932 		if (reg->umin_value > val)
13933 			return 1;
13934 		else if (reg->umax_value <= val)
13935 			return 0;
13936 		break;
13937 	case BPF_JSGT:
13938 		if (reg->smin_value > sval)
13939 			return 1;
13940 		else if (reg->smax_value <= sval)
13941 			return 0;
13942 		break;
13943 	case BPF_JLT:
13944 		if (reg->umax_value < val)
13945 			return 1;
13946 		else if (reg->umin_value >= val)
13947 			return 0;
13948 		break;
13949 	case BPF_JSLT:
13950 		if (reg->smax_value < sval)
13951 			return 1;
13952 		else if (reg->smin_value >= sval)
13953 			return 0;
13954 		break;
13955 	case BPF_JGE:
13956 		if (reg->umin_value >= val)
13957 			return 1;
13958 		else if (reg->umax_value < val)
13959 			return 0;
13960 		break;
13961 	case BPF_JSGE:
13962 		if (reg->smin_value >= sval)
13963 			return 1;
13964 		else if (reg->smax_value < sval)
13965 			return 0;
13966 		break;
13967 	case BPF_JLE:
13968 		if (reg->umax_value <= val)
13969 			return 1;
13970 		else if (reg->umin_value > val)
13971 			return 0;
13972 		break;
13973 	case BPF_JSLE:
13974 		if (reg->smax_value <= sval)
13975 			return 1;
13976 		else if (reg->smin_value > sval)
13977 			return 0;
13978 		break;
13979 	}
13980 
13981 	return -1;
13982 }
13983 
13984 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13985  * and return:
13986  *  1 - branch will be taken and "goto target" will be executed
13987  *  0 - branch will not be taken and fall-through to next insn
13988  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13989  *      range [0,10]
13990  */
13991 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13992 			   bool is_jmp32)
13993 {
13994 	if (__is_pointer_value(false, reg)) {
13995 		if (!reg_not_null(reg))
13996 			return -1;
13997 
13998 		/* If pointer is valid tests against zero will fail so we can
13999 		 * use this to direct branch taken.
14000 		 */
14001 		if (val != 0)
14002 			return -1;
14003 
14004 		switch (opcode) {
14005 		case BPF_JEQ:
14006 			return 0;
14007 		case BPF_JNE:
14008 			return 1;
14009 		default:
14010 			return -1;
14011 		}
14012 	}
14013 
14014 	if (is_jmp32)
14015 		return is_branch32_taken(reg, val, opcode);
14016 	return is_branch64_taken(reg, val, opcode);
14017 }
14018 
14019 static int flip_opcode(u32 opcode)
14020 {
14021 	/* How can we transform "a <op> b" into "b <op> a"? */
14022 	static const u8 opcode_flip[16] = {
14023 		/* these stay the same */
14024 		[BPF_JEQ  >> 4] = BPF_JEQ,
14025 		[BPF_JNE  >> 4] = BPF_JNE,
14026 		[BPF_JSET >> 4] = BPF_JSET,
14027 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14028 		[BPF_JGE  >> 4] = BPF_JLE,
14029 		[BPF_JGT  >> 4] = BPF_JLT,
14030 		[BPF_JLE  >> 4] = BPF_JGE,
14031 		[BPF_JLT  >> 4] = BPF_JGT,
14032 		[BPF_JSGE >> 4] = BPF_JSLE,
14033 		[BPF_JSGT >> 4] = BPF_JSLT,
14034 		[BPF_JSLE >> 4] = BPF_JSGE,
14035 		[BPF_JSLT >> 4] = BPF_JSGT
14036 	};
14037 	return opcode_flip[opcode >> 4];
14038 }
14039 
14040 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14041 				   struct bpf_reg_state *src_reg,
14042 				   u8 opcode)
14043 {
14044 	struct bpf_reg_state *pkt;
14045 
14046 	if (src_reg->type == PTR_TO_PACKET_END) {
14047 		pkt = dst_reg;
14048 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14049 		pkt = src_reg;
14050 		opcode = flip_opcode(opcode);
14051 	} else {
14052 		return -1;
14053 	}
14054 
14055 	if (pkt->range >= 0)
14056 		return -1;
14057 
14058 	switch (opcode) {
14059 	case BPF_JLE:
14060 		/* pkt <= pkt_end */
14061 		fallthrough;
14062 	case BPF_JGT:
14063 		/* pkt > pkt_end */
14064 		if (pkt->range == BEYOND_PKT_END)
14065 			/* pkt has at last one extra byte beyond pkt_end */
14066 			return opcode == BPF_JGT;
14067 		break;
14068 	case BPF_JLT:
14069 		/* pkt < pkt_end */
14070 		fallthrough;
14071 	case BPF_JGE:
14072 		/* pkt >= pkt_end */
14073 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14074 			return opcode == BPF_JGE;
14075 		break;
14076 	}
14077 	return -1;
14078 }
14079 
14080 /* Adjusts the register min/max values in the case that the dst_reg is the
14081  * variable register that we are working on, and src_reg is a constant or we're
14082  * simply doing a BPF_K check.
14083  * In JEQ/JNE cases we also adjust the var_off values.
14084  */
14085 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14086 			    struct bpf_reg_state *false_reg,
14087 			    u64 val, u32 val32,
14088 			    u8 opcode, bool is_jmp32)
14089 {
14090 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14091 	struct tnum false_64off = false_reg->var_off;
14092 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14093 	struct tnum true_64off = true_reg->var_off;
14094 	s64 sval = (s64)val;
14095 	s32 sval32 = (s32)val32;
14096 
14097 	/* If the dst_reg is a pointer, we can't learn anything about its
14098 	 * variable offset from the compare (unless src_reg were a pointer into
14099 	 * the same object, but we don't bother with that.
14100 	 * Since false_reg and true_reg have the same type by construction, we
14101 	 * only need to check one of them for pointerness.
14102 	 */
14103 	if (__is_pointer_value(false, false_reg))
14104 		return;
14105 
14106 	switch (opcode) {
14107 	/* JEQ/JNE comparison doesn't change the register equivalence.
14108 	 *
14109 	 * r1 = r2;
14110 	 * if (r1 == 42) goto label;
14111 	 * ...
14112 	 * label: // here both r1 and r2 are known to be 42.
14113 	 *
14114 	 * Hence when marking register as known preserve it's ID.
14115 	 */
14116 	case BPF_JEQ:
14117 		if (is_jmp32) {
14118 			__mark_reg32_known(true_reg, val32);
14119 			true_32off = tnum_subreg(true_reg->var_off);
14120 		} else {
14121 			___mark_reg_known(true_reg, val);
14122 			true_64off = true_reg->var_off;
14123 		}
14124 		break;
14125 	case BPF_JNE:
14126 		if (is_jmp32) {
14127 			__mark_reg32_known(false_reg, val32);
14128 			false_32off = tnum_subreg(false_reg->var_off);
14129 		} else {
14130 			___mark_reg_known(false_reg, val);
14131 			false_64off = false_reg->var_off;
14132 		}
14133 		break;
14134 	case BPF_JSET:
14135 		if (is_jmp32) {
14136 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14137 			if (is_power_of_2(val32))
14138 				true_32off = tnum_or(true_32off,
14139 						     tnum_const(val32));
14140 		} else {
14141 			false_64off = tnum_and(false_64off, tnum_const(~val));
14142 			if (is_power_of_2(val))
14143 				true_64off = tnum_or(true_64off,
14144 						     tnum_const(val));
14145 		}
14146 		break;
14147 	case BPF_JGE:
14148 	case BPF_JGT:
14149 	{
14150 		if (is_jmp32) {
14151 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14152 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14153 
14154 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14155 						       false_umax);
14156 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14157 						      true_umin);
14158 		} else {
14159 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14160 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14161 
14162 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14163 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14164 		}
14165 		break;
14166 	}
14167 	case BPF_JSGE:
14168 	case BPF_JSGT:
14169 	{
14170 		if (is_jmp32) {
14171 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14172 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14173 
14174 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14175 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14176 		} else {
14177 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14178 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14179 
14180 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14181 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14182 		}
14183 		break;
14184 	}
14185 	case BPF_JLE:
14186 	case BPF_JLT:
14187 	{
14188 		if (is_jmp32) {
14189 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14190 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14191 
14192 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14193 						       false_umin);
14194 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14195 						      true_umax);
14196 		} else {
14197 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14198 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14199 
14200 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14201 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14202 		}
14203 		break;
14204 	}
14205 	case BPF_JSLE:
14206 	case BPF_JSLT:
14207 	{
14208 		if (is_jmp32) {
14209 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14210 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14211 
14212 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14213 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14214 		} else {
14215 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14216 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14217 
14218 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14219 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14220 		}
14221 		break;
14222 	}
14223 	default:
14224 		return;
14225 	}
14226 
14227 	if (is_jmp32) {
14228 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14229 					     tnum_subreg(false_32off));
14230 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14231 					    tnum_subreg(true_32off));
14232 		__reg_combine_32_into_64(false_reg);
14233 		__reg_combine_32_into_64(true_reg);
14234 	} else {
14235 		false_reg->var_off = false_64off;
14236 		true_reg->var_off = true_64off;
14237 		__reg_combine_64_into_32(false_reg);
14238 		__reg_combine_64_into_32(true_reg);
14239 	}
14240 }
14241 
14242 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14243  * the variable reg.
14244  */
14245 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14246 				struct bpf_reg_state *false_reg,
14247 				u64 val, u32 val32,
14248 				u8 opcode, bool is_jmp32)
14249 {
14250 	opcode = flip_opcode(opcode);
14251 	/* This uses zero as "not present in table"; luckily the zero opcode,
14252 	 * BPF_JA, can't get here.
14253 	 */
14254 	if (opcode)
14255 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14256 }
14257 
14258 /* Regs are known to be equal, so intersect their min/max/var_off */
14259 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14260 				  struct bpf_reg_state *dst_reg)
14261 {
14262 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14263 							dst_reg->umin_value);
14264 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14265 							dst_reg->umax_value);
14266 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14267 							dst_reg->smin_value);
14268 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14269 							dst_reg->smax_value);
14270 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14271 							     dst_reg->var_off);
14272 	reg_bounds_sync(src_reg);
14273 	reg_bounds_sync(dst_reg);
14274 }
14275 
14276 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14277 				struct bpf_reg_state *true_dst,
14278 				struct bpf_reg_state *false_src,
14279 				struct bpf_reg_state *false_dst,
14280 				u8 opcode)
14281 {
14282 	switch (opcode) {
14283 	case BPF_JEQ:
14284 		__reg_combine_min_max(true_src, true_dst);
14285 		break;
14286 	case BPF_JNE:
14287 		__reg_combine_min_max(false_src, false_dst);
14288 		break;
14289 	}
14290 }
14291 
14292 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14293 				 struct bpf_reg_state *reg, u32 id,
14294 				 bool is_null)
14295 {
14296 	if (type_may_be_null(reg->type) && reg->id == id &&
14297 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14298 		/* Old offset (both fixed and variable parts) should have been
14299 		 * known-zero, because we don't allow pointer arithmetic on
14300 		 * pointers that might be NULL. If we see this happening, don't
14301 		 * convert the register.
14302 		 *
14303 		 * But in some cases, some helpers that return local kptrs
14304 		 * advance offset for the returned pointer. In those cases, it
14305 		 * is fine to expect to see reg->off.
14306 		 */
14307 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14308 			return;
14309 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14310 		    WARN_ON_ONCE(reg->off))
14311 			return;
14312 
14313 		if (is_null) {
14314 			reg->type = SCALAR_VALUE;
14315 			/* We don't need id and ref_obj_id from this point
14316 			 * onwards anymore, thus we should better reset it,
14317 			 * so that state pruning has chances to take effect.
14318 			 */
14319 			reg->id = 0;
14320 			reg->ref_obj_id = 0;
14321 
14322 			return;
14323 		}
14324 
14325 		mark_ptr_not_null_reg(reg);
14326 
14327 		if (!reg_may_point_to_spin_lock(reg)) {
14328 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14329 			 * in release_reference().
14330 			 *
14331 			 * reg->id is still used by spin_lock ptr. Other
14332 			 * than spin_lock ptr type, reg->id can be reset.
14333 			 */
14334 			reg->id = 0;
14335 		}
14336 	}
14337 }
14338 
14339 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14340  * be folded together at some point.
14341  */
14342 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14343 				  bool is_null)
14344 {
14345 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14346 	struct bpf_reg_state *regs = state->regs, *reg;
14347 	u32 ref_obj_id = regs[regno].ref_obj_id;
14348 	u32 id = regs[regno].id;
14349 
14350 	if (ref_obj_id && ref_obj_id == id && is_null)
14351 		/* regs[regno] is in the " == NULL" branch.
14352 		 * No one could have freed the reference state before
14353 		 * doing the NULL check.
14354 		 */
14355 		WARN_ON_ONCE(release_reference_state(state, id));
14356 
14357 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14358 		mark_ptr_or_null_reg(state, reg, id, is_null);
14359 	}));
14360 }
14361 
14362 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14363 				   struct bpf_reg_state *dst_reg,
14364 				   struct bpf_reg_state *src_reg,
14365 				   struct bpf_verifier_state *this_branch,
14366 				   struct bpf_verifier_state *other_branch)
14367 {
14368 	if (BPF_SRC(insn->code) != BPF_X)
14369 		return false;
14370 
14371 	/* Pointers are always 64-bit. */
14372 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14373 		return false;
14374 
14375 	switch (BPF_OP(insn->code)) {
14376 	case BPF_JGT:
14377 		if ((dst_reg->type == PTR_TO_PACKET &&
14378 		     src_reg->type == PTR_TO_PACKET_END) ||
14379 		    (dst_reg->type == PTR_TO_PACKET_META &&
14380 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14381 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14382 			find_good_pkt_pointers(this_branch, dst_reg,
14383 					       dst_reg->type, false);
14384 			mark_pkt_end(other_branch, insn->dst_reg, true);
14385 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14386 			    src_reg->type == PTR_TO_PACKET) ||
14387 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14388 			    src_reg->type == PTR_TO_PACKET_META)) {
14389 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14390 			find_good_pkt_pointers(other_branch, src_reg,
14391 					       src_reg->type, true);
14392 			mark_pkt_end(this_branch, insn->src_reg, false);
14393 		} else {
14394 			return false;
14395 		}
14396 		break;
14397 	case BPF_JLT:
14398 		if ((dst_reg->type == PTR_TO_PACKET &&
14399 		     src_reg->type == PTR_TO_PACKET_END) ||
14400 		    (dst_reg->type == PTR_TO_PACKET_META &&
14401 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14402 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14403 			find_good_pkt_pointers(other_branch, dst_reg,
14404 					       dst_reg->type, true);
14405 			mark_pkt_end(this_branch, insn->dst_reg, false);
14406 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14407 			    src_reg->type == PTR_TO_PACKET) ||
14408 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14409 			    src_reg->type == PTR_TO_PACKET_META)) {
14410 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14411 			find_good_pkt_pointers(this_branch, src_reg,
14412 					       src_reg->type, false);
14413 			mark_pkt_end(other_branch, insn->src_reg, true);
14414 		} else {
14415 			return false;
14416 		}
14417 		break;
14418 	case BPF_JGE:
14419 		if ((dst_reg->type == PTR_TO_PACKET &&
14420 		     src_reg->type == PTR_TO_PACKET_END) ||
14421 		    (dst_reg->type == PTR_TO_PACKET_META &&
14422 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14423 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14424 			find_good_pkt_pointers(this_branch, dst_reg,
14425 					       dst_reg->type, true);
14426 			mark_pkt_end(other_branch, insn->dst_reg, false);
14427 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14428 			    src_reg->type == PTR_TO_PACKET) ||
14429 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14430 			    src_reg->type == PTR_TO_PACKET_META)) {
14431 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14432 			find_good_pkt_pointers(other_branch, src_reg,
14433 					       src_reg->type, false);
14434 			mark_pkt_end(this_branch, insn->src_reg, true);
14435 		} else {
14436 			return false;
14437 		}
14438 		break;
14439 	case BPF_JLE:
14440 		if ((dst_reg->type == PTR_TO_PACKET &&
14441 		     src_reg->type == PTR_TO_PACKET_END) ||
14442 		    (dst_reg->type == PTR_TO_PACKET_META &&
14443 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14444 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14445 			find_good_pkt_pointers(other_branch, dst_reg,
14446 					       dst_reg->type, false);
14447 			mark_pkt_end(this_branch, insn->dst_reg, true);
14448 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14449 			    src_reg->type == PTR_TO_PACKET) ||
14450 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14451 			    src_reg->type == PTR_TO_PACKET_META)) {
14452 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14453 			find_good_pkt_pointers(this_branch, src_reg,
14454 					       src_reg->type, true);
14455 			mark_pkt_end(other_branch, insn->src_reg, false);
14456 		} else {
14457 			return false;
14458 		}
14459 		break;
14460 	default:
14461 		return false;
14462 	}
14463 
14464 	return true;
14465 }
14466 
14467 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14468 			       struct bpf_reg_state *known_reg)
14469 {
14470 	struct bpf_func_state *state;
14471 	struct bpf_reg_state *reg;
14472 
14473 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14474 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14475 			copy_register_state(reg, known_reg);
14476 	}));
14477 }
14478 
14479 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14480 			     struct bpf_insn *insn, int *insn_idx)
14481 {
14482 	struct bpf_verifier_state *this_branch = env->cur_state;
14483 	struct bpf_verifier_state *other_branch;
14484 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14485 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14486 	struct bpf_reg_state *eq_branch_regs;
14487 	u8 opcode = BPF_OP(insn->code);
14488 	bool is_jmp32;
14489 	int pred = -1;
14490 	int err;
14491 
14492 	/* Only conditional jumps are expected to reach here. */
14493 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14494 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14495 		return -EINVAL;
14496 	}
14497 
14498 	/* check src2 operand */
14499 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14500 	if (err)
14501 		return err;
14502 
14503 	dst_reg = &regs[insn->dst_reg];
14504 	if (BPF_SRC(insn->code) == BPF_X) {
14505 		if (insn->imm != 0) {
14506 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14507 			return -EINVAL;
14508 		}
14509 
14510 		/* check src1 operand */
14511 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14512 		if (err)
14513 			return err;
14514 
14515 		src_reg = &regs[insn->src_reg];
14516 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14517 		    is_pointer_value(env, insn->src_reg)) {
14518 			verbose(env, "R%d pointer comparison prohibited\n",
14519 				insn->src_reg);
14520 			return -EACCES;
14521 		}
14522 	} else {
14523 		if (insn->src_reg != BPF_REG_0) {
14524 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14525 			return -EINVAL;
14526 		}
14527 	}
14528 
14529 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14530 
14531 	if (BPF_SRC(insn->code) == BPF_K) {
14532 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14533 	} else if (src_reg->type == SCALAR_VALUE &&
14534 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14535 		pred = is_branch_taken(dst_reg,
14536 				       tnum_subreg(src_reg->var_off).value,
14537 				       opcode,
14538 				       is_jmp32);
14539 	} else if (src_reg->type == SCALAR_VALUE &&
14540 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14541 		pred = is_branch_taken(dst_reg,
14542 				       src_reg->var_off.value,
14543 				       opcode,
14544 				       is_jmp32);
14545 	} else if (dst_reg->type == SCALAR_VALUE &&
14546 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14547 		pred = is_branch_taken(src_reg,
14548 				       tnum_subreg(dst_reg->var_off).value,
14549 				       flip_opcode(opcode),
14550 				       is_jmp32);
14551 	} else if (dst_reg->type == SCALAR_VALUE &&
14552 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14553 		pred = is_branch_taken(src_reg,
14554 				       dst_reg->var_off.value,
14555 				       flip_opcode(opcode),
14556 				       is_jmp32);
14557 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14558 		   reg_is_pkt_pointer_any(src_reg) &&
14559 		   !is_jmp32) {
14560 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14561 	}
14562 
14563 	if (pred >= 0) {
14564 		/* If we get here with a dst_reg pointer type it is because
14565 		 * above is_branch_taken() special cased the 0 comparison.
14566 		 */
14567 		if (!__is_pointer_value(false, dst_reg))
14568 			err = mark_chain_precision(env, insn->dst_reg);
14569 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14570 		    !__is_pointer_value(false, src_reg))
14571 			err = mark_chain_precision(env, insn->src_reg);
14572 		if (err)
14573 			return err;
14574 	}
14575 
14576 	if (pred == 1) {
14577 		/* Only follow the goto, ignore fall-through. If needed, push
14578 		 * the fall-through branch for simulation under speculative
14579 		 * execution.
14580 		 */
14581 		if (!env->bypass_spec_v1 &&
14582 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14583 					       *insn_idx))
14584 			return -EFAULT;
14585 		if (env->log.level & BPF_LOG_LEVEL)
14586 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14587 		*insn_idx += insn->off;
14588 		return 0;
14589 	} else if (pred == 0) {
14590 		/* Only follow the fall-through branch, since that's where the
14591 		 * program will go. If needed, push the goto branch for
14592 		 * simulation under speculative execution.
14593 		 */
14594 		if (!env->bypass_spec_v1 &&
14595 		    !sanitize_speculative_path(env, insn,
14596 					       *insn_idx + insn->off + 1,
14597 					       *insn_idx))
14598 			return -EFAULT;
14599 		if (env->log.level & BPF_LOG_LEVEL)
14600 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14601 		return 0;
14602 	}
14603 
14604 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14605 				  false);
14606 	if (!other_branch)
14607 		return -EFAULT;
14608 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14609 
14610 	/* detect if we are comparing against a constant value so we can adjust
14611 	 * our min/max values for our dst register.
14612 	 * this is only legit if both are scalars (or pointers to the same
14613 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14614 	 * because otherwise the different base pointers mean the offsets aren't
14615 	 * comparable.
14616 	 */
14617 	if (BPF_SRC(insn->code) == BPF_X) {
14618 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14619 
14620 		if (dst_reg->type == SCALAR_VALUE &&
14621 		    src_reg->type == SCALAR_VALUE) {
14622 			if (tnum_is_const(src_reg->var_off) ||
14623 			    (is_jmp32 &&
14624 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14625 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14626 						dst_reg,
14627 						src_reg->var_off.value,
14628 						tnum_subreg(src_reg->var_off).value,
14629 						opcode, is_jmp32);
14630 			else if (tnum_is_const(dst_reg->var_off) ||
14631 				 (is_jmp32 &&
14632 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14633 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14634 						    src_reg,
14635 						    dst_reg->var_off.value,
14636 						    tnum_subreg(dst_reg->var_off).value,
14637 						    opcode, is_jmp32);
14638 			else if (!is_jmp32 &&
14639 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14640 				/* Comparing for equality, we can combine knowledge */
14641 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14642 						    &other_branch_regs[insn->dst_reg],
14643 						    src_reg, dst_reg, opcode);
14644 			if (src_reg->id &&
14645 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14646 				find_equal_scalars(this_branch, src_reg);
14647 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14648 			}
14649 
14650 		}
14651 	} else if (dst_reg->type == SCALAR_VALUE) {
14652 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14653 					dst_reg, insn->imm, (u32)insn->imm,
14654 					opcode, is_jmp32);
14655 	}
14656 
14657 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14658 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14659 		find_equal_scalars(this_branch, dst_reg);
14660 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14661 	}
14662 
14663 	/* if one pointer register is compared to another pointer
14664 	 * register check if PTR_MAYBE_NULL could be lifted.
14665 	 * E.g. register A - maybe null
14666 	 *      register B - not null
14667 	 * for JNE A, B, ... - A is not null in the false branch;
14668 	 * for JEQ A, B, ... - A is not null in the true branch.
14669 	 *
14670 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14671 	 * not need to be null checked by the BPF program, i.e.,
14672 	 * could be null even without PTR_MAYBE_NULL marking, so
14673 	 * only propagate nullness when neither reg is that type.
14674 	 */
14675 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14676 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14677 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14678 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14679 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14680 		eq_branch_regs = NULL;
14681 		switch (opcode) {
14682 		case BPF_JEQ:
14683 			eq_branch_regs = other_branch_regs;
14684 			break;
14685 		case BPF_JNE:
14686 			eq_branch_regs = regs;
14687 			break;
14688 		default:
14689 			/* do nothing */
14690 			break;
14691 		}
14692 		if (eq_branch_regs) {
14693 			if (type_may_be_null(src_reg->type))
14694 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14695 			else
14696 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14697 		}
14698 	}
14699 
14700 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14701 	 * NOTE: these optimizations below are related with pointer comparison
14702 	 *       which will never be JMP32.
14703 	 */
14704 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14705 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14706 	    type_may_be_null(dst_reg->type)) {
14707 		/* Mark all identical registers in each branch as either
14708 		 * safe or unknown depending R == 0 or R != 0 conditional.
14709 		 */
14710 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14711 				      opcode == BPF_JNE);
14712 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14713 				      opcode == BPF_JEQ);
14714 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14715 					   this_branch, other_branch) &&
14716 		   is_pointer_value(env, insn->dst_reg)) {
14717 		verbose(env, "R%d pointer comparison prohibited\n",
14718 			insn->dst_reg);
14719 		return -EACCES;
14720 	}
14721 	if (env->log.level & BPF_LOG_LEVEL)
14722 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14723 	return 0;
14724 }
14725 
14726 /* verify BPF_LD_IMM64 instruction */
14727 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14728 {
14729 	struct bpf_insn_aux_data *aux = cur_aux(env);
14730 	struct bpf_reg_state *regs = cur_regs(env);
14731 	struct bpf_reg_state *dst_reg;
14732 	struct bpf_map *map;
14733 	int err;
14734 
14735 	if (BPF_SIZE(insn->code) != BPF_DW) {
14736 		verbose(env, "invalid BPF_LD_IMM insn\n");
14737 		return -EINVAL;
14738 	}
14739 	if (insn->off != 0) {
14740 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14741 		return -EINVAL;
14742 	}
14743 
14744 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14745 	if (err)
14746 		return err;
14747 
14748 	dst_reg = &regs[insn->dst_reg];
14749 	if (insn->src_reg == 0) {
14750 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14751 
14752 		dst_reg->type = SCALAR_VALUE;
14753 		__mark_reg_known(&regs[insn->dst_reg], imm);
14754 		return 0;
14755 	}
14756 
14757 	/* All special src_reg cases are listed below. From this point onwards
14758 	 * we either succeed and assign a corresponding dst_reg->type after
14759 	 * zeroing the offset, or fail and reject the program.
14760 	 */
14761 	mark_reg_known_zero(env, regs, insn->dst_reg);
14762 
14763 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14764 		dst_reg->type = aux->btf_var.reg_type;
14765 		switch (base_type(dst_reg->type)) {
14766 		case PTR_TO_MEM:
14767 			dst_reg->mem_size = aux->btf_var.mem_size;
14768 			break;
14769 		case PTR_TO_BTF_ID:
14770 			dst_reg->btf = aux->btf_var.btf;
14771 			dst_reg->btf_id = aux->btf_var.btf_id;
14772 			break;
14773 		default:
14774 			verbose(env, "bpf verifier is misconfigured\n");
14775 			return -EFAULT;
14776 		}
14777 		return 0;
14778 	}
14779 
14780 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14781 		struct bpf_prog_aux *aux = env->prog->aux;
14782 		u32 subprogno = find_subprog(env,
14783 					     env->insn_idx + insn->imm + 1);
14784 
14785 		if (!aux->func_info) {
14786 			verbose(env, "missing btf func_info\n");
14787 			return -EINVAL;
14788 		}
14789 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14790 			verbose(env, "callback function not static\n");
14791 			return -EINVAL;
14792 		}
14793 
14794 		dst_reg->type = PTR_TO_FUNC;
14795 		dst_reg->subprogno = subprogno;
14796 		return 0;
14797 	}
14798 
14799 	map = env->used_maps[aux->map_index];
14800 	dst_reg->map_ptr = map;
14801 
14802 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14803 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14804 		dst_reg->type = PTR_TO_MAP_VALUE;
14805 		dst_reg->off = aux->map_off;
14806 		WARN_ON_ONCE(map->max_entries != 1);
14807 		/* We want reg->id to be same (0) as map_value is not distinct */
14808 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14809 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14810 		dst_reg->type = CONST_PTR_TO_MAP;
14811 	} else {
14812 		verbose(env, "bpf verifier is misconfigured\n");
14813 		return -EINVAL;
14814 	}
14815 
14816 	return 0;
14817 }
14818 
14819 static bool may_access_skb(enum bpf_prog_type type)
14820 {
14821 	switch (type) {
14822 	case BPF_PROG_TYPE_SOCKET_FILTER:
14823 	case BPF_PROG_TYPE_SCHED_CLS:
14824 	case BPF_PROG_TYPE_SCHED_ACT:
14825 		return true;
14826 	default:
14827 		return false;
14828 	}
14829 }
14830 
14831 /* verify safety of LD_ABS|LD_IND instructions:
14832  * - they can only appear in the programs where ctx == skb
14833  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14834  *   preserve R6-R9, and store return value into R0
14835  *
14836  * Implicit input:
14837  *   ctx == skb == R6 == CTX
14838  *
14839  * Explicit input:
14840  *   SRC == any register
14841  *   IMM == 32-bit immediate
14842  *
14843  * Output:
14844  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14845  */
14846 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14847 {
14848 	struct bpf_reg_state *regs = cur_regs(env);
14849 	static const int ctx_reg = BPF_REG_6;
14850 	u8 mode = BPF_MODE(insn->code);
14851 	int i, err;
14852 
14853 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14854 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14855 		return -EINVAL;
14856 	}
14857 
14858 	if (!env->ops->gen_ld_abs) {
14859 		verbose(env, "bpf verifier is misconfigured\n");
14860 		return -EINVAL;
14861 	}
14862 
14863 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14864 	    BPF_SIZE(insn->code) == BPF_DW ||
14865 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14866 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14867 		return -EINVAL;
14868 	}
14869 
14870 	/* check whether implicit source operand (register R6) is readable */
14871 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14872 	if (err)
14873 		return err;
14874 
14875 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14876 	 * gen_ld_abs() may terminate the program at runtime, leading to
14877 	 * reference leak.
14878 	 */
14879 	err = check_reference_leak(env);
14880 	if (err) {
14881 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14882 		return err;
14883 	}
14884 
14885 	if (env->cur_state->active_lock.ptr) {
14886 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14887 		return -EINVAL;
14888 	}
14889 
14890 	if (env->cur_state->active_rcu_lock) {
14891 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14892 		return -EINVAL;
14893 	}
14894 
14895 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14896 		verbose(env,
14897 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14898 		return -EINVAL;
14899 	}
14900 
14901 	if (mode == BPF_IND) {
14902 		/* check explicit source operand */
14903 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14904 		if (err)
14905 			return err;
14906 	}
14907 
14908 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14909 	if (err < 0)
14910 		return err;
14911 
14912 	/* reset caller saved regs to unreadable */
14913 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14914 		mark_reg_not_init(env, regs, caller_saved[i]);
14915 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14916 	}
14917 
14918 	/* mark destination R0 register as readable, since it contains
14919 	 * the value fetched from the packet.
14920 	 * Already marked as written above.
14921 	 */
14922 	mark_reg_unknown(env, regs, BPF_REG_0);
14923 	/* ld_abs load up to 32-bit skb data. */
14924 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14925 	return 0;
14926 }
14927 
14928 static int check_return_code(struct bpf_verifier_env *env)
14929 {
14930 	struct tnum enforce_attach_type_range = tnum_unknown;
14931 	const struct bpf_prog *prog = env->prog;
14932 	struct bpf_reg_state *reg;
14933 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14934 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14935 	int err;
14936 	struct bpf_func_state *frame = env->cur_state->frame[0];
14937 	const bool is_subprog = frame->subprogno;
14938 
14939 	/* LSM and struct_ops func-ptr's return type could be "void" */
14940 	if (!is_subprog) {
14941 		switch (prog_type) {
14942 		case BPF_PROG_TYPE_LSM:
14943 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14944 				/* See below, can be 0 or 0-1 depending on hook. */
14945 				break;
14946 			fallthrough;
14947 		case BPF_PROG_TYPE_STRUCT_OPS:
14948 			if (!prog->aux->attach_func_proto->type)
14949 				return 0;
14950 			break;
14951 		default:
14952 			break;
14953 		}
14954 	}
14955 
14956 	/* eBPF calling convention is such that R0 is used
14957 	 * to return the value from eBPF program.
14958 	 * Make sure that it's readable at this time
14959 	 * of bpf_exit, which means that program wrote
14960 	 * something into it earlier
14961 	 */
14962 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14963 	if (err)
14964 		return err;
14965 
14966 	if (is_pointer_value(env, BPF_REG_0)) {
14967 		verbose(env, "R0 leaks addr as return value\n");
14968 		return -EACCES;
14969 	}
14970 
14971 	reg = cur_regs(env) + BPF_REG_0;
14972 
14973 	if (frame->in_async_callback_fn) {
14974 		/* enforce return zero from async callbacks like timer */
14975 		if (reg->type != SCALAR_VALUE) {
14976 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14977 				reg_type_str(env, reg->type));
14978 			return -EINVAL;
14979 		}
14980 
14981 		if (!tnum_in(const_0, reg->var_off)) {
14982 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14983 			return -EINVAL;
14984 		}
14985 		return 0;
14986 	}
14987 
14988 	if (is_subprog) {
14989 		if (reg->type != SCALAR_VALUE) {
14990 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14991 				reg_type_str(env, reg->type));
14992 			return -EINVAL;
14993 		}
14994 		return 0;
14995 	}
14996 
14997 	switch (prog_type) {
14998 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14999 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15000 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15001 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15002 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15003 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15004 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15005 			range = tnum_range(1, 1);
15006 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15007 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15008 			range = tnum_range(0, 3);
15009 		break;
15010 	case BPF_PROG_TYPE_CGROUP_SKB:
15011 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15012 			range = tnum_range(0, 3);
15013 			enforce_attach_type_range = tnum_range(2, 3);
15014 		}
15015 		break;
15016 	case BPF_PROG_TYPE_CGROUP_SOCK:
15017 	case BPF_PROG_TYPE_SOCK_OPS:
15018 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15019 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15020 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15021 		break;
15022 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15023 		if (!env->prog->aux->attach_btf_id)
15024 			return 0;
15025 		range = tnum_const(0);
15026 		break;
15027 	case BPF_PROG_TYPE_TRACING:
15028 		switch (env->prog->expected_attach_type) {
15029 		case BPF_TRACE_FENTRY:
15030 		case BPF_TRACE_FEXIT:
15031 			range = tnum_const(0);
15032 			break;
15033 		case BPF_TRACE_RAW_TP:
15034 		case BPF_MODIFY_RETURN:
15035 			return 0;
15036 		case BPF_TRACE_ITER:
15037 			break;
15038 		default:
15039 			return -ENOTSUPP;
15040 		}
15041 		break;
15042 	case BPF_PROG_TYPE_SK_LOOKUP:
15043 		range = tnum_range(SK_DROP, SK_PASS);
15044 		break;
15045 
15046 	case BPF_PROG_TYPE_LSM:
15047 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15048 			/* Regular BPF_PROG_TYPE_LSM programs can return
15049 			 * any value.
15050 			 */
15051 			return 0;
15052 		}
15053 		if (!env->prog->aux->attach_func_proto->type) {
15054 			/* Make sure programs that attach to void
15055 			 * hooks don't try to modify return value.
15056 			 */
15057 			range = tnum_range(1, 1);
15058 		}
15059 		break;
15060 
15061 	case BPF_PROG_TYPE_NETFILTER:
15062 		range = tnum_range(NF_DROP, NF_ACCEPT);
15063 		break;
15064 	case BPF_PROG_TYPE_EXT:
15065 		/* freplace program can return anything as its return value
15066 		 * depends on the to-be-replaced kernel func or bpf program.
15067 		 */
15068 	default:
15069 		return 0;
15070 	}
15071 
15072 	if (reg->type != SCALAR_VALUE) {
15073 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15074 			reg_type_str(env, reg->type));
15075 		return -EINVAL;
15076 	}
15077 
15078 	if (!tnum_in(range, reg->var_off)) {
15079 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15080 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15081 		    prog_type == BPF_PROG_TYPE_LSM &&
15082 		    !prog->aux->attach_func_proto->type)
15083 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15084 		return -EINVAL;
15085 	}
15086 
15087 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15088 	    tnum_in(enforce_attach_type_range, reg->var_off))
15089 		env->prog->enforce_expected_attach_type = 1;
15090 	return 0;
15091 }
15092 
15093 /* non-recursive DFS pseudo code
15094  * 1  procedure DFS-iterative(G,v):
15095  * 2      label v as discovered
15096  * 3      let S be a stack
15097  * 4      S.push(v)
15098  * 5      while S is not empty
15099  * 6            t <- S.peek()
15100  * 7            if t is what we're looking for:
15101  * 8                return t
15102  * 9            for all edges e in G.adjacentEdges(t) do
15103  * 10               if edge e is already labelled
15104  * 11                   continue with the next edge
15105  * 12               w <- G.adjacentVertex(t,e)
15106  * 13               if vertex w is not discovered and not explored
15107  * 14                   label e as tree-edge
15108  * 15                   label w as discovered
15109  * 16                   S.push(w)
15110  * 17                   continue at 5
15111  * 18               else if vertex w is discovered
15112  * 19                   label e as back-edge
15113  * 20               else
15114  * 21                   // vertex w is explored
15115  * 22                   label e as forward- or cross-edge
15116  * 23           label t as explored
15117  * 24           S.pop()
15118  *
15119  * convention:
15120  * 0x10 - discovered
15121  * 0x11 - discovered and fall-through edge labelled
15122  * 0x12 - discovered and fall-through and branch edges labelled
15123  * 0x20 - explored
15124  */
15125 
15126 enum {
15127 	DISCOVERED = 0x10,
15128 	EXPLORED = 0x20,
15129 	FALLTHROUGH = 1,
15130 	BRANCH = 2,
15131 };
15132 
15133 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15134 {
15135 	env->insn_aux_data[idx].prune_point = true;
15136 }
15137 
15138 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15139 {
15140 	return env->insn_aux_data[insn_idx].prune_point;
15141 }
15142 
15143 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15144 {
15145 	env->insn_aux_data[idx].force_checkpoint = true;
15146 }
15147 
15148 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15149 {
15150 	return env->insn_aux_data[insn_idx].force_checkpoint;
15151 }
15152 
15153 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15154 {
15155 	env->insn_aux_data[idx].calls_callback = true;
15156 }
15157 
15158 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15159 {
15160 	return env->insn_aux_data[insn_idx].calls_callback;
15161 }
15162 
15163 enum {
15164 	DONE_EXPLORING = 0,
15165 	KEEP_EXPLORING = 1,
15166 };
15167 
15168 /* t, w, e - match pseudo-code above:
15169  * t - index of current instruction
15170  * w - next instruction
15171  * e - edge
15172  */
15173 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15174 {
15175 	int *insn_stack = env->cfg.insn_stack;
15176 	int *insn_state = env->cfg.insn_state;
15177 
15178 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15179 		return DONE_EXPLORING;
15180 
15181 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15182 		return DONE_EXPLORING;
15183 
15184 	if (w < 0 || w >= env->prog->len) {
15185 		verbose_linfo(env, t, "%d: ", t);
15186 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15187 		return -EINVAL;
15188 	}
15189 
15190 	if (e == BRANCH) {
15191 		/* mark branch target for state pruning */
15192 		mark_prune_point(env, w);
15193 		mark_jmp_point(env, w);
15194 	}
15195 
15196 	if (insn_state[w] == 0) {
15197 		/* tree-edge */
15198 		insn_state[t] = DISCOVERED | e;
15199 		insn_state[w] = DISCOVERED;
15200 		if (env->cfg.cur_stack >= env->prog->len)
15201 			return -E2BIG;
15202 		insn_stack[env->cfg.cur_stack++] = w;
15203 		return KEEP_EXPLORING;
15204 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15205 		if (env->bpf_capable)
15206 			return DONE_EXPLORING;
15207 		verbose_linfo(env, t, "%d: ", t);
15208 		verbose_linfo(env, w, "%d: ", w);
15209 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15210 		return -EINVAL;
15211 	} else if (insn_state[w] == EXPLORED) {
15212 		/* forward- or cross-edge */
15213 		insn_state[t] = DISCOVERED | e;
15214 	} else {
15215 		verbose(env, "insn state internal bug\n");
15216 		return -EFAULT;
15217 	}
15218 	return DONE_EXPLORING;
15219 }
15220 
15221 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15222 				struct bpf_verifier_env *env,
15223 				bool visit_callee)
15224 {
15225 	int ret, insn_sz;
15226 
15227 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15228 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15229 	if (ret)
15230 		return ret;
15231 
15232 	mark_prune_point(env, t + insn_sz);
15233 	/* when we exit from subprog, we need to record non-linear history */
15234 	mark_jmp_point(env, t + insn_sz);
15235 
15236 	if (visit_callee) {
15237 		mark_prune_point(env, t);
15238 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15239 	}
15240 	return ret;
15241 }
15242 
15243 /* Visits the instruction at index t and returns one of the following:
15244  *  < 0 - an error occurred
15245  *  DONE_EXPLORING - the instruction was fully explored
15246  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15247  */
15248 static int visit_insn(int t, struct bpf_verifier_env *env)
15249 {
15250 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15251 	int ret, off, insn_sz;
15252 
15253 	if (bpf_pseudo_func(insn))
15254 		return visit_func_call_insn(t, insns, env, true);
15255 
15256 	/* All non-branch instructions have a single fall-through edge. */
15257 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15258 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15259 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15260 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15261 	}
15262 
15263 	switch (BPF_OP(insn->code)) {
15264 	case BPF_EXIT:
15265 		return DONE_EXPLORING;
15266 
15267 	case BPF_CALL:
15268 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15269 			/* Mark this call insn as a prune point to trigger
15270 			 * is_state_visited() check before call itself is
15271 			 * processed by __check_func_call(). Otherwise new
15272 			 * async state will be pushed for further exploration.
15273 			 */
15274 			mark_prune_point(env, t);
15275 		/* For functions that invoke callbacks it is not known how many times
15276 		 * callback would be called. Verifier models callback calling functions
15277 		 * by repeatedly visiting callback bodies and returning to origin call
15278 		 * instruction.
15279 		 * In order to stop such iteration verifier needs to identify when a
15280 		 * state identical some state from a previous iteration is reached.
15281 		 * Check below forces creation of checkpoint before callback calling
15282 		 * instruction to allow search for such identical states.
15283 		 */
15284 		if (is_sync_callback_calling_insn(insn)) {
15285 			mark_calls_callback(env, t);
15286 			mark_force_checkpoint(env, t);
15287 			mark_prune_point(env, t);
15288 			mark_jmp_point(env, t);
15289 		}
15290 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15291 			struct bpf_kfunc_call_arg_meta meta;
15292 
15293 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15294 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15295 				mark_prune_point(env, t);
15296 				/* Checking and saving state checkpoints at iter_next() call
15297 				 * is crucial for fast convergence of open-coded iterator loop
15298 				 * logic, so we need to force it. If we don't do that,
15299 				 * is_state_visited() might skip saving a checkpoint, causing
15300 				 * unnecessarily long sequence of not checkpointed
15301 				 * instructions and jumps, leading to exhaustion of jump
15302 				 * history buffer, and potentially other undesired outcomes.
15303 				 * It is expected that with correct open-coded iterators
15304 				 * convergence will happen quickly, so we don't run a risk of
15305 				 * exhausting memory.
15306 				 */
15307 				mark_force_checkpoint(env, t);
15308 			}
15309 		}
15310 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15311 
15312 	case BPF_JA:
15313 		if (BPF_SRC(insn->code) != BPF_K)
15314 			return -EINVAL;
15315 
15316 		if (BPF_CLASS(insn->code) == BPF_JMP)
15317 			off = insn->off;
15318 		else
15319 			off = insn->imm;
15320 
15321 		/* unconditional jump with single edge */
15322 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15323 		if (ret)
15324 			return ret;
15325 
15326 		mark_prune_point(env, t + off + 1);
15327 		mark_jmp_point(env, t + off + 1);
15328 
15329 		return ret;
15330 
15331 	default:
15332 		/* conditional jump with two edges */
15333 		mark_prune_point(env, t);
15334 
15335 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15336 		if (ret)
15337 			return ret;
15338 
15339 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15340 	}
15341 }
15342 
15343 /* non-recursive depth-first-search to detect loops in BPF program
15344  * loop == back-edge in directed graph
15345  */
15346 static int check_cfg(struct bpf_verifier_env *env)
15347 {
15348 	int insn_cnt = env->prog->len;
15349 	int *insn_stack, *insn_state;
15350 	int ret = 0;
15351 	int i;
15352 
15353 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15354 	if (!insn_state)
15355 		return -ENOMEM;
15356 
15357 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15358 	if (!insn_stack) {
15359 		kvfree(insn_state);
15360 		return -ENOMEM;
15361 	}
15362 
15363 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15364 	insn_stack[0] = 0; /* 0 is the first instruction */
15365 	env->cfg.cur_stack = 1;
15366 
15367 	while (env->cfg.cur_stack > 0) {
15368 		int t = insn_stack[env->cfg.cur_stack - 1];
15369 
15370 		ret = visit_insn(t, env);
15371 		switch (ret) {
15372 		case DONE_EXPLORING:
15373 			insn_state[t] = EXPLORED;
15374 			env->cfg.cur_stack--;
15375 			break;
15376 		case KEEP_EXPLORING:
15377 			break;
15378 		default:
15379 			if (ret > 0) {
15380 				verbose(env, "visit_insn internal bug\n");
15381 				ret = -EFAULT;
15382 			}
15383 			goto err_free;
15384 		}
15385 	}
15386 
15387 	if (env->cfg.cur_stack < 0) {
15388 		verbose(env, "pop stack internal bug\n");
15389 		ret = -EFAULT;
15390 		goto err_free;
15391 	}
15392 
15393 	for (i = 0; i < insn_cnt; i++) {
15394 		struct bpf_insn *insn = &env->prog->insnsi[i];
15395 
15396 		if (insn_state[i] != EXPLORED) {
15397 			verbose(env, "unreachable insn %d\n", i);
15398 			ret = -EINVAL;
15399 			goto err_free;
15400 		}
15401 		if (bpf_is_ldimm64(insn)) {
15402 			if (insn_state[i + 1] != 0) {
15403 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15404 				ret = -EINVAL;
15405 				goto err_free;
15406 			}
15407 			i++; /* skip second half of ldimm64 */
15408 		}
15409 	}
15410 	ret = 0; /* cfg looks good */
15411 
15412 err_free:
15413 	kvfree(insn_state);
15414 	kvfree(insn_stack);
15415 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15416 	return ret;
15417 }
15418 
15419 static int check_abnormal_return(struct bpf_verifier_env *env)
15420 {
15421 	int i;
15422 
15423 	for (i = 1; i < env->subprog_cnt; i++) {
15424 		if (env->subprog_info[i].has_ld_abs) {
15425 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15426 			return -EINVAL;
15427 		}
15428 		if (env->subprog_info[i].has_tail_call) {
15429 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15430 			return -EINVAL;
15431 		}
15432 	}
15433 	return 0;
15434 }
15435 
15436 /* The minimum supported BTF func info size */
15437 #define MIN_BPF_FUNCINFO_SIZE	8
15438 #define MAX_FUNCINFO_REC_SIZE	252
15439 
15440 static int check_btf_func(struct bpf_verifier_env *env,
15441 			  const union bpf_attr *attr,
15442 			  bpfptr_t uattr)
15443 {
15444 	const struct btf_type *type, *func_proto, *ret_type;
15445 	u32 i, nfuncs, urec_size, min_size;
15446 	u32 krec_size = sizeof(struct bpf_func_info);
15447 	struct bpf_func_info *krecord;
15448 	struct bpf_func_info_aux *info_aux = NULL;
15449 	struct bpf_prog *prog;
15450 	const struct btf *btf;
15451 	bpfptr_t urecord;
15452 	u32 prev_offset = 0;
15453 	bool scalar_return;
15454 	int ret = -ENOMEM;
15455 
15456 	nfuncs = attr->func_info_cnt;
15457 	if (!nfuncs) {
15458 		if (check_abnormal_return(env))
15459 			return -EINVAL;
15460 		return 0;
15461 	}
15462 
15463 	if (nfuncs != env->subprog_cnt) {
15464 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15465 		return -EINVAL;
15466 	}
15467 
15468 	urec_size = attr->func_info_rec_size;
15469 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15470 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15471 	    urec_size % sizeof(u32)) {
15472 		verbose(env, "invalid func info rec size %u\n", urec_size);
15473 		return -EINVAL;
15474 	}
15475 
15476 	prog = env->prog;
15477 	btf = prog->aux->btf;
15478 
15479 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15480 	min_size = min_t(u32, krec_size, urec_size);
15481 
15482 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15483 	if (!krecord)
15484 		return -ENOMEM;
15485 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15486 	if (!info_aux)
15487 		goto err_free;
15488 
15489 	for (i = 0; i < nfuncs; i++) {
15490 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15491 		if (ret) {
15492 			if (ret == -E2BIG) {
15493 				verbose(env, "nonzero tailing record in func info");
15494 				/* set the size kernel expects so loader can zero
15495 				 * out the rest of the record.
15496 				 */
15497 				if (copy_to_bpfptr_offset(uattr,
15498 							  offsetof(union bpf_attr, func_info_rec_size),
15499 							  &min_size, sizeof(min_size)))
15500 					ret = -EFAULT;
15501 			}
15502 			goto err_free;
15503 		}
15504 
15505 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15506 			ret = -EFAULT;
15507 			goto err_free;
15508 		}
15509 
15510 		/* check insn_off */
15511 		ret = -EINVAL;
15512 		if (i == 0) {
15513 			if (krecord[i].insn_off) {
15514 				verbose(env,
15515 					"nonzero insn_off %u for the first func info record",
15516 					krecord[i].insn_off);
15517 				goto err_free;
15518 			}
15519 		} else if (krecord[i].insn_off <= prev_offset) {
15520 			verbose(env,
15521 				"same or smaller insn offset (%u) than previous func info record (%u)",
15522 				krecord[i].insn_off, prev_offset);
15523 			goto err_free;
15524 		}
15525 
15526 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15527 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15528 			goto err_free;
15529 		}
15530 
15531 		/* check type_id */
15532 		type = btf_type_by_id(btf, krecord[i].type_id);
15533 		if (!type || !btf_type_is_func(type)) {
15534 			verbose(env, "invalid type id %d in func info",
15535 				krecord[i].type_id);
15536 			goto err_free;
15537 		}
15538 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15539 
15540 		func_proto = btf_type_by_id(btf, type->type);
15541 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15542 			/* btf_func_check() already verified it during BTF load */
15543 			goto err_free;
15544 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15545 		scalar_return =
15546 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15547 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15548 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15549 			goto err_free;
15550 		}
15551 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15552 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15553 			goto err_free;
15554 		}
15555 
15556 		prev_offset = krecord[i].insn_off;
15557 		bpfptr_add(&urecord, urec_size);
15558 	}
15559 
15560 	prog->aux->func_info = krecord;
15561 	prog->aux->func_info_cnt = nfuncs;
15562 	prog->aux->func_info_aux = info_aux;
15563 	return 0;
15564 
15565 err_free:
15566 	kvfree(krecord);
15567 	kfree(info_aux);
15568 	return ret;
15569 }
15570 
15571 static void adjust_btf_func(struct bpf_verifier_env *env)
15572 {
15573 	struct bpf_prog_aux *aux = env->prog->aux;
15574 	int i;
15575 
15576 	if (!aux->func_info)
15577 		return;
15578 
15579 	for (i = 0; i < env->subprog_cnt; i++)
15580 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15581 }
15582 
15583 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15584 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15585 
15586 static int check_btf_line(struct bpf_verifier_env *env,
15587 			  const union bpf_attr *attr,
15588 			  bpfptr_t uattr)
15589 {
15590 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15591 	struct bpf_subprog_info *sub;
15592 	struct bpf_line_info *linfo;
15593 	struct bpf_prog *prog;
15594 	const struct btf *btf;
15595 	bpfptr_t ulinfo;
15596 	int err;
15597 
15598 	nr_linfo = attr->line_info_cnt;
15599 	if (!nr_linfo)
15600 		return 0;
15601 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15602 		return -EINVAL;
15603 
15604 	rec_size = attr->line_info_rec_size;
15605 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15606 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15607 	    rec_size & (sizeof(u32) - 1))
15608 		return -EINVAL;
15609 
15610 	/* Need to zero it in case the userspace may
15611 	 * pass in a smaller bpf_line_info object.
15612 	 */
15613 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15614 			 GFP_KERNEL | __GFP_NOWARN);
15615 	if (!linfo)
15616 		return -ENOMEM;
15617 
15618 	prog = env->prog;
15619 	btf = prog->aux->btf;
15620 
15621 	s = 0;
15622 	sub = env->subprog_info;
15623 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15624 	expected_size = sizeof(struct bpf_line_info);
15625 	ncopy = min_t(u32, expected_size, rec_size);
15626 	for (i = 0; i < nr_linfo; i++) {
15627 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15628 		if (err) {
15629 			if (err == -E2BIG) {
15630 				verbose(env, "nonzero tailing record in line_info");
15631 				if (copy_to_bpfptr_offset(uattr,
15632 							  offsetof(union bpf_attr, line_info_rec_size),
15633 							  &expected_size, sizeof(expected_size)))
15634 					err = -EFAULT;
15635 			}
15636 			goto err_free;
15637 		}
15638 
15639 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15640 			err = -EFAULT;
15641 			goto err_free;
15642 		}
15643 
15644 		/*
15645 		 * Check insn_off to ensure
15646 		 * 1) strictly increasing AND
15647 		 * 2) bounded by prog->len
15648 		 *
15649 		 * The linfo[0].insn_off == 0 check logically falls into
15650 		 * the later "missing bpf_line_info for func..." case
15651 		 * because the first linfo[0].insn_off must be the
15652 		 * first sub also and the first sub must have
15653 		 * subprog_info[0].start == 0.
15654 		 */
15655 		if ((i && linfo[i].insn_off <= prev_offset) ||
15656 		    linfo[i].insn_off >= prog->len) {
15657 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15658 				i, linfo[i].insn_off, prev_offset,
15659 				prog->len);
15660 			err = -EINVAL;
15661 			goto err_free;
15662 		}
15663 
15664 		if (!prog->insnsi[linfo[i].insn_off].code) {
15665 			verbose(env,
15666 				"Invalid insn code at line_info[%u].insn_off\n",
15667 				i);
15668 			err = -EINVAL;
15669 			goto err_free;
15670 		}
15671 
15672 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15673 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15674 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15675 			err = -EINVAL;
15676 			goto err_free;
15677 		}
15678 
15679 		if (s != env->subprog_cnt) {
15680 			if (linfo[i].insn_off == sub[s].start) {
15681 				sub[s].linfo_idx = i;
15682 				s++;
15683 			} else if (sub[s].start < linfo[i].insn_off) {
15684 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15685 				err = -EINVAL;
15686 				goto err_free;
15687 			}
15688 		}
15689 
15690 		prev_offset = linfo[i].insn_off;
15691 		bpfptr_add(&ulinfo, rec_size);
15692 	}
15693 
15694 	if (s != env->subprog_cnt) {
15695 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15696 			env->subprog_cnt - s, s);
15697 		err = -EINVAL;
15698 		goto err_free;
15699 	}
15700 
15701 	prog->aux->linfo = linfo;
15702 	prog->aux->nr_linfo = nr_linfo;
15703 
15704 	return 0;
15705 
15706 err_free:
15707 	kvfree(linfo);
15708 	return err;
15709 }
15710 
15711 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15712 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15713 
15714 static int check_core_relo(struct bpf_verifier_env *env,
15715 			   const union bpf_attr *attr,
15716 			   bpfptr_t uattr)
15717 {
15718 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15719 	struct bpf_core_relo core_relo = {};
15720 	struct bpf_prog *prog = env->prog;
15721 	const struct btf *btf = prog->aux->btf;
15722 	struct bpf_core_ctx ctx = {
15723 		.log = &env->log,
15724 		.btf = btf,
15725 	};
15726 	bpfptr_t u_core_relo;
15727 	int err;
15728 
15729 	nr_core_relo = attr->core_relo_cnt;
15730 	if (!nr_core_relo)
15731 		return 0;
15732 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15733 		return -EINVAL;
15734 
15735 	rec_size = attr->core_relo_rec_size;
15736 	if (rec_size < MIN_CORE_RELO_SIZE ||
15737 	    rec_size > MAX_CORE_RELO_SIZE ||
15738 	    rec_size % sizeof(u32))
15739 		return -EINVAL;
15740 
15741 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15742 	expected_size = sizeof(struct bpf_core_relo);
15743 	ncopy = min_t(u32, expected_size, rec_size);
15744 
15745 	/* Unlike func_info and line_info, copy and apply each CO-RE
15746 	 * relocation record one at a time.
15747 	 */
15748 	for (i = 0; i < nr_core_relo; i++) {
15749 		/* future proofing when sizeof(bpf_core_relo) changes */
15750 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15751 		if (err) {
15752 			if (err == -E2BIG) {
15753 				verbose(env, "nonzero tailing record in core_relo");
15754 				if (copy_to_bpfptr_offset(uattr,
15755 							  offsetof(union bpf_attr, core_relo_rec_size),
15756 							  &expected_size, sizeof(expected_size)))
15757 					err = -EFAULT;
15758 			}
15759 			break;
15760 		}
15761 
15762 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15763 			err = -EFAULT;
15764 			break;
15765 		}
15766 
15767 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15768 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15769 				i, core_relo.insn_off, prog->len);
15770 			err = -EINVAL;
15771 			break;
15772 		}
15773 
15774 		err = bpf_core_apply(&ctx, &core_relo, i,
15775 				     &prog->insnsi[core_relo.insn_off / 8]);
15776 		if (err)
15777 			break;
15778 		bpfptr_add(&u_core_relo, rec_size);
15779 	}
15780 	return err;
15781 }
15782 
15783 static int check_btf_info(struct bpf_verifier_env *env,
15784 			  const union bpf_attr *attr,
15785 			  bpfptr_t uattr)
15786 {
15787 	struct btf *btf;
15788 	int err;
15789 
15790 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15791 		if (check_abnormal_return(env))
15792 			return -EINVAL;
15793 		return 0;
15794 	}
15795 
15796 	btf = btf_get_by_fd(attr->prog_btf_fd);
15797 	if (IS_ERR(btf))
15798 		return PTR_ERR(btf);
15799 	if (btf_is_kernel(btf)) {
15800 		btf_put(btf);
15801 		return -EACCES;
15802 	}
15803 	env->prog->aux->btf = btf;
15804 
15805 	err = check_btf_func(env, attr, uattr);
15806 	if (err)
15807 		return err;
15808 
15809 	err = check_btf_line(env, attr, uattr);
15810 	if (err)
15811 		return err;
15812 
15813 	err = check_core_relo(env, attr, uattr);
15814 	if (err)
15815 		return err;
15816 
15817 	return 0;
15818 }
15819 
15820 /* check %cur's range satisfies %old's */
15821 static bool range_within(struct bpf_reg_state *old,
15822 			 struct bpf_reg_state *cur)
15823 {
15824 	return old->umin_value <= cur->umin_value &&
15825 	       old->umax_value >= cur->umax_value &&
15826 	       old->smin_value <= cur->smin_value &&
15827 	       old->smax_value >= cur->smax_value &&
15828 	       old->u32_min_value <= cur->u32_min_value &&
15829 	       old->u32_max_value >= cur->u32_max_value &&
15830 	       old->s32_min_value <= cur->s32_min_value &&
15831 	       old->s32_max_value >= cur->s32_max_value;
15832 }
15833 
15834 /* If in the old state two registers had the same id, then they need to have
15835  * the same id in the new state as well.  But that id could be different from
15836  * the old state, so we need to track the mapping from old to new ids.
15837  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15838  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15839  * regs with a different old id could still have new id 9, we don't care about
15840  * that.
15841  * So we look through our idmap to see if this old id has been seen before.  If
15842  * so, we require the new id to match; otherwise, we add the id pair to the map.
15843  */
15844 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15845 {
15846 	struct bpf_id_pair *map = idmap->map;
15847 	unsigned int i;
15848 
15849 	/* either both IDs should be set or both should be zero */
15850 	if (!!old_id != !!cur_id)
15851 		return false;
15852 
15853 	if (old_id == 0) /* cur_id == 0 as well */
15854 		return true;
15855 
15856 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15857 		if (!map[i].old) {
15858 			/* Reached an empty slot; haven't seen this id before */
15859 			map[i].old = old_id;
15860 			map[i].cur = cur_id;
15861 			return true;
15862 		}
15863 		if (map[i].old == old_id)
15864 			return map[i].cur == cur_id;
15865 		if (map[i].cur == cur_id)
15866 			return false;
15867 	}
15868 	/* We ran out of idmap slots, which should be impossible */
15869 	WARN_ON_ONCE(1);
15870 	return false;
15871 }
15872 
15873 /* Similar to check_ids(), but allocate a unique temporary ID
15874  * for 'old_id' or 'cur_id' of zero.
15875  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15876  */
15877 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15878 {
15879 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15880 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15881 
15882 	return check_ids(old_id, cur_id, idmap);
15883 }
15884 
15885 static void clean_func_state(struct bpf_verifier_env *env,
15886 			     struct bpf_func_state *st)
15887 {
15888 	enum bpf_reg_liveness live;
15889 	int i, j;
15890 
15891 	for (i = 0; i < BPF_REG_FP; i++) {
15892 		live = st->regs[i].live;
15893 		/* liveness must not touch this register anymore */
15894 		st->regs[i].live |= REG_LIVE_DONE;
15895 		if (!(live & REG_LIVE_READ))
15896 			/* since the register is unused, clear its state
15897 			 * to make further comparison simpler
15898 			 */
15899 			__mark_reg_not_init(env, &st->regs[i]);
15900 	}
15901 
15902 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15903 		live = st->stack[i].spilled_ptr.live;
15904 		/* liveness must not touch this stack slot anymore */
15905 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15906 		if (!(live & REG_LIVE_READ)) {
15907 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15908 			for (j = 0; j < BPF_REG_SIZE; j++)
15909 				st->stack[i].slot_type[j] = STACK_INVALID;
15910 		}
15911 	}
15912 }
15913 
15914 static void clean_verifier_state(struct bpf_verifier_env *env,
15915 				 struct bpf_verifier_state *st)
15916 {
15917 	int i;
15918 
15919 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15920 		/* all regs in this state in all frames were already marked */
15921 		return;
15922 
15923 	for (i = 0; i <= st->curframe; i++)
15924 		clean_func_state(env, st->frame[i]);
15925 }
15926 
15927 /* the parentage chains form a tree.
15928  * the verifier states are added to state lists at given insn and
15929  * pushed into state stack for future exploration.
15930  * when the verifier reaches bpf_exit insn some of the verifer states
15931  * stored in the state lists have their final liveness state already,
15932  * but a lot of states will get revised from liveness point of view when
15933  * the verifier explores other branches.
15934  * Example:
15935  * 1: r0 = 1
15936  * 2: if r1 == 100 goto pc+1
15937  * 3: r0 = 2
15938  * 4: exit
15939  * when the verifier reaches exit insn the register r0 in the state list of
15940  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15941  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15942  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15943  *
15944  * Since the verifier pushes the branch states as it sees them while exploring
15945  * the program the condition of walking the branch instruction for the second
15946  * time means that all states below this branch were already explored and
15947  * their final liveness marks are already propagated.
15948  * Hence when the verifier completes the search of state list in is_state_visited()
15949  * we can call this clean_live_states() function to mark all liveness states
15950  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15951  * will not be used.
15952  * This function also clears the registers and stack for states that !READ
15953  * to simplify state merging.
15954  *
15955  * Important note here that walking the same branch instruction in the callee
15956  * doesn't meant that the states are DONE. The verifier has to compare
15957  * the callsites
15958  */
15959 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15960 			      struct bpf_verifier_state *cur)
15961 {
15962 	struct bpf_verifier_state_list *sl;
15963 
15964 	sl = *explored_state(env, insn);
15965 	while (sl) {
15966 		if (sl->state.branches)
15967 			goto next;
15968 		if (sl->state.insn_idx != insn ||
15969 		    !same_callsites(&sl->state, cur))
15970 			goto next;
15971 		clean_verifier_state(env, &sl->state);
15972 next:
15973 		sl = sl->next;
15974 	}
15975 }
15976 
15977 static bool regs_exact(const struct bpf_reg_state *rold,
15978 		       const struct bpf_reg_state *rcur,
15979 		       struct bpf_idmap *idmap)
15980 {
15981 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15982 	       check_ids(rold->id, rcur->id, idmap) &&
15983 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15984 }
15985 
15986 /* Returns true if (rold safe implies rcur safe) */
15987 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15988 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15989 {
15990 	if (exact)
15991 		return regs_exact(rold, rcur, idmap);
15992 
15993 	if (!(rold->live & REG_LIVE_READ))
15994 		/* explored state didn't use this */
15995 		return true;
15996 	if (rold->type == NOT_INIT)
15997 		/* explored state can't have used this */
15998 		return true;
15999 	if (rcur->type == NOT_INIT)
16000 		return false;
16001 
16002 	/* Enforce that register types have to match exactly, including their
16003 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16004 	 * rule.
16005 	 *
16006 	 * One can make a point that using a pointer register as unbounded
16007 	 * SCALAR would be technically acceptable, but this could lead to
16008 	 * pointer leaks because scalars are allowed to leak while pointers
16009 	 * are not. We could make this safe in special cases if root is
16010 	 * calling us, but it's probably not worth the hassle.
16011 	 *
16012 	 * Also, register types that are *not* MAYBE_NULL could technically be
16013 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16014 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16015 	 * to the same map).
16016 	 * However, if the old MAYBE_NULL register then got NULL checked,
16017 	 * doing so could have affected others with the same id, and we can't
16018 	 * check for that because we lost the id when we converted to
16019 	 * a non-MAYBE_NULL variant.
16020 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16021 	 * non-MAYBE_NULL registers as well.
16022 	 */
16023 	if (rold->type != rcur->type)
16024 		return false;
16025 
16026 	switch (base_type(rold->type)) {
16027 	case SCALAR_VALUE:
16028 		if (env->explore_alu_limits) {
16029 			/* explore_alu_limits disables tnum_in() and range_within()
16030 			 * logic and requires everything to be strict
16031 			 */
16032 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16033 			       check_scalar_ids(rold->id, rcur->id, idmap);
16034 		}
16035 		if (!rold->precise)
16036 			return true;
16037 		/* Why check_ids() for scalar registers?
16038 		 *
16039 		 * Consider the following BPF code:
16040 		 *   1: r6 = ... unbound scalar, ID=a ...
16041 		 *   2: r7 = ... unbound scalar, ID=b ...
16042 		 *   3: if (r6 > r7) goto +1
16043 		 *   4: r6 = r7
16044 		 *   5: if (r6 > X) goto ...
16045 		 *   6: ... memory operation using r7 ...
16046 		 *
16047 		 * First verification path is [1-6]:
16048 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16049 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16050 		 *   r7 <= X, because r6 and r7 share same id.
16051 		 * Next verification path is [1-4, 6].
16052 		 *
16053 		 * Instruction (6) would be reached in two states:
16054 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16055 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16056 		 *
16057 		 * Use check_ids() to distinguish these states.
16058 		 * ---
16059 		 * Also verify that new value satisfies old value range knowledge.
16060 		 */
16061 		return range_within(rold, rcur) &&
16062 		       tnum_in(rold->var_off, rcur->var_off) &&
16063 		       check_scalar_ids(rold->id, rcur->id, idmap);
16064 	case PTR_TO_MAP_KEY:
16065 	case PTR_TO_MAP_VALUE:
16066 	case PTR_TO_MEM:
16067 	case PTR_TO_BUF:
16068 	case PTR_TO_TP_BUFFER:
16069 		/* If the new min/max/var_off satisfy the old ones and
16070 		 * everything else matches, we are OK.
16071 		 */
16072 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16073 		       range_within(rold, rcur) &&
16074 		       tnum_in(rold->var_off, rcur->var_off) &&
16075 		       check_ids(rold->id, rcur->id, idmap) &&
16076 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16077 	case PTR_TO_PACKET_META:
16078 	case PTR_TO_PACKET:
16079 		/* We must have at least as much range as the old ptr
16080 		 * did, so that any accesses which were safe before are
16081 		 * still safe.  This is true even if old range < old off,
16082 		 * since someone could have accessed through (ptr - k), or
16083 		 * even done ptr -= k in a register, to get a safe access.
16084 		 */
16085 		if (rold->range > rcur->range)
16086 			return false;
16087 		/* If the offsets don't match, we can't trust our alignment;
16088 		 * nor can we be sure that we won't fall out of range.
16089 		 */
16090 		if (rold->off != rcur->off)
16091 			return false;
16092 		/* id relations must be preserved */
16093 		if (!check_ids(rold->id, rcur->id, idmap))
16094 			return false;
16095 		/* new val must satisfy old val knowledge */
16096 		return range_within(rold, rcur) &&
16097 		       tnum_in(rold->var_off, rcur->var_off);
16098 	case PTR_TO_STACK:
16099 		/* two stack pointers are equal only if they're pointing to
16100 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16101 		 */
16102 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16103 	default:
16104 		return regs_exact(rold, rcur, idmap);
16105 	}
16106 }
16107 
16108 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16109 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16110 {
16111 	int i, spi;
16112 
16113 	/* walk slots of the explored stack and ignore any additional
16114 	 * slots in the current stack, since explored(safe) state
16115 	 * didn't use them
16116 	 */
16117 	for (i = 0; i < old->allocated_stack; i++) {
16118 		struct bpf_reg_state *old_reg, *cur_reg;
16119 
16120 		spi = i / BPF_REG_SIZE;
16121 
16122 		if (exact &&
16123 		    (i >= cur->allocated_stack ||
16124 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16125 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16126 			return false;
16127 
16128 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16129 			i += BPF_REG_SIZE - 1;
16130 			/* explored state didn't use this */
16131 			continue;
16132 		}
16133 
16134 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16135 			continue;
16136 
16137 		if (env->allow_uninit_stack &&
16138 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16139 			continue;
16140 
16141 		/* explored stack has more populated slots than current stack
16142 		 * and these slots were used
16143 		 */
16144 		if (i >= cur->allocated_stack)
16145 			return false;
16146 
16147 		/* if old state was safe with misc data in the stack
16148 		 * it will be safe with zero-initialized stack.
16149 		 * The opposite is not true
16150 		 */
16151 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16152 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16153 			continue;
16154 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16155 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16156 			/* Ex: old explored (safe) state has STACK_SPILL in
16157 			 * this stack slot, but current has STACK_MISC ->
16158 			 * this verifier states are not equivalent,
16159 			 * return false to continue verification of this path
16160 			 */
16161 			return false;
16162 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16163 			continue;
16164 		/* Both old and cur are having same slot_type */
16165 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16166 		case STACK_SPILL:
16167 			/* when explored and current stack slot are both storing
16168 			 * spilled registers, check that stored pointers types
16169 			 * are the same as well.
16170 			 * Ex: explored safe path could have stored
16171 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16172 			 * but current path has stored:
16173 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16174 			 * such verifier states are not equivalent.
16175 			 * return false to continue verification of this path
16176 			 */
16177 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16178 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16179 				return false;
16180 			break;
16181 		case STACK_DYNPTR:
16182 			old_reg = &old->stack[spi].spilled_ptr;
16183 			cur_reg = &cur->stack[spi].spilled_ptr;
16184 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16185 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16186 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16187 				return false;
16188 			break;
16189 		case STACK_ITER:
16190 			old_reg = &old->stack[spi].spilled_ptr;
16191 			cur_reg = &cur->stack[spi].spilled_ptr;
16192 			/* iter.depth is not compared between states as it
16193 			 * doesn't matter for correctness and would otherwise
16194 			 * prevent convergence; we maintain it only to prevent
16195 			 * infinite loop check triggering, see
16196 			 * iter_active_depths_differ()
16197 			 */
16198 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16199 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16200 			    old_reg->iter.state != cur_reg->iter.state ||
16201 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16202 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16203 				return false;
16204 			break;
16205 		case STACK_MISC:
16206 		case STACK_ZERO:
16207 		case STACK_INVALID:
16208 			continue;
16209 		/* Ensure that new unhandled slot types return false by default */
16210 		default:
16211 			return false;
16212 		}
16213 	}
16214 	return true;
16215 }
16216 
16217 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16218 		    struct bpf_idmap *idmap)
16219 {
16220 	int i;
16221 
16222 	if (old->acquired_refs != cur->acquired_refs)
16223 		return false;
16224 
16225 	for (i = 0; i < old->acquired_refs; i++) {
16226 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16227 			return false;
16228 	}
16229 
16230 	return true;
16231 }
16232 
16233 /* compare two verifier states
16234  *
16235  * all states stored in state_list are known to be valid, since
16236  * verifier reached 'bpf_exit' instruction through them
16237  *
16238  * this function is called when verifier exploring different branches of
16239  * execution popped from the state stack. If it sees an old state that has
16240  * more strict register state and more strict stack state then this execution
16241  * branch doesn't need to be explored further, since verifier already
16242  * concluded that more strict state leads to valid finish.
16243  *
16244  * Therefore two states are equivalent if register state is more conservative
16245  * and explored stack state is more conservative than the current one.
16246  * Example:
16247  *       explored                   current
16248  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16249  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16250  *
16251  * In other words if current stack state (one being explored) has more
16252  * valid slots than old one that already passed validation, it means
16253  * the verifier can stop exploring and conclude that current state is valid too
16254  *
16255  * Similarly with registers. If explored state has register type as invalid
16256  * whereas register type in current state is meaningful, it means that
16257  * the current state will reach 'bpf_exit' instruction safely
16258  */
16259 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16260 			      struct bpf_func_state *cur, bool exact)
16261 {
16262 	int i;
16263 
16264 	if (old->callback_depth > cur->callback_depth)
16265 		return false;
16266 
16267 	for (i = 0; i < MAX_BPF_REG; i++)
16268 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16269 			     &env->idmap_scratch, exact))
16270 			return false;
16271 
16272 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16273 		return false;
16274 
16275 	if (!refsafe(old, cur, &env->idmap_scratch))
16276 		return false;
16277 
16278 	return true;
16279 }
16280 
16281 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16282 {
16283 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16284 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16285 }
16286 
16287 static bool states_equal(struct bpf_verifier_env *env,
16288 			 struct bpf_verifier_state *old,
16289 			 struct bpf_verifier_state *cur,
16290 			 bool exact)
16291 {
16292 	int i;
16293 
16294 	if (old->curframe != cur->curframe)
16295 		return false;
16296 
16297 	reset_idmap_scratch(env);
16298 
16299 	/* Verification state from speculative execution simulation
16300 	 * must never prune a non-speculative execution one.
16301 	 */
16302 	if (old->speculative && !cur->speculative)
16303 		return false;
16304 
16305 	if (old->active_lock.ptr != cur->active_lock.ptr)
16306 		return false;
16307 
16308 	/* Old and cur active_lock's have to be either both present
16309 	 * or both absent.
16310 	 */
16311 	if (!!old->active_lock.id != !!cur->active_lock.id)
16312 		return false;
16313 
16314 	if (old->active_lock.id &&
16315 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16316 		return false;
16317 
16318 	if (old->active_rcu_lock != cur->active_rcu_lock)
16319 		return false;
16320 
16321 	/* for states to be equal callsites have to be the same
16322 	 * and all frame states need to be equivalent
16323 	 */
16324 	for (i = 0; i <= old->curframe; i++) {
16325 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16326 			return false;
16327 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16328 			return false;
16329 	}
16330 	return true;
16331 }
16332 
16333 /* Return 0 if no propagation happened. Return negative error code if error
16334  * happened. Otherwise, return the propagated bit.
16335  */
16336 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16337 				  struct bpf_reg_state *reg,
16338 				  struct bpf_reg_state *parent_reg)
16339 {
16340 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16341 	u8 flag = reg->live & REG_LIVE_READ;
16342 	int err;
16343 
16344 	/* When comes here, read flags of PARENT_REG or REG could be any of
16345 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16346 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16347 	 */
16348 	if (parent_flag == REG_LIVE_READ64 ||
16349 	    /* Or if there is no read flag from REG. */
16350 	    !flag ||
16351 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16352 	    parent_flag == flag)
16353 		return 0;
16354 
16355 	err = mark_reg_read(env, reg, parent_reg, flag);
16356 	if (err)
16357 		return err;
16358 
16359 	return flag;
16360 }
16361 
16362 /* A write screens off any subsequent reads; but write marks come from the
16363  * straight-line code between a state and its parent.  When we arrive at an
16364  * equivalent state (jump target or such) we didn't arrive by the straight-line
16365  * code, so read marks in the state must propagate to the parent regardless
16366  * of the state's write marks. That's what 'parent == state->parent' comparison
16367  * in mark_reg_read() is for.
16368  */
16369 static int propagate_liveness(struct bpf_verifier_env *env,
16370 			      const struct bpf_verifier_state *vstate,
16371 			      struct bpf_verifier_state *vparent)
16372 {
16373 	struct bpf_reg_state *state_reg, *parent_reg;
16374 	struct bpf_func_state *state, *parent;
16375 	int i, frame, err = 0;
16376 
16377 	if (vparent->curframe != vstate->curframe) {
16378 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16379 		     vparent->curframe, vstate->curframe);
16380 		return -EFAULT;
16381 	}
16382 	/* Propagate read liveness of registers... */
16383 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16384 	for (frame = 0; frame <= vstate->curframe; frame++) {
16385 		parent = vparent->frame[frame];
16386 		state = vstate->frame[frame];
16387 		parent_reg = parent->regs;
16388 		state_reg = state->regs;
16389 		/* We don't need to worry about FP liveness, it's read-only */
16390 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16391 			err = propagate_liveness_reg(env, &state_reg[i],
16392 						     &parent_reg[i]);
16393 			if (err < 0)
16394 				return err;
16395 			if (err == REG_LIVE_READ64)
16396 				mark_insn_zext(env, &parent_reg[i]);
16397 		}
16398 
16399 		/* Propagate stack slots. */
16400 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16401 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16402 			parent_reg = &parent->stack[i].spilled_ptr;
16403 			state_reg = &state->stack[i].spilled_ptr;
16404 			err = propagate_liveness_reg(env, state_reg,
16405 						     parent_reg);
16406 			if (err < 0)
16407 				return err;
16408 		}
16409 	}
16410 	return 0;
16411 }
16412 
16413 /* find precise scalars in the previous equivalent state and
16414  * propagate them into the current state
16415  */
16416 static int propagate_precision(struct bpf_verifier_env *env,
16417 			       const struct bpf_verifier_state *old)
16418 {
16419 	struct bpf_reg_state *state_reg;
16420 	struct bpf_func_state *state;
16421 	int i, err = 0, fr;
16422 	bool first;
16423 
16424 	for (fr = old->curframe; fr >= 0; fr--) {
16425 		state = old->frame[fr];
16426 		state_reg = state->regs;
16427 		first = true;
16428 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16429 			if (state_reg->type != SCALAR_VALUE ||
16430 			    !state_reg->precise ||
16431 			    !(state_reg->live & REG_LIVE_READ))
16432 				continue;
16433 			if (env->log.level & BPF_LOG_LEVEL2) {
16434 				if (first)
16435 					verbose(env, "frame %d: propagating r%d", fr, i);
16436 				else
16437 					verbose(env, ",r%d", i);
16438 			}
16439 			bt_set_frame_reg(&env->bt, fr, i);
16440 			first = false;
16441 		}
16442 
16443 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16444 			if (!is_spilled_reg(&state->stack[i]))
16445 				continue;
16446 			state_reg = &state->stack[i].spilled_ptr;
16447 			if (state_reg->type != SCALAR_VALUE ||
16448 			    !state_reg->precise ||
16449 			    !(state_reg->live & REG_LIVE_READ))
16450 				continue;
16451 			if (env->log.level & BPF_LOG_LEVEL2) {
16452 				if (first)
16453 					verbose(env, "frame %d: propagating fp%d",
16454 						fr, (-i - 1) * BPF_REG_SIZE);
16455 				else
16456 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16457 			}
16458 			bt_set_frame_slot(&env->bt, fr, i);
16459 			first = false;
16460 		}
16461 		if (!first)
16462 			verbose(env, "\n");
16463 	}
16464 
16465 	err = mark_chain_precision_batch(env);
16466 	if (err < 0)
16467 		return err;
16468 
16469 	return 0;
16470 }
16471 
16472 static bool states_maybe_looping(struct bpf_verifier_state *old,
16473 				 struct bpf_verifier_state *cur)
16474 {
16475 	struct bpf_func_state *fold, *fcur;
16476 	int i, fr = cur->curframe;
16477 
16478 	if (old->curframe != fr)
16479 		return false;
16480 
16481 	fold = old->frame[fr];
16482 	fcur = cur->frame[fr];
16483 	for (i = 0; i < MAX_BPF_REG; i++)
16484 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16485 			   offsetof(struct bpf_reg_state, parent)))
16486 			return false;
16487 	return true;
16488 }
16489 
16490 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16491 {
16492 	return env->insn_aux_data[insn_idx].is_iter_next;
16493 }
16494 
16495 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16496  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16497  * states to match, which otherwise would look like an infinite loop. So while
16498  * iter_next() calls are taken care of, we still need to be careful and
16499  * prevent erroneous and too eager declaration of "ininite loop", when
16500  * iterators are involved.
16501  *
16502  * Here's a situation in pseudo-BPF assembly form:
16503  *
16504  *   0: again:                          ; set up iter_next() call args
16505  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16506  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16507  *   3:   if r0 == 0 goto done
16508  *   4:   ... something useful here ...
16509  *   5:   goto again                    ; another iteration
16510  *   6: done:
16511  *   7:   r1 = &it
16512  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16513  *   9:   exit
16514  *
16515  * This is a typical loop. Let's assume that we have a prune point at 1:,
16516  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16517  * again`, assuming other heuristics don't get in a way).
16518  *
16519  * When we first time come to 1:, let's say we have some state X. We proceed
16520  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16521  * Now we come back to validate that forked ACTIVE state. We proceed through
16522  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16523  * are converging. But the problem is that we don't know that yet, as this
16524  * convergence has to happen at iter_next() call site only. So if nothing is
16525  * done, at 1: verifier will use bounded loop logic and declare infinite
16526  * looping (and would be *technically* correct, if not for iterator's
16527  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16528  * don't want that. So what we do in process_iter_next_call() when we go on
16529  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16530  * a different iteration. So when we suspect an infinite loop, we additionally
16531  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16532  * pretend we are not looping and wait for next iter_next() call.
16533  *
16534  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16535  * loop, because that would actually mean infinite loop, as DRAINED state is
16536  * "sticky", and so we'll keep returning into the same instruction with the
16537  * same state (at least in one of possible code paths).
16538  *
16539  * This approach allows to keep infinite loop heuristic even in the face of
16540  * active iterator. E.g., C snippet below is and will be detected as
16541  * inifintely looping:
16542  *
16543  *   struct bpf_iter_num it;
16544  *   int *p, x;
16545  *
16546  *   bpf_iter_num_new(&it, 0, 10);
16547  *   while ((p = bpf_iter_num_next(&t))) {
16548  *       x = p;
16549  *       while (x--) {} // <<-- infinite loop here
16550  *   }
16551  *
16552  */
16553 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16554 {
16555 	struct bpf_reg_state *slot, *cur_slot;
16556 	struct bpf_func_state *state;
16557 	int i, fr;
16558 
16559 	for (fr = old->curframe; fr >= 0; fr--) {
16560 		state = old->frame[fr];
16561 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16562 			if (state->stack[i].slot_type[0] != STACK_ITER)
16563 				continue;
16564 
16565 			slot = &state->stack[i].spilled_ptr;
16566 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16567 				continue;
16568 
16569 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16570 			if (cur_slot->iter.depth != slot->iter.depth)
16571 				return true;
16572 		}
16573 	}
16574 	return false;
16575 }
16576 
16577 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16578 {
16579 	struct bpf_verifier_state_list *new_sl;
16580 	struct bpf_verifier_state_list *sl, **pprev;
16581 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16582 	int i, j, n, err, states_cnt = 0;
16583 	bool force_new_state, add_new_state, force_exact;
16584 
16585 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
16586 			  /* Avoid accumulating infinitely long jmp history */
16587 			  cur->jmp_history_cnt > 40;
16588 
16589 	/* bpf progs typically have pruning point every 4 instructions
16590 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16591 	 * Do not add new state for future pruning if the verifier hasn't seen
16592 	 * at least 2 jumps and at least 8 instructions.
16593 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16594 	 * In tests that amounts to up to 50% reduction into total verifier
16595 	 * memory consumption and 20% verifier time speedup.
16596 	 */
16597 	add_new_state = force_new_state;
16598 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16599 	    env->insn_processed - env->prev_insn_processed >= 8)
16600 		add_new_state = true;
16601 
16602 	pprev = explored_state(env, insn_idx);
16603 	sl = *pprev;
16604 
16605 	clean_live_states(env, insn_idx, cur);
16606 
16607 	while (sl) {
16608 		states_cnt++;
16609 		if (sl->state.insn_idx != insn_idx)
16610 			goto next;
16611 
16612 		if (sl->state.branches) {
16613 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16614 
16615 			if (frame->in_async_callback_fn &&
16616 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16617 				/* Different async_entry_cnt means that the verifier is
16618 				 * processing another entry into async callback.
16619 				 * Seeing the same state is not an indication of infinite
16620 				 * loop or infinite recursion.
16621 				 * But finding the same state doesn't mean that it's safe
16622 				 * to stop processing the current state. The previous state
16623 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16624 				 * Checking in_async_callback_fn alone is not enough either.
16625 				 * Since the verifier still needs to catch infinite loops
16626 				 * inside async callbacks.
16627 				 */
16628 				goto skip_inf_loop_check;
16629 			}
16630 			/* BPF open-coded iterators loop detection is special.
16631 			 * states_maybe_looping() logic is too simplistic in detecting
16632 			 * states that *might* be equivalent, because it doesn't know
16633 			 * about ID remapping, so don't even perform it.
16634 			 * See process_iter_next_call() and iter_active_depths_differ()
16635 			 * for overview of the logic. When current and one of parent
16636 			 * states are detected as equivalent, it's a good thing: we prove
16637 			 * convergence and can stop simulating further iterations.
16638 			 * It's safe to assume that iterator loop will finish, taking into
16639 			 * account iter_next() contract of eventually returning
16640 			 * sticky NULL result.
16641 			 *
16642 			 * Note, that states have to be compared exactly in this case because
16643 			 * read and precision marks might not be finalized inside the loop.
16644 			 * E.g. as in the program below:
16645 			 *
16646 			 *     1. r7 = -16
16647 			 *     2. r6 = bpf_get_prandom_u32()
16648 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16649 			 *     4.   if (r6 != 42) {
16650 			 *     5.     r7 = -32
16651 			 *     6.     r6 = bpf_get_prandom_u32()
16652 			 *     7.     continue
16653 			 *     8.   }
16654 			 *     9.   r0 = r10
16655 			 *    10.   r0 += r7
16656 			 *    11.   r8 = *(u64 *)(r0 + 0)
16657 			 *    12.   r6 = bpf_get_prandom_u32()
16658 			 *    13. }
16659 			 *
16660 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16661 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16662 			 * not have read or precision mark for r7 yet, thus inexact states
16663 			 * comparison would discard current state with r7=-32
16664 			 * => unsafe memory access at 11 would not be caught.
16665 			 */
16666 			if (is_iter_next_insn(env, insn_idx)) {
16667 				if (states_equal(env, &sl->state, cur, true)) {
16668 					struct bpf_func_state *cur_frame;
16669 					struct bpf_reg_state *iter_state, *iter_reg;
16670 					int spi;
16671 
16672 					cur_frame = cur->frame[cur->curframe];
16673 					/* btf_check_iter_kfuncs() enforces that
16674 					 * iter state pointer is always the first arg
16675 					 */
16676 					iter_reg = &cur_frame->regs[BPF_REG_1];
16677 					/* current state is valid due to states_equal(),
16678 					 * so we can assume valid iter and reg state,
16679 					 * no need for extra (re-)validations
16680 					 */
16681 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16682 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16683 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16684 						update_loop_entry(cur, &sl->state);
16685 						goto hit;
16686 					}
16687 				}
16688 				goto skip_inf_loop_check;
16689 			}
16690 			if (calls_callback(env, insn_idx)) {
16691 				if (states_equal(env, &sl->state, cur, true))
16692 					goto hit;
16693 				goto skip_inf_loop_check;
16694 			}
16695 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16696 			if (states_maybe_looping(&sl->state, cur) &&
16697 			    states_equal(env, &sl->state, cur, false) &&
16698 			    !iter_active_depths_differ(&sl->state, cur) &&
16699 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16700 				verbose_linfo(env, insn_idx, "; ");
16701 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16702 				verbose(env, "cur state:");
16703 				print_verifier_state(env, cur->frame[cur->curframe], true);
16704 				verbose(env, "old state:");
16705 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16706 				return -EINVAL;
16707 			}
16708 			/* if the verifier is processing a loop, avoid adding new state
16709 			 * too often, since different loop iterations have distinct
16710 			 * states and may not help future pruning.
16711 			 * This threshold shouldn't be too low to make sure that
16712 			 * a loop with large bound will be rejected quickly.
16713 			 * The most abusive loop will be:
16714 			 * r1 += 1
16715 			 * if r1 < 1000000 goto pc-2
16716 			 * 1M insn_procssed limit / 100 == 10k peak states.
16717 			 * This threshold shouldn't be too high either, since states
16718 			 * at the end of the loop are likely to be useful in pruning.
16719 			 */
16720 skip_inf_loop_check:
16721 			if (!force_new_state &&
16722 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16723 			    env->insn_processed - env->prev_insn_processed < 100)
16724 				add_new_state = false;
16725 			goto miss;
16726 		}
16727 		/* If sl->state is a part of a loop and this loop's entry is a part of
16728 		 * current verification path then states have to be compared exactly.
16729 		 * 'force_exact' is needed to catch the following case:
16730 		 *
16731 		 *                initial     Here state 'succ' was processed first,
16732 		 *                  |         it was eventually tracked to produce a
16733 		 *                  V         state identical to 'hdr'.
16734 		 *     .---------> hdr        All branches from 'succ' had been explored
16735 		 *     |            |         and thus 'succ' has its .branches == 0.
16736 		 *     |            V
16737 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16738 		 *     |    |       |         to the same instruction + callsites.
16739 		 *     |    V       V         In such case it is necessary to check
16740 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16741 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16742 		 *     |    V       V         same loop exact flag has to be set.
16743 		 *     |   succ <- cur        To check if that is the case, verify
16744 		 *     |    |                 if loop entry of 'succ' is in current
16745 		 *     |    V                 DFS path.
16746 		 *     |   ...
16747 		 *     |    |
16748 		 *     '----'
16749 		 *
16750 		 * Additional details are in the comment before get_loop_entry().
16751 		 */
16752 		loop_entry = get_loop_entry(&sl->state);
16753 		force_exact = loop_entry && loop_entry->branches > 0;
16754 		if (states_equal(env, &sl->state, cur, force_exact)) {
16755 			if (force_exact)
16756 				update_loop_entry(cur, loop_entry);
16757 hit:
16758 			sl->hit_cnt++;
16759 			/* reached equivalent register/stack state,
16760 			 * prune the search.
16761 			 * Registers read by the continuation are read by us.
16762 			 * If we have any write marks in env->cur_state, they
16763 			 * will prevent corresponding reads in the continuation
16764 			 * from reaching our parent (an explored_state).  Our
16765 			 * own state will get the read marks recorded, but
16766 			 * they'll be immediately forgotten as we're pruning
16767 			 * this state and will pop a new one.
16768 			 */
16769 			err = propagate_liveness(env, &sl->state, cur);
16770 
16771 			/* if previous state reached the exit with precision and
16772 			 * current state is equivalent to it (except precsion marks)
16773 			 * the precision needs to be propagated back in
16774 			 * the current state.
16775 			 */
16776 			err = err ? : push_jmp_history(env, cur);
16777 			err = err ? : propagate_precision(env, &sl->state);
16778 			if (err)
16779 				return err;
16780 			return 1;
16781 		}
16782 miss:
16783 		/* when new state is not going to be added do not increase miss count.
16784 		 * Otherwise several loop iterations will remove the state
16785 		 * recorded earlier. The goal of these heuristics is to have
16786 		 * states from some iterations of the loop (some in the beginning
16787 		 * and some at the end) to help pruning.
16788 		 */
16789 		if (add_new_state)
16790 			sl->miss_cnt++;
16791 		/* heuristic to determine whether this state is beneficial
16792 		 * to keep checking from state equivalence point of view.
16793 		 * Higher numbers increase max_states_per_insn and verification time,
16794 		 * but do not meaningfully decrease insn_processed.
16795 		 * 'n' controls how many times state could miss before eviction.
16796 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16797 		 * too early would hinder iterator convergence.
16798 		 */
16799 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16800 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16801 			/* the state is unlikely to be useful. Remove it to
16802 			 * speed up verification
16803 			 */
16804 			*pprev = sl->next;
16805 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16806 			    !sl->state.used_as_loop_entry) {
16807 				u32 br = sl->state.branches;
16808 
16809 				WARN_ONCE(br,
16810 					  "BUG live_done but branches_to_explore %d\n",
16811 					  br);
16812 				free_verifier_state(&sl->state, false);
16813 				kfree(sl);
16814 				env->peak_states--;
16815 			} else {
16816 				/* cannot free this state, since parentage chain may
16817 				 * walk it later. Add it for free_list instead to
16818 				 * be freed at the end of verification
16819 				 */
16820 				sl->next = env->free_list;
16821 				env->free_list = sl;
16822 			}
16823 			sl = *pprev;
16824 			continue;
16825 		}
16826 next:
16827 		pprev = &sl->next;
16828 		sl = *pprev;
16829 	}
16830 
16831 	if (env->max_states_per_insn < states_cnt)
16832 		env->max_states_per_insn = states_cnt;
16833 
16834 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16835 		return 0;
16836 
16837 	if (!add_new_state)
16838 		return 0;
16839 
16840 	/* There were no equivalent states, remember the current one.
16841 	 * Technically the current state is not proven to be safe yet,
16842 	 * but it will either reach outer most bpf_exit (which means it's safe)
16843 	 * or it will be rejected. When there are no loops the verifier won't be
16844 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16845 	 * again on the way to bpf_exit.
16846 	 * When looping the sl->state.branches will be > 0 and this state
16847 	 * will not be considered for equivalence until branches == 0.
16848 	 */
16849 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16850 	if (!new_sl)
16851 		return -ENOMEM;
16852 	env->total_states++;
16853 	env->peak_states++;
16854 	env->prev_jmps_processed = env->jmps_processed;
16855 	env->prev_insn_processed = env->insn_processed;
16856 
16857 	/* forget precise markings we inherited, see __mark_chain_precision */
16858 	if (env->bpf_capable)
16859 		mark_all_scalars_imprecise(env, cur);
16860 
16861 	/* add new state to the head of linked list */
16862 	new = &new_sl->state;
16863 	err = copy_verifier_state(new, cur);
16864 	if (err) {
16865 		free_verifier_state(new, false);
16866 		kfree(new_sl);
16867 		return err;
16868 	}
16869 	new->insn_idx = insn_idx;
16870 	WARN_ONCE(new->branches != 1,
16871 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16872 
16873 	cur->parent = new;
16874 	cur->first_insn_idx = insn_idx;
16875 	cur->dfs_depth = new->dfs_depth + 1;
16876 	clear_jmp_history(cur);
16877 	new_sl->next = *explored_state(env, insn_idx);
16878 	*explored_state(env, insn_idx) = new_sl;
16879 	/* connect new state to parentage chain. Current frame needs all
16880 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16881 	 * to the stack implicitly by JITs) so in callers' frames connect just
16882 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16883 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16884 	 * from callee with its full parentage chain, anyway.
16885 	 */
16886 	/* clear write marks in current state: the writes we did are not writes
16887 	 * our child did, so they don't screen off its reads from us.
16888 	 * (There are no read marks in current state, because reads always mark
16889 	 * their parent and current state never has children yet.  Only
16890 	 * explored_states can get read marks.)
16891 	 */
16892 	for (j = 0; j <= cur->curframe; j++) {
16893 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16894 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16895 		for (i = 0; i < BPF_REG_FP; i++)
16896 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16897 	}
16898 
16899 	/* all stack frames are accessible from callee, clear them all */
16900 	for (j = 0; j <= cur->curframe; j++) {
16901 		struct bpf_func_state *frame = cur->frame[j];
16902 		struct bpf_func_state *newframe = new->frame[j];
16903 
16904 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16905 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16906 			frame->stack[i].spilled_ptr.parent =
16907 						&newframe->stack[i].spilled_ptr;
16908 		}
16909 	}
16910 	return 0;
16911 }
16912 
16913 /* Return true if it's OK to have the same insn return a different type. */
16914 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16915 {
16916 	switch (base_type(type)) {
16917 	case PTR_TO_CTX:
16918 	case PTR_TO_SOCKET:
16919 	case PTR_TO_SOCK_COMMON:
16920 	case PTR_TO_TCP_SOCK:
16921 	case PTR_TO_XDP_SOCK:
16922 	case PTR_TO_BTF_ID:
16923 		return false;
16924 	default:
16925 		return true;
16926 	}
16927 }
16928 
16929 /* If an instruction was previously used with particular pointer types, then we
16930  * need to be careful to avoid cases such as the below, where it may be ok
16931  * for one branch accessing the pointer, but not ok for the other branch:
16932  *
16933  * R1 = sock_ptr
16934  * goto X;
16935  * ...
16936  * R1 = some_other_valid_ptr;
16937  * goto X;
16938  * ...
16939  * R2 = *(u32 *)(R1 + 0);
16940  */
16941 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16942 {
16943 	return src != prev && (!reg_type_mismatch_ok(src) ||
16944 			       !reg_type_mismatch_ok(prev));
16945 }
16946 
16947 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16948 			     bool allow_trust_missmatch)
16949 {
16950 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16951 
16952 	if (*prev_type == NOT_INIT) {
16953 		/* Saw a valid insn
16954 		 * dst_reg = *(u32 *)(src_reg + off)
16955 		 * save type to validate intersecting paths
16956 		 */
16957 		*prev_type = type;
16958 	} else if (reg_type_mismatch(type, *prev_type)) {
16959 		/* Abuser program is trying to use the same insn
16960 		 * dst_reg = *(u32*) (src_reg + off)
16961 		 * with different pointer types:
16962 		 * src_reg == ctx in one branch and
16963 		 * src_reg == stack|map in some other branch.
16964 		 * Reject it.
16965 		 */
16966 		if (allow_trust_missmatch &&
16967 		    base_type(type) == PTR_TO_BTF_ID &&
16968 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16969 			/*
16970 			 * Have to support a use case when one path through
16971 			 * the program yields TRUSTED pointer while another
16972 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16973 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16974 			 */
16975 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16976 		} else {
16977 			verbose(env, "same insn cannot be used with different pointers\n");
16978 			return -EINVAL;
16979 		}
16980 	}
16981 
16982 	return 0;
16983 }
16984 
16985 static int do_check(struct bpf_verifier_env *env)
16986 {
16987 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16988 	struct bpf_verifier_state *state = env->cur_state;
16989 	struct bpf_insn *insns = env->prog->insnsi;
16990 	struct bpf_reg_state *regs;
16991 	int insn_cnt = env->prog->len;
16992 	bool do_print_state = false;
16993 	int prev_insn_idx = -1;
16994 
16995 	for (;;) {
16996 		struct bpf_insn *insn;
16997 		u8 class;
16998 		int err;
16999 
17000 		env->prev_insn_idx = prev_insn_idx;
17001 		if (env->insn_idx >= insn_cnt) {
17002 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17003 				env->insn_idx, insn_cnt);
17004 			return -EFAULT;
17005 		}
17006 
17007 		insn = &insns[env->insn_idx];
17008 		class = BPF_CLASS(insn->code);
17009 
17010 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17011 			verbose(env,
17012 				"BPF program is too large. Processed %d insn\n",
17013 				env->insn_processed);
17014 			return -E2BIG;
17015 		}
17016 
17017 		state->last_insn_idx = env->prev_insn_idx;
17018 
17019 		if (is_prune_point(env, env->insn_idx)) {
17020 			err = is_state_visited(env, env->insn_idx);
17021 			if (err < 0)
17022 				return err;
17023 			if (err == 1) {
17024 				/* found equivalent state, can prune the search */
17025 				if (env->log.level & BPF_LOG_LEVEL) {
17026 					if (do_print_state)
17027 						verbose(env, "\nfrom %d to %d%s: safe\n",
17028 							env->prev_insn_idx, env->insn_idx,
17029 							env->cur_state->speculative ?
17030 							" (speculative execution)" : "");
17031 					else
17032 						verbose(env, "%d: safe\n", env->insn_idx);
17033 				}
17034 				goto process_bpf_exit;
17035 			}
17036 		}
17037 
17038 		if (is_jmp_point(env, env->insn_idx)) {
17039 			err = push_jmp_history(env, state);
17040 			if (err)
17041 				return err;
17042 		}
17043 
17044 		if (signal_pending(current))
17045 			return -EAGAIN;
17046 
17047 		if (need_resched())
17048 			cond_resched();
17049 
17050 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17051 			verbose(env, "\nfrom %d to %d%s:",
17052 				env->prev_insn_idx, env->insn_idx,
17053 				env->cur_state->speculative ?
17054 				" (speculative execution)" : "");
17055 			print_verifier_state(env, state->frame[state->curframe], true);
17056 			do_print_state = false;
17057 		}
17058 
17059 		if (env->log.level & BPF_LOG_LEVEL) {
17060 			const struct bpf_insn_cbs cbs = {
17061 				.cb_call	= disasm_kfunc_name,
17062 				.cb_print	= verbose,
17063 				.private_data	= env,
17064 			};
17065 
17066 			if (verifier_state_scratched(env))
17067 				print_insn_state(env, state->frame[state->curframe]);
17068 
17069 			verbose_linfo(env, env->insn_idx, "; ");
17070 			env->prev_log_pos = env->log.end_pos;
17071 			verbose(env, "%d: ", env->insn_idx);
17072 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17073 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17074 			env->prev_log_pos = env->log.end_pos;
17075 		}
17076 
17077 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17078 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17079 							   env->prev_insn_idx);
17080 			if (err)
17081 				return err;
17082 		}
17083 
17084 		regs = cur_regs(env);
17085 		sanitize_mark_insn_seen(env);
17086 		prev_insn_idx = env->insn_idx;
17087 
17088 		if (class == BPF_ALU || class == BPF_ALU64) {
17089 			err = check_alu_op(env, insn);
17090 			if (err)
17091 				return err;
17092 
17093 		} else if (class == BPF_LDX) {
17094 			enum bpf_reg_type src_reg_type;
17095 
17096 			/* check for reserved fields is already done */
17097 
17098 			/* check src operand */
17099 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17100 			if (err)
17101 				return err;
17102 
17103 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17104 			if (err)
17105 				return err;
17106 
17107 			src_reg_type = regs[insn->src_reg].type;
17108 
17109 			/* check that memory (src_reg + off) is readable,
17110 			 * the state of dst_reg will be updated by this func
17111 			 */
17112 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17113 					       insn->off, BPF_SIZE(insn->code),
17114 					       BPF_READ, insn->dst_reg, false,
17115 					       BPF_MODE(insn->code) == BPF_MEMSX);
17116 			if (err)
17117 				return err;
17118 
17119 			err = save_aux_ptr_type(env, src_reg_type, true);
17120 			if (err)
17121 				return err;
17122 		} else if (class == BPF_STX) {
17123 			enum bpf_reg_type dst_reg_type;
17124 
17125 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17126 				err = check_atomic(env, env->insn_idx, insn);
17127 				if (err)
17128 					return err;
17129 				env->insn_idx++;
17130 				continue;
17131 			}
17132 
17133 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17134 				verbose(env, "BPF_STX uses reserved fields\n");
17135 				return -EINVAL;
17136 			}
17137 
17138 			/* check src1 operand */
17139 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17140 			if (err)
17141 				return err;
17142 			/* check src2 operand */
17143 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17144 			if (err)
17145 				return err;
17146 
17147 			dst_reg_type = regs[insn->dst_reg].type;
17148 
17149 			/* check that memory (dst_reg + off) is writeable */
17150 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17151 					       insn->off, BPF_SIZE(insn->code),
17152 					       BPF_WRITE, insn->src_reg, false, false);
17153 			if (err)
17154 				return err;
17155 
17156 			err = save_aux_ptr_type(env, dst_reg_type, false);
17157 			if (err)
17158 				return err;
17159 		} else if (class == BPF_ST) {
17160 			enum bpf_reg_type dst_reg_type;
17161 
17162 			if (BPF_MODE(insn->code) != BPF_MEM ||
17163 			    insn->src_reg != BPF_REG_0) {
17164 				verbose(env, "BPF_ST uses reserved fields\n");
17165 				return -EINVAL;
17166 			}
17167 			/* check src operand */
17168 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17169 			if (err)
17170 				return err;
17171 
17172 			dst_reg_type = regs[insn->dst_reg].type;
17173 
17174 			/* check that memory (dst_reg + off) is writeable */
17175 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17176 					       insn->off, BPF_SIZE(insn->code),
17177 					       BPF_WRITE, -1, false, false);
17178 			if (err)
17179 				return err;
17180 
17181 			err = save_aux_ptr_type(env, dst_reg_type, false);
17182 			if (err)
17183 				return err;
17184 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17185 			u8 opcode = BPF_OP(insn->code);
17186 
17187 			env->jmps_processed++;
17188 			if (opcode == BPF_CALL) {
17189 				if (BPF_SRC(insn->code) != BPF_K ||
17190 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17191 				     && insn->off != 0) ||
17192 				    (insn->src_reg != BPF_REG_0 &&
17193 				     insn->src_reg != BPF_PSEUDO_CALL &&
17194 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17195 				    insn->dst_reg != BPF_REG_0 ||
17196 				    class == BPF_JMP32) {
17197 					verbose(env, "BPF_CALL uses reserved fields\n");
17198 					return -EINVAL;
17199 				}
17200 
17201 				if (env->cur_state->active_lock.ptr) {
17202 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17203 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17204 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17205 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17206 						verbose(env, "function calls are not allowed while holding a lock\n");
17207 						return -EINVAL;
17208 					}
17209 				}
17210 				if (insn->src_reg == BPF_PSEUDO_CALL)
17211 					err = check_func_call(env, insn, &env->insn_idx);
17212 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17213 					err = check_kfunc_call(env, insn, &env->insn_idx);
17214 				else
17215 					err = check_helper_call(env, insn, &env->insn_idx);
17216 				if (err)
17217 					return err;
17218 
17219 				mark_reg_scratched(env, BPF_REG_0);
17220 			} else if (opcode == BPF_JA) {
17221 				if (BPF_SRC(insn->code) != BPF_K ||
17222 				    insn->src_reg != BPF_REG_0 ||
17223 				    insn->dst_reg != BPF_REG_0 ||
17224 				    (class == BPF_JMP && insn->imm != 0) ||
17225 				    (class == BPF_JMP32 && insn->off != 0)) {
17226 					verbose(env, "BPF_JA uses reserved fields\n");
17227 					return -EINVAL;
17228 				}
17229 
17230 				if (class == BPF_JMP)
17231 					env->insn_idx += insn->off + 1;
17232 				else
17233 					env->insn_idx += insn->imm + 1;
17234 				continue;
17235 
17236 			} else if (opcode == BPF_EXIT) {
17237 				if (BPF_SRC(insn->code) != BPF_K ||
17238 				    insn->imm != 0 ||
17239 				    insn->src_reg != BPF_REG_0 ||
17240 				    insn->dst_reg != BPF_REG_0 ||
17241 				    class == BPF_JMP32) {
17242 					verbose(env, "BPF_EXIT uses reserved fields\n");
17243 					return -EINVAL;
17244 				}
17245 
17246 				if (env->cur_state->active_lock.ptr &&
17247 				    !in_rbtree_lock_required_cb(env)) {
17248 					verbose(env, "bpf_spin_unlock is missing\n");
17249 					return -EINVAL;
17250 				}
17251 
17252 				if (env->cur_state->active_rcu_lock &&
17253 				    !in_rbtree_lock_required_cb(env)) {
17254 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17255 					return -EINVAL;
17256 				}
17257 
17258 				/* We must do check_reference_leak here before
17259 				 * prepare_func_exit to handle the case when
17260 				 * state->curframe > 0, it may be a callback
17261 				 * function, for which reference_state must
17262 				 * match caller reference state when it exits.
17263 				 */
17264 				err = check_reference_leak(env);
17265 				if (err)
17266 					return err;
17267 
17268 				if (state->curframe) {
17269 					/* exit from nested function */
17270 					err = prepare_func_exit(env, &env->insn_idx);
17271 					if (err)
17272 						return err;
17273 					do_print_state = true;
17274 					continue;
17275 				}
17276 
17277 				err = check_return_code(env);
17278 				if (err)
17279 					return err;
17280 process_bpf_exit:
17281 				mark_verifier_state_scratched(env);
17282 				update_branch_counts(env, env->cur_state);
17283 				err = pop_stack(env, &prev_insn_idx,
17284 						&env->insn_idx, pop_log);
17285 				if (err < 0) {
17286 					if (err != -ENOENT)
17287 						return err;
17288 					break;
17289 				} else {
17290 					do_print_state = true;
17291 					continue;
17292 				}
17293 			} else {
17294 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17295 				if (err)
17296 					return err;
17297 			}
17298 		} else if (class == BPF_LD) {
17299 			u8 mode = BPF_MODE(insn->code);
17300 
17301 			if (mode == BPF_ABS || mode == BPF_IND) {
17302 				err = check_ld_abs(env, insn);
17303 				if (err)
17304 					return err;
17305 
17306 			} else if (mode == BPF_IMM) {
17307 				err = check_ld_imm(env, insn);
17308 				if (err)
17309 					return err;
17310 
17311 				env->insn_idx++;
17312 				sanitize_mark_insn_seen(env);
17313 			} else {
17314 				verbose(env, "invalid BPF_LD mode\n");
17315 				return -EINVAL;
17316 			}
17317 		} else {
17318 			verbose(env, "unknown insn class %d\n", class);
17319 			return -EINVAL;
17320 		}
17321 
17322 		env->insn_idx++;
17323 	}
17324 
17325 	return 0;
17326 }
17327 
17328 static int find_btf_percpu_datasec(struct btf *btf)
17329 {
17330 	const struct btf_type *t;
17331 	const char *tname;
17332 	int i, n;
17333 
17334 	/*
17335 	 * Both vmlinux and module each have their own ".data..percpu"
17336 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17337 	 * types to look at only module's own BTF types.
17338 	 */
17339 	n = btf_nr_types(btf);
17340 	if (btf_is_module(btf))
17341 		i = btf_nr_types(btf_vmlinux);
17342 	else
17343 		i = 1;
17344 
17345 	for(; i < n; i++) {
17346 		t = btf_type_by_id(btf, i);
17347 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17348 			continue;
17349 
17350 		tname = btf_name_by_offset(btf, t->name_off);
17351 		if (!strcmp(tname, ".data..percpu"))
17352 			return i;
17353 	}
17354 
17355 	return -ENOENT;
17356 }
17357 
17358 /* replace pseudo btf_id with kernel symbol address */
17359 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17360 			       struct bpf_insn *insn,
17361 			       struct bpf_insn_aux_data *aux)
17362 {
17363 	const struct btf_var_secinfo *vsi;
17364 	const struct btf_type *datasec;
17365 	struct btf_mod_pair *btf_mod;
17366 	const struct btf_type *t;
17367 	const char *sym_name;
17368 	bool percpu = false;
17369 	u32 type, id = insn->imm;
17370 	struct btf *btf;
17371 	s32 datasec_id;
17372 	u64 addr;
17373 	int i, btf_fd, err;
17374 
17375 	btf_fd = insn[1].imm;
17376 	if (btf_fd) {
17377 		btf = btf_get_by_fd(btf_fd);
17378 		if (IS_ERR(btf)) {
17379 			verbose(env, "invalid module BTF object FD specified.\n");
17380 			return -EINVAL;
17381 		}
17382 	} else {
17383 		if (!btf_vmlinux) {
17384 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17385 			return -EINVAL;
17386 		}
17387 		btf = btf_vmlinux;
17388 		btf_get(btf);
17389 	}
17390 
17391 	t = btf_type_by_id(btf, id);
17392 	if (!t) {
17393 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17394 		err = -ENOENT;
17395 		goto err_put;
17396 	}
17397 
17398 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17399 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17400 		err = -EINVAL;
17401 		goto err_put;
17402 	}
17403 
17404 	sym_name = btf_name_by_offset(btf, t->name_off);
17405 	addr = kallsyms_lookup_name(sym_name);
17406 	if (!addr) {
17407 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17408 			sym_name);
17409 		err = -ENOENT;
17410 		goto err_put;
17411 	}
17412 	insn[0].imm = (u32)addr;
17413 	insn[1].imm = addr >> 32;
17414 
17415 	if (btf_type_is_func(t)) {
17416 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17417 		aux->btf_var.mem_size = 0;
17418 		goto check_btf;
17419 	}
17420 
17421 	datasec_id = find_btf_percpu_datasec(btf);
17422 	if (datasec_id > 0) {
17423 		datasec = btf_type_by_id(btf, datasec_id);
17424 		for_each_vsi(i, datasec, vsi) {
17425 			if (vsi->type == id) {
17426 				percpu = true;
17427 				break;
17428 			}
17429 		}
17430 	}
17431 
17432 	type = t->type;
17433 	t = btf_type_skip_modifiers(btf, type, NULL);
17434 	if (percpu) {
17435 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17436 		aux->btf_var.btf = btf;
17437 		aux->btf_var.btf_id = type;
17438 	} else if (!btf_type_is_struct(t)) {
17439 		const struct btf_type *ret;
17440 		const char *tname;
17441 		u32 tsize;
17442 
17443 		/* resolve the type size of ksym. */
17444 		ret = btf_resolve_size(btf, t, &tsize);
17445 		if (IS_ERR(ret)) {
17446 			tname = btf_name_by_offset(btf, t->name_off);
17447 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17448 				tname, PTR_ERR(ret));
17449 			err = -EINVAL;
17450 			goto err_put;
17451 		}
17452 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17453 		aux->btf_var.mem_size = tsize;
17454 	} else {
17455 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17456 		aux->btf_var.btf = btf;
17457 		aux->btf_var.btf_id = type;
17458 	}
17459 check_btf:
17460 	/* check whether we recorded this BTF (and maybe module) already */
17461 	for (i = 0; i < env->used_btf_cnt; i++) {
17462 		if (env->used_btfs[i].btf == btf) {
17463 			btf_put(btf);
17464 			return 0;
17465 		}
17466 	}
17467 
17468 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17469 		err = -E2BIG;
17470 		goto err_put;
17471 	}
17472 
17473 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17474 	btf_mod->btf = btf;
17475 	btf_mod->module = NULL;
17476 
17477 	/* if we reference variables from kernel module, bump its refcount */
17478 	if (btf_is_module(btf)) {
17479 		btf_mod->module = btf_try_get_module(btf);
17480 		if (!btf_mod->module) {
17481 			err = -ENXIO;
17482 			goto err_put;
17483 		}
17484 	}
17485 
17486 	env->used_btf_cnt++;
17487 
17488 	return 0;
17489 err_put:
17490 	btf_put(btf);
17491 	return err;
17492 }
17493 
17494 static bool is_tracing_prog_type(enum bpf_prog_type type)
17495 {
17496 	switch (type) {
17497 	case BPF_PROG_TYPE_KPROBE:
17498 	case BPF_PROG_TYPE_TRACEPOINT:
17499 	case BPF_PROG_TYPE_PERF_EVENT:
17500 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17501 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17502 		return true;
17503 	default:
17504 		return false;
17505 	}
17506 }
17507 
17508 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17509 					struct bpf_map *map,
17510 					struct bpf_prog *prog)
17511 
17512 {
17513 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17514 
17515 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17516 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17517 		if (is_tracing_prog_type(prog_type)) {
17518 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17519 			return -EINVAL;
17520 		}
17521 	}
17522 
17523 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17524 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17525 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17526 			return -EINVAL;
17527 		}
17528 
17529 		if (is_tracing_prog_type(prog_type)) {
17530 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17531 			return -EINVAL;
17532 		}
17533 	}
17534 
17535 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17536 		if (is_tracing_prog_type(prog_type)) {
17537 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17538 			return -EINVAL;
17539 		}
17540 	}
17541 
17542 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17543 	    !bpf_offload_prog_map_match(prog, map)) {
17544 		verbose(env, "offload device mismatch between prog and map\n");
17545 		return -EINVAL;
17546 	}
17547 
17548 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17549 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17550 		return -EINVAL;
17551 	}
17552 
17553 	if (prog->aux->sleepable)
17554 		switch (map->map_type) {
17555 		case BPF_MAP_TYPE_HASH:
17556 		case BPF_MAP_TYPE_LRU_HASH:
17557 		case BPF_MAP_TYPE_ARRAY:
17558 		case BPF_MAP_TYPE_PERCPU_HASH:
17559 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17560 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17561 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17562 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17563 		case BPF_MAP_TYPE_RINGBUF:
17564 		case BPF_MAP_TYPE_USER_RINGBUF:
17565 		case BPF_MAP_TYPE_INODE_STORAGE:
17566 		case BPF_MAP_TYPE_SK_STORAGE:
17567 		case BPF_MAP_TYPE_TASK_STORAGE:
17568 		case BPF_MAP_TYPE_CGRP_STORAGE:
17569 			break;
17570 		default:
17571 			verbose(env,
17572 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17573 			return -EINVAL;
17574 		}
17575 
17576 	return 0;
17577 }
17578 
17579 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17580 {
17581 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17582 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17583 }
17584 
17585 /* find and rewrite pseudo imm in ld_imm64 instructions:
17586  *
17587  * 1. if it accesses map FD, replace it with actual map pointer.
17588  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17589  *
17590  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17591  */
17592 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17593 {
17594 	struct bpf_insn *insn = env->prog->insnsi;
17595 	int insn_cnt = env->prog->len;
17596 	int i, j, err;
17597 
17598 	err = bpf_prog_calc_tag(env->prog);
17599 	if (err)
17600 		return err;
17601 
17602 	for (i = 0; i < insn_cnt; i++, insn++) {
17603 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17604 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17605 		    insn->imm != 0)) {
17606 			verbose(env, "BPF_LDX uses reserved fields\n");
17607 			return -EINVAL;
17608 		}
17609 
17610 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17611 			struct bpf_insn_aux_data *aux;
17612 			struct bpf_map *map;
17613 			struct fd f;
17614 			u64 addr;
17615 			u32 fd;
17616 
17617 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17618 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17619 			    insn[1].off != 0) {
17620 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17621 				return -EINVAL;
17622 			}
17623 
17624 			if (insn[0].src_reg == 0)
17625 				/* valid generic load 64-bit imm */
17626 				goto next_insn;
17627 
17628 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17629 				aux = &env->insn_aux_data[i];
17630 				err = check_pseudo_btf_id(env, insn, aux);
17631 				if (err)
17632 					return err;
17633 				goto next_insn;
17634 			}
17635 
17636 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17637 				aux = &env->insn_aux_data[i];
17638 				aux->ptr_type = PTR_TO_FUNC;
17639 				goto next_insn;
17640 			}
17641 
17642 			/* In final convert_pseudo_ld_imm64() step, this is
17643 			 * converted into regular 64-bit imm load insn.
17644 			 */
17645 			switch (insn[0].src_reg) {
17646 			case BPF_PSEUDO_MAP_VALUE:
17647 			case BPF_PSEUDO_MAP_IDX_VALUE:
17648 				break;
17649 			case BPF_PSEUDO_MAP_FD:
17650 			case BPF_PSEUDO_MAP_IDX:
17651 				if (insn[1].imm == 0)
17652 					break;
17653 				fallthrough;
17654 			default:
17655 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17656 				return -EINVAL;
17657 			}
17658 
17659 			switch (insn[0].src_reg) {
17660 			case BPF_PSEUDO_MAP_IDX_VALUE:
17661 			case BPF_PSEUDO_MAP_IDX:
17662 				if (bpfptr_is_null(env->fd_array)) {
17663 					verbose(env, "fd_idx without fd_array is invalid\n");
17664 					return -EPROTO;
17665 				}
17666 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17667 							    insn[0].imm * sizeof(fd),
17668 							    sizeof(fd)))
17669 					return -EFAULT;
17670 				break;
17671 			default:
17672 				fd = insn[0].imm;
17673 				break;
17674 			}
17675 
17676 			f = fdget(fd);
17677 			map = __bpf_map_get(f);
17678 			if (IS_ERR(map)) {
17679 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17680 				return PTR_ERR(map);
17681 			}
17682 
17683 			err = check_map_prog_compatibility(env, map, env->prog);
17684 			if (err) {
17685 				fdput(f);
17686 				return err;
17687 			}
17688 
17689 			aux = &env->insn_aux_data[i];
17690 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17691 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17692 				addr = (unsigned long)map;
17693 			} else {
17694 				u32 off = insn[1].imm;
17695 
17696 				if (off >= BPF_MAX_VAR_OFF) {
17697 					verbose(env, "direct value offset of %u is not allowed\n", off);
17698 					fdput(f);
17699 					return -EINVAL;
17700 				}
17701 
17702 				if (!map->ops->map_direct_value_addr) {
17703 					verbose(env, "no direct value access support for this map type\n");
17704 					fdput(f);
17705 					return -EINVAL;
17706 				}
17707 
17708 				err = map->ops->map_direct_value_addr(map, &addr, off);
17709 				if (err) {
17710 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17711 						map->value_size, off);
17712 					fdput(f);
17713 					return err;
17714 				}
17715 
17716 				aux->map_off = off;
17717 				addr += off;
17718 			}
17719 
17720 			insn[0].imm = (u32)addr;
17721 			insn[1].imm = addr >> 32;
17722 
17723 			/* check whether we recorded this map already */
17724 			for (j = 0; j < env->used_map_cnt; j++) {
17725 				if (env->used_maps[j] == map) {
17726 					aux->map_index = j;
17727 					fdput(f);
17728 					goto next_insn;
17729 				}
17730 			}
17731 
17732 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17733 				fdput(f);
17734 				return -E2BIG;
17735 			}
17736 
17737 			if (env->prog->aux->sleepable)
17738 				atomic64_inc(&map->sleepable_refcnt);
17739 			/* hold the map. If the program is rejected by verifier,
17740 			 * the map will be released by release_maps() or it
17741 			 * will be used by the valid program until it's unloaded
17742 			 * and all maps are released in bpf_free_used_maps()
17743 			 */
17744 			bpf_map_inc(map);
17745 
17746 			aux->map_index = env->used_map_cnt;
17747 			env->used_maps[env->used_map_cnt++] = map;
17748 
17749 			if (bpf_map_is_cgroup_storage(map) &&
17750 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17751 				verbose(env, "only one cgroup storage of each type is allowed\n");
17752 				fdput(f);
17753 				return -EBUSY;
17754 			}
17755 
17756 			fdput(f);
17757 next_insn:
17758 			insn++;
17759 			i++;
17760 			continue;
17761 		}
17762 
17763 		/* Basic sanity check before we invest more work here. */
17764 		if (!bpf_opcode_in_insntable(insn->code)) {
17765 			verbose(env, "unknown opcode %02x\n", insn->code);
17766 			return -EINVAL;
17767 		}
17768 	}
17769 
17770 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17771 	 * 'struct bpf_map *' into a register instead of user map_fd.
17772 	 * These pointers will be used later by verifier to validate map access.
17773 	 */
17774 	return 0;
17775 }
17776 
17777 /* drop refcnt of maps used by the rejected program */
17778 static void release_maps(struct bpf_verifier_env *env)
17779 {
17780 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17781 			     env->used_map_cnt);
17782 }
17783 
17784 /* drop refcnt of maps used by the rejected program */
17785 static void release_btfs(struct bpf_verifier_env *env)
17786 {
17787 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17788 			     env->used_btf_cnt);
17789 }
17790 
17791 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17792 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17793 {
17794 	struct bpf_insn *insn = env->prog->insnsi;
17795 	int insn_cnt = env->prog->len;
17796 	int i;
17797 
17798 	for (i = 0; i < insn_cnt; i++, insn++) {
17799 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17800 			continue;
17801 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17802 			continue;
17803 		insn->src_reg = 0;
17804 	}
17805 }
17806 
17807 /* single env->prog->insni[off] instruction was replaced with the range
17808  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17809  * [0, off) and [off, end) to new locations, so the patched range stays zero
17810  */
17811 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17812 				 struct bpf_insn_aux_data *new_data,
17813 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17814 {
17815 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17816 	struct bpf_insn *insn = new_prog->insnsi;
17817 	u32 old_seen = old_data[off].seen;
17818 	u32 prog_len;
17819 	int i;
17820 
17821 	/* aux info at OFF always needs adjustment, no matter fast path
17822 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17823 	 * original insn at old prog.
17824 	 */
17825 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17826 
17827 	if (cnt == 1)
17828 		return;
17829 	prog_len = new_prog->len;
17830 
17831 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17832 	memcpy(new_data + off + cnt - 1, old_data + off,
17833 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17834 	for (i = off; i < off + cnt - 1; i++) {
17835 		/* Expand insni[off]'s seen count to the patched range. */
17836 		new_data[i].seen = old_seen;
17837 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17838 	}
17839 	env->insn_aux_data = new_data;
17840 	vfree(old_data);
17841 }
17842 
17843 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17844 {
17845 	int i;
17846 
17847 	if (len == 1)
17848 		return;
17849 	/* NOTE: fake 'exit' subprog should be updated as well. */
17850 	for (i = 0; i <= env->subprog_cnt; i++) {
17851 		if (env->subprog_info[i].start <= off)
17852 			continue;
17853 		env->subprog_info[i].start += len - 1;
17854 	}
17855 }
17856 
17857 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17858 {
17859 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17860 	int i, sz = prog->aux->size_poke_tab;
17861 	struct bpf_jit_poke_descriptor *desc;
17862 
17863 	for (i = 0; i < sz; i++) {
17864 		desc = &tab[i];
17865 		if (desc->insn_idx <= off)
17866 			continue;
17867 		desc->insn_idx += len - 1;
17868 	}
17869 }
17870 
17871 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17872 					    const struct bpf_insn *patch, u32 len)
17873 {
17874 	struct bpf_prog *new_prog;
17875 	struct bpf_insn_aux_data *new_data = NULL;
17876 
17877 	if (len > 1) {
17878 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17879 					      sizeof(struct bpf_insn_aux_data)));
17880 		if (!new_data)
17881 			return NULL;
17882 	}
17883 
17884 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17885 	if (IS_ERR(new_prog)) {
17886 		if (PTR_ERR(new_prog) == -ERANGE)
17887 			verbose(env,
17888 				"insn %d cannot be patched due to 16-bit range\n",
17889 				env->insn_aux_data[off].orig_idx);
17890 		vfree(new_data);
17891 		return NULL;
17892 	}
17893 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17894 	adjust_subprog_starts(env, off, len);
17895 	adjust_poke_descs(new_prog, off, len);
17896 	return new_prog;
17897 }
17898 
17899 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17900 					      u32 off, u32 cnt)
17901 {
17902 	int i, j;
17903 
17904 	/* find first prog starting at or after off (first to remove) */
17905 	for (i = 0; i < env->subprog_cnt; i++)
17906 		if (env->subprog_info[i].start >= off)
17907 			break;
17908 	/* find first prog starting at or after off + cnt (first to stay) */
17909 	for (j = i; j < env->subprog_cnt; j++)
17910 		if (env->subprog_info[j].start >= off + cnt)
17911 			break;
17912 	/* if j doesn't start exactly at off + cnt, we are just removing
17913 	 * the front of previous prog
17914 	 */
17915 	if (env->subprog_info[j].start != off + cnt)
17916 		j--;
17917 
17918 	if (j > i) {
17919 		struct bpf_prog_aux *aux = env->prog->aux;
17920 		int move;
17921 
17922 		/* move fake 'exit' subprog as well */
17923 		move = env->subprog_cnt + 1 - j;
17924 
17925 		memmove(env->subprog_info + i,
17926 			env->subprog_info + j,
17927 			sizeof(*env->subprog_info) * move);
17928 		env->subprog_cnt -= j - i;
17929 
17930 		/* remove func_info */
17931 		if (aux->func_info) {
17932 			move = aux->func_info_cnt - j;
17933 
17934 			memmove(aux->func_info + i,
17935 				aux->func_info + j,
17936 				sizeof(*aux->func_info) * move);
17937 			aux->func_info_cnt -= j - i;
17938 			/* func_info->insn_off is set after all code rewrites,
17939 			 * in adjust_btf_func() - no need to adjust
17940 			 */
17941 		}
17942 	} else {
17943 		/* convert i from "first prog to remove" to "first to adjust" */
17944 		if (env->subprog_info[i].start == off)
17945 			i++;
17946 	}
17947 
17948 	/* update fake 'exit' subprog as well */
17949 	for (; i <= env->subprog_cnt; i++)
17950 		env->subprog_info[i].start -= cnt;
17951 
17952 	return 0;
17953 }
17954 
17955 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17956 				      u32 cnt)
17957 {
17958 	struct bpf_prog *prog = env->prog;
17959 	u32 i, l_off, l_cnt, nr_linfo;
17960 	struct bpf_line_info *linfo;
17961 
17962 	nr_linfo = prog->aux->nr_linfo;
17963 	if (!nr_linfo)
17964 		return 0;
17965 
17966 	linfo = prog->aux->linfo;
17967 
17968 	/* find first line info to remove, count lines to be removed */
17969 	for (i = 0; i < nr_linfo; i++)
17970 		if (linfo[i].insn_off >= off)
17971 			break;
17972 
17973 	l_off = i;
17974 	l_cnt = 0;
17975 	for (; i < nr_linfo; i++)
17976 		if (linfo[i].insn_off < off + cnt)
17977 			l_cnt++;
17978 		else
17979 			break;
17980 
17981 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17982 	 * last removed linfo.  prog is already modified, so prog->len == off
17983 	 * means no live instructions after (tail of the program was removed).
17984 	 */
17985 	if (prog->len != off && l_cnt &&
17986 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17987 		l_cnt--;
17988 		linfo[--i].insn_off = off + cnt;
17989 	}
17990 
17991 	/* remove the line info which refer to the removed instructions */
17992 	if (l_cnt) {
17993 		memmove(linfo + l_off, linfo + i,
17994 			sizeof(*linfo) * (nr_linfo - i));
17995 
17996 		prog->aux->nr_linfo -= l_cnt;
17997 		nr_linfo = prog->aux->nr_linfo;
17998 	}
17999 
18000 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18001 	for (i = l_off; i < nr_linfo; i++)
18002 		linfo[i].insn_off -= cnt;
18003 
18004 	/* fix up all subprogs (incl. 'exit') which start >= off */
18005 	for (i = 0; i <= env->subprog_cnt; i++)
18006 		if (env->subprog_info[i].linfo_idx > l_off) {
18007 			/* program may have started in the removed region but
18008 			 * may not be fully removed
18009 			 */
18010 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18011 				env->subprog_info[i].linfo_idx -= l_cnt;
18012 			else
18013 				env->subprog_info[i].linfo_idx = l_off;
18014 		}
18015 
18016 	return 0;
18017 }
18018 
18019 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18020 {
18021 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18022 	unsigned int orig_prog_len = env->prog->len;
18023 	int err;
18024 
18025 	if (bpf_prog_is_offloaded(env->prog->aux))
18026 		bpf_prog_offload_remove_insns(env, off, cnt);
18027 
18028 	err = bpf_remove_insns(env->prog, off, cnt);
18029 	if (err)
18030 		return err;
18031 
18032 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18033 	if (err)
18034 		return err;
18035 
18036 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18037 	if (err)
18038 		return err;
18039 
18040 	memmove(aux_data + off,	aux_data + off + cnt,
18041 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18042 
18043 	return 0;
18044 }
18045 
18046 /* The verifier does more data flow analysis than llvm and will not
18047  * explore branches that are dead at run time. Malicious programs can
18048  * have dead code too. Therefore replace all dead at-run-time code
18049  * with 'ja -1'.
18050  *
18051  * Just nops are not optimal, e.g. if they would sit at the end of the
18052  * program and through another bug we would manage to jump there, then
18053  * we'd execute beyond program memory otherwise. Returning exception
18054  * code also wouldn't work since we can have subprogs where the dead
18055  * code could be located.
18056  */
18057 static void sanitize_dead_code(struct bpf_verifier_env *env)
18058 {
18059 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18060 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18061 	struct bpf_insn *insn = env->prog->insnsi;
18062 	const int insn_cnt = env->prog->len;
18063 	int i;
18064 
18065 	for (i = 0; i < insn_cnt; i++) {
18066 		if (aux_data[i].seen)
18067 			continue;
18068 		memcpy(insn + i, &trap, sizeof(trap));
18069 		aux_data[i].zext_dst = false;
18070 	}
18071 }
18072 
18073 static bool insn_is_cond_jump(u8 code)
18074 {
18075 	u8 op;
18076 
18077 	op = BPF_OP(code);
18078 	if (BPF_CLASS(code) == BPF_JMP32)
18079 		return op != BPF_JA;
18080 
18081 	if (BPF_CLASS(code) != BPF_JMP)
18082 		return false;
18083 
18084 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18085 }
18086 
18087 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18088 {
18089 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18090 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18091 	struct bpf_insn *insn = env->prog->insnsi;
18092 	const int insn_cnt = env->prog->len;
18093 	int i;
18094 
18095 	for (i = 0; i < insn_cnt; i++, insn++) {
18096 		if (!insn_is_cond_jump(insn->code))
18097 			continue;
18098 
18099 		if (!aux_data[i + 1].seen)
18100 			ja.off = insn->off;
18101 		else if (!aux_data[i + 1 + insn->off].seen)
18102 			ja.off = 0;
18103 		else
18104 			continue;
18105 
18106 		if (bpf_prog_is_offloaded(env->prog->aux))
18107 			bpf_prog_offload_replace_insn(env, i, &ja);
18108 
18109 		memcpy(insn, &ja, sizeof(ja));
18110 	}
18111 }
18112 
18113 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18114 {
18115 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18116 	int insn_cnt = env->prog->len;
18117 	int i, err;
18118 
18119 	for (i = 0; i < insn_cnt; i++) {
18120 		int j;
18121 
18122 		j = 0;
18123 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18124 			j++;
18125 		if (!j)
18126 			continue;
18127 
18128 		err = verifier_remove_insns(env, i, j);
18129 		if (err)
18130 			return err;
18131 		insn_cnt = env->prog->len;
18132 	}
18133 
18134 	return 0;
18135 }
18136 
18137 static int opt_remove_nops(struct bpf_verifier_env *env)
18138 {
18139 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18140 	struct bpf_insn *insn = env->prog->insnsi;
18141 	int insn_cnt = env->prog->len;
18142 	int i, err;
18143 
18144 	for (i = 0; i < insn_cnt; i++) {
18145 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18146 			continue;
18147 
18148 		err = verifier_remove_insns(env, i, 1);
18149 		if (err)
18150 			return err;
18151 		insn_cnt--;
18152 		i--;
18153 	}
18154 
18155 	return 0;
18156 }
18157 
18158 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18159 					 const union bpf_attr *attr)
18160 {
18161 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18162 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18163 	int i, patch_len, delta = 0, len = env->prog->len;
18164 	struct bpf_insn *insns = env->prog->insnsi;
18165 	struct bpf_prog *new_prog;
18166 	bool rnd_hi32;
18167 
18168 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18169 	zext_patch[1] = BPF_ZEXT_REG(0);
18170 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18171 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18172 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18173 	for (i = 0; i < len; i++) {
18174 		int adj_idx = i + delta;
18175 		struct bpf_insn insn;
18176 		int load_reg;
18177 
18178 		insn = insns[adj_idx];
18179 		load_reg = insn_def_regno(&insn);
18180 		if (!aux[adj_idx].zext_dst) {
18181 			u8 code, class;
18182 			u32 imm_rnd;
18183 
18184 			if (!rnd_hi32)
18185 				continue;
18186 
18187 			code = insn.code;
18188 			class = BPF_CLASS(code);
18189 			if (load_reg == -1)
18190 				continue;
18191 
18192 			/* NOTE: arg "reg" (the fourth one) is only used for
18193 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18194 			 *       here.
18195 			 */
18196 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18197 				if (class == BPF_LD &&
18198 				    BPF_MODE(code) == BPF_IMM)
18199 					i++;
18200 				continue;
18201 			}
18202 
18203 			/* ctx load could be transformed into wider load. */
18204 			if (class == BPF_LDX &&
18205 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18206 				continue;
18207 
18208 			imm_rnd = get_random_u32();
18209 			rnd_hi32_patch[0] = insn;
18210 			rnd_hi32_patch[1].imm = imm_rnd;
18211 			rnd_hi32_patch[3].dst_reg = load_reg;
18212 			patch = rnd_hi32_patch;
18213 			patch_len = 4;
18214 			goto apply_patch_buffer;
18215 		}
18216 
18217 		/* Add in an zero-extend instruction if a) the JIT has requested
18218 		 * it or b) it's a CMPXCHG.
18219 		 *
18220 		 * The latter is because: BPF_CMPXCHG always loads a value into
18221 		 * R0, therefore always zero-extends. However some archs'
18222 		 * equivalent instruction only does this load when the
18223 		 * comparison is successful. This detail of CMPXCHG is
18224 		 * orthogonal to the general zero-extension behaviour of the
18225 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18226 		 */
18227 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18228 			continue;
18229 
18230 		/* Zero-extension is done by the caller. */
18231 		if (bpf_pseudo_kfunc_call(&insn))
18232 			continue;
18233 
18234 		if (WARN_ON(load_reg == -1)) {
18235 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18236 			return -EFAULT;
18237 		}
18238 
18239 		zext_patch[0] = insn;
18240 		zext_patch[1].dst_reg = load_reg;
18241 		zext_patch[1].src_reg = load_reg;
18242 		patch = zext_patch;
18243 		patch_len = 2;
18244 apply_patch_buffer:
18245 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18246 		if (!new_prog)
18247 			return -ENOMEM;
18248 		env->prog = new_prog;
18249 		insns = new_prog->insnsi;
18250 		aux = env->insn_aux_data;
18251 		delta += patch_len - 1;
18252 	}
18253 
18254 	return 0;
18255 }
18256 
18257 /* convert load instructions that access fields of a context type into a
18258  * sequence of instructions that access fields of the underlying structure:
18259  *     struct __sk_buff    -> struct sk_buff
18260  *     struct bpf_sock_ops -> struct sock
18261  */
18262 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18263 {
18264 	const struct bpf_verifier_ops *ops = env->ops;
18265 	int i, cnt, size, ctx_field_size, delta = 0;
18266 	const int insn_cnt = env->prog->len;
18267 	struct bpf_insn insn_buf[16], *insn;
18268 	u32 target_size, size_default, off;
18269 	struct bpf_prog *new_prog;
18270 	enum bpf_access_type type;
18271 	bool is_narrower_load;
18272 
18273 	if (ops->gen_prologue || env->seen_direct_write) {
18274 		if (!ops->gen_prologue) {
18275 			verbose(env, "bpf verifier is misconfigured\n");
18276 			return -EINVAL;
18277 		}
18278 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18279 					env->prog);
18280 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18281 			verbose(env, "bpf verifier is misconfigured\n");
18282 			return -EINVAL;
18283 		} else if (cnt) {
18284 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18285 			if (!new_prog)
18286 				return -ENOMEM;
18287 
18288 			env->prog = new_prog;
18289 			delta += cnt - 1;
18290 		}
18291 	}
18292 
18293 	if (bpf_prog_is_offloaded(env->prog->aux))
18294 		return 0;
18295 
18296 	insn = env->prog->insnsi + delta;
18297 
18298 	for (i = 0; i < insn_cnt; i++, insn++) {
18299 		bpf_convert_ctx_access_t convert_ctx_access;
18300 		u8 mode;
18301 
18302 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18303 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18304 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18305 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18306 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18307 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18308 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18309 			type = BPF_READ;
18310 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18311 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18312 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18313 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18314 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18315 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18316 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18317 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18318 			type = BPF_WRITE;
18319 		} else {
18320 			continue;
18321 		}
18322 
18323 		if (type == BPF_WRITE &&
18324 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18325 			struct bpf_insn patch[] = {
18326 				*insn,
18327 				BPF_ST_NOSPEC(),
18328 			};
18329 
18330 			cnt = ARRAY_SIZE(patch);
18331 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18332 			if (!new_prog)
18333 				return -ENOMEM;
18334 
18335 			delta    += cnt - 1;
18336 			env->prog = new_prog;
18337 			insn      = new_prog->insnsi + i + delta;
18338 			continue;
18339 		}
18340 
18341 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18342 		case PTR_TO_CTX:
18343 			if (!ops->convert_ctx_access)
18344 				continue;
18345 			convert_ctx_access = ops->convert_ctx_access;
18346 			break;
18347 		case PTR_TO_SOCKET:
18348 		case PTR_TO_SOCK_COMMON:
18349 			convert_ctx_access = bpf_sock_convert_ctx_access;
18350 			break;
18351 		case PTR_TO_TCP_SOCK:
18352 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18353 			break;
18354 		case PTR_TO_XDP_SOCK:
18355 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18356 			break;
18357 		case PTR_TO_BTF_ID:
18358 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18359 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18360 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18361 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18362 		 * any faults for loads into such types. BPF_WRITE is disallowed
18363 		 * for this case.
18364 		 */
18365 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18366 			if (type == BPF_READ) {
18367 				if (BPF_MODE(insn->code) == BPF_MEM)
18368 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18369 						     BPF_SIZE((insn)->code);
18370 				else
18371 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18372 						     BPF_SIZE((insn)->code);
18373 				env->prog->aux->num_exentries++;
18374 			}
18375 			continue;
18376 		default:
18377 			continue;
18378 		}
18379 
18380 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18381 		size = BPF_LDST_BYTES(insn);
18382 		mode = BPF_MODE(insn->code);
18383 
18384 		/* If the read access is a narrower load of the field,
18385 		 * convert to a 4/8-byte load, to minimum program type specific
18386 		 * convert_ctx_access changes. If conversion is successful,
18387 		 * we will apply proper mask to the result.
18388 		 */
18389 		is_narrower_load = size < ctx_field_size;
18390 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18391 		off = insn->off;
18392 		if (is_narrower_load) {
18393 			u8 size_code;
18394 
18395 			if (type == BPF_WRITE) {
18396 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18397 				return -EINVAL;
18398 			}
18399 
18400 			size_code = BPF_H;
18401 			if (ctx_field_size == 4)
18402 				size_code = BPF_W;
18403 			else if (ctx_field_size == 8)
18404 				size_code = BPF_DW;
18405 
18406 			insn->off = off & ~(size_default - 1);
18407 			insn->code = BPF_LDX | BPF_MEM | size_code;
18408 		}
18409 
18410 		target_size = 0;
18411 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18412 					 &target_size);
18413 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18414 		    (ctx_field_size && !target_size)) {
18415 			verbose(env, "bpf verifier is misconfigured\n");
18416 			return -EINVAL;
18417 		}
18418 
18419 		if (is_narrower_load && size < target_size) {
18420 			u8 shift = bpf_ctx_narrow_access_offset(
18421 				off, size, size_default) * 8;
18422 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18423 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18424 				return -EINVAL;
18425 			}
18426 			if (ctx_field_size <= 4) {
18427 				if (shift)
18428 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18429 									insn->dst_reg,
18430 									shift);
18431 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18432 								(1 << size * 8) - 1);
18433 			} else {
18434 				if (shift)
18435 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18436 									insn->dst_reg,
18437 									shift);
18438 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18439 								(1ULL << size * 8) - 1);
18440 			}
18441 		}
18442 		if (mode == BPF_MEMSX)
18443 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18444 						       insn->dst_reg, insn->dst_reg,
18445 						       size * 8, 0);
18446 
18447 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18448 		if (!new_prog)
18449 			return -ENOMEM;
18450 
18451 		delta += cnt - 1;
18452 
18453 		/* keep walking new program and skip insns we just inserted */
18454 		env->prog = new_prog;
18455 		insn      = new_prog->insnsi + i + delta;
18456 	}
18457 
18458 	return 0;
18459 }
18460 
18461 static int jit_subprogs(struct bpf_verifier_env *env)
18462 {
18463 	struct bpf_prog *prog = env->prog, **func, *tmp;
18464 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18465 	struct bpf_map *map_ptr;
18466 	struct bpf_insn *insn;
18467 	void *old_bpf_func;
18468 	int err, num_exentries;
18469 
18470 	if (env->subprog_cnt <= 1)
18471 		return 0;
18472 
18473 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18474 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18475 			continue;
18476 
18477 		/* Upon error here we cannot fall back to interpreter but
18478 		 * need a hard reject of the program. Thus -EFAULT is
18479 		 * propagated in any case.
18480 		 */
18481 		subprog = find_subprog(env, i + insn->imm + 1);
18482 		if (subprog < 0) {
18483 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18484 				  i + insn->imm + 1);
18485 			return -EFAULT;
18486 		}
18487 		/* temporarily remember subprog id inside insn instead of
18488 		 * aux_data, since next loop will split up all insns into funcs
18489 		 */
18490 		insn->off = subprog;
18491 		/* remember original imm in case JIT fails and fallback
18492 		 * to interpreter will be needed
18493 		 */
18494 		env->insn_aux_data[i].call_imm = insn->imm;
18495 		/* point imm to __bpf_call_base+1 from JITs point of view */
18496 		insn->imm = 1;
18497 		if (bpf_pseudo_func(insn))
18498 			/* jit (e.g. x86_64) may emit fewer instructions
18499 			 * if it learns a u32 imm is the same as a u64 imm.
18500 			 * Force a non zero here.
18501 			 */
18502 			insn[1].imm = 1;
18503 	}
18504 
18505 	err = bpf_prog_alloc_jited_linfo(prog);
18506 	if (err)
18507 		goto out_undo_insn;
18508 
18509 	err = -ENOMEM;
18510 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18511 	if (!func)
18512 		goto out_undo_insn;
18513 
18514 	for (i = 0; i < env->subprog_cnt; i++) {
18515 		subprog_start = subprog_end;
18516 		subprog_end = env->subprog_info[i + 1].start;
18517 
18518 		len = subprog_end - subprog_start;
18519 		/* bpf_prog_run() doesn't call subprogs directly,
18520 		 * hence main prog stats include the runtime of subprogs.
18521 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18522 		 * func[i]->stats will never be accessed and stays NULL
18523 		 */
18524 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18525 		if (!func[i])
18526 			goto out_free;
18527 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18528 		       len * sizeof(struct bpf_insn));
18529 		func[i]->type = prog->type;
18530 		func[i]->len = len;
18531 		if (bpf_prog_calc_tag(func[i]))
18532 			goto out_free;
18533 		func[i]->is_func = 1;
18534 		func[i]->aux->func_idx = i;
18535 		/* Below members will be freed only at prog->aux */
18536 		func[i]->aux->btf = prog->aux->btf;
18537 		func[i]->aux->func_info = prog->aux->func_info;
18538 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18539 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18540 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18541 
18542 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18543 			struct bpf_jit_poke_descriptor *poke;
18544 
18545 			poke = &prog->aux->poke_tab[j];
18546 			if (poke->insn_idx < subprog_end &&
18547 			    poke->insn_idx >= subprog_start)
18548 				poke->aux = func[i]->aux;
18549 		}
18550 
18551 		func[i]->aux->name[0] = 'F';
18552 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18553 		func[i]->jit_requested = 1;
18554 		func[i]->blinding_requested = prog->blinding_requested;
18555 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18556 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18557 		func[i]->aux->linfo = prog->aux->linfo;
18558 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18559 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18560 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18561 		num_exentries = 0;
18562 		insn = func[i]->insnsi;
18563 		for (j = 0; j < func[i]->len; j++, insn++) {
18564 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18565 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18566 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18567 				num_exentries++;
18568 		}
18569 		func[i]->aux->num_exentries = num_exentries;
18570 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18571 		func[i] = bpf_int_jit_compile(func[i]);
18572 		if (!func[i]->jited) {
18573 			err = -ENOTSUPP;
18574 			goto out_free;
18575 		}
18576 		cond_resched();
18577 	}
18578 
18579 	/* at this point all bpf functions were successfully JITed
18580 	 * now populate all bpf_calls with correct addresses and
18581 	 * run last pass of JIT
18582 	 */
18583 	for (i = 0; i < env->subprog_cnt; i++) {
18584 		insn = func[i]->insnsi;
18585 		for (j = 0; j < func[i]->len; j++, insn++) {
18586 			if (bpf_pseudo_func(insn)) {
18587 				subprog = insn->off;
18588 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18589 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18590 				continue;
18591 			}
18592 			if (!bpf_pseudo_call(insn))
18593 				continue;
18594 			subprog = insn->off;
18595 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18596 		}
18597 
18598 		/* we use the aux data to keep a list of the start addresses
18599 		 * of the JITed images for each function in the program
18600 		 *
18601 		 * for some architectures, such as powerpc64, the imm field
18602 		 * might not be large enough to hold the offset of the start
18603 		 * address of the callee's JITed image from __bpf_call_base
18604 		 *
18605 		 * in such cases, we can lookup the start address of a callee
18606 		 * by using its subprog id, available from the off field of
18607 		 * the call instruction, as an index for this list
18608 		 */
18609 		func[i]->aux->func = func;
18610 		func[i]->aux->func_cnt = env->subprog_cnt;
18611 	}
18612 	for (i = 0; i < env->subprog_cnt; i++) {
18613 		old_bpf_func = func[i]->bpf_func;
18614 		tmp = bpf_int_jit_compile(func[i]);
18615 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18616 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18617 			err = -ENOTSUPP;
18618 			goto out_free;
18619 		}
18620 		cond_resched();
18621 	}
18622 
18623 	/* finally lock prog and jit images for all functions and
18624 	 * populate kallsysm. Begin at the first subprogram, since
18625 	 * bpf_prog_load will add the kallsyms for the main program.
18626 	 */
18627 	for (i = 1; i < env->subprog_cnt; i++) {
18628 		bpf_prog_lock_ro(func[i]);
18629 		bpf_prog_kallsyms_add(func[i]);
18630 	}
18631 
18632 	/* Last step: make now unused interpreter insns from main
18633 	 * prog consistent for later dump requests, so they can
18634 	 * later look the same as if they were interpreted only.
18635 	 */
18636 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18637 		if (bpf_pseudo_func(insn)) {
18638 			insn[0].imm = env->insn_aux_data[i].call_imm;
18639 			insn[1].imm = insn->off;
18640 			insn->off = 0;
18641 			continue;
18642 		}
18643 		if (!bpf_pseudo_call(insn))
18644 			continue;
18645 		insn->off = env->insn_aux_data[i].call_imm;
18646 		subprog = find_subprog(env, i + insn->off + 1);
18647 		insn->imm = subprog;
18648 	}
18649 
18650 	prog->jited = 1;
18651 	prog->bpf_func = func[0]->bpf_func;
18652 	prog->jited_len = func[0]->jited_len;
18653 	prog->aux->extable = func[0]->aux->extable;
18654 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18655 	prog->aux->func = func;
18656 	prog->aux->func_cnt = env->subprog_cnt;
18657 	bpf_prog_jit_attempt_done(prog);
18658 	return 0;
18659 out_free:
18660 	/* We failed JIT'ing, so at this point we need to unregister poke
18661 	 * descriptors from subprogs, so that kernel is not attempting to
18662 	 * patch it anymore as we're freeing the subprog JIT memory.
18663 	 */
18664 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18665 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18666 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18667 	}
18668 	/* At this point we're guaranteed that poke descriptors are not
18669 	 * live anymore. We can just unlink its descriptor table as it's
18670 	 * released with the main prog.
18671 	 */
18672 	for (i = 0; i < env->subprog_cnt; i++) {
18673 		if (!func[i])
18674 			continue;
18675 		func[i]->aux->poke_tab = NULL;
18676 		bpf_jit_free(func[i]);
18677 	}
18678 	kfree(func);
18679 out_undo_insn:
18680 	/* cleanup main prog to be interpreted */
18681 	prog->jit_requested = 0;
18682 	prog->blinding_requested = 0;
18683 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18684 		if (!bpf_pseudo_call(insn))
18685 			continue;
18686 		insn->off = 0;
18687 		insn->imm = env->insn_aux_data[i].call_imm;
18688 	}
18689 	bpf_prog_jit_attempt_done(prog);
18690 	return err;
18691 }
18692 
18693 static int fixup_call_args(struct bpf_verifier_env *env)
18694 {
18695 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18696 	struct bpf_prog *prog = env->prog;
18697 	struct bpf_insn *insn = prog->insnsi;
18698 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18699 	int i, depth;
18700 #endif
18701 	int err = 0;
18702 
18703 	if (env->prog->jit_requested &&
18704 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18705 		err = jit_subprogs(env);
18706 		if (err == 0)
18707 			return 0;
18708 		if (err == -EFAULT)
18709 			return err;
18710 	}
18711 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18712 	if (has_kfunc_call) {
18713 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18714 		return -EINVAL;
18715 	}
18716 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18717 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18718 		 * have to be rejected, since interpreter doesn't support them yet.
18719 		 */
18720 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18721 		return -EINVAL;
18722 	}
18723 	for (i = 0; i < prog->len; i++, insn++) {
18724 		if (bpf_pseudo_func(insn)) {
18725 			/* When JIT fails the progs with callback calls
18726 			 * have to be rejected, since interpreter doesn't support them yet.
18727 			 */
18728 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18729 			return -EINVAL;
18730 		}
18731 
18732 		if (!bpf_pseudo_call(insn))
18733 			continue;
18734 		depth = get_callee_stack_depth(env, insn, i);
18735 		if (depth < 0)
18736 			return depth;
18737 		bpf_patch_call_args(insn, depth);
18738 	}
18739 	err = 0;
18740 #endif
18741 	return err;
18742 }
18743 
18744 /* replace a generic kfunc with a specialized version if necessary */
18745 static void specialize_kfunc(struct bpf_verifier_env *env,
18746 			     u32 func_id, u16 offset, unsigned long *addr)
18747 {
18748 	struct bpf_prog *prog = env->prog;
18749 	bool seen_direct_write;
18750 	void *xdp_kfunc;
18751 	bool is_rdonly;
18752 
18753 	if (bpf_dev_bound_kfunc_id(func_id)) {
18754 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18755 		if (xdp_kfunc) {
18756 			*addr = (unsigned long)xdp_kfunc;
18757 			return;
18758 		}
18759 		/* fallback to default kfunc when not supported by netdev */
18760 	}
18761 
18762 	if (offset)
18763 		return;
18764 
18765 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18766 		seen_direct_write = env->seen_direct_write;
18767 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18768 
18769 		if (is_rdonly)
18770 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18771 
18772 		/* restore env->seen_direct_write to its original value, since
18773 		 * may_access_direct_pkt_data mutates it
18774 		 */
18775 		env->seen_direct_write = seen_direct_write;
18776 	}
18777 }
18778 
18779 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18780 					    u16 struct_meta_reg,
18781 					    u16 node_offset_reg,
18782 					    struct bpf_insn *insn,
18783 					    struct bpf_insn *insn_buf,
18784 					    int *cnt)
18785 {
18786 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18787 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18788 
18789 	insn_buf[0] = addr[0];
18790 	insn_buf[1] = addr[1];
18791 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18792 	insn_buf[3] = *insn;
18793 	*cnt = 4;
18794 }
18795 
18796 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18797 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18798 {
18799 	const struct bpf_kfunc_desc *desc;
18800 
18801 	if (!insn->imm) {
18802 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18803 		return -EINVAL;
18804 	}
18805 
18806 	*cnt = 0;
18807 
18808 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18809 	 * __bpf_call_base, unless the JIT needs to call functions that are
18810 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18811 	 */
18812 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18813 	if (!desc) {
18814 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18815 			insn->imm);
18816 		return -EFAULT;
18817 	}
18818 
18819 	if (!bpf_jit_supports_far_kfunc_call())
18820 		insn->imm = BPF_CALL_IMM(desc->addr);
18821 	if (insn->off)
18822 		return 0;
18823 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18824 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18825 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18826 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18827 
18828 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18829 		insn_buf[1] = addr[0];
18830 		insn_buf[2] = addr[1];
18831 		insn_buf[3] = *insn;
18832 		*cnt = 4;
18833 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18834 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18835 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18836 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18837 
18838 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18839 		    !kptr_struct_meta) {
18840 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18841 				insn_idx);
18842 			return -EFAULT;
18843 		}
18844 
18845 		insn_buf[0] = addr[0];
18846 		insn_buf[1] = addr[1];
18847 		insn_buf[2] = *insn;
18848 		*cnt = 3;
18849 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18850 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18851 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18852 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18853 		int struct_meta_reg = BPF_REG_3;
18854 		int node_offset_reg = BPF_REG_4;
18855 
18856 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18857 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18858 			struct_meta_reg = BPF_REG_4;
18859 			node_offset_reg = BPF_REG_5;
18860 		}
18861 
18862 		if (!kptr_struct_meta) {
18863 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18864 				insn_idx);
18865 			return -EFAULT;
18866 		}
18867 
18868 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18869 						node_offset_reg, insn, insn_buf, cnt);
18870 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18871 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18872 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18873 		*cnt = 1;
18874 	}
18875 	return 0;
18876 }
18877 
18878 /* Do various post-verification rewrites in a single program pass.
18879  * These rewrites simplify JIT and interpreter implementations.
18880  */
18881 static int do_misc_fixups(struct bpf_verifier_env *env)
18882 {
18883 	struct bpf_prog *prog = env->prog;
18884 	enum bpf_attach_type eatype = prog->expected_attach_type;
18885 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18886 	struct bpf_insn *insn = prog->insnsi;
18887 	const struct bpf_func_proto *fn;
18888 	const int insn_cnt = prog->len;
18889 	const struct bpf_map_ops *ops;
18890 	struct bpf_insn_aux_data *aux;
18891 	struct bpf_insn insn_buf[16];
18892 	struct bpf_prog *new_prog;
18893 	struct bpf_map *map_ptr;
18894 	int i, ret, cnt, delta = 0;
18895 
18896 	for (i = 0; i < insn_cnt; i++, insn++) {
18897 		/* Make divide-by-zero exceptions impossible. */
18898 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18899 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18900 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18901 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18902 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18903 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18904 			struct bpf_insn *patchlet;
18905 			struct bpf_insn chk_and_div[] = {
18906 				/* [R,W]x div 0 -> 0 */
18907 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18908 					     BPF_JNE | BPF_K, insn->src_reg,
18909 					     0, 2, 0),
18910 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18911 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18912 				*insn,
18913 			};
18914 			struct bpf_insn chk_and_mod[] = {
18915 				/* [R,W]x mod 0 -> [R,W]x */
18916 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18917 					     BPF_JEQ | BPF_K, insn->src_reg,
18918 					     0, 1 + (is64 ? 0 : 1), 0),
18919 				*insn,
18920 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18921 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18922 			};
18923 
18924 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18925 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18926 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18927 
18928 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18929 			if (!new_prog)
18930 				return -ENOMEM;
18931 
18932 			delta    += cnt - 1;
18933 			env->prog = prog = new_prog;
18934 			insn      = new_prog->insnsi + i + delta;
18935 			continue;
18936 		}
18937 
18938 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18939 		if (BPF_CLASS(insn->code) == BPF_LD &&
18940 		    (BPF_MODE(insn->code) == BPF_ABS ||
18941 		     BPF_MODE(insn->code) == BPF_IND)) {
18942 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18943 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18944 				verbose(env, "bpf verifier is misconfigured\n");
18945 				return -EINVAL;
18946 			}
18947 
18948 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18949 			if (!new_prog)
18950 				return -ENOMEM;
18951 
18952 			delta    += cnt - 1;
18953 			env->prog = prog = new_prog;
18954 			insn      = new_prog->insnsi + i + delta;
18955 			continue;
18956 		}
18957 
18958 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18959 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18960 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18961 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18962 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18963 			struct bpf_insn *patch = &insn_buf[0];
18964 			bool issrc, isneg, isimm;
18965 			u32 off_reg;
18966 
18967 			aux = &env->insn_aux_data[i + delta];
18968 			if (!aux->alu_state ||
18969 			    aux->alu_state == BPF_ALU_NON_POINTER)
18970 				continue;
18971 
18972 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18973 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18974 				BPF_ALU_SANITIZE_SRC;
18975 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18976 
18977 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18978 			if (isimm) {
18979 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18980 			} else {
18981 				if (isneg)
18982 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18983 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18984 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18985 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18986 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18987 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18988 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18989 			}
18990 			if (!issrc)
18991 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18992 			insn->src_reg = BPF_REG_AX;
18993 			if (isneg)
18994 				insn->code = insn->code == code_add ?
18995 					     code_sub : code_add;
18996 			*patch++ = *insn;
18997 			if (issrc && isneg && !isimm)
18998 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18999 			cnt = patch - insn_buf;
19000 
19001 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19002 			if (!new_prog)
19003 				return -ENOMEM;
19004 
19005 			delta    += cnt - 1;
19006 			env->prog = prog = new_prog;
19007 			insn      = new_prog->insnsi + i + delta;
19008 			continue;
19009 		}
19010 
19011 		if (insn->code != (BPF_JMP | BPF_CALL))
19012 			continue;
19013 		if (insn->src_reg == BPF_PSEUDO_CALL)
19014 			continue;
19015 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19016 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19017 			if (ret)
19018 				return ret;
19019 			if (cnt == 0)
19020 				continue;
19021 
19022 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19023 			if (!new_prog)
19024 				return -ENOMEM;
19025 
19026 			delta	 += cnt - 1;
19027 			env->prog = prog = new_prog;
19028 			insn	  = new_prog->insnsi + i + delta;
19029 			continue;
19030 		}
19031 
19032 		if (insn->imm == BPF_FUNC_get_route_realm)
19033 			prog->dst_needed = 1;
19034 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19035 			bpf_user_rnd_init_once();
19036 		if (insn->imm == BPF_FUNC_override_return)
19037 			prog->kprobe_override = 1;
19038 		if (insn->imm == BPF_FUNC_tail_call) {
19039 			/* If we tail call into other programs, we
19040 			 * cannot make any assumptions since they can
19041 			 * be replaced dynamically during runtime in
19042 			 * the program array.
19043 			 */
19044 			prog->cb_access = 1;
19045 			if (!allow_tail_call_in_subprogs(env))
19046 				prog->aux->stack_depth = MAX_BPF_STACK;
19047 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19048 
19049 			/* mark bpf_tail_call as different opcode to avoid
19050 			 * conditional branch in the interpreter for every normal
19051 			 * call and to prevent accidental JITing by JIT compiler
19052 			 * that doesn't support bpf_tail_call yet
19053 			 */
19054 			insn->imm = 0;
19055 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19056 
19057 			aux = &env->insn_aux_data[i + delta];
19058 			if (env->bpf_capable && !prog->blinding_requested &&
19059 			    prog->jit_requested &&
19060 			    !bpf_map_key_poisoned(aux) &&
19061 			    !bpf_map_ptr_poisoned(aux) &&
19062 			    !bpf_map_ptr_unpriv(aux)) {
19063 				struct bpf_jit_poke_descriptor desc = {
19064 					.reason = BPF_POKE_REASON_TAIL_CALL,
19065 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19066 					.tail_call.key = bpf_map_key_immediate(aux),
19067 					.insn_idx = i + delta,
19068 				};
19069 
19070 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19071 				if (ret < 0) {
19072 					verbose(env, "adding tail call poke descriptor failed\n");
19073 					return ret;
19074 				}
19075 
19076 				insn->imm = ret + 1;
19077 				continue;
19078 			}
19079 
19080 			if (!bpf_map_ptr_unpriv(aux))
19081 				continue;
19082 
19083 			/* instead of changing every JIT dealing with tail_call
19084 			 * emit two extra insns:
19085 			 * if (index >= max_entries) goto out;
19086 			 * index &= array->index_mask;
19087 			 * to avoid out-of-bounds cpu speculation
19088 			 */
19089 			if (bpf_map_ptr_poisoned(aux)) {
19090 				verbose(env, "tail_call abusing map_ptr\n");
19091 				return -EINVAL;
19092 			}
19093 
19094 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19095 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19096 						  map_ptr->max_entries, 2);
19097 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19098 						    container_of(map_ptr,
19099 								 struct bpf_array,
19100 								 map)->index_mask);
19101 			insn_buf[2] = *insn;
19102 			cnt = 3;
19103 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19104 			if (!new_prog)
19105 				return -ENOMEM;
19106 
19107 			delta    += cnt - 1;
19108 			env->prog = prog = new_prog;
19109 			insn      = new_prog->insnsi + i + delta;
19110 			continue;
19111 		}
19112 
19113 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19114 			/* The verifier will process callback_fn as many times as necessary
19115 			 * with different maps and the register states prepared by
19116 			 * set_timer_callback_state will be accurate.
19117 			 *
19118 			 * The following use case is valid:
19119 			 *   map1 is shared by prog1, prog2, prog3.
19120 			 *   prog1 calls bpf_timer_init for some map1 elements
19121 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19122 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19123 			 *   prog3 calls bpf_timer_start for some map1 elements.
19124 			 *     Those that were not both bpf_timer_init-ed and
19125 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19126 			 */
19127 			struct bpf_insn ld_addrs[2] = {
19128 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19129 			};
19130 
19131 			insn_buf[0] = ld_addrs[0];
19132 			insn_buf[1] = ld_addrs[1];
19133 			insn_buf[2] = *insn;
19134 			cnt = 3;
19135 
19136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19137 			if (!new_prog)
19138 				return -ENOMEM;
19139 
19140 			delta    += cnt - 1;
19141 			env->prog = prog = new_prog;
19142 			insn      = new_prog->insnsi + i + delta;
19143 			goto patch_call_imm;
19144 		}
19145 
19146 		if (is_storage_get_function(insn->imm)) {
19147 			if (!env->prog->aux->sleepable ||
19148 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19149 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19150 			else
19151 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19152 			insn_buf[1] = *insn;
19153 			cnt = 2;
19154 
19155 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19156 			if (!new_prog)
19157 				return -ENOMEM;
19158 
19159 			delta += cnt - 1;
19160 			env->prog = prog = new_prog;
19161 			insn = new_prog->insnsi + i + delta;
19162 			goto patch_call_imm;
19163 		}
19164 
19165 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19166 		 * and other inlining handlers are currently limited to 64 bit
19167 		 * only.
19168 		 */
19169 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19170 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19171 		     insn->imm == BPF_FUNC_map_update_elem ||
19172 		     insn->imm == BPF_FUNC_map_delete_elem ||
19173 		     insn->imm == BPF_FUNC_map_push_elem   ||
19174 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19175 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19176 		     insn->imm == BPF_FUNC_redirect_map    ||
19177 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19178 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19179 			aux = &env->insn_aux_data[i + delta];
19180 			if (bpf_map_ptr_poisoned(aux))
19181 				goto patch_call_imm;
19182 
19183 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19184 			ops = map_ptr->ops;
19185 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19186 			    ops->map_gen_lookup) {
19187 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19188 				if (cnt == -EOPNOTSUPP)
19189 					goto patch_map_ops_generic;
19190 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19191 					verbose(env, "bpf verifier is misconfigured\n");
19192 					return -EINVAL;
19193 				}
19194 
19195 				new_prog = bpf_patch_insn_data(env, i + delta,
19196 							       insn_buf, cnt);
19197 				if (!new_prog)
19198 					return -ENOMEM;
19199 
19200 				delta    += cnt - 1;
19201 				env->prog = prog = new_prog;
19202 				insn      = new_prog->insnsi + i + delta;
19203 				continue;
19204 			}
19205 
19206 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19207 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19208 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19209 				     (long (*)(struct bpf_map *map, void *key))NULL));
19210 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19211 				     (long (*)(struct bpf_map *map, void *key, void *value,
19212 					      u64 flags))NULL));
19213 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19214 				     (long (*)(struct bpf_map *map, void *value,
19215 					      u64 flags))NULL));
19216 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19217 				     (long (*)(struct bpf_map *map, void *value))NULL));
19218 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19219 				     (long (*)(struct bpf_map *map, void *value))NULL));
19220 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19221 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19222 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19223 				     (long (*)(struct bpf_map *map,
19224 					      bpf_callback_t callback_fn,
19225 					      void *callback_ctx,
19226 					      u64 flags))NULL));
19227 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19228 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19229 
19230 patch_map_ops_generic:
19231 			switch (insn->imm) {
19232 			case BPF_FUNC_map_lookup_elem:
19233 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19234 				continue;
19235 			case BPF_FUNC_map_update_elem:
19236 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19237 				continue;
19238 			case BPF_FUNC_map_delete_elem:
19239 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19240 				continue;
19241 			case BPF_FUNC_map_push_elem:
19242 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19243 				continue;
19244 			case BPF_FUNC_map_pop_elem:
19245 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19246 				continue;
19247 			case BPF_FUNC_map_peek_elem:
19248 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19249 				continue;
19250 			case BPF_FUNC_redirect_map:
19251 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19252 				continue;
19253 			case BPF_FUNC_for_each_map_elem:
19254 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19255 				continue;
19256 			case BPF_FUNC_map_lookup_percpu_elem:
19257 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19258 				continue;
19259 			}
19260 
19261 			goto patch_call_imm;
19262 		}
19263 
19264 		/* Implement bpf_jiffies64 inline. */
19265 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19266 		    insn->imm == BPF_FUNC_jiffies64) {
19267 			struct bpf_insn ld_jiffies_addr[2] = {
19268 				BPF_LD_IMM64(BPF_REG_0,
19269 					     (unsigned long)&jiffies),
19270 			};
19271 
19272 			insn_buf[0] = ld_jiffies_addr[0];
19273 			insn_buf[1] = ld_jiffies_addr[1];
19274 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19275 						  BPF_REG_0, 0);
19276 			cnt = 3;
19277 
19278 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19279 						       cnt);
19280 			if (!new_prog)
19281 				return -ENOMEM;
19282 
19283 			delta    += cnt - 1;
19284 			env->prog = prog = new_prog;
19285 			insn      = new_prog->insnsi + i + delta;
19286 			continue;
19287 		}
19288 
19289 		/* Implement bpf_get_func_arg inline. */
19290 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19291 		    insn->imm == BPF_FUNC_get_func_arg) {
19292 			/* Load nr_args from ctx - 8 */
19293 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19294 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19295 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19296 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19297 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19298 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19299 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19300 			insn_buf[7] = BPF_JMP_A(1);
19301 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19302 			cnt = 9;
19303 
19304 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19305 			if (!new_prog)
19306 				return -ENOMEM;
19307 
19308 			delta    += cnt - 1;
19309 			env->prog = prog = new_prog;
19310 			insn      = new_prog->insnsi + i + delta;
19311 			continue;
19312 		}
19313 
19314 		/* Implement bpf_get_func_ret inline. */
19315 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19316 		    insn->imm == BPF_FUNC_get_func_ret) {
19317 			if (eatype == BPF_TRACE_FEXIT ||
19318 			    eatype == BPF_MODIFY_RETURN) {
19319 				/* Load nr_args from ctx - 8 */
19320 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19321 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19322 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19323 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19324 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19325 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19326 				cnt = 6;
19327 			} else {
19328 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19329 				cnt = 1;
19330 			}
19331 
19332 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19333 			if (!new_prog)
19334 				return -ENOMEM;
19335 
19336 			delta    += cnt - 1;
19337 			env->prog = prog = new_prog;
19338 			insn      = new_prog->insnsi + i + delta;
19339 			continue;
19340 		}
19341 
19342 		/* Implement get_func_arg_cnt inline. */
19343 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19344 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19345 			/* Load nr_args from ctx - 8 */
19346 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19347 
19348 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19349 			if (!new_prog)
19350 				return -ENOMEM;
19351 
19352 			env->prog = prog = new_prog;
19353 			insn      = new_prog->insnsi + i + delta;
19354 			continue;
19355 		}
19356 
19357 		/* Implement bpf_get_func_ip inline. */
19358 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19359 		    insn->imm == BPF_FUNC_get_func_ip) {
19360 			/* Load IP address from ctx - 16 */
19361 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19362 
19363 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19364 			if (!new_prog)
19365 				return -ENOMEM;
19366 
19367 			env->prog = prog = new_prog;
19368 			insn      = new_prog->insnsi + i + delta;
19369 			continue;
19370 		}
19371 
19372 patch_call_imm:
19373 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19374 		/* all functions that have prototype and verifier allowed
19375 		 * programs to call them, must be real in-kernel functions
19376 		 */
19377 		if (!fn->func) {
19378 			verbose(env,
19379 				"kernel subsystem misconfigured func %s#%d\n",
19380 				func_id_name(insn->imm), insn->imm);
19381 			return -EFAULT;
19382 		}
19383 		insn->imm = fn->func - __bpf_call_base;
19384 	}
19385 
19386 	/* Since poke tab is now finalized, publish aux to tracker. */
19387 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19388 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19389 		if (!map_ptr->ops->map_poke_track ||
19390 		    !map_ptr->ops->map_poke_untrack ||
19391 		    !map_ptr->ops->map_poke_run) {
19392 			verbose(env, "bpf verifier is misconfigured\n");
19393 			return -EINVAL;
19394 		}
19395 
19396 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19397 		if (ret < 0) {
19398 			verbose(env, "tracking tail call prog failed\n");
19399 			return ret;
19400 		}
19401 	}
19402 
19403 	sort_kfunc_descs_by_imm_off(env->prog);
19404 
19405 	return 0;
19406 }
19407 
19408 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19409 					int position,
19410 					s32 stack_base,
19411 					u32 callback_subprogno,
19412 					u32 *cnt)
19413 {
19414 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19415 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19416 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19417 	int reg_loop_max = BPF_REG_6;
19418 	int reg_loop_cnt = BPF_REG_7;
19419 	int reg_loop_ctx = BPF_REG_8;
19420 
19421 	struct bpf_prog *new_prog;
19422 	u32 callback_start;
19423 	u32 call_insn_offset;
19424 	s32 callback_offset;
19425 
19426 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19427 	 * be careful to modify this code in sync.
19428 	 */
19429 	struct bpf_insn insn_buf[] = {
19430 		/* Return error and jump to the end of the patch if
19431 		 * expected number of iterations is too big.
19432 		 */
19433 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19434 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19435 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19436 		/* spill R6, R7, R8 to use these as loop vars */
19437 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19438 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19439 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19440 		/* initialize loop vars */
19441 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19442 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19443 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19444 		/* loop header,
19445 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19446 		 */
19447 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19448 		/* callback call,
19449 		 * correct callback offset would be set after patching
19450 		 */
19451 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19452 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19453 		BPF_CALL_REL(0),
19454 		/* increment loop counter */
19455 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19456 		/* jump to loop header if callback returned 0 */
19457 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19458 		/* return value of bpf_loop,
19459 		 * set R0 to the number of iterations
19460 		 */
19461 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19462 		/* restore original values of R6, R7, R8 */
19463 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19464 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19465 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19466 	};
19467 
19468 	*cnt = ARRAY_SIZE(insn_buf);
19469 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19470 	if (!new_prog)
19471 		return new_prog;
19472 
19473 	/* callback start is known only after patching */
19474 	callback_start = env->subprog_info[callback_subprogno].start;
19475 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19476 	call_insn_offset = position + 12;
19477 	callback_offset = callback_start - call_insn_offset - 1;
19478 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19479 
19480 	return new_prog;
19481 }
19482 
19483 static bool is_bpf_loop_call(struct bpf_insn *insn)
19484 {
19485 	return insn->code == (BPF_JMP | BPF_CALL) &&
19486 		insn->src_reg == 0 &&
19487 		insn->imm == BPF_FUNC_loop;
19488 }
19489 
19490 /* For all sub-programs in the program (including main) check
19491  * insn_aux_data to see if there are bpf_loop calls that require
19492  * inlining. If such calls are found the calls are replaced with a
19493  * sequence of instructions produced by `inline_bpf_loop` function and
19494  * subprog stack_depth is increased by the size of 3 registers.
19495  * This stack space is used to spill values of the R6, R7, R8.  These
19496  * registers are used to store the loop bound, counter and context
19497  * variables.
19498  */
19499 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19500 {
19501 	struct bpf_subprog_info *subprogs = env->subprog_info;
19502 	int i, cur_subprog = 0, cnt, delta = 0;
19503 	struct bpf_insn *insn = env->prog->insnsi;
19504 	int insn_cnt = env->prog->len;
19505 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19506 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19507 	u16 stack_depth_extra = 0;
19508 
19509 	for (i = 0; i < insn_cnt; i++, insn++) {
19510 		struct bpf_loop_inline_state *inline_state =
19511 			&env->insn_aux_data[i + delta].loop_inline_state;
19512 
19513 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19514 			struct bpf_prog *new_prog;
19515 
19516 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19517 			new_prog = inline_bpf_loop(env,
19518 						   i + delta,
19519 						   -(stack_depth + stack_depth_extra),
19520 						   inline_state->callback_subprogno,
19521 						   &cnt);
19522 			if (!new_prog)
19523 				return -ENOMEM;
19524 
19525 			delta     += cnt - 1;
19526 			env->prog  = new_prog;
19527 			insn       = new_prog->insnsi + i + delta;
19528 		}
19529 
19530 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19531 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19532 			cur_subprog++;
19533 			stack_depth = subprogs[cur_subprog].stack_depth;
19534 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19535 			stack_depth_extra = 0;
19536 		}
19537 	}
19538 
19539 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19540 
19541 	return 0;
19542 }
19543 
19544 static void free_states(struct bpf_verifier_env *env)
19545 {
19546 	struct bpf_verifier_state_list *sl, *sln;
19547 	int i;
19548 
19549 	sl = env->free_list;
19550 	while (sl) {
19551 		sln = sl->next;
19552 		free_verifier_state(&sl->state, false);
19553 		kfree(sl);
19554 		sl = sln;
19555 	}
19556 	env->free_list = NULL;
19557 
19558 	if (!env->explored_states)
19559 		return;
19560 
19561 	for (i = 0; i < state_htab_size(env); i++) {
19562 		sl = env->explored_states[i];
19563 
19564 		while (sl) {
19565 			sln = sl->next;
19566 			free_verifier_state(&sl->state, false);
19567 			kfree(sl);
19568 			sl = sln;
19569 		}
19570 		env->explored_states[i] = NULL;
19571 	}
19572 }
19573 
19574 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19575 {
19576 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19577 	struct bpf_verifier_state *state;
19578 	struct bpf_reg_state *regs;
19579 	int ret, i;
19580 
19581 	env->prev_linfo = NULL;
19582 	env->pass_cnt++;
19583 
19584 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19585 	if (!state)
19586 		return -ENOMEM;
19587 	state->curframe = 0;
19588 	state->speculative = false;
19589 	state->branches = 1;
19590 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19591 	if (!state->frame[0]) {
19592 		kfree(state);
19593 		return -ENOMEM;
19594 	}
19595 	env->cur_state = state;
19596 	init_func_state(env, state->frame[0],
19597 			BPF_MAIN_FUNC /* callsite */,
19598 			0 /* frameno */,
19599 			subprog);
19600 	state->first_insn_idx = env->subprog_info[subprog].start;
19601 	state->last_insn_idx = -1;
19602 
19603 	regs = state->frame[state->curframe]->regs;
19604 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19605 		ret = btf_prepare_func_args(env, subprog, regs);
19606 		if (ret)
19607 			goto out;
19608 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19609 			if (regs[i].type == PTR_TO_CTX)
19610 				mark_reg_known_zero(env, regs, i);
19611 			else if (regs[i].type == SCALAR_VALUE)
19612 				mark_reg_unknown(env, regs, i);
19613 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19614 				const u32 mem_size = regs[i].mem_size;
19615 
19616 				mark_reg_known_zero(env, regs, i);
19617 				regs[i].mem_size = mem_size;
19618 				regs[i].id = ++env->id_gen;
19619 			}
19620 		}
19621 	} else {
19622 		/* 1st arg to a function */
19623 		regs[BPF_REG_1].type = PTR_TO_CTX;
19624 		mark_reg_known_zero(env, regs, BPF_REG_1);
19625 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19626 		if (ret == -EFAULT)
19627 			/* unlikely verifier bug. abort.
19628 			 * ret == 0 and ret < 0 are sadly acceptable for
19629 			 * main() function due to backward compatibility.
19630 			 * Like socket filter program may be written as:
19631 			 * int bpf_prog(struct pt_regs *ctx)
19632 			 * and never dereference that ctx in the program.
19633 			 * 'struct pt_regs' is a type mismatch for socket
19634 			 * filter that should be using 'struct __sk_buff'.
19635 			 */
19636 			goto out;
19637 	}
19638 
19639 	ret = do_check(env);
19640 out:
19641 	/* check for NULL is necessary, since cur_state can be freed inside
19642 	 * do_check() under memory pressure.
19643 	 */
19644 	if (env->cur_state) {
19645 		free_verifier_state(env->cur_state, true);
19646 		env->cur_state = NULL;
19647 	}
19648 	while (!pop_stack(env, NULL, NULL, false));
19649 	if (!ret && pop_log)
19650 		bpf_vlog_reset(&env->log, 0);
19651 	free_states(env);
19652 	return ret;
19653 }
19654 
19655 /* Verify all global functions in a BPF program one by one based on their BTF.
19656  * All global functions must pass verification. Otherwise the whole program is rejected.
19657  * Consider:
19658  * int bar(int);
19659  * int foo(int f)
19660  * {
19661  *    return bar(f);
19662  * }
19663  * int bar(int b)
19664  * {
19665  *    ...
19666  * }
19667  * foo() will be verified first for R1=any_scalar_value. During verification it
19668  * will be assumed that bar() already verified successfully and call to bar()
19669  * from foo() will be checked for type match only. Later bar() will be verified
19670  * independently to check that it's safe for R1=any_scalar_value.
19671  */
19672 static int do_check_subprogs(struct bpf_verifier_env *env)
19673 {
19674 	struct bpf_prog_aux *aux = env->prog->aux;
19675 	int i, ret;
19676 
19677 	if (!aux->func_info)
19678 		return 0;
19679 
19680 	for (i = 1; i < env->subprog_cnt; i++) {
19681 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19682 			continue;
19683 		env->insn_idx = env->subprog_info[i].start;
19684 		WARN_ON_ONCE(env->insn_idx == 0);
19685 		ret = do_check_common(env, i);
19686 		if (ret) {
19687 			return ret;
19688 		} else if (env->log.level & BPF_LOG_LEVEL) {
19689 			verbose(env,
19690 				"Func#%d is safe for any args that match its prototype\n",
19691 				i);
19692 		}
19693 	}
19694 	return 0;
19695 }
19696 
19697 static int do_check_main(struct bpf_verifier_env *env)
19698 {
19699 	int ret;
19700 
19701 	env->insn_idx = 0;
19702 	ret = do_check_common(env, 0);
19703 	if (!ret)
19704 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19705 	return ret;
19706 }
19707 
19708 
19709 static void print_verification_stats(struct bpf_verifier_env *env)
19710 {
19711 	int i;
19712 
19713 	if (env->log.level & BPF_LOG_STATS) {
19714 		verbose(env, "verification time %lld usec\n",
19715 			div_u64(env->verification_time, 1000));
19716 		verbose(env, "stack depth ");
19717 		for (i = 0; i < env->subprog_cnt; i++) {
19718 			u32 depth = env->subprog_info[i].stack_depth;
19719 
19720 			verbose(env, "%d", depth);
19721 			if (i + 1 < env->subprog_cnt)
19722 				verbose(env, "+");
19723 		}
19724 		verbose(env, "\n");
19725 	}
19726 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19727 		"total_states %d peak_states %d mark_read %d\n",
19728 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19729 		env->max_states_per_insn, env->total_states,
19730 		env->peak_states, env->longest_mark_read_walk);
19731 }
19732 
19733 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19734 {
19735 	const struct btf_type *t, *func_proto;
19736 	const struct bpf_struct_ops *st_ops;
19737 	const struct btf_member *member;
19738 	struct bpf_prog *prog = env->prog;
19739 	u32 btf_id, member_idx;
19740 	const char *mname;
19741 
19742 	if (!prog->gpl_compatible) {
19743 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19744 		return -EINVAL;
19745 	}
19746 
19747 	btf_id = prog->aux->attach_btf_id;
19748 	st_ops = bpf_struct_ops_find(btf_id);
19749 	if (!st_ops) {
19750 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19751 			btf_id);
19752 		return -ENOTSUPP;
19753 	}
19754 
19755 	t = st_ops->type;
19756 	member_idx = prog->expected_attach_type;
19757 	if (member_idx >= btf_type_vlen(t)) {
19758 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19759 			member_idx, st_ops->name);
19760 		return -EINVAL;
19761 	}
19762 
19763 	member = &btf_type_member(t)[member_idx];
19764 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19765 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19766 					       NULL);
19767 	if (!func_proto) {
19768 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19769 			mname, member_idx, st_ops->name);
19770 		return -EINVAL;
19771 	}
19772 
19773 	if (st_ops->check_member) {
19774 		int err = st_ops->check_member(t, member, prog);
19775 
19776 		if (err) {
19777 			verbose(env, "attach to unsupported member %s of struct %s\n",
19778 				mname, st_ops->name);
19779 			return err;
19780 		}
19781 	}
19782 
19783 	prog->aux->attach_func_proto = func_proto;
19784 	prog->aux->attach_func_name = mname;
19785 	env->ops = st_ops->verifier_ops;
19786 
19787 	return 0;
19788 }
19789 #define SECURITY_PREFIX "security_"
19790 
19791 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19792 {
19793 	if (within_error_injection_list(addr) ||
19794 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19795 		return 0;
19796 
19797 	return -EINVAL;
19798 }
19799 
19800 /* list of non-sleepable functions that are otherwise on
19801  * ALLOW_ERROR_INJECTION list
19802  */
19803 BTF_SET_START(btf_non_sleepable_error_inject)
19804 /* Three functions below can be called from sleepable and non-sleepable context.
19805  * Assume non-sleepable from bpf safety point of view.
19806  */
19807 BTF_ID(func, __filemap_add_folio)
19808 BTF_ID(func, should_fail_alloc_page)
19809 BTF_ID(func, should_failslab)
19810 BTF_SET_END(btf_non_sleepable_error_inject)
19811 
19812 static int check_non_sleepable_error_inject(u32 btf_id)
19813 {
19814 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19815 }
19816 
19817 int bpf_check_attach_target(struct bpf_verifier_log *log,
19818 			    const struct bpf_prog *prog,
19819 			    const struct bpf_prog *tgt_prog,
19820 			    u32 btf_id,
19821 			    struct bpf_attach_target_info *tgt_info)
19822 {
19823 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19824 	const char prefix[] = "btf_trace_";
19825 	int ret = 0, subprog = -1, i;
19826 	const struct btf_type *t;
19827 	bool conservative = true;
19828 	const char *tname;
19829 	struct btf *btf;
19830 	long addr = 0;
19831 	struct module *mod = NULL;
19832 
19833 	if (!btf_id) {
19834 		bpf_log(log, "Tracing programs must provide btf_id\n");
19835 		return -EINVAL;
19836 	}
19837 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19838 	if (!btf) {
19839 		bpf_log(log,
19840 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19841 		return -EINVAL;
19842 	}
19843 	t = btf_type_by_id(btf, btf_id);
19844 	if (!t) {
19845 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19846 		return -EINVAL;
19847 	}
19848 	tname = btf_name_by_offset(btf, t->name_off);
19849 	if (!tname) {
19850 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19851 		return -EINVAL;
19852 	}
19853 	if (tgt_prog) {
19854 		struct bpf_prog_aux *aux = tgt_prog->aux;
19855 
19856 		if (bpf_prog_is_dev_bound(prog->aux) &&
19857 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19858 			bpf_log(log, "Target program bound device mismatch");
19859 			return -EINVAL;
19860 		}
19861 
19862 		for (i = 0; i < aux->func_info_cnt; i++)
19863 			if (aux->func_info[i].type_id == btf_id) {
19864 				subprog = i;
19865 				break;
19866 			}
19867 		if (subprog == -1) {
19868 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19869 			return -EINVAL;
19870 		}
19871 		conservative = aux->func_info_aux[subprog].unreliable;
19872 		if (prog_extension) {
19873 			if (conservative) {
19874 				bpf_log(log,
19875 					"Cannot replace static functions\n");
19876 				return -EINVAL;
19877 			}
19878 			if (!prog->jit_requested) {
19879 				bpf_log(log,
19880 					"Extension programs should be JITed\n");
19881 				return -EINVAL;
19882 			}
19883 		}
19884 		if (!tgt_prog->jited) {
19885 			bpf_log(log, "Can attach to only JITed progs\n");
19886 			return -EINVAL;
19887 		}
19888 		if (tgt_prog->type == prog->type) {
19889 			/* Cannot fentry/fexit another fentry/fexit program.
19890 			 * Cannot attach program extension to another extension.
19891 			 * It's ok to attach fentry/fexit to extension program.
19892 			 */
19893 			bpf_log(log, "Cannot recursively attach\n");
19894 			return -EINVAL;
19895 		}
19896 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19897 		    prog_extension &&
19898 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19899 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19900 			/* Program extensions can extend all program types
19901 			 * except fentry/fexit. The reason is the following.
19902 			 * The fentry/fexit programs are used for performance
19903 			 * analysis, stats and can be attached to any program
19904 			 * type except themselves. When extension program is
19905 			 * replacing XDP function it is necessary to allow
19906 			 * performance analysis of all functions. Both original
19907 			 * XDP program and its program extension. Hence
19908 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19909 			 * allowed. If extending of fentry/fexit was allowed it
19910 			 * would be possible to create long call chain
19911 			 * fentry->extension->fentry->extension beyond
19912 			 * reasonable stack size. Hence extending fentry is not
19913 			 * allowed.
19914 			 */
19915 			bpf_log(log, "Cannot extend fentry/fexit\n");
19916 			return -EINVAL;
19917 		}
19918 	} else {
19919 		if (prog_extension) {
19920 			bpf_log(log, "Cannot replace kernel functions\n");
19921 			return -EINVAL;
19922 		}
19923 	}
19924 
19925 	switch (prog->expected_attach_type) {
19926 	case BPF_TRACE_RAW_TP:
19927 		if (tgt_prog) {
19928 			bpf_log(log,
19929 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19930 			return -EINVAL;
19931 		}
19932 		if (!btf_type_is_typedef(t)) {
19933 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19934 				btf_id);
19935 			return -EINVAL;
19936 		}
19937 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19938 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19939 				btf_id, tname);
19940 			return -EINVAL;
19941 		}
19942 		tname += sizeof(prefix) - 1;
19943 		t = btf_type_by_id(btf, t->type);
19944 		if (!btf_type_is_ptr(t))
19945 			/* should never happen in valid vmlinux build */
19946 			return -EINVAL;
19947 		t = btf_type_by_id(btf, t->type);
19948 		if (!btf_type_is_func_proto(t))
19949 			/* should never happen in valid vmlinux build */
19950 			return -EINVAL;
19951 
19952 		break;
19953 	case BPF_TRACE_ITER:
19954 		if (!btf_type_is_func(t)) {
19955 			bpf_log(log, "attach_btf_id %u is not a function\n",
19956 				btf_id);
19957 			return -EINVAL;
19958 		}
19959 		t = btf_type_by_id(btf, t->type);
19960 		if (!btf_type_is_func_proto(t))
19961 			return -EINVAL;
19962 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19963 		if (ret)
19964 			return ret;
19965 		break;
19966 	default:
19967 		if (!prog_extension)
19968 			return -EINVAL;
19969 		fallthrough;
19970 	case BPF_MODIFY_RETURN:
19971 	case BPF_LSM_MAC:
19972 	case BPF_LSM_CGROUP:
19973 	case BPF_TRACE_FENTRY:
19974 	case BPF_TRACE_FEXIT:
19975 		if (!btf_type_is_func(t)) {
19976 			bpf_log(log, "attach_btf_id %u is not a function\n",
19977 				btf_id);
19978 			return -EINVAL;
19979 		}
19980 		if (prog_extension &&
19981 		    btf_check_type_match(log, prog, btf, t))
19982 			return -EINVAL;
19983 		t = btf_type_by_id(btf, t->type);
19984 		if (!btf_type_is_func_proto(t))
19985 			return -EINVAL;
19986 
19987 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19988 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19989 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19990 			return -EINVAL;
19991 
19992 		if (tgt_prog && conservative)
19993 			t = NULL;
19994 
19995 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19996 		if (ret < 0)
19997 			return ret;
19998 
19999 		if (tgt_prog) {
20000 			if (subprog == 0)
20001 				addr = (long) tgt_prog->bpf_func;
20002 			else
20003 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20004 		} else {
20005 			if (btf_is_module(btf)) {
20006 				mod = btf_try_get_module(btf);
20007 				if (mod)
20008 					addr = find_kallsyms_symbol_value(mod, tname);
20009 				else
20010 					addr = 0;
20011 			} else {
20012 				addr = kallsyms_lookup_name(tname);
20013 			}
20014 			if (!addr) {
20015 				module_put(mod);
20016 				bpf_log(log,
20017 					"The address of function %s cannot be found\n",
20018 					tname);
20019 				return -ENOENT;
20020 			}
20021 		}
20022 
20023 		if (prog->aux->sleepable) {
20024 			ret = -EINVAL;
20025 			switch (prog->type) {
20026 			case BPF_PROG_TYPE_TRACING:
20027 
20028 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20029 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20030 				 */
20031 				if (!check_non_sleepable_error_inject(btf_id) &&
20032 				    within_error_injection_list(addr))
20033 					ret = 0;
20034 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20035 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20036 				 */
20037 				else {
20038 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20039 										prog);
20040 
20041 					if (flags && (*flags & KF_SLEEPABLE))
20042 						ret = 0;
20043 				}
20044 				break;
20045 			case BPF_PROG_TYPE_LSM:
20046 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20047 				 * Only some of them are sleepable.
20048 				 */
20049 				if (bpf_lsm_is_sleepable_hook(btf_id))
20050 					ret = 0;
20051 				break;
20052 			default:
20053 				break;
20054 			}
20055 			if (ret) {
20056 				module_put(mod);
20057 				bpf_log(log, "%s is not sleepable\n", tname);
20058 				return ret;
20059 			}
20060 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20061 			if (tgt_prog) {
20062 				module_put(mod);
20063 				bpf_log(log, "can't modify return codes of BPF programs\n");
20064 				return -EINVAL;
20065 			}
20066 			ret = -EINVAL;
20067 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20068 			    !check_attach_modify_return(addr, tname))
20069 				ret = 0;
20070 			if (ret) {
20071 				module_put(mod);
20072 				bpf_log(log, "%s() is not modifiable\n", tname);
20073 				return ret;
20074 			}
20075 		}
20076 
20077 		break;
20078 	}
20079 	tgt_info->tgt_addr = addr;
20080 	tgt_info->tgt_name = tname;
20081 	tgt_info->tgt_type = t;
20082 	tgt_info->tgt_mod = mod;
20083 	return 0;
20084 }
20085 
20086 BTF_SET_START(btf_id_deny)
20087 BTF_ID_UNUSED
20088 #ifdef CONFIG_SMP
20089 BTF_ID(func, migrate_disable)
20090 BTF_ID(func, migrate_enable)
20091 #endif
20092 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20093 BTF_ID(func, rcu_read_unlock_strict)
20094 #endif
20095 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20096 BTF_ID(func, preempt_count_add)
20097 BTF_ID(func, preempt_count_sub)
20098 #endif
20099 #ifdef CONFIG_PREEMPT_RCU
20100 BTF_ID(func, __rcu_read_lock)
20101 BTF_ID(func, __rcu_read_unlock)
20102 #endif
20103 BTF_SET_END(btf_id_deny)
20104 
20105 static bool can_be_sleepable(struct bpf_prog *prog)
20106 {
20107 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20108 		switch (prog->expected_attach_type) {
20109 		case BPF_TRACE_FENTRY:
20110 		case BPF_TRACE_FEXIT:
20111 		case BPF_MODIFY_RETURN:
20112 		case BPF_TRACE_ITER:
20113 			return true;
20114 		default:
20115 			return false;
20116 		}
20117 	}
20118 	return prog->type == BPF_PROG_TYPE_LSM ||
20119 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20120 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20121 }
20122 
20123 static int check_attach_btf_id(struct bpf_verifier_env *env)
20124 {
20125 	struct bpf_prog *prog = env->prog;
20126 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20127 	struct bpf_attach_target_info tgt_info = {};
20128 	u32 btf_id = prog->aux->attach_btf_id;
20129 	struct bpf_trampoline *tr;
20130 	int ret;
20131 	u64 key;
20132 
20133 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20134 		if (prog->aux->sleepable)
20135 			/* attach_btf_id checked to be zero already */
20136 			return 0;
20137 		verbose(env, "Syscall programs can only be sleepable\n");
20138 		return -EINVAL;
20139 	}
20140 
20141 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20142 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20143 		return -EINVAL;
20144 	}
20145 
20146 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20147 		return check_struct_ops_btf_id(env);
20148 
20149 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20150 	    prog->type != BPF_PROG_TYPE_LSM &&
20151 	    prog->type != BPF_PROG_TYPE_EXT)
20152 		return 0;
20153 
20154 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20155 	if (ret)
20156 		return ret;
20157 
20158 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20159 		/* to make freplace equivalent to their targets, they need to
20160 		 * inherit env->ops and expected_attach_type for the rest of the
20161 		 * verification
20162 		 */
20163 		env->ops = bpf_verifier_ops[tgt_prog->type];
20164 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20165 	}
20166 
20167 	/* store info about the attachment target that will be used later */
20168 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20169 	prog->aux->attach_func_name = tgt_info.tgt_name;
20170 	prog->aux->mod = tgt_info.tgt_mod;
20171 
20172 	if (tgt_prog) {
20173 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20174 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20175 	}
20176 
20177 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20178 		prog->aux->attach_btf_trace = true;
20179 		return 0;
20180 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20181 		if (!bpf_iter_prog_supported(prog))
20182 			return -EINVAL;
20183 		return 0;
20184 	}
20185 
20186 	if (prog->type == BPF_PROG_TYPE_LSM) {
20187 		ret = bpf_lsm_verify_prog(&env->log, prog);
20188 		if (ret < 0)
20189 			return ret;
20190 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20191 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20192 		return -EINVAL;
20193 	}
20194 
20195 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20196 	tr = bpf_trampoline_get(key, &tgt_info);
20197 	if (!tr)
20198 		return -ENOMEM;
20199 
20200 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20201 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20202 
20203 	prog->aux->dst_trampoline = tr;
20204 	return 0;
20205 }
20206 
20207 struct btf *bpf_get_btf_vmlinux(void)
20208 {
20209 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20210 		mutex_lock(&bpf_verifier_lock);
20211 		if (!btf_vmlinux)
20212 			btf_vmlinux = btf_parse_vmlinux();
20213 		mutex_unlock(&bpf_verifier_lock);
20214 	}
20215 	return btf_vmlinux;
20216 }
20217 
20218 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20219 {
20220 	u64 start_time = ktime_get_ns();
20221 	struct bpf_verifier_env *env;
20222 	int i, len, ret = -EINVAL, err;
20223 	u32 log_true_size;
20224 	bool is_priv;
20225 
20226 	/* no program is valid */
20227 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20228 		return -EINVAL;
20229 
20230 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20231 	 * allocate/free it every time bpf_check() is called
20232 	 */
20233 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20234 	if (!env)
20235 		return -ENOMEM;
20236 
20237 	env->bt.env = env;
20238 
20239 	len = (*prog)->len;
20240 	env->insn_aux_data =
20241 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20242 	ret = -ENOMEM;
20243 	if (!env->insn_aux_data)
20244 		goto err_free_env;
20245 	for (i = 0; i < len; i++)
20246 		env->insn_aux_data[i].orig_idx = i;
20247 	env->prog = *prog;
20248 	env->ops = bpf_verifier_ops[env->prog->type];
20249 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20250 	is_priv = bpf_capable();
20251 
20252 	bpf_get_btf_vmlinux();
20253 
20254 	/* grab the mutex to protect few globals used by verifier */
20255 	if (!is_priv)
20256 		mutex_lock(&bpf_verifier_lock);
20257 
20258 	/* user could have requested verbose verifier output
20259 	 * and supplied buffer to store the verification trace
20260 	 */
20261 	ret = bpf_vlog_init(&env->log, attr->log_level,
20262 			    (char __user *) (unsigned long) attr->log_buf,
20263 			    attr->log_size);
20264 	if (ret)
20265 		goto err_unlock;
20266 
20267 	mark_verifier_state_clean(env);
20268 
20269 	if (IS_ERR(btf_vmlinux)) {
20270 		/* Either gcc or pahole or kernel are broken. */
20271 		verbose(env, "in-kernel BTF is malformed\n");
20272 		ret = PTR_ERR(btf_vmlinux);
20273 		goto skip_full_check;
20274 	}
20275 
20276 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20277 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20278 		env->strict_alignment = true;
20279 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20280 		env->strict_alignment = false;
20281 
20282 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20283 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20284 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20285 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20286 	env->bpf_capable = bpf_capable();
20287 
20288 	if (is_priv)
20289 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20290 
20291 	env->explored_states = kvcalloc(state_htab_size(env),
20292 				       sizeof(struct bpf_verifier_state_list *),
20293 				       GFP_USER);
20294 	ret = -ENOMEM;
20295 	if (!env->explored_states)
20296 		goto skip_full_check;
20297 
20298 	ret = add_subprog_and_kfunc(env);
20299 	if (ret < 0)
20300 		goto skip_full_check;
20301 
20302 	ret = check_subprogs(env);
20303 	if (ret < 0)
20304 		goto skip_full_check;
20305 
20306 	ret = check_btf_info(env, attr, uattr);
20307 	if (ret < 0)
20308 		goto skip_full_check;
20309 
20310 	ret = check_attach_btf_id(env);
20311 	if (ret)
20312 		goto skip_full_check;
20313 
20314 	ret = resolve_pseudo_ldimm64(env);
20315 	if (ret < 0)
20316 		goto skip_full_check;
20317 
20318 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20319 		ret = bpf_prog_offload_verifier_prep(env->prog);
20320 		if (ret)
20321 			goto skip_full_check;
20322 	}
20323 
20324 	ret = check_cfg(env);
20325 	if (ret < 0)
20326 		goto skip_full_check;
20327 
20328 	ret = do_check_subprogs(env);
20329 	ret = ret ?: do_check_main(env);
20330 
20331 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20332 		ret = bpf_prog_offload_finalize(env);
20333 
20334 skip_full_check:
20335 	kvfree(env->explored_states);
20336 
20337 	if (ret == 0)
20338 		ret = check_max_stack_depth(env);
20339 
20340 	/* instruction rewrites happen after this point */
20341 	if (ret == 0)
20342 		ret = optimize_bpf_loop(env);
20343 
20344 	if (is_priv) {
20345 		if (ret == 0)
20346 			opt_hard_wire_dead_code_branches(env);
20347 		if (ret == 0)
20348 			ret = opt_remove_dead_code(env);
20349 		if (ret == 0)
20350 			ret = opt_remove_nops(env);
20351 	} else {
20352 		if (ret == 0)
20353 			sanitize_dead_code(env);
20354 	}
20355 
20356 	if (ret == 0)
20357 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20358 		ret = convert_ctx_accesses(env);
20359 
20360 	if (ret == 0)
20361 		ret = do_misc_fixups(env);
20362 
20363 	/* do 32-bit optimization after insn patching has done so those patched
20364 	 * insns could be handled correctly.
20365 	 */
20366 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20367 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20368 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20369 								     : false;
20370 	}
20371 
20372 	if (ret == 0)
20373 		ret = fixup_call_args(env);
20374 
20375 	env->verification_time = ktime_get_ns() - start_time;
20376 	print_verification_stats(env);
20377 	env->prog->aux->verified_insns = env->insn_processed;
20378 
20379 	/* preserve original error even if log finalization is successful */
20380 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20381 	if (err)
20382 		ret = err;
20383 
20384 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20385 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20386 				  &log_true_size, sizeof(log_true_size))) {
20387 		ret = -EFAULT;
20388 		goto err_release_maps;
20389 	}
20390 
20391 	if (ret)
20392 		goto err_release_maps;
20393 
20394 	if (env->used_map_cnt) {
20395 		/* if program passed verifier, update used_maps in bpf_prog_info */
20396 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20397 							  sizeof(env->used_maps[0]),
20398 							  GFP_KERNEL);
20399 
20400 		if (!env->prog->aux->used_maps) {
20401 			ret = -ENOMEM;
20402 			goto err_release_maps;
20403 		}
20404 
20405 		memcpy(env->prog->aux->used_maps, env->used_maps,
20406 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20407 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20408 	}
20409 	if (env->used_btf_cnt) {
20410 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20411 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20412 							  sizeof(env->used_btfs[0]),
20413 							  GFP_KERNEL);
20414 		if (!env->prog->aux->used_btfs) {
20415 			ret = -ENOMEM;
20416 			goto err_release_maps;
20417 		}
20418 
20419 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20420 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20421 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20422 	}
20423 	if (env->used_map_cnt || env->used_btf_cnt) {
20424 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20425 		 * bpf_ld_imm64 instructions
20426 		 */
20427 		convert_pseudo_ld_imm64(env);
20428 	}
20429 
20430 	adjust_btf_func(env);
20431 
20432 err_release_maps:
20433 	if (!env->prog->aux->used_maps)
20434 		/* if we didn't copy map pointers into bpf_prog_info, release
20435 		 * them now. Otherwise free_used_maps() will release them.
20436 		 */
20437 		release_maps(env);
20438 	if (!env->prog->aux->used_btfs)
20439 		release_btfs(env);
20440 
20441 	/* extension progs temporarily inherit the attach_type of their targets
20442 	   for verification purposes, so set it back to zero before returning
20443 	 */
20444 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20445 		env->prog->expected_attach_type = 0;
20446 
20447 	*prog = env->prog;
20448 err_unlock:
20449 	if (!is_priv)
20450 		mutex_unlock(&bpf_verifier_lock);
20451 	vfree(env->insn_aux_data);
20452 err_free_env:
20453 	kfree(env);
20454 	return ret;
20455 }
20456