xref: /openbmc/linux/kernel/bpf/verifier.c (revision adb19164)
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 }
2543 
2544 #define DEF_NOT_SUBREG	(0)
2545 static void init_reg_state(struct bpf_verifier_env *env,
2546 			   struct bpf_func_state *state)
2547 {
2548 	struct bpf_reg_state *regs = state->regs;
2549 	int i;
2550 
2551 	for (i = 0; i < MAX_BPF_REG; i++) {
2552 		mark_reg_not_init(env, regs, i);
2553 		regs[i].live = REG_LIVE_NONE;
2554 		regs[i].parent = NULL;
2555 		regs[i].subreg_def = DEF_NOT_SUBREG;
2556 	}
2557 
2558 	/* frame pointer */
2559 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2560 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2561 	regs[BPF_REG_FP].frameno = state->frameno;
2562 }
2563 
2564 #define BPF_MAIN_FUNC (-1)
2565 static void init_func_state(struct bpf_verifier_env *env,
2566 			    struct bpf_func_state *state,
2567 			    int callsite, int frameno, int subprogno)
2568 {
2569 	state->callsite = callsite;
2570 	state->frameno = frameno;
2571 	state->subprogno = subprogno;
2572 	state->callback_ret_range = tnum_range(0, 0);
2573 	init_reg_state(env, state);
2574 	mark_verifier_state_scratched(env);
2575 }
2576 
2577 /* Similar to push_stack(), but for async callbacks */
2578 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2579 						int insn_idx, int prev_insn_idx,
2580 						int subprog)
2581 {
2582 	struct bpf_verifier_stack_elem *elem;
2583 	struct bpf_func_state *frame;
2584 
2585 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2586 	if (!elem)
2587 		goto err;
2588 
2589 	elem->insn_idx = insn_idx;
2590 	elem->prev_insn_idx = prev_insn_idx;
2591 	elem->next = env->head;
2592 	elem->log_pos = env->log.end_pos;
2593 	env->head = elem;
2594 	env->stack_size++;
2595 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2596 		verbose(env,
2597 			"The sequence of %d jumps is too complex for async cb.\n",
2598 			env->stack_size);
2599 		goto err;
2600 	}
2601 	/* Unlike push_stack() do not copy_verifier_state().
2602 	 * The caller state doesn't matter.
2603 	 * This is async callback. It starts in a fresh stack.
2604 	 * Initialize it similar to do_check_common().
2605 	 */
2606 	elem->st.branches = 1;
2607 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2608 	if (!frame)
2609 		goto err;
2610 	init_func_state(env, frame,
2611 			BPF_MAIN_FUNC /* callsite */,
2612 			0 /* frameno within this callchain */,
2613 			subprog /* subprog number within this prog */);
2614 	elem->st.frame[0] = frame;
2615 	return &elem->st;
2616 err:
2617 	free_verifier_state(env->cur_state, true);
2618 	env->cur_state = NULL;
2619 	/* pop all elements and return */
2620 	while (!pop_stack(env, NULL, NULL, false));
2621 	return NULL;
2622 }
2623 
2624 
2625 enum reg_arg_type {
2626 	SRC_OP,		/* register is used as source operand */
2627 	DST_OP,		/* register is used as destination operand */
2628 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2629 };
2630 
2631 static int cmp_subprogs(const void *a, const void *b)
2632 {
2633 	return ((struct bpf_subprog_info *)a)->start -
2634 	       ((struct bpf_subprog_info *)b)->start;
2635 }
2636 
2637 static int find_subprog(struct bpf_verifier_env *env, int off)
2638 {
2639 	struct bpf_subprog_info *p;
2640 
2641 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2642 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2643 	if (!p)
2644 		return -ENOENT;
2645 	return p - env->subprog_info;
2646 
2647 }
2648 
2649 static int add_subprog(struct bpf_verifier_env *env, int off)
2650 {
2651 	int insn_cnt = env->prog->len;
2652 	int ret;
2653 
2654 	if (off >= insn_cnt || off < 0) {
2655 		verbose(env, "call to invalid destination\n");
2656 		return -EINVAL;
2657 	}
2658 	ret = find_subprog(env, off);
2659 	if (ret >= 0)
2660 		return ret;
2661 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2662 		verbose(env, "too many subprograms\n");
2663 		return -E2BIG;
2664 	}
2665 	/* determine subprog starts. The end is one before the next starts */
2666 	env->subprog_info[env->subprog_cnt++].start = off;
2667 	sort(env->subprog_info, env->subprog_cnt,
2668 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2669 	return env->subprog_cnt - 1;
2670 }
2671 
2672 #define MAX_KFUNC_DESCS 256
2673 #define MAX_KFUNC_BTFS	256
2674 
2675 struct bpf_kfunc_desc {
2676 	struct btf_func_model func_model;
2677 	u32 func_id;
2678 	s32 imm;
2679 	u16 offset;
2680 	unsigned long addr;
2681 };
2682 
2683 struct bpf_kfunc_btf {
2684 	struct btf *btf;
2685 	struct module *module;
2686 	u16 offset;
2687 };
2688 
2689 struct bpf_kfunc_desc_tab {
2690 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2691 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2692 	 * available, therefore at the end of verification do_misc_fixups()
2693 	 * sorts this by imm and offset.
2694 	 */
2695 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2696 	u32 nr_descs;
2697 };
2698 
2699 struct bpf_kfunc_btf_tab {
2700 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2701 	u32 nr_descs;
2702 };
2703 
2704 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2705 {
2706 	const struct bpf_kfunc_desc *d0 = a;
2707 	const struct bpf_kfunc_desc *d1 = b;
2708 
2709 	/* func_id is not greater than BTF_MAX_TYPE */
2710 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2711 }
2712 
2713 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2714 {
2715 	const struct bpf_kfunc_btf *d0 = a;
2716 	const struct bpf_kfunc_btf *d1 = b;
2717 
2718 	return d0->offset - d1->offset;
2719 }
2720 
2721 static const struct bpf_kfunc_desc *
2722 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2723 {
2724 	struct bpf_kfunc_desc desc = {
2725 		.func_id = func_id,
2726 		.offset = offset,
2727 	};
2728 	struct bpf_kfunc_desc_tab *tab;
2729 
2730 	tab = prog->aux->kfunc_tab;
2731 	return bsearch(&desc, tab->descs, tab->nr_descs,
2732 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2733 }
2734 
2735 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2736 		       u16 btf_fd_idx, u8 **func_addr)
2737 {
2738 	const struct bpf_kfunc_desc *desc;
2739 
2740 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2741 	if (!desc)
2742 		return -EFAULT;
2743 
2744 	*func_addr = (u8 *)desc->addr;
2745 	return 0;
2746 }
2747 
2748 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2749 					 s16 offset)
2750 {
2751 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2752 	struct bpf_kfunc_btf_tab *tab;
2753 	struct bpf_kfunc_btf *b;
2754 	struct module *mod;
2755 	struct btf *btf;
2756 	int btf_fd;
2757 
2758 	tab = env->prog->aux->kfunc_btf_tab;
2759 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2760 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2761 	if (!b) {
2762 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2763 			verbose(env, "too many different module BTFs\n");
2764 			return ERR_PTR(-E2BIG);
2765 		}
2766 
2767 		if (bpfptr_is_null(env->fd_array)) {
2768 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2769 			return ERR_PTR(-EPROTO);
2770 		}
2771 
2772 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2773 					    offset * sizeof(btf_fd),
2774 					    sizeof(btf_fd)))
2775 			return ERR_PTR(-EFAULT);
2776 
2777 		btf = btf_get_by_fd(btf_fd);
2778 		if (IS_ERR(btf)) {
2779 			verbose(env, "invalid module BTF fd specified\n");
2780 			return btf;
2781 		}
2782 
2783 		if (!btf_is_module(btf)) {
2784 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2785 			btf_put(btf);
2786 			return ERR_PTR(-EINVAL);
2787 		}
2788 
2789 		mod = btf_try_get_module(btf);
2790 		if (!mod) {
2791 			btf_put(btf);
2792 			return ERR_PTR(-ENXIO);
2793 		}
2794 
2795 		b = &tab->descs[tab->nr_descs++];
2796 		b->btf = btf;
2797 		b->module = mod;
2798 		b->offset = offset;
2799 
2800 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2801 		     kfunc_btf_cmp_by_off, NULL);
2802 	}
2803 	return b->btf;
2804 }
2805 
2806 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2807 {
2808 	if (!tab)
2809 		return;
2810 
2811 	while (tab->nr_descs--) {
2812 		module_put(tab->descs[tab->nr_descs].module);
2813 		btf_put(tab->descs[tab->nr_descs].btf);
2814 	}
2815 	kfree(tab);
2816 }
2817 
2818 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2819 {
2820 	if (offset) {
2821 		if (offset < 0) {
2822 			/* In the future, this can be allowed to increase limit
2823 			 * of fd index into fd_array, interpreted as u16.
2824 			 */
2825 			verbose(env, "negative offset disallowed for kernel module function call\n");
2826 			return ERR_PTR(-EINVAL);
2827 		}
2828 
2829 		return __find_kfunc_desc_btf(env, offset);
2830 	}
2831 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2832 }
2833 
2834 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2835 {
2836 	const struct btf_type *func, *func_proto;
2837 	struct bpf_kfunc_btf_tab *btf_tab;
2838 	struct bpf_kfunc_desc_tab *tab;
2839 	struct bpf_prog_aux *prog_aux;
2840 	struct bpf_kfunc_desc *desc;
2841 	const char *func_name;
2842 	struct btf *desc_btf;
2843 	unsigned long call_imm;
2844 	unsigned long addr;
2845 	int err;
2846 
2847 	prog_aux = env->prog->aux;
2848 	tab = prog_aux->kfunc_tab;
2849 	btf_tab = prog_aux->kfunc_btf_tab;
2850 	if (!tab) {
2851 		if (!btf_vmlinux) {
2852 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2853 			return -ENOTSUPP;
2854 		}
2855 
2856 		if (!env->prog->jit_requested) {
2857 			verbose(env, "JIT is required for calling kernel function\n");
2858 			return -ENOTSUPP;
2859 		}
2860 
2861 		if (!bpf_jit_supports_kfunc_call()) {
2862 			verbose(env, "JIT does not support calling kernel function\n");
2863 			return -ENOTSUPP;
2864 		}
2865 
2866 		if (!env->prog->gpl_compatible) {
2867 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2868 			return -EINVAL;
2869 		}
2870 
2871 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2872 		if (!tab)
2873 			return -ENOMEM;
2874 		prog_aux->kfunc_tab = tab;
2875 	}
2876 
2877 	/* func_id == 0 is always invalid, but instead of returning an error, be
2878 	 * conservative and wait until the code elimination pass before returning
2879 	 * error, so that invalid calls that get pruned out can be in BPF programs
2880 	 * loaded from userspace.  It is also required that offset be untouched
2881 	 * for such calls.
2882 	 */
2883 	if (!func_id && !offset)
2884 		return 0;
2885 
2886 	if (!btf_tab && offset) {
2887 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2888 		if (!btf_tab)
2889 			return -ENOMEM;
2890 		prog_aux->kfunc_btf_tab = btf_tab;
2891 	}
2892 
2893 	desc_btf = find_kfunc_desc_btf(env, offset);
2894 	if (IS_ERR(desc_btf)) {
2895 		verbose(env, "failed to find BTF for kernel function\n");
2896 		return PTR_ERR(desc_btf);
2897 	}
2898 
2899 	if (find_kfunc_desc(env->prog, func_id, offset))
2900 		return 0;
2901 
2902 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2903 		verbose(env, "too many different kernel function calls\n");
2904 		return -E2BIG;
2905 	}
2906 
2907 	func = btf_type_by_id(desc_btf, func_id);
2908 	if (!func || !btf_type_is_func(func)) {
2909 		verbose(env, "kernel btf_id %u is not a function\n",
2910 			func_id);
2911 		return -EINVAL;
2912 	}
2913 	func_proto = btf_type_by_id(desc_btf, func->type);
2914 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2915 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2916 			func_id);
2917 		return -EINVAL;
2918 	}
2919 
2920 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2921 	addr = kallsyms_lookup_name(func_name);
2922 	if (!addr) {
2923 		verbose(env, "cannot find address for kernel function %s\n",
2924 			func_name);
2925 		return -EINVAL;
2926 	}
2927 	specialize_kfunc(env, func_id, offset, &addr);
2928 
2929 	if (bpf_jit_supports_far_kfunc_call()) {
2930 		call_imm = func_id;
2931 	} else {
2932 		call_imm = BPF_CALL_IMM(addr);
2933 		/* Check whether the relative offset overflows desc->imm */
2934 		if ((unsigned long)(s32)call_imm != call_imm) {
2935 			verbose(env, "address of kernel function %s is out of range\n",
2936 				func_name);
2937 			return -EINVAL;
2938 		}
2939 	}
2940 
2941 	if (bpf_dev_bound_kfunc_id(func_id)) {
2942 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2943 		if (err)
2944 			return err;
2945 	}
2946 
2947 	desc = &tab->descs[tab->nr_descs++];
2948 	desc->func_id = func_id;
2949 	desc->imm = call_imm;
2950 	desc->offset = offset;
2951 	desc->addr = addr;
2952 	err = btf_distill_func_proto(&env->log, desc_btf,
2953 				     func_proto, func_name,
2954 				     &desc->func_model);
2955 	if (!err)
2956 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2957 		     kfunc_desc_cmp_by_id_off, NULL);
2958 	return err;
2959 }
2960 
2961 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2962 {
2963 	const struct bpf_kfunc_desc *d0 = a;
2964 	const struct bpf_kfunc_desc *d1 = b;
2965 
2966 	if (d0->imm != d1->imm)
2967 		return d0->imm < d1->imm ? -1 : 1;
2968 	if (d0->offset != d1->offset)
2969 		return d0->offset < d1->offset ? -1 : 1;
2970 	return 0;
2971 }
2972 
2973 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2974 {
2975 	struct bpf_kfunc_desc_tab *tab;
2976 
2977 	tab = prog->aux->kfunc_tab;
2978 	if (!tab)
2979 		return;
2980 
2981 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2982 	     kfunc_desc_cmp_by_imm_off, NULL);
2983 }
2984 
2985 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2986 {
2987 	return !!prog->aux->kfunc_tab;
2988 }
2989 
2990 const struct btf_func_model *
2991 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2992 			 const struct bpf_insn *insn)
2993 {
2994 	const struct bpf_kfunc_desc desc = {
2995 		.imm = insn->imm,
2996 		.offset = insn->off,
2997 	};
2998 	const struct bpf_kfunc_desc *res;
2999 	struct bpf_kfunc_desc_tab *tab;
3000 
3001 	tab = prog->aux->kfunc_tab;
3002 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3003 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3004 
3005 	return res ? &res->func_model : NULL;
3006 }
3007 
3008 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3009 {
3010 	struct bpf_subprog_info *subprog = env->subprog_info;
3011 	struct bpf_insn *insn = env->prog->insnsi;
3012 	int i, ret, insn_cnt = env->prog->len;
3013 
3014 	/* Add entry function. */
3015 	ret = add_subprog(env, 0);
3016 	if (ret)
3017 		return ret;
3018 
3019 	for (i = 0; i < insn_cnt; i++, insn++) {
3020 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3021 		    !bpf_pseudo_kfunc_call(insn))
3022 			continue;
3023 
3024 		if (!env->bpf_capable) {
3025 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3026 			return -EPERM;
3027 		}
3028 
3029 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3030 			ret = add_subprog(env, i + insn->imm + 1);
3031 		else
3032 			ret = add_kfunc_call(env, insn->imm, insn->off);
3033 
3034 		if (ret < 0)
3035 			return ret;
3036 	}
3037 
3038 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3039 	 * logic. 'subprog_cnt' should not be increased.
3040 	 */
3041 	subprog[env->subprog_cnt].start = insn_cnt;
3042 
3043 	if (env->log.level & BPF_LOG_LEVEL2)
3044 		for (i = 0; i < env->subprog_cnt; i++)
3045 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3046 
3047 	return 0;
3048 }
3049 
3050 static int check_subprogs(struct bpf_verifier_env *env)
3051 {
3052 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3053 	struct bpf_subprog_info *subprog = env->subprog_info;
3054 	struct bpf_insn *insn = env->prog->insnsi;
3055 	int insn_cnt = env->prog->len;
3056 
3057 	/* now check that all jumps are within the same subprog */
3058 	subprog_start = subprog[cur_subprog].start;
3059 	subprog_end = subprog[cur_subprog + 1].start;
3060 	for (i = 0; i < insn_cnt; i++) {
3061 		u8 code = insn[i].code;
3062 
3063 		if (code == (BPF_JMP | BPF_CALL) &&
3064 		    insn[i].src_reg == 0 &&
3065 		    insn[i].imm == BPF_FUNC_tail_call)
3066 			subprog[cur_subprog].has_tail_call = true;
3067 		if (BPF_CLASS(code) == BPF_LD &&
3068 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3069 			subprog[cur_subprog].has_ld_abs = true;
3070 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3071 			goto next;
3072 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3073 			goto next;
3074 		if (code == (BPF_JMP32 | BPF_JA))
3075 			off = i + insn[i].imm + 1;
3076 		else
3077 			off = i + insn[i].off + 1;
3078 		if (off < subprog_start || off >= subprog_end) {
3079 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3080 			return -EINVAL;
3081 		}
3082 next:
3083 		if (i == subprog_end - 1) {
3084 			/* to avoid fall-through from one subprog into another
3085 			 * the last insn of the subprog should be either exit
3086 			 * or unconditional jump back
3087 			 */
3088 			if (code != (BPF_JMP | BPF_EXIT) &&
3089 			    code != (BPF_JMP32 | BPF_JA) &&
3090 			    code != (BPF_JMP | BPF_JA)) {
3091 				verbose(env, "last insn is not an exit or jmp\n");
3092 				return -EINVAL;
3093 			}
3094 			subprog_start = subprog_end;
3095 			cur_subprog++;
3096 			if (cur_subprog < env->subprog_cnt)
3097 				subprog_end = subprog[cur_subprog + 1].start;
3098 		}
3099 	}
3100 	return 0;
3101 }
3102 
3103 /* Parentage chain of this register (or stack slot) should take care of all
3104  * issues like callee-saved registers, stack slot allocation time, etc.
3105  */
3106 static int mark_reg_read(struct bpf_verifier_env *env,
3107 			 const struct bpf_reg_state *state,
3108 			 struct bpf_reg_state *parent, u8 flag)
3109 {
3110 	bool writes = parent == state->parent; /* Observe write marks */
3111 	int cnt = 0;
3112 
3113 	while (parent) {
3114 		/* if read wasn't screened by an earlier write ... */
3115 		if (writes && state->live & REG_LIVE_WRITTEN)
3116 			break;
3117 		if (parent->live & REG_LIVE_DONE) {
3118 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3119 				reg_type_str(env, parent->type),
3120 				parent->var_off.value, parent->off);
3121 			return -EFAULT;
3122 		}
3123 		/* The first condition is more likely to be true than the
3124 		 * second, checked it first.
3125 		 */
3126 		if ((parent->live & REG_LIVE_READ) == flag ||
3127 		    parent->live & REG_LIVE_READ64)
3128 			/* The parentage chain never changes and
3129 			 * this parent was already marked as LIVE_READ.
3130 			 * There is no need to keep walking the chain again and
3131 			 * keep re-marking all parents as LIVE_READ.
3132 			 * This case happens when the same register is read
3133 			 * multiple times without writes into it in-between.
3134 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3135 			 * then no need to set the weak REG_LIVE_READ32.
3136 			 */
3137 			break;
3138 		/* ... then we depend on parent's value */
3139 		parent->live |= flag;
3140 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3141 		if (flag == REG_LIVE_READ64)
3142 			parent->live &= ~REG_LIVE_READ32;
3143 		state = parent;
3144 		parent = state->parent;
3145 		writes = true;
3146 		cnt++;
3147 	}
3148 
3149 	if (env->longest_mark_read_walk < cnt)
3150 		env->longest_mark_read_walk = cnt;
3151 	return 0;
3152 }
3153 
3154 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3155 {
3156 	struct bpf_func_state *state = func(env, reg);
3157 	int spi, ret;
3158 
3159 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3160 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3161 	 * check_kfunc_call.
3162 	 */
3163 	if (reg->type == CONST_PTR_TO_DYNPTR)
3164 		return 0;
3165 	spi = dynptr_get_spi(env, reg);
3166 	if (spi < 0)
3167 		return spi;
3168 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3169 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3170 	 * read.
3171 	 */
3172 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3173 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3174 	if (ret)
3175 		return ret;
3176 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3177 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3178 }
3179 
3180 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3181 			  int spi, int nr_slots)
3182 {
3183 	struct bpf_func_state *state = func(env, reg);
3184 	int err, i;
3185 
3186 	for (i = 0; i < nr_slots; i++) {
3187 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3188 
3189 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3190 		if (err)
3191 			return err;
3192 
3193 		mark_stack_slot_scratched(env, spi - i);
3194 	}
3195 
3196 	return 0;
3197 }
3198 
3199 /* This function is supposed to be used by the following 32-bit optimization
3200  * code only. It returns TRUE if the source or destination register operates
3201  * on 64-bit, otherwise return FALSE.
3202  */
3203 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3204 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3205 {
3206 	u8 code, class, op;
3207 
3208 	code = insn->code;
3209 	class = BPF_CLASS(code);
3210 	op = BPF_OP(code);
3211 	if (class == BPF_JMP) {
3212 		/* BPF_EXIT for "main" will reach here. Return TRUE
3213 		 * conservatively.
3214 		 */
3215 		if (op == BPF_EXIT)
3216 			return true;
3217 		if (op == BPF_CALL) {
3218 			/* BPF to BPF call will reach here because of marking
3219 			 * caller saved clobber with DST_OP_NO_MARK for which we
3220 			 * don't care the register def because they are anyway
3221 			 * marked as NOT_INIT already.
3222 			 */
3223 			if (insn->src_reg == BPF_PSEUDO_CALL)
3224 				return false;
3225 			/* Helper call will reach here because of arg type
3226 			 * check, conservatively return TRUE.
3227 			 */
3228 			if (t == SRC_OP)
3229 				return true;
3230 
3231 			return false;
3232 		}
3233 	}
3234 
3235 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3236 		return false;
3237 
3238 	if (class == BPF_ALU64 || class == BPF_JMP ||
3239 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3240 		return true;
3241 
3242 	if (class == BPF_ALU || class == BPF_JMP32)
3243 		return false;
3244 
3245 	if (class == BPF_LDX) {
3246 		if (t != SRC_OP)
3247 			return BPF_SIZE(code) == BPF_DW;
3248 		/* LDX source must be ptr. */
3249 		return true;
3250 	}
3251 
3252 	if (class == BPF_STX) {
3253 		/* BPF_STX (including atomic variants) has multiple source
3254 		 * operands, one of which is a ptr. Check whether the caller is
3255 		 * asking about it.
3256 		 */
3257 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3258 			return true;
3259 		return BPF_SIZE(code) == BPF_DW;
3260 	}
3261 
3262 	if (class == BPF_LD) {
3263 		u8 mode = BPF_MODE(code);
3264 
3265 		/* LD_IMM64 */
3266 		if (mode == BPF_IMM)
3267 			return true;
3268 
3269 		/* Both LD_IND and LD_ABS return 32-bit data. */
3270 		if (t != SRC_OP)
3271 			return  false;
3272 
3273 		/* Implicit ctx ptr. */
3274 		if (regno == BPF_REG_6)
3275 			return true;
3276 
3277 		/* Explicit source could be any width. */
3278 		return true;
3279 	}
3280 
3281 	if (class == BPF_ST)
3282 		/* The only source register for BPF_ST is a ptr. */
3283 		return true;
3284 
3285 	/* Conservatively return true at default. */
3286 	return true;
3287 }
3288 
3289 /* Return the regno defined by the insn, or -1. */
3290 static int insn_def_regno(const struct bpf_insn *insn)
3291 {
3292 	switch (BPF_CLASS(insn->code)) {
3293 	case BPF_JMP:
3294 	case BPF_JMP32:
3295 	case BPF_ST:
3296 		return -1;
3297 	case BPF_STX:
3298 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3299 		    (insn->imm & BPF_FETCH)) {
3300 			if (insn->imm == BPF_CMPXCHG)
3301 				return BPF_REG_0;
3302 			else
3303 				return insn->src_reg;
3304 		} else {
3305 			return -1;
3306 		}
3307 	default:
3308 		return insn->dst_reg;
3309 	}
3310 }
3311 
3312 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3313 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3314 {
3315 	int dst_reg = insn_def_regno(insn);
3316 
3317 	if (dst_reg == -1)
3318 		return false;
3319 
3320 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3321 }
3322 
3323 static void mark_insn_zext(struct bpf_verifier_env *env,
3324 			   struct bpf_reg_state *reg)
3325 {
3326 	s32 def_idx = reg->subreg_def;
3327 
3328 	if (def_idx == DEF_NOT_SUBREG)
3329 		return;
3330 
3331 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3332 	/* The dst will be zero extended, so won't be sub-register anymore. */
3333 	reg->subreg_def = DEF_NOT_SUBREG;
3334 }
3335 
3336 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3337 			   enum reg_arg_type t)
3338 {
3339 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3340 	struct bpf_reg_state *reg;
3341 	bool rw64;
3342 
3343 	if (regno >= MAX_BPF_REG) {
3344 		verbose(env, "R%d is invalid\n", regno);
3345 		return -EINVAL;
3346 	}
3347 
3348 	mark_reg_scratched(env, regno);
3349 
3350 	reg = &regs[regno];
3351 	rw64 = is_reg64(env, insn, regno, reg, t);
3352 	if (t == SRC_OP) {
3353 		/* check whether register used as source operand can be read */
3354 		if (reg->type == NOT_INIT) {
3355 			verbose(env, "R%d !read_ok\n", regno);
3356 			return -EACCES;
3357 		}
3358 		/* We don't need to worry about FP liveness because it's read-only */
3359 		if (regno == BPF_REG_FP)
3360 			return 0;
3361 
3362 		if (rw64)
3363 			mark_insn_zext(env, reg);
3364 
3365 		return mark_reg_read(env, reg, reg->parent,
3366 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3367 	} else {
3368 		/* check whether register used as dest operand can be written to */
3369 		if (regno == BPF_REG_FP) {
3370 			verbose(env, "frame pointer is read only\n");
3371 			return -EACCES;
3372 		}
3373 		reg->live |= REG_LIVE_WRITTEN;
3374 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3375 		if (t == DST_OP)
3376 			mark_reg_unknown(env, regs, regno);
3377 	}
3378 	return 0;
3379 }
3380 
3381 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3382 			 enum reg_arg_type t)
3383 {
3384 	struct bpf_verifier_state *vstate = env->cur_state;
3385 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3386 
3387 	return __check_reg_arg(env, state->regs, regno, t);
3388 }
3389 
3390 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3391 {
3392 	env->insn_aux_data[idx].jmp_point = true;
3393 }
3394 
3395 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3396 {
3397 	return env->insn_aux_data[insn_idx].jmp_point;
3398 }
3399 
3400 /* for any branch, call, exit record the history of jmps in the given state */
3401 static int push_jmp_history(struct bpf_verifier_env *env,
3402 			    struct bpf_verifier_state *cur)
3403 {
3404 	u32 cnt = cur->jmp_history_cnt;
3405 	struct bpf_idx_pair *p;
3406 	size_t alloc_size;
3407 
3408 	if (!is_jmp_point(env, env->insn_idx))
3409 		return 0;
3410 
3411 	cnt++;
3412 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3413 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3414 	if (!p)
3415 		return -ENOMEM;
3416 	p[cnt - 1].idx = env->insn_idx;
3417 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3418 	cur->jmp_history = p;
3419 	cur->jmp_history_cnt = cnt;
3420 	return 0;
3421 }
3422 
3423 /* Backtrack one insn at a time. If idx is not at the top of recorded
3424  * history then previous instruction came from straight line execution.
3425  * Return -ENOENT if we exhausted all instructions within given state.
3426  *
3427  * It's legal to have a bit of a looping with the same starting and ending
3428  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3429  * instruction index is the same as state's first_idx doesn't mean we are
3430  * done. If there is still some jump history left, we should keep going. We
3431  * need to take into account that we might have a jump history between given
3432  * state's parent and itself, due to checkpointing. In this case, we'll have
3433  * history entry recording a jump from last instruction of parent state and
3434  * first instruction of given state.
3435  */
3436 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3437 			     u32 *history)
3438 {
3439 	u32 cnt = *history;
3440 
3441 	if (i == st->first_insn_idx) {
3442 		if (cnt == 0)
3443 			return -ENOENT;
3444 		if (cnt == 1 && st->jmp_history[0].idx == i)
3445 			return -ENOENT;
3446 	}
3447 
3448 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3449 		i = st->jmp_history[cnt - 1].prev_idx;
3450 		(*history)--;
3451 	} else {
3452 		i--;
3453 	}
3454 	return i;
3455 }
3456 
3457 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3458 {
3459 	const struct btf_type *func;
3460 	struct btf *desc_btf;
3461 
3462 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3463 		return NULL;
3464 
3465 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3466 	if (IS_ERR(desc_btf))
3467 		return "<error>";
3468 
3469 	func = btf_type_by_id(desc_btf, insn->imm);
3470 	return btf_name_by_offset(desc_btf, func->name_off);
3471 }
3472 
3473 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3474 {
3475 	bt->frame = frame;
3476 }
3477 
3478 static inline void bt_reset(struct backtrack_state *bt)
3479 {
3480 	struct bpf_verifier_env *env = bt->env;
3481 
3482 	memset(bt, 0, sizeof(*bt));
3483 	bt->env = env;
3484 }
3485 
3486 static inline u32 bt_empty(struct backtrack_state *bt)
3487 {
3488 	u64 mask = 0;
3489 	int i;
3490 
3491 	for (i = 0; i <= bt->frame; i++)
3492 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3493 
3494 	return mask == 0;
3495 }
3496 
3497 static inline int bt_subprog_enter(struct backtrack_state *bt)
3498 {
3499 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3500 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3501 		WARN_ONCE(1, "verifier backtracking bug");
3502 		return -EFAULT;
3503 	}
3504 	bt->frame++;
3505 	return 0;
3506 }
3507 
3508 static inline int bt_subprog_exit(struct backtrack_state *bt)
3509 {
3510 	if (bt->frame == 0) {
3511 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3512 		WARN_ONCE(1, "verifier backtracking bug");
3513 		return -EFAULT;
3514 	}
3515 	bt->frame--;
3516 	return 0;
3517 }
3518 
3519 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3520 {
3521 	bt->reg_masks[frame] |= 1 << reg;
3522 }
3523 
3524 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3525 {
3526 	bt->reg_masks[frame] &= ~(1 << reg);
3527 }
3528 
3529 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3530 {
3531 	bt_set_frame_reg(bt, bt->frame, reg);
3532 }
3533 
3534 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3535 {
3536 	bt_clear_frame_reg(bt, bt->frame, reg);
3537 }
3538 
3539 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3540 {
3541 	bt->stack_masks[frame] |= 1ull << slot;
3542 }
3543 
3544 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3545 {
3546 	bt->stack_masks[frame] &= ~(1ull << slot);
3547 }
3548 
3549 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3550 {
3551 	bt_set_frame_slot(bt, bt->frame, slot);
3552 }
3553 
3554 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3555 {
3556 	bt_clear_frame_slot(bt, bt->frame, slot);
3557 }
3558 
3559 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3560 {
3561 	return bt->reg_masks[frame];
3562 }
3563 
3564 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3565 {
3566 	return bt->reg_masks[bt->frame];
3567 }
3568 
3569 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3570 {
3571 	return bt->stack_masks[frame];
3572 }
3573 
3574 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3575 {
3576 	return bt->stack_masks[bt->frame];
3577 }
3578 
3579 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3580 {
3581 	return bt->reg_masks[bt->frame] & (1 << reg);
3582 }
3583 
3584 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3585 {
3586 	return bt->stack_masks[bt->frame] & (1ull << slot);
3587 }
3588 
3589 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3590 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3591 {
3592 	DECLARE_BITMAP(mask, 64);
3593 	bool first = true;
3594 	int i, n;
3595 
3596 	buf[0] = '\0';
3597 
3598 	bitmap_from_u64(mask, reg_mask);
3599 	for_each_set_bit(i, mask, 32) {
3600 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3601 		first = false;
3602 		buf += n;
3603 		buf_sz -= n;
3604 		if (buf_sz < 0)
3605 			break;
3606 	}
3607 }
3608 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3609 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3610 {
3611 	DECLARE_BITMAP(mask, 64);
3612 	bool first = true;
3613 	int i, n;
3614 
3615 	buf[0] = '\0';
3616 
3617 	bitmap_from_u64(mask, stack_mask);
3618 	for_each_set_bit(i, mask, 64) {
3619 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3620 		first = false;
3621 		buf += n;
3622 		buf_sz -= n;
3623 		if (buf_sz < 0)
3624 			break;
3625 	}
3626 }
3627 
3628 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3629 
3630 /* For given verifier state backtrack_insn() is called from the last insn to
3631  * the first insn. Its purpose is to compute a bitmask of registers and
3632  * stack slots that needs precision in the parent verifier state.
3633  *
3634  * @idx is an index of the instruction we are currently processing;
3635  * @subseq_idx is an index of the subsequent instruction that:
3636  *   - *would be* executed next, if jump history is viewed in forward order;
3637  *   - *was* processed previously during backtracking.
3638  */
3639 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3640 			  struct backtrack_state *bt)
3641 {
3642 	const struct bpf_insn_cbs cbs = {
3643 		.cb_call	= disasm_kfunc_name,
3644 		.cb_print	= verbose,
3645 		.private_data	= env,
3646 	};
3647 	struct bpf_insn *insn = env->prog->insnsi + idx;
3648 	u8 class = BPF_CLASS(insn->code);
3649 	u8 opcode = BPF_OP(insn->code);
3650 	u8 mode = BPF_MODE(insn->code);
3651 	u32 dreg = insn->dst_reg;
3652 	u32 sreg = insn->src_reg;
3653 	u32 spi, i;
3654 
3655 	if (insn->code == 0)
3656 		return 0;
3657 	if (env->log.level & BPF_LOG_LEVEL2) {
3658 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3659 		verbose(env, "mark_precise: frame%d: regs=%s ",
3660 			bt->frame, env->tmp_str_buf);
3661 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3662 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3663 		verbose(env, "%d: ", idx);
3664 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3665 	}
3666 
3667 	if (class == BPF_ALU || class == BPF_ALU64) {
3668 		if (!bt_is_reg_set(bt, dreg))
3669 			return 0;
3670 		if (opcode == BPF_END || opcode == BPF_NEG) {
3671 			/* sreg is reserved and unused
3672 			 * dreg still need precision before this insn
3673 			 */
3674 			return 0;
3675 		} else if (opcode == BPF_MOV) {
3676 			if (BPF_SRC(insn->code) == BPF_X) {
3677 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3678 				 * dreg needs precision after this insn
3679 				 * sreg needs precision before this insn
3680 				 */
3681 				bt_clear_reg(bt, dreg);
3682 				bt_set_reg(bt, sreg);
3683 			} else {
3684 				/* dreg = K
3685 				 * dreg needs precision after this insn.
3686 				 * Corresponding register is already marked
3687 				 * as precise=true in this verifier state.
3688 				 * No further markings in parent are necessary
3689 				 */
3690 				bt_clear_reg(bt, dreg);
3691 			}
3692 		} else {
3693 			if (BPF_SRC(insn->code) == BPF_X) {
3694 				/* dreg += sreg
3695 				 * both dreg and sreg need precision
3696 				 * before this insn
3697 				 */
3698 				bt_set_reg(bt, sreg);
3699 			} /* else dreg += K
3700 			   * dreg still needs precision before this insn
3701 			   */
3702 		}
3703 	} else if (class == BPF_LDX) {
3704 		if (!bt_is_reg_set(bt, dreg))
3705 			return 0;
3706 		bt_clear_reg(bt, dreg);
3707 
3708 		/* scalars can only be spilled into stack w/o losing precision.
3709 		 * Load from any other memory can be zero extended.
3710 		 * The desire to keep that precision is already indicated
3711 		 * by 'precise' mark in corresponding register of this state.
3712 		 * No further tracking necessary.
3713 		 */
3714 		if (insn->src_reg != BPF_REG_FP)
3715 			return 0;
3716 
3717 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3718 		 * that [fp - off] slot contains scalar that needs to be
3719 		 * tracked with precision
3720 		 */
3721 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3722 		if (spi >= 64) {
3723 			verbose(env, "BUG spi %d\n", spi);
3724 			WARN_ONCE(1, "verifier backtracking bug");
3725 			return -EFAULT;
3726 		}
3727 		bt_set_slot(bt, spi);
3728 	} else if (class == BPF_STX || class == BPF_ST) {
3729 		if (bt_is_reg_set(bt, dreg))
3730 			/* stx & st shouldn't be using _scalar_ dst_reg
3731 			 * to access memory. It means backtracking
3732 			 * encountered a case of pointer subtraction.
3733 			 */
3734 			return -ENOTSUPP;
3735 		/* scalars can only be spilled into stack */
3736 		if (insn->dst_reg != BPF_REG_FP)
3737 			return 0;
3738 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3739 		if (spi >= 64) {
3740 			verbose(env, "BUG spi %d\n", spi);
3741 			WARN_ONCE(1, "verifier backtracking bug");
3742 			return -EFAULT;
3743 		}
3744 		if (!bt_is_slot_set(bt, spi))
3745 			return 0;
3746 		bt_clear_slot(bt, spi);
3747 		if (class == BPF_STX)
3748 			bt_set_reg(bt, sreg);
3749 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3750 		if (bpf_pseudo_call(insn)) {
3751 			int subprog_insn_idx, subprog;
3752 
3753 			subprog_insn_idx = idx + insn->imm + 1;
3754 			subprog = find_subprog(env, subprog_insn_idx);
3755 			if (subprog < 0)
3756 				return -EFAULT;
3757 
3758 			if (subprog_is_global(env, subprog)) {
3759 				/* check that jump history doesn't have any
3760 				 * extra instructions from subprog; the next
3761 				 * instruction after call to global subprog
3762 				 * should be literally next instruction in
3763 				 * caller program
3764 				 */
3765 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3766 				/* r1-r5 are invalidated after subprog call,
3767 				 * so for global func call it shouldn't be set
3768 				 * anymore
3769 				 */
3770 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3771 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3772 					WARN_ONCE(1, "verifier backtracking bug");
3773 					return -EFAULT;
3774 				}
3775 				/* global subprog always sets R0 */
3776 				bt_clear_reg(bt, BPF_REG_0);
3777 				return 0;
3778 			} else {
3779 				/* static subprog call instruction, which
3780 				 * means that we are exiting current subprog,
3781 				 * so only r1-r5 could be still requested as
3782 				 * precise, r0 and r6-r10 or any stack slot in
3783 				 * the current frame should be zero by now
3784 				 */
3785 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3786 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3787 					WARN_ONCE(1, "verifier backtracking bug");
3788 					return -EFAULT;
3789 				}
3790 				/* we don't track register spills perfectly,
3791 				 * so fallback to force-precise instead of failing */
3792 				if (bt_stack_mask(bt) != 0)
3793 					return -ENOTSUPP;
3794 				/* propagate r1-r5 to the caller */
3795 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3796 					if (bt_is_reg_set(bt, i)) {
3797 						bt_clear_reg(bt, i);
3798 						bt_set_frame_reg(bt, bt->frame - 1, i);
3799 					}
3800 				}
3801 				if (bt_subprog_exit(bt))
3802 					return -EFAULT;
3803 				return 0;
3804 			}
3805 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3806 			/* exit from callback subprog to callback-calling helper or
3807 			 * kfunc call. Use idx/subseq_idx check to discern it from
3808 			 * straight line code backtracking.
3809 			 * Unlike the subprog call handling above, we shouldn't
3810 			 * propagate precision of r1-r5 (if any requested), as they are
3811 			 * not actually arguments passed directly to callback subprogs
3812 			 */
3813 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3814 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3815 				WARN_ONCE(1, "verifier backtracking bug");
3816 				return -EFAULT;
3817 			}
3818 			if (bt_stack_mask(bt) != 0)
3819 				return -ENOTSUPP;
3820 			/* clear r1-r5 in callback subprog's mask */
3821 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3822 				bt_clear_reg(bt, i);
3823 			if (bt_subprog_exit(bt))
3824 				return -EFAULT;
3825 			return 0;
3826 		} else if (opcode == BPF_CALL) {
3827 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3828 			 * catch this error later. Make backtracking conservative
3829 			 * with ENOTSUPP.
3830 			 */
3831 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3832 				return -ENOTSUPP;
3833 			/* regular helper call sets R0 */
3834 			bt_clear_reg(bt, BPF_REG_0);
3835 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3836 				/* if backtracing was looking for registers R1-R5
3837 				 * they should have been found already.
3838 				 */
3839 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3840 				WARN_ONCE(1, "verifier backtracking bug");
3841 				return -EFAULT;
3842 			}
3843 		} else if (opcode == BPF_EXIT) {
3844 			bool r0_precise;
3845 
3846 			/* Backtracking to a nested function call, 'idx' is a part of
3847 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3848 			 * In case of a regular function call, instructions giving
3849 			 * precision to registers R1-R5 should have been found already.
3850 			 * In case of a callback, it is ok to have R1-R5 marked for
3851 			 * backtracking, as these registers are set by the function
3852 			 * invoking callback.
3853 			 */
3854 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3855 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3856 					bt_clear_reg(bt, i);
3857 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3858 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3859 				WARN_ONCE(1, "verifier backtracking bug");
3860 				return -EFAULT;
3861 			}
3862 
3863 			/* BPF_EXIT in subprog or callback always returns
3864 			 * right after the call instruction, so by checking
3865 			 * whether the instruction at subseq_idx-1 is subprog
3866 			 * call or not we can distinguish actual exit from
3867 			 * *subprog* from exit from *callback*. In the former
3868 			 * case, we need to propagate r0 precision, if
3869 			 * necessary. In the former we never do that.
3870 			 */
3871 			r0_precise = subseq_idx - 1 >= 0 &&
3872 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3873 				     bt_is_reg_set(bt, BPF_REG_0);
3874 
3875 			bt_clear_reg(bt, BPF_REG_0);
3876 			if (bt_subprog_enter(bt))
3877 				return -EFAULT;
3878 
3879 			if (r0_precise)
3880 				bt_set_reg(bt, BPF_REG_0);
3881 			/* r6-r9 and stack slots will stay set in caller frame
3882 			 * bitmasks until we return back from callee(s)
3883 			 */
3884 			return 0;
3885 		} else if (BPF_SRC(insn->code) == BPF_X) {
3886 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3887 				return 0;
3888 			/* dreg <cond> sreg
3889 			 * Both dreg and sreg need precision before
3890 			 * this insn. If only sreg was marked precise
3891 			 * before it would be equally necessary to
3892 			 * propagate it to dreg.
3893 			 */
3894 			bt_set_reg(bt, dreg);
3895 			bt_set_reg(bt, sreg);
3896 			 /* else dreg <cond> K
3897 			  * Only dreg still needs precision before
3898 			  * this insn, so for the K-based conditional
3899 			  * there is nothing new to be marked.
3900 			  */
3901 		}
3902 	} else if (class == BPF_LD) {
3903 		if (!bt_is_reg_set(bt, dreg))
3904 			return 0;
3905 		bt_clear_reg(bt, dreg);
3906 		/* It's ld_imm64 or ld_abs or ld_ind.
3907 		 * For ld_imm64 no further tracking of precision
3908 		 * into parent is necessary
3909 		 */
3910 		if (mode == BPF_IND || mode == BPF_ABS)
3911 			/* to be analyzed */
3912 			return -ENOTSUPP;
3913 	}
3914 	return 0;
3915 }
3916 
3917 /* the scalar precision tracking algorithm:
3918  * . at the start all registers have precise=false.
3919  * . scalar ranges are tracked as normal through alu and jmp insns.
3920  * . once precise value of the scalar register is used in:
3921  *   .  ptr + scalar alu
3922  *   . if (scalar cond K|scalar)
3923  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3924  *   backtrack through the verifier states and mark all registers and
3925  *   stack slots with spilled constants that these scalar regisers
3926  *   should be precise.
3927  * . during state pruning two registers (or spilled stack slots)
3928  *   are equivalent if both are not precise.
3929  *
3930  * Note the verifier cannot simply walk register parentage chain,
3931  * since many different registers and stack slots could have been
3932  * used to compute single precise scalar.
3933  *
3934  * The approach of starting with precise=true for all registers and then
3935  * backtrack to mark a register as not precise when the verifier detects
3936  * that program doesn't care about specific value (e.g., when helper
3937  * takes register as ARG_ANYTHING parameter) is not safe.
3938  *
3939  * It's ok to walk single parentage chain of the verifier states.
3940  * It's possible that this backtracking will go all the way till 1st insn.
3941  * All other branches will be explored for needing precision later.
3942  *
3943  * The backtracking needs to deal with cases like:
3944  *   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)
3945  * r9 -= r8
3946  * r5 = r9
3947  * if r5 > 0x79f goto pc+7
3948  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3949  * r5 += 1
3950  * ...
3951  * call bpf_perf_event_output#25
3952  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3953  *
3954  * and this case:
3955  * r6 = 1
3956  * call foo // uses callee's r6 inside to compute r0
3957  * r0 += r6
3958  * if r0 == 0 goto
3959  *
3960  * to track above reg_mask/stack_mask needs to be independent for each frame.
3961  *
3962  * Also if parent's curframe > frame where backtracking started,
3963  * the verifier need to mark registers in both frames, otherwise callees
3964  * may incorrectly prune callers. This is similar to
3965  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3966  *
3967  * For now backtracking falls back into conservative marking.
3968  */
3969 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3970 				     struct bpf_verifier_state *st)
3971 {
3972 	struct bpf_func_state *func;
3973 	struct bpf_reg_state *reg;
3974 	int i, j;
3975 
3976 	if (env->log.level & BPF_LOG_LEVEL2) {
3977 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3978 			st->curframe);
3979 	}
3980 
3981 	/* big hammer: mark all scalars precise in this path.
3982 	 * pop_stack may still get !precise scalars.
3983 	 * We also skip current state and go straight to first parent state,
3984 	 * because precision markings in current non-checkpointed state are
3985 	 * not needed. See why in the comment in __mark_chain_precision below.
3986 	 */
3987 	for (st = st->parent; st; st = st->parent) {
3988 		for (i = 0; i <= st->curframe; i++) {
3989 			func = st->frame[i];
3990 			for (j = 0; j < BPF_REG_FP; j++) {
3991 				reg = &func->regs[j];
3992 				if (reg->type != SCALAR_VALUE || reg->precise)
3993 					continue;
3994 				reg->precise = true;
3995 				if (env->log.level & BPF_LOG_LEVEL2) {
3996 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3997 						i, j);
3998 				}
3999 			}
4000 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4001 				if (!is_spilled_reg(&func->stack[j]))
4002 					continue;
4003 				reg = &func->stack[j].spilled_ptr;
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 fp%d to be precise\n",
4009 						i, -(j + 1) * 8);
4010 				}
4011 			}
4012 		}
4013 	}
4014 }
4015 
4016 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4017 {
4018 	struct bpf_func_state *func;
4019 	struct bpf_reg_state *reg;
4020 	int i, j;
4021 
4022 	for (i = 0; i <= st->curframe; i++) {
4023 		func = st->frame[i];
4024 		for (j = 0; j < BPF_REG_FP; j++) {
4025 			reg = &func->regs[j];
4026 			if (reg->type != SCALAR_VALUE)
4027 				continue;
4028 			reg->precise = false;
4029 		}
4030 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4031 			if (!is_spilled_reg(&func->stack[j]))
4032 				continue;
4033 			reg = &func->stack[j].spilled_ptr;
4034 			if (reg->type != SCALAR_VALUE)
4035 				continue;
4036 			reg->precise = false;
4037 		}
4038 	}
4039 }
4040 
4041 static bool idset_contains(struct bpf_idset *s, u32 id)
4042 {
4043 	u32 i;
4044 
4045 	for (i = 0; i < s->count; ++i)
4046 		if (s->ids[i] == id)
4047 			return true;
4048 
4049 	return false;
4050 }
4051 
4052 static int idset_push(struct bpf_idset *s, u32 id)
4053 {
4054 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4055 		return -EFAULT;
4056 	s->ids[s->count++] = id;
4057 	return 0;
4058 }
4059 
4060 static void idset_reset(struct bpf_idset *s)
4061 {
4062 	s->count = 0;
4063 }
4064 
4065 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4066  * Mark all registers with these IDs as precise.
4067  */
4068 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4069 {
4070 	struct bpf_idset *precise_ids = &env->idset_scratch;
4071 	struct backtrack_state *bt = &env->bt;
4072 	struct bpf_func_state *func;
4073 	struct bpf_reg_state *reg;
4074 	DECLARE_BITMAP(mask, 64);
4075 	int i, fr;
4076 
4077 	idset_reset(precise_ids);
4078 
4079 	for (fr = bt->frame; fr >= 0; fr--) {
4080 		func = st->frame[fr];
4081 
4082 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4083 		for_each_set_bit(i, mask, 32) {
4084 			reg = &func->regs[i];
4085 			if (!reg->id || reg->type != SCALAR_VALUE)
4086 				continue;
4087 			if (idset_push(precise_ids, reg->id))
4088 				return -EFAULT;
4089 		}
4090 
4091 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4092 		for_each_set_bit(i, mask, 64) {
4093 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4094 				break;
4095 			if (!is_spilled_scalar_reg(&func->stack[i]))
4096 				continue;
4097 			reg = &func->stack[i].spilled_ptr;
4098 			if (!reg->id)
4099 				continue;
4100 			if (idset_push(precise_ids, reg->id))
4101 				return -EFAULT;
4102 		}
4103 	}
4104 
4105 	for (fr = 0; fr <= st->curframe; ++fr) {
4106 		func = st->frame[fr];
4107 
4108 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4109 			reg = &func->regs[i];
4110 			if (!reg->id)
4111 				continue;
4112 			if (!idset_contains(precise_ids, reg->id))
4113 				continue;
4114 			bt_set_frame_reg(bt, fr, i);
4115 		}
4116 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4117 			if (!is_spilled_scalar_reg(&func->stack[i]))
4118 				continue;
4119 			reg = &func->stack[i].spilled_ptr;
4120 			if (!reg->id)
4121 				continue;
4122 			if (!idset_contains(precise_ids, reg->id))
4123 				continue;
4124 			bt_set_frame_slot(bt, fr, i);
4125 		}
4126 	}
4127 
4128 	return 0;
4129 }
4130 
4131 /*
4132  * __mark_chain_precision() backtracks BPF program instruction sequence and
4133  * chain of verifier states making sure that register *regno* (if regno >= 0)
4134  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4135  * SCALARS, as well as any other registers and slots that contribute to
4136  * a tracked state of given registers/stack slots, depending on specific BPF
4137  * assembly instructions (see backtrack_insns() for exact instruction handling
4138  * logic). This backtracking relies on recorded jmp_history and is able to
4139  * traverse entire chain of parent states. This process ends only when all the
4140  * necessary registers/slots and their transitive dependencies are marked as
4141  * precise.
4142  *
4143  * One important and subtle aspect is that precise marks *do not matter* in
4144  * the currently verified state (current state). It is important to understand
4145  * why this is the case.
4146  *
4147  * First, note that current state is the state that is not yet "checkpointed",
4148  * i.e., it is not yet put into env->explored_states, and it has no children
4149  * states as well. It's ephemeral, and can end up either a) being discarded if
4150  * compatible explored state is found at some point or BPF_EXIT instruction is
4151  * reached or b) checkpointed and put into env->explored_states, branching out
4152  * into one or more children states.
4153  *
4154  * In the former case, precise markings in current state are completely
4155  * ignored by state comparison code (see regsafe() for details). Only
4156  * checkpointed ("old") state precise markings are important, and if old
4157  * state's register/slot is precise, regsafe() assumes current state's
4158  * register/slot as precise and checks value ranges exactly and precisely. If
4159  * states turn out to be compatible, current state's necessary precise
4160  * markings and any required parent states' precise markings are enforced
4161  * after the fact with propagate_precision() logic, after the fact. But it's
4162  * important to realize that in this case, even after marking current state
4163  * registers/slots as precise, we immediately discard current state. So what
4164  * actually matters is any of the precise markings propagated into current
4165  * state's parent states, which are always checkpointed (due to b) case above).
4166  * As such, for scenario a) it doesn't matter if current state has precise
4167  * markings set or not.
4168  *
4169  * Now, for the scenario b), checkpointing and forking into child(ren)
4170  * state(s). Note that before current state gets to checkpointing step, any
4171  * processed instruction always assumes precise SCALAR register/slot
4172  * knowledge: if precise value or range is useful to prune jump branch, BPF
4173  * verifier takes this opportunity enthusiastically. Similarly, when
4174  * register's value is used to calculate offset or memory address, exact
4175  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4176  * what we mentioned above about state comparison ignoring precise markings
4177  * during state comparison, BPF verifier ignores and also assumes precise
4178  * markings *at will* during instruction verification process. But as verifier
4179  * assumes precision, it also propagates any precision dependencies across
4180  * parent states, which are not yet finalized, so can be further restricted
4181  * based on new knowledge gained from restrictions enforced by their children
4182  * states. This is so that once those parent states are finalized, i.e., when
4183  * they have no more active children state, state comparison logic in
4184  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4185  * required for correctness.
4186  *
4187  * To build a bit more intuition, note also that once a state is checkpointed,
4188  * the path we took to get to that state is not important. This is crucial
4189  * property for state pruning. When state is checkpointed and finalized at
4190  * some instruction index, it can be correctly and safely used to "short
4191  * circuit" any *compatible* state that reaches exactly the same instruction
4192  * index. I.e., if we jumped to that instruction from a completely different
4193  * code path than original finalized state was derived from, it doesn't
4194  * matter, current state can be discarded because from that instruction
4195  * forward having a compatible state will ensure we will safely reach the
4196  * exit. States describe preconditions for further exploration, but completely
4197  * forget the history of how we got here.
4198  *
4199  * This also means that even if we needed precise SCALAR range to get to
4200  * finalized state, but from that point forward *that same* SCALAR register is
4201  * never used in a precise context (i.e., it's precise value is not needed for
4202  * correctness), it's correct and safe to mark such register as "imprecise"
4203  * (i.e., precise marking set to false). This is what we rely on when we do
4204  * not set precise marking in current state. If no child state requires
4205  * precision for any given SCALAR register, it's safe to dictate that it can
4206  * be imprecise. If any child state does require this register to be precise,
4207  * we'll mark it precise later retroactively during precise markings
4208  * propagation from child state to parent states.
4209  *
4210  * Skipping precise marking setting in current state is a mild version of
4211  * relying on the above observation. But we can utilize this property even
4212  * more aggressively by proactively forgetting any precise marking in the
4213  * current state (which we inherited from the parent state), right before we
4214  * checkpoint it and branch off into new child state. This is done by
4215  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4216  * finalized states which help in short circuiting more future states.
4217  */
4218 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4219 {
4220 	struct backtrack_state *bt = &env->bt;
4221 	struct bpf_verifier_state *st = env->cur_state;
4222 	int first_idx = st->first_insn_idx;
4223 	int last_idx = env->insn_idx;
4224 	int subseq_idx = -1;
4225 	struct bpf_func_state *func;
4226 	struct bpf_reg_state *reg;
4227 	bool skip_first = true;
4228 	int i, fr, err;
4229 
4230 	if (!env->bpf_capable)
4231 		return 0;
4232 
4233 	/* set frame number from which we are starting to backtrack */
4234 	bt_init(bt, env->cur_state->curframe);
4235 
4236 	/* Do sanity checks against current state of register and/or stack
4237 	 * slot, but don't set precise flag in current state, as precision
4238 	 * tracking in the current state is unnecessary.
4239 	 */
4240 	func = st->frame[bt->frame];
4241 	if (regno >= 0) {
4242 		reg = &func->regs[regno];
4243 		if (reg->type != SCALAR_VALUE) {
4244 			WARN_ONCE(1, "backtracing misuse");
4245 			return -EFAULT;
4246 		}
4247 		bt_set_reg(bt, regno);
4248 	}
4249 
4250 	if (bt_empty(bt))
4251 		return 0;
4252 
4253 	for (;;) {
4254 		DECLARE_BITMAP(mask, 64);
4255 		u32 history = st->jmp_history_cnt;
4256 
4257 		if (env->log.level & BPF_LOG_LEVEL2) {
4258 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4259 				bt->frame, last_idx, first_idx, subseq_idx);
4260 		}
4261 
4262 		/* If some register with scalar ID is marked as precise,
4263 		 * make sure that all registers sharing this ID are also precise.
4264 		 * This is needed to estimate effect of find_equal_scalars().
4265 		 * Do this at the last instruction of each state,
4266 		 * bpf_reg_state::id fields are valid for these instructions.
4267 		 *
4268 		 * Allows to track precision in situation like below:
4269 		 *
4270 		 *     r2 = unknown value
4271 		 *     ...
4272 		 *   --- state #0 ---
4273 		 *     ...
4274 		 *     r1 = r2                 // r1 and r2 now share the same ID
4275 		 *     ...
4276 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4277 		 *     ...
4278 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4279 		 *     ...
4280 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4281 		 *     r3 = r10
4282 		 *     r3 += r1                // need to mark both r1 and r2
4283 		 */
4284 		if (mark_precise_scalar_ids(env, st))
4285 			return -EFAULT;
4286 
4287 		if (last_idx < 0) {
4288 			/* we are at the entry into subprog, which
4289 			 * is expected for global funcs, but only if
4290 			 * requested precise registers are R1-R5
4291 			 * (which are global func's input arguments)
4292 			 */
4293 			if (st->curframe == 0 &&
4294 			    st->frame[0]->subprogno > 0 &&
4295 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4296 			    bt_stack_mask(bt) == 0 &&
4297 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4298 				bitmap_from_u64(mask, bt_reg_mask(bt));
4299 				for_each_set_bit(i, mask, 32) {
4300 					reg = &st->frame[0]->regs[i];
4301 					bt_clear_reg(bt, i);
4302 					if (reg->type == SCALAR_VALUE)
4303 						reg->precise = true;
4304 				}
4305 				return 0;
4306 			}
4307 
4308 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4309 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4310 			WARN_ONCE(1, "verifier backtracking bug");
4311 			return -EFAULT;
4312 		}
4313 
4314 		for (i = last_idx;;) {
4315 			if (skip_first) {
4316 				err = 0;
4317 				skip_first = false;
4318 			} else {
4319 				err = backtrack_insn(env, i, subseq_idx, bt);
4320 			}
4321 			if (err == -ENOTSUPP) {
4322 				mark_all_scalars_precise(env, env->cur_state);
4323 				bt_reset(bt);
4324 				return 0;
4325 			} else if (err) {
4326 				return err;
4327 			}
4328 			if (bt_empty(bt))
4329 				/* Found assignment(s) into tracked register in this state.
4330 				 * Since this state is already marked, just return.
4331 				 * Nothing to be tracked further in the parent state.
4332 				 */
4333 				return 0;
4334 			subseq_idx = i;
4335 			i = get_prev_insn_idx(st, i, &history);
4336 			if (i == -ENOENT)
4337 				break;
4338 			if (i >= env->prog->len) {
4339 				/* This can happen if backtracking reached insn 0
4340 				 * and there are still reg_mask or stack_mask
4341 				 * to backtrack.
4342 				 * It means the backtracking missed the spot where
4343 				 * particular register was initialized with a constant.
4344 				 */
4345 				verbose(env, "BUG backtracking idx %d\n", i);
4346 				WARN_ONCE(1, "verifier backtracking bug");
4347 				return -EFAULT;
4348 			}
4349 		}
4350 		st = st->parent;
4351 		if (!st)
4352 			break;
4353 
4354 		for (fr = bt->frame; fr >= 0; fr--) {
4355 			func = st->frame[fr];
4356 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4357 			for_each_set_bit(i, mask, 32) {
4358 				reg = &func->regs[i];
4359 				if (reg->type != SCALAR_VALUE) {
4360 					bt_clear_frame_reg(bt, fr, i);
4361 					continue;
4362 				}
4363 				if (reg->precise)
4364 					bt_clear_frame_reg(bt, fr, i);
4365 				else
4366 					reg->precise = true;
4367 			}
4368 
4369 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4370 			for_each_set_bit(i, mask, 64) {
4371 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4372 					/* the sequence of instructions:
4373 					 * 2: (bf) r3 = r10
4374 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4375 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4376 					 * doesn't contain jmps. It's backtracked
4377 					 * as a single block.
4378 					 * During backtracking insn 3 is not recognized as
4379 					 * stack access, so at the end of backtracking
4380 					 * stack slot fp-8 is still marked in stack_mask.
4381 					 * However the parent state may not have accessed
4382 					 * fp-8 and it's "unallocated" stack space.
4383 					 * In such case fallback to conservative.
4384 					 */
4385 					mark_all_scalars_precise(env, env->cur_state);
4386 					bt_reset(bt);
4387 					return 0;
4388 				}
4389 
4390 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4391 					bt_clear_frame_slot(bt, fr, i);
4392 					continue;
4393 				}
4394 				reg = &func->stack[i].spilled_ptr;
4395 				if (reg->precise)
4396 					bt_clear_frame_slot(bt, fr, i);
4397 				else
4398 					reg->precise = true;
4399 			}
4400 			if (env->log.level & BPF_LOG_LEVEL2) {
4401 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4402 					     bt_frame_reg_mask(bt, fr));
4403 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4404 					fr, env->tmp_str_buf);
4405 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4406 					       bt_frame_stack_mask(bt, fr));
4407 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4408 				print_verifier_state(env, func, true);
4409 			}
4410 		}
4411 
4412 		if (bt_empty(bt))
4413 			return 0;
4414 
4415 		subseq_idx = first_idx;
4416 		last_idx = st->last_insn_idx;
4417 		first_idx = st->first_insn_idx;
4418 	}
4419 
4420 	/* if we still have requested precise regs or slots, we missed
4421 	 * something (e.g., stack access through non-r10 register), so
4422 	 * fallback to marking all precise
4423 	 */
4424 	if (!bt_empty(bt)) {
4425 		mark_all_scalars_precise(env, env->cur_state);
4426 		bt_reset(bt);
4427 	}
4428 
4429 	return 0;
4430 }
4431 
4432 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4433 {
4434 	return __mark_chain_precision(env, regno);
4435 }
4436 
4437 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4438  * desired reg and stack masks across all relevant frames
4439  */
4440 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4441 {
4442 	return __mark_chain_precision(env, -1);
4443 }
4444 
4445 static bool is_spillable_regtype(enum bpf_reg_type type)
4446 {
4447 	switch (base_type(type)) {
4448 	case PTR_TO_MAP_VALUE:
4449 	case PTR_TO_STACK:
4450 	case PTR_TO_CTX:
4451 	case PTR_TO_PACKET:
4452 	case PTR_TO_PACKET_META:
4453 	case PTR_TO_PACKET_END:
4454 	case PTR_TO_FLOW_KEYS:
4455 	case CONST_PTR_TO_MAP:
4456 	case PTR_TO_SOCKET:
4457 	case PTR_TO_SOCK_COMMON:
4458 	case PTR_TO_TCP_SOCK:
4459 	case PTR_TO_XDP_SOCK:
4460 	case PTR_TO_BTF_ID:
4461 	case PTR_TO_BUF:
4462 	case PTR_TO_MEM:
4463 	case PTR_TO_FUNC:
4464 	case PTR_TO_MAP_KEY:
4465 		return true;
4466 	default:
4467 		return false;
4468 	}
4469 }
4470 
4471 /* Does this register contain a constant zero? */
4472 static bool register_is_null(struct bpf_reg_state *reg)
4473 {
4474 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4475 }
4476 
4477 static bool register_is_const(struct bpf_reg_state *reg)
4478 {
4479 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4480 }
4481 
4482 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4483 {
4484 	return tnum_is_unknown(reg->var_off) &&
4485 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4486 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4487 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4488 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4489 }
4490 
4491 static bool register_is_bounded(struct bpf_reg_state *reg)
4492 {
4493 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4494 }
4495 
4496 static bool __is_pointer_value(bool allow_ptr_leaks,
4497 			       const struct bpf_reg_state *reg)
4498 {
4499 	if (allow_ptr_leaks)
4500 		return false;
4501 
4502 	return reg->type != SCALAR_VALUE;
4503 }
4504 
4505 /* Copy src state preserving dst->parent and dst->live fields */
4506 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4507 {
4508 	struct bpf_reg_state *parent = dst->parent;
4509 	enum bpf_reg_liveness live = dst->live;
4510 
4511 	*dst = *src;
4512 	dst->parent = parent;
4513 	dst->live = live;
4514 }
4515 
4516 static void save_register_state(struct bpf_func_state *state,
4517 				int spi, struct bpf_reg_state *reg,
4518 				int size)
4519 {
4520 	int i;
4521 
4522 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4523 	if (size == BPF_REG_SIZE)
4524 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4525 
4526 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4527 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4528 
4529 	/* size < 8 bytes spill */
4530 	for (; i; i--)
4531 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4532 }
4533 
4534 static bool is_bpf_st_mem(struct bpf_insn *insn)
4535 {
4536 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4537 }
4538 
4539 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4540  * stack boundary and alignment are checked in check_mem_access()
4541  */
4542 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4543 				       /* stack frame we're writing to */
4544 				       struct bpf_func_state *state,
4545 				       int off, int size, int value_regno,
4546 				       int insn_idx)
4547 {
4548 	struct bpf_func_state *cur; /* state of the current function */
4549 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4550 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4551 	struct bpf_reg_state *reg = NULL;
4552 	u32 dst_reg = insn->dst_reg;
4553 
4554 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4555 	 * so it's aligned access and [off, off + size) are within stack limits
4556 	 */
4557 	if (!env->allow_ptr_leaks &&
4558 	    is_spilled_reg(&state->stack[spi]) &&
4559 	    size != BPF_REG_SIZE) {
4560 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4561 		return -EACCES;
4562 	}
4563 
4564 	cur = env->cur_state->frame[env->cur_state->curframe];
4565 	if (value_regno >= 0)
4566 		reg = &cur->regs[value_regno];
4567 	if (!env->bypass_spec_v4) {
4568 		bool sanitize = reg && is_spillable_regtype(reg->type);
4569 
4570 		for (i = 0; i < size; i++) {
4571 			u8 type = state->stack[spi].slot_type[i];
4572 
4573 			if (type != STACK_MISC && type != STACK_ZERO) {
4574 				sanitize = true;
4575 				break;
4576 			}
4577 		}
4578 
4579 		if (sanitize)
4580 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4581 	}
4582 
4583 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4584 	if (err)
4585 		return err;
4586 
4587 	mark_stack_slot_scratched(env, spi);
4588 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4589 	    !register_is_null(reg) && env->bpf_capable) {
4590 		if (dst_reg != BPF_REG_FP) {
4591 			/* The backtracking logic can only recognize explicit
4592 			 * stack slot address like [fp - 8]. Other spill of
4593 			 * scalar via different register has to be conservative.
4594 			 * Backtrack from here and mark all registers as precise
4595 			 * that contributed into 'reg' being a constant.
4596 			 */
4597 			err = mark_chain_precision(env, value_regno);
4598 			if (err)
4599 				return err;
4600 		}
4601 		save_register_state(state, spi, reg, size);
4602 		/* Break the relation on a narrowing spill. */
4603 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4604 			state->stack[spi].spilled_ptr.id = 0;
4605 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4606 		   insn->imm != 0 && env->bpf_capable) {
4607 		struct bpf_reg_state fake_reg = {};
4608 
4609 		__mark_reg_known(&fake_reg, insn->imm);
4610 		fake_reg.type = SCALAR_VALUE;
4611 		save_register_state(state, spi, &fake_reg, size);
4612 	} else if (reg && is_spillable_regtype(reg->type)) {
4613 		/* register containing pointer is being spilled into stack */
4614 		if (size != BPF_REG_SIZE) {
4615 			verbose_linfo(env, insn_idx, "; ");
4616 			verbose(env, "invalid size of register spill\n");
4617 			return -EACCES;
4618 		}
4619 		if (state != cur && reg->type == PTR_TO_STACK) {
4620 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4621 			return -EINVAL;
4622 		}
4623 		save_register_state(state, spi, reg, size);
4624 	} else {
4625 		u8 type = STACK_MISC;
4626 
4627 		/* regular write of data into stack destroys any spilled ptr */
4628 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4629 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4630 		if (is_stack_slot_special(&state->stack[spi]))
4631 			for (i = 0; i < BPF_REG_SIZE; i++)
4632 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4633 
4634 		/* only mark the slot as written if all 8 bytes were written
4635 		 * otherwise read propagation may incorrectly stop too soon
4636 		 * when stack slots are partially written.
4637 		 * This heuristic means that read propagation will be
4638 		 * conservative, since it will add reg_live_read marks
4639 		 * to stack slots all the way to first state when programs
4640 		 * writes+reads less than 8 bytes
4641 		 */
4642 		if (size == BPF_REG_SIZE)
4643 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4644 
4645 		/* when we zero initialize stack slots mark them as such */
4646 		if ((reg && register_is_null(reg)) ||
4647 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4648 			/* backtracking doesn't work for STACK_ZERO yet. */
4649 			err = mark_chain_precision(env, value_regno);
4650 			if (err)
4651 				return err;
4652 			type = STACK_ZERO;
4653 		}
4654 
4655 		/* Mark slots affected by this stack write. */
4656 		for (i = 0; i < size; i++)
4657 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4658 				type;
4659 	}
4660 	return 0;
4661 }
4662 
4663 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4664  * known to contain a variable offset.
4665  * This function checks whether the write is permitted and conservatively
4666  * tracks the effects of the write, considering that each stack slot in the
4667  * dynamic range is potentially written to.
4668  *
4669  * 'off' includes 'regno->off'.
4670  * 'value_regno' can be -1, meaning that an unknown value is being written to
4671  * the stack.
4672  *
4673  * Spilled pointers in range are not marked as written because we don't know
4674  * what's going to be actually written. This means that read propagation for
4675  * future reads cannot be terminated by this write.
4676  *
4677  * For privileged programs, uninitialized stack slots are considered
4678  * initialized by this write (even though we don't know exactly what offsets
4679  * are going to be written to). The idea is that we don't want the verifier to
4680  * reject future reads that access slots written to through variable offsets.
4681  */
4682 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4683 				     /* func where register points to */
4684 				     struct bpf_func_state *state,
4685 				     int ptr_regno, int off, int size,
4686 				     int value_regno, int insn_idx)
4687 {
4688 	struct bpf_func_state *cur; /* state of the current function */
4689 	int min_off, max_off;
4690 	int i, err;
4691 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4692 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4693 	bool writing_zero = false;
4694 	/* set if the fact that we're writing a zero is used to let any
4695 	 * stack slots remain STACK_ZERO
4696 	 */
4697 	bool zero_used = false;
4698 
4699 	cur = env->cur_state->frame[env->cur_state->curframe];
4700 	ptr_reg = &cur->regs[ptr_regno];
4701 	min_off = ptr_reg->smin_value + off;
4702 	max_off = ptr_reg->smax_value + off + size;
4703 	if (value_regno >= 0)
4704 		value_reg = &cur->regs[value_regno];
4705 	if ((value_reg && register_is_null(value_reg)) ||
4706 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4707 		writing_zero = true;
4708 
4709 	for (i = min_off; i < max_off; i++) {
4710 		int spi;
4711 
4712 		spi = __get_spi(i);
4713 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4714 		if (err)
4715 			return err;
4716 	}
4717 
4718 	/* Variable offset writes destroy any spilled pointers in range. */
4719 	for (i = min_off; i < max_off; i++) {
4720 		u8 new_type, *stype;
4721 		int slot, spi;
4722 
4723 		slot = -i - 1;
4724 		spi = slot / BPF_REG_SIZE;
4725 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4726 		mark_stack_slot_scratched(env, spi);
4727 
4728 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4729 			/* Reject the write if range we may write to has not
4730 			 * been initialized beforehand. If we didn't reject
4731 			 * here, the ptr status would be erased below (even
4732 			 * though not all slots are actually overwritten),
4733 			 * possibly opening the door to leaks.
4734 			 *
4735 			 * We do however catch STACK_INVALID case below, and
4736 			 * only allow reading possibly uninitialized memory
4737 			 * later for CAP_PERFMON, as the write may not happen to
4738 			 * that slot.
4739 			 */
4740 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4741 				insn_idx, i);
4742 			return -EINVAL;
4743 		}
4744 
4745 		/* Erase all spilled pointers. */
4746 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4747 
4748 		/* Update the slot type. */
4749 		new_type = STACK_MISC;
4750 		if (writing_zero && *stype == STACK_ZERO) {
4751 			new_type = STACK_ZERO;
4752 			zero_used = true;
4753 		}
4754 		/* If the slot is STACK_INVALID, we check whether it's OK to
4755 		 * pretend that it will be initialized by this write. The slot
4756 		 * might not actually be written to, and so if we mark it as
4757 		 * initialized future reads might leak uninitialized memory.
4758 		 * For privileged programs, we will accept such reads to slots
4759 		 * that may or may not be written because, if we're reject
4760 		 * them, the error would be too confusing.
4761 		 */
4762 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4763 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4764 					insn_idx, i);
4765 			return -EINVAL;
4766 		}
4767 		*stype = new_type;
4768 	}
4769 	if (zero_used) {
4770 		/* backtracking doesn't work for STACK_ZERO yet. */
4771 		err = mark_chain_precision(env, value_regno);
4772 		if (err)
4773 			return err;
4774 	}
4775 	return 0;
4776 }
4777 
4778 /* When register 'dst_regno' is assigned some values from stack[min_off,
4779  * max_off), we set the register's type according to the types of the
4780  * respective stack slots. If all the stack values are known to be zeros, then
4781  * so is the destination reg. Otherwise, the register is considered to be
4782  * SCALAR. This function does not deal with register filling; the caller must
4783  * ensure that all spilled registers in the stack range have been marked as
4784  * read.
4785  */
4786 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4787 				/* func where src register points to */
4788 				struct bpf_func_state *ptr_state,
4789 				int min_off, int max_off, int dst_regno)
4790 {
4791 	struct bpf_verifier_state *vstate = env->cur_state;
4792 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4793 	int i, slot, spi;
4794 	u8 *stype;
4795 	int zeros = 0;
4796 
4797 	for (i = min_off; i < max_off; i++) {
4798 		slot = -i - 1;
4799 		spi = slot / BPF_REG_SIZE;
4800 		mark_stack_slot_scratched(env, spi);
4801 		stype = ptr_state->stack[spi].slot_type;
4802 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4803 			break;
4804 		zeros++;
4805 	}
4806 	if (zeros == max_off - min_off) {
4807 		/* any access_size read into register is zero extended,
4808 		 * so the whole register == const_zero
4809 		 */
4810 		__mark_reg_const_zero(&state->regs[dst_regno]);
4811 		/* backtracking doesn't support STACK_ZERO yet,
4812 		 * so mark it precise here, so that later
4813 		 * backtracking can stop here.
4814 		 * Backtracking may not need this if this register
4815 		 * doesn't participate in pointer adjustment.
4816 		 * Forward propagation of precise flag is not
4817 		 * necessary either. This mark is only to stop
4818 		 * backtracking. Any register that contributed
4819 		 * to const 0 was marked precise before spill.
4820 		 */
4821 		state->regs[dst_regno].precise = true;
4822 	} else {
4823 		/* have read misc data from the stack */
4824 		mark_reg_unknown(env, state->regs, dst_regno);
4825 	}
4826 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4827 }
4828 
4829 /* Read the stack at 'off' and put the results into the register indicated by
4830  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4831  * spilled reg.
4832  *
4833  * 'dst_regno' can be -1, meaning that the read value is not going to a
4834  * register.
4835  *
4836  * The access is assumed to be within the current stack bounds.
4837  */
4838 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4839 				      /* func where src register points to */
4840 				      struct bpf_func_state *reg_state,
4841 				      int off, int size, int dst_regno)
4842 {
4843 	struct bpf_verifier_state *vstate = env->cur_state;
4844 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4845 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4846 	struct bpf_reg_state *reg;
4847 	u8 *stype, type;
4848 
4849 	stype = reg_state->stack[spi].slot_type;
4850 	reg = &reg_state->stack[spi].spilled_ptr;
4851 
4852 	mark_stack_slot_scratched(env, spi);
4853 
4854 	if (is_spilled_reg(&reg_state->stack[spi])) {
4855 		u8 spill_size = 1;
4856 
4857 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4858 			spill_size++;
4859 
4860 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4861 			if (reg->type != SCALAR_VALUE) {
4862 				verbose_linfo(env, env->insn_idx, "; ");
4863 				verbose(env, "invalid size of register fill\n");
4864 				return -EACCES;
4865 			}
4866 
4867 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4868 			if (dst_regno < 0)
4869 				return 0;
4870 
4871 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4872 				/* The earlier check_reg_arg() has decided the
4873 				 * subreg_def for this insn.  Save it first.
4874 				 */
4875 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4876 
4877 				copy_register_state(&state->regs[dst_regno], reg);
4878 				state->regs[dst_regno].subreg_def = subreg_def;
4879 			} else {
4880 				for (i = 0; i < size; i++) {
4881 					type = stype[(slot - i) % BPF_REG_SIZE];
4882 					if (type == STACK_SPILL)
4883 						continue;
4884 					if (type == STACK_MISC)
4885 						continue;
4886 					if (type == STACK_INVALID && env->allow_uninit_stack)
4887 						continue;
4888 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4889 						off, i, size);
4890 					return -EACCES;
4891 				}
4892 				mark_reg_unknown(env, state->regs, dst_regno);
4893 			}
4894 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4895 			return 0;
4896 		}
4897 
4898 		if (dst_regno >= 0) {
4899 			/* restore register state from stack */
4900 			copy_register_state(&state->regs[dst_regno], reg);
4901 			/* mark reg as written since spilled pointer state likely
4902 			 * has its liveness marks cleared by is_state_visited()
4903 			 * which resets stack/reg liveness for state transitions
4904 			 */
4905 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4906 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4907 			/* If dst_regno==-1, the caller is asking us whether
4908 			 * it is acceptable to use this value as a SCALAR_VALUE
4909 			 * (e.g. for XADD).
4910 			 * We must not allow unprivileged callers to do that
4911 			 * with spilled pointers.
4912 			 */
4913 			verbose(env, "leaking pointer from stack off %d\n",
4914 				off);
4915 			return -EACCES;
4916 		}
4917 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4918 	} else {
4919 		for (i = 0; i < size; i++) {
4920 			type = stype[(slot - i) % BPF_REG_SIZE];
4921 			if (type == STACK_MISC)
4922 				continue;
4923 			if (type == STACK_ZERO)
4924 				continue;
4925 			if (type == STACK_INVALID && env->allow_uninit_stack)
4926 				continue;
4927 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4928 				off, i, size);
4929 			return -EACCES;
4930 		}
4931 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4932 		if (dst_regno >= 0)
4933 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4934 	}
4935 	return 0;
4936 }
4937 
4938 enum bpf_access_src {
4939 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4940 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4941 };
4942 
4943 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4944 					 int regno, int off, int access_size,
4945 					 bool zero_size_allowed,
4946 					 enum bpf_access_src type,
4947 					 struct bpf_call_arg_meta *meta);
4948 
4949 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4950 {
4951 	return cur_regs(env) + regno;
4952 }
4953 
4954 /* Read the stack at 'ptr_regno + off' and put the result into the register
4955  * 'dst_regno'.
4956  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4957  * but not its variable offset.
4958  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4959  *
4960  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4961  * filling registers (i.e. reads of spilled register cannot be detected when
4962  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4963  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4964  * offset; for a fixed offset check_stack_read_fixed_off should be used
4965  * instead.
4966  */
4967 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4968 				    int ptr_regno, int off, int size, int dst_regno)
4969 {
4970 	/* The state of the source register. */
4971 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4972 	struct bpf_func_state *ptr_state = func(env, reg);
4973 	int err;
4974 	int min_off, max_off;
4975 
4976 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4977 	 */
4978 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4979 					    false, ACCESS_DIRECT, NULL);
4980 	if (err)
4981 		return err;
4982 
4983 	min_off = reg->smin_value + off;
4984 	max_off = reg->smax_value + off;
4985 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4986 	return 0;
4987 }
4988 
4989 /* check_stack_read dispatches to check_stack_read_fixed_off or
4990  * check_stack_read_var_off.
4991  *
4992  * The caller must ensure that the offset falls within the allocated stack
4993  * bounds.
4994  *
4995  * 'dst_regno' is a register which will receive the value from the stack. It
4996  * can be -1, meaning that the read value is not going to a register.
4997  */
4998 static int check_stack_read(struct bpf_verifier_env *env,
4999 			    int ptr_regno, int off, int size,
5000 			    int dst_regno)
5001 {
5002 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5003 	struct bpf_func_state *state = func(env, reg);
5004 	int err;
5005 	/* Some accesses are only permitted with a static offset. */
5006 	bool var_off = !tnum_is_const(reg->var_off);
5007 
5008 	/* The offset is required to be static when reads don't go to a
5009 	 * register, in order to not leak pointers (see
5010 	 * check_stack_read_fixed_off).
5011 	 */
5012 	if (dst_regno < 0 && var_off) {
5013 		char tn_buf[48];
5014 
5015 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5016 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5017 			tn_buf, off, size);
5018 		return -EACCES;
5019 	}
5020 	/* Variable offset is prohibited for unprivileged mode for simplicity
5021 	 * since it requires corresponding support in Spectre masking for stack
5022 	 * ALU. See also retrieve_ptr_limit(). The check in
5023 	 * check_stack_access_for_ptr_arithmetic() called by
5024 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5025 	 * with variable offsets, therefore no check is required here. Further,
5026 	 * just checking it here would be insufficient as speculative stack
5027 	 * writes could still lead to unsafe speculative behaviour.
5028 	 */
5029 	if (!var_off) {
5030 		off += reg->var_off.value;
5031 		err = check_stack_read_fixed_off(env, state, off, size,
5032 						 dst_regno);
5033 	} else {
5034 		/* Variable offset stack reads need more conservative handling
5035 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5036 		 * branch.
5037 		 */
5038 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5039 					       dst_regno);
5040 	}
5041 	return err;
5042 }
5043 
5044 
5045 /* check_stack_write dispatches to check_stack_write_fixed_off or
5046  * check_stack_write_var_off.
5047  *
5048  * 'ptr_regno' is the register used as a pointer into the stack.
5049  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5050  * 'value_regno' is the register whose value we're writing to the stack. It can
5051  * be -1, meaning that we're not writing from a register.
5052  *
5053  * The caller must ensure that the offset falls within the maximum stack size.
5054  */
5055 static int check_stack_write(struct bpf_verifier_env *env,
5056 			     int ptr_regno, int off, int size,
5057 			     int value_regno, int insn_idx)
5058 {
5059 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5060 	struct bpf_func_state *state = func(env, reg);
5061 	int err;
5062 
5063 	if (tnum_is_const(reg->var_off)) {
5064 		off += reg->var_off.value;
5065 		err = check_stack_write_fixed_off(env, state, off, size,
5066 						  value_regno, insn_idx);
5067 	} else {
5068 		/* Variable offset stack reads need more conservative handling
5069 		 * than fixed offset ones.
5070 		 */
5071 		err = check_stack_write_var_off(env, state,
5072 						ptr_regno, off, size,
5073 						value_regno, insn_idx);
5074 	}
5075 	return err;
5076 }
5077 
5078 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5079 				 int off, int size, enum bpf_access_type type)
5080 {
5081 	struct bpf_reg_state *regs = cur_regs(env);
5082 	struct bpf_map *map = regs[regno].map_ptr;
5083 	u32 cap = bpf_map_flags_to_cap(map);
5084 
5085 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5086 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5087 			map->value_size, off, size);
5088 		return -EACCES;
5089 	}
5090 
5091 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5092 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5093 			map->value_size, off, size);
5094 		return -EACCES;
5095 	}
5096 
5097 	return 0;
5098 }
5099 
5100 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5101 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5102 			      int off, int size, u32 mem_size,
5103 			      bool zero_size_allowed)
5104 {
5105 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5106 	struct bpf_reg_state *reg;
5107 
5108 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5109 		return 0;
5110 
5111 	reg = &cur_regs(env)[regno];
5112 	switch (reg->type) {
5113 	case PTR_TO_MAP_KEY:
5114 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5115 			mem_size, off, size);
5116 		break;
5117 	case PTR_TO_MAP_VALUE:
5118 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5119 			mem_size, off, size);
5120 		break;
5121 	case PTR_TO_PACKET:
5122 	case PTR_TO_PACKET_META:
5123 	case PTR_TO_PACKET_END:
5124 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5125 			off, size, regno, reg->id, off, mem_size);
5126 		break;
5127 	case PTR_TO_MEM:
5128 	default:
5129 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5130 			mem_size, off, size);
5131 	}
5132 
5133 	return -EACCES;
5134 }
5135 
5136 /* check read/write into a memory region with possible variable offset */
5137 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5138 				   int off, int size, u32 mem_size,
5139 				   bool zero_size_allowed)
5140 {
5141 	struct bpf_verifier_state *vstate = env->cur_state;
5142 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5143 	struct bpf_reg_state *reg = &state->regs[regno];
5144 	int err;
5145 
5146 	/* We may have adjusted the register pointing to memory region, so we
5147 	 * need to try adding each of min_value and max_value to off
5148 	 * to make sure our theoretical access will be safe.
5149 	 *
5150 	 * The minimum value is only important with signed
5151 	 * comparisons where we can't assume the floor of a
5152 	 * value is 0.  If we are using signed variables for our
5153 	 * index'es we need to make sure that whatever we use
5154 	 * will have a set floor within our range.
5155 	 */
5156 	if (reg->smin_value < 0 &&
5157 	    (reg->smin_value == S64_MIN ||
5158 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5159 	      reg->smin_value + off < 0)) {
5160 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5161 			regno);
5162 		return -EACCES;
5163 	}
5164 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5165 				 mem_size, zero_size_allowed);
5166 	if (err) {
5167 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5168 			regno);
5169 		return err;
5170 	}
5171 
5172 	/* If we haven't set a max value then we need to bail since we can't be
5173 	 * sure we won't do bad things.
5174 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5175 	 */
5176 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5177 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5178 			regno);
5179 		return -EACCES;
5180 	}
5181 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5182 				 mem_size, zero_size_allowed);
5183 	if (err) {
5184 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5185 			regno);
5186 		return err;
5187 	}
5188 
5189 	return 0;
5190 }
5191 
5192 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5193 			       const struct bpf_reg_state *reg, int regno,
5194 			       bool fixed_off_ok)
5195 {
5196 	/* Access to this pointer-typed register or passing it to a helper
5197 	 * is only allowed in its original, unmodified form.
5198 	 */
5199 
5200 	if (reg->off < 0) {
5201 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5202 			reg_type_str(env, reg->type), regno, reg->off);
5203 		return -EACCES;
5204 	}
5205 
5206 	if (!fixed_off_ok && reg->off) {
5207 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5208 			reg_type_str(env, reg->type), regno, reg->off);
5209 		return -EACCES;
5210 	}
5211 
5212 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5213 		char tn_buf[48];
5214 
5215 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5216 		verbose(env, "variable %s access var_off=%s disallowed\n",
5217 			reg_type_str(env, reg->type), tn_buf);
5218 		return -EACCES;
5219 	}
5220 
5221 	return 0;
5222 }
5223 
5224 int check_ptr_off_reg(struct bpf_verifier_env *env,
5225 		      const struct bpf_reg_state *reg, int regno)
5226 {
5227 	return __check_ptr_off_reg(env, reg, regno, false);
5228 }
5229 
5230 static int map_kptr_match_type(struct bpf_verifier_env *env,
5231 			       struct btf_field *kptr_field,
5232 			       struct bpf_reg_state *reg, u32 regno)
5233 {
5234 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5235 	int perm_flags;
5236 	const char *reg_name = "";
5237 
5238 	if (btf_is_kernel(reg->btf)) {
5239 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5240 
5241 		/* Only unreferenced case accepts untrusted pointers */
5242 		if (kptr_field->type == BPF_KPTR_UNREF)
5243 			perm_flags |= PTR_UNTRUSTED;
5244 	} else {
5245 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5246 	}
5247 
5248 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5249 		goto bad_type;
5250 
5251 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5252 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5253 
5254 	/* For ref_ptr case, release function check should ensure we get one
5255 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5256 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5257 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5258 	 * reg->off and reg->ref_obj_id are not needed here.
5259 	 */
5260 	if (__check_ptr_off_reg(env, reg, regno, true))
5261 		return -EACCES;
5262 
5263 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5264 	 * we also need to take into account the reg->off.
5265 	 *
5266 	 * We want to support cases like:
5267 	 *
5268 	 * struct foo {
5269 	 *         struct bar br;
5270 	 *         struct baz bz;
5271 	 * };
5272 	 *
5273 	 * struct foo *v;
5274 	 * v = func();	      // PTR_TO_BTF_ID
5275 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5276 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5277 	 *                    // first member type of struct after comparison fails
5278 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5279 	 *                    // to match type
5280 	 *
5281 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5282 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5283 	 * the struct to match type against first member of struct, i.e. reject
5284 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5285 	 * strict mode to true for type match.
5286 	 */
5287 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5288 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5289 				  kptr_field->type == BPF_KPTR_REF))
5290 		goto bad_type;
5291 	return 0;
5292 bad_type:
5293 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5294 		reg_type_str(env, reg->type), reg_name);
5295 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5296 	if (kptr_field->type == BPF_KPTR_UNREF)
5297 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5298 			targ_name);
5299 	else
5300 		verbose(env, "\n");
5301 	return -EINVAL;
5302 }
5303 
5304 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5305  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5306  */
5307 static bool in_rcu_cs(struct bpf_verifier_env *env)
5308 {
5309 	return env->cur_state->active_rcu_lock ||
5310 	       env->cur_state->active_lock.ptr ||
5311 	       !env->prog->aux->sleepable;
5312 }
5313 
5314 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5315 BTF_SET_START(rcu_protected_types)
5316 BTF_ID(struct, prog_test_ref_kfunc)
5317 BTF_ID(struct, cgroup)
5318 BTF_ID(struct, bpf_cpumask)
5319 BTF_ID(struct, task_struct)
5320 BTF_SET_END(rcu_protected_types)
5321 
5322 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5323 {
5324 	if (!btf_is_kernel(btf))
5325 		return false;
5326 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5327 }
5328 
5329 static bool rcu_safe_kptr(const struct btf_field *field)
5330 {
5331 	const struct btf_field_kptr *kptr = &field->kptr;
5332 
5333 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5334 }
5335 
5336 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5337 				 int value_regno, int insn_idx,
5338 				 struct btf_field *kptr_field)
5339 {
5340 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5341 	int class = BPF_CLASS(insn->code);
5342 	struct bpf_reg_state *val_reg;
5343 
5344 	/* Things we already checked for in check_map_access and caller:
5345 	 *  - Reject cases where variable offset may touch kptr
5346 	 *  - size of access (must be BPF_DW)
5347 	 *  - tnum_is_const(reg->var_off)
5348 	 *  - kptr_field->offset == off + reg->var_off.value
5349 	 */
5350 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5351 	if (BPF_MODE(insn->code) != BPF_MEM) {
5352 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5353 		return -EACCES;
5354 	}
5355 
5356 	/* We only allow loading referenced kptr, since it will be marked as
5357 	 * untrusted, similar to unreferenced kptr.
5358 	 */
5359 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5360 		verbose(env, "store to referenced kptr disallowed\n");
5361 		return -EACCES;
5362 	}
5363 
5364 	if (class == BPF_LDX) {
5365 		val_reg = reg_state(env, value_regno);
5366 		/* We can simply mark the value_regno receiving the pointer
5367 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5368 		 */
5369 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5370 				kptr_field->kptr.btf_id,
5371 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5372 				PTR_MAYBE_NULL | MEM_RCU :
5373 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5374 		/* For mark_ptr_or_null_reg */
5375 		val_reg->id = ++env->id_gen;
5376 	} else if (class == BPF_STX) {
5377 		val_reg = reg_state(env, value_regno);
5378 		if (!register_is_null(val_reg) &&
5379 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5380 			return -EACCES;
5381 	} else if (class == BPF_ST) {
5382 		if (insn->imm) {
5383 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5384 				kptr_field->offset);
5385 			return -EACCES;
5386 		}
5387 	} else {
5388 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5389 		return -EACCES;
5390 	}
5391 	return 0;
5392 }
5393 
5394 /* check read/write into a map element with possible variable offset */
5395 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5396 			    int off, int size, bool zero_size_allowed,
5397 			    enum bpf_access_src src)
5398 {
5399 	struct bpf_verifier_state *vstate = env->cur_state;
5400 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5401 	struct bpf_reg_state *reg = &state->regs[regno];
5402 	struct bpf_map *map = reg->map_ptr;
5403 	struct btf_record *rec;
5404 	int err, i;
5405 
5406 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5407 				      zero_size_allowed);
5408 	if (err)
5409 		return err;
5410 
5411 	if (IS_ERR_OR_NULL(map->record))
5412 		return 0;
5413 	rec = map->record;
5414 	for (i = 0; i < rec->cnt; i++) {
5415 		struct btf_field *field = &rec->fields[i];
5416 		u32 p = field->offset;
5417 
5418 		/* If any part of a field  can be touched by load/store, reject
5419 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5420 		 * it is sufficient to check x1 < y2 && y1 < x2.
5421 		 */
5422 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5423 		    p < reg->umax_value + off + size) {
5424 			switch (field->type) {
5425 			case BPF_KPTR_UNREF:
5426 			case BPF_KPTR_REF:
5427 				if (src != ACCESS_DIRECT) {
5428 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5429 					return -EACCES;
5430 				}
5431 				if (!tnum_is_const(reg->var_off)) {
5432 					verbose(env, "kptr access cannot have variable offset\n");
5433 					return -EACCES;
5434 				}
5435 				if (p != off + reg->var_off.value) {
5436 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5437 						p, off + reg->var_off.value);
5438 					return -EACCES;
5439 				}
5440 				if (size != bpf_size_to_bytes(BPF_DW)) {
5441 					verbose(env, "kptr access size must be BPF_DW\n");
5442 					return -EACCES;
5443 				}
5444 				break;
5445 			default:
5446 				verbose(env, "%s cannot be accessed directly by load/store\n",
5447 					btf_field_type_name(field->type));
5448 				return -EACCES;
5449 			}
5450 		}
5451 	}
5452 	return 0;
5453 }
5454 
5455 #define MAX_PACKET_OFF 0xffff
5456 
5457 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5458 				       const struct bpf_call_arg_meta *meta,
5459 				       enum bpf_access_type t)
5460 {
5461 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5462 
5463 	switch (prog_type) {
5464 	/* Program types only with direct read access go here! */
5465 	case BPF_PROG_TYPE_LWT_IN:
5466 	case BPF_PROG_TYPE_LWT_OUT:
5467 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5468 	case BPF_PROG_TYPE_SK_REUSEPORT:
5469 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5470 	case BPF_PROG_TYPE_CGROUP_SKB:
5471 		if (t == BPF_WRITE)
5472 			return false;
5473 		fallthrough;
5474 
5475 	/* Program types with direct read + write access go here! */
5476 	case BPF_PROG_TYPE_SCHED_CLS:
5477 	case BPF_PROG_TYPE_SCHED_ACT:
5478 	case BPF_PROG_TYPE_XDP:
5479 	case BPF_PROG_TYPE_LWT_XMIT:
5480 	case BPF_PROG_TYPE_SK_SKB:
5481 	case BPF_PROG_TYPE_SK_MSG:
5482 		if (meta)
5483 			return meta->pkt_access;
5484 
5485 		env->seen_direct_write = true;
5486 		return true;
5487 
5488 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5489 		if (t == BPF_WRITE)
5490 			env->seen_direct_write = true;
5491 
5492 		return true;
5493 
5494 	default:
5495 		return false;
5496 	}
5497 }
5498 
5499 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5500 			       int size, bool zero_size_allowed)
5501 {
5502 	struct bpf_reg_state *regs = cur_regs(env);
5503 	struct bpf_reg_state *reg = &regs[regno];
5504 	int err;
5505 
5506 	/* We may have added a variable offset to the packet pointer; but any
5507 	 * reg->range we have comes after that.  We are only checking the fixed
5508 	 * offset.
5509 	 */
5510 
5511 	/* We don't allow negative numbers, because we aren't tracking enough
5512 	 * detail to prove they're safe.
5513 	 */
5514 	if (reg->smin_value < 0) {
5515 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5516 			regno);
5517 		return -EACCES;
5518 	}
5519 
5520 	err = reg->range < 0 ? -EINVAL :
5521 	      __check_mem_access(env, regno, off, size, reg->range,
5522 				 zero_size_allowed);
5523 	if (err) {
5524 		verbose(env, "R%d offset is outside of the packet\n", regno);
5525 		return err;
5526 	}
5527 
5528 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5529 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5530 	 * otherwise find_good_pkt_pointers would have refused to set range info
5531 	 * that __check_mem_access would have rejected this pkt access.
5532 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5533 	 */
5534 	env->prog->aux->max_pkt_offset =
5535 		max_t(u32, env->prog->aux->max_pkt_offset,
5536 		      off + reg->umax_value + size - 1);
5537 
5538 	return err;
5539 }
5540 
5541 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5542 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5543 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5544 			    struct btf **btf, u32 *btf_id)
5545 {
5546 	struct bpf_insn_access_aux info = {
5547 		.reg_type = *reg_type,
5548 		.log = &env->log,
5549 	};
5550 
5551 	if (env->ops->is_valid_access &&
5552 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5553 		/* A non zero info.ctx_field_size indicates that this field is a
5554 		 * candidate for later verifier transformation to load the whole
5555 		 * field and then apply a mask when accessed with a narrower
5556 		 * access than actual ctx access size. A zero info.ctx_field_size
5557 		 * will only allow for whole field access and rejects any other
5558 		 * type of narrower access.
5559 		 */
5560 		*reg_type = info.reg_type;
5561 
5562 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5563 			*btf = info.btf;
5564 			*btf_id = info.btf_id;
5565 		} else {
5566 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5567 		}
5568 		/* remember the offset of last byte accessed in ctx */
5569 		if (env->prog->aux->max_ctx_offset < off + size)
5570 			env->prog->aux->max_ctx_offset = off + size;
5571 		return 0;
5572 	}
5573 
5574 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5575 	return -EACCES;
5576 }
5577 
5578 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5579 				  int size)
5580 {
5581 	if (size < 0 || off < 0 ||
5582 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5583 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5584 			off, size);
5585 		return -EACCES;
5586 	}
5587 	return 0;
5588 }
5589 
5590 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5591 			     u32 regno, int off, int size,
5592 			     enum bpf_access_type t)
5593 {
5594 	struct bpf_reg_state *regs = cur_regs(env);
5595 	struct bpf_reg_state *reg = &regs[regno];
5596 	struct bpf_insn_access_aux info = {};
5597 	bool valid;
5598 
5599 	if (reg->smin_value < 0) {
5600 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5601 			regno);
5602 		return -EACCES;
5603 	}
5604 
5605 	switch (reg->type) {
5606 	case PTR_TO_SOCK_COMMON:
5607 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5608 		break;
5609 	case PTR_TO_SOCKET:
5610 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5611 		break;
5612 	case PTR_TO_TCP_SOCK:
5613 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5614 		break;
5615 	case PTR_TO_XDP_SOCK:
5616 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5617 		break;
5618 	default:
5619 		valid = false;
5620 	}
5621 
5622 
5623 	if (valid) {
5624 		env->insn_aux_data[insn_idx].ctx_field_size =
5625 			info.ctx_field_size;
5626 		return 0;
5627 	}
5628 
5629 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5630 		regno, reg_type_str(env, reg->type), off, size);
5631 
5632 	return -EACCES;
5633 }
5634 
5635 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5636 {
5637 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5638 }
5639 
5640 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5641 {
5642 	const struct bpf_reg_state *reg = reg_state(env, regno);
5643 
5644 	return reg->type == PTR_TO_CTX;
5645 }
5646 
5647 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5648 {
5649 	const struct bpf_reg_state *reg = reg_state(env, regno);
5650 
5651 	return type_is_sk_pointer(reg->type);
5652 }
5653 
5654 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5655 {
5656 	const struct bpf_reg_state *reg = reg_state(env, regno);
5657 
5658 	return type_is_pkt_pointer(reg->type);
5659 }
5660 
5661 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5662 {
5663 	const struct bpf_reg_state *reg = reg_state(env, regno);
5664 
5665 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5666 	return reg->type == PTR_TO_FLOW_KEYS;
5667 }
5668 
5669 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5670 #ifdef CONFIG_NET
5671 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5672 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5673 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5674 #endif
5675 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5676 };
5677 
5678 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5679 {
5680 	/* A referenced register is always trusted. */
5681 	if (reg->ref_obj_id)
5682 		return true;
5683 
5684 	/* Types listed in the reg2btf_ids are always trusted */
5685 	if (reg2btf_ids[base_type(reg->type)])
5686 		return true;
5687 
5688 	/* If a register is not referenced, it is trusted if it has the
5689 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5690 	 * other type modifiers may be safe, but we elect to take an opt-in
5691 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5692 	 * not.
5693 	 *
5694 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5695 	 * for whether a register is trusted.
5696 	 */
5697 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5698 	       !bpf_type_has_unsafe_modifiers(reg->type);
5699 }
5700 
5701 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5702 {
5703 	return reg->type & MEM_RCU;
5704 }
5705 
5706 static void clear_trusted_flags(enum bpf_type_flag *flag)
5707 {
5708 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5709 }
5710 
5711 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5712 				   const struct bpf_reg_state *reg,
5713 				   int off, int size, bool strict)
5714 {
5715 	struct tnum reg_off;
5716 	int ip_align;
5717 
5718 	/* Byte size accesses are always allowed. */
5719 	if (!strict || size == 1)
5720 		return 0;
5721 
5722 	/* For platforms that do not have a Kconfig enabling
5723 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5724 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5725 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5726 	 * to this code only in strict mode where we want to emulate
5727 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5728 	 * unconditional IP align value of '2'.
5729 	 */
5730 	ip_align = 2;
5731 
5732 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5733 	if (!tnum_is_aligned(reg_off, size)) {
5734 		char tn_buf[48];
5735 
5736 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5737 		verbose(env,
5738 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5739 			ip_align, tn_buf, reg->off, off, size);
5740 		return -EACCES;
5741 	}
5742 
5743 	return 0;
5744 }
5745 
5746 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5747 				       const struct bpf_reg_state *reg,
5748 				       const char *pointer_desc,
5749 				       int off, int size, bool strict)
5750 {
5751 	struct tnum reg_off;
5752 
5753 	/* Byte size accesses are always allowed. */
5754 	if (!strict || size == 1)
5755 		return 0;
5756 
5757 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5758 	if (!tnum_is_aligned(reg_off, size)) {
5759 		char tn_buf[48];
5760 
5761 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5762 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5763 			pointer_desc, tn_buf, reg->off, off, size);
5764 		return -EACCES;
5765 	}
5766 
5767 	return 0;
5768 }
5769 
5770 static int check_ptr_alignment(struct bpf_verifier_env *env,
5771 			       const struct bpf_reg_state *reg, int off,
5772 			       int size, bool strict_alignment_once)
5773 {
5774 	bool strict = env->strict_alignment || strict_alignment_once;
5775 	const char *pointer_desc = "";
5776 
5777 	switch (reg->type) {
5778 	case PTR_TO_PACKET:
5779 	case PTR_TO_PACKET_META:
5780 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5781 		 * right in front, treat it the very same way.
5782 		 */
5783 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5784 	case PTR_TO_FLOW_KEYS:
5785 		pointer_desc = "flow keys ";
5786 		break;
5787 	case PTR_TO_MAP_KEY:
5788 		pointer_desc = "key ";
5789 		break;
5790 	case PTR_TO_MAP_VALUE:
5791 		pointer_desc = "value ";
5792 		break;
5793 	case PTR_TO_CTX:
5794 		pointer_desc = "context ";
5795 		break;
5796 	case PTR_TO_STACK:
5797 		pointer_desc = "stack ";
5798 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5799 		 * and check_stack_read_fixed_off() relies on stack accesses being
5800 		 * aligned.
5801 		 */
5802 		strict = true;
5803 		break;
5804 	case PTR_TO_SOCKET:
5805 		pointer_desc = "sock ";
5806 		break;
5807 	case PTR_TO_SOCK_COMMON:
5808 		pointer_desc = "sock_common ";
5809 		break;
5810 	case PTR_TO_TCP_SOCK:
5811 		pointer_desc = "tcp_sock ";
5812 		break;
5813 	case PTR_TO_XDP_SOCK:
5814 		pointer_desc = "xdp_sock ";
5815 		break;
5816 	default:
5817 		break;
5818 	}
5819 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5820 					   strict);
5821 }
5822 
5823 /* starting from main bpf function walk all instructions of the function
5824  * and recursively walk all callees that given function can call.
5825  * Ignore jump and exit insns.
5826  * Since recursion is prevented by check_cfg() this algorithm
5827  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5828  */
5829 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5830 {
5831 	struct bpf_subprog_info *subprog = env->subprog_info;
5832 	struct bpf_insn *insn = env->prog->insnsi;
5833 	int depth = 0, frame = 0, i, subprog_end;
5834 	bool tail_call_reachable = false;
5835 	int ret_insn[MAX_CALL_FRAMES];
5836 	int ret_prog[MAX_CALL_FRAMES];
5837 	int j;
5838 
5839 	i = subprog[idx].start;
5840 process_func:
5841 	/* protect against potential stack overflow that might happen when
5842 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5843 	 * depth for such case down to 256 so that the worst case scenario
5844 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5845 	 * 8k).
5846 	 *
5847 	 * To get the idea what might happen, see an example:
5848 	 * func1 -> sub rsp, 128
5849 	 *  subfunc1 -> sub rsp, 256
5850 	 *  tailcall1 -> add rsp, 256
5851 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5852 	 *   subfunc2 -> sub rsp, 64
5853 	 *   subfunc22 -> sub rsp, 128
5854 	 *   tailcall2 -> add rsp, 128
5855 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5856 	 *
5857 	 * tailcall will unwind the current stack frame but it will not get rid
5858 	 * of caller's stack as shown on the example above.
5859 	 */
5860 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5861 		verbose(env,
5862 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5863 			depth);
5864 		return -EACCES;
5865 	}
5866 	/* round up to 32-bytes, since this is granularity
5867 	 * of interpreter stack size
5868 	 */
5869 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5870 	if (depth > MAX_BPF_STACK) {
5871 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5872 			frame + 1, depth);
5873 		return -EACCES;
5874 	}
5875 continue_func:
5876 	subprog_end = subprog[idx + 1].start;
5877 	for (; i < subprog_end; i++) {
5878 		int next_insn, sidx;
5879 
5880 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5881 			continue;
5882 		/* remember insn and function to return to */
5883 		ret_insn[frame] = i + 1;
5884 		ret_prog[frame] = idx;
5885 
5886 		/* find the callee */
5887 		next_insn = i + insn[i].imm + 1;
5888 		sidx = find_subprog(env, next_insn);
5889 		if (sidx < 0) {
5890 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5891 				  next_insn);
5892 			return -EFAULT;
5893 		}
5894 		if (subprog[sidx].is_async_cb) {
5895 			if (subprog[sidx].has_tail_call) {
5896 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5897 				return -EFAULT;
5898 			}
5899 			/* async callbacks don't increase bpf prog stack size unless called directly */
5900 			if (!bpf_pseudo_call(insn + i))
5901 				continue;
5902 		}
5903 		i = next_insn;
5904 		idx = sidx;
5905 
5906 		if (subprog[idx].has_tail_call)
5907 			tail_call_reachable = true;
5908 
5909 		frame++;
5910 		if (frame >= MAX_CALL_FRAMES) {
5911 			verbose(env, "the call stack of %d frames is too deep !\n",
5912 				frame);
5913 			return -E2BIG;
5914 		}
5915 		goto process_func;
5916 	}
5917 	/* if tail call got detected across bpf2bpf calls then mark each of the
5918 	 * currently present subprog frames as tail call reachable subprogs;
5919 	 * this info will be utilized by JIT so that we will be preserving the
5920 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5921 	 */
5922 	if (tail_call_reachable)
5923 		for (j = 0; j < frame; j++)
5924 			subprog[ret_prog[j]].tail_call_reachable = true;
5925 	if (subprog[0].tail_call_reachable)
5926 		env->prog->aux->tail_call_reachable = true;
5927 
5928 	/* end of for() loop means the last insn of the 'subprog'
5929 	 * was reached. Doesn't matter whether it was JA or EXIT
5930 	 */
5931 	if (frame == 0)
5932 		return 0;
5933 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5934 	frame--;
5935 	i = ret_insn[frame];
5936 	idx = ret_prog[frame];
5937 	goto continue_func;
5938 }
5939 
5940 static int check_max_stack_depth(struct bpf_verifier_env *env)
5941 {
5942 	struct bpf_subprog_info *si = env->subprog_info;
5943 	int ret;
5944 
5945 	for (int i = 0; i < env->subprog_cnt; i++) {
5946 		if (!i || si[i].is_async_cb) {
5947 			ret = check_max_stack_depth_subprog(env, i);
5948 			if (ret < 0)
5949 				return ret;
5950 		}
5951 		continue;
5952 	}
5953 	return 0;
5954 }
5955 
5956 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5957 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5958 				  const struct bpf_insn *insn, int idx)
5959 {
5960 	int start = idx + insn->imm + 1, subprog;
5961 
5962 	subprog = find_subprog(env, start);
5963 	if (subprog < 0) {
5964 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5965 			  start);
5966 		return -EFAULT;
5967 	}
5968 	return env->subprog_info[subprog].stack_depth;
5969 }
5970 #endif
5971 
5972 static int __check_buffer_access(struct bpf_verifier_env *env,
5973 				 const char *buf_info,
5974 				 const struct bpf_reg_state *reg,
5975 				 int regno, int off, int size)
5976 {
5977 	if (off < 0) {
5978 		verbose(env,
5979 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5980 			regno, buf_info, off, size);
5981 		return -EACCES;
5982 	}
5983 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5984 		char tn_buf[48];
5985 
5986 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5987 		verbose(env,
5988 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5989 			regno, off, tn_buf);
5990 		return -EACCES;
5991 	}
5992 
5993 	return 0;
5994 }
5995 
5996 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5997 				  const struct bpf_reg_state *reg,
5998 				  int regno, int off, int size)
5999 {
6000 	int err;
6001 
6002 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6003 	if (err)
6004 		return err;
6005 
6006 	if (off + size > env->prog->aux->max_tp_access)
6007 		env->prog->aux->max_tp_access = off + size;
6008 
6009 	return 0;
6010 }
6011 
6012 static int check_buffer_access(struct bpf_verifier_env *env,
6013 			       const struct bpf_reg_state *reg,
6014 			       int regno, int off, int size,
6015 			       bool zero_size_allowed,
6016 			       u32 *max_access)
6017 {
6018 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6019 	int err;
6020 
6021 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6022 	if (err)
6023 		return err;
6024 
6025 	if (off + size > *max_access)
6026 		*max_access = off + size;
6027 
6028 	return 0;
6029 }
6030 
6031 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6032 static void zext_32_to_64(struct bpf_reg_state *reg)
6033 {
6034 	reg->var_off = tnum_subreg(reg->var_off);
6035 	__reg_assign_32_into_64(reg);
6036 }
6037 
6038 /* truncate register to smaller size (in bytes)
6039  * must be called with size < BPF_REG_SIZE
6040  */
6041 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6042 {
6043 	u64 mask;
6044 
6045 	/* clear high bits in bit representation */
6046 	reg->var_off = tnum_cast(reg->var_off, size);
6047 
6048 	/* fix arithmetic bounds */
6049 	mask = ((u64)1 << (size * 8)) - 1;
6050 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6051 		reg->umin_value &= mask;
6052 		reg->umax_value &= mask;
6053 	} else {
6054 		reg->umin_value = 0;
6055 		reg->umax_value = mask;
6056 	}
6057 	reg->smin_value = reg->umin_value;
6058 	reg->smax_value = reg->umax_value;
6059 
6060 	/* If size is smaller than 32bit register the 32bit register
6061 	 * values are also truncated so we push 64-bit bounds into
6062 	 * 32-bit bounds. Above were truncated < 32-bits already.
6063 	 */
6064 	if (size >= 4)
6065 		return;
6066 	__reg_combine_64_into_32(reg);
6067 }
6068 
6069 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6070 {
6071 	if (size == 1) {
6072 		reg->smin_value = reg->s32_min_value = S8_MIN;
6073 		reg->smax_value = reg->s32_max_value = S8_MAX;
6074 	} else if (size == 2) {
6075 		reg->smin_value = reg->s32_min_value = S16_MIN;
6076 		reg->smax_value = reg->s32_max_value = S16_MAX;
6077 	} else {
6078 		/* size == 4 */
6079 		reg->smin_value = reg->s32_min_value = S32_MIN;
6080 		reg->smax_value = reg->s32_max_value = S32_MAX;
6081 	}
6082 	reg->umin_value = reg->u32_min_value = 0;
6083 	reg->umax_value = U64_MAX;
6084 	reg->u32_max_value = U32_MAX;
6085 	reg->var_off = tnum_unknown;
6086 }
6087 
6088 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6089 {
6090 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6091 	u64 top_smax_value, top_smin_value;
6092 	u64 num_bits = size * 8;
6093 
6094 	if (tnum_is_const(reg->var_off)) {
6095 		u64_cval = reg->var_off.value;
6096 		if (size == 1)
6097 			reg->var_off = tnum_const((s8)u64_cval);
6098 		else if (size == 2)
6099 			reg->var_off = tnum_const((s16)u64_cval);
6100 		else
6101 			/* size == 4 */
6102 			reg->var_off = tnum_const((s32)u64_cval);
6103 
6104 		u64_cval = reg->var_off.value;
6105 		reg->smax_value = reg->smin_value = u64_cval;
6106 		reg->umax_value = reg->umin_value = u64_cval;
6107 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6108 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6109 		return;
6110 	}
6111 
6112 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6113 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6114 
6115 	if (top_smax_value != top_smin_value)
6116 		goto out;
6117 
6118 	/* find the s64_min and s64_min after sign extension */
6119 	if (size == 1) {
6120 		init_s64_max = (s8)reg->smax_value;
6121 		init_s64_min = (s8)reg->smin_value;
6122 	} else if (size == 2) {
6123 		init_s64_max = (s16)reg->smax_value;
6124 		init_s64_min = (s16)reg->smin_value;
6125 	} else {
6126 		init_s64_max = (s32)reg->smax_value;
6127 		init_s64_min = (s32)reg->smin_value;
6128 	}
6129 
6130 	s64_max = max(init_s64_max, init_s64_min);
6131 	s64_min = min(init_s64_max, init_s64_min);
6132 
6133 	/* both of s64_max/s64_min positive or negative */
6134 	if ((s64_max >= 0) == (s64_min >= 0)) {
6135 		reg->smin_value = reg->s32_min_value = s64_min;
6136 		reg->smax_value = reg->s32_max_value = s64_max;
6137 		reg->umin_value = reg->u32_min_value = s64_min;
6138 		reg->umax_value = reg->u32_max_value = s64_max;
6139 		reg->var_off = tnum_range(s64_min, s64_max);
6140 		return;
6141 	}
6142 
6143 out:
6144 	set_sext64_default_val(reg, size);
6145 }
6146 
6147 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6148 {
6149 	if (size == 1) {
6150 		reg->s32_min_value = S8_MIN;
6151 		reg->s32_max_value = S8_MAX;
6152 	} else {
6153 		/* size == 2 */
6154 		reg->s32_min_value = S16_MIN;
6155 		reg->s32_max_value = S16_MAX;
6156 	}
6157 	reg->u32_min_value = 0;
6158 	reg->u32_max_value = U32_MAX;
6159 }
6160 
6161 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6162 {
6163 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6164 	u32 top_smax_value, top_smin_value;
6165 	u32 num_bits = size * 8;
6166 
6167 	if (tnum_is_const(reg->var_off)) {
6168 		u32_val = reg->var_off.value;
6169 		if (size == 1)
6170 			reg->var_off = tnum_const((s8)u32_val);
6171 		else
6172 			reg->var_off = tnum_const((s16)u32_val);
6173 
6174 		u32_val = reg->var_off.value;
6175 		reg->s32_min_value = reg->s32_max_value = u32_val;
6176 		reg->u32_min_value = reg->u32_max_value = u32_val;
6177 		return;
6178 	}
6179 
6180 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6181 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6182 
6183 	if (top_smax_value != top_smin_value)
6184 		goto out;
6185 
6186 	/* find the s32_min and s32_min after sign extension */
6187 	if (size == 1) {
6188 		init_s32_max = (s8)reg->s32_max_value;
6189 		init_s32_min = (s8)reg->s32_min_value;
6190 	} else {
6191 		/* size == 2 */
6192 		init_s32_max = (s16)reg->s32_max_value;
6193 		init_s32_min = (s16)reg->s32_min_value;
6194 	}
6195 	s32_max = max(init_s32_max, init_s32_min);
6196 	s32_min = min(init_s32_max, init_s32_min);
6197 
6198 	if ((s32_min >= 0) == (s32_max >= 0)) {
6199 		reg->s32_min_value = s32_min;
6200 		reg->s32_max_value = s32_max;
6201 		reg->u32_min_value = (u32)s32_min;
6202 		reg->u32_max_value = (u32)s32_max;
6203 		return;
6204 	}
6205 
6206 out:
6207 	set_sext32_default_val(reg, size);
6208 }
6209 
6210 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6211 {
6212 	/* A map is considered read-only if the following condition are true:
6213 	 *
6214 	 * 1) BPF program side cannot change any of the map content. The
6215 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6216 	 *    and was set at map creation time.
6217 	 * 2) The map value(s) have been initialized from user space by a
6218 	 *    loader and then "frozen", such that no new map update/delete
6219 	 *    operations from syscall side are possible for the rest of
6220 	 *    the map's lifetime from that point onwards.
6221 	 * 3) Any parallel/pending map update/delete operations from syscall
6222 	 *    side have been completed. Only after that point, it's safe to
6223 	 *    assume that map value(s) are immutable.
6224 	 */
6225 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6226 	       READ_ONCE(map->frozen) &&
6227 	       !bpf_map_write_active(map);
6228 }
6229 
6230 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6231 			       bool is_ldsx)
6232 {
6233 	void *ptr;
6234 	u64 addr;
6235 	int err;
6236 
6237 	err = map->ops->map_direct_value_addr(map, &addr, off);
6238 	if (err)
6239 		return err;
6240 	ptr = (void *)(long)addr + off;
6241 
6242 	switch (size) {
6243 	case sizeof(u8):
6244 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6245 		break;
6246 	case sizeof(u16):
6247 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6248 		break;
6249 	case sizeof(u32):
6250 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6251 		break;
6252 	case sizeof(u64):
6253 		*val = *(u64 *)ptr;
6254 		break;
6255 	default:
6256 		return -EINVAL;
6257 	}
6258 	return 0;
6259 }
6260 
6261 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6262 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6263 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6264 
6265 /*
6266  * Allow list few fields as RCU trusted or full trusted.
6267  * This logic doesn't allow mix tagging and will be removed once GCC supports
6268  * btf_type_tag.
6269  */
6270 
6271 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6272 BTF_TYPE_SAFE_RCU(struct task_struct) {
6273 	const cpumask_t *cpus_ptr;
6274 	struct css_set __rcu *cgroups;
6275 	struct task_struct __rcu *real_parent;
6276 	struct task_struct *group_leader;
6277 };
6278 
6279 BTF_TYPE_SAFE_RCU(struct cgroup) {
6280 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6281 	struct kernfs_node *kn;
6282 };
6283 
6284 BTF_TYPE_SAFE_RCU(struct css_set) {
6285 	struct cgroup *dfl_cgrp;
6286 };
6287 
6288 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6289 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6290 	struct file __rcu *exe_file;
6291 };
6292 
6293 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6294  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6295  */
6296 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6297 	struct sock *sk;
6298 };
6299 
6300 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6301 	struct sock *sk;
6302 };
6303 
6304 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6305 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6306 	struct seq_file *seq;
6307 };
6308 
6309 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6310 	struct bpf_iter_meta *meta;
6311 	struct task_struct *task;
6312 };
6313 
6314 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6315 	struct file *file;
6316 };
6317 
6318 BTF_TYPE_SAFE_TRUSTED(struct file) {
6319 	struct inode *f_inode;
6320 };
6321 
6322 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6323 	/* no negative dentry-s in places where bpf can see it */
6324 	struct inode *d_inode;
6325 };
6326 
6327 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6328 	struct sock *sk;
6329 };
6330 
6331 static bool type_is_rcu(struct bpf_verifier_env *env,
6332 			struct bpf_reg_state *reg,
6333 			const char *field_name, u32 btf_id)
6334 {
6335 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6336 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6337 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6338 
6339 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6340 }
6341 
6342 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6343 				struct bpf_reg_state *reg,
6344 				const char *field_name, u32 btf_id)
6345 {
6346 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6347 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6348 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6349 
6350 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6351 }
6352 
6353 static bool type_is_trusted(struct bpf_verifier_env *env,
6354 			    struct bpf_reg_state *reg,
6355 			    const char *field_name, u32 btf_id)
6356 {
6357 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6358 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6359 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6360 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6361 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6362 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6363 
6364 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6365 }
6366 
6367 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6368 				   struct bpf_reg_state *regs,
6369 				   int regno, int off, int size,
6370 				   enum bpf_access_type atype,
6371 				   int value_regno)
6372 {
6373 	struct bpf_reg_state *reg = regs + regno;
6374 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6375 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6376 	const char *field_name = NULL;
6377 	enum bpf_type_flag flag = 0;
6378 	u32 btf_id = 0;
6379 	int ret;
6380 
6381 	if (!env->allow_ptr_leaks) {
6382 		verbose(env,
6383 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6384 			tname);
6385 		return -EPERM;
6386 	}
6387 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6388 		verbose(env,
6389 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6390 			tname);
6391 		return -EINVAL;
6392 	}
6393 	if (off < 0) {
6394 		verbose(env,
6395 			"R%d is ptr_%s invalid negative access: off=%d\n",
6396 			regno, tname, off);
6397 		return -EACCES;
6398 	}
6399 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6400 		char tn_buf[48];
6401 
6402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6403 		verbose(env,
6404 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6405 			regno, tname, off, tn_buf);
6406 		return -EACCES;
6407 	}
6408 
6409 	if (reg->type & MEM_USER) {
6410 		verbose(env,
6411 			"R%d is ptr_%s access user memory: off=%d\n",
6412 			regno, tname, off);
6413 		return -EACCES;
6414 	}
6415 
6416 	if (reg->type & MEM_PERCPU) {
6417 		verbose(env,
6418 			"R%d is ptr_%s access percpu memory: off=%d\n",
6419 			regno, tname, off);
6420 		return -EACCES;
6421 	}
6422 
6423 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6424 		if (!btf_is_kernel(reg->btf)) {
6425 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6426 			return -EFAULT;
6427 		}
6428 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6429 	} else {
6430 		/* Writes are permitted with default btf_struct_access for
6431 		 * program allocated objects (which always have ref_obj_id > 0),
6432 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6433 		 */
6434 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6435 			verbose(env, "only read is supported\n");
6436 			return -EACCES;
6437 		}
6438 
6439 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6440 		    !reg->ref_obj_id) {
6441 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6442 			return -EFAULT;
6443 		}
6444 
6445 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6446 	}
6447 
6448 	if (ret < 0)
6449 		return ret;
6450 
6451 	if (ret != PTR_TO_BTF_ID) {
6452 		/* just mark; */
6453 
6454 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6455 		/* If this is an untrusted pointer, all pointers formed by walking it
6456 		 * also inherit the untrusted flag.
6457 		 */
6458 		flag = PTR_UNTRUSTED;
6459 
6460 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6461 		/* By default any pointer obtained from walking a trusted pointer is no
6462 		 * longer trusted, unless the field being accessed has explicitly been
6463 		 * marked as inheriting its parent's state of trust (either full or RCU).
6464 		 * For example:
6465 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6466 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6467 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6468 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6469 		 *
6470 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6471 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6472 		 */
6473 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6474 			flag |= PTR_TRUSTED;
6475 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6476 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6477 				/* ignore __rcu tag and mark it MEM_RCU */
6478 				flag |= MEM_RCU;
6479 			} else if (flag & MEM_RCU ||
6480 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6481 				/* __rcu tagged pointers can be NULL */
6482 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6483 
6484 				/* We always trust them */
6485 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6486 				    flag & PTR_UNTRUSTED)
6487 					flag &= ~PTR_UNTRUSTED;
6488 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6489 				/* keep as-is */
6490 			} else {
6491 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6492 				clear_trusted_flags(&flag);
6493 			}
6494 		} else {
6495 			/*
6496 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6497 			 * aggressively mark as untrusted otherwise such
6498 			 * pointers will be plain PTR_TO_BTF_ID without flags
6499 			 * and will be allowed to be passed into helpers for
6500 			 * compat reasons.
6501 			 */
6502 			flag = PTR_UNTRUSTED;
6503 		}
6504 	} else {
6505 		/* Old compat. Deprecated */
6506 		clear_trusted_flags(&flag);
6507 	}
6508 
6509 	if (atype == BPF_READ && value_regno >= 0)
6510 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6511 
6512 	return 0;
6513 }
6514 
6515 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6516 				   struct bpf_reg_state *regs,
6517 				   int regno, int off, int size,
6518 				   enum bpf_access_type atype,
6519 				   int value_regno)
6520 {
6521 	struct bpf_reg_state *reg = regs + regno;
6522 	struct bpf_map *map = reg->map_ptr;
6523 	struct bpf_reg_state map_reg;
6524 	enum bpf_type_flag flag = 0;
6525 	const struct btf_type *t;
6526 	const char *tname;
6527 	u32 btf_id;
6528 	int ret;
6529 
6530 	if (!btf_vmlinux) {
6531 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6532 		return -ENOTSUPP;
6533 	}
6534 
6535 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6536 		verbose(env, "map_ptr access not supported for map type %d\n",
6537 			map->map_type);
6538 		return -ENOTSUPP;
6539 	}
6540 
6541 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6542 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6543 
6544 	if (!env->allow_ptr_leaks) {
6545 		verbose(env,
6546 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6547 			tname);
6548 		return -EPERM;
6549 	}
6550 
6551 	if (off < 0) {
6552 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6553 			regno, tname, off);
6554 		return -EACCES;
6555 	}
6556 
6557 	if (atype != BPF_READ) {
6558 		verbose(env, "only read from %s is supported\n", tname);
6559 		return -EACCES;
6560 	}
6561 
6562 	/* Simulate access to a PTR_TO_BTF_ID */
6563 	memset(&map_reg, 0, sizeof(map_reg));
6564 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6565 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6566 	if (ret < 0)
6567 		return ret;
6568 
6569 	if (value_regno >= 0)
6570 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6571 
6572 	return 0;
6573 }
6574 
6575 /* Check that the stack access at the given offset is within bounds. The
6576  * maximum valid offset is -1.
6577  *
6578  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6579  * -state->allocated_stack for reads.
6580  */
6581 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6582                                           s64 off,
6583                                           struct bpf_func_state *state,
6584                                           enum bpf_access_type t)
6585 {
6586 	int min_valid_off;
6587 
6588 	if (t == BPF_WRITE || env->allow_uninit_stack)
6589 		min_valid_off = -MAX_BPF_STACK;
6590 	else
6591 		min_valid_off = -state->allocated_stack;
6592 
6593 	if (off < min_valid_off || off > -1)
6594 		return -EACCES;
6595 	return 0;
6596 }
6597 
6598 /* Check that the stack access at 'regno + off' falls within the maximum stack
6599  * bounds.
6600  *
6601  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6602  */
6603 static int check_stack_access_within_bounds(
6604 		struct bpf_verifier_env *env,
6605 		int regno, int off, int access_size,
6606 		enum bpf_access_src src, enum bpf_access_type type)
6607 {
6608 	struct bpf_reg_state *regs = cur_regs(env);
6609 	struct bpf_reg_state *reg = regs + regno;
6610 	struct bpf_func_state *state = func(env, reg);
6611 	s64 min_off, max_off;
6612 	int err;
6613 	char *err_extra;
6614 
6615 	if (src == ACCESS_HELPER)
6616 		/* We don't know if helpers are reading or writing (or both). */
6617 		err_extra = " indirect access to";
6618 	else if (type == BPF_READ)
6619 		err_extra = " read from";
6620 	else
6621 		err_extra = " write to";
6622 
6623 	if (tnum_is_const(reg->var_off)) {
6624 		min_off = (s64)reg->var_off.value + off;
6625 		max_off = min_off + access_size;
6626 	} else {
6627 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6628 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6629 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6630 				err_extra, regno);
6631 			return -EACCES;
6632 		}
6633 		min_off = reg->smin_value + off;
6634 		max_off = reg->smax_value + off + access_size;
6635 	}
6636 
6637 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6638 	if (!err && max_off > 0)
6639 		err = -EINVAL; /* out of stack access into non-negative offsets */
6640 
6641 	if (err) {
6642 		if (tnum_is_const(reg->var_off)) {
6643 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6644 				err_extra, regno, off, access_size);
6645 		} else {
6646 			char tn_buf[48];
6647 
6648 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6649 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6650 				err_extra, regno, tn_buf, access_size);
6651 		}
6652 		return err;
6653 	}
6654 
6655 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6656 }
6657 
6658 /* check whether memory at (regno + off) is accessible for t = (read | write)
6659  * if t==write, value_regno is a register which value is stored into memory
6660  * if t==read, value_regno is a register which will receive the value from memory
6661  * if t==write && value_regno==-1, some unknown value is stored into memory
6662  * if t==read && value_regno==-1, don't care what we read from memory
6663  */
6664 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6665 			    int off, int bpf_size, enum bpf_access_type t,
6666 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6667 {
6668 	struct bpf_reg_state *regs = cur_regs(env);
6669 	struct bpf_reg_state *reg = regs + regno;
6670 	int size, err = 0;
6671 
6672 	size = bpf_size_to_bytes(bpf_size);
6673 	if (size < 0)
6674 		return size;
6675 
6676 	/* alignment checks will add in reg->off themselves */
6677 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6678 	if (err)
6679 		return err;
6680 
6681 	/* for access checks, reg->off is just part of off */
6682 	off += reg->off;
6683 
6684 	if (reg->type == PTR_TO_MAP_KEY) {
6685 		if (t == BPF_WRITE) {
6686 			verbose(env, "write to change key R%d not allowed\n", regno);
6687 			return -EACCES;
6688 		}
6689 
6690 		err = check_mem_region_access(env, regno, off, size,
6691 					      reg->map_ptr->key_size, false);
6692 		if (err)
6693 			return err;
6694 		if (value_regno >= 0)
6695 			mark_reg_unknown(env, regs, value_regno);
6696 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6697 		struct btf_field *kptr_field = NULL;
6698 
6699 		if (t == BPF_WRITE && value_regno >= 0 &&
6700 		    is_pointer_value(env, value_regno)) {
6701 			verbose(env, "R%d leaks addr into map\n", value_regno);
6702 			return -EACCES;
6703 		}
6704 		err = check_map_access_type(env, regno, off, size, t);
6705 		if (err)
6706 			return err;
6707 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6708 		if (err)
6709 			return err;
6710 		if (tnum_is_const(reg->var_off))
6711 			kptr_field = btf_record_find(reg->map_ptr->record,
6712 						     off + reg->var_off.value, BPF_KPTR);
6713 		if (kptr_field) {
6714 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6715 		} else if (t == BPF_READ && value_regno >= 0) {
6716 			struct bpf_map *map = reg->map_ptr;
6717 
6718 			/* if map is read-only, track its contents as scalars */
6719 			if (tnum_is_const(reg->var_off) &&
6720 			    bpf_map_is_rdonly(map) &&
6721 			    map->ops->map_direct_value_addr) {
6722 				int map_off = off + reg->var_off.value;
6723 				u64 val = 0;
6724 
6725 				err = bpf_map_direct_read(map, map_off, size,
6726 							  &val, is_ldsx);
6727 				if (err)
6728 					return err;
6729 
6730 				regs[value_regno].type = SCALAR_VALUE;
6731 				__mark_reg_known(&regs[value_regno], val);
6732 			} else {
6733 				mark_reg_unknown(env, regs, value_regno);
6734 			}
6735 		}
6736 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6737 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6738 
6739 		if (type_may_be_null(reg->type)) {
6740 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6741 				reg_type_str(env, reg->type));
6742 			return -EACCES;
6743 		}
6744 
6745 		if (t == BPF_WRITE && rdonly_mem) {
6746 			verbose(env, "R%d cannot write into %s\n",
6747 				regno, reg_type_str(env, reg->type));
6748 			return -EACCES;
6749 		}
6750 
6751 		if (t == BPF_WRITE && value_regno >= 0 &&
6752 		    is_pointer_value(env, value_regno)) {
6753 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6754 			return -EACCES;
6755 		}
6756 
6757 		err = check_mem_region_access(env, regno, off, size,
6758 					      reg->mem_size, false);
6759 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6760 			mark_reg_unknown(env, regs, value_regno);
6761 	} else if (reg->type == PTR_TO_CTX) {
6762 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6763 		struct btf *btf = NULL;
6764 		u32 btf_id = 0;
6765 
6766 		if (t == BPF_WRITE && value_regno >= 0 &&
6767 		    is_pointer_value(env, value_regno)) {
6768 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6769 			return -EACCES;
6770 		}
6771 
6772 		err = check_ptr_off_reg(env, reg, regno);
6773 		if (err < 0)
6774 			return err;
6775 
6776 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6777 				       &btf_id);
6778 		if (err)
6779 			verbose_linfo(env, insn_idx, "; ");
6780 		if (!err && t == BPF_READ && value_regno >= 0) {
6781 			/* ctx access returns either a scalar, or a
6782 			 * PTR_TO_PACKET[_META,_END]. In the latter
6783 			 * case, we know the offset is zero.
6784 			 */
6785 			if (reg_type == SCALAR_VALUE) {
6786 				mark_reg_unknown(env, regs, value_regno);
6787 			} else {
6788 				mark_reg_known_zero(env, regs,
6789 						    value_regno);
6790 				if (type_may_be_null(reg_type))
6791 					regs[value_regno].id = ++env->id_gen;
6792 				/* A load of ctx field could have different
6793 				 * actual load size with the one encoded in the
6794 				 * insn. When the dst is PTR, it is for sure not
6795 				 * a sub-register.
6796 				 */
6797 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6798 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6799 					regs[value_regno].btf = btf;
6800 					regs[value_regno].btf_id = btf_id;
6801 				}
6802 			}
6803 			regs[value_regno].type = reg_type;
6804 		}
6805 
6806 	} else if (reg->type == PTR_TO_STACK) {
6807 		/* Basic bounds checks. */
6808 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6809 		if (err)
6810 			return err;
6811 
6812 		if (t == BPF_READ)
6813 			err = check_stack_read(env, regno, off, size,
6814 					       value_regno);
6815 		else
6816 			err = check_stack_write(env, regno, off, size,
6817 						value_regno, insn_idx);
6818 	} else if (reg_is_pkt_pointer(reg)) {
6819 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6820 			verbose(env, "cannot write into packet\n");
6821 			return -EACCES;
6822 		}
6823 		if (t == BPF_WRITE && value_regno >= 0 &&
6824 		    is_pointer_value(env, value_regno)) {
6825 			verbose(env, "R%d leaks addr into packet\n",
6826 				value_regno);
6827 			return -EACCES;
6828 		}
6829 		err = check_packet_access(env, regno, off, size, false);
6830 		if (!err && t == BPF_READ && value_regno >= 0)
6831 			mark_reg_unknown(env, regs, value_regno);
6832 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6833 		if (t == BPF_WRITE && value_regno >= 0 &&
6834 		    is_pointer_value(env, value_regno)) {
6835 			verbose(env, "R%d leaks addr into flow keys\n",
6836 				value_regno);
6837 			return -EACCES;
6838 		}
6839 
6840 		err = check_flow_keys_access(env, off, size);
6841 		if (!err && t == BPF_READ && value_regno >= 0)
6842 			mark_reg_unknown(env, regs, value_regno);
6843 	} else if (type_is_sk_pointer(reg->type)) {
6844 		if (t == BPF_WRITE) {
6845 			verbose(env, "R%d cannot write into %s\n",
6846 				regno, reg_type_str(env, reg->type));
6847 			return -EACCES;
6848 		}
6849 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6850 		if (!err && value_regno >= 0)
6851 			mark_reg_unknown(env, regs, value_regno);
6852 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6853 		err = check_tp_buffer_access(env, reg, regno, off, size);
6854 		if (!err && t == BPF_READ && value_regno >= 0)
6855 			mark_reg_unknown(env, regs, value_regno);
6856 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6857 		   !type_may_be_null(reg->type)) {
6858 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6859 					      value_regno);
6860 	} else if (reg->type == CONST_PTR_TO_MAP) {
6861 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6862 					      value_regno);
6863 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6864 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6865 		u32 *max_access;
6866 
6867 		if (rdonly_mem) {
6868 			if (t == BPF_WRITE) {
6869 				verbose(env, "R%d cannot write into %s\n",
6870 					regno, reg_type_str(env, reg->type));
6871 				return -EACCES;
6872 			}
6873 			max_access = &env->prog->aux->max_rdonly_access;
6874 		} else {
6875 			max_access = &env->prog->aux->max_rdwr_access;
6876 		}
6877 
6878 		err = check_buffer_access(env, reg, regno, off, size, false,
6879 					  max_access);
6880 
6881 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6882 			mark_reg_unknown(env, regs, value_regno);
6883 	} else {
6884 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6885 			reg_type_str(env, reg->type));
6886 		return -EACCES;
6887 	}
6888 
6889 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6890 	    regs[value_regno].type == SCALAR_VALUE) {
6891 		if (!is_ldsx)
6892 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6893 			coerce_reg_to_size(&regs[value_regno], size);
6894 		else
6895 			coerce_reg_to_size_sx(&regs[value_regno], size);
6896 	}
6897 	return err;
6898 }
6899 
6900 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6901 {
6902 	int load_reg;
6903 	int err;
6904 
6905 	switch (insn->imm) {
6906 	case BPF_ADD:
6907 	case BPF_ADD | BPF_FETCH:
6908 	case BPF_AND:
6909 	case BPF_AND | BPF_FETCH:
6910 	case BPF_OR:
6911 	case BPF_OR | BPF_FETCH:
6912 	case BPF_XOR:
6913 	case BPF_XOR | BPF_FETCH:
6914 	case BPF_XCHG:
6915 	case BPF_CMPXCHG:
6916 		break;
6917 	default:
6918 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6919 		return -EINVAL;
6920 	}
6921 
6922 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6923 		verbose(env, "invalid atomic operand size\n");
6924 		return -EINVAL;
6925 	}
6926 
6927 	/* check src1 operand */
6928 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6929 	if (err)
6930 		return err;
6931 
6932 	/* check src2 operand */
6933 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6934 	if (err)
6935 		return err;
6936 
6937 	if (insn->imm == BPF_CMPXCHG) {
6938 		/* Check comparison of R0 with memory location */
6939 		const u32 aux_reg = BPF_REG_0;
6940 
6941 		err = check_reg_arg(env, aux_reg, SRC_OP);
6942 		if (err)
6943 			return err;
6944 
6945 		if (is_pointer_value(env, aux_reg)) {
6946 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6947 			return -EACCES;
6948 		}
6949 	}
6950 
6951 	if (is_pointer_value(env, insn->src_reg)) {
6952 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6953 		return -EACCES;
6954 	}
6955 
6956 	if (is_ctx_reg(env, insn->dst_reg) ||
6957 	    is_pkt_reg(env, insn->dst_reg) ||
6958 	    is_flow_key_reg(env, insn->dst_reg) ||
6959 	    is_sk_reg(env, insn->dst_reg)) {
6960 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6961 			insn->dst_reg,
6962 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6963 		return -EACCES;
6964 	}
6965 
6966 	if (insn->imm & BPF_FETCH) {
6967 		if (insn->imm == BPF_CMPXCHG)
6968 			load_reg = BPF_REG_0;
6969 		else
6970 			load_reg = insn->src_reg;
6971 
6972 		/* check and record load of old value */
6973 		err = check_reg_arg(env, load_reg, DST_OP);
6974 		if (err)
6975 			return err;
6976 	} else {
6977 		/* This instruction accesses a memory location but doesn't
6978 		 * actually load it into a register.
6979 		 */
6980 		load_reg = -1;
6981 	}
6982 
6983 	/* Check whether we can read the memory, with second call for fetch
6984 	 * case to simulate the register fill.
6985 	 */
6986 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6987 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6988 	if (!err && load_reg >= 0)
6989 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6990 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6991 				       true, false);
6992 	if (err)
6993 		return err;
6994 
6995 	/* Check whether we can write into the same memory. */
6996 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6997 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6998 	if (err)
6999 		return err;
7000 
7001 	return 0;
7002 }
7003 
7004 /* When register 'regno' is used to read the stack (either directly or through
7005  * a helper function) make sure that it's within stack boundary and, depending
7006  * on the access type and privileges, that all elements of the stack are
7007  * initialized.
7008  *
7009  * 'off' includes 'regno->off', but not its dynamic part (if any).
7010  *
7011  * All registers that have been spilled on the stack in the slots within the
7012  * read offsets are marked as read.
7013  */
7014 static int check_stack_range_initialized(
7015 		struct bpf_verifier_env *env, int regno, int off,
7016 		int access_size, bool zero_size_allowed,
7017 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7018 {
7019 	struct bpf_reg_state *reg = reg_state(env, regno);
7020 	struct bpf_func_state *state = func(env, reg);
7021 	int err, min_off, max_off, i, j, slot, spi;
7022 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7023 	enum bpf_access_type bounds_check_type;
7024 	/* Some accesses can write anything into the stack, others are
7025 	 * read-only.
7026 	 */
7027 	bool clobber = false;
7028 
7029 	if (access_size == 0 && !zero_size_allowed) {
7030 		verbose(env, "invalid zero-sized read\n");
7031 		return -EACCES;
7032 	}
7033 
7034 	if (type == ACCESS_HELPER) {
7035 		/* The bounds checks for writes are more permissive than for
7036 		 * reads. However, if raw_mode is not set, we'll do extra
7037 		 * checks below.
7038 		 */
7039 		bounds_check_type = BPF_WRITE;
7040 		clobber = true;
7041 	} else {
7042 		bounds_check_type = BPF_READ;
7043 	}
7044 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7045 					       type, bounds_check_type);
7046 	if (err)
7047 		return err;
7048 
7049 
7050 	if (tnum_is_const(reg->var_off)) {
7051 		min_off = max_off = reg->var_off.value + off;
7052 	} else {
7053 		/* Variable offset is prohibited for unprivileged mode for
7054 		 * simplicity since it requires corresponding support in
7055 		 * Spectre masking for stack ALU.
7056 		 * See also retrieve_ptr_limit().
7057 		 */
7058 		if (!env->bypass_spec_v1) {
7059 			char tn_buf[48];
7060 
7061 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7062 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7063 				regno, err_extra, tn_buf);
7064 			return -EACCES;
7065 		}
7066 		/* Only initialized buffer on stack is allowed to be accessed
7067 		 * with variable offset. With uninitialized buffer it's hard to
7068 		 * guarantee that whole memory is marked as initialized on
7069 		 * helper return since specific bounds are unknown what may
7070 		 * cause uninitialized stack leaking.
7071 		 */
7072 		if (meta && meta->raw_mode)
7073 			meta = NULL;
7074 
7075 		min_off = reg->smin_value + off;
7076 		max_off = reg->smax_value + off;
7077 	}
7078 
7079 	if (meta && meta->raw_mode) {
7080 		/* Ensure we won't be overwriting dynptrs when simulating byte
7081 		 * by byte access in check_helper_call using meta.access_size.
7082 		 * This would be a problem if we have a helper in the future
7083 		 * which takes:
7084 		 *
7085 		 *	helper(uninit_mem, len, dynptr)
7086 		 *
7087 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7088 		 * may end up writing to dynptr itself when touching memory from
7089 		 * arg 1. This can be relaxed on a case by case basis for known
7090 		 * safe cases, but reject due to the possibilitiy of aliasing by
7091 		 * default.
7092 		 */
7093 		for (i = min_off; i < max_off + access_size; i++) {
7094 			int stack_off = -i - 1;
7095 
7096 			spi = __get_spi(i);
7097 			/* raw_mode may write past allocated_stack */
7098 			if (state->allocated_stack <= stack_off)
7099 				continue;
7100 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7101 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7102 				return -EACCES;
7103 			}
7104 		}
7105 		meta->access_size = access_size;
7106 		meta->regno = regno;
7107 		return 0;
7108 	}
7109 
7110 	for (i = min_off; i < max_off + access_size; i++) {
7111 		u8 *stype;
7112 
7113 		slot = -i - 1;
7114 		spi = slot / BPF_REG_SIZE;
7115 		if (state->allocated_stack <= slot) {
7116 			verbose(env, "verifier bug: allocated_stack too small");
7117 			return -EFAULT;
7118 		}
7119 
7120 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7121 		if (*stype == STACK_MISC)
7122 			goto mark;
7123 		if ((*stype == STACK_ZERO) ||
7124 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7125 			if (clobber) {
7126 				/* helper can write anything into the stack */
7127 				*stype = STACK_MISC;
7128 			}
7129 			goto mark;
7130 		}
7131 
7132 		if (is_spilled_reg(&state->stack[spi]) &&
7133 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7134 		     env->allow_ptr_leaks)) {
7135 			if (clobber) {
7136 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7137 				for (j = 0; j < BPF_REG_SIZE; j++)
7138 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7139 			}
7140 			goto mark;
7141 		}
7142 
7143 		if (tnum_is_const(reg->var_off)) {
7144 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7145 				err_extra, regno, min_off, i - min_off, access_size);
7146 		} else {
7147 			char tn_buf[48];
7148 
7149 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7150 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7151 				err_extra, regno, tn_buf, i - min_off, access_size);
7152 		}
7153 		return -EACCES;
7154 mark:
7155 		/* reading any byte out of 8-byte 'spill_slot' will cause
7156 		 * the whole slot to be marked as 'read'
7157 		 */
7158 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7159 			      state->stack[spi].spilled_ptr.parent,
7160 			      REG_LIVE_READ64);
7161 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7162 		 * be sure that whether stack slot is written to or not. Hence,
7163 		 * we must still conservatively propagate reads upwards even if
7164 		 * helper may write to the entire memory range.
7165 		 */
7166 	}
7167 	return 0;
7168 }
7169 
7170 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7171 				   int access_size, bool zero_size_allowed,
7172 				   struct bpf_call_arg_meta *meta)
7173 {
7174 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7175 	u32 *max_access;
7176 
7177 	switch (base_type(reg->type)) {
7178 	case PTR_TO_PACKET:
7179 	case PTR_TO_PACKET_META:
7180 		return check_packet_access(env, regno, reg->off, access_size,
7181 					   zero_size_allowed);
7182 	case PTR_TO_MAP_KEY:
7183 		if (meta && meta->raw_mode) {
7184 			verbose(env, "R%d cannot write into %s\n", regno,
7185 				reg_type_str(env, reg->type));
7186 			return -EACCES;
7187 		}
7188 		return check_mem_region_access(env, regno, reg->off, access_size,
7189 					       reg->map_ptr->key_size, false);
7190 	case PTR_TO_MAP_VALUE:
7191 		if (check_map_access_type(env, regno, reg->off, access_size,
7192 					  meta && meta->raw_mode ? BPF_WRITE :
7193 					  BPF_READ))
7194 			return -EACCES;
7195 		return check_map_access(env, regno, reg->off, access_size,
7196 					zero_size_allowed, ACCESS_HELPER);
7197 	case PTR_TO_MEM:
7198 		if (type_is_rdonly_mem(reg->type)) {
7199 			if (meta && meta->raw_mode) {
7200 				verbose(env, "R%d cannot write into %s\n", regno,
7201 					reg_type_str(env, reg->type));
7202 				return -EACCES;
7203 			}
7204 		}
7205 		return check_mem_region_access(env, regno, reg->off,
7206 					       access_size, reg->mem_size,
7207 					       zero_size_allowed);
7208 	case PTR_TO_BUF:
7209 		if (type_is_rdonly_mem(reg->type)) {
7210 			if (meta && meta->raw_mode) {
7211 				verbose(env, "R%d cannot write into %s\n", regno,
7212 					reg_type_str(env, reg->type));
7213 				return -EACCES;
7214 			}
7215 
7216 			max_access = &env->prog->aux->max_rdonly_access;
7217 		} else {
7218 			max_access = &env->prog->aux->max_rdwr_access;
7219 		}
7220 		return check_buffer_access(env, reg, regno, reg->off,
7221 					   access_size, zero_size_allowed,
7222 					   max_access);
7223 	case PTR_TO_STACK:
7224 		return check_stack_range_initialized(
7225 				env,
7226 				regno, reg->off, access_size,
7227 				zero_size_allowed, ACCESS_HELPER, meta);
7228 	case PTR_TO_BTF_ID:
7229 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7230 					       access_size, BPF_READ, -1);
7231 	case PTR_TO_CTX:
7232 		/* in case the function doesn't know how to access the context,
7233 		 * (because we are in a program of type SYSCALL for example), we
7234 		 * can not statically check its size.
7235 		 * Dynamically check it now.
7236 		 */
7237 		if (!env->ops->convert_ctx_access) {
7238 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7239 			int offset = access_size - 1;
7240 
7241 			/* Allow zero-byte read from PTR_TO_CTX */
7242 			if (access_size == 0)
7243 				return zero_size_allowed ? 0 : -EACCES;
7244 
7245 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7246 						atype, -1, false, false);
7247 		}
7248 
7249 		fallthrough;
7250 	default: /* scalar_value or invalid ptr */
7251 		/* Allow zero-byte read from NULL, regardless of pointer type */
7252 		if (zero_size_allowed && access_size == 0 &&
7253 		    register_is_null(reg))
7254 			return 0;
7255 
7256 		verbose(env, "R%d type=%s ", regno,
7257 			reg_type_str(env, reg->type));
7258 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7259 		return -EACCES;
7260 	}
7261 }
7262 
7263 static int check_mem_size_reg(struct bpf_verifier_env *env,
7264 			      struct bpf_reg_state *reg, u32 regno,
7265 			      bool zero_size_allowed,
7266 			      struct bpf_call_arg_meta *meta)
7267 {
7268 	int err;
7269 
7270 	/* This is used to refine r0 return value bounds for helpers
7271 	 * that enforce this value as an upper bound on return values.
7272 	 * See do_refine_retval_range() for helpers that can refine
7273 	 * the return value. C type of helper is u32 so we pull register
7274 	 * bound from umax_value however, if negative verifier errors
7275 	 * out. Only upper bounds can be learned because retval is an
7276 	 * int type and negative retvals are allowed.
7277 	 */
7278 	meta->msize_max_value = reg->umax_value;
7279 
7280 	/* The register is SCALAR_VALUE; the access check
7281 	 * happens using its boundaries.
7282 	 */
7283 	if (!tnum_is_const(reg->var_off))
7284 		/* For unprivileged variable accesses, disable raw
7285 		 * mode so that the program is required to
7286 		 * initialize all the memory that the helper could
7287 		 * just partially fill up.
7288 		 */
7289 		meta = NULL;
7290 
7291 	if (reg->smin_value < 0) {
7292 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7293 			regno);
7294 		return -EACCES;
7295 	}
7296 
7297 	if (reg->umin_value == 0) {
7298 		err = check_helper_mem_access(env, regno - 1, 0,
7299 					      zero_size_allowed,
7300 					      meta);
7301 		if (err)
7302 			return err;
7303 	}
7304 
7305 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7306 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7307 			regno);
7308 		return -EACCES;
7309 	}
7310 	err = check_helper_mem_access(env, regno - 1,
7311 				      reg->umax_value,
7312 				      zero_size_allowed, meta);
7313 	if (!err)
7314 		err = mark_chain_precision(env, regno);
7315 	return err;
7316 }
7317 
7318 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7319 		   u32 regno, u32 mem_size)
7320 {
7321 	bool may_be_null = type_may_be_null(reg->type);
7322 	struct bpf_reg_state saved_reg;
7323 	struct bpf_call_arg_meta meta;
7324 	int err;
7325 
7326 	if (register_is_null(reg))
7327 		return 0;
7328 
7329 	memset(&meta, 0, sizeof(meta));
7330 	/* Assuming that the register contains a value check if the memory
7331 	 * access is safe. Temporarily save and restore the register's state as
7332 	 * the conversion shouldn't be visible to a caller.
7333 	 */
7334 	if (may_be_null) {
7335 		saved_reg = *reg;
7336 		mark_ptr_not_null_reg(reg);
7337 	}
7338 
7339 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7340 	/* Check access for BPF_WRITE */
7341 	meta.raw_mode = true;
7342 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7343 
7344 	if (may_be_null)
7345 		*reg = saved_reg;
7346 
7347 	return err;
7348 }
7349 
7350 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7351 				    u32 regno)
7352 {
7353 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7354 	bool may_be_null = type_may_be_null(mem_reg->type);
7355 	struct bpf_reg_state saved_reg;
7356 	struct bpf_call_arg_meta meta;
7357 	int err;
7358 
7359 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7360 
7361 	memset(&meta, 0, sizeof(meta));
7362 
7363 	if (may_be_null) {
7364 		saved_reg = *mem_reg;
7365 		mark_ptr_not_null_reg(mem_reg);
7366 	}
7367 
7368 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7369 	/* Check access for BPF_WRITE */
7370 	meta.raw_mode = true;
7371 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7372 
7373 	if (may_be_null)
7374 		*mem_reg = saved_reg;
7375 	return err;
7376 }
7377 
7378 /* Implementation details:
7379  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7380  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7381  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7382  * Two separate bpf_obj_new will also have different reg->id.
7383  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7384  * clears reg->id after value_or_null->value transition, since the verifier only
7385  * cares about the range of access to valid map value pointer and doesn't care
7386  * about actual address of the map element.
7387  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7388  * reg->id > 0 after value_or_null->value transition. By doing so
7389  * two bpf_map_lookups will be considered two different pointers that
7390  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7391  * returned from bpf_obj_new.
7392  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7393  * dead-locks.
7394  * Since only one bpf_spin_lock is allowed the checks are simpler than
7395  * reg_is_refcounted() logic. The verifier needs to remember only
7396  * one spin_lock instead of array of acquired_refs.
7397  * cur_state->active_lock remembers which map value element or allocated
7398  * object got locked and clears it after bpf_spin_unlock.
7399  */
7400 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7401 			     bool is_lock)
7402 {
7403 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7404 	struct bpf_verifier_state *cur = env->cur_state;
7405 	bool is_const = tnum_is_const(reg->var_off);
7406 	u64 val = reg->var_off.value;
7407 	struct bpf_map *map = NULL;
7408 	struct btf *btf = NULL;
7409 	struct btf_record *rec;
7410 
7411 	if (!is_const) {
7412 		verbose(env,
7413 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7414 			regno);
7415 		return -EINVAL;
7416 	}
7417 	if (reg->type == PTR_TO_MAP_VALUE) {
7418 		map = reg->map_ptr;
7419 		if (!map->btf) {
7420 			verbose(env,
7421 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7422 				map->name);
7423 			return -EINVAL;
7424 		}
7425 	} else {
7426 		btf = reg->btf;
7427 	}
7428 
7429 	rec = reg_btf_record(reg);
7430 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7431 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7432 			map ? map->name : "kptr");
7433 		return -EINVAL;
7434 	}
7435 	if (rec->spin_lock_off != val + reg->off) {
7436 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7437 			val + reg->off, rec->spin_lock_off);
7438 		return -EINVAL;
7439 	}
7440 	if (is_lock) {
7441 		if (cur->active_lock.ptr) {
7442 			verbose(env,
7443 				"Locking two bpf_spin_locks are not allowed\n");
7444 			return -EINVAL;
7445 		}
7446 		if (map)
7447 			cur->active_lock.ptr = map;
7448 		else
7449 			cur->active_lock.ptr = btf;
7450 		cur->active_lock.id = reg->id;
7451 	} else {
7452 		void *ptr;
7453 
7454 		if (map)
7455 			ptr = map;
7456 		else
7457 			ptr = btf;
7458 
7459 		if (!cur->active_lock.ptr) {
7460 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7461 			return -EINVAL;
7462 		}
7463 		if (cur->active_lock.ptr != ptr ||
7464 		    cur->active_lock.id != reg->id) {
7465 			verbose(env, "bpf_spin_unlock of different lock\n");
7466 			return -EINVAL;
7467 		}
7468 
7469 		invalidate_non_owning_refs(env);
7470 
7471 		cur->active_lock.ptr = NULL;
7472 		cur->active_lock.id = 0;
7473 	}
7474 	return 0;
7475 }
7476 
7477 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7478 			      struct bpf_call_arg_meta *meta)
7479 {
7480 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7481 	bool is_const = tnum_is_const(reg->var_off);
7482 	struct bpf_map *map = reg->map_ptr;
7483 	u64 val = reg->var_off.value;
7484 
7485 	if (!is_const) {
7486 		verbose(env,
7487 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7488 			regno);
7489 		return -EINVAL;
7490 	}
7491 	if (!map->btf) {
7492 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7493 			map->name);
7494 		return -EINVAL;
7495 	}
7496 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7497 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7498 		return -EINVAL;
7499 	}
7500 	if (map->record->timer_off != val + reg->off) {
7501 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7502 			val + reg->off, map->record->timer_off);
7503 		return -EINVAL;
7504 	}
7505 	if (meta->map_ptr) {
7506 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7507 		return -EFAULT;
7508 	}
7509 	meta->map_uid = reg->map_uid;
7510 	meta->map_ptr = map;
7511 	return 0;
7512 }
7513 
7514 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7515 			     struct bpf_call_arg_meta *meta)
7516 {
7517 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7518 	struct bpf_map *map_ptr = reg->map_ptr;
7519 	struct btf_field *kptr_field;
7520 	u32 kptr_off;
7521 
7522 	if (!tnum_is_const(reg->var_off)) {
7523 		verbose(env,
7524 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7525 			regno);
7526 		return -EINVAL;
7527 	}
7528 	if (!map_ptr->btf) {
7529 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7530 			map_ptr->name);
7531 		return -EINVAL;
7532 	}
7533 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7534 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7535 		return -EINVAL;
7536 	}
7537 
7538 	meta->map_ptr = map_ptr;
7539 	kptr_off = reg->off + reg->var_off.value;
7540 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7541 	if (!kptr_field) {
7542 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7543 		return -EACCES;
7544 	}
7545 	if (kptr_field->type != BPF_KPTR_REF) {
7546 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7547 		return -EACCES;
7548 	}
7549 	meta->kptr_field = kptr_field;
7550 	return 0;
7551 }
7552 
7553 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7554  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7555  *
7556  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7557  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7558  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7559  *
7560  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7561  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7562  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7563  * mutate the view of the dynptr and also possibly destroy it. In the latter
7564  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7565  * memory that dynptr points to.
7566  *
7567  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7568  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7569  * readonly dynptr view yet, hence only the first case is tracked and checked.
7570  *
7571  * This is consistent with how C applies the const modifier to a struct object,
7572  * where the pointer itself inside bpf_dynptr becomes const but not what it
7573  * points to.
7574  *
7575  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7576  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7577  */
7578 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7579 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7580 {
7581 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7582 	int err;
7583 
7584 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7585 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7586 	 */
7587 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7588 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7589 		return -EFAULT;
7590 	}
7591 
7592 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7593 	 *		 constructing a mutable bpf_dynptr object.
7594 	 *
7595 	 *		 Currently, this is only possible with PTR_TO_STACK
7596 	 *		 pointing to a region of at least 16 bytes which doesn't
7597 	 *		 contain an existing bpf_dynptr.
7598 	 *
7599 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7600 	 *		 mutated or destroyed. However, the memory it points to
7601 	 *		 may be mutated.
7602 	 *
7603 	 *  None       - Points to a initialized dynptr that can be mutated and
7604 	 *		 destroyed, including mutation of the memory it points
7605 	 *		 to.
7606 	 */
7607 	if (arg_type & MEM_UNINIT) {
7608 		int i;
7609 
7610 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7611 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7612 			return -EINVAL;
7613 		}
7614 
7615 		/* we write BPF_DW bits (8 bytes) at a time */
7616 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7617 			err = check_mem_access(env, insn_idx, regno,
7618 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7619 			if (err)
7620 				return err;
7621 		}
7622 
7623 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7624 	} else /* MEM_RDONLY and None case from above */ {
7625 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7626 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7627 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7628 			return -EINVAL;
7629 		}
7630 
7631 		if (!is_dynptr_reg_valid_init(env, reg)) {
7632 			verbose(env,
7633 				"Expected an initialized dynptr as arg #%d\n",
7634 				regno);
7635 			return -EINVAL;
7636 		}
7637 
7638 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7639 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7640 			verbose(env,
7641 				"Expected a dynptr of type %s as arg #%d\n",
7642 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7643 			return -EINVAL;
7644 		}
7645 
7646 		err = mark_dynptr_read(env, reg);
7647 	}
7648 	return err;
7649 }
7650 
7651 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7652 {
7653 	struct bpf_func_state *state = func(env, reg);
7654 
7655 	return state->stack[spi].spilled_ptr.ref_obj_id;
7656 }
7657 
7658 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7659 {
7660 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7661 }
7662 
7663 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7664 {
7665 	return meta->kfunc_flags & KF_ITER_NEW;
7666 }
7667 
7668 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7669 {
7670 	return meta->kfunc_flags & KF_ITER_NEXT;
7671 }
7672 
7673 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7674 {
7675 	return meta->kfunc_flags & KF_ITER_DESTROY;
7676 }
7677 
7678 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7679 {
7680 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7681 	 * kfunc is iter state pointer
7682 	 */
7683 	return arg == 0 && is_iter_kfunc(meta);
7684 }
7685 
7686 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7687 			    struct bpf_kfunc_call_arg_meta *meta)
7688 {
7689 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7690 	const struct btf_type *t;
7691 	const struct btf_param *arg;
7692 	int spi, err, i, nr_slots;
7693 	u32 btf_id;
7694 
7695 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7696 	arg = &btf_params(meta->func_proto)[0];
7697 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7698 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7699 	nr_slots = t->size / BPF_REG_SIZE;
7700 
7701 	if (is_iter_new_kfunc(meta)) {
7702 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7703 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7704 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7705 				iter_type_str(meta->btf, btf_id), regno);
7706 			return -EINVAL;
7707 		}
7708 
7709 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7710 			err = check_mem_access(env, insn_idx, regno,
7711 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7712 			if (err)
7713 				return err;
7714 		}
7715 
7716 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7717 		if (err)
7718 			return err;
7719 	} else {
7720 		/* iter_next() or iter_destroy() expect initialized iter state*/
7721 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7722 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7723 				iter_type_str(meta->btf, btf_id), regno);
7724 			return -EINVAL;
7725 		}
7726 
7727 		spi = iter_get_spi(env, reg, nr_slots);
7728 		if (spi < 0)
7729 			return spi;
7730 
7731 		err = mark_iter_read(env, reg, spi, nr_slots);
7732 		if (err)
7733 			return err;
7734 
7735 		/* remember meta->iter info for process_iter_next_call() */
7736 		meta->iter.spi = spi;
7737 		meta->iter.frameno = reg->frameno;
7738 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7739 
7740 		if (is_iter_destroy_kfunc(meta)) {
7741 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7742 			if (err)
7743 				return err;
7744 		}
7745 	}
7746 
7747 	return 0;
7748 }
7749 
7750 /* Look for a previous loop entry at insn_idx: nearest parent state
7751  * stopped at insn_idx with callsites matching those in cur->frame.
7752  */
7753 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7754 						  struct bpf_verifier_state *cur,
7755 						  int insn_idx)
7756 {
7757 	struct bpf_verifier_state_list *sl;
7758 	struct bpf_verifier_state *st;
7759 
7760 	/* Explored states are pushed in stack order, most recent states come first */
7761 	sl = *explored_state(env, insn_idx);
7762 	for (; sl; sl = sl->next) {
7763 		/* If st->branches != 0 state is a part of current DFS verification path,
7764 		 * hence cur & st for a loop.
7765 		 */
7766 		st = &sl->state;
7767 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7768 		    st->dfs_depth < cur->dfs_depth)
7769 			return st;
7770 	}
7771 
7772 	return NULL;
7773 }
7774 
7775 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7776 static bool regs_exact(const struct bpf_reg_state *rold,
7777 		       const struct bpf_reg_state *rcur,
7778 		       struct bpf_idmap *idmap);
7779 
7780 static void maybe_widen_reg(struct bpf_verifier_env *env,
7781 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7782 			    struct bpf_idmap *idmap)
7783 {
7784 	if (rold->type != SCALAR_VALUE)
7785 		return;
7786 	if (rold->type != rcur->type)
7787 		return;
7788 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7789 		return;
7790 	__mark_reg_unknown(env, rcur);
7791 }
7792 
7793 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7794 				   struct bpf_verifier_state *old,
7795 				   struct bpf_verifier_state *cur)
7796 {
7797 	struct bpf_func_state *fold, *fcur;
7798 	int i, fr;
7799 
7800 	reset_idmap_scratch(env);
7801 	for (fr = old->curframe; fr >= 0; fr--) {
7802 		fold = old->frame[fr];
7803 		fcur = cur->frame[fr];
7804 
7805 		for (i = 0; i < MAX_BPF_REG; i++)
7806 			maybe_widen_reg(env,
7807 					&fold->regs[i],
7808 					&fcur->regs[i],
7809 					&env->idmap_scratch);
7810 
7811 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7812 			if (!is_spilled_reg(&fold->stack[i]) ||
7813 			    !is_spilled_reg(&fcur->stack[i]))
7814 				continue;
7815 
7816 			maybe_widen_reg(env,
7817 					&fold->stack[i].spilled_ptr,
7818 					&fcur->stack[i].spilled_ptr,
7819 					&env->idmap_scratch);
7820 		}
7821 	}
7822 	return 0;
7823 }
7824 
7825 /* process_iter_next_call() is called when verifier gets to iterator's next
7826  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7827  * to it as just "iter_next()" in comments below.
7828  *
7829  * BPF verifier relies on a crucial contract for any iter_next()
7830  * implementation: it should *eventually* return NULL, and once that happens
7831  * it should keep returning NULL. That is, once iterator exhausts elements to
7832  * iterate, it should never reset or spuriously return new elements.
7833  *
7834  * With the assumption of such contract, process_iter_next_call() simulates
7835  * a fork in the verifier state to validate loop logic correctness and safety
7836  * without having to simulate infinite amount of iterations.
7837  *
7838  * In current state, we first assume that iter_next() returned NULL and
7839  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7840  * conditions we should not form an infinite loop and should eventually reach
7841  * exit.
7842  *
7843  * Besides that, we also fork current state and enqueue it for later
7844  * verification. In a forked state we keep iterator state as ACTIVE
7845  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7846  * also bump iteration depth to prevent erroneous infinite loop detection
7847  * later on (see iter_active_depths_differ() comment for details). In this
7848  * state we assume that we'll eventually loop back to another iter_next()
7849  * calls (it could be in exactly same location or in some other instruction,
7850  * it doesn't matter, we don't make any unnecessary assumptions about this,
7851  * everything revolves around iterator state in a stack slot, not which
7852  * instruction is calling iter_next()). When that happens, we either will come
7853  * to iter_next() with equivalent state and can conclude that next iteration
7854  * will proceed in exactly the same way as we just verified, so it's safe to
7855  * assume that loop converges. If not, we'll go on another iteration
7856  * simulation with a different input state, until all possible starting states
7857  * are validated or we reach maximum number of instructions limit.
7858  *
7859  * This way, we will either exhaustively discover all possible input states
7860  * that iterator loop can start with and eventually will converge, or we'll
7861  * effectively regress into bounded loop simulation logic and either reach
7862  * maximum number of instructions if loop is not provably convergent, or there
7863  * is some statically known limit on number of iterations (e.g., if there is
7864  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7865  *
7866  * Iteration convergence logic in is_state_visited() relies on exact
7867  * states comparison, which ignores read and precision marks.
7868  * This is necessary because read and precision marks are not finalized
7869  * while in the loop. Exact comparison might preclude convergence for
7870  * simple programs like below:
7871  *
7872  *     i = 0;
7873  *     while(iter_next(&it))
7874  *       i++;
7875  *
7876  * At each iteration step i++ would produce a new distinct state and
7877  * eventually instruction processing limit would be reached.
7878  *
7879  * To avoid such behavior speculatively forget (widen) range for
7880  * imprecise scalar registers, if those registers were not precise at the
7881  * end of the previous iteration and do not match exactly.
7882  *
7883  * This is a conservative heuristic that allows to verify wide range of programs,
7884  * however it precludes verification of programs that conjure an
7885  * imprecise value on the first loop iteration and use it as precise on a second.
7886  * For example, the following safe program would fail to verify:
7887  *
7888  *     struct bpf_num_iter it;
7889  *     int arr[10];
7890  *     int i = 0, a = 0;
7891  *     bpf_iter_num_new(&it, 0, 10);
7892  *     while (bpf_iter_num_next(&it)) {
7893  *       if (a == 0) {
7894  *         a = 1;
7895  *         i = 7; // Because i changed verifier would forget
7896  *                // it's range on second loop entry.
7897  *       } else {
7898  *         arr[i] = 42; // This would fail to verify.
7899  *       }
7900  *     }
7901  *     bpf_iter_num_destroy(&it);
7902  */
7903 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7904 				  struct bpf_kfunc_call_arg_meta *meta)
7905 {
7906 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7907 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7908 	struct bpf_reg_state *cur_iter, *queued_iter;
7909 	int iter_frameno = meta->iter.frameno;
7910 	int iter_spi = meta->iter.spi;
7911 
7912 	BTF_TYPE_EMIT(struct bpf_iter);
7913 
7914 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7915 
7916 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7917 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7918 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7919 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7920 		return -EFAULT;
7921 	}
7922 
7923 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7924 		/* Because iter_next() call is a checkpoint is_state_visitied()
7925 		 * should guarantee parent state with same call sites and insn_idx.
7926 		 */
7927 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7928 		    !same_callsites(cur_st->parent, cur_st)) {
7929 			verbose(env, "bug: bad parent state for iter next call");
7930 			return -EFAULT;
7931 		}
7932 		/* Note cur_st->parent in the call below, it is necessary to skip
7933 		 * checkpoint created for cur_st by is_state_visited()
7934 		 * right at this instruction.
7935 		 */
7936 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7937 		/* branch out active iter state */
7938 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7939 		if (!queued_st)
7940 			return -ENOMEM;
7941 
7942 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7943 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7944 		queued_iter->iter.depth++;
7945 		if (prev_st)
7946 			widen_imprecise_scalars(env, prev_st, queued_st);
7947 
7948 		queued_fr = queued_st->frame[queued_st->curframe];
7949 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7950 	}
7951 
7952 	/* switch to DRAINED state, but keep the depth unchanged */
7953 	/* mark current iter state as drained and assume returned NULL */
7954 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7955 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7956 
7957 	return 0;
7958 }
7959 
7960 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7961 {
7962 	return type == ARG_CONST_SIZE ||
7963 	       type == ARG_CONST_SIZE_OR_ZERO;
7964 }
7965 
7966 static bool arg_type_is_release(enum bpf_arg_type type)
7967 {
7968 	return type & OBJ_RELEASE;
7969 }
7970 
7971 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7972 {
7973 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7974 }
7975 
7976 static int int_ptr_type_to_size(enum bpf_arg_type type)
7977 {
7978 	if (type == ARG_PTR_TO_INT)
7979 		return sizeof(u32);
7980 	else if (type == ARG_PTR_TO_LONG)
7981 		return sizeof(u64);
7982 
7983 	return -EINVAL;
7984 }
7985 
7986 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7987 				 const struct bpf_call_arg_meta *meta,
7988 				 enum bpf_arg_type *arg_type)
7989 {
7990 	if (!meta->map_ptr) {
7991 		/* kernel subsystem misconfigured verifier */
7992 		verbose(env, "invalid map_ptr to access map->type\n");
7993 		return -EACCES;
7994 	}
7995 
7996 	switch (meta->map_ptr->map_type) {
7997 	case BPF_MAP_TYPE_SOCKMAP:
7998 	case BPF_MAP_TYPE_SOCKHASH:
7999 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8000 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8001 		} else {
8002 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8003 			return -EINVAL;
8004 		}
8005 		break;
8006 	case BPF_MAP_TYPE_BLOOM_FILTER:
8007 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8008 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8009 		break;
8010 	default:
8011 		break;
8012 	}
8013 	return 0;
8014 }
8015 
8016 struct bpf_reg_types {
8017 	const enum bpf_reg_type types[10];
8018 	u32 *btf_id;
8019 };
8020 
8021 static const struct bpf_reg_types sock_types = {
8022 	.types = {
8023 		PTR_TO_SOCK_COMMON,
8024 		PTR_TO_SOCKET,
8025 		PTR_TO_TCP_SOCK,
8026 		PTR_TO_XDP_SOCK,
8027 	},
8028 };
8029 
8030 #ifdef CONFIG_NET
8031 static const struct bpf_reg_types btf_id_sock_common_types = {
8032 	.types = {
8033 		PTR_TO_SOCK_COMMON,
8034 		PTR_TO_SOCKET,
8035 		PTR_TO_TCP_SOCK,
8036 		PTR_TO_XDP_SOCK,
8037 		PTR_TO_BTF_ID,
8038 		PTR_TO_BTF_ID | PTR_TRUSTED,
8039 	},
8040 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8041 };
8042 #endif
8043 
8044 static const struct bpf_reg_types mem_types = {
8045 	.types = {
8046 		PTR_TO_STACK,
8047 		PTR_TO_PACKET,
8048 		PTR_TO_PACKET_META,
8049 		PTR_TO_MAP_KEY,
8050 		PTR_TO_MAP_VALUE,
8051 		PTR_TO_MEM,
8052 		PTR_TO_MEM | MEM_RINGBUF,
8053 		PTR_TO_BUF,
8054 		PTR_TO_BTF_ID | PTR_TRUSTED,
8055 	},
8056 };
8057 
8058 static const struct bpf_reg_types int_ptr_types = {
8059 	.types = {
8060 		PTR_TO_STACK,
8061 		PTR_TO_PACKET,
8062 		PTR_TO_PACKET_META,
8063 		PTR_TO_MAP_KEY,
8064 		PTR_TO_MAP_VALUE,
8065 	},
8066 };
8067 
8068 static const struct bpf_reg_types spin_lock_types = {
8069 	.types = {
8070 		PTR_TO_MAP_VALUE,
8071 		PTR_TO_BTF_ID | MEM_ALLOC,
8072 	}
8073 };
8074 
8075 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8076 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8077 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8078 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8079 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8080 static const struct bpf_reg_types btf_ptr_types = {
8081 	.types = {
8082 		PTR_TO_BTF_ID,
8083 		PTR_TO_BTF_ID | PTR_TRUSTED,
8084 		PTR_TO_BTF_ID | MEM_RCU,
8085 	},
8086 };
8087 static const struct bpf_reg_types percpu_btf_ptr_types = {
8088 	.types = {
8089 		PTR_TO_BTF_ID | MEM_PERCPU,
8090 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8091 	}
8092 };
8093 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8094 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8095 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8096 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8097 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8098 static const struct bpf_reg_types dynptr_types = {
8099 	.types = {
8100 		PTR_TO_STACK,
8101 		CONST_PTR_TO_DYNPTR,
8102 	}
8103 };
8104 
8105 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8106 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8107 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8108 	[ARG_CONST_SIZE]		= &scalar_types,
8109 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8110 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8111 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8112 	[ARG_PTR_TO_CTX]		= &context_types,
8113 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8114 #ifdef CONFIG_NET
8115 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8116 #endif
8117 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8118 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8119 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8120 	[ARG_PTR_TO_MEM]		= &mem_types,
8121 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8122 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8123 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8124 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8125 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8126 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8127 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8128 	[ARG_PTR_TO_TIMER]		= &timer_types,
8129 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8130 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8131 };
8132 
8133 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8134 			  enum bpf_arg_type arg_type,
8135 			  const u32 *arg_btf_id,
8136 			  struct bpf_call_arg_meta *meta)
8137 {
8138 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8139 	enum bpf_reg_type expected, type = reg->type;
8140 	const struct bpf_reg_types *compatible;
8141 	int i, j;
8142 
8143 	compatible = compatible_reg_types[base_type(arg_type)];
8144 	if (!compatible) {
8145 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8146 		return -EFAULT;
8147 	}
8148 
8149 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8150 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8151 	 *
8152 	 * Same for MAYBE_NULL:
8153 	 *
8154 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8155 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8156 	 *
8157 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8158 	 *
8159 	 * Therefore we fold these flags depending on the arg_type before comparison.
8160 	 */
8161 	if (arg_type & MEM_RDONLY)
8162 		type &= ~MEM_RDONLY;
8163 	if (arg_type & PTR_MAYBE_NULL)
8164 		type &= ~PTR_MAYBE_NULL;
8165 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8166 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8167 
8168 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8169 		type &= ~MEM_ALLOC;
8170 
8171 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8172 		expected = compatible->types[i];
8173 		if (expected == NOT_INIT)
8174 			break;
8175 
8176 		if (type == expected)
8177 			goto found;
8178 	}
8179 
8180 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8181 	for (j = 0; j + 1 < i; j++)
8182 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8183 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8184 	return -EACCES;
8185 
8186 found:
8187 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8188 		return 0;
8189 
8190 	if (compatible == &mem_types) {
8191 		if (!(arg_type & MEM_RDONLY)) {
8192 			verbose(env,
8193 				"%s() may write into memory pointed by R%d type=%s\n",
8194 				func_id_name(meta->func_id),
8195 				regno, reg_type_str(env, reg->type));
8196 			return -EACCES;
8197 		}
8198 		return 0;
8199 	}
8200 
8201 	switch ((int)reg->type) {
8202 	case PTR_TO_BTF_ID:
8203 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8204 	case PTR_TO_BTF_ID | MEM_RCU:
8205 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8206 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8207 	{
8208 		/* For bpf_sk_release, it needs to match against first member
8209 		 * 'struct sock_common', hence make an exception for it. This
8210 		 * allows bpf_sk_release to work for multiple socket types.
8211 		 */
8212 		bool strict_type_match = arg_type_is_release(arg_type) &&
8213 					 meta->func_id != BPF_FUNC_sk_release;
8214 
8215 		if (type_may_be_null(reg->type) &&
8216 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8217 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8218 			return -EACCES;
8219 		}
8220 
8221 		if (!arg_btf_id) {
8222 			if (!compatible->btf_id) {
8223 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8224 				return -EFAULT;
8225 			}
8226 			arg_btf_id = compatible->btf_id;
8227 		}
8228 
8229 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8230 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8231 				return -EACCES;
8232 		} else {
8233 			if (arg_btf_id == BPF_PTR_POISON) {
8234 				verbose(env, "verifier internal error:");
8235 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8236 					regno);
8237 				return -EACCES;
8238 			}
8239 
8240 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8241 						  btf_vmlinux, *arg_btf_id,
8242 						  strict_type_match)) {
8243 				verbose(env, "R%d is of type %s but %s is expected\n",
8244 					regno, btf_type_name(reg->btf, reg->btf_id),
8245 					btf_type_name(btf_vmlinux, *arg_btf_id));
8246 				return -EACCES;
8247 			}
8248 		}
8249 		break;
8250 	}
8251 	case PTR_TO_BTF_ID | MEM_ALLOC:
8252 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8253 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8254 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8255 			return -EFAULT;
8256 		}
8257 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8258 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8259 				return -EACCES;
8260 		}
8261 		break;
8262 	case PTR_TO_BTF_ID | MEM_PERCPU:
8263 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8264 		/* Handled by helper specific checks */
8265 		break;
8266 	default:
8267 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8268 		return -EFAULT;
8269 	}
8270 	return 0;
8271 }
8272 
8273 static struct btf_field *
8274 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8275 {
8276 	struct btf_field *field;
8277 	struct btf_record *rec;
8278 
8279 	rec = reg_btf_record(reg);
8280 	if (!rec)
8281 		return NULL;
8282 
8283 	field = btf_record_find(rec, off, fields);
8284 	if (!field)
8285 		return NULL;
8286 
8287 	return field;
8288 }
8289 
8290 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8291 			   const struct bpf_reg_state *reg, int regno,
8292 			   enum bpf_arg_type arg_type)
8293 {
8294 	u32 type = reg->type;
8295 
8296 	/* When referenced register is passed to release function, its fixed
8297 	 * offset must be 0.
8298 	 *
8299 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8300 	 * meta->release_regno.
8301 	 */
8302 	if (arg_type_is_release(arg_type)) {
8303 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8304 		 * may not directly point to the object being released, but to
8305 		 * dynptr pointing to such object, which might be at some offset
8306 		 * on the stack. In that case, we simply to fallback to the
8307 		 * default handling.
8308 		 */
8309 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8310 			return 0;
8311 
8312 		/* Doing check_ptr_off_reg check for the offset will catch this
8313 		 * because fixed_off_ok is false, but checking here allows us
8314 		 * to give the user a better error message.
8315 		 */
8316 		if (reg->off) {
8317 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8318 				regno);
8319 			return -EINVAL;
8320 		}
8321 		return __check_ptr_off_reg(env, reg, regno, false);
8322 	}
8323 
8324 	switch (type) {
8325 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8326 	case PTR_TO_STACK:
8327 	case PTR_TO_PACKET:
8328 	case PTR_TO_PACKET_META:
8329 	case PTR_TO_MAP_KEY:
8330 	case PTR_TO_MAP_VALUE:
8331 	case PTR_TO_MEM:
8332 	case PTR_TO_MEM | MEM_RDONLY:
8333 	case PTR_TO_MEM | MEM_RINGBUF:
8334 	case PTR_TO_BUF:
8335 	case PTR_TO_BUF | MEM_RDONLY:
8336 	case SCALAR_VALUE:
8337 		return 0;
8338 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8339 	 * fixed offset.
8340 	 */
8341 	case PTR_TO_BTF_ID:
8342 	case PTR_TO_BTF_ID | MEM_ALLOC:
8343 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8344 	case PTR_TO_BTF_ID | MEM_RCU:
8345 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8346 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8347 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8348 		 * its fixed offset must be 0. In the other cases, fixed offset
8349 		 * can be non-zero. This was already checked above. So pass
8350 		 * fixed_off_ok as true to allow fixed offset for all other
8351 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8352 		 * still need to do checks instead of returning.
8353 		 */
8354 		return __check_ptr_off_reg(env, reg, regno, true);
8355 	default:
8356 		return __check_ptr_off_reg(env, reg, regno, false);
8357 	}
8358 }
8359 
8360 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8361 						const struct bpf_func_proto *fn,
8362 						struct bpf_reg_state *regs)
8363 {
8364 	struct bpf_reg_state *state = NULL;
8365 	int i;
8366 
8367 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8368 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8369 			if (state) {
8370 				verbose(env, "verifier internal error: multiple dynptr args\n");
8371 				return NULL;
8372 			}
8373 			state = &regs[BPF_REG_1 + i];
8374 		}
8375 
8376 	if (!state)
8377 		verbose(env, "verifier internal error: no dynptr arg found\n");
8378 
8379 	return state;
8380 }
8381 
8382 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8383 {
8384 	struct bpf_func_state *state = func(env, reg);
8385 	int spi;
8386 
8387 	if (reg->type == CONST_PTR_TO_DYNPTR)
8388 		return reg->id;
8389 	spi = dynptr_get_spi(env, reg);
8390 	if (spi < 0)
8391 		return spi;
8392 	return state->stack[spi].spilled_ptr.id;
8393 }
8394 
8395 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8396 {
8397 	struct bpf_func_state *state = func(env, reg);
8398 	int spi;
8399 
8400 	if (reg->type == CONST_PTR_TO_DYNPTR)
8401 		return reg->ref_obj_id;
8402 	spi = dynptr_get_spi(env, reg);
8403 	if (spi < 0)
8404 		return spi;
8405 	return state->stack[spi].spilled_ptr.ref_obj_id;
8406 }
8407 
8408 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8409 					    struct bpf_reg_state *reg)
8410 {
8411 	struct bpf_func_state *state = func(env, reg);
8412 	int spi;
8413 
8414 	if (reg->type == CONST_PTR_TO_DYNPTR)
8415 		return reg->dynptr.type;
8416 
8417 	spi = __get_spi(reg->off);
8418 	if (spi < 0) {
8419 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8420 		return BPF_DYNPTR_TYPE_INVALID;
8421 	}
8422 
8423 	return state->stack[spi].spilled_ptr.dynptr.type;
8424 }
8425 
8426 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8427 			  struct bpf_call_arg_meta *meta,
8428 			  const struct bpf_func_proto *fn,
8429 			  int insn_idx)
8430 {
8431 	u32 regno = BPF_REG_1 + arg;
8432 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8433 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8434 	enum bpf_reg_type type = reg->type;
8435 	u32 *arg_btf_id = NULL;
8436 	int err = 0;
8437 
8438 	if (arg_type == ARG_DONTCARE)
8439 		return 0;
8440 
8441 	err = check_reg_arg(env, regno, SRC_OP);
8442 	if (err)
8443 		return err;
8444 
8445 	if (arg_type == ARG_ANYTHING) {
8446 		if (is_pointer_value(env, regno)) {
8447 			verbose(env, "R%d leaks addr into helper function\n",
8448 				regno);
8449 			return -EACCES;
8450 		}
8451 		return 0;
8452 	}
8453 
8454 	if (type_is_pkt_pointer(type) &&
8455 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8456 		verbose(env, "helper access to the packet is not allowed\n");
8457 		return -EACCES;
8458 	}
8459 
8460 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8461 		err = resolve_map_arg_type(env, meta, &arg_type);
8462 		if (err)
8463 			return err;
8464 	}
8465 
8466 	if (register_is_null(reg) && type_may_be_null(arg_type))
8467 		/* A NULL register has a SCALAR_VALUE type, so skip
8468 		 * type checking.
8469 		 */
8470 		goto skip_type_check;
8471 
8472 	/* arg_btf_id and arg_size are in a union. */
8473 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8474 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8475 		arg_btf_id = fn->arg_btf_id[arg];
8476 
8477 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8478 	if (err)
8479 		return err;
8480 
8481 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8482 	if (err)
8483 		return err;
8484 
8485 skip_type_check:
8486 	if (arg_type_is_release(arg_type)) {
8487 		if (arg_type_is_dynptr(arg_type)) {
8488 			struct bpf_func_state *state = func(env, reg);
8489 			int spi;
8490 
8491 			/* Only dynptr created on stack can be released, thus
8492 			 * the get_spi and stack state checks for spilled_ptr
8493 			 * should only be done before process_dynptr_func for
8494 			 * PTR_TO_STACK.
8495 			 */
8496 			if (reg->type == PTR_TO_STACK) {
8497 				spi = dynptr_get_spi(env, reg);
8498 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8499 					verbose(env, "arg %d is an unacquired reference\n", regno);
8500 					return -EINVAL;
8501 				}
8502 			} else {
8503 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8504 				return -EINVAL;
8505 			}
8506 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8507 			verbose(env, "R%d must be referenced when passed to release function\n",
8508 				regno);
8509 			return -EINVAL;
8510 		}
8511 		if (meta->release_regno) {
8512 			verbose(env, "verifier internal error: more than one release argument\n");
8513 			return -EFAULT;
8514 		}
8515 		meta->release_regno = regno;
8516 	}
8517 
8518 	if (reg->ref_obj_id) {
8519 		if (meta->ref_obj_id) {
8520 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8521 				regno, reg->ref_obj_id,
8522 				meta->ref_obj_id);
8523 			return -EFAULT;
8524 		}
8525 		meta->ref_obj_id = reg->ref_obj_id;
8526 	}
8527 
8528 	switch (base_type(arg_type)) {
8529 	case ARG_CONST_MAP_PTR:
8530 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8531 		if (meta->map_ptr) {
8532 			/* Use map_uid (which is unique id of inner map) to reject:
8533 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8534 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8535 			 * if (inner_map1 && inner_map2) {
8536 			 *     timer = bpf_map_lookup_elem(inner_map1);
8537 			 *     if (timer)
8538 			 *         // mismatch would have been allowed
8539 			 *         bpf_timer_init(timer, inner_map2);
8540 			 * }
8541 			 *
8542 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8543 			 */
8544 			if (meta->map_ptr != reg->map_ptr ||
8545 			    meta->map_uid != reg->map_uid) {
8546 				verbose(env,
8547 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8548 					meta->map_uid, reg->map_uid);
8549 				return -EINVAL;
8550 			}
8551 		}
8552 		meta->map_ptr = reg->map_ptr;
8553 		meta->map_uid = reg->map_uid;
8554 		break;
8555 	case ARG_PTR_TO_MAP_KEY:
8556 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8557 		 * check that [key, key + map->key_size) are within
8558 		 * stack limits and initialized
8559 		 */
8560 		if (!meta->map_ptr) {
8561 			/* in function declaration map_ptr must come before
8562 			 * map_key, so that it's verified and known before
8563 			 * we have to check map_key here. Otherwise it means
8564 			 * that kernel subsystem misconfigured verifier
8565 			 */
8566 			verbose(env, "invalid map_ptr to access map->key\n");
8567 			return -EACCES;
8568 		}
8569 		err = check_helper_mem_access(env, regno,
8570 					      meta->map_ptr->key_size, false,
8571 					      NULL);
8572 		break;
8573 	case ARG_PTR_TO_MAP_VALUE:
8574 		if (type_may_be_null(arg_type) && register_is_null(reg))
8575 			return 0;
8576 
8577 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8578 		 * check [value, value + map->value_size) validity
8579 		 */
8580 		if (!meta->map_ptr) {
8581 			/* kernel subsystem misconfigured verifier */
8582 			verbose(env, "invalid map_ptr to access map->value\n");
8583 			return -EACCES;
8584 		}
8585 		meta->raw_mode = arg_type & MEM_UNINIT;
8586 		err = check_helper_mem_access(env, regno,
8587 					      meta->map_ptr->value_size, false,
8588 					      meta);
8589 		break;
8590 	case ARG_PTR_TO_PERCPU_BTF_ID:
8591 		if (!reg->btf_id) {
8592 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8593 			return -EACCES;
8594 		}
8595 		meta->ret_btf = reg->btf;
8596 		meta->ret_btf_id = reg->btf_id;
8597 		break;
8598 	case ARG_PTR_TO_SPIN_LOCK:
8599 		if (in_rbtree_lock_required_cb(env)) {
8600 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8601 			return -EACCES;
8602 		}
8603 		if (meta->func_id == BPF_FUNC_spin_lock) {
8604 			err = process_spin_lock(env, regno, true);
8605 			if (err)
8606 				return err;
8607 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8608 			err = process_spin_lock(env, regno, false);
8609 			if (err)
8610 				return err;
8611 		} else {
8612 			verbose(env, "verifier internal error\n");
8613 			return -EFAULT;
8614 		}
8615 		break;
8616 	case ARG_PTR_TO_TIMER:
8617 		err = process_timer_func(env, regno, meta);
8618 		if (err)
8619 			return err;
8620 		break;
8621 	case ARG_PTR_TO_FUNC:
8622 		meta->subprogno = reg->subprogno;
8623 		break;
8624 	case ARG_PTR_TO_MEM:
8625 		/* The access to this pointer is only checked when we hit the
8626 		 * next is_mem_size argument below.
8627 		 */
8628 		meta->raw_mode = arg_type & MEM_UNINIT;
8629 		if (arg_type & MEM_FIXED_SIZE) {
8630 			err = check_helper_mem_access(env, regno,
8631 						      fn->arg_size[arg], false,
8632 						      meta);
8633 		}
8634 		break;
8635 	case ARG_CONST_SIZE:
8636 		err = check_mem_size_reg(env, reg, regno, false, meta);
8637 		break;
8638 	case ARG_CONST_SIZE_OR_ZERO:
8639 		err = check_mem_size_reg(env, reg, regno, true, meta);
8640 		break;
8641 	case ARG_PTR_TO_DYNPTR:
8642 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8643 		if (err)
8644 			return err;
8645 		break;
8646 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8647 		if (!tnum_is_const(reg->var_off)) {
8648 			verbose(env, "R%d is not a known constant'\n",
8649 				regno);
8650 			return -EACCES;
8651 		}
8652 		meta->mem_size = reg->var_off.value;
8653 		err = mark_chain_precision(env, regno);
8654 		if (err)
8655 			return err;
8656 		break;
8657 	case ARG_PTR_TO_INT:
8658 	case ARG_PTR_TO_LONG:
8659 	{
8660 		int size = int_ptr_type_to_size(arg_type);
8661 
8662 		err = check_helper_mem_access(env, regno, size, false, meta);
8663 		if (err)
8664 			return err;
8665 		err = check_ptr_alignment(env, reg, 0, size, true);
8666 		break;
8667 	}
8668 	case ARG_PTR_TO_CONST_STR:
8669 	{
8670 		struct bpf_map *map = reg->map_ptr;
8671 		int map_off;
8672 		u64 map_addr;
8673 		char *str_ptr;
8674 
8675 		if (!bpf_map_is_rdonly(map)) {
8676 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8677 			return -EACCES;
8678 		}
8679 
8680 		if (!tnum_is_const(reg->var_off)) {
8681 			verbose(env, "R%d is not a constant address'\n", regno);
8682 			return -EACCES;
8683 		}
8684 
8685 		if (!map->ops->map_direct_value_addr) {
8686 			verbose(env, "no direct value access support for this map type\n");
8687 			return -EACCES;
8688 		}
8689 
8690 		err = check_map_access(env, regno, reg->off,
8691 				       map->value_size - reg->off, false,
8692 				       ACCESS_HELPER);
8693 		if (err)
8694 			return err;
8695 
8696 		map_off = reg->off + reg->var_off.value;
8697 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8698 		if (err) {
8699 			verbose(env, "direct value access on string failed\n");
8700 			return err;
8701 		}
8702 
8703 		str_ptr = (char *)(long)(map_addr);
8704 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8705 			verbose(env, "string is not zero-terminated\n");
8706 			return -EINVAL;
8707 		}
8708 		break;
8709 	}
8710 	case ARG_PTR_TO_KPTR:
8711 		err = process_kptr_func(env, regno, meta);
8712 		if (err)
8713 			return err;
8714 		break;
8715 	}
8716 
8717 	return err;
8718 }
8719 
8720 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8721 {
8722 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8723 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8724 
8725 	if (func_id != BPF_FUNC_map_update_elem)
8726 		return false;
8727 
8728 	/* It's not possible to get access to a locked struct sock in these
8729 	 * contexts, so updating is safe.
8730 	 */
8731 	switch (type) {
8732 	case BPF_PROG_TYPE_TRACING:
8733 		if (eatype == BPF_TRACE_ITER)
8734 			return true;
8735 		break;
8736 	case BPF_PROG_TYPE_SOCKET_FILTER:
8737 	case BPF_PROG_TYPE_SCHED_CLS:
8738 	case BPF_PROG_TYPE_SCHED_ACT:
8739 	case BPF_PROG_TYPE_XDP:
8740 	case BPF_PROG_TYPE_SK_REUSEPORT:
8741 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8742 	case BPF_PROG_TYPE_SK_LOOKUP:
8743 		return true;
8744 	default:
8745 		break;
8746 	}
8747 
8748 	verbose(env, "cannot update sockmap in this context\n");
8749 	return false;
8750 }
8751 
8752 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8753 {
8754 	return env->prog->jit_requested &&
8755 	       bpf_jit_supports_subprog_tailcalls();
8756 }
8757 
8758 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8759 					struct bpf_map *map, int func_id)
8760 {
8761 	if (!map)
8762 		return 0;
8763 
8764 	/* We need a two way check, first is from map perspective ... */
8765 	switch (map->map_type) {
8766 	case BPF_MAP_TYPE_PROG_ARRAY:
8767 		if (func_id != BPF_FUNC_tail_call)
8768 			goto error;
8769 		break;
8770 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8771 		if (func_id != BPF_FUNC_perf_event_read &&
8772 		    func_id != BPF_FUNC_perf_event_output &&
8773 		    func_id != BPF_FUNC_skb_output &&
8774 		    func_id != BPF_FUNC_perf_event_read_value &&
8775 		    func_id != BPF_FUNC_xdp_output)
8776 			goto error;
8777 		break;
8778 	case BPF_MAP_TYPE_RINGBUF:
8779 		if (func_id != BPF_FUNC_ringbuf_output &&
8780 		    func_id != BPF_FUNC_ringbuf_reserve &&
8781 		    func_id != BPF_FUNC_ringbuf_query &&
8782 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8783 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8784 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8785 			goto error;
8786 		break;
8787 	case BPF_MAP_TYPE_USER_RINGBUF:
8788 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8789 			goto error;
8790 		break;
8791 	case BPF_MAP_TYPE_STACK_TRACE:
8792 		if (func_id != BPF_FUNC_get_stackid)
8793 			goto error;
8794 		break;
8795 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8796 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8797 		    func_id != BPF_FUNC_current_task_under_cgroup)
8798 			goto error;
8799 		break;
8800 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8801 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8802 		if (func_id != BPF_FUNC_get_local_storage)
8803 			goto error;
8804 		break;
8805 	case BPF_MAP_TYPE_DEVMAP:
8806 	case BPF_MAP_TYPE_DEVMAP_HASH:
8807 		if (func_id != BPF_FUNC_redirect_map &&
8808 		    func_id != BPF_FUNC_map_lookup_elem)
8809 			goto error;
8810 		break;
8811 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8812 	 * appear.
8813 	 */
8814 	case BPF_MAP_TYPE_CPUMAP:
8815 		if (func_id != BPF_FUNC_redirect_map)
8816 			goto error;
8817 		break;
8818 	case BPF_MAP_TYPE_XSKMAP:
8819 		if (func_id != BPF_FUNC_redirect_map &&
8820 		    func_id != BPF_FUNC_map_lookup_elem)
8821 			goto error;
8822 		break;
8823 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8824 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8825 		if (func_id != BPF_FUNC_map_lookup_elem)
8826 			goto error;
8827 		break;
8828 	case BPF_MAP_TYPE_SOCKMAP:
8829 		if (func_id != BPF_FUNC_sk_redirect_map &&
8830 		    func_id != BPF_FUNC_sock_map_update &&
8831 		    func_id != BPF_FUNC_map_delete_elem &&
8832 		    func_id != BPF_FUNC_msg_redirect_map &&
8833 		    func_id != BPF_FUNC_sk_select_reuseport &&
8834 		    func_id != BPF_FUNC_map_lookup_elem &&
8835 		    !may_update_sockmap(env, func_id))
8836 			goto error;
8837 		break;
8838 	case BPF_MAP_TYPE_SOCKHASH:
8839 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8840 		    func_id != BPF_FUNC_sock_hash_update &&
8841 		    func_id != BPF_FUNC_map_delete_elem &&
8842 		    func_id != BPF_FUNC_msg_redirect_hash &&
8843 		    func_id != BPF_FUNC_sk_select_reuseport &&
8844 		    func_id != BPF_FUNC_map_lookup_elem &&
8845 		    !may_update_sockmap(env, func_id))
8846 			goto error;
8847 		break;
8848 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8849 		if (func_id != BPF_FUNC_sk_select_reuseport)
8850 			goto error;
8851 		break;
8852 	case BPF_MAP_TYPE_QUEUE:
8853 	case BPF_MAP_TYPE_STACK:
8854 		if (func_id != BPF_FUNC_map_peek_elem &&
8855 		    func_id != BPF_FUNC_map_pop_elem &&
8856 		    func_id != BPF_FUNC_map_push_elem)
8857 			goto error;
8858 		break;
8859 	case BPF_MAP_TYPE_SK_STORAGE:
8860 		if (func_id != BPF_FUNC_sk_storage_get &&
8861 		    func_id != BPF_FUNC_sk_storage_delete &&
8862 		    func_id != BPF_FUNC_kptr_xchg)
8863 			goto error;
8864 		break;
8865 	case BPF_MAP_TYPE_INODE_STORAGE:
8866 		if (func_id != BPF_FUNC_inode_storage_get &&
8867 		    func_id != BPF_FUNC_inode_storage_delete &&
8868 		    func_id != BPF_FUNC_kptr_xchg)
8869 			goto error;
8870 		break;
8871 	case BPF_MAP_TYPE_TASK_STORAGE:
8872 		if (func_id != BPF_FUNC_task_storage_get &&
8873 		    func_id != BPF_FUNC_task_storage_delete &&
8874 		    func_id != BPF_FUNC_kptr_xchg)
8875 			goto error;
8876 		break;
8877 	case BPF_MAP_TYPE_CGRP_STORAGE:
8878 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8879 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8880 		    func_id != BPF_FUNC_kptr_xchg)
8881 			goto error;
8882 		break;
8883 	case BPF_MAP_TYPE_BLOOM_FILTER:
8884 		if (func_id != BPF_FUNC_map_peek_elem &&
8885 		    func_id != BPF_FUNC_map_push_elem)
8886 			goto error;
8887 		break;
8888 	default:
8889 		break;
8890 	}
8891 
8892 	/* ... and second from the function itself. */
8893 	switch (func_id) {
8894 	case BPF_FUNC_tail_call:
8895 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8896 			goto error;
8897 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8898 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8899 			return -EINVAL;
8900 		}
8901 		break;
8902 	case BPF_FUNC_perf_event_read:
8903 	case BPF_FUNC_perf_event_output:
8904 	case BPF_FUNC_perf_event_read_value:
8905 	case BPF_FUNC_skb_output:
8906 	case BPF_FUNC_xdp_output:
8907 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8908 			goto error;
8909 		break;
8910 	case BPF_FUNC_ringbuf_output:
8911 	case BPF_FUNC_ringbuf_reserve:
8912 	case BPF_FUNC_ringbuf_query:
8913 	case BPF_FUNC_ringbuf_reserve_dynptr:
8914 	case BPF_FUNC_ringbuf_submit_dynptr:
8915 	case BPF_FUNC_ringbuf_discard_dynptr:
8916 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8917 			goto error;
8918 		break;
8919 	case BPF_FUNC_user_ringbuf_drain:
8920 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8921 			goto error;
8922 		break;
8923 	case BPF_FUNC_get_stackid:
8924 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8925 			goto error;
8926 		break;
8927 	case BPF_FUNC_current_task_under_cgroup:
8928 	case BPF_FUNC_skb_under_cgroup:
8929 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8930 			goto error;
8931 		break;
8932 	case BPF_FUNC_redirect_map:
8933 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8934 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8935 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8936 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8937 			goto error;
8938 		break;
8939 	case BPF_FUNC_sk_redirect_map:
8940 	case BPF_FUNC_msg_redirect_map:
8941 	case BPF_FUNC_sock_map_update:
8942 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8943 			goto error;
8944 		break;
8945 	case BPF_FUNC_sk_redirect_hash:
8946 	case BPF_FUNC_msg_redirect_hash:
8947 	case BPF_FUNC_sock_hash_update:
8948 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8949 			goto error;
8950 		break;
8951 	case BPF_FUNC_get_local_storage:
8952 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8953 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8954 			goto error;
8955 		break;
8956 	case BPF_FUNC_sk_select_reuseport:
8957 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8958 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8959 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8960 			goto error;
8961 		break;
8962 	case BPF_FUNC_map_pop_elem:
8963 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8964 		    map->map_type != BPF_MAP_TYPE_STACK)
8965 			goto error;
8966 		break;
8967 	case BPF_FUNC_map_peek_elem:
8968 	case BPF_FUNC_map_push_elem:
8969 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8970 		    map->map_type != BPF_MAP_TYPE_STACK &&
8971 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8972 			goto error;
8973 		break;
8974 	case BPF_FUNC_map_lookup_percpu_elem:
8975 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8976 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8977 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8978 			goto error;
8979 		break;
8980 	case BPF_FUNC_sk_storage_get:
8981 	case BPF_FUNC_sk_storage_delete:
8982 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8983 			goto error;
8984 		break;
8985 	case BPF_FUNC_inode_storage_get:
8986 	case BPF_FUNC_inode_storage_delete:
8987 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8988 			goto error;
8989 		break;
8990 	case BPF_FUNC_task_storage_get:
8991 	case BPF_FUNC_task_storage_delete:
8992 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8993 			goto error;
8994 		break;
8995 	case BPF_FUNC_cgrp_storage_get:
8996 	case BPF_FUNC_cgrp_storage_delete:
8997 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8998 			goto error;
8999 		break;
9000 	default:
9001 		break;
9002 	}
9003 
9004 	return 0;
9005 error:
9006 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9007 		map->map_type, func_id_name(func_id), func_id);
9008 	return -EINVAL;
9009 }
9010 
9011 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9012 {
9013 	int count = 0;
9014 
9015 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9016 		count++;
9017 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9018 		count++;
9019 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9020 		count++;
9021 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9022 		count++;
9023 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9024 		count++;
9025 
9026 	/* We only support one arg being in raw mode at the moment,
9027 	 * which is sufficient for the helper functions we have
9028 	 * right now.
9029 	 */
9030 	return count <= 1;
9031 }
9032 
9033 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9034 {
9035 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9036 	bool has_size = fn->arg_size[arg] != 0;
9037 	bool is_next_size = false;
9038 
9039 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9040 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9041 
9042 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9043 		return is_next_size;
9044 
9045 	return has_size == is_next_size || is_next_size == is_fixed;
9046 }
9047 
9048 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9049 {
9050 	/* bpf_xxx(..., buf, len) call will access 'len'
9051 	 * bytes from memory 'buf'. Both arg types need
9052 	 * to be paired, so make sure there's no buggy
9053 	 * helper function specification.
9054 	 */
9055 	if (arg_type_is_mem_size(fn->arg1_type) ||
9056 	    check_args_pair_invalid(fn, 0) ||
9057 	    check_args_pair_invalid(fn, 1) ||
9058 	    check_args_pair_invalid(fn, 2) ||
9059 	    check_args_pair_invalid(fn, 3) ||
9060 	    check_args_pair_invalid(fn, 4))
9061 		return false;
9062 
9063 	return true;
9064 }
9065 
9066 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9067 {
9068 	int i;
9069 
9070 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9071 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9072 			return !!fn->arg_btf_id[i];
9073 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9074 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9075 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9076 		    /* arg_btf_id and arg_size are in a union. */
9077 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9078 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9079 			return false;
9080 	}
9081 
9082 	return true;
9083 }
9084 
9085 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9086 {
9087 	return check_raw_mode_ok(fn) &&
9088 	       check_arg_pair_ok(fn) &&
9089 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9090 }
9091 
9092 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9093  * are now invalid, so turn them into unknown SCALAR_VALUE.
9094  *
9095  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9096  * since these slices point to packet data.
9097  */
9098 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9099 {
9100 	struct bpf_func_state *state;
9101 	struct bpf_reg_state *reg;
9102 
9103 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9104 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9105 			mark_reg_invalid(env, reg);
9106 	}));
9107 }
9108 
9109 enum {
9110 	AT_PKT_END = -1,
9111 	BEYOND_PKT_END = -2,
9112 };
9113 
9114 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9115 {
9116 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9117 	struct bpf_reg_state *reg = &state->regs[regn];
9118 
9119 	if (reg->type != PTR_TO_PACKET)
9120 		/* PTR_TO_PACKET_META is not supported yet */
9121 		return;
9122 
9123 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9124 	 * How far beyond pkt_end it goes is unknown.
9125 	 * if (!range_open) it's the case of pkt >= pkt_end
9126 	 * if (range_open) it's the case of pkt > pkt_end
9127 	 * hence this pointer is at least 1 byte bigger than pkt_end
9128 	 */
9129 	if (range_open)
9130 		reg->range = BEYOND_PKT_END;
9131 	else
9132 		reg->range = AT_PKT_END;
9133 }
9134 
9135 /* The pointer with the specified id has released its reference to kernel
9136  * resources. Identify all copies of the same pointer and clear the reference.
9137  */
9138 static int release_reference(struct bpf_verifier_env *env,
9139 			     int ref_obj_id)
9140 {
9141 	struct bpf_func_state *state;
9142 	struct bpf_reg_state *reg;
9143 	int err;
9144 
9145 	err = release_reference_state(cur_func(env), ref_obj_id);
9146 	if (err)
9147 		return err;
9148 
9149 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9150 		if (reg->ref_obj_id == ref_obj_id)
9151 			mark_reg_invalid(env, reg);
9152 	}));
9153 
9154 	return 0;
9155 }
9156 
9157 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9158 {
9159 	struct bpf_func_state *unused;
9160 	struct bpf_reg_state *reg;
9161 
9162 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9163 		if (type_is_non_owning_ref(reg->type))
9164 			mark_reg_invalid(env, reg);
9165 	}));
9166 }
9167 
9168 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9169 				    struct bpf_reg_state *regs)
9170 {
9171 	int i;
9172 
9173 	/* after the call registers r0 - r5 were scratched */
9174 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9175 		mark_reg_not_init(env, regs, caller_saved[i]);
9176 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9177 	}
9178 }
9179 
9180 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9181 				   struct bpf_func_state *caller,
9182 				   struct bpf_func_state *callee,
9183 				   int insn_idx);
9184 
9185 static int set_callee_state(struct bpf_verifier_env *env,
9186 			    struct bpf_func_state *caller,
9187 			    struct bpf_func_state *callee, int insn_idx);
9188 
9189 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9190 			    set_callee_state_fn set_callee_state_cb,
9191 			    struct bpf_verifier_state *state)
9192 {
9193 	struct bpf_func_state *caller, *callee;
9194 	int err;
9195 
9196 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9197 		verbose(env, "the call stack of %d frames is too deep\n",
9198 			state->curframe + 2);
9199 		return -E2BIG;
9200 	}
9201 
9202 	if (state->frame[state->curframe + 1]) {
9203 		verbose(env, "verifier bug. Frame %d already allocated\n",
9204 			state->curframe + 1);
9205 		return -EFAULT;
9206 	}
9207 
9208 	caller = state->frame[state->curframe];
9209 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9210 	if (!callee)
9211 		return -ENOMEM;
9212 	state->frame[state->curframe + 1] = callee;
9213 
9214 	/* callee cannot access r0, r6 - r9 for reading and has to write
9215 	 * into its own stack before reading from it.
9216 	 * callee can read/write into caller's stack
9217 	 */
9218 	init_func_state(env, callee,
9219 			/* remember the callsite, it will be used by bpf_exit */
9220 			callsite,
9221 			state->curframe + 1 /* frameno within this callchain */,
9222 			subprog /* subprog number within this prog */);
9223 	/* Transfer references to the callee */
9224 	err = copy_reference_state(callee, caller);
9225 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9226 	if (err)
9227 		goto err_out;
9228 
9229 	/* only increment it after check_reg_arg() finished */
9230 	state->curframe++;
9231 
9232 	return 0;
9233 
9234 err_out:
9235 	free_func_state(callee);
9236 	state->frame[state->curframe + 1] = NULL;
9237 	return err;
9238 }
9239 
9240 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9241 			      int insn_idx, int subprog,
9242 			      set_callee_state_fn set_callee_state_cb)
9243 {
9244 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9245 	struct bpf_func_state *caller, *callee;
9246 	int err;
9247 
9248 	caller = state->frame[state->curframe];
9249 	err = btf_check_subprog_call(env, subprog, caller->regs);
9250 	if (err == -EFAULT)
9251 		return err;
9252 
9253 	/* set_callee_state is used for direct subprog calls, but we are
9254 	 * interested in validating only BPF helpers that can call subprogs as
9255 	 * callbacks
9256 	 */
9257 	if (bpf_pseudo_kfunc_call(insn) &&
9258 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9259 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9260 			func_id_name(insn->imm), insn->imm);
9261 		return -EFAULT;
9262 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9263 		   !is_callback_calling_function(insn->imm)) { /* helper */
9264 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9265 			func_id_name(insn->imm), insn->imm);
9266 		return -EFAULT;
9267 	}
9268 
9269 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9270 	    insn->src_reg == 0 &&
9271 	    insn->imm == BPF_FUNC_timer_set_callback) {
9272 		struct bpf_verifier_state *async_cb;
9273 
9274 		/* there is no real recursion here. timer callbacks are async */
9275 		env->subprog_info[subprog].is_async_cb = true;
9276 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9277 					 insn_idx, subprog);
9278 		if (!async_cb)
9279 			return -EFAULT;
9280 		callee = async_cb->frame[0];
9281 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9282 
9283 		/* Convert bpf_timer_set_callback() args into timer callback args */
9284 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9285 		if (err)
9286 			return err;
9287 
9288 		return 0;
9289 	}
9290 
9291 	/* for callback functions enqueue entry to callback and
9292 	 * proceed with next instruction within current frame.
9293 	 */
9294 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9295 	if (!callback_state)
9296 		return -ENOMEM;
9297 
9298 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9299 			       callback_state);
9300 	if (err)
9301 		return err;
9302 
9303 	callback_state->callback_unroll_depth++;
9304 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9305 	caller->callback_depth = 0;
9306 	return 0;
9307 }
9308 
9309 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9310 			   int *insn_idx)
9311 {
9312 	struct bpf_verifier_state *state = env->cur_state;
9313 	struct bpf_func_state *caller;
9314 	int err, subprog, target_insn;
9315 
9316 	target_insn = *insn_idx + insn->imm + 1;
9317 	subprog = find_subprog(env, target_insn);
9318 	if (subprog < 0) {
9319 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9320 		return -EFAULT;
9321 	}
9322 
9323 	caller = state->frame[state->curframe];
9324 	err = btf_check_subprog_call(env, subprog, caller->regs);
9325 	if (err == -EFAULT)
9326 		return err;
9327 	if (subprog_is_global(env, subprog)) {
9328 		if (err) {
9329 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9330 			return err;
9331 		}
9332 
9333 		if (env->log.level & BPF_LOG_LEVEL)
9334 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9335 		clear_caller_saved_regs(env, caller->regs);
9336 
9337 		/* All global functions return a 64-bit SCALAR_VALUE */
9338 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9339 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9340 
9341 		/* continue with next insn after call */
9342 		return 0;
9343 	}
9344 
9345 	/* for regular function entry setup new frame and continue
9346 	 * from that frame.
9347 	 */
9348 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9349 	if (err)
9350 		return err;
9351 
9352 	clear_caller_saved_regs(env, caller->regs);
9353 
9354 	/* and go analyze first insn of the callee */
9355 	*insn_idx = env->subprog_info[subprog].start - 1;
9356 
9357 	if (env->log.level & BPF_LOG_LEVEL) {
9358 		verbose(env, "caller:\n");
9359 		print_verifier_state(env, caller, true);
9360 		verbose(env, "callee:\n");
9361 		print_verifier_state(env, state->frame[state->curframe], true);
9362 	}
9363 
9364 	return 0;
9365 }
9366 
9367 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9368 				   struct bpf_func_state *caller,
9369 				   struct bpf_func_state *callee)
9370 {
9371 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9372 	 *      void *callback_ctx, u64 flags);
9373 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9374 	 *      void *callback_ctx);
9375 	 */
9376 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9377 
9378 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9379 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9380 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9381 
9382 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9383 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9384 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9385 
9386 	/* pointer to stack or null */
9387 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9388 
9389 	/* unused */
9390 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9391 	return 0;
9392 }
9393 
9394 static int set_callee_state(struct bpf_verifier_env *env,
9395 			    struct bpf_func_state *caller,
9396 			    struct bpf_func_state *callee, int insn_idx)
9397 {
9398 	int i;
9399 
9400 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9401 	 * pointers, which connects us up to the liveness chain
9402 	 */
9403 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9404 		callee->regs[i] = caller->regs[i];
9405 	return 0;
9406 }
9407 
9408 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9409 				       struct bpf_func_state *caller,
9410 				       struct bpf_func_state *callee,
9411 				       int insn_idx)
9412 {
9413 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9414 	struct bpf_map *map;
9415 	int err;
9416 
9417 	if (bpf_map_ptr_poisoned(insn_aux)) {
9418 		verbose(env, "tail_call abusing map_ptr\n");
9419 		return -EINVAL;
9420 	}
9421 
9422 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9423 	if (!map->ops->map_set_for_each_callback_args ||
9424 	    !map->ops->map_for_each_callback) {
9425 		verbose(env, "callback function not allowed for map\n");
9426 		return -ENOTSUPP;
9427 	}
9428 
9429 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9430 	if (err)
9431 		return err;
9432 
9433 	callee->in_callback_fn = true;
9434 	callee->callback_ret_range = tnum_range(0, 1);
9435 	return 0;
9436 }
9437 
9438 static int set_loop_callback_state(struct bpf_verifier_env *env,
9439 				   struct bpf_func_state *caller,
9440 				   struct bpf_func_state *callee,
9441 				   int insn_idx)
9442 {
9443 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9444 	 *	    u64 flags);
9445 	 * callback_fn(u32 index, void *callback_ctx);
9446 	 */
9447 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9448 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9449 
9450 	/* unused */
9451 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9452 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9453 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9454 
9455 	callee->in_callback_fn = true;
9456 	callee->callback_ret_range = tnum_range(0, 1);
9457 	return 0;
9458 }
9459 
9460 static int set_timer_callback_state(struct bpf_verifier_env *env,
9461 				    struct bpf_func_state *caller,
9462 				    struct bpf_func_state *callee,
9463 				    int insn_idx)
9464 {
9465 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9466 
9467 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9468 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9469 	 */
9470 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9471 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9472 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9473 
9474 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9475 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9476 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9477 
9478 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9479 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9480 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9481 
9482 	/* unused */
9483 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9484 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9485 	callee->in_async_callback_fn = true;
9486 	callee->callback_ret_range = tnum_range(0, 1);
9487 	return 0;
9488 }
9489 
9490 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9491 				       struct bpf_func_state *caller,
9492 				       struct bpf_func_state *callee,
9493 				       int insn_idx)
9494 {
9495 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9496 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9497 	 * (callback_fn)(struct task_struct *task,
9498 	 *               struct vm_area_struct *vma, void *callback_ctx);
9499 	 */
9500 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9501 
9502 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9503 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9504 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9505 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9506 
9507 	/* pointer to stack or null */
9508 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9509 
9510 	/* unused */
9511 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9512 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9513 	callee->in_callback_fn = true;
9514 	callee->callback_ret_range = tnum_range(0, 1);
9515 	return 0;
9516 }
9517 
9518 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9519 					   struct bpf_func_state *caller,
9520 					   struct bpf_func_state *callee,
9521 					   int insn_idx)
9522 {
9523 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9524 	 *			  callback_ctx, u64 flags);
9525 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9526 	 */
9527 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9528 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9529 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9530 
9531 	/* unused */
9532 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9533 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9534 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9535 
9536 	callee->in_callback_fn = true;
9537 	callee->callback_ret_range = tnum_range(0, 1);
9538 	return 0;
9539 }
9540 
9541 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9542 					 struct bpf_func_state *caller,
9543 					 struct bpf_func_state *callee,
9544 					 int insn_idx)
9545 {
9546 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9547 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9548 	 *
9549 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9550 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9551 	 * by this point, so look at 'root'
9552 	 */
9553 	struct btf_field *field;
9554 
9555 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9556 				      BPF_RB_ROOT);
9557 	if (!field || !field->graph_root.value_btf_id)
9558 		return -EFAULT;
9559 
9560 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9561 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9562 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9563 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9564 
9565 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9566 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9567 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9568 	callee->in_callback_fn = true;
9569 	callee->callback_ret_range = tnum_range(0, 1);
9570 	return 0;
9571 }
9572 
9573 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9574 
9575 /* Are we currently verifying the callback for a rbtree helper that must
9576  * be called with lock held? If so, no need to complain about unreleased
9577  * lock
9578  */
9579 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9580 {
9581 	struct bpf_verifier_state *state = env->cur_state;
9582 	struct bpf_insn *insn = env->prog->insnsi;
9583 	struct bpf_func_state *callee;
9584 	int kfunc_btf_id;
9585 
9586 	if (!state->curframe)
9587 		return false;
9588 
9589 	callee = state->frame[state->curframe];
9590 
9591 	if (!callee->in_callback_fn)
9592 		return false;
9593 
9594 	kfunc_btf_id = insn[callee->callsite].imm;
9595 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9596 }
9597 
9598 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9599 {
9600 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9601 	struct bpf_func_state *caller, *callee;
9602 	struct bpf_reg_state *r0;
9603 	bool in_callback_fn;
9604 	int err;
9605 
9606 	callee = state->frame[state->curframe];
9607 	r0 = &callee->regs[BPF_REG_0];
9608 	if (r0->type == PTR_TO_STACK) {
9609 		/* technically it's ok to return caller's stack pointer
9610 		 * (or caller's caller's pointer) back to the caller,
9611 		 * since these pointers are valid. Only current stack
9612 		 * pointer will be invalid as soon as function exits,
9613 		 * but let's be conservative
9614 		 */
9615 		verbose(env, "cannot return stack pointer to the caller\n");
9616 		return -EINVAL;
9617 	}
9618 
9619 	caller = state->frame[state->curframe - 1];
9620 	if (callee->in_callback_fn) {
9621 		/* enforce R0 return value range [0, 1]. */
9622 		struct tnum range = callee->callback_ret_range;
9623 
9624 		if (r0->type != SCALAR_VALUE) {
9625 			verbose(env, "R0 not a scalar value\n");
9626 			return -EACCES;
9627 		}
9628 
9629 		/* we are going to rely on register's precise value */
9630 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9631 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9632 		if (err)
9633 			return err;
9634 
9635 		if (!tnum_in(range, r0->var_off)) {
9636 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9637 			return -EINVAL;
9638 		}
9639 		if (!calls_callback(env, callee->callsite)) {
9640 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9641 				*insn_idx, callee->callsite);
9642 			return -EFAULT;
9643 		}
9644 	} else {
9645 		/* return to the caller whatever r0 had in the callee */
9646 		caller->regs[BPF_REG_0] = *r0;
9647 	}
9648 
9649 	/* callback_fn frame should have released its own additions to parent's
9650 	 * reference state at this point, or check_reference_leak would
9651 	 * complain, hence it must be the same as the caller. There is no need
9652 	 * to copy it back.
9653 	 */
9654 	if (!callee->in_callback_fn) {
9655 		/* Transfer references to the caller */
9656 		err = copy_reference_state(caller, callee);
9657 		if (err)
9658 			return err;
9659 	}
9660 
9661 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9662 	 * there function call logic would reschedule callback visit. If iteration
9663 	 * converges is_state_visited() would prune that visit eventually.
9664 	 */
9665 	in_callback_fn = callee->in_callback_fn;
9666 	if (in_callback_fn)
9667 		*insn_idx = callee->callsite;
9668 	else
9669 		*insn_idx = callee->callsite + 1;
9670 
9671 	if (env->log.level & BPF_LOG_LEVEL) {
9672 		verbose(env, "returning from callee:\n");
9673 		print_verifier_state(env, callee, true);
9674 		verbose(env, "to caller at %d:\n", *insn_idx);
9675 		print_verifier_state(env, caller, true);
9676 	}
9677 	/* clear everything in the callee */
9678 	free_func_state(callee);
9679 	state->frame[state->curframe--] = NULL;
9680 
9681 	/* for callbacks widen imprecise scalars to make programs like below verify:
9682 	 *
9683 	 *   struct ctx { int i; }
9684 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9685 	 *   ...
9686 	 *   struct ctx = { .i = 0; }
9687 	 *   bpf_loop(100, cb, &ctx, 0);
9688 	 *
9689 	 * This is similar to what is done in process_iter_next_call() for open
9690 	 * coded iterators.
9691 	 */
9692 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9693 	if (prev_st) {
9694 		err = widen_imprecise_scalars(env, prev_st, state);
9695 		if (err)
9696 			return err;
9697 	}
9698 	return 0;
9699 }
9700 
9701 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9702 				   int func_id,
9703 				   struct bpf_call_arg_meta *meta)
9704 {
9705 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9706 
9707 	if (ret_type != RET_INTEGER)
9708 		return;
9709 
9710 	switch (func_id) {
9711 	case BPF_FUNC_get_stack:
9712 	case BPF_FUNC_get_task_stack:
9713 	case BPF_FUNC_probe_read_str:
9714 	case BPF_FUNC_probe_read_kernel_str:
9715 	case BPF_FUNC_probe_read_user_str:
9716 		ret_reg->smax_value = meta->msize_max_value;
9717 		ret_reg->s32_max_value = meta->msize_max_value;
9718 		ret_reg->smin_value = -MAX_ERRNO;
9719 		ret_reg->s32_min_value = -MAX_ERRNO;
9720 		reg_bounds_sync(ret_reg);
9721 		break;
9722 	case BPF_FUNC_get_smp_processor_id:
9723 		ret_reg->umax_value = nr_cpu_ids - 1;
9724 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9725 		ret_reg->smax_value = nr_cpu_ids - 1;
9726 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9727 		ret_reg->umin_value = 0;
9728 		ret_reg->u32_min_value = 0;
9729 		ret_reg->smin_value = 0;
9730 		ret_reg->s32_min_value = 0;
9731 		reg_bounds_sync(ret_reg);
9732 		break;
9733 	}
9734 }
9735 
9736 static int
9737 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9738 		int func_id, int insn_idx)
9739 {
9740 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9741 	struct bpf_map *map = meta->map_ptr;
9742 
9743 	if (func_id != BPF_FUNC_tail_call &&
9744 	    func_id != BPF_FUNC_map_lookup_elem &&
9745 	    func_id != BPF_FUNC_map_update_elem &&
9746 	    func_id != BPF_FUNC_map_delete_elem &&
9747 	    func_id != BPF_FUNC_map_push_elem &&
9748 	    func_id != BPF_FUNC_map_pop_elem &&
9749 	    func_id != BPF_FUNC_map_peek_elem &&
9750 	    func_id != BPF_FUNC_for_each_map_elem &&
9751 	    func_id != BPF_FUNC_redirect_map &&
9752 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9753 		return 0;
9754 
9755 	if (map == NULL) {
9756 		verbose(env, "kernel subsystem misconfigured verifier\n");
9757 		return -EINVAL;
9758 	}
9759 
9760 	/* In case of read-only, some additional restrictions
9761 	 * need to be applied in order to prevent altering the
9762 	 * state of the map from program side.
9763 	 */
9764 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9765 	    (func_id == BPF_FUNC_map_delete_elem ||
9766 	     func_id == BPF_FUNC_map_update_elem ||
9767 	     func_id == BPF_FUNC_map_push_elem ||
9768 	     func_id == BPF_FUNC_map_pop_elem)) {
9769 		verbose(env, "write into map forbidden\n");
9770 		return -EACCES;
9771 	}
9772 
9773 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9774 		bpf_map_ptr_store(aux, meta->map_ptr,
9775 				  !meta->map_ptr->bypass_spec_v1);
9776 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9777 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9778 				  !meta->map_ptr->bypass_spec_v1);
9779 	return 0;
9780 }
9781 
9782 static int
9783 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9784 		int func_id, int insn_idx)
9785 {
9786 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9787 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9788 	struct bpf_map *map = meta->map_ptr;
9789 	u64 val, max;
9790 	int err;
9791 
9792 	if (func_id != BPF_FUNC_tail_call)
9793 		return 0;
9794 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9795 		verbose(env, "kernel subsystem misconfigured verifier\n");
9796 		return -EINVAL;
9797 	}
9798 
9799 	reg = &regs[BPF_REG_3];
9800 	val = reg->var_off.value;
9801 	max = map->max_entries;
9802 
9803 	if (!(register_is_const(reg) && val < max)) {
9804 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9805 		return 0;
9806 	}
9807 
9808 	err = mark_chain_precision(env, BPF_REG_3);
9809 	if (err)
9810 		return err;
9811 	if (bpf_map_key_unseen(aux))
9812 		bpf_map_key_store(aux, val);
9813 	else if (!bpf_map_key_poisoned(aux) &&
9814 		  bpf_map_key_immediate(aux) != val)
9815 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9816 	return 0;
9817 }
9818 
9819 static int check_reference_leak(struct bpf_verifier_env *env)
9820 {
9821 	struct bpf_func_state *state = cur_func(env);
9822 	bool refs_lingering = false;
9823 	int i;
9824 
9825 	if (state->frameno && !state->in_callback_fn)
9826 		return 0;
9827 
9828 	for (i = 0; i < state->acquired_refs; i++) {
9829 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9830 			continue;
9831 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9832 			state->refs[i].id, state->refs[i].insn_idx);
9833 		refs_lingering = true;
9834 	}
9835 	return refs_lingering ? -EINVAL : 0;
9836 }
9837 
9838 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9839 				   struct bpf_reg_state *regs)
9840 {
9841 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9842 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9843 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9844 	struct bpf_bprintf_data data = {};
9845 	int err, fmt_map_off, num_args;
9846 	u64 fmt_addr;
9847 	char *fmt;
9848 
9849 	/* data must be an array of u64 */
9850 	if (data_len_reg->var_off.value % 8)
9851 		return -EINVAL;
9852 	num_args = data_len_reg->var_off.value / 8;
9853 
9854 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9855 	 * and map_direct_value_addr is set.
9856 	 */
9857 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9858 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9859 						  fmt_map_off);
9860 	if (err) {
9861 		verbose(env, "verifier bug\n");
9862 		return -EFAULT;
9863 	}
9864 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9865 
9866 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9867 	 * can focus on validating the format specifiers.
9868 	 */
9869 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9870 	if (err < 0)
9871 		verbose(env, "Invalid format string\n");
9872 
9873 	return err;
9874 }
9875 
9876 static int check_get_func_ip(struct bpf_verifier_env *env)
9877 {
9878 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9879 	int func_id = BPF_FUNC_get_func_ip;
9880 
9881 	if (type == BPF_PROG_TYPE_TRACING) {
9882 		if (!bpf_prog_has_trampoline(env->prog)) {
9883 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9884 				func_id_name(func_id), func_id);
9885 			return -ENOTSUPP;
9886 		}
9887 		return 0;
9888 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9889 		return 0;
9890 	}
9891 
9892 	verbose(env, "func %s#%d not supported for program type %d\n",
9893 		func_id_name(func_id), func_id, type);
9894 	return -ENOTSUPP;
9895 }
9896 
9897 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9898 {
9899 	return &env->insn_aux_data[env->insn_idx];
9900 }
9901 
9902 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9903 {
9904 	struct bpf_reg_state *regs = cur_regs(env);
9905 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9906 	bool reg_is_null = register_is_null(reg);
9907 
9908 	if (reg_is_null)
9909 		mark_chain_precision(env, BPF_REG_4);
9910 
9911 	return reg_is_null;
9912 }
9913 
9914 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9915 {
9916 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9917 
9918 	if (!state->initialized) {
9919 		state->initialized = 1;
9920 		state->fit_for_inline = loop_flag_is_zero(env);
9921 		state->callback_subprogno = subprogno;
9922 		return;
9923 	}
9924 
9925 	if (!state->fit_for_inline)
9926 		return;
9927 
9928 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9929 				 state->callback_subprogno == subprogno);
9930 }
9931 
9932 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9933 			     int *insn_idx_p)
9934 {
9935 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9936 	const struct bpf_func_proto *fn = NULL;
9937 	enum bpf_return_type ret_type;
9938 	enum bpf_type_flag ret_flag;
9939 	struct bpf_reg_state *regs;
9940 	struct bpf_call_arg_meta meta;
9941 	int insn_idx = *insn_idx_p;
9942 	bool changes_data;
9943 	int i, err, func_id;
9944 
9945 	/* find function prototype */
9946 	func_id = insn->imm;
9947 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9948 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9949 			func_id);
9950 		return -EINVAL;
9951 	}
9952 
9953 	if (env->ops->get_func_proto)
9954 		fn = env->ops->get_func_proto(func_id, env->prog);
9955 	if (!fn) {
9956 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9957 			func_id);
9958 		return -EINVAL;
9959 	}
9960 
9961 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9962 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9963 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9964 		return -EINVAL;
9965 	}
9966 
9967 	if (fn->allowed && !fn->allowed(env->prog)) {
9968 		verbose(env, "helper call is not allowed in probe\n");
9969 		return -EINVAL;
9970 	}
9971 
9972 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9973 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9974 		return -EINVAL;
9975 	}
9976 
9977 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9978 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9979 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9980 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9981 			func_id_name(func_id), func_id);
9982 		return -EINVAL;
9983 	}
9984 
9985 	memset(&meta, 0, sizeof(meta));
9986 	meta.pkt_access = fn->pkt_access;
9987 
9988 	err = check_func_proto(fn, func_id);
9989 	if (err) {
9990 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9991 			func_id_name(func_id), func_id);
9992 		return err;
9993 	}
9994 
9995 	if (env->cur_state->active_rcu_lock) {
9996 		if (fn->might_sleep) {
9997 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9998 				func_id_name(func_id), func_id);
9999 			return -EINVAL;
10000 		}
10001 
10002 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10003 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10004 	}
10005 
10006 	meta.func_id = func_id;
10007 	/* check args */
10008 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10009 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10010 		if (err)
10011 			return err;
10012 	}
10013 
10014 	err = record_func_map(env, &meta, func_id, insn_idx);
10015 	if (err)
10016 		return err;
10017 
10018 	err = record_func_key(env, &meta, func_id, insn_idx);
10019 	if (err)
10020 		return err;
10021 
10022 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10023 	 * is inferred from register state.
10024 	 */
10025 	for (i = 0; i < meta.access_size; i++) {
10026 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10027 				       BPF_WRITE, -1, false, false);
10028 		if (err)
10029 			return err;
10030 	}
10031 
10032 	regs = cur_regs(env);
10033 
10034 	if (meta.release_regno) {
10035 		err = -EINVAL;
10036 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10037 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10038 		 * is safe to do directly.
10039 		 */
10040 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10041 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10042 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10043 				return -EFAULT;
10044 			}
10045 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10046 		} else if (meta.ref_obj_id) {
10047 			err = release_reference(env, meta.ref_obj_id);
10048 		} else if (register_is_null(&regs[meta.release_regno])) {
10049 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10050 			 * released is NULL, which must be > R0.
10051 			 */
10052 			err = 0;
10053 		}
10054 		if (err) {
10055 			verbose(env, "func %s#%d reference has not been acquired before\n",
10056 				func_id_name(func_id), func_id);
10057 			return err;
10058 		}
10059 	}
10060 
10061 	switch (func_id) {
10062 	case BPF_FUNC_tail_call:
10063 		err = check_reference_leak(env);
10064 		if (err) {
10065 			verbose(env, "tail_call would lead to reference leak\n");
10066 			return err;
10067 		}
10068 		break;
10069 	case BPF_FUNC_get_local_storage:
10070 		/* check that flags argument in get_local_storage(map, flags) is 0,
10071 		 * this is required because get_local_storage() can't return an error.
10072 		 */
10073 		if (!register_is_null(&regs[BPF_REG_2])) {
10074 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10075 			return -EINVAL;
10076 		}
10077 		break;
10078 	case BPF_FUNC_for_each_map_elem:
10079 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10080 					 set_map_elem_callback_state);
10081 		break;
10082 	case BPF_FUNC_timer_set_callback:
10083 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10084 					 set_timer_callback_state);
10085 		break;
10086 	case BPF_FUNC_find_vma:
10087 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10088 					 set_find_vma_callback_state);
10089 		break;
10090 	case BPF_FUNC_snprintf:
10091 		err = check_bpf_snprintf_call(env, regs);
10092 		break;
10093 	case BPF_FUNC_loop:
10094 		update_loop_inline_state(env, meta.subprogno);
10095 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10096 		 * is finished, thus mark it precise.
10097 		 */
10098 		err = mark_chain_precision(env, BPF_REG_1);
10099 		if (err)
10100 			return err;
10101 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10102 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10103 						 set_loop_callback_state);
10104 		} else {
10105 			cur_func(env)->callback_depth = 0;
10106 			if (env->log.level & BPF_LOG_LEVEL2)
10107 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10108 					env->cur_state->curframe);
10109 		}
10110 		break;
10111 	case BPF_FUNC_dynptr_from_mem:
10112 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10113 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10114 				reg_type_str(env, regs[BPF_REG_1].type));
10115 			return -EACCES;
10116 		}
10117 		break;
10118 	case BPF_FUNC_set_retval:
10119 		if (prog_type == BPF_PROG_TYPE_LSM &&
10120 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10121 			if (!env->prog->aux->attach_func_proto->type) {
10122 				/* Make sure programs that attach to void
10123 				 * hooks don't try to modify return value.
10124 				 */
10125 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10126 				return -EINVAL;
10127 			}
10128 		}
10129 		break;
10130 	case BPF_FUNC_dynptr_data:
10131 	{
10132 		struct bpf_reg_state *reg;
10133 		int id, ref_obj_id;
10134 
10135 		reg = get_dynptr_arg_reg(env, fn, regs);
10136 		if (!reg)
10137 			return -EFAULT;
10138 
10139 
10140 		if (meta.dynptr_id) {
10141 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10142 			return -EFAULT;
10143 		}
10144 		if (meta.ref_obj_id) {
10145 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10146 			return -EFAULT;
10147 		}
10148 
10149 		id = dynptr_id(env, reg);
10150 		if (id < 0) {
10151 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10152 			return id;
10153 		}
10154 
10155 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10156 		if (ref_obj_id < 0) {
10157 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10158 			return ref_obj_id;
10159 		}
10160 
10161 		meta.dynptr_id = id;
10162 		meta.ref_obj_id = ref_obj_id;
10163 
10164 		break;
10165 	}
10166 	case BPF_FUNC_dynptr_write:
10167 	{
10168 		enum bpf_dynptr_type dynptr_type;
10169 		struct bpf_reg_state *reg;
10170 
10171 		reg = get_dynptr_arg_reg(env, fn, regs);
10172 		if (!reg)
10173 			return -EFAULT;
10174 
10175 		dynptr_type = dynptr_get_type(env, reg);
10176 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10177 			return -EFAULT;
10178 
10179 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10180 			/* this will trigger clear_all_pkt_pointers(), which will
10181 			 * invalidate all dynptr slices associated with the skb
10182 			 */
10183 			changes_data = true;
10184 
10185 		break;
10186 	}
10187 	case BPF_FUNC_user_ringbuf_drain:
10188 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10189 					 set_user_ringbuf_callback_state);
10190 		break;
10191 	}
10192 
10193 	if (err)
10194 		return err;
10195 
10196 	/* reset caller saved regs */
10197 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10198 		mark_reg_not_init(env, regs, caller_saved[i]);
10199 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10200 	}
10201 
10202 	/* helper call returns 64-bit value. */
10203 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10204 
10205 	/* update return register (already marked as written above) */
10206 	ret_type = fn->ret_type;
10207 	ret_flag = type_flag(ret_type);
10208 
10209 	switch (base_type(ret_type)) {
10210 	case RET_INTEGER:
10211 		/* sets type to SCALAR_VALUE */
10212 		mark_reg_unknown(env, regs, BPF_REG_0);
10213 		break;
10214 	case RET_VOID:
10215 		regs[BPF_REG_0].type = NOT_INIT;
10216 		break;
10217 	case RET_PTR_TO_MAP_VALUE:
10218 		/* There is no offset yet applied, variable or fixed */
10219 		mark_reg_known_zero(env, regs, BPF_REG_0);
10220 		/* remember map_ptr, so that check_map_access()
10221 		 * can check 'value_size' boundary of memory access
10222 		 * to map element returned from bpf_map_lookup_elem()
10223 		 */
10224 		if (meta.map_ptr == NULL) {
10225 			verbose(env,
10226 				"kernel subsystem misconfigured verifier\n");
10227 			return -EINVAL;
10228 		}
10229 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10230 		regs[BPF_REG_0].map_uid = meta.map_uid;
10231 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10232 		if (!type_may_be_null(ret_type) &&
10233 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10234 			regs[BPF_REG_0].id = ++env->id_gen;
10235 		}
10236 		break;
10237 	case RET_PTR_TO_SOCKET:
10238 		mark_reg_known_zero(env, regs, BPF_REG_0);
10239 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10240 		break;
10241 	case RET_PTR_TO_SOCK_COMMON:
10242 		mark_reg_known_zero(env, regs, BPF_REG_0);
10243 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10244 		break;
10245 	case RET_PTR_TO_TCP_SOCK:
10246 		mark_reg_known_zero(env, regs, BPF_REG_0);
10247 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10248 		break;
10249 	case RET_PTR_TO_MEM:
10250 		mark_reg_known_zero(env, regs, BPF_REG_0);
10251 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10252 		regs[BPF_REG_0].mem_size = meta.mem_size;
10253 		break;
10254 	case RET_PTR_TO_MEM_OR_BTF_ID:
10255 	{
10256 		const struct btf_type *t;
10257 
10258 		mark_reg_known_zero(env, regs, BPF_REG_0);
10259 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10260 		if (!btf_type_is_struct(t)) {
10261 			u32 tsize;
10262 			const struct btf_type *ret;
10263 			const char *tname;
10264 
10265 			/* resolve the type size of ksym. */
10266 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10267 			if (IS_ERR(ret)) {
10268 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10269 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10270 					tname, PTR_ERR(ret));
10271 				return -EINVAL;
10272 			}
10273 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10274 			regs[BPF_REG_0].mem_size = tsize;
10275 		} else {
10276 			/* MEM_RDONLY may be carried from ret_flag, but it
10277 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10278 			 * it will confuse the check of PTR_TO_BTF_ID in
10279 			 * check_mem_access().
10280 			 */
10281 			ret_flag &= ~MEM_RDONLY;
10282 
10283 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10284 			regs[BPF_REG_0].btf = meta.ret_btf;
10285 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10286 		}
10287 		break;
10288 	}
10289 	case RET_PTR_TO_BTF_ID:
10290 	{
10291 		struct btf *ret_btf;
10292 		int ret_btf_id;
10293 
10294 		mark_reg_known_zero(env, regs, BPF_REG_0);
10295 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10296 		if (func_id == BPF_FUNC_kptr_xchg) {
10297 			ret_btf = meta.kptr_field->kptr.btf;
10298 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10299 			if (!btf_is_kernel(ret_btf))
10300 				regs[BPF_REG_0].type |= MEM_ALLOC;
10301 		} else {
10302 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10303 				verbose(env, "verifier internal error:");
10304 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10305 					func_id_name(func_id));
10306 				return -EINVAL;
10307 			}
10308 			ret_btf = btf_vmlinux;
10309 			ret_btf_id = *fn->ret_btf_id;
10310 		}
10311 		if (ret_btf_id == 0) {
10312 			verbose(env, "invalid return type %u of func %s#%d\n",
10313 				base_type(ret_type), func_id_name(func_id),
10314 				func_id);
10315 			return -EINVAL;
10316 		}
10317 		regs[BPF_REG_0].btf = ret_btf;
10318 		regs[BPF_REG_0].btf_id = ret_btf_id;
10319 		break;
10320 	}
10321 	default:
10322 		verbose(env, "unknown return type %u of func %s#%d\n",
10323 			base_type(ret_type), func_id_name(func_id), func_id);
10324 		return -EINVAL;
10325 	}
10326 
10327 	if (type_may_be_null(regs[BPF_REG_0].type))
10328 		regs[BPF_REG_0].id = ++env->id_gen;
10329 
10330 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10331 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10332 			func_id_name(func_id), func_id);
10333 		return -EFAULT;
10334 	}
10335 
10336 	if (is_dynptr_ref_function(func_id))
10337 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10338 
10339 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10340 		/* For release_reference() */
10341 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10342 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10343 		int id = acquire_reference_state(env, insn_idx);
10344 
10345 		if (id < 0)
10346 			return id;
10347 		/* For mark_ptr_or_null_reg() */
10348 		regs[BPF_REG_0].id = id;
10349 		/* For release_reference() */
10350 		regs[BPF_REG_0].ref_obj_id = id;
10351 	}
10352 
10353 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10354 
10355 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10356 	if (err)
10357 		return err;
10358 
10359 	if ((func_id == BPF_FUNC_get_stack ||
10360 	     func_id == BPF_FUNC_get_task_stack) &&
10361 	    !env->prog->has_callchain_buf) {
10362 		const char *err_str;
10363 
10364 #ifdef CONFIG_PERF_EVENTS
10365 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10366 		err_str = "cannot get callchain buffer for func %s#%d\n";
10367 #else
10368 		err = -ENOTSUPP;
10369 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10370 #endif
10371 		if (err) {
10372 			verbose(env, err_str, func_id_name(func_id), func_id);
10373 			return err;
10374 		}
10375 
10376 		env->prog->has_callchain_buf = true;
10377 	}
10378 
10379 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10380 		env->prog->call_get_stack = true;
10381 
10382 	if (func_id == BPF_FUNC_get_func_ip) {
10383 		if (check_get_func_ip(env))
10384 			return -ENOTSUPP;
10385 		env->prog->call_get_func_ip = true;
10386 	}
10387 
10388 	if (changes_data)
10389 		clear_all_pkt_pointers(env);
10390 	return 0;
10391 }
10392 
10393 /* mark_btf_func_reg_size() is used when the reg size is determined by
10394  * the BTF func_proto's return value size and argument.
10395  */
10396 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10397 				   size_t reg_size)
10398 {
10399 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10400 
10401 	if (regno == BPF_REG_0) {
10402 		/* Function return value */
10403 		reg->live |= REG_LIVE_WRITTEN;
10404 		reg->subreg_def = reg_size == sizeof(u64) ?
10405 			DEF_NOT_SUBREG : env->insn_idx + 1;
10406 	} else {
10407 		/* Function argument */
10408 		if (reg_size == sizeof(u64)) {
10409 			mark_insn_zext(env, reg);
10410 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10411 		} else {
10412 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10413 		}
10414 	}
10415 }
10416 
10417 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10418 {
10419 	return meta->kfunc_flags & KF_ACQUIRE;
10420 }
10421 
10422 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10423 {
10424 	return meta->kfunc_flags & KF_RELEASE;
10425 }
10426 
10427 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10428 {
10429 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10430 }
10431 
10432 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10433 {
10434 	return meta->kfunc_flags & KF_SLEEPABLE;
10435 }
10436 
10437 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10438 {
10439 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10440 }
10441 
10442 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10443 {
10444 	return meta->kfunc_flags & KF_RCU;
10445 }
10446 
10447 static bool __kfunc_param_match_suffix(const struct btf *btf,
10448 				       const struct btf_param *arg,
10449 				       const char *suffix)
10450 {
10451 	int suffix_len = strlen(suffix), len;
10452 	const char *param_name;
10453 
10454 	/* In the future, this can be ported to use BTF tagging */
10455 	param_name = btf_name_by_offset(btf, arg->name_off);
10456 	if (str_is_empty(param_name))
10457 		return false;
10458 	len = strlen(param_name);
10459 	if (len < suffix_len)
10460 		return false;
10461 	param_name += len - suffix_len;
10462 	return !strncmp(param_name, suffix, suffix_len);
10463 }
10464 
10465 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10466 				  const struct btf_param *arg,
10467 				  const struct bpf_reg_state *reg)
10468 {
10469 	const struct btf_type *t;
10470 
10471 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10472 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10473 		return false;
10474 
10475 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10476 }
10477 
10478 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10479 					const struct btf_param *arg,
10480 					const struct bpf_reg_state *reg)
10481 {
10482 	const struct btf_type *t;
10483 
10484 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10485 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10486 		return false;
10487 
10488 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10489 }
10490 
10491 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10492 {
10493 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10494 }
10495 
10496 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10497 {
10498 	return __kfunc_param_match_suffix(btf, arg, "__k");
10499 }
10500 
10501 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10502 {
10503 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10504 }
10505 
10506 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10507 {
10508 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10509 }
10510 
10511 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10512 {
10513 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10514 }
10515 
10516 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10517 {
10518 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10519 }
10520 
10521 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10522 					  const struct btf_param *arg,
10523 					  const char *name)
10524 {
10525 	int len, target_len = strlen(name);
10526 	const char *param_name;
10527 
10528 	param_name = btf_name_by_offset(btf, arg->name_off);
10529 	if (str_is_empty(param_name))
10530 		return false;
10531 	len = strlen(param_name);
10532 	if (len != target_len)
10533 		return false;
10534 	if (strcmp(param_name, name))
10535 		return false;
10536 
10537 	return true;
10538 }
10539 
10540 enum {
10541 	KF_ARG_DYNPTR_ID,
10542 	KF_ARG_LIST_HEAD_ID,
10543 	KF_ARG_LIST_NODE_ID,
10544 	KF_ARG_RB_ROOT_ID,
10545 	KF_ARG_RB_NODE_ID,
10546 };
10547 
10548 BTF_ID_LIST(kf_arg_btf_ids)
10549 BTF_ID(struct, bpf_dynptr_kern)
10550 BTF_ID(struct, bpf_list_head)
10551 BTF_ID(struct, bpf_list_node)
10552 BTF_ID(struct, bpf_rb_root)
10553 BTF_ID(struct, bpf_rb_node)
10554 
10555 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10556 				    const struct btf_param *arg, int type)
10557 {
10558 	const struct btf_type *t;
10559 	u32 res_id;
10560 
10561 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10562 	if (!t)
10563 		return false;
10564 	if (!btf_type_is_ptr(t))
10565 		return false;
10566 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10567 	if (!t)
10568 		return false;
10569 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10570 }
10571 
10572 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10573 {
10574 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10575 }
10576 
10577 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10578 {
10579 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10580 }
10581 
10582 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10583 {
10584 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10585 }
10586 
10587 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10588 {
10589 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10590 }
10591 
10592 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10593 {
10594 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10595 }
10596 
10597 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10598 				  const struct btf_param *arg)
10599 {
10600 	const struct btf_type *t;
10601 
10602 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10603 	if (!t)
10604 		return false;
10605 
10606 	return true;
10607 }
10608 
10609 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10610 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10611 					const struct btf *btf,
10612 					const struct btf_type *t, int rec)
10613 {
10614 	const struct btf_type *member_type;
10615 	const struct btf_member *member;
10616 	u32 i;
10617 
10618 	if (!btf_type_is_struct(t))
10619 		return false;
10620 
10621 	for_each_member(i, t, member) {
10622 		const struct btf_array *array;
10623 
10624 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10625 		if (btf_type_is_struct(member_type)) {
10626 			if (rec >= 3) {
10627 				verbose(env, "max struct nesting depth exceeded\n");
10628 				return false;
10629 			}
10630 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10631 				return false;
10632 			continue;
10633 		}
10634 		if (btf_type_is_array(member_type)) {
10635 			array = btf_array(member_type);
10636 			if (!array->nelems)
10637 				return false;
10638 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10639 			if (!btf_type_is_scalar(member_type))
10640 				return false;
10641 			continue;
10642 		}
10643 		if (!btf_type_is_scalar(member_type))
10644 			return false;
10645 	}
10646 	return true;
10647 }
10648 
10649 enum kfunc_ptr_arg_type {
10650 	KF_ARG_PTR_TO_CTX,
10651 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10652 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10653 	KF_ARG_PTR_TO_DYNPTR,
10654 	KF_ARG_PTR_TO_ITER,
10655 	KF_ARG_PTR_TO_LIST_HEAD,
10656 	KF_ARG_PTR_TO_LIST_NODE,
10657 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10658 	KF_ARG_PTR_TO_MEM,
10659 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10660 	KF_ARG_PTR_TO_CALLBACK,
10661 	KF_ARG_PTR_TO_RB_ROOT,
10662 	KF_ARG_PTR_TO_RB_NODE,
10663 };
10664 
10665 enum special_kfunc_type {
10666 	KF_bpf_obj_new_impl,
10667 	KF_bpf_obj_drop_impl,
10668 	KF_bpf_refcount_acquire_impl,
10669 	KF_bpf_list_push_front_impl,
10670 	KF_bpf_list_push_back_impl,
10671 	KF_bpf_list_pop_front,
10672 	KF_bpf_list_pop_back,
10673 	KF_bpf_cast_to_kern_ctx,
10674 	KF_bpf_rdonly_cast,
10675 	KF_bpf_rcu_read_lock,
10676 	KF_bpf_rcu_read_unlock,
10677 	KF_bpf_rbtree_remove,
10678 	KF_bpf_rbtree_add_impl,
10679 	KF_bpf_rbtree_first,
10680 	KF_bpf_dynptr_from_skb,
10681 	KF_bpf_dynptr_from_xdp,
10682 	KF_bpf_dynptr_slice,
10683 	KF_bpf_dynptr_slice_rdwr,
10684 	KF_bpf_dynptr_clone,
10685 };
10686 
10687 BTF_SET_START(special_kfunc_set)
10688 BTF_ID(func, bpf_obj_new_impl)
10689 BTF_ID(func, bpf_obj_drop_impl)
10690 BTF_ID(func, bpf_refcount_acquire_impl)
10691 BTF_ID(func, bpf_list_push_front_impl)
10692 BTF_ID(func, bpf_list_push_back_impl)
10693 BTF_ID(func, bpf_list_pop_front)
10694 BTF_ID(func, bpf_list_pop_back)
10695 BTF_ID(func, bpf_cast_to_kern_ctx)
10696 BTF_ID(func, bpf_rdonly_cast)
10697 BTF_ID(func, bpf_rbtree_remove)
10698 BTF_ID(func, bpf_rbtree_add_impl)
10699 BTF_ID(func, bpf_rbtree_first)
10700 BTF_ID(func, bpf_dynptr_from_skb)
10701 BTF_ID(func, bpf_dynptr_from_xdp)
10702 BTF_ID(func, bpf_dynptr_slice)
10703 BTF_ID(func, bpf_dynptr_slice_rdwr)
10704 BTF_ID(func, bpf_dynptr_clone)
10705 BTF_SET_END(special_kfunc_set)
10706 
10707 BTF_ID_LIST(special_kfunc_list)
10708 BTF_ID(func, bpf_obj_new_impl)
10709 BTF_ID(func, bpf_obj_drop_impl)
10710 BTF_ID(func, bpf_refcount_acquire_impl)
10711 BTF_ID(func, bpf_list_push_front_impl)
10712 BTF_ID(func, bpf_list_push_back_impl)
10713 BTF_ID(func, bpf_list_pop_front)
10714 BTF_ID(func, bpf_list_pop_back)
10715 BTF_ID(func, bpf_cast_to_kern_ctx)
10716 BTF_ID(func, bpf_rdonly_cast)
10717 BTF_ID(func, bpf_rcu_read_lock)
10718 BTF_ID(func, bpf_rcu_read_unlock)
10719 BTF_ID(func, bpf_rbtree_remove)
10720 BTF_ID(func, bpf_rbtree_add_impl)
10721 BTF_ID(func, bpf_rbtree_first)
10722 BTF_ID(func, bpf_dynptr_from_skb)
10723 BTF_ID(func, bpf_dynptr_from_xdp)
10724 BTF_ID(func, bpf_dynptr_slice)
10725 BTF_ID(func, bpf_dynptr_slice_rdwr)
10726 BTF_ID(func, bpf_dynptr_clone)
10727 
10728 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10729 {
10730 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10731 	    meta->arg_owning_ref) {
10732 		return false;
10733 	}
10734 
10735 	return meta->kfunc_flags & KF_RET_NULL;
10736 }
10737 
10738 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10739 {
10740 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10741 }
10742 
10743 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10744 {
10745 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10746 }
10747 
10748 static enum kfunc_ptr_arg_type
10749 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10750 		       struct bpf_kfunc_call_arg_meta *meta,
10751 		       const struct btf_type *t, const struct btf_type *ref_t,
10752 		       const char *ref_tname, const struct btf_param *args,
10753 		       int argno, int nargs)
10754 {
10755 	u32 regno = argno + 1;
10756 	struct bpf_reg_state *regs = cur_regs(env);
10757 	struct bpf_reg_state *reg = &regs[regno];
10758 	bool arg_mem_size = false;
10759 
10760 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10761 		return KF_ARG_PTR_TO_CTX;
10762 
10763 	/* In this function, we verify the kfunc's BTF as per the argument type,
10764 	 * leaving the rest of the verification with respect to the register
10765 	 * type to our caller. When a set of conditions hold in the BTF type of
10766 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10767 	 */
10768 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10769 		return KF_ARG_PTR_TO_CTX;
10770 
10771 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10772 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10773 
10774 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10775 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10776 
10777 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10778 		return KF_ARG_PTR_TO_DYNPTR;
10779 
10780 	if (is_kfunc_arg_iter(meta, argno))
10781 		return KF_ARG_PTR_TO_ITER;
10782 
10783 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10784 		return KF_ARG_PTR_TO_LIST_HEAD;
10785 
10786 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10787 		return KF_ARG_PTR_TO_LIST_NODE;
10788 
10789 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10790 		return KF_ARG_PTR_TO_RB_ROOT;
10791 
10792 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10793 		return KF_ARG_PTR_TO_RB_NODE;
10794 
10795 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10796 		if (!btf_type_is_struct(ref_t)) {
10797 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10798 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10799 			return -EINVAL;
10800 		}
10801 		return KF_ARG_PTR_TO_BTF_ID;
10802 	}
10803 
10804 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10805 		return KF_ARG_PTR_TO_CALLBACK;
10806 
10807 
10808 	if (argno + 1 < nargs &&
10809 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10810 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10811 		arg_mem_size = true;
10812 
10813 	/* This is the catch all argument type of register types supported by
10814 	 * check_helper_mem_access. However, we only allow when argument type is
10815 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10816 	 * arg_mem_size is true, the pointer can be void *.
10817 	 */
10818 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10819 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10820 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10821 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10822 		return -EINVAL;
10823 	}
10824 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10825 }
10826 
10827 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10828 					struct bpf_reg_state *reg,
10829 					const struct btf_type *ref_t,
10830 					const char *ref_tname, u32 ref_id,
10831 					struct bpf_kfunc_call_arg_meta *meta,
10832 					int argno)
10833 {
10834 	const struct btf_type *reg_ref_t;
10835 	bool strict_type_match = false;
10836 	const struct btf *reg_btf;
10837 	const char *reg_ref_tname;
10838 	u32 reg_ref_id;
10839 
10840 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10841 		reg_btf = reg->btf;
10842 		reg_ref_id = reg->btf_id;
10843 	} else {
10844 		reg_btf = btf_vmlinux;
10845 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10846 	}
10847 
10848 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10849 	 * or releasing a reference, or are no-cast aliases. We do _not_
10850 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10851 	 * as we want to enable BPF programs to pass types that are bitwise
10852 	 * equivalent without forcing them to explicitly cast with something
10853 	 * like bpf_cast_to_kern_ctx().
10854 	 *
10855 	 * For example, say we had a type like the following:
10856 	 *
10857 	 * struct bpf_cpumask {
10858 	 *	cpumask_t cpumask;
10859 	 *	refcount_t usage;
10860 	 * };
10861 	 *
10862 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10863 	 * to a struct cpumask, so it would be safe to pass a struct
10864 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10865 	 *
10866 	 * The philosophy here is similar to how we allow scalars of different
10867 	 * types to be passed to kfuncs as long as the size is the same. The
10868 	 * only difference here is that we're simply allowing
10869 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10870 	 * resolve types.
10871 	 */
10872 	if (is_kfunc_acquire(meta) ||
10873 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10874 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10875 		strict_type_match = true;
10876 
10877 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10878 
10879 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10880 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10881 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10882 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10883 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10884 			btf_type_str(reg_ref_t), reg_ref_tname);
10885 		return -EINVAL;
10886 	}
10887 	return 0;
10888 }
10889 
10890 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10891 {
10892 	struct bpf_verifier_state *state = env->cur_state;
10893 	struct btf_record *rec = reg_btf_record(reg);
10894 
10895 	if (!state->active_lock.ptr) {
10896 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10897 		return -EFAULT;
10898 	}
10899 
10900 	if (type_flag(reg->type) & NON_OWN_REF) {
10901 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10902 		return -EFAULT;
10903 	}
10904 
10905 	reg->type |= NON_OWN_REF;
10906 	if (rec->refcount_off >= 0)
10907 		reg->type |= MEM_RCU;
10908 
10909 	return 0;
10910 }
10911 
10912 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10913 {
10914 	struct bpf_func_state *state, *unused;
10915 	struct bpf_reg_state *reg;
10916 	int i;
10917 
10918 	state = cur_func(env);
10919 
10920 	if (!ref_obj_id) {
10921 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10922 			     "owning -> non-owning conversion\n");
10923 		return -EFAULT;
10924 	}
10925 
10926 	for (i = 0; i < state->acquired_refs; i++) {
10927 		if (state->refs[i].id != ref_obj_id)
10928 			continue;
10929 
10930 		/* Clear ref_obj_id here so release_reference doesn't clobber
10931 		 * the whole reg
10932 		 */
10933 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10934 			if (reg->ref_obj_id == ref_obj_id) {
10935 				reg->ref_obj_id = 0;
10936 				ref_set_non_owning(env, reg);
10937 			}
10938 		}));
10939 		return 0;
10940 	}
10941 
10942 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10943 	return -EFAULT;
10944 }
10945 
10946 /* Implementation details:
10947  *
10948  * Each register points to some region of memory, which we define as an
10949  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10950  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10951  * allocation. The lock and the data it protects are colocated in the same
10952  * memory region.
10953  *
10954  * Hence, everytime a register holds a pointer value pointing to such
10955  * allocation, the verifier preserves a unique reg->id for it.
10956  *
10957  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10958  * bpf_spin_lock is called.
10959  *
10960  * To enable this, lock state in the verifier captures two values:
10961  *	active_lock.ptr = Register's type specific pointer
10962  *	active_lock.id  = A unique ID for each register pointer value
10963  *
10964  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10965  * supported register types.
10966  *
10967  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10968  * allocated objects is the reg->btf pointer.
10969  *
10970  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10971  * can establish the provenance of the map value statically for each distinct
10972  * lookup into such maps. They always contain a single map value hence unique
10973  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10974  *
10975  * So, in case of global variables, they use array maps with max_entries = 1,
10976  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10977  * into the same map value as max_entries is 1, as described above).
10978  *
10979  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10980  * outer map pointer (in verifier context), but each lookup into an inner map
10981  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10982  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10983  * will get different reg->id assigned to each lookup, hence different
10984  * active_lock.id.
10985  *
10986  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10987  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10988  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10989  */
10990 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10991 {
10992 	void *ptr;
10993 	u32 id;
10994 
10995 	switch ((int)reg->type) {
10996 	case PTR_TO_MAP_VALUE:
10997 		ptr = reg->map_ptr;
10998 		break;
10999 	case PTR_TO_BTF_ID | MEM_ALLOC:
11000 		ptr = reg->btf;
11001 		break;
11002 	default:
11003 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11004 		return -EFAULT;
11005 	}
11006 	id = reg->id;
11007 
11008 	if (!env->cur_state->active_lock.ptr)
11009 		return -EINVAL;
11010 	if (env->cur_state->active_lock.ptr != ptr ||
11011 	    env->cur_state->active_lock.id != id) {
11012 		verbose(env, "held lock and object are not in the same allocation\n");
11013 		return -EINVAL;
11014 	}
11015 	return 0;
11016 }
11017 
11018 static bool is_bpf_list_api_kfunc(u32 btf_id)
11019 {
11020 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11021 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11022 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11023 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11024 }
11025 
11026 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11027 {
11028 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11029 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11030 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11031 }
11032 
11033 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11034 {
11035 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11036 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11037 }
11038 
11039 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11040 {
11041 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11042 }
11043 
11044 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11045 {
11046 	return is_bpf_rbtree_api_kfunc(btf_id);
11047 }
11048 
11049 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11050 					  enum btf_field_type head_field_type,
11051 					  u32 kfunc_btf_id)
11052 {
11053 	bool ret;
11054 
11055 	switch (head_field_type) {
11056 	case BPF_LIST_HEAD:
11057 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11058 		break;
11059 	case BPF_RB_ROOT:
11060 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11061 		break;
11062 	default:
11063 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11064 			btf_field_type_name(head_field_type));
11065 		return false;
11066 	}
11067 
11068 	if (!ret)
11069 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11070 			btf_field_type_name(head_field_type));
11071 	return ret;
11072 }
11073 
11074 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11075 					  enum btf_field_type node_field_type,
11076 					  u32 kfunc_btf_id)
11077 {
11078 	bool ret;
11079 
11080 	switch (node_field_type) {
11081 	case BPF_LIST_NODE:
11082 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11083 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11084 		break;
11085 	case BPF_RB_NODE:
11086 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11087 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11088 		break;
11089 	default:
11090 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11091 			btf_field_type_name(node_field_type));
11092 		return false;
11093 	}
11094 
11095 	if (!ret)
11096 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11097 			btf_field_type_name(node_field_type));
11098 	return ret;
11099 }
11100 
11101 static int
11102 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11103 				   struct bpf_reg_state *reg, u32 regno,
11104 				   struct bpf_kfunc_call_arg_meta *meta,
11105 				   enum btf_field_type head_field_type,
11106 				   struct btf_field **head_field)
11107 {
11108 	const char *head_type_name;
11109 	struct btf_field *field;
11110 	struct btf_record *rec;
11111 	u32 head_off;
11112 
11113 	if (meta->btf != btf_vmlinux) {
11114 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11115 		return -EFAULT;
11116 	}
11117 
11118 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11119 		return -EFAULT;
11120 
11121 	head_type_name = btf_field_type_name(head_field_type);
11122 	if (!tnum_is_const(reg->var_off)) {
11123 		verbose(env,
11124 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11125 			regno, head_type_name);
11126 		return -EINVAL;
11127 	}
11128 
11129 	rec = reg_btf_record(reg);
11130 	head_off = reg->off + reg->var_off.value;
11131 	field = btf_record_find(rec, head_off, head_field_type);
11132 	if (!field) {
11133 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11134 		return -EINVAL;
11135 	}
11136 
11137 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11138 	if (check_reg_allocation_locked(env, reg)) {
11139 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11140 			rec->spin_lock_off, head_type_name);
11141 		return -EINVAL;
11142 	}
11143 
11144 	if (*head_field) {
11145 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11146 		return -EFAULT;
11147 	}
11148 	*head_field = field;
11149 	return 0;
11150 }
11151 
11152 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11153 					   struct bpf_reg_state *reg, u32 regno,
11154 					   struct bpf_kfunc_call_arg_meta *meta)
11155 {
11156 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11157 							  &meta->arg_list_head.field);
11158 }
11159 
11160 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11161 					     struct bpf_reg_state *reg, u32 regno,
11162 					     struct bpf_kfunc_call_arg_meta *meta)
11163 {
11164 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11165 							  &meta->arg_rbtree_root.field);
11166 }
11167 
11168 static int
11169 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11170 				   struct bpf_reg_state *reg, u32 regno,
11171 				   struct bpf_kfunc_call_arg_meta *meta,
11172 				   enum btf_field_type head_field_type,
11173 				   enum btf_field_type node_field_type,
11174 				   struct btf_field **node_field)
11175 {
11176 	const char *node_type_name;
11177 	const struct btf_type *et, *t;
11178 	struct btf_field *field;
11179 	u32 node_off;
11180 
11181 	if (meta->btf != btf_vmlinux) {
11182 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11183 		return -EFAULT;
11184 	}
11185 
11186 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11187 		return -EFAULT;
11188 
11189 	node_type_name = btf_field_type_name(node_field_type);
11190 	if (!tnum_is_const(reg->var_off)) {
11191 		verbose(env,
11192 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11193 			regno, node_type_name);
11194 		return -EINVAL;
11195 	}
11196 
11197 	node_off = reg->off + reg->var_off.value;
11198 	field = reg_find_field_offset(reg, node_off, node_field_type);
11199 	if (!field || field->offset != node_off) {
11200 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11201 		return -EINVAL;
11202 	}
11203 
11204 	field = *node_field;
11205 
11206 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11207 	t = btf_type_by_id(reg->btf, reg->btf_id);
11208 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11209 				  field->graph_root.value_btf_id, true)) {
11210 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11211 			"in struct %s, but arg is at offset=%d in struct %s\n",
11212 			btf_field_type_name(head_field_type),
11213 			btf_field_type_name(node_field_type),
11214 			field->graph_root.node_offset,
11215 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11216 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11217 		return -EINVAL;
11218 	}
11219 	meta->arg_btf = reg->btf;
11220 	meta->arg_btf_id = reg->btf_id;
11221 
11222 	if (node_off != field->graph_root.node_offset) {
11223 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11224 			node_off, 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 		return -EINVAL;
11228 	}
11229 
11230 	return 0;
11231 }
11232 
11233 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11234 					   struct bpf_reg_state *reg, u32 regno,
11235 					   struct bpf_kfunc_call_arg_meta *meta)
11236 {
11237 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11238 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11239 						  &meta->arg_list_head.field);
11240 }
11241 
11242 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11243 					     struct bpf_reg_state *reg, u32 regno,
11244 					     struct bpf_kfunc_call_arg_meta *meta)
11245 {
11246 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11247 						  BPF_RB_ROOT, BPF_RB_NODE,
11248 						  &meta->arg_rbtree_root.field);
11249 }
11250 
11251 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11252 			    int insn_idx)
11253 {
11254 	const char *func_name = meta->func_name, *ref_tname;
11255 	const struct btf *btf = meta->btf;
11256 	const struct btf_param *args;
11257 	struct btf_record *rec;
11258 	u32 i, nargs;
11259 	int ret;
11260 
11261 	args = (const struct btf_param *)(meta->func_proto + 1);
11262 	nargs = btf_type_vlen(meta->func_proto);
11263 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11264 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11265 			MAX_BPF_FUNC_REG_ARGS);
11266 		return -EINVAL;
11267 	}
11268 
11269 	/* Check that BTF function arguments match actual types that the
11270 	 * verifier sees.
11271 	 */
11272 	for (i = 0; i < nargs; i++) {
11273 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11274 		const struct btf_type *t, *ref_t, *resolve_ret;
11275 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11276 		u32 regno = i + 1, ref_id, type_size;
11277 		bool is_ret_buf_sz = false;
11278 		int kf_arg_type;
11279 
11280 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11281 
11282 		if (is_kfunc_arg_ignore(btf, &args[i]))
11283 			continue;
11284 
11285 		if (btf_type_is_scalar(t)) {
11286 			if (reg->type != SCALAR_VALUE) {
11287 				verbose(env, "R%d is not a scalar\n", regno);
11288 				return -EINVAL;
11289 			}
11290 
11291 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11292 				if (meta->arg_constant.found) {
11293 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11294 					return -EFAULT;
11295 				}
11296 				if (!tnum_is_const(reg->var_off)) {
11297 					verbose(env, "R%d must be a known constant\n", regno);
11298 					return -EINVAL;
11299 				}
11300 				ret = mark_chain_precision(env, regno);
11301 				if (ret < 0)
11302 					return ret;
11303 				meta->arg_constant.found = true;
11304 				meta->arg_constant.value = reg->var_off.value;
11305 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11306 				meta->r0_rdonly = true;
11307 				is_ret_buf_sz = true;
11308 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11309 				is_ret_buf_sz = true;
11310 			}
11311 
11312 			if (is_ret_buf_sz) {
11313 				if (meta->r0_size) {
11314 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11315 					return -EINVAL;
11316 				}
11317 
11318 				if (!tnum_is_const(reg->var_off)) {
11319 					verbose(env, "R%d is not a const\n", regno);
11320 					return -EINVAL;
11321 				}
11322 
11323 				meta->r0_size = reg->var_off.value;
11324 				ret = mark_chain_precision(env, regno);
11325 				if (ret)
11326 					return ret;
11327 			}
11328 			continue;
11329 		}
11330 
11331 		if (!btf_type_is_ptr(t)) {
11332 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11333 			return -EINVAL;
11334 		}
11335 
11336 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11337 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11338 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11339 			return -EACCES;
11340 		}
11341 
11342 		if (reg->ref_obj_id) {
11343 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11344 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11345 					regno, reg->ref_obj_id,
11346 					meta->ref_obj_id);
11347 				return -EFAULT;
11348 			}
11349 			meta->ref_obj_id = reg->ref_obj_id;
11350 			if (is_kfunc_release(meta))
11351 				meta->release_regno = regno;
11352 		}
11353 
11354 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11355 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11356 
11357 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11358 		if (kf_arg_type < 0)
11359 			return kf_arg_type;
11360 
11361 		switch (kf_arg_type) {
11362 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11363 		case KF_ARG_PTR_TO_BTF_ID:
11364 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11365 				break;
11366 
11367 			if (!is_trusted_reg(reg)) {
11368 				if (!is_kfunc_rcu(meta)) {
11369 					verbose(env, "R%d must be referenced or trusted\n", regno);
11370 					return -EINVAL;
11371 				}
11372 				if (!is_rcu_reg(reg)) {
11373 					verbose(env, "R%d must be a rcu pointer\n", regno);
11374 					return -EINVAL;
11375 				}
11376 			}
11377 
11378 			fallthrough;
11379 		case KF_ARG_PTR_TO_CTX:
11380 			/* Trusted arguments have the same offset checks as release arguments */
11381 			arg_type |= OBJ_RELEASE;
11382 			break;
11383 		case KF_ARG_PTR_TO_DYNPTR:
11384 		case KF_ARG_PTR_TO_ITER:
11385 		case KF_ARG_PTR_TO_LIST_HEAD:
11386 		case KF_ARG_PTR_TO_LIST_NODE:
11387 		case KF_ARG_PTR_TO_RB_ROOT:
11388 		case KF_ARG_PTR_TO_RB_NODE:
11389 		case KF_ARG_PTR_TO_MEM:
11390 		case KF_ARG_PTR_TO_MEM_SIZE:
11391 		case KF_ARG_PTR_TO_CALLBACK:
11392 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11393 			/* Trusted by default */
11394 			break;
11395 		default:
11396 			WARN_ON_ONCE(1);
11397 			return -EFAULT;
11398 		}
11399 
11400 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11401 			arg_type |= OBJ_RELEASE;
11402 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11403 		if (ret < 0)
11404 			return ret;
11405 
11406 		switch (kf_arg_type) {
11407 		case KF_ARG_PTR_TO_CTX:
11408 			if (reg->type != PTR_TO_CTX) {
11409 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11410 				return -EINVAL;
11411 			}
11412 
11413 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11414 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11415 				if (ret < 0)
11416 					return -EINVAL;
11417 				meta->ret_btf_id  = ret;
11418 			}
11419 			break;
11420 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11421 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11422 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11423 				return -EINVAL;
11424 			}
11425 			if (!reg->ref_obj_id) {
11426 				verbose(env, "allocated object must be referenced\n");
11427 				return -EINVAL;
11428 			}
11429 			if (meta->btf == btf_vmlinux &&
11430 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11431 				meta->arg_btf = reg->btf;
11432 				meta->arg_btf_id = reg->btf_id;
11433 			}
11434 			break;
11435 		case KF_ARG_PTR_TO_DYNPTR:
11436 		{
11437 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11438 			int clone_ref_obj_id = 0;
11439 
11440 			if (reg->type != PTR_TO_STACK &&
11441 			    reg->type != CONST_PTR_TO_DYNPTR) {
11442 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11443 				return -EINVAL;
11444 			}
11445 
11446 			if (reg->type == CONST_PTR_TO_DYNPTR)
11447 				dynptr_arg_type |= MEM_RDONLY;
11448 
11449 			if (is_kfunc_arg_uninit(btf, &args[i]))
11450 				dynptr_arg_type |= MEM_UNINIT;
11451 
11452 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11453 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11454 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11455 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11456 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11457 				   (dynptr_arg_type & MEM_UNINIT)) {
11458 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11459 
11460 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11461 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11462 					return -EFAULT;
11463 				}
11464 
11465 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11466 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11467 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11468 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11469 					return -EFAULT;
11470 				}
11471 			}
11472 
11473 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11474 			if (ret < 0)
11475 				return ret;
11476 
11477 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11478 				int id = dynptr_id(env, reg);
11479 
11480 				if (id < 0) {
11481 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11482 					return id;
11483 				}
11484 				meta->initialized_dynptr.id = id;
11485 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11486 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11487 			}
11488 
11489 			break;
11490 		}
11491 		case KF_ARG_PTR_TO_ITER:
11492 			ret = process_iter_arg(env, regno, insn_idx, meta);
11493 			if (ret < 0)
11494 				return ret;
11495 			break;
11496 		case KF_ARG_PTR_TO_LIST_HEAD:
11497 			if (reg->type != PTR_TO_MAP_VALUE &&
11498 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11499 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11500 				return -EINVAL;
11501 			}
11502 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11503 				verbose(env, "allocated object must be referenced\n");
11504 				return -EINVAL;
11505 			}
11506 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11507 			if (ret < 0)
11508 				return ret;
11509 			break;
11510 		case KF_ARG_PTR_TO_RB_ROOT:
11511 			if (reg->type != PTR_TO_MAP_VALUE &&
11512 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11513 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11514 				return -EINVAL;
11515 			}
11516 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11517 				verbose(env, "allocated object must be referenced\n");
11518 				return -EINVAL;
11519 			}
11520 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11521 			if (ret < 0)
11522 				return ret;
11523 			break;
11524 		case KF_ARG_PTR_TO_LIST_NODE:
11525 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11526 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11527 				return -EINVAL;
11528 			}
11529 			if (!reg->ref_obj_id) {
11530 				verbose(env, "allocated object must be referenced\n");
11531 				return -EINVAL;
11532 			}
11533 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11534 			if (ret < 0)
11535 				return ret;
11536 			break;
11537 		case KF_ARG_PTR_TO_RB_NODE:
11538 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11539 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11540 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11541 					return -EINVAL;
11542 				}
11543 				if (in_rbtree_lock_required_cb(env)) {
11544 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11545 					return -EINVAL;
11546 				}
11547 			} else {
11548 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11549 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11550 					return -EINVAL;
11551 				}
11552 				if (!reg->ref_obj_id) {
11553 					verbose(env, "allocated object must be referenced\n");
11554 					return -EINVAL;
11555 				}
11556 			}
11557 
11558 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11559 			if (ret < 0)
11560 				return ret;
11561 			break;
11562 		case KF_ARG_PTR_TO_BTF_ID:
11563 			/* Only base_type is checked, further checks are done here */
11564 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11565 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11566 			    !reg2btf_ids[base_type(reg->type)]) {
11567 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11568 				verbose(env, "expected %s or socket\n",
11569 					reg_type_str(env, base_type(reg->type) |
11570 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11571 				return -EINVAL;
11572 			}
11573 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11574 			if (ret < 0)
11575 				return ret;
11576 			break;
11577 		case KF_ARG_PTR_TO_MEM:
11578 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11579 			if (IS_ERR(resolve_ret)) {
11580 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11581 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11582 				return -EINVAL;
11583 			}
11584 			ret = check_mem_reg(env, reg, regno, type_size);
11585 			if (ret < 0)
11586 				return ret;
11587 			break;
11588 		case KF_ARG_PTR_TO_MEM_SIZE:
11589 		{
11590 			struct bpf_reg_state *buff_reg = &regs[regno];
11591 			const struct btf_param *buff_arg = &args[i];
11592 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11593 			const struct btf_param *size_arg = &args[i + 1];
11594 
11595 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11596 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11597 				if (ret < 0) {
11598 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11599 					return ret;
11600 				}
11601 			}
11602 
11603 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11604 				if (meta->arg_constant.found) {
11605 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11606 					return -EFAULT;
11607 				}
11608 				if (!tnum_is_const(size_reg->var_off)) {
11609 					verbose(env, "R%d must be a known constant\n", regno + 1);
11610 					return -EINVAL;
11611 				}
11612 				meta->arg_constant.found = true;
11613 				meta->arg_constant.value = size_reg->var_off.value;
11614 			}
11615 
11616 			/* Skip next '__sz' or '__szk' argument */
11617 			i++;
11618 			break;
11619 		}
11620 		case KF_ARG_PTR_TO_CALLBACK:
11621 			if (reg->type != PTR_TO_FUNC) {
11622 				verbose(env, "arg%d expected pointer to func\n", i);
11623 				return -EINVAL;
11624 			}
11625 			meta->subprogno = reg->subprogno;
11626 			break;
11627 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11628 			if (!type_is_ptr_alloc_obj(reg->type)) {
11629 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11630 				return -EINVAL;
11631 			}
11632 			if (!type_is_non_owning_ref(reg->type))
11633 				meta->arg_owning_ref = true;
11634 
11635 			rec = reg_btf_record(reg);
11636 			if (!rec) {
11637 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11638 				return -EFAULT;
11639 			}
11640 
11641 			if (rec->refcount_off < 0) {
11642 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11643 				return -EINVAL;
11644 			}
11645 
11646 			meta->arg_btf = reg->btf;
11647 			meta->arg_btf_id = reg->btf_id;
11648 			break;
11649 		}
11650 	}
11651 
11652 	if (is_kfunc_release(meta) && !meta->release_regno) {
11653 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11654 			func_name);
11655 		return -EINVAL;
11656 	}
11657 
11658 	return 0;
11659 }
11660 
11661 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11662 			    struct bpf_insn *insn,
11663 			    struct bpf_kfunc_call_arg_meta *meta,
11664 			    const char **kfunc_name)
11665 {
11666 	const struct btf_type *func, *func_proto;
11667 	u32 func_id, *kfunc_flags;
11668 	const char *func_name;
11669 	struct btf *desc_btf;
11670 
11671 	if (kfunc_name)
11672 		*kfunc_name = NULL;
11673 
11674 	if (!insn->imm)
11675 		return -EINVAL;
11676 
11677 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11678 	if (IS_ERR(desc_btf))
11679 		return PTR_ERR(desc_btf);
11680 
11681 	func_id = insn->imm;
11682 	func = btf_type_by_id(desc_btf, func_id);
11683 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11684 	if (kfunc_name)
11685 		*kfunc_name = func_name;
11686 	func_proto = btf_type_by_id(desc_btf, func->type);
11687 
11688 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11689 	if (!kfunc_flags) {
11690 		return -EACCES;
11691 	}
11692 
11693 	memset(meta, 0, sizeof(*meta));
11694 	meta->btf = desc_btf;
11695 	meta->func_id = func_id;
11696 	meta->kfunc_flags = *kfunc_flags;
11697 	meta->func_proto = func_proto;
11698 	meta->func_name = func_name;
11699 
11700 	return 0;
11701 }
11702 
11703 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11704 			    int *insn_idx_p)
11705 {
11706 	const struct btf_type *t, *ptr_type;
11707 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11708 	struct bpf_reg_state *regs = cur_regs(env);
11709 	const char *func_name, *ptr_type_name;
11710 	bool sleepable, rcu_lock, rcu_unlock;
11711 	struct bpf_kfunc_call_arg_meta meta;
11712 	struct bpf_insn_aux_data *insn_aux;
11713 	int err, insn_idx = *insn_idx_p;
11714 	const struct btf_param *args;
11715 	const struct btf_type *ret_t;
11716 	struct btf *desc_btf;
11717 
11718 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11719 	if (!insn->imm)
11720 		return 0;
11721 
11722 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11723 	if (err == -EACCES && func_name)
11724 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11725 	if (err)
11726 		return err;
11727 	desc_btf = meta.btf;
11728 	insn_aux = &env->insn_aux_data[insn_idx];
11729 
11730 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11731 
11732 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11733 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11734 		return -EACCES;
11735 	}
11736 
11737 	sleepable = is_kfunc_sleepable(&meta);
11738 	if (sleepable && !env->prog->aux->sleepable) {
11739 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11740 		return -EACCES;
11741 	}
11742 
11743 	/* Check the arguments */
11744 	err = check_kfunc_args(env, &meta, insn_idx);
11745 	if (err < 0)
11746 		return err;
11747 
11748 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11749 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11750 					 set_rbtree_add_callback_state);
11751 		if (err) {
11752 			verbose(env, "kfunc %s#%d failed callback verification\n",
11753 				func_name, meta.func_id);
11754 			return err;
11755 		}
11756 	}
11757 
11758 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11759 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11760 
11761 	if (env->cur_state->active_rcu_lock) {
11762 		struct bpf_func_state *state;
11763 		struct bpf_reg_state *reg;
11764 
11765 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11766 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11767 			return -EACCES;
11768 		}
11769 
11770 		if (rcu_lock) {
11771 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11772 			return -EINVAL;
11773 		} else if (rcu_unlock) {
11774 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11775 				if (reg->type & MEM_RCU) {
11776 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11777 					reg->type |= PTR_UNTRUSTED;
11778 				}
11779 			}));
11780 			env->cur_state->active_rcu_lock = false;
11781 		} else if (sleepable) {
11782 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11783 			return -EACCES;
11784 		}
11785 	} else if (rcu_lock) {
11786 		env->cur_state->active_rcu_lock = true;
11787 	} else if (rcu_unlock) {
11788 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11789 		return -EINVAL;
11790 	}
11791 
11792 	/* In case of release function, we get register number of refcounted
11793 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11794 	 */
11795 	if (meta.release_regno) {
11796 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11797 		if (err) {
11798 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11799 				func_name, meta.func_id);
11800 			return err;
11801 		}
11802 	}
11803 
11804 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11805 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11806 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11807 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11808 		insn_aux->insert_off = regs[BPF_REG_2].off;
11809 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11810 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11811 		if (err) {
11812 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11813 				func_name, meta.func_id);
11814 			return err;
11815 		}
11816 
11817 		err = release_reference(env, release_ref_obj_id);
11818 		if (err) {
11819 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11820 				func_name, meta.func_id);
11821 			return err;
11822 		}
11823 	}
11824 
11825 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11826 		mark_reg_not_init(env, regs, caller_saved[i]);
11827 
11828 	/* Check return type */
11829 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11830 
11831 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11832 		/* Only exception is bpf_obj_new_impl */
11833 		if (meta.btf != btf_vmlinux ||
11834 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11835 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11836 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11837 			return -EINVAL;
11838 		}
11839 	}
11840 
11841 	if (btf_type_is_scalar(t)) {
11842 		mark_reg_unknown(env, regs, BPF_REG_0);
11843 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11844 	} else if (btf_type_is_ptr(t)) {
11845 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11846 
11847 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11848 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11849 				struct btf *ret_btf;
11850 				u32 ret_btf_id;
11851 
11852 				if (unlikely(!bpf_global_ma_set))
11853 					return -ENOMEM;
11854 
11855 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11856 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11857 					return -EINVAL;
11858 				}
11859 
11860 				ret_btf = env->prog->aux->btf;
11861 				ret_btf_id = meta.arg_constant.value;
11862 
11863 				/* This may be NULL due to user not supplying a BTF */
11864 				if (!ret_btf) {
11865 					verbose(env, "bpf_obj_new requires prog BTF\n");
11866 					return -EINVAL;
11867 				}
11868 
11869 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11870 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11871 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11872 					return -EINVAL;
11873 				}
11874 
11875 				mark_reg_known_zero(env, regs, BPF_REG_0);
11876 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11877 				regs[BPF_REG_0].btf = ret_btf;
11878 				regs[BPF_REG_0].btf_id = ret_btf_id;
11879 
11880 				insn_aux->obj_new_size = ret_t->size;
11881 				insn_aux->kptr_struct_meta =
11882 					btf_find_struct_meta(ret_btf, ret_btf_id);
11883 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11884 				mark_reg_known_zero(env, regs, BPF_REG_0);
11885 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11886 				regs[BPF_REG_0].btf = meta.arg_btf;
11887 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11888 
11889 				insn_aux->kptr_struct_meta =
11890 					btf_find_struct_meta(meta.arg_btf,
11891 							     meta.arg_btf_id);
11892 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11893 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11894 				struct btf_field *field = meta.arg_list_head.field;
11895 
11896 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11897 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11898 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11899 				struct btf_field *field = meta.arg_rbtree_root.field;
11900 
11901 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11902 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11903 				mark_reg_known_zero(env, regs, BPF_REG_0);
11904 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11905 				regs[BPF_REG_0].btf = desc_btf;
11906 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11907 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11908 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11909 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11910 					verbose(env,
11911 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11912 					return -EINVAL;
11913 				}
11914 
11915 				mark_reg_known_zero(env, regs, BPF_REG_0);
11916 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11917 				regs[BPF_REG_0].btf = desc_btf;
11918 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11919 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11920 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11921 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11922 
11923 				mark_reg_known_zero(env, regs, BPF_REG_0);
11924 
11925 				if (!meta.arg_constant.found) {
11926 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11927 					return -EFAULT;
11928 				}
11929 
11930 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11931 
11932 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11933 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11934 
11935 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11936 					regs[BPF_REG_0].type |= MEM_RDONLY;
11937 				} else {
11938 					/* this will set env->seen_direct_write to true */
11939 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11940 						verbose(env, "the prog does not allow writes to packet data\n");
11941 						return -EINVAL;
11942 					}
11943 				}
11944 
11945 				if (!meta.initialized_dynptr.id) {
11946 					verbose(env, "verifier internal error: no dynptr id\n");
11947 					return -EFAULT;
11948 				}
11949 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11950 
11951 				/* we don't need to set BPF_REG_0's ref obj id
11952 				 * because packet slices are not refcounted (see
11953 				 * dynptr_type_refcounted)
11954 				 */
11955 			} else {
11956 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11957 					meta.func_name);
11958 				return -EFAULT;
11959 			}
11960 		} else if (!__btf_type_is_struct(ptr_type)) {
11961 			if (!meta.r0_size) {
11962 				__u32 sz;
11963 
11964 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11965 					meta.r0_size = sz;
11966 					meta.r0_rdonly = true;
11967 				}
11968 			}
11969 			if (!meta.r0_size) {
11970 				ptr_type_name = btf_name_by_offset(desc_btf,
11971 								   ptr_type->name_off);
11972 				verbose(env,
11973 					"kernel function %s returns pointer type %s %s is not supported\n",
11974 					func_name,
11975 					btf_type_str(ptr_type),
11976 					ptr_type_name);
11977 				return -EINVAL;
11978 			}
11979 
11980 			mark_reg_known_zero(env, regs, BPF_REG_0);
11981 			regs[BPF_REG_0].type = PTR_TO_MEM;
11982 			regs[BPF_REG_0].mem_size = meta.r0_size;
11983 
11984 			if (meta.r0_rdonly)
11985 				regs[BPF_REG_0].type |= MEM_RDONLY;
11986 
11987 			/* Ensures we don't access the memory after a release_reference() */
11988 			if (meta.ref_obj_id)
11989 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11990 		} else {
11991 			mark_reg_known_zero(env, regs, BPF_REG_0);
11992 			regs[BPF_REG_0].btf = desc_btf;
11993 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11994 			regs[BPF_REG_0].btf_id = ptr_type_id;
11995 		}
11996 
11997 		if (is_kfunc_ret_null(&meta)) {
11998 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11999 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12000 			regs[BPF_REG_0].id = ++env->id_gen;
12001 		}
12002 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12003 		if (is_kfunc_acquire(&meta)) {
12004 			int id = acquire_reference_state(env, insn_idx);
12005 
12006 			if (id < 0)
12007 				return id;
12008 			if (is_kfunc_ret_null(&meta))
12009 				regs[BPF_REG_0].id = id;
12010 			regs[BPF_REG_0].ref_obj_id = id;
12011 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12012 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12013 		}
12014 
12015 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12016 			regs[BPF_REG_0].id = ++env->id_gen;
12017 	} else if (btf_type_is_void(t)) {
12018 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12019 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12020 				insn_aux->kptr_struct_meta =
12021 					btf_find_struct_meta(meta.arg_btf,
12022 							     meta.arg_btf_id);
12023 			}
12024 		}
12025 	}
12026 
12027 	nargs = btf_type_vlen(meta.func_proto);
12028 	args = (const struct btf_param *)(meta.func_proto + 1);
12029 	for (i = 0; i < nargs; i++) {
12030 		u32 regno = i + 1;
12031 
12032 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12033 		if (btf_type_is_ptr(t))
12034 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12035 		else
12036 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12037 			mark_btf_func_reg_size(env, regno, t->size);
12038 	}
12039 
12040 	if (is_iter_next_kfunc(&meta)) {
12041 		err = process_iter_next_call(env, insn_idx, &meta);
12042 		if (err)
12043 			return err;
12044 	}
12045 
12046 	return 0;
12047 }
12048 
12049 static bool signed_add_overflows(s64 a, s64 b)
12050 {
12051 	/* Do the add in u64, where overflow is well-defined */
12052 	s64 res = (s64)((u64)a + (u64)b);
12053 
12054 	if (b < 0)
12055 		return res > a;
12056 	return res < a;
12057 }
12058 
12059 static bool signed_add32_overflows(s32 a, s32 b)
12060 {
12061 	/* Do the add in u32, where overflow is well-defined */
12062 	s32 res = (s32)((u32)a + (u32)b);
12063 
12064 	if (b < 0)
12065 		return res > a;
12066 	return res < a;
12067 }
12068 
12069 static bool signed_sub_overflows(s64 a, s64 b)
12070 {
12071 	/* Do the sub in u64, where overflow is well-defined */
12072 	s64 res = (s64)((u64)a - (u64)b);
12073 
12074 	if (b < 0)
12075 		return res < a;
12076 	return res > a;
12077 }
12078 
12079 static bool signed_sub32_overflows(s32 a, s32 b)
12080 {
12081 	/* Do the sub in u32, where overflow is well-defined */
12082 	s32 res = (s32)((u32)a - (u32)b);
12083 
12084 	if (b < 0)
12085 		return res < a;
12086 	return res > a;
12087 }
12088 
12089 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12090 				  const struct bpf_reg_state *reg,
12091 				  enum bpf_reg_type type)
12092 {
12093 	bool known = tnum_is_const(reg->var_off);
12094 	s64 val = reg->var_off.value;
12095 	s64 smin = reg->smin_value;
12096 
12097 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12098 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12099 			reg_type_str(env, type), val);
12100 		return false;
12101 	}
12102 
12103 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12104 		verbose(env, "%s pointer offset %d is not allowed\n",
12105 			reg_type_str(env, type), reg->off);
12106 		return false;
12107 	}
12108 
12109 	if (smin == S64_MIN) {
12110 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12111 			reg_type_str(env, type));
12112 		return false;
12113 	}
12114 
12115 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12116 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12117 			smin, reg_type_str(env, type));
12118 		return false;
12119 	}
12120 
12121 	return true;
12122 }
12123 
12124 enum {
12125 	REASON_BOUNDS	= -1,
12126 	REASON_TYPE	= -2,
12127 	REASON_PATHS	= -3,
12128 	REASON_LIMIT	= -4,
12129 	REASON_STACK	= -5,
12130 };
12131 
12132 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12133 			      u32 *alu_limit, bool mask_to_left)
12134 {
12135 	u32 max = 0, ptr_limit = 0;
12136 
12137 	switch (ptr_reg->type) {
12138 	case PTR_TO_STACK:
12139 		/* Offset 0 is out-of-bounds, but acceptable start for the
12140 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12141 		 * offset where we would need to deal with min/max bounds is
12142 		 * currently prohibited for unprivileged.
12143 		 */
12144 		max = MAX_BPF_STACK + mask_to_left;
12145 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12146 		break;
12147 	case PTR_TO_MAP_VALUE:
12148 		max = ptr_reg->map_ptr->value_size;
12149 		ptr_limit = (mask_to_left ?
12150 			     ptr_reg->smin_value :
12151 			     ptr_reg->umax_value) + ptr_reg->off;
12152 		break;
12153 	default:
12154 		return REASON_TYPE;
12155 	}
12156 
12157 	if (ptr_limit >= max)
12158 		return REASON_LIMIT;
12159 	*alu_limit = ptr_limit;
12160 	return 0;
12161 }
12162 
12163 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12164 				    const struct bpf_insn *insn)
12165 {
12166 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12167 }
12168 
12169 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12170 				       u32 alu_state, u32 alu_limit)
12171 {
12172 	/* If we arrived here from different branches with different
12173 	 * state or limits to sanitize, then this won't work.
12174 	 */
12175 	if (aux->alu_state &&
12176 	    (aux->alu_state != alu_state ||
12177 	     aux->alu_limit != alu_limit))
12178 		return REASON_PATHS;
12179 
12180 	/* Corresponding fixup done in do_misc_fixups(). */
12181 	aux->alu_state = alu_state;
12182 	aux->alu_limit = alu_limit;
12183 	return 0;
12184 }
12185 
12186 static int sanitize_val_alu(struct bpf_verifier_env *env,
12187 			    struct bpf_insn *insn)
12188 {
12189 	struct bpf_insn_aux_data *aux = cur_aux(env);
12190 
12191 	if (can_skip_alu_sanitation(env, insn))
12192 		return 0;
12193 
12194 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12195 }
12196 
12197 static bool sanitize_needed(u8 opcode)
12198 {
12199 	return opcode == BPF_ADD || opcode == BPF_SUB;
12200 }
12201 
12202 struct bpf_sanitize_info {
12203 	struct bpf_insn_aux_data aux;
12204 	bool mask_to_left;
12205 };
12206 
12207 static struct bpf_verifier_state *
12208 sanitize_speculative_path(struct bpf_verifier_env *env,
12209 			  const struct bpf_insn *insn,
12210 			  u32 next_idx, u32 curr_idx)
12211 {
12212 	struct bpf_verifier_state *branch;
12213 	struct bpf_reg_state *regs;
12214 
12215 	branch = push_stack(env, next_idx, curr_idx, true);
12216 	if (branch && insn) {
12217 		regs = branch->frame[branch->curframe]->regs;
12218 		if (BPF_SRC(insn->code) == BPF_K) {
12219 			mark_reg_unknown(env, regs, insn->dst_reg);
12220 		} else if (BPF_SRC(insn->code) == BPF_X) {
12221 			mark_reg_unknown(env, regs, insn->dst_reg);
12222 			mark_reg_unknown(env, regs, insn->src_reg);
12223 		}
12224 	}
12225 	return branch;
12226 }
12227 
12228 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12229 			    struct bpf_insn *insn,
12230 			    const struct bpf_reg_state *ptr_reg,
12231 			    const struct bpf_reg_state *off_reg,
12232 			    struct bpf_reg_state *dst_reg,
12233 			    struct bpf_sanitize_info *info,
12234 			    const bool commit_window)
12235 {
12236 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12237 	struct bpf_verifier_state *vstate = env->cur_state;
12238 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12239 	bool off_is_neg = off_reg->smin_value < 0;
12240 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12241 	u8 opcode = BPF_OP(insn->code);
12242 	u32 alu_state, alu_limit;
12243 	struct bpf_reg_state tmp;
12244 	bool ret;
12245 	int err;
12246 
12247 	if (can_skip_alu_sanitation(env, insn))
12248 		return 0;
12249 
12250 	/* We already marked aux for masking from non-speculative
12251 	 * paths, thus we got here in the first place. We only care
12252 	 * to explore bad access from here.
12253 	 */
12254 	if (vstate->speculative)
12255 		goto do_sim;
12256 
12257 	if (!commit_window) {
12258 		if (!tnum_is_const(off_reg->var_off) &&
12259 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12260 			return REASON_BOUNDS;
12261 
12262 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12263 				     (opcode == BPF_SUB && !off_is_neg);
12264 	}
12265 
12266 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12267 	if (err < 0)
12268 		return err;
12269 
12270 	if (commit_window) {
12271 		/* In commit phase we narrow the masking window based on
12272 		 * the observed pointer move after the simulated operation.
12273 		 */
12274 		alu_state = info->aux.alu_state;
12275 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12276 	} else {
12277 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12278 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12279 		alu_state |= ptr_is_dst_reg ?
12280 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12281 
12282 		/* Limit pruning on unknown scalars to enable deep search for
12283 		 * potential masking differences from other program paths.
12284 		 */
12285 		if (!off_is_imm)
12286 			env->explore_alu_limits = true;
12287 	}
12288 
12289 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12290 	if (err < 0)
12291 		return err;
12292 do_sim:
12293 	/* If we're in commit phase, we're done here given we already
12294 	 * pushed the truncated dst_reg into the speculative verification
12295 	 * stack.
12296 	 *
12297 	 * Also, when register is a known constant, we rewrite register-based
12298 	 * operation to immediate-based, and thus do not need masking (and as
12299 	 * a consequence, do not need to simulate the zero-truncation either).
12300 	 */
12301 	if (commit_window || off_is_imm)
12302 		return 0;
12303 
12304 	/* Simulate and find potential out-of-bounds access under
12305 	 * speculative execution from truncation as a result of
12306 	 * masking when off was not within expected range. If off
12307 	 * sits in dst, then we temporarily need to move ptr there
12308 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12309 	 * for cases where we use K-based arithmetic in one direction
12310 	 * and truncated reg-based in the other in order to explore
12311 	 * bad access.
12312 	 */
12313 	if (!ptr_is_dst_reg) {
12314 		tmp = *dst_reg;
12315 		copy_register_state(dst_reg, ptr_reg);
12316 	}
12317 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12318 					env->insn_idx);
12319 	if (!ptr_is_dst_reg && ret)
12320 		*dst_reg = tmp;
12321 	return !ret ? REASON_STACK : 0;
12322 }
12323 
12324 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12325 {
12326 	struct bpf_verifier_state *vstate = env->cur_state;
12327 
12328 	/* If we simulate paths under speculation, we don't update the
12329 	 * insn as 'seen' such that when we verify unreachable paths in
12330 	 * the non-speculative domain, sanitize_dead_code() can still
12331 	 * rewrite/sanitize them.
12332 	 */
12333 	if (!vstate->speculative)
12334 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12335 }
12336 
12337 static int sanitize_err(struct bpf_verifier_env *env,
12338 			const struct bpf_insn *insn, int reason,
12339 			const struct bpf_reg_state *off_reg,
12340 			const struct bpf_reg_state *dst_reg)
12341 {
12342 	static const char *err = "pointer arithmetic with it prohibited for !root";
12343 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12344 	u32 dst = insn->dst_reg, src = insn->src_reg;
12345 
12346 	switch (reason) {
12347 	case REASON_BOUNDS:
12348 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12349 			off_reg == dst_reg ? dst : src, err);
12350 		break;
12351 	case REASON_TYPE:
12352 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12353 			off_reg == dst_reg ? src : dst, err);
12354 		break;
12355 	case REASON_PATHS:
12356 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12357 			dst, op, err);
12358 		break;
12359 	case REASON_LIMIT:
12360 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12361 			dst, op, err);
12362 		break;
12363 	case REASON_STACK:
12364 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12365 			dst, err);
12366 		break;
12367 	default:
12368 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12369 			reason);
12370 		break;
12371 	}
12372 
12373 	return -EACCES;
12374 }
12375 
12376 /* check that stack access falls within stack limits and that 'reg' doesn't
12377  * have a variable offset.
12378  *
12379  * Variable offset is prohibited for unprivileged mode for simplicity since it
12380  * requires corresponding support in Spectre masking for stack ALU.  See also
12381  * retrieve_ptr_limit().
12382  *
12383  *
12384  * 'off' includes 'reg->off'.
12385  */
12386 static int check_stack_access_for_ptr_arithmetic(
12387 				struct bpf_verifier_env *env,
12388 				int regno,
12389 				const struct bpf_reg_state *reg,
12390 				int off)
12391 {
12392 	if (!tnum_is_const(reg->var_off)) {
12393 		char tn_buf[48];
12394 
12395 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12396 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12397 			regno, tn_buf, off);
12398 		return -EACCES;
12399 	}
12400 
12401 	if (off >= 0 || off < -MAX_BPF_STACK) {
12402 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12403 			"prohibited for !root; off=%d\n", regno, off);
12404 		return -EACCES;
12405 	}
12406 
12407 	return 0;
12408 }
12409 
12410 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12411 				 const struct bpf_insn *insn,
12412 				 const struct bpf_reg_state *dst_reg)
12413 {
12414 	u32 dst = insn->dst_reg;
12415 
12416 	/* For unprivileged we require that resulting offset must be in bounds
12417 	 * in order to be able to sanitize access later on.
12418 	 */
12419 	if (env->bypass_spec_v1)
12420 		return 0;
12421 
12422 	switch (dst_reg->type) {
12423 	case PTR_TO_STACK:
12424 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12425 					dst_reg->off + dst_reg->var_off.value))
12426 			return -EACCES;
12427 		break;
12428 	case PTR_TO_MAP_VALUE:
12429 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12430 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12431 				"prohibited for !root\n", dst);
12432 			return -EACCES;
12433 		}
12434 		break;
12435 	default:
12436 		break;
12437 	}
12438 
12439 	return 0;
12440 }
12441 
12442 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12443  * Caller should also handle BPF_MOV case separately.
12444  * If we return -EACCES, caller may want to try again treating pointer as a
12445  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12446  */
12447 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12448 				   struct bpf_insn *insn,
12449 				   const struct bpf_reg_state *ptr_reg,
12450 				   const struct bpf_reg_state *off_reg)
12451 {
12452 	struct bpf_verifier_state *vstate = env->cur_state;
12453 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12454 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12455 	bool known = tnum_is_const(off_reg->var_off);
12456 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12457 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12458 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12459 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12460 	struct bpf_sanitize_info info = {};
12461 	u8 opcode = BPF_OP(insn->code);
12462 	u32 dst = insn->dst_reg;
12463 	int ret;
12464 
12465 	dst_reg = &regs[dst];
12466 
12467 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12468 	    smin_val > smax_val || umin_val > umax_val) {
12469 		/* Taint dst register if offset had invalid bounds derived from
12470 		 * e.g. dead branches.
12471 		 */
12472 		__mark_reg_unknown(env, dst_reg);
12473 		return 0;
12474 	}
12475 
12476 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12477 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12478 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12479 			__mark_reg_unknown(env, dst_reg);
12480 			return 0;
12481 		}
12482 
12483 		verbose(env,
12484 			"R%d 32-bit pointer arithmetic prohibited\n",
12485 			dst);
12486 		return -EACCES;
12487 	}
12488 
12489 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12490 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12491 			dst, reg_type_str(env, ptr_reg->type));
12492 		return -EACCES;
12493 	}
12494 
12495 	switch (base_type(ptr_reg->type)) {
12496 	case PTR_TO_FLOW_KEYS:
12497 		if (known)
12498 			break;
12499 		fallthrough;
12500 	case CONST_PTR_TO_MAP:
12501 		/* smin_val represents the known value */
12502 		if (known && smin_val == 0 && opcode == BPF_ADD)
12503 			break;
12504 		fallthrough;
12505 	case PTR_TO_PACKET_END:
12506 	case PTR_TO_SOCKET:
12507 	case PTR_TO_SOCK_COMMON:
12508 	case PTR_TO_TCP_SOCK:
12509 	case PTR_TO_XDP_SOCK:
12510 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12511 			dst, reg_type_str(env, ptr_reg->type));
12512 		return -EACCES;
12513 	default:
12514 		break;
12515 	}
12516 
12517 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12518 	 * The id may be overwritten later if we create a new variable offset.
12519 	 */
12520 	dst_reg->type = ptr_reg->type;
12521 	dst_reg->id = ptr_reg->id;
12522 
12523 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12524 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12525 		return -EINVAL;
12526 
12527 	/* pointer types do not carry 32-bit bounds at the moment. */
12528 	__mark_reg32_unbounded(dst_reg);
12529 
12530 	if (sanitize_needed(opcode)) {
12531 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12532 				       &info, false);
12533 		if (ret < 0)
12534 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12535 	}
12536 
12537 	switch (opcode) {
12538 	case BPF_ADD:
12539 		/* We can take a fixed offset as long as it doesn't overflow
12540 		 * the s32 'off' field
12541 		 */
12542 		if (known && (ptr_reg->off + smin_val ==
12543 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12544 			/* pointer += K.  Accumulate it into fixed offset */
12545 			dst_reg->smin_value = smin_ptr;
12546 			dst_reg->smax_value = smax_ptr;
12547 			dst_reg->umin_value = umin_ptr;
12548 			dst_reg->umax_value = umax_ptr;
12549 			dst_reg->var_off = ptr_reg->var_off;
12550 			dst_reg->off = ptr_reg->off + smin_val;
12551 			dst_reg->raw = ptr_reg->raw;
12552 			break;
12553 		}
12554 		/* A new variable offset is created.  Note that off_reg->off
12555 		 * == 0, since it's a scalar.
12556 		 * dst_reg gets the pointer type and since some positive
12557 		 * integer value was added to the pointer, give it a new 'id'
12558 		 * if it's a PTR_TO_PACKET.
12559 		 * this creates a new 'base' pointer, off_reg (variable) gets
12560 		 * added into the variable offset, and we copy the fixed offset
12561 		 * from ptr_reg.
12562 		 */
12563 		if (signed_add_overflows(smin_ptr, smin_val) ||
12564 		    signed_add_overflows(smax_ptr, smax_val)) {
12565 			dst_reg->smin_value = S64_MIN;
12566 			dst_reg->smax_value = S64_MAX;
12567 		} else {
12568 			dst_reg->smin_value = smin_ptr + smin_val;
12569 			dst_reg->smax_value = smax_ptr + smax_val;
12570 		}
12571 		if (umin_ptr + umin_val < umin_ptr ||
12572 		    umax_ptr + umax_val < umax_ptr) {
12573 			dst_reg->umin_value = 0;
12574 			dst_reg->umax_value = U64_MAX;
12575 		} else {
12576 			dst_reg->umin_value = umin_ptr + umin_val;
12577 			dst_reg->umax_value = umax_ptr + umax_val;
12578 		}
12579 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12580 		dst_reg->off = ptr_reg->off;
12581 		dst_reg->raw = ptr_reg->raw;
12582 		if (reg_is_pkt_pointer(ptr_reg)) {
12583 			dst_reg->id = ++env->id_gen;
12584 			/* something was added to pkt_ptr, set range to zero */
12585 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12586 		}
12587 		break;
12588 	case BPF_SUB:
12589 		if (dst_reg == off_reg) {
12590 			/* scalar -= pointer.  Creates an unknown scalar */
12591 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12592 				dst);
12593 			return -EACCES;
12594 		}
12595 		/* We don't allow subtraction from FP, because (according to
12596 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12597 		 * be able to deal with it.
12598 		 */
12599 		if (ptr_reg->type == PTR_TO_STACK) {
12600 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12601 				dst);
12602 			return -EACCES;
12603 		}
12604 		if (known && (ptr_reg->off - smin_val ==
12605 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12606 			/* pointer -= K.  Subtract it from fixed offset */
12607 			dst_reg->smin_value = smin_ptr;
12608 			dst_reg->smax_value = smax_ptr;
12609 			dst_reg->umin_value = umin_ptr;
12610 			dst_reg->umax_value = umax_ptr;
12611 			dst_reg->var_off = ptr_reg->var_off;
12612 			dst_reg->id = ptr_reg->id;
12613 			dst_reg->off = ptr_reg->off - smin_val;
12614 			dst_reg->raw = ptr_reg->raw;
12615 			break;
12616 		}
12617 		/* A new variable offset is created.  If the subtrahend is known
12618 		 * nonnegative, then any reg->range we had before is still good.
12619 		 */
12620 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12621 		    signed_sub_overflows(smax_ptr, smin_val)) {
12622 			/* Overflow possible, we know nothing */
12623 			dst_reg->smin_value = S64_MIN;
12624 			dst_reg->smax_value = S64_MAX;
12625 		} else {
12626 			dst_reg->smin_value = smin_ptr - smax_val;
12627 			dst_reg->smax_value = smax_ptr - smin_val;
12628 		}
12629 		if (umin_ptr < umax_val) {
12630 			/* Overflow possible, we know nothing */
12631 			dst_reg->umin_value = 0;
12632 			dst_reg->umax_value = U64_MAX;
12633 		} else {
12634 			/* Cannot overflow (as long as bounds are consistent) */
12635 			dst_reg->umin_value = umin_ptr - umax_val;
12636 			dst_reg->umax_value = umax_ptr - umin_val;
12637 		}
12638 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12639 		dst_reg->off = ptr_reg->off;
12640 		dst_reg->raw = ptr_reg->raw;
12641 		if (reg_is_pkt_pointer(ptr_reg)) {
12642 			dst_reg->id = ++env->id_gen;
12643 			/* something was added to pkt_ptr, set range to zero */
12644 			if (smin_val < 0)
12645 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12646 		}
12647 		break;
12648 	case BPF_AND:
12649 	case BPF_OR:
12650 	case BPF_XOR:
12651 		/* bitwise ops on pointers are troublesome, prohibit. */
12652 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12653 			dst, bpf_alu_string[opcode >> 4]);
12654 		return -EACCES;
12655 	default:
12656 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12657 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12658 			dst, bpf_alu_string[opcode >> 4]);
12659 		return -EACCES;
12660 	}
12661 
12662 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12663 		return -EINVAL;
12664 	reg_bounds_sync(dst_reg);
12665 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12666 		return -EACCES;
12667 	if (sanitize_needed(opcode)) {
12668 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12669 				       &info, true);
12670 		if (ret < 0)
12671 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12672 	}
12673 
12674 	return 0;
12675 }
12676 
12677 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12678 				 struct bpf_reg_state *src_reg)
12679 {
12680 	s32 smin_val = src_reg->s32_min_value;
12681 	s32 smax_val = src_reg->s32_max_value;
12682 	u32 umin_val = src_reg->u32_min_value;
12683 	u32 umax_val = src_reg->u32_max_value;
12684 
12685 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12686 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12687 		dst_reg->s32_min_value = S32_MIN;
12688 		dst_reg->s32_max_value = S32_MAX;
12689 	} else {
12690 		dst_reg->s32_min_value += smin_val;
12691 		dst_reg->s32_max_value += smax_val;
12692 	}
12693 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12694 	    dst_reg->u32_max_value + umax_val < umax_val) {
12695 		dst_reg->u32_min_value = 0;
12696 		dst_reg->u32_max_value = U32_MAX;
12697 	} else {
12698 		dst_reg->u32_min_value += umin_val;
12699 		dst_reg->u32_max_value += umax_val;
12700 	}
12701 }
12702 
12703 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12704 			       struct bpf_reg_state *src_reg)
12705 {
12706 	s64 smin_val = src_reg->smin_value;
12707 	s64 smax_val = src_reg->smax_value;
12708 	u64 umin_val = src_reg->umin_value;
12709 	u64 umax_val = src_reg->umax_value;
12710 
12711 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12712 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12713 		dst_reg->smin_value = S64_MIN;
12714 		dst_reg->smax_value = S64_MAX;
12715 	} else {
12716 		dst_reg->smin_value += smin_val;
12717 		dst_reg->smax_value += smax_val;
12718 	}
12719 	if (dst_reg->umin_value + umin_val < umin_val ||
12720 	    dst_reg->umax_value + umax_val < umax_val) {
12721 		dst_reg->umin_value = 0;
12722 		dst_reg->umax_value = U64_MAX;
12723 	} else {
12724 		dst_reg->umin_value += umin_val;
12725 		dst_reg->umax_value += umax_val;
12726 	}
12727 }
12728 
12729 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12730 				 struct bpf_reg_state *src_reg)
12731 {
12732 	s32 smin_val = src_reg->s32_min_value;
12733 	s32 smax_val = src_reg->s32_max_value;
12734 	u32 umin_val = src_reg->u32_min_value;
12735 	u32 umax_val = src_reg->u32_max_value;
12736 
12737 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12738 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12739 		/* Overflow possible, we know nothing */
12740 		dst_reg->s32_min_value = S32_MIN;
12741 		dst_reg->s32_max_value = S32_MAX;
12742 	} else {
12743 		dst_reg->s32_min_value -= smax_val;
12744 		dst_reg->s32_max_value -= smin_val;
12745 	}
12746 	if (dst_reg->u32_min_value < umax_val) {
12747 		/* Overflow possible, we know nothing */
12748 		dst_reg->u32_min_value = 0;
12749 		dst_reg->u32_max_value = U32_MAX;
12750 	} else {
12751 		/* Cannot overflow (as long as bounds are consistent) */
12752 		dst_reg->u32_min_value -= umax_val;
12753 		dst_reg->u32_max_value -= umin_val;
12754 	}
12755 }
12756 
12757 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12758 			       struct bpf_reg_state *src_reg)
12759 {
12760 	s64 smin_val = src_reg->smin_value;
12761 	s64 smax_val = src_reg->smax_value;
12762 	u64 umin_val = src_reg->umin_value;
12763 	u64 umax_val = src_reg->umax_value;
12764 
12765 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12766 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12767 		/* Overflow possible, we know nothing */
12768 		dst_reg->smin_value = S64_MIN;
12769 		dst_reg->smax_value = S64_MAX;
12770 	} else {
12771 		dst_reg->smin_value -= smax_val;
12772 		dst_reg->smax_value -= smin_val;
12773 	}
12774 	if (dst_reg->umin_value < umax_val) {
12775 		/* Overflow possible, we know nothing */
12776 		dst_reg->umin_value = 0;
12777 		dst_reg->umax_value = U64_MAX;
12778 	} else {
12779 		/* Cannot overflow (as long as bounds are consistent) */
12780 		dst_reg->umin_value -= umax_val;
12781 		dst_reg->umax_value -= umin_val;
12782 	}
12783 }
12784 
12785 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12786 				 struct bpf_reg_state *src_reg)
12787 {
12788 	s32 smin_val = src_reg->s32_min_value;
12789 	u32 umin_val = src_reg->u32_min_value;
12790 	u32 umax_val = src_reg->u32_max_value;
12791 
12792 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12793 		/* Ain't nobody got time to multiply that sign */
12794 		__mark_reg32_unbounded(dst_reg);
12795 		return;
12796 	}
12797 	/* Both values are positive, so we can work with unsigned and
12798 	 * copy the result to signed (unless it exceeds S32_MAX).
12799 	 */
12800 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12801 		/* Potential overflow, we know nothing */
12802 		__mark_reg32_unbounded(dst_reg);
12803 		return;
12804 	}
12805 	dst_reg->u32_min_value *= umin_val;
12806 	dst_reg->u32_max_value *= umax_val;
12807 	if (dst_reg->u32_max_value > S32_MAX) {
12808 		/* Overflow possible, we know nothing */
12809 		dst_reg->s32_min_value = S32_MIN;
12810 		dst_reg->s32_max_value = S32_MAX;
12811 	} else {
12812 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12813 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12814 	}
12815 }
12816 
12817 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12818 			       struct bpf_reg_state *src_reg)
12819 {
12820 	s64 smin_val = src_reg->smin_value;
12821 	u64 umin_val = src_reg->umin_value;
12822 	u64 umax_val = src_reg->umax_value;
12823 
12824 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12825 		/* Ain't nobody got time to multiply that sign */
12826 		__mark_reg64_unbounded(dst_reg);
12827 		return;
12828 	}
12829 	/* Both values are positive, so we can work with unsigned and
12830 	 * copy the result to signed (unless it exceeds S64_MAX).
12831 	 */
12832 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12833 		/* Potential overflow, we know nothing */
12834 		__mark_reg64_unbounded(dst_reg);
12835 		return;
12836 	}
12837 	dst_reg->umin_value *= umin_val;
12838 	dst_reg->umax_value *= umax_val;
12839 	if (dst_reg->umax_value > S64_MAX) {
12840 		/* Overflow possible, we know nothing */
12841 		dst_reg->smin_value = S64_MIN;
12842 		dst_reg->smax_value = S64_MAX;
12843 	} else {
12844 		dst_reg->smin_value = dst_reg->umin_value;
12845 		dst_reg->smax_value = dst_reg->umax_value;
12846 	}
12847 }
12848 
12849 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12850 				 struct bpf_reg_state *src_reg)
12851 {
12852 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12853 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12854 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12855 	s32 smin_val = src_reg->s32_min_value;
12856 	u32 umax_val = src_reg->u32_max_value;
12857 
12858 	if (src_known && dst_known) {
12859 		__mark_reg32_known(dst_reg, var32_off.value);
12860 		return;
12861 	}
12862 
12863 	/* We get our minimum from the var_off, since that's inherently
12864 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12865 	 */
12866 	dst_reg->u32_min_value = var32_off.value;
12867 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12868 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12869 		/* Lose signed bounds when ANDing negative numbers,
12870 		 * ain't nobody got time for that.
12871 		 */
12872 		dst_reg->s32_min_value = S32_MIN;
12873 		dst_reg->s32_max_value = S32_MAX;
12874 	} else {
12875 		/* ANDing two positives gives a positive, so safe to
12876 		 * cast result into s64.
12877 		 */
12878 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12879 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12880 	}
12881 }
12882 
12883 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12884 			       struct bpf_reg_state *src_reg)
12885 {
12886 	bool src_known = tnum_is_const(src_reg->var_off);
12887 	bool dst_known = tnum_is_const(dst_reg->var_off);
12888 	s64 smin_val = src_reg->smin_value;
12889 	u64 umax_val = src_reg->umax_value;
12890 
12891 	if (src_known && dst_known) {
12892 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12893 		return;
12894 	}
12895 
12896 	/* We get our minimum from the var_off, since that's inherently
12897 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12898 	 */
12899 	dst_reg->umin_value = dst_reg->var_off.value;
12900 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12901 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12902 		/* Lose signed bounds when ANDing negative numbers,
12903 		 * ain't nobody got time for that.
12904 		 */
12905 		dst_reg->smin_value = S64_MIN;
12906 		dst_reg->smax_value = S64_MAX;
12907 	} else {
12908 		/* ANDing two positives gives a positive, so safe to
12909 		 * cast result into s64.
12910 		 */
12911 		dst_reg->smin_value = dst_reg->umin_value;
12912 		dst_reg->smax_value = dst_reg->umax_value;
12913 	}
12914 	/* We may learn something more from the var_off */
12915 	__update_reg_bounds(dst_reg);
12916 }
12917 
12918 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12919 				struct bpf_reg_state *src_reg)
12920 {
12921 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12922 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12923 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12924 	s32 smin_val = src_reg->s32_min_value;
12925 	u32 umin_val = src_reg->u32_min_value;
12926 
12927 	if (src_known && dst_known) {
12928 		__mark_reg32_known(dst_reg, var32_off.value);
12929 		return;
12930 	}
12931 
12932 	/* We get our maximum from the var_off, and our minimum is the
12933 	 * maximum of the operands' minima
12934 	 */
12935 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12936 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12937 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12938 		/* Lose signed bounds when ORing negative numbers,
12939 		 * ain't nobody got time for that.
12940 		 */
12941 		dst_reg->s32_min_value = S32_MIN;
12942 		dst_reg->s32_max_value = S32_MAX;
12943 	} else {
12944 		/* ORing two positives gives a positive, so safe to
12945 		 * cast result into s64.
12946 		 */
12947 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12948 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12949 	}
12950 }
12951 
12952 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12953 			      struct bpf_reg_state *src_reg)
12954 {
12955 	bool src_known = tnum_is_const(src_reg->var_off);
12956 	bool dst_known = tnum_is_const(dst_reg->var_off);
12957 	s64 smin_val = src_reg->smin_value;
12958 	u64 umin_val = src_reg->umin_value;
12959 
12960 	if (src_known && dst_known) {
12961 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12962 		return;
12963 	}
12964 
12965 	/* We get our maximum from the var_off, and our minimum is the
12966 	 * maximum of the operands' minima
12967 	 */
12968 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12969 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12970 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12971 		/* Lose signed bounds when ORing negative numbers,
12972 		 * ain't nobody got time for that.
12973 		 */
12974 		dst_reg->smin_value = S64_MIN;
12975 		dst_reg->smax_value = S64_MAX;
12976 	} else {
12977 		/* ORing two positives gives a positive, so safe to
12978 		 * cast result into s64.
12979 		 */
12980 		dst_reg->smin_value = dst_reg->umin_value;
12981 		dst_reg->smax_value = dst_reg->umax_value;
12982 	}
12983 	/* We may learn something more from the var_off */
12984 	__update_reg_bounds(dst_reg);
12985 }
12986 
12987 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12988 				 struct bpf_reg_state *src_reg)
12989 {
12990 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12991 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12992 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12993 	s32 smin_val = src_reg->s32_min_value;
12994 
12995 	if (src_known && dst_known) {
12996 		__mark_reg32_known(dst_reg, var32_off.value);
12997 		return;
12998 	}
12999 
13000 	/* We get both minimum and maximum from the var32_off. */
13001 	dst_reg->u32_min_value = var32_off.value;
13002 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13003 
13004 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13005 		/* XORing two positive sign numbers gives a positive,
13006 		 * so safe to cast u32 result into s32.
13007 		 */
13008 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13009 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13010 	} else {
13011 		dst_reg->s32_min_value = S32_MIN;
13012 		dst_reg->s32_max_value = S32_MAX;
13013 	}
13014 }
13015 
13016 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13017 			       struct bpf_reg_state *src_reg)
13018 {
13019 	bool src_known = tnum_is_const(src_reg->var_off);
13020 	bool dst_known = tnum_is_const(dst_reg->var_off);
13021 	s64 smin_val = src_reg->smin_value;
13022 
13023 	if (src_known && dst_known) {
13024 		/* dst_reg->var_off.value has been updated earlier */
13025 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13026 		return;
13027 	}
13028 
13029 	/* We get both minimum and maximum from the var_off. */
13030 	dst_reg->umin_value = dst_reg->var_off.value;
13031 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13032 
13033 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13034 		/* XORing two positive sign numbers gives a positive,
13035 		 * so safe to cast u64 result into s64.
13036 		 */
13037 		dst_reg->smin_value = dst_reg->umin_value;
13038 		dst_reg->smax_value = dst_reg->umax_value;
13039 	} else {
13040 		dst_reg->smin_value = S64_MIN;
13041 		dst_reg->smax_value = S64_MAX;
13042 	}
13043 
13044 	__update_reg_bounds(dst_reg);
13045 }
13046 
13047 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13048 				   u64 umin_val, u64 umax_val)
13049 {
13050 	/* We lose all sign bit information (except what we can pick
13051 	 * up from var_off)
13052 	 */
13053 	dst_reg->s32_min_value = S32_MIN;
13054 	dst_reg->s32_max_value = S32_MAX;
13055 	/* If we might shift our top bit out, then we know nothing */
13056 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13057 		dst_reg->u32_min_value = 0;
13058 		dst_reg->u32_max_value = U32_MAX;
13059 	} else {
13060 		dst_reg->u32_min_value <<= umin_val;
13061 		dst_reg->u32_max_value <<= umax_val;
13062 	}
13063 }
13064 
13065 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13066 				 struct bpf_reg_state *src_reg)
13067 {
13068 	u32 umax_val = src_reg->u32_max_value;
13069 	u32 umin_val = src_reg->u32_min_value;
13070 	/* u32 alu operation will zext upper bits */
13071 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13072 
13073 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13074 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13075 	/* Not required but being careful mark reg64 bounds as unknown so
13076 	 * that we are forced to pick them up from tnum and zext later and
13077 	 * if some path skips this step we are still safe.
13078 	 */
13079 	__mark_reg64_unbounded(dst_reg);
13080 	__update_reg32_bounds(dst_reg);
13081 }
13082 
13083 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13084 				   u64 umin_val, u64 umax_val)
13085 {
13086 	/* Special case <<32 because it is a common compiler pattern to sign
13087 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13088 	 * positive we know this shift will also be positive so we can track
13089 	 * bounds correctly. Otherwise we lose all sign bit information except
13090 	 * what we can pick up from var_off. Perhaps we can generalize this
13091 	 * later to shifts of any length.
13092 	 */
13093 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13094 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13095 	else
13096 		dst_reg->smax_value = S64_MAX;
13097 
13098 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13099 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13100 	else
13101 		dst_reg->smin_value = S64_MIN;
13102 
13103 	/* If we might shift our top bit out, then we know nothing */
13104 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13105 		dst_reg->umin_value = 0;
13106 		dst_reg->umax_value = U64_MAX;
13107 	} else {
13108 		dst_reg->umin_value <<= umin_val;
13109 		dst_reg->umax_value <<= umax_val;
13110 	}
13111 }
13112 
13113 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13114 			       struct bpf_reg_state *src_reg)
13115 {
13116 	u64 umax_val = src_reg->umax_value;
13117 	u64 umin_val = src_reg->umin_value;
13118 
13119 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13120 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13121 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13122 
13123 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13124 	/* We may learn something more from the var_off */
13125 	__update_reg_bounds(dst_reg);
13126 }
13127 
13128 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13129 				 struct bpf_reg_state *src_reg)
13130 {
13131 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13132 	u32 umax_val = src_reg->u32_max_value;
13133 	u32 umin_val = src_reg->u32_min_value;
13134 
13135 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13136 	 * be negative, then either:
13137 	 * 1) src_reg might be zero, so the sign bit of the result is
13138 	 *    unknown, so we lose our signed bounds
13139 	 * 2) it's known negative, thus the unsigned bounds capture the
13140 	 *    signed bounds
13141 	 * 3) the signed bounds cross zero, so they tell us nothing
13142 	 *    about the result
13143 	 * If the value in dst_reg is known nonnegative, then again the
13144 	 * unsigned bounds capture the signed bounds.
13145 	 * Thus, in all cases it suffices to blow away our signed bounds
13146 	 * and rely on inferring new ones from the unsigned bounds and
13147 	 * var_off of the result.
13148 	 */
13149 	dst_reg->s32_min_value = S32_MIN;
13150 	dst_reg->s32_max_value = S32_MAX;
13151 
13152 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13153 	dst_reg->u32_min_value >>= umax_val;
13154 	dst_reg->u32_max_value >>= umin_val;
13155 
13156 	__mark_reg64_unbounded(dst_reg);
13157 	__update_reg32_bounds(dst_reg);
13158 }
13159 
13160 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13161 			       struct bpf_reg_state *src_reg)
13162 {
13163 	u64 umax_val = src_reg->umax_value;
13164 	u64 umin_val = src_reg->umin_value;
13165 
13166 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13167 	 * be negative, then either:
13168 	 * 1) src_reg might be zero, so the sign bit of the result is
13169 	 *    unknown, so we lose our signed bounds
13170 	 * 2) it's known negative, thus the unsigned bounds capture the
13171 	 *    signed bounds
13172 	 * 3) the signed bounds cross zero, so they tell us nothing
13173 	 *    about the result
13174 	 * If the value in dst_reg is known nonnegative, then again the
13175 	 * unsigned bounds capture the signed bounds.
13176 	 * Thus, in all cases it suffices to blow away our signed bounds
13177 	 * and rely on inferring new ones from the unsigned bounds and
13178 	 * var_off of the result.
13179 	 */
13180 	dst_reg->smin_value = S64_MIN;
13181 	dst_reg->smax_value = S64_MAX;
13182 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13183 	dst_reg->umin_value >>= umax_val;
13184 	dst_reg->umax_value >>= umin_val;
13185 
13186 	/* Its not easy to operate on alu32 bounds here because it depends
13187 	 * on bits being shifted in. Take easy way out and mark unbounded
13188 	 * so we can recalculate later from tnum.
13189 	 */
13190 	__mark_reg32_unbounded(dst_reg);
13191 	__update_reg_bounds(dst_reg);
13192 }
13193 
13194 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13195 				  struct bpf_reg_state *src_reg)
13196 {
13197 	u64 umin_val = src_reg->u32_min_value;
13198 
13199 	/* Upon reaching here, src_known is true and
13200 	 * umax_val is equal to umin_val.
13201 	 */
13202 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13203 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13204 
13205 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13206 
13207 	/* blow away the dst_reg umin_value/umax_value and rely on
13208 	 * dst_reg var_off to refine the result.
13209 	 */
13210 	dst_reg->u32_min_value = 0;
13211 	dst_reg->u32_max_value = U32_MAX;
13212 
13213 	__mark_reg64_unbounded(dst_reg);
13214 	__update_reg32_bounds(dst_reg);
13215 }
13216 
13217 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13218 				struct bpf_reg_state *src_reg)
13219 {
13220 	u64 umin_val = src_reg->umin_value;
13221 
13222 	/* Upon reaching here, src_known is true and umax_val is equal
13223 	 * to umin_val.
13224 	 */
13225 	dst_reg->smin_value >>= umin_val;
13226 	dst_reg->smax_value >>= umin_val;
13227 
13228 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13229 
13230 	/* blow away the dst_reg umin_value/umax_value and rely on
13231 	 * dst_reg var_off to refine the result.
13232 	 */
13233 	dst_reg->umin_value = 0;
13234 	dst_reg->umax_value = U64_MAX;
13235 
13236 	/* Its not easy to operate on alu32 bounds here because it depends
13237 	 * on bits being shifted in from upper 32-bits. Take easy way out
13238 	 * and mark unbounded so we can recalculate later from tnum.
13239 	 */
13240 	__mark_reg32_unbounded(dst_reg);
13241 	__update_reg_bounds(dst_reg);
13242 }
13243 
13244 /* WARNING: This function does calculations on 64-bit values, but the actual
13245  * execution may occur on 32-bit values. Therefore, things like bitshifts
13246  * need extra checks in the 32-bit case.
13247  */
13248 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13249 				      struct bpf_insn *insn,
13250 				      struct bpf_reg_state *dst_reg,
13251 				      struct bpf_reg_state src_reg)
13252 {
13253 	struct bpf_reg_state *regs = cur_regs(env);
13254 	u8 opcode = BPF_OP(insn->code);
13255 	bool src_known;
13256 	s64 smin_val, smax_val;
13257 	u64 umin_val, umax_val;
13258 	s32 s32_min_val, s32_max_val;
13259 	u32 u32_min_val, u32_max_val;
13260 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13261 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13262 	int ret;
13263 
13264 	smin_val = src_reg.smin_value;
13265 	smax_val = src_reg.smax_value;
13266 	umin_val = src_reg.umin_value;
13267 	umax_val = src_reg.umax_value;
13268 
13269 	s32_min_val = src_reg.s32_min_value;
13270 	s32_max_val = src_reg.s32_max_value;
13271 	u32_min_val = src_reg.u32_min_value;
13272 	u32_max_val = src_reg.u32_max_value;
13273 
13274 	if (alu32) {
13275 		src_known = tnum_subreg_is_const(src_reg.var_off);
13276 		if ((src_known &&
13277 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13278 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13279 			/* Taint dst register if offset had invalid bounds
13280 			 * derived from e.g. dead branches.
13281 			 */
13282 			__mark_reg_unknown(env, dst_reg);
13283 			return 0;
13284 		}
13285 	} else {
13286 		src_known = tnum_is_const(src_reg.var_off);
13287 		if ((src_known &&
13288 		     (smin_val != smax_val || umin_val != umax_val)) ||
13289 		    smin_val > smax_val || umin_val > umax_val) {
13290 			/* Taint dst register if offset had invalid bounds
13291 			 * derived from e.g. dead branches.
13292 			 */
13293 			__mark_reg_unknown(env, dst_reg);
13294 			return 0;
13295 		}
13296 	}
13297 
13298 	if (!src_known &&
13299 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13300 		__mark_reg_unknown(env, dst_reg);
13301 		return 0;
13302 	}
13303 
13304 	if (sanitize_needed(opcode)) {
13305 		ret = sanitize_val_alu(env, insn);
13306 		if (ret < 0)
13307 			return sanitize_err(env, insn, ret, NULL, NULL);
13308 	}
13309 
13310 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13311 	 * There are two classes of instructions: The first class we track both
13312 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13313 	 * greatest amount of precision when alu operations are mixed with jmp32
13314 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13315 	 * and BPF_OR. This is possible because these ops have fairly easy to
13316 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13317 	 * See alu32 verifier tests for examples. The second class of
13318 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13319 	 * with regards to tracking sign/unsigned bounds because the bits may
13320 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13321 	 * the reg unbounded in the subreg bound space and use the resulting
13322 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13323 	 */
13324 	switch (opcode) {
13325 	case BPF_ADD:
13326 		scalar32_min_max_add(dst_reg, &src_reg);
13327 		scalar_min_max_add(dst_reg, &src_reg);
13328 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13329 		break;
13330 	case BPF_SUB:
13331 		scalar32_min_max_sub(dst_reg, &src_reg);
13332 		scalar_min_max_sub(dst_reg, &src_reg);
13333 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13334 		break;
13335 	case BPF_MUL:
13336 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13337 		scalar32_min_max_mul(dst_reg, &src_reg);
13338 		scalar_min_max_mul(dst_reg, &src_reg);
13339 		break;
13340 	case BPF_AND:
13341 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13342 		scalar32_min_max_and(dst_reg, &src_reg);
13343 		scalar_min_max_and(dst_reg, &src_reg);
13344 		break;
13345 	case BPF_OR:
13346 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13347 		scalar32_min_max_or(dst_reg, &src_reg);
13348 		scalar_min_max_or(dst_reg, &src_reg);
13349 		break;
13350 	case BPF_XOR:
13351 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13352 		scalar32_min_max_xor(dst_reg, &src_reg);
13353 		scalar_min_max_xor(dst_reg, &src_reg);
13354 		break;
13355 	case BPF_LSH:
13356 		if (umax_val >= insn_bitness) {
13357 			/* Shifts greater than 31 or 63 are undefined.
13358 			 * This includes shifts by a negative number.
13359 			 */
13360 			mark_reg_unknown(env, regs, insn->dst_reg);
13361 			break;
13362 		}
13363 		if (alu32)
13364 			scalar32_min_max_lsh(dst_reg, &src_reg);
13365 		else
13366 			scalar_min_max_lsh(dst_reg, &src_reg);
13367 		break;
13368 	case BPF_RSH:
13369 		if (umax_val >= insn_bitness) {
13370 			/* Shifts greater than 31 or 63 are undefined.
13371 			 * This includes shifts by a negative number.
13372 			 */
13373 			mark_reg_unknown(env, regs, insn->dst_reg);
13374 			break;
13375 		}
13376 		if (alu32)
13377 			scalar32_min_max_rsh(dst_reg, &src_reg);
13378 		else
13379 			scalar_min_max_rsh(dst_reg, &src_reg);
13380 		break;
13381 	case BPF_ARSH:
13382 		if (umax_val >= insn_bitness) {
13383 			/* Shifts greater than 31 or 63 are undefined.
13384 			 * This includes shifts by a negative number.
13385 			 */
13386 			mark_reg_unknown(env, regs, insn->dst_reg);
13387 			break;
13388 		}
13389 		if (alu32)
13390 			scalar32_min_max_arsh(dst_reg, &src_reg);
13391 		else
13392 			scalar_min_max_arsh(dst_reg, &src_reg);
13393 		break;
13394 	default:
13395 		mark_reg_unknown(env, regs, insn->dst_reg);
13396 		break;
13397 	}
13398 
13399 	/* ALU32 ops are zero extended into 64bit register */
13400 	if (alu32)
13401 		zext_32_to_64(dst_reg);
13402 	reg_bounds_sync(dst_reg);
13403 	return 0;
13404 }
13405 
13406 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13407  * and var_off.
13408  */
13409 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13410 				   struct bpf_insn *insn)
13411 {
13412 	struct bpf_verifier_state *vstate = env->cur_state;
13413 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13414 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13415 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13416 	u8 opcode = BPF_OP(insn->code);
13417 	int err;
13418 
13419 	dst_reg = &regs[insn->dst_reg];
13420 	src_reg = NULL;
13421 	if (dst_reg->type != SCALAR_VALUE)
13422 		ptr_reg = dst_reg;
13423 	else
13424 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13425 		 * incorrectly propagated into other registers by find_equal_scalars()
13426 		 */
13427 		dst_reg->id = 0;
13428 	if (BPF_SRC(insn->code) == BPF_X) {
13429 		src_reg = &regs[insn->src_reg];
13430 		if (src_reg->type != SCALAR_VALUE) {
13431 			if (dst_reg->type != SCALAR_VALUE) {
13432 				/* Combining two pointers by any ALU op yields
13433 				 * an arbitrary scalar. Disallow all math except
13434 				 * pointer subtraction
13435 				 */
13436 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13437 					mark_reg_unknown(env, regs, insn->dst_reg);
13438 					return 0;
13439 				}
13440 				verbose(env, "R%d pointer %s pointer prohibited\n",
13441 					insn->dst_reg,
13442 					bpf_alu_string[opcode >> 4]);
13443 				return -EACCES;
13444 			} else {
13445 				/* scalar += pointer
13446 				 * This is legal, but we have to reverse our
13447 				 * src/dest handling in computing the range
13448 				 */
13449 				err = mark_chain_precision(env, insn->dst_reg);
13450 				if (err)
13451 					return err;
13452 				return adjust_ptr_min_max_vals(env, insn,
13453 							       src_reg, dst_reg);
13454 			}
13455 		} else if (ptr_reg) {
13456 			/* pointer += scalar */
13457 			err = mark_chain_precision(env, insn->src_reg);
13458 			if (err)
13459 				return err;
13460 			return adjust_ptr_min_max_vals(env, insn,
13461 						       dst_reg, src_reg);
13462 		} else if (dst_reg->precise) {
13463 			/* if dst_reg is precise, src_reg should be precise as well */
13464 			err = mark_chain_precision(env, insn->src_reg);
13465 			if (err)
13466 				return err;
13467 		}
13468 	} else {
13469 		/* Pretend the src is a reg with a known value, since we only
13470 		 * need to be able to read from this state.
13471 		 */
13472 		off_reg.type = SCALAR_VALUE;
13473 		__mark_reg_known(&off_reg, insn->imm);
13474 		src_reg = &off_reg;
13475 		if (ptr_reg) /* pointer += K */
13476 			return adjust_ptr_min_max_vals(env, insn,
13477 						       ptr_reg, src_reg);
13478 	}
13479 
13480 	/* Got here implies adding two SCALAR_VALUEs */
13481 	if (WARN_ON_ONCE(ptr_reg)) {
13482 		print_verifier_state(env, state, true);
13483 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13484 		return -EINVAL;
13485 	}
13486 	if (WARN_ON(!src_reg)) {
13487 		print_verifier_state(env, state, true);
13488 		verbose(env, "verifier internal error: no src_reg\n");
13489 		return -EINVAL;
13490 	}
13491 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13492 }
13493 
13494 /* check validity of 32-bit and 64-bit arithmetic operations */
13495 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13496 {
13497 	struct bpf_reg_state *regs = cur_regs(env);
13498 	u8 opcode = BPF_OP(insn->code);
13499 	int err;
13500 
13501 	if (opcode == BPF_END || opcode == BPF_NEG) {
13502 		if (opcode == BPF_NEG) {
13503 			if (BPF_SRC(insn->code) != BPF_K ||
13504 			    insn->src_reg != BPF_REG_0 ||
13505 			    insn->off != 0 || insn->imm != 0) {
13506 				verbose(env, "BPF_NEG uses reserved fields\n");
13507 				return -EINVAL;
13508 			}
13509 		} else {
13510 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13511 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13512 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13513 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13514 				verbose(env, "BPF_END uses reserved fields\n");
13515 				return -EINVAL;
13516 			}
13517 		}
13518 
13519 		/* check src operand */
13520 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13521 		if (err)
13522 			return err;
13523 
13524 		if (is_pointer_value(env, insn->dst_reg)) {
13525 			verbose(env, "R%d pointer arithmetic prohibited\n",
13526 				insn->dst_reg);
13527 			return -EACCES;
13528 		}
13529 
13530 		/* check dest operand */
13531 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13532 		if (err)
13533 			return err;
13534 
13535 	} else if (opcode == BPF_MOV) {
13536 
13537 		if (BPF_SRC(insn->code) == BPF_X) {
13538 			if (insn->imm != 0) {
13539 				verbose(env, "BPF_MOV uses reserved fields\n");
13540 				return -EINVAL;
13541 			}
13542 
13543 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13544 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13545 					verbose(env, "BPF_MOV uses reserved fields\n");
13546 					return -EINVAL;
13547 				}
13548 			} else {
13549 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13550 				    insn->off != 32) {
13551 					verbose(env, "BPF_MOV uses reserved fields\n");
13552 					return -EINVAL;
13553 				}
13554 			}
13555 
13556 			/* check src operand */
13557 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13558 			if (err)
13559 				return err;
13560 		} else {
13561 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13562 				verbose(env, "BPF_MOV uses reserved fields\n");
13563 				return -EINVAL;
13564 			}
13565 		}
13566 
13567 		/* check dest operand, mark as required later */
13568 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13569 		if (err)
13570 			return err;
13571 
13572 		if (BPF_SRC(insn->code) == BPF_X) {
13573 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13574 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13575 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13576 				       !tnum_is_const(src_reg->var_off);
13577 
13578 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13579 				if (insn->off == 0) {
13580 					/* case: R1 = R2
13581 					 * copy register state to dest reg
13582 					 */
13583 					if (need_id)
13584 						/* Assign src and dst registers the same ID
13585 						 * that will be used by find_equal_scalars()
13586 						 * to propagate min/max range.
13587 						 */
13588 						src_reg->id = ++env->id_gen;
13589 					copy_register_state(dst_reg, src_reg);
13590 					dst_reg->live |= REG_LIVE_WRITTEN;
13591 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13592 				} else {
13593 					/* case: R1 = (s8, s16 s32)R2 */
13594 					if (is_pointer_value(env, insn->src_reg)) {
13595 						verbose(env,
13596 							"R%d sign-extension part of pointer\n",
13597 							insn->src_reg);
13598 						return -EACCES;
13599 					} else if (src_reg->type == SCALAR_VALUE) {
13600 						bool no_sext;
13601 
13602 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13603 						if (no_sext && need_id)
13604 							src_reg->id = ++env->id_gen;
13605 						copy_register_state(dst_reg, src_reg);
13606 						if (!no_sext)
13607 							dst_reg->id = 0;
13608 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13609 						dst_reg->live |= REG_LIVE_WRITTEN;
13610 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13611 					} else {
13612 						mark_reg_unknown(env, regs, insn->dst_reg);
13613 					}
13614 				}
13615 			} else {
13616 				/* R1 = (u32) R2 */
13617 				if (is_pointer_value(env, insn->src_reg)) {
13618 					verbose(env,
13619 						"R%d partial copy of pointer\n",
13620 						insn->src_reg);
13621 					return -EACCES;
13622 				} else if (src_reg->type == SCALAR_VALUE) {
13623 					if (insn->off == 0) {
13624 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13625 
13626 						if (is_src_reg_u32 && need_id)
13627 							src_reg->id = ++env->id_gen;
13628 						copy_register_state(dst_reg, src_reg);
13629 						/* Make sure ID is cleared if src_reg is not in u32
13630 						 * range otherwise dst_reg min/max could be incorrectly
13631 						 * propagated into src_reg by find_equal_scalars()
13632 						 */
13633 						if (!is_src_reg_u32)
13634 							dst_reg->id = 0;
13635 						dst_reg->live |= REG_LIVE_WRITTEN;
13636 						dst_reg->subreg_def = env->insn_idx + 1;
13637 					} else {
13638 						/* case: W1 = (s8, s16)W2 */
13639 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13640 
13641 						if (no_sext && need_id)
13642 							src_reg->id = ++env->id_gen;
13643 						copy_register_state(dst_reg, src_reg);
13644 						if (!no_sext)
13645 							dst_reg->id = 0;
13646 						dst_reg->live |= REG_LIVE_WRITTEN;
13647 						dst_reg->subreg_def = env->insn_idx + 1;
13648 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13649 					}
13650 				} else {
13651 					mark_reg_unknown(env, regs,
13652 							 insn->dst_reg);
13653 				}
13654 				zext_32_to_64(dst_reg);
13655 				reg_bounds_sync(dst_reg);
13656 			}
13657 		} else {
13658 			/* case: R = imm
13659 			 * remember the value we stored into this reg
13660 			 */
13661 			/* clear any state __mark_reg_known doesn't set */
13662 			mark_reg_unknown(env, regs, insn->dst_reg);
13663 			regs[insn->dst_reg].type = SCALAR_VALUE;
13664 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13665 				__mark_reg_known(regs + insn->dst_reg,
13666 						 insn->imm);
13667 			} else {
13668 				__mark_reg_known(regs + insn->dst_reg,
13669 						 (u32)insn->imm);
13670 			}
13671 		}
13672 
13673 	} else if (opcode > BPF_END) {
13674 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13675 		return -EINVAL;
13676 
13677 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13678 
13679 		if (BPF_SRC(insn->code) == BPF_X) {
13680 			if (insn->imm != 0 || insn->off > 1 ||
13681 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13682 				verbose(env, "BPF_ALU uses reserved fields\n");
13683 				return -EINVAL;
13684 			}
13685 			/* check src1 operand */
13686 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13687 			if (err)
13688 				return err;
13689 		} else {
13690 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13691 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13692 				verbose(env, "BPF_ALU uses reserved fields\n");
13693 				return -EINVAL;
13694 			}
13695 		}
13696 
13697 		/* check src2 operand */
13698 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13699 		if (err)
13700 			return err;
13701 
13702 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13703 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13704 			verbose(env, "div by zero\n");
13705 			return -EINVAL;
13706 		}
13707 
13708 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13709 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13710 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13711 
13712 			if (insn->imm < 0 || insn->imm >= size) {
13713 				verbose(env, "invalid shift %d\n", insn->imm);
13714 				return -EINVAL;
13715 			}
13716 		}
13717 
13718 		/* check dest operand */
13719 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13720 		if (err)
13721 			return err;
13722 
13723 		return adjust_reg_min_max_vals(env, insn);
13724 	}
13725 
13726 	return 0;
13727 }
13728 
13729 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13730 				   struct bpf_reg_state *dst_reg,
13731 				   enum bpf_reg_type type,
13732 				   bool range_right_open)
13733 {
13734 	struct bpf_func_state *state;
13735 	struct bpf_reg_state *reg;
13736 	int new_range;
13737 
13738 	if (dst_reg->off < 0 ||
13739 	    (dst_reg->off == 0 && range_right_open))
13740 		/* This doesn't give us any range */
13741 		return;
13742 
13743 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13744 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13745 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13746 		 * than pkt_end, but that's because it's also less than pkt.
13747 		 */
13748 		return;
13749 
13750 	new_range = dst_reg->off;
13751 	if (range_right_open)
13752 		new_range++;
13753 
13754 	/* Examples for register markings:
13755 	 *
13756 	 * pkt_data in dst register:
13757 	 *
13758 	 *   r2 = r3;
13759 	 *   r2 += 8;
13760 	 *   if (r2 > pkt_end) goto <handle exception>
13761 	 *   <access okay>
13762 	 *
13763 	 *   r2 = r3;
13764 	 *   r2 += 8;
13765 	 *   if (r2 < pkt_end) goto <access okay>
13766 	 *   <handle exception>
13767 	 *
13768 	 *   Where:
13769 	 *     r2 == dst_reg, pkt_end == src_reg
13770 	 *     r2=pkt(id=n,off=8,r=0)
13771 	 *     r3=pkt(id=n,off=0,r=0)
13772 	 *
13773 	 * pkt_data in src register:
13774 	 *
13775 	 *   r2 = r3;
13776 	 *   r2 += 8;
13777 	 *   if (pkt_end >= r2) goto <access okay>
13778 	 *   <handle exception>
13779 	 *
13780 	 *   r2 = r3;
13781 	 *   r2 += 8;
13782 	 *   if (pkt_end <= r2) goto <handle exception>
13783 	 *   <access okay>
13784 	 *
13785 	 *   Where:
13786 	 *     pkt_end == dst_reg, r2 == src_reg
13787 	 *     r2=pkt(id=n,off=8,r=0)
13788 	 *     r3=pkt(id=n,off=0,r=0)
13789 	 *
13790 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13791 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13792 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13793 	 * the check.
13794 	 */
13795 
13796 	/* If our ids match, then we must have the same max_value.  And we
13797 	 * don't care about the other reg's fixed offset, since if it's too big
13798 	 * the range won't allow anything.
13799 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13800 	 */
13801 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13802 		if (reg->type == type && reg->id == dst_reg->id)
13803 			/* keep the maximum range already checked */
13804 			reg->range = max(reg->range, new_range);
13805 	}));
13806 }
13807 
13808 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13809 {
13810 	struct tnum subreg = tnum_subreg(reg->var_off);
13811 	s32 sval = (s32)val;
13812 
13813 	switch (opcode) {
13814 	case BPF_JEQ:
13815 		if (tnum_is_const(subreg))
13816 			return !!tnum_equals_const(subreg, val);
13817 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13818 			return 0;
13819 		break;
13820 	case BPF_JNE:
13821 		if (tnum_is_const(subreg))
13822 			return !tnum_equals_const(subreg, val);
13823 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13824 			return 1;
13825 		break;
13826 	case BPF_JSET:
13827 		if ((~subreg.mask & subreg.value) & val)
13828 			return 1;
13829 		if (!((subreg.mask | subreg.value) & val))
13830 			return 0;
13831 		break;
13832 	case BPF_JGT:
13833 		if (reg->u32_min_value > val)
13834 			return 1;
13835 		else if (reg->u32_max_value <= val)
13836 			return 0;
13837 		break;
13838 	case BPF_JSGT:
13839 		if (reg->s32_min_value > sval)
13840 			return 1;
13841 		else if (reg->s32_max_value <= sval)
13842 			return 0;
13843 		break;
13844 	case BPF_JLT:
13845 		if (reg->u32_max_value < val)
13846 			return 1;
13847 		else if (reg->u32_min_value >= val)
13848 			return 0;
13849 		break;
13850 	case BPF_JSLT:
13851 		if (reg->s32_max_value < sval)
13852 			return 1;
13853 		else if (reg->s32_min_value >= sval)
13854 			return 0;
13855 		break;
13856 	case BPF_JGE:
13857 		if (reg->u32_min_value >= val)
13858 			return 1;
13859 		else if (reg->u32_max_value < val)
13860 			return 0;
13861 		break;
13862 	case BPF_JSGE:
13863 		if (reg->s32_min_value >= sval)
13864 			return 1;
13865 		else if (reg->s32_max_value < sval)
13866 			return 0;
13867 		break;
13868 	case BPF_JLE:
13869 		if (reg->u32_max_value <= val)
13870 			return 1;
13871 		else if (reg->u32_min_value > val)
13872 			return 0;
13873 		break;
13874 	case BPF_JSLE:
13875 		if (reg->s32_max_value <= sval)
13876 			return 1;
13877 		else if (reg->s32_min_value > sval)
13878 			return 0;
13879 		break;
13880 	}
13881 
13882 	return -1;
13883 }
13884 
13885 
13886 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13887 {
13888 	s64 sval = (s64)val;
13889 
13890 	switch (opcode) {
13891 	case BPF_JEQ:
13892 		if (tnum_is_const(reg->var_off))
13893 			return !!tnum_equals_const(reg->var_off, val);
13894 		else if (val < reg->umin_value || val > reg->umax_value)
13895 			return 0;
13896 		break;
13897 	case BPF_JNE:
13898 		if (tnum_is_const(reg->var_off))
13899 			return !tnum_equals_const(reg->var_off, val);
13900 		else if (val < reg->umin_value || val > reg->umax_value)
13901 			return 1;
13902 		break;
13903 	case BPF_JSET:
13904 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13905 			return 1;
13906 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13907 			return 0;
13908 		break;
13909 	case BPF_JGT:
13910 		if (reg->umin_value > val)
13911 			return 1;
13912 		else if (reg->umax_value <= val)
13913 			return 0;
13914 		break;
13915 	case BPF_JSGT:
13916 		if (reg->smin_value > sval)
13917 			return 1;
13918 		else if (reg->smax_value <= sval)
13919 			return 0;
13920 		break;
13921 	case BPF_JLT:
13922 		if (reg->umax_value < val)
13923 			return 1;
13924 		else if (reg->umin_value >= val)
13925 			return 0;
13926 		break;
13927 	case BPF_JSLT:
13928 		if (reg->smax_value < sval)
13929 			return 1;
13930 		else if (reg->smin_value >= sval)
13931 			return 0;
13932 		break;
13933 	case BPF_JGE:
13934 		if (reg->umin_value >= val)
13935 			return 1;
13936 		else if (reg->umax_value < val)
13937 			return 0;
13938 		break;
13939 	case BPF_JSGE:
13940 		if (reg->smin_value >= sval)
13941 			return 1;
13942 		else if (reg->smax_value < sval)
13943 			return 0;
13944 		break;
13945 	case BPF_JLE:
13946 		if (reg->umax_value <= val)
13947 			return 1;
13948 		else if (reg->umin_value > val)
13949 			return 0;
13950 		break;
13951 	case BPF_JSLE:
13952 		if (reg->smax_value <= sval)
13953 			return 1;
13954 		else if (reg->smin_value > sval)
13955 			return 0;
13956 		break;
13957 	}
13958 
13959 	return -1;
13960 }
13961 
13962 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13963  * and return:
13964  *  1 - branch will be taken and "goto target" will be executed
13965  *  0 - branch will not be taken and fall-through to next insn
13966  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13967  *      range [0,10]
13968  */
13969 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13970 			   bool is_jmp32)
13971 {
13972 	if (__is_pointer_value(false, reg)) {
13973 		if (!reg_not_null(reg))
13974 			return -1;
13975 
13976 		/* If pointer is valid tests against zero will fail so we can
13977 		 * use this to direct branch taken.
13978 		 */
13979 		if (val != 0)
13980 			return -1;
13981 
13982 		switch (opcode) {
13983 		case BPF_JEQ:
13984 			return 0;
13985 		case BPF_JNE:
13986 			return 1;
13987 		default:
13988 			return -1;
13989 		}
13990 	}
13991 
13992 	if (is_jmp32)
13993 		return is_branch32_taken(reg, val, opcode);
13994 	return is_branch64_taken(reg, val, opcode);
13995 }
13996 
13997 static int flip_opcode(u32 opcode)
13998 {
13999 	/* How can we transform "a <op> b" into "b <op> a"? */
14000 	static const u8 opcode_flip[16] = {
14001 		/* these stay the same */
14002 		[BPF_JEQ  >> 4] = BPF_JEQ,
14003 		[BPF_JNE  >> 4] = BPF_JNE,
14004 		[BPF_JSET >> 4] = BPF_JSET,
14005 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14006 		[BPF_JGE  >> 4] = BPF_JLE,
14007 		[BPF_JGT  >> 4] = BPF_JLT,
14008 		[BPF_JLE  >> 4] = BPF_JGE,
14009 		[BPF_JLT  >> 4] = BPF_JGT,
14010 		[BPF_JSGE >> 4] = BPF_JSLE,
14011 		[BPF_JSGT >> 4] = BPF_JSLT,
14012 		[BPF_JSLE >> 4] = BPF_JSGE,
14013 		[BPF_JSLT >> 4] = BPF_JSGT
14014 	};
14015 	return opcode_flip[opcode >> 4];
14016 }
14017 
14018 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14019 				   struct bpf_reg_state *src_reg,
14020 				   u8 opcode)
14021 {
14022 	struct bpf_reg_state *pkt;
14023 
14024 	if (src_reg->type == PTR_TO_PACKET_END) {
14025 		pkt = dst_reg;
14026 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14027 		pkt = src_reg;
14028 		opcode = flip_opcode(opcode);
14029 	} else {
14030 		return -1;
14031 	}
14032 
14033 	if (pkt->range >= 0)
14034 		return -1;
14035 
14036 	switch (opcode) {
14037 	case BPF_JLE:
14038 		/* pkt <= pkt_end */
14039 		fallthrough;
14040 	case BPF_JGT:
14041 		/* pkt > pkt_end */
14042 		if (pkt->range == BEYOND_PKT_END)
14043 			/* pkt has at last one extra byte beyond pkt_end */
14044 			return opcode == BPF_JGT;
14045 		break;
14046 	case BPF_JLT:
14047 		/* pkt < pkt_end */
14048 		fallthrough;
14049 	case BPF_JGE:
14050 		/* pkt >= pkt_end */
14051 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14052 			return opcode == BPF_JGE;
14053 		break;
14054 	}
14055 	return -1;
14056 }
14057 
14058 /* Adjusts the register min/max values in the case that the dst_reg is the
14059  * variable register that we are working on, and src_reg is a constant or we're
14060  * simply doing a BPF_K check.
14061  * In JEQ/JNE cases we also adjust the var_off values.
14062  */
14063 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14064 			    struct bpf_reg_state *false_reg,
14065 			    u64 val, u32 val32,
14066 			    u8 opcode, bool is_jmp32)
14067 {
14068 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14069 	struct tnum false_64off = false_reg->var_off;
14070 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14071 	struct tnum true_64off = true_reg->var_off;
14072 	s64 sval = (s64)val;
14073 	s32 sval32 = (s32)val32;
14074 
14075 	/* If the dst_reg is a pointer, we can't learn anything about its
14076 	 * variable offset from the compare (unless src_reg were a pointer into
14077 	 * the same object, but we don't bother with that.
14078 	 * Since false_reg and true_reg have the same type by construction, we
14079 	 * only need to check one of them for pointerness.
14080 	 */
14081 	if (__is_pointer_value(false, false_reg))
14082 		return;
14083 
14084 	switch (opcode) {
14085 	/* JEQ/JNE comparison doesn't change the register equivalence.
14086 	 *
14087 	 * r1 = r2;
14088 	 * if (r1 == 42) goto label;
14089 	 * ...
14090 	 * label: // here both r1 and r2 are known to be 42.
14091 	 *
14092 	 * Hence when marking register as known preserve it's ID.
14093 	 */
14094 	case BPF_JEQ:
14095 		if (is_jmp32) {
14096 			__mark_reg32_known(true_reg, val32);
14097 			true_32off = tnum_subreg(true_reg->var_off);
14098 		} else {
14099 			___mark_reg_known(true_reg, val);
14100 			true_64off = true_reg->var_off;
14101 		}
14102 		break;
14103 	case BPF_JNE:
14104 		if (is_jmp32) {
14105 			__mark_reg32_known(false_reg, val32);
14106 			false_32off = tnum_subreg(false_reg->var_off);
14107 		} else {
14108 			___mark_reg_known(false_reg, val);
14109 			false_64off = false_reg->var_off;
14110 		}
14111 		break;
14112 	case BPF_JSET:
14113 		if (is_jmp32) {
14114 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14115 			if (is_power_of_2(val32))
14116 				true_32off = tnum_or(true_32off,
14117 						     tnum_const(val32));
14118 		} else {
14119 			false_64off = tnum_and(false_64off, tnum_const(~val));
14120 			if (is_power_of_2(val))
14121 				true_64off = tnum_or(true_64off,
14122 						     tnum_const(val));
14123 		}
14124 		break;
14125 	case BPF_JGE:
14126 	case BPF_JGT:
14127 	{
14128 		if (is_jmp32) {
14129 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14130 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14131 
14132 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14133 						       false_umax);
14134 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14135 						      true_umin);
14136 		} else {
14137 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14138 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14139 
14140 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14141 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14142 		}
14143 		break;
14144 	}
14145 	case BPF_JSGE:
14146 	case BPF_JSGT:
14147 	{
14148 		if (is_jmp32) {
14149 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14150 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14151 
14152 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14153 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14154 		} else {
14155 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14156 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14157 
14158 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14159 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14160 		}
14161 		break;
14162 	}
14163 	case BPF_JLE:
14164 	case BPF_JLT:
14165 	{
14166 		if (is_jmp32) {
14167 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14168 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14169 
14170 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14171 						       false_umin);
14172 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14173 						      true_umax);
14174 		} else {
14175 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14176 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14177 
14178 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14179 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14180 		}
14181 		break;
14182 	}
14183 	case BPF_JSLE:
14184 	case BPF_JSLT:
14185 	{
14186 		if (is_jmp32) {
14187 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14188 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14189 
14190 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14191 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14192 		} else {
14193 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14194 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14195 
14196 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14197 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14198 		}
14199 		break;
14200 	}
14201 	default:
14202 		return;
14203 	}
14204 
14205 	if (is_jmp32) {
14206 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14207 					     tnum_subreg(false_32off));
14208 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14209 					    tnum_subreg(true_32off));
14210 		__reg_combine_32_into_64(false_reg);
14211 		__reg_combine_32_into_64(true_reg);
14212 	} else {
14213 		false_reg->var_off = false_64off;
14214 		true_reg->var_off = true_64off;
14215 		__reg_combine_64_into_32(false_reg);
14216 		__reg_combine_64_into_32(true_reg);
14217 	}
14218 }
14219 
14220 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14221  * the variable reg.
14222  */
14223 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14224 				struct bpf_reg_state *false_reg,
14225 				u64 val, u32 val32,
14226 				u8 opcode, bool is_jmp32)
14227 {
14228 	opcode = flip_opcode(opcode);
14229 	/* This uses zero as "not present in table"; luckily the zero opcode,
14230 	 * BPF_JA, can't get here.
14231 	 */
14232 	if (opcode)
14233 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14234 }
14235 
14236 /* Regs are known to be equal, so intersect their min/max/var_off */
14237 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14238 				  struct bpf_reg_state *dst_reg)
14239 {
14240 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14241 							dst_reg->umin_value);
14242 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14243 							dst_reg->umax_value);
14244 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14245 							dst_reg->smin_value);
14246 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14247 							dst_reg->smax_value);
14248 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14249 							     dst_reg->var_off);
14250 	reg_bounds_sync(src_reg);
14251 	reg_bounds_sync(dst_reg);
14252 }
14253 
14254 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14255 				struct bpf_reg_state *true_dst,
14256 				struct bpf_reg_state *false_src,
14257 				struct bpf_reg_state *false_dst,
14258 				u8 opcode)
14259 {
14260 	switch (opcode) {
14261 	case BPF_JEQ:
14262 		__reg_combine_min_max(true_src, true_dst);
14263 		break;
14264 	case BPF_JNE:
14265 		__reg_combine_min_max(false_src, false_dst);
14266 		break;
14267 	}
14268 }
14269 
14270 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14271 				 struct bpf_reg_state *reg, u32 id,
14272 				 bool is_null)
14273 {
14274 	if (type_may_be_null(reg->type) && reg->id == id &&
14275 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14276 		/* Old offset (both fixed and variable parts) should have been
14277 		 * known-zero, because we don't allow pointer arithmetic on
14278 		 * pointers that might be NULL. If we see this happening, don't
14279 		 * convert the register.
14280 		 *
14281 		 * But in some cases, some helpers that return local kptrs
14282 		 * advance offset for the returned pointer. In those cases, it
14283 		 * is fine to expect to see reg->off.
14284 		 */
14285 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14286 			return;
14287 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14288 		    WARN_ON_ONCE(reg->off))
14289 			return;
14290 
14291 		if (is_null) {
14292 			reg->type = SCALAR_VALUE;
14293 			/* We don't need id and ref_obj_id from this point
14294 			 * onwards anymore, thus we should better reset it,
14295 			 * so that state pruning has chances to take effect.
14296 			 */
14297 			reg->id = 0;
14298 			reg->ref_obj_id = 0;
14299 
14300 			return;
14301 		}
14302 
14303 		mark_ptr_not_null_reg(reg);
14304 
14305 		if (!reg_may_point_to_spin_lock(reg)) {
14306 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14307 			 * in release_reference().
14308 			 *
14309 			 * reg->id is still used by spin_lock ptr. Other
14310 			 * than spin_lock ptr type, reg->id can be reset.
14311 			 */
14312 			reg->id = 0;
14313 		}
14314 	}
14315 }
14316 
14317 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14318  * be folded together at some point.
14319  */
14320 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14321 				  bool is_null)
14322 {
14323 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14324 	struct bpf_reg_state *regs = state->regs, *reg;
14325 	u32 ref_obj_id = regs[regno].ref_obj_id;
14326 	u32 id = regs[regno].id;
14327 
14328 	if (ref_obj_id && ref_obj_id == id && is_null)
14329 		/* regs[regno] is in the " == NULL" branch.
14330 		 * No one could have freed the reference state before
14331 		 * doing the NULL check.
14332 		 */
14333 		WARN_ON_ONCE(release_reference_state(state, id));
14334 
14335 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14336 		mark_ptr_or_null_reg(state, reg, id, is_null);
14337 	}));
14338 }
14339 
14340 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14341 				   struct bpf_reg_state *dst_reg,
14342 				   struct bpf_reg_state *src_reg,
14343 				   struct bpf_verifier_state *this_branch,
14344 				   struct bpf_verifier_state *other_branch)
14345 {
14346 	if (BPF_SRC(insn->code) != BPF_X)
14347 		return false;
14348 
14349 	/* Pointers are always 64-bit. */
14350 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14351 		return false;
14352 
14353 	switch (BPF_OP(insn->code)) {
14354 	case BPF_JGT:
14355 		if ((dst_reg->type == PTR_TO_PACKET &&
14356 		     src_reg->type == PTR_TO_PACKET_END) ||
14357 		    (dst_reg->type == PTR_TO_PACKET_META &&
14358 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14359 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14360 			find_good_pkt_pointers(this_branch, dst_reg,
14361 					       dst_reg->type, false);
14362 			mark_pkt_end(other_branch, insn->dst_reg, true);
14363 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14364 			    src_reg->type == PTR_TO_PACKET) ||
14365 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14366 			    src_reg->type == PTR_TO_PACKET_META)) {
14367 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14368 			find_good_pkt_pointers(other_branch, src_reg,
14369 					       src_reg->type, true);
14370 			mark_pkt_end(this_branch, insn->src_reg, false);
14371 		} else {
14372 			return false;
14373 		}
14374 		break;
14375 	case BPF_JLT:
14376 		if ((dst_reg->type == PTR_TO_PACKET &&
14377 		     src_reg->type == PTR_TO_PACKET_END) ||
14378 		    (dst_reg->type == PTR_TO_PACKET_META &&
14379 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14380 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14381 			find_good_pkt_pointers(other_branch, dst_reg,
14382 					       dst_reg->type, true);
14383 			mark_pkt_end(this_branch, insn->dst_reg, false);
14384 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14385 			    src_reg->type == PTR_TO_PACKET) ||
14386 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14387 			    src_reg->type == PTR_TO_PACKET_META)) {
14388 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14389 			find_good_pkt_pointers(this_branch, src_reg,
14390 					       src_reg->type, false);
14391 			mark_pkt_end(other_branch, insn->src_reg, true);
14392 		} else {
14393 			return false;
14394 		}
14395 		break;
14396 	case BPF_JGE:
14397 		if ((dst_reg->type == PTR_TO_PACKET &&
14398 		     src_reg->type == PTR_TO_PACKET_END) ||
14399 		    (dst_reg->type == PTR_TO_PACKET_META &&
14400 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14401 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14402 			find_good_pkt_pointers(this_branch, dst_reg,
14403 					       dst_reg->type, true);
14404 			mark_pkt_end(other_branch, insn->dst_reg, false);
14405 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14406 			    src_reg->type == PTR_TO_PACKET) ||
14407 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14408 			    src_reg->type == PTR_TO_PACKET_META)) {
14409 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14410 			find_good_pkt_pointers(other_branch, src_reg,
14411 					       src_reg->type, false);
14412 			mark_pkt_end(this_branch, insn->src_reg, true);
14413 		} else {
14414 			return false;
14415 		}
14416 		break;
14417 	case BPF_JLE:
14418 		if ((dst_reg->type == PTR_TO_PACKET &&
14419 		     src_reg->type == PTR_TO_PACKET_END) ||
14420 		    (dst_reg->type == PTR_TO_PACKET_META &&
14421 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14422 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14423 			find_good_pkt_pointers(other_branch, dst_reg,
14424 					       dst_reg->type, false);
14425 			mark_pkt_end(this_branch, insn->dst_reg, true);
14426 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14427 			    src_reg->type == PTR_TO_PACKET) ||
14428 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14429 			    src_reg->type == PTR_TO_PACKET_META)) {
14430 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14431 			find_good_pkt_pointers(this_branch, src_reg,
14432 					       src_reg->type, true);
14433 			mark_pkt_end(other_branch, insn->src_reg, false);
14434 		} else {
14435 			return false;
14436 		}
14437 		break;
14438 	default:
14439 		return false;
14440 	}
14441 
14442 	return true;
14443 }
14444 
14445 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14446 			       struct bpf_reg_state *known_reg)
14447 {
14448 	struct bpf_func_state *state;
14449 	struct bpf_reg_state *reg;
14450 
14451 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14452 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14453 			copy_register_state(reg, known_reg);
14454 	}));
14455 }
14456 
14457 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14458 			     struct bpf_insn *insn, int *insn_idx)
14459 {
14460 	struct bpf_verifier_state *this_branch = env->cur_state;
14461 	struct bpf_verifier_state *other_branch;
14462 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14463 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14464 	struct bpf_reg_state *eq_branch_regs;
14465 	u8 opcode = BPF_OP(insn->code);
14466 	bool is_jmp32;
14467 	int pred = -1;
14468 	int err;
14469 
14470 	/* Only conditional jumps are expected to reach here. */
14471 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14472 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14473 		return -EINVAL;
14474 	}
14475 
14476 	/* check src2 operand */
14477 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14478 	if (err)
14479 		return err;
14480 
14481 	dst_reg = &regs[insn->dst_reg];
14482 	if (BPF_SRC(insn->code) == BPF_X) {
14483 		if (insn->imm != 0) {
14484 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14485 			return -EINVAL;
14486 		}
14487 
14488 		/* check src1 operand */
14489 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14490 		if (err)
14491 			return err;
14492 
14493 		src_reg = &regs[insn->src_reg];
14494 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14495 		    is_pointer_value(env, insn->src_reg)) {
14496 			verbose(env, "R%d pointer comparison prohibited\n",
14497 				insn->src_reg);
14498 			return -EACCES;
14499 		}
14500 	} else {
14501 		if (insn->src_reg != BPF_REG_0) {
14502 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14503 			return -EINVAL;
14504 		}
14505 	}
14506 
14507 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14508 
14509 	if (BPF_SRC(insn->code) == BPF_K) {
14510 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14511 	} else if (src_reg->type == SCALAR_VALUE &&
14512 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14513 		pred = is_branch_taken(dst_reg,
14514 				       tnum_subreg(src_reg->var_off).value,
14515 				       opcode,
14516 				       is_jmp32);
14517 	} else if (src_reg->type == SCALAR_VALUE &&
14518 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14519 		pred = is_branch_taken(dst_reg,
14520 				       src_reg->var_off.value,
14521 				       opcode,
14522 				       is_jmp32);
14523 	} else if (dst_reg->type == SCALAR_VALUE &&
14524 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14525 		pred = is_branch_taken(src_reg,
14526 				       tnum_subreg(dst_reg->var_off).value,
14527 				       flip_opcode(opcode),
14528 				       is_jmp32);
14529 	} else if (dst_reg->type == SCALAR_VALUE &&
14530 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14531 		pred = is_branch_taken(src_reg,
14532 				       dst_reg->var_off.value,
14533 				       flip_opcode(opcode),
14534 				       is_jmp32);
14535 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14536 		   reg_is_pkt_pointer_any(src_reg) &&
14537 		   !is_jmp32) {
14538 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14539 	}
14540 
14541 	if (pred >= 0) {
14542 		/* If we get here with a dst_reg pointer type it is because
14543 		 * above is_branch_taken() special cased the 0 comparison.
14544 		 */
14545 		if (!__is_pointer_value(false, dst_reg))
14546 			err = mark_chain_precision(env, insn->dst_reg);
14547 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14548 		    !__is_pointer_value(false, src_reg))
14549 			err = mark_chain_precision(env, insn->src_reg);
14550 		if (err)
14551 			return err;
14552 	}
14553 
14554 	if (pred == 1) {
14555 		/* Only follow the goto, ignore fall-through. If needed, push
14556 		 * the fall-through branch for simulation under speculative
14557 		 * execution.
14558 		 */
14559 		if (!env->bypass_spec_v1 &&
14560 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14561 					       *insn_idx))
14562 			return -EFAULT;
14563 		if (env->log.level & BPF_LOG_LEVEL)
14564 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14565 		*insn_idx += insn->off;
14566 		return 0;
14567 	} else if (pred == 0) {
14568 		/* Only follow the fall-through branch, since that's where the
14569 		 * program will go. If needed, push the goto branch for
14570 		 * simulation under speculative execution.
14571 		 */
14572 		if (!env->bypass_spec_v1 &&
14573 		    !sanitize_speculative_path(env, insn,
14574 					       *insn_idx + insn->off + 1,
14575 					       *insn_idx))
14576 			return -EFAULT;
14577 		if (env->log.level & BPF_LOG_LEVEL)
14578 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14579 		return 0;
14580 	}
14581 
14582 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14583 				  false);
14584 	if (!other_branch)
14585 		return -EFAULT;
14586 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14587 
14588 	/* detect if we are comparing against a constant value so we can adjust
14589 	 * our min/max values for our dst register.
14590 	 * this is only legit if both are scalars (or pointers to the same
14591 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14592 	 * because otherwise the different base pointers mean the offsets aren't
14593 	 * comparable.
14594 	 */
14595 	if (BPF_SRC(insn->code) == BPF_X) {
14596 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14597 
14598 		if (dst_reg->type == SCALAR_VALUE &&
14599 		    src_reg->type == SCALAR_VALUE) {
14600 			if (tnum_is_const(src_reg->var_off) ||
14601 			    (is_jmp32 &&
14602 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14603 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14604 						dst_reg,
14605 						src_reg->var_off.value,
14606 						tnum_subreg(src_reg->var_off).value,
14607 						opcode, is_jmp32);
14608 			else if (tnum_is_const(dst_reg->var_off) ||
14609 				 (is_jmp32 &&
14610 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14611 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14612 						    src_reg,
14613 						    dst_reg->var_off.value,
14614 						    tnum_subreg(dst_reg->var_off).value,
14615 						    opcode, is_jmp32);
14616 			else if (!is_jmp32 &&
14617 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14618 				/* Comparing for equality, we can combine knowledge */
14619 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14620 						    &other_branch_regs[insn->dst_reg],
14621 						    src_reg, dst_reg, opcode);
14622 			if (src_reg->id &&
14623 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14624 				find_equal_scalars(this_branch, src_reg);
14625 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14626 			}
14627 
14628 		}
14629 	} else if (dst_reg->type == SCALAR_VALUE) {
14630 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14631 					dst_reg, insn->imm, (u32)insn->imm,
14632 					opcode, is_jmp32);
14633 	}
14634 
14635 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14636 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14637 		find_equal_scalars(this_branch, dst_reg);
14638 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14639 	}
14640 
14641 	/* if one pointer register is compared to another pointer
14642 	 * register check if PTR_MAYBE_NULL could be lifted.
14643 	 * E.g. register A - maybe null
14644 	 *      register B - not null
14645 	 * for JNE A, B, ... - A is not null in the false branch;
14646 	 * for JEQ A, B, ... - A is not null in the true branch.
14647 	 *
14648 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14649 	 * not need to be null checked by the BPF program, i.e.,
14650 	 * could be null even without PTR_MAYBE_NULL marking, so
14651 	 * only propagate nullness when neither reg is that type.
14652 	 */
14653 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14654 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14655 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14656 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14657 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14658 		eq_branch_regs = NULL;
14659 		switch (opcode) {
14660 		case BPF_JEQ:
14661 			eq_branch_regs = other_branch_regs;
14662 			break;
14663 		case BPF_JNE:
14664 			eq_branch_regs = regs;
14665 			break;
14666 		default:
14667 			/* do nothing */
14668 			break;
14669 		}
14670 		if (eq_branch_regs) {
14671 			if (type_may_be_null(src_reg->type))
14672 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14673 			else
14674 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14675 		}
14676 	}
14677 
14678 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14679 	 * NOTE: these optimizations below are related with pointer comparison
14680 	 *       which will never be JMP32.
14681 	 */
14682 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14683 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14684 	    type_may_be_null(dst_reg->type)) {
14685 		/* Mark all identical registers in each branch as either
14686 		 * safe or unknown depending R == 0 or R != 0 conditional.
14687 		 */
14688 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14689 				      opcode == BPF_JNE);
14690 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14691 				      opcode == BPF_JEQ);
14692 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14693 					   this_branch, other_branch) &&
14694 		   is_pointer_value(env, insn->dst_reg)) {
14695 		verbose(env, "R%d pointer comparison prohibited\n",
14696 			insn->dst_reg);
14697 		return -EACCES;
14698 	}
14699 	if (env->log.level & BPF_LOG_LEVEL)
14700 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14701 	return 0;
14702 }
14703 
14704 /* verify BPF_LD_IMM64 instruction */
14705 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14706 {
14707 	struct bpf_insn_aux_data *aux = cur_aux(env);
14708 	struct bpf_reg_state *regs = cur_regs(env);
14709 	struct bpf_reg_state *dst_reg;
14710 	struct bpf_map *map;
14711 	int err;
14712 
14713 	if (BPF_SIZE(insn->code) != BPF_DW) {
14714 		verbose(env, "invalid BPF_LD_IMM insn\n");
14715 		return -EINVAL;
14716 	}
14717 	if (insn->off != 0) {
14718 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14719 		return -EINVAL;
14720 	}
14721 
14722 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14723 	if (err)
14724 		return err;
14725 
14726 	dst_reg = &regs[insn->dst_reg];
14727 	if (insn->src_reg == 0) {
14728 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14729 
14730 		dst_reg->type = SCALAR_VALUE;
14731 		__mark_reg_known(&regs[insn->dst_reg], imm);
14732 		return 0;
14733 	}
14734 
14735 	/* All special src_reg cases are listed below. From this point onwards
14736 	 * we either succeed and assign a corresponding dst_reg->type after
14737 	 * zeroing the offset, or fail and reject the program.
14738 	 */
14739 	mark_reg_known_zero(env, regs, insn->dst_reg);
14740 
14741 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14742 		dst_reg->type = aux->btf_var.reg_type;
14743 		switch (base_type(dst_reg->type)) {
14744 		case PTR_TO_MEM:
14745 			dst_reg->mem_size = aux->btf_var.mem_size;
14746 			break;
14747 		case PTR_TO_BTF_ID:
14748 			dst_reg->btf = aux->btf_var.btf;
14749 			dst_reg->btf_id = aux->btf_var.btf_id;
14750 			break;
14751 		default:
14752 			verbose(env, "bpf verifier is misconfigured\n");
14753 			return -EFAULT;
14754 		}
14755 		return 0;
14756 	}
14757 
14758 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14759 		struct bpf_prog_aux *aux = env->prog->aux;
14760 		u32 subprogno = find_subprog(env,
14761 					     env->insn_idx + insn->imm + 1);
14762 
14763 		if (!aux->func_info) {
14764 			verbose(env, "missing btf func_info\n");
14765 			return -EINVAL;
14766 		}
14767 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14768 			verbose(env, "callback function not static\n");
14769 			return -EINVAL;
14770 		}
14771 
14772 		dst_reg->type = PTR_TO_FUNC;
14773 		dst_reg->subprogno = subprogno;
14774 		return 0;
14775 	}
14776 
14777 	map = env->used_maps[aux->map_index];
14778 	dst_reg->map_ptr = map;
14779 
14780 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14781 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14782 		dst_reg->type = PTR_TO_MAP_VALUE;
14783 		dst_reg->off = aux->map_off;
14784 		WARN_ON_ONCE(map->max_entries != 1);
14785 		/* We want reg->id to be same (0) as map_value is not distinct */
14786 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14787 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14788 		dst_reg->type = CONST_PTR_TO_MAP;
14789 	} else {
14790 		verbose(env, "bpf verifier is misconfigured\n");
14791 		return -EINVAL;
14792 	}
14793 
14794 	return 0;
14795 }
14796 
14797 static bool may_access_skb(enum bpf_prog_type type)
14798 {
14799 	switch (type) {
14800 	case BPF_PROG_TYPE_SOCKET_FILTER:
14801 	case BPF_PROG_TYPE_SCHED_CLS:
14802 	case BPF_PROG_TYPE_SCHED_ACT:
14803 		return true;
14804 	default:
14805 		return false;
14806 	}
14807 }
14808 
14809 /* verify safety of LD_ABS|LD_IND instructions:
14810  * - they can only appear in the programs where ctx == skb
14811  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14812  *   preserve R6-R9, and store return value into R0
14813  *
14814  * Implicit input:
14815  *   ctx == skb == R6 == CTX
14816  *
14817  * Explicit input:
14818  *   SRC == any register
14819  *   IMM == 32-bit immediate
14820  *
14821  * Output:
14822  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14823  */
14824 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14825 {
14826 	struct bpf_reg_state *regs = cur_regs(env);
14827 	static const int ctx_reg = BPF_REG_6;
14828 	u8 mode = BPF_MODE(insn->code);
14829 	int i, err;
14830 
14831 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14832 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14833 		return -EINVAL;
14834 	}
14835 
14836 	if (!env->ops->gen_ld_abs) {
14837 		verbose(env, "bpf verifier is misconfigured\n");
14838 		return -EINVAL;
14839 	}
14840 
14841 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14842 	    BPF_SIZE(insn->code) == BPF_DW ||
14843 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14844 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14845 		return -EINVAL;
14846 	}
14847 
14848 	/* check whether implicit source operand (register R6) is readable */
14849 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14850 	if (err)
14851 		return err;
14852 
14853 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14854 	 * gen_ld_abs() may terminate the program at runtime, leading to
14855 	 * reference leak.
14856 	 */
14857 	err = check_reference_leak(env);
14858 	if (err) {
14859 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14860 		return err;
14861 	}
14862 
14863 	if (env->cur_state->active_lock.ptr) {
14864 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14865 		return -EINVAL;
14866 	}
14867 
14868 	if (env->cur_state->active_rcu_lock) {
14869 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14870 		return -EINVAL;
14871 	}
14872 
14873 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14874 		verbose(env,
14875 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14876 		return -EINVAL;
14877 	}
14878 
14879 	if (mode == BPF_IND) {
14880 		/* check explicit source operand */
14881 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14882 		if (err)
14883 			return err;
14884 	}
14885 
14886 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14887 	if (err < 0)
14888 		return err;
14889 
14890 	/* reset caller saved regs to unreadable */
14891 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14892 		mark_reg_not_init(env, regs, caller_saved[i]);
14893 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14894 	}
14895 
14896 	/* mark destination R0 register as readable, since it contains
14897 	 * the value fetched from the packet.
14898 	 * Already marked as written above.
14899 	 */
14900 	mark_reg_unknown(env, regs, BPF_REG_0);
14901 	/* ld_abs load up to 32-bit skb data. */
14902 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14903 	return 0;
14904 }
14905 
14906 static int check_return_code(struct bpf_verifier_env *env)
14907 {
14908 	struct tnum enforce_attach_type_range = tnum_unknown;
14909 	const struct bpf_prog *prog = env->prog;
14910 	struct bpf_reg_state *reg;
14911 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14912 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14913 	int err;
14914 	struct bpf_func_state *frame = env->cur_state->frame[0];
14915 	const bool is_subprog = frame->subprogno;
14916 
14917 	/* LSM and struct_ops func-ptr's return type could be "void" */
14918 	if (!is_subprog) {
14919 		switch (prog_type) {
14920 		case BPF_PROG_TYPE_LSM:
14921 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14922 				/* See below, can be 0 or 0-1 depending on hook. */
14923 				break;
14924 			fallthrough;
14925 		case BPF_PROG_TYPE_STRUCT_OPS:
14926 			if (!prog->aux->attach_func_proto->type)
14927 				return 0;
14928 			break;
14929 		default:
14930 			break;
14931 		}
14932 	}
14933 
14934 	/* eBPF calling convention is such that R0 is used
14935 	 * to return the value from eBPF program.
14936 	 * Make sure that it's readable at this time
14937 	 * of bpf_exit, which means that program wrote
14938 	 * something into it earlier
14939 	 */
14940 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14941 	if (err)
14942 		return err;
14943 
14944 	if (is_pointer_value(env, BPF_REG_0)) {
14945 		verbose(env, "R0 leaks addr as return value\n");
14946 		return -EACCES;
14947 	}
14948 
14949 	reg = cur_regs(env) + BPF_REG_0;
14950 
14951 	if (frame->in_async_callback_fn) {
14952 		/* enforce return zero from async callbacks like timer */
14953 		if (reg->type != SCALAR_VALUE) {
14954 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14955 				reg_type_str(env, reg->type));
14956 			return -EINVAL;
14957 		}
14958 
14959 		if (!tnum_in(const_0, reg->var_off)) {
14960 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14961 			return -EINVAL;
14962 		}
14963 		return 0;
14964 	}
14965 
14966 	if (is_subprog) {
14967 		if (reg->type != SCALAR_VALUE) {
14968 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14969 				reg_type_str(env, reg->type));
14970 			return -EINVAL;
14971 		}
14972 		return 0;
14973 	}
14974 
14975 	switch (prog_type) {
14976 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14977 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14978 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14979 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14980 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14981 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14982 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14983 			range = tnum_range(1, 1);
14984 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14985 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14986 			range = tnum_range(0, 3);
14987 		break;
14988 	case BPF_PROG_TYPE_CGROUP_SKB:
14989 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14990 			range = tnum_range(0, 3);
14991 			enforce_attach_type_range = tnum_range(2, 3);
14992 		}
14993 		break;
14994 	case BPF_PROG_TYPE_CGROUP_SOCK:
14995 	case BPF_PROG_TYPE_SOCK_OPS:
14996 	case BPF_PROG_TYPE_CGROUP_DEVICE:
14997 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
14998 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14999 		break;
15000 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15001 		if (!env->prog->aux->attach_btf_id)
15002 			return 0;
15003 		range = tnum_const(0);
15004 		break;
15005 	case BPF_PROG_TYPE_TRACING:
15006 		switch (env->prog->expected_attach_type) {
15007 		case BPF_TRACE_FENTRY:
15008 		case BPF_TRACE_FEXIT:
15009 			range = tnum_const(0);
15010 			break;
15011 		case BPF_TRACE_RAW_TP:
15012 		case BPF_MODIFY_RETURN:
15013 			return 0;
15014 		case BPF_TRACE_ITER:
15015 			break;
15016 		default:
15017 			return -ENOTSUPP;
15018 		}
15019 		break;
15020 	case BPF_PROG_TYPE_SK_LOOKUP:
15021 		range = tnum_range(SK_DROP, SK_PASS);
15022 		break;
15023 
15024 	case BPF_PROG_TYPE_LSM:
15025 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15026 			/* Regular BPF_PROG_TYPE_LSM programs can return
15027 			 * any value.
15028 			 */
15029 			return 0;
15030 		}
15031 		if (!env->prog->aux->attach_func_proto->type) {
15032 			/* Make sure programs that attach to void
15033 			 * hooks don't try to modify return value.
15034 			 */
15035 			range = tnum_range(1, 1);
15036 		}
15037 		break;
15038 
15039 	case BPF_PROG_TYPE_NETFILTER:
15040 		range = tnum_range(NF_DROP, NF_ACCEPT);
15041 		break;
15042 	case BPF_PROG_TYPE_EXT:
15043 		/* freplace program can return anything as its return value
15044 		 * depends on the to-be-replaced kernel func or bpf program.
15045 		 */
15046 	default:
15047 		return 0;
15048 	}
15049 
15050 	if (reg->type != SCALAR_VALUE) {
15051 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15052 			reg_type_str(env, reg->type));
15053 		return -EINVAL;
15054 	}
15055 
15056 	if (!tnum_in(range, reg->var_off)) {
15057 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15058 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15059 		    prog_type == BPF_PROG_TYPE_LSM &&
15060 		    !prog->aux->attach_func_proto->type)
15061 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15062 		return -EINVAL;
15063 	}
15064 
15065 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15066 	    tnum_in(enforce_attach_type_range, reg->var_off))
15067 		env->prog->enforce_expected_attach_type = 1;
15068 	return 0;
15069 }
15070 
15071 /* non-recursive DFS pseudo code
15072  * 1  procedure DFS-iterative(G,v):
15073  * 2      label v as discovered
15074  * 3      let S be a stack
15075  * 4      S.push(v)
15076  * 5      while S is not empty
15077  * 6            t <- S.peek()
15078  * 7            if t is what we're looking for:
15079  * 8                return t
15080  * 9            for all edges e in G.adjacentEdges(t) do
15081  * 10               if edge e is already labelled
15082  * 11                   continue with the next edge
15083  * 12               w <- G.adjacentVertex(t,e)
15084  * 13               if vertex w is not discovered and not explored
15085  * 14                   label e as tree-edge
15086  * 15                   label w as discovered
15087  * 16                   S.push(w)
15088  * 17                   continue at 5
15089  * 18               else if vertex w is discovered
15090  * 19                   label e as back-edge
15091  * 20               else
15092  * 21                   // vertex w is explored
15093  * 22                   label e as forward- or cross-edge
15094  * 23           label t as explored
15095  * 24           S.pop()
15096  *
15097  * convention:
15098  * 0x10 - discovered
15099  * 0x11 - discovered and fall-through edge labelled
15100  * 0x12 - discovered and fall-through and branch edges labelled
15101  * 0x20 - explored
15102  */
15103 
15104 enum {
15105 	DISCOVERED = 0x10,
15106 	EXPLORED = 0x20,
15107 	FALLTHROUGH = 1,
15108 	BRANCH = 2,
15109 };
15110 
15111 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15112 {
15113 	env->insn_aux_data[idx].prune_point = true;
15114 }
15115 
15116 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15117 {
15118 	return env->insn_aux_data[insn_idx].prune_point;
15119 }
15120 
15121 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15122 {
15123 	env->insn_aux_data[idx].force_checkpoint = true;
15124 }
15125 
15126 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15127 {
15128 	return env->insn_aux_data[insn_idx].force_checkpoint;
15129 }
15130 
15131 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15132 {
15133 	env->insn_aux_data[idx].calls_callback = true;
15134 }
15135 
15136 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15137 {
15138 	return env->insn_aux_data[insn_idx].calls_callback;
15139 }
15140 
15141 enum {
15142 	DONE_EXPLORING = 0,
15143 	KEEP_EXPLORING = 1,
15144 };
15145 
15146 /* t, w, e - match pseudo-code above:
15147  * t - index of current instruction
15148  * w - next instruction
15149  * e - edge
15150  */
15151 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15152 {
15153 	int *insn_stack = env->cfg.insn_stack;
15154 	int *insn_state = env->cfg.insn_state;
15155 
15156 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15157 		return DONE_EXPLORING;
15158 
15159 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15160 		return DONE_EXPLORING;
15161 
15162 	if (w < 0 || w >= env->prog->len) {
15163 		verbose_linfo(env, t, "%d: ", t);
15164 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15165 		return -EINVAL;
15166 	}
15167 
15168 	if (e == BRANCH) {
15169 		/* mark branch target for state pruning */
15170 		mark_prune_point(env, w);
15171 		mark_jmp_point(env, w);
15172 	}
15173 
15174 	if (insn_state[w] == 0) {
15175 		/* tree-edge */
15176 		insn_state[t] = DISCOVERED | e;
15177 		insn_state[w] = DISCOVERED;
15178 		if (env->cfg.cur_stack >= env->prog->len)
15179 			return -E2BIG;
15180 		insn_stack[env->cfg.cur_stack++] = w;
15181 		return KEEP_EXPLORING;
15182 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15183 		if (env->bpf_capable)
15184 			return DONE_EXPLORING;
15185 		verbose_linfo(env, t, "%d: ", t);
15186 		verbose_linfo(env, w, "%d: ", w);
15187 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15188 		return -EINVAL;
15189 	} else if (insn_state[w] == EXPLORED) {
15190 		/* forward- or cross-edge */
15191 		insn_state[t] = DISCOVERED | e;
15192 	} else {
15193 		verbose(env, "insn state internal bug\n");
15194 		return -EFAULT;
15195 	}
15196 	return DONE_EXPLORING;
15197 }
15198 
15199 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15200 				struct bpf_verifier_env *env,
15201 				bool visit_callee)
15202 {
15203 	int ret, insn_sz;
15204 
15205 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15206 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15207 	if (ret)
15208 		return ret;
15209 
15210 	mark_prune_point(env, t + insn_sz);
15211 	/* when we exit from subprog, we need to record non-linear history */
15212 	mark_jmp_point(env, t + insn_sz);
15213 
15214 	if (visit_callee) {
15215 		mark_prune_point(env, t);
15216 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15217 	}
15218 	return ret;
15219 }
15220 
15221 /* Visits the instruction at index t and returns one of the following:
15222  *  < 0 - an error occurred
15223  *  DONE_EXPLORING - the instruction was fully explored
15224  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15225  */
15226 static int visit_insn(int t, struct bpf_verifier_env *env)
15227 {
15228 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15229 	int ret, off, insn_sz;
15230 
15231 	if (bpf_pseudo_func(insn))
15232 		return visit_func_call_insn(t, insns, env, true);
15233 
15234 	/* All non-branch instructions have a single fall-through edge. */
15235 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15236 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15237 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15238 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15239 	}
15240 
15241 	switch (BPF_OP(insn->code)) {
15242 	case BPF_EXIT:
15243 		return DONE_EXPLORING;
15244 
15245 	case BPF_CALL:
15246 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15247 			/* Mark this call insn as a prune point to trigger
15248 			 * is_state_visited() check before call itself is
15249 			 * processed by __check_func_call(). Otherwise new
15250 			 * async state will be pushed for further exploration.
15251 			 */
15252 			mark_prune_point(env, t);
15253 		/* For functions that invoke callbacks it is not known how many times
15254 		 * callback would be called. Verifier models callback calling functions
15255 		 * by repeatedly visiting callback bodies and returning to origin call
15256 		 * instruction.
15257 		 * In order to stop such iteration verifier needs to identify when a
15258 		 * state identical some state from a previous iteration is reached.
15259 		 * Check below forces creation of checkpoint before callback calling
15260 		 * instruction to allow search for such identical states.
15261 		 */
15262 		if (is_sync_callback_calling_insn(insn)) {
15263 			mark_calls_callback(env, t);
15264 			mark_force_checkpoint(env, t);
15265 			mark_prune_point(env, t);
15266 			mark_jmp_point(env, t);
15267 		}
15268 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15269 			struct bpf_kfunc_call_arg_meta meta;
15270 
15271 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15272 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15273 				mark_prune_point(env, t);
15274 				/* Checking and saving state checkpoints at iter_next() call
15275 				 * is crucial for fast convergence of open-coded iterator loop
15276 				 * logic, so we need to force it. If we don't do that,
15277 				 * is_state_visited() might skip saving a checkpoint, causing
15278 				 * unnecessarily long sequence of not checkpointed
15279 				 * instructions and jumps, leading to exhaustion of jump
15280 				 * history buffer, and potentially other undesired outcomes.
15281 				 * It is expected that with correct open-coded iterators
15282 				 * convergence will happen quickly, so we don't run a risk of
15283 				 * exhausting memory.
15284 				 */
15285 				mark_force_checkpoint(env, t);
15286 			}
15287 		}
15288 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15289 
15290 	case BPF_JA:
15291 		if (BPF_SRC(insn->code) != BPF_K)
15292 			return -EINVAL;
15293 
15294 		if (BPF_CLASS(insn->code) == BPF_JMP)
15295 			off = insn->off;
15296 		else
15297 			off = insn->imm;
15298 
15299 		/* unconditional jump with single edge */
15300 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15301 		if (ret)
15302 			return ret;
15303 
15304 		mark_prune_point(env, t + off + 1);
15305 		mark_jmp_point(env, t + off + 1);
15306 
15307 		return ret;
15308 
15309 	default:
15310 		/* conditional jump with two edges */
15311 		mark_prune_point(env, t);
15312 
15313 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15314 		if (ret)
15315 			return ret;
15316 
15317 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15318 	}
15319 }
15320 
15321 /* non-recursive depth-first-search to detect loops in BPF program
15322  * loop == back-edge in directed graph
15323  */
15324 static int check_cfg(struct bpf_verifier_env *env)
15325 {
15326 	int insn_cnt = env->prog->len;
15327 	int *insn_stack, *insn_state;
15328 	int ret = 0;
15329 	int i;
15330 
15331 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15332 	if (!insn_state)
15333 		return -ENOMEM;
15334 
15335 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15336 	if (!insn_stack) {
15337 		kvfree(insn_state);
15338 		return -ENOMEM;
15339 	}
15340 
15341 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15342 	insn_stack[0] = 0; /* 0 is the first instruction */
15343 	env->cfg.cur_stack = 1;
15344 
15345 	while (env->cfg.cur_stack > 0) {
15346 		int t = insn_stack[env->cfg.cur_stack - 1];
15347 
15348 		ret = visit_insn(t, env);
15349 		switch (ret) {
15350 		case DONE_EXPLORING:
15351 			insn_state[t] = EXPLORED;
15352 			env->cfg.cur_stack--;
15353 			break;
15354 		case KEEP_EXPLORING:
15355 			break;
15356 		default:
15357 			if (ret > 0) {
15358 				verbose(env, "visit_insn internal bug\n");
15359 				ret = -EFAULT;
15360 			}
15361 			goto err_free;
15362 		}
15363 	}
15364 
15365 	if (env->cfg.cur_stack < 0) {
15366 		verbose(env, "pop stack internal bug\n");
15367 		ret = -EFAULT;
15368 		goto err_free;
15369 	}
15370 
15371 	for (i = 0; i < insn_cnt; i++) {
15372 		struct bpf_insn *insn = &env->prog->insnsi[i];
15373 
15374 		if (insn_state[i] != EXPLORED) {
15375 			verbose(env, "unreachable insn %d\n", i);
15376 			ret = -EINVAL;
15377 			goto err_free;
15378 		}
15379 		if (bpf_is_ldimm64(insn)) {
15380 			if (insn_state[i + 1] != 0) {
15381 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15382 				ret = -EINVAL;
15383 				goto err_free;
15384 			}
15385 			i++; /* skip second half of ldimm64 */
15386 		}
15387 	}
15388 	ret = 0; /* cfg looks good */
15389 
15390 err_free:
15391 	kvfree(insn_state);
15392 	kvfree(insn_stack);
15393 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15394 	return ret;
15395 }
15396 
15397 static int check_abnormal_return(struct bpf_verifier_env *env)
15398 {
15399 	int i;
15400 
15401 	for (i = 1; i < env->subprog_cnt; i++) {
15402 		if (env->subprog_info[i].has_ld_abs) {
15403 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15404 			return -EINVAL;
15405 		}
15406 		if (env->subprog_info[i].has_tail_call) {
15407 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15408 			return -EINVAL;
15409 		}
15410 	}
15411 	return 0;
15412 }
15413 
15414 /* The minimum supported BTF func info size */
15415 #define MIN_BPF_FUNCINFO_SIZE	8
15416 #define MAX_FUNCINFO_REC_SIZE	252
15417 
15418 static int check_btf_func(struct bpf_verifier_env *env,
15419 			  const union bpf_attr *attr,
15420 			  bpfptr_t uattr)
15421 {
15422 	const struct btf_type *type, *func_proto, *ret_type;
15423 	u32 i, nfuncs, urec_size, min_size;
15424 	u32 krec_size = sizeof(struct bpf_func_info);
15425 	struct bpf_func_info *krecord;
15426 	struct bpf_func_info_aux *info_aux = NULL;
15427 	struct bpf_prog *prog;
15428 	const struct btf *btf;
15429 	bpfptr_t urecord;
15430 	u32 prev_offset = 0;
15431 	bool scalar_return;
15432 	int ret = -ENOMEM;
15433 
15434 	nfuncs = attr->func_info_cnt;
15435 	if (!nfuncs) {
15436 		if (check_abnormal_return(env))
15437 			return -EINVAL;
15438 		return 0;
15439 	}
15440 
15441 	if (nfuncs != env->subprog_cnt) {
15442 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15443 		return -EINVAL;
15444 	}
15445 
15446 	urec_size = attr->func_info_rec_size;
15447 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15448 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15449 	    urec_size % sizeof(u32)) {
15450 		verbose(env, "invalid func info rec size %u\n", urec_size);
15451 		return -EINVAL;
15452 	}
15453 
15454 	prog = env->prog;
15455 	btf = prog->aux->btf;
15456 
15457 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15458 	min_size = min_t(u32, krec_size, urec_size);
15459 
15460 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15461 	if (!krecord)
15462 		return -ENOMEM;
15463 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15464 	if (!info_aux)
15465 		goto err_free;
15466 
15467 	for (i = 0; i < nfuncs; i++) {
15468 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15469 		if (ret) {
15470 			if (ret == -E2BIG) {
15471 				verbose(env, "nonzero tailing record in func info");
15472 				/* set the size kernel expects so loader can zero
15473 				 * out the rest of the record.
15474 				 */
15475 				if (copy_to_bpfptr_offset(uattr,
15476 							  offsetof(union bpf_attr, func_info_rec_size),
15477 							  &min_size, sizeof(min_size)))
15478 					ret = -EFAULT;
15479 			}
15480 			goto err_free;
15481 		}
15482 
15483 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15484 			ret = -EFAULT;
15485 			goto err_free;
15486 		}
15487 
15488 		/* check insn_off */
15489 		ret = -EINVAL;
15490 		if (i == 0) {
15491 			if (krecord[i].insn_off) {
15492 				verbose(env,
15493 					"nonzero insn_off %u for the first func info record",
15494 					krecord[i].insn_off);
15495 				goto err_free;
15496 			}
15497 		} else if (krecord[i].insn_off <= prev_offset) {
15498 			verbose(env,
15499 				"same or smaller insn offset (%u) than previous func info record (%u)",
15500 				krecord[i].insn_off, prev_offset);
15501 			goto err_free;
15502 		}
15503 
15504 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15505 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15506 			goto err_free;
15507 		}
15508 
15509 		/* check type_id */
15510 		type = btf_type_by_id(btf, krecord[i].type_id);
15511 		if (!type || !btf_type_is_func(type)) {
15512 			verbose(env, "invalid type id %d in func info",
15513 				krecord[i].type_id);
15514 			goto err_free;
15515 		}
15516 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15517 
15518 		func_proto = btf_type_by_id(btf, type->type);
15519 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15520 			/* btf_func_check() already verified it during BTF load */
15521 			goto err_free;
15522 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15523 		scalar_return =
15524 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15525 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15526 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15527 			goto err_free;
15528 		}
15529 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15530 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15531 			goto err_free;
15532 		}
15533 
15534 		prev_offset = krecord[i].insn_off;
15535 		bpfptr_add(&urecord, urec_size);
15536 	}
15537 
15538 	prog->aux->func_info = krecord;
15539 	prog->aux->func_info_cnt = nfuncs;
15540 	prog->aux->func_info_aux = info_aux;
15541 	return 0;
15542 
15543 err_free:
15544 	kvfree(krecord);
15545 	kfree(info_aux);
15546 	return ret;
15547 }
15548 
15549 static void adjust_btf_func(struct bpf_verifier_env *env)
15550 {
15551 	struct bpf_prog_aux *aux = env->prog->aux;
15552 	int i;
15553 
15554 	if (!aux->func_info)
15555 		return;
15556 
15557 	for (i = 0; i < env->subprog_cnt; i++)
15558 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15559 }
15560 
15561 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15562 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15563 
15564 static int check_btf_line(struct bpf_verifier_env *env,
15565 			  const union bpf_attr *attr,
15566 			  bpfptr_t uattr)
15567 {
15568 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15569 	struct bpf_subprog_info *sub;
15570 	struct bpf_line_info *linfo;
15571 	struct bpf_prog *prog;
15572 	const struct btf *btf;
15573 	bpfptr_t ulinfo;
15574 	int err;
15575 
15576 	nr_linfo = attr->line_info_cnt;
15577 	if (!nr_linfo)
15578 		return 0;
15579 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15580 		return -EINVAL;
15581 
15582 	rec_size = attr->line_info_rec_size;
15583 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15584 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15585 	    rec_size & (sizeof(u32) - 1))
15586 		return -EINVAL;
15587 
15588 	/* Need to zero it in case the userspace may
15589 	 * pass in a smaller bpf_line_info object.
15590 	 */
15591 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15592 			 GFP_KERNEL | __GFP_NOWARN);
15593 	if (!linfo)
15594 		return -ENOMEM;
15595 
15596 	prog = env->prog;
15597 	btf = prog->aux->btf;
15598 
15599 	s = 0;
15600 	sub = env->subprog_info;
15601 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15602 	expected_size = sizeof(struct bpf_line_info);
15603 	ncopy = min_t(u32, expected_size, rec_size);
15604 	for (i = 0; i < nr_linfo; i++) {
15605 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15606 		if (err) {
15607 			if (err == -E2BIG) {
15608 				verbose(env, "nonzero tailing record in line_info");
15609 				if (copy_to_bpfptr_offset(uattr,
15610 							  offsetof(union bpf_attr, line_info_rec_size),
15611 							  &expected_size, sizeof(expected_size)))
15612 					err = -EFAULT;
15613 			}
15614 			goto err_free;
15615 		}
15616 
15617 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15618 			err = -EFAULT;
15619 			goto err_free;
15620 		}
15621 
15622 		/*
15623 		 * Check insn_off to ensure
15624 		 * 1) strictly increasing AND
15625 		 * 2) bounded by prog->len
15626 		 *
15627 		 * The linfo[0].insn_off == 0 check logically falls into
15628 		 * the later "missing bpf_line_info for func..." case
15629 		 * because the first linfo[0].insn_off must be the
15630 		 * first sub also and the first sub must have
15631 		 * subprog_info[0].start == 0.
15632 		 */
15633 		if ((i && linfo[i].insn_off <= prev_offset) ||
15634 		    linfo[i].insn_off >= prog->len) {
15635 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15636 				i, linfo[i].insn_off, prev_offset,
15637 				prog->len);
15638 			err = -EINVAL;
15639 			goto err_free;
15640 		}
15641 
15642 		if (!prog->insnsi[linfo[i].insn_off].code) {
15643 			verbose(env,
15644 				"Invalid insn code at line_info[%u].insn_off\n",
15645 				i);
15646 			err = -EINVAL;
15647 			goto err_free;
15648 		}
15649 
15650 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15651 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15652 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15653 			err = -EINVAL;
15654 			goto err_free;
15655 		}
15656 
15657 		if (s != env->subprog_cnt) {
15658 			if (linfo[i].insn_off == sub[s].start) {
15659 				sub[s].linfo_idx = i;
15660 				s++;
15661 			} else if (sub[s].start < linfo[i].insn_off) {
15662 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15663 				err = -EINVAL;
15664 				goto err_free;
15665 			}
15666 		}
15667 
15668 		prev_offset = linfo[i].insn_off;
15669 		bpfptr_add(&ulinfo, rec_size);
15670 	}
15671 
15672 	if (s != env->subprog_cnt) {
15673 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15674 			env->subprog_cnt - s, s);
15675 		err = -EINVAL;
15676 		goto err_free;
15677 	}
15678 
15679 	prog->aux->linfo = linfo;
15680 	prog->aux->nr_linfo = nr_linfo;
15681 
15682 	return 0;
15683 
15684 err_free:
15685 	kvfree(linfo);
15686 	return err;
15687 }
15688 
15689 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15690 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15691 
15692 static int check_core_relo(struct bpf_verifier_env *env,
15693 			   const union bpf_attr *attr,
15694 			   bpfptr_t uattr)
15695 {
15696 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15697 	struct bpf_core_relo core_relo = {};
15698 	struct bpf_prog *prog = env->prog;
15699 	const struct btf *btf = prog->aux->btf;
15700 	struct bpf_core_ctx ctx = {
15701 		.log = &env->log,
15702 		.btf = btf,
15703 	};
15704 	bpfptr_t u_core_relo;
15705 	int err;
15706 
15707 	nr_core_relo = attr->core_relo_cnt;
15708 	if (!nr_core_relo)
15709 		return 0;
15710 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15711 		return -EINVAL;
15712 
15713 	rec_size = attr->core_relo_rec_size;
15714 	if (rec_size < MIN_CORE_RELO_SIZE ||
15715 	    rec_size > MAX_CORE_RELO_SIZE ||
15716 	    rec_size % sizeof(u32))
15717 		return -EINVAL;
15718 
15719 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15720 	expected_size = sizeof(struct bpf_core_relo);
15721 	ncopy = min_t(u32, expected_size, rec_size);
15722 
15723 	/* Unlike func_info and line_info, copy and apply each CO-RE
15724 	 * relocation record one at a time.
15725 	 */
15726 	for (i = 0; i < nr_core_relo; i++) {
15727 		/* future proofing when sizeof(bpf_core_relo) changes */
15728 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15729 		if (err) {
15730 			if (err == -E2BIG) {
15731 				verbose(env, "nonzero tailing record in core_relo");
15732 				if (copy_to_bpfptr_offset(uattr,
15733 							  offsetof(union bpf_attr, core_relo_rec_size),
15734 							  &expected_size, sizeof(expected_size)))
15735 					err = -EFAULT;
15736 			}
15737 			break;
15738 		}
15739 
15740 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15741 			err = -EFAULT;
15742 			break;
15743 		}
15744 
15745 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15746 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15747 				i, core_relo.insn_off, prog->len);
15748 			err = -EINVAL;
15749 			break;
15750 		}
15751 
15752 		err = bpf_core_apply(&ctx, &core_relo, i,
15753 				     &prog->insnsi[core_relo.insn_off / 8]);
15754 		if (err)
15755 			break;
15756 		bpfptr_add(&u_core_relo, rec_size);
15757 	}
15758 	return err;
15759 }
15760 
15761 static int check_btf_info(struct bpf_verifier_env *env,
15762 			  const union bpf_attr *attr,
15763 			  bpfptr_t uattr)
15764 {
15765 	struct btf *btf;
15766 	int err;
15767 
15768 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15769 		if (check_abnormal_return(env))
15770 			return -EINVAL;
15771 		return 0;
15772 	}
15773 
15774 	btf = btf_get_by_fd(attr->prog_btf_fd);
15775 	if (IS_ERR(btf))
15776 		return PTR_ERR(btf);
15777 	if (btf_is_kernel(btf)) {
15778 		btf_put(btf);
15779 		return -EACCES;
15780 	}
15781 	env->prog->aux->btf = btf;
15782 
15783 	err = check_btf_func(env, attr, uattr);
15784 	if (err)
15785 		return err;
15786 
15787 	err = check_btf_line(env, attr, uattr);
15788 	if (err)
15789 		return err;
15790 
15791 	err = check_core_relo(env, attr, uattr);
15792 	if (err)
15793 		return err;
15794 
15795 	return 0;
15796 }
15797 
15798 /* check %cur's range satisfies %old's */
15799 static bool range_within(struct bpf_reg_state *old,
15800 			 struct bpf_reg_state *cur)
15801 {
15802 	return old->umin_value <= cur->umin_value &&
15803 	       old->umax_value >= cur->umax_value &&
15804 	       old->smin_value <= cur->smin_value &&
15805 	       old->smax_value >= cur->smax_value &&
15806 	       old->u32_min_value <= cur->u32_min_value &&
15807 	       old->u32_max_value >= cur->u32_max_value &&
15808 	       old->s32_min_value <= cur->s32_min_value &&
15809 	       old->s32_max_value >= cur->s32_max_value;
15810 }
15811 
15812 /* If in the old state two registers had the same id, then they need to have
15813  * the same id in the new state as well.  But that id could be different from
15814  * the old state, so we need to track the mapping from old to new ids.
15815  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15816  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15817  * regs with a different old id could still have new id 9, we don't care about
15818  * that.
15819  * So we look through our idmap to see if this old id has been seen before.  If
15820  * so, we require the new id to match; otherwise, we add the id pair to the map.
15821  */
15822 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15823 {
15824 	struct bpf_id_pair *map = idmap->map;
15825 	unsigned int i;
15826 
15827 	/* either both IDs should be set or both should be zero */
15828 	if (!!old_id != !!cur_id)
15829 		return false;
15830 
15831 	if (old_id == 0) /* cur_id == 0 as well */
15832 		return true;
15833 
15834 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15835 		if (!map[i].old) {
15836 			/* Reached an empty slot; haven't seen this id before */
15837 			map[i].old = old_id;
15838 			map[i].cur = cur_id;
15839 			return true;
15840 		}
15841 		if (map[i].old == old_id)
15842 			return map[i].cur == cur_id;
15843 		if (map[i].cur == cur_id)
15844 			return false;
15845 	}
15846 	/* We ran out of idmap slots, which should be impossible */
15847 	WARN_ON_ONCE(1);
15848 	return false;
15849 }
15850 
15851 /* Similar to check_ids(), but allocate a unique temporary ID
15852  * for 'old_id' or 'cur_id' of zero.
15853  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15854  */
15855 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15856 {
15857 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15858 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15859 
15860 	return check_ids(old_id, cur_id, idmap);
15861 }
15862 
15863 static void clean_func_state(struct bpf_verifier_env *env,
15864 			     struct bpf_func_state *st)
15865 {
15866 	enum bpf_reg_liveness live;
15867 	int i, j;
15868 
15869 	for (i = 0; i < BPF_REG_FP; i++) {
15870 		live = st->regs[i].live;
15871 		/* liveness must not touch this register anymore */
15872 		st->regs[i].live |= REG_LIVE_DONE;
15873 		if (!(live & REG_LIVE_READ))
15874 			/* since the register is unused, clear its state
15875 			 * to make further comparison simpler
15876 			 */
15877 			__mark_reg_not_init(env, &st->regs[i]);
15878 	}
15879 
15880 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15881 		live = st->stack[i].spilled_ptr.live;
15882 		/* liveness must not touch this stack slot anymore */
15883 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15884 		if (!(live & REG_LIVE_READ)) {
15885 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15886 			for (j = 0; j < BPF_REG_SIZE; j++)
15887 				st->stack[i].slot_type[j] = STACK_INVALID;
15888 		}
15889 	}
15890 }
15891 
15892 static void clean_verifier_state(struct bpf_verifier_env *env,
15893 				 struct bpf_verifier_state *st)
15894 {
15895 	int i;
15896 
15897 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15898 		/* all regs in this state in all frames were already marked */
15899 		return;
15900 
15901 	for (i = 0; i <= st->curframe; i++)
15902 		clean_func_state(env, st->frame[i]);
15903 }
15904 
15905 /* the parentage chains form a tree.
15906  * the verifier states are added to state lists at given insn and
15907  * pushed into state stack for future exploration.
15908  * when the verifier reaches bpf_exit insn some of the verifer states
15909  * stored in the state lists have their final liveness state already,
15910  * but a lot of states will get revised from liveness point of view when
15911  * the verifier explores other branches.
15912  * Example:
15913  * 1: r0 = 1
15914  * 2: if r1 == 100 goto pc+1
15915  * 3: r0 = 2
15916  * 4: exit
15917  * when the verifier reaches exit insn the register r0 in the state list of
15918  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15919  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15920  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15921  *
15922  * Since the verifier pushes the branch states as it sees them while exploring
15923  * the program the condition of walking the branch instruction for the second
15924  * time means that all states below this branch were already explored and
15925  * their final liveness marks are already propagated.
15926  * Hence when the verifier completes the search of state list in is_state_visited()
15927  * we can call this clean_live_states() function to mark all liveness states
15928  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15929  * will not be used.
15930  * This function also clears the registers and stack for states that !READ
15931  * to simplify state merging.
15932  *
15933  * Important note here that walking the same branch instruction in the callee
15934  * doesn't meant that the states are DONE. The verifier has to compare
15935  * the callsites
15936  */
15937 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15938 			      struct bpf_verifier_state *cur)
15939 {
15940 	struct bpf_verifier_state_list *sl;
15941 
15942 	sl = *explored_state(env, insn);
15943 	while (sl) {
15944 		if (sl->state.branches)
15945 			goto next;
15946 		if (sl->state.insn_idx != insn ||
15947 		    !same_callsites(&sl->state, cur))
15948 			goto next;
15949 		clean_verifier_state(env, &sl->state);
15950 next:
15951 		sl = sl->next;
15952 	}
15953 }
15954 
15955 static bool regs_exact(const struct bpf_reg_state *rold,
15956 		       const struct bpf_reg_state *rcur,
15957 		       struct bpf_idmap *idmap)
15958 {
15959 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15960 	       check_ids(rold->id, rcur->id, idmap) &&
15961 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15962 }
15963 
15964 /* Returns true if (rold safe implies rcur safe) */
15965 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15966 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15967 {
15968 	if (exact)
15969 		return regs_exact(rold, rcur, idmap);
15970 
15971 	if (!(rold->live & REG_LIVE_READ))
15972 		/* explored state didn't use this */
15973 		return true;
15974 	if (rold->type == NOT_INIT)
15975 		/* explored state can't have used this */
15976 		return true;
15977 	if (rcur->type == NOT_INIT)
15978 		return false;
15979 
15980 	/* Enforce that register types have to match exactly, including their
15981 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15982 	 * rule.
15983 	 *
15984 	 * One can make a point that using a pointer register as unbounded
15985 	 * SCALAR would be technically acceptable, but this could lead to
15986 	 * pointer leaks because scalars are allowed to leak while pointers
15987 	 * are not. We could make this safe in special cases if root is
15988 	 * calling us, but it's probably not worth the hassle.
15989 	 *
15990 	 * Also, register types that are *not* MAYBE_NULL could technically be
15991 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15992 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15993 	 * to the same map).
15994 	 * However, if the old MAYBE_NULL register then got NULL checked,
15995 	 * doing so could have affected others with the same id, and we can't
15996 	 * check for that because we lost the id when we converted to
15997 	 * a non-MAYBE_NULL variant.
15998 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
15999 	 * non-MAYBE_NULL registers as well.
16000 	 */
16001 	if (rold->type != rcur->type)
16002 		return false;
16003 
16004 	switch (base_type(rold->type)) {
16005 	case SCALAR_VALUE:
16006 		if (env->explore_alu_limits) {
16007 			/* explore_alu_limits disables tnum_in() and range_within()
16008 			 * logic and requires everything to be strict
16009 			 */
16010 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16011 			       check_scalar_ids(rold->id, rcur->id, idmap);
16012 		}
16013 		if (!rold->precise)
16014 			return true;
16015 		/* Why check_ids() for scalar registers?
16016 		 *
16017 		 * Consider the following BPF code:
16018 		 *   1: r6 = ... unbound scalar, ID=a ...
16019 		 *   2: r7 = ... unbound scalar, ID=b ...
16020 		 *   3: if (r6 > r7) goto +1
16021 		 *   4: r6 = r7
16022 		 *   5: if (r6 > X) goto ...
16023 		 *   6: ... memory operation using r7 ...
16024 		 *
16025 		 * First verification path is [1-6]:
16026 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16027 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16028 		 *   r7 <= X, because r6 and r7 share same id.
16029 		 * Next verification path is [1-4, 6].
16030 		 *
16031 		 * Instruction (6) would be reached in two states:
16032 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16033 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16034 		 *
16035 		 * Use check_ids() to distinguish these states.
16036 		 * ---
16037 		 * Also verify that new value satisfies old value range knowledge.
16038 		 */
16039 		return range_within(rold, rcur) &&
16040 		       tnum_in(rold->var_off, rcur->var_off) &&
16041 		       check_scalar_ids(rold->id, rcur->id, idmap);
16042 	case PTR_TO_MAP_KEY:
16043 	case PTR_TO_MAP_VALUE:
16044 	case PTR_TO_MEM:
16045 	case PTR_TO_BUF:
16046 	case PTR_TO_TP_BUFFER:
16047 		/* If the new min/max/var_off satisfy the old ones and
16048 		 * everything else matches, we are OK.
16049 		 */
16050 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16051 		       range_within(rold, rcur) &&
16052 		       tnum_in(rold->var_off, rcur->var_off) &&
16053 		       check_ids(rold->id, rcur->id, idmap) &&
16054 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16055 	case PTR_TO_PACKET_META:
16056 	case PTR_TO_PACKET:
16057 		/* We must have at least as much range as the old ptr
16058 		 * did, so that any accesses which were safe before are
16059 		 * still safe.  This is true even if old range < old off,
16060 		 * since someone could have accessed through (ptr - k), or
16061 		 * even done ptr -= k in a register, to get a safe access.
16062 		 */
16063 		if (rold->range > rcur->range)
16064 			return false;
16065 		/* If the offsets don't match, we can't trust our alignment;
16066 		 * nor can we be sure that we won't fall out of range.
16067 		 */
16068 		if (rold->off != rcur->off)
16069 			return false;
16070 		/* id relations must be preserved */
16071 		if (!check_ids(rold->id, rcur->id, idmap))
16072 			return false;
16073 		/* new val must satisfy old val knowledge */
16074 		return range_within(rold, rcur) &&
16075 		       tnum_in(rold->var_off, rcur->var_off);
16076 	case PTR_TO_STACK:
16077 		/* two stack pointers are equal only if they're pointing to
16078 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16079 		 */
16080 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16081 	default:
16082 		return regs_exact(rold, rcur, idmap);
16083 	}
16084 }
16085 
16086 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16087 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16088 {
16089 	int i, spi;
16090 
16091 	/* walk slots of the explored stack and ignore any additional
16092 	 * slots in the current stack, since explored(safe) state
16093 	 * didn't use them
16094 	 */
16095 	for (i = 0; i < old->allocated_stack; i++) {
16096 		struct bpf_reg_state *old_reg, *cur_reg;
16097 
16098 		spi = i / BPF_REG_SIZE;
16099 
16100 		if (exact &&
16101 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16102 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16103 			return false;
16104 
16105 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16106 			i += BPF_REG_SIZE - 1;
16107 			/* explored state didn't use this */
16108 			continue;
16109 		}
16110 
16111 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16112 			continue;
16113 
16114 		if (env->allow_uninit_stack &&
16115 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16116 			continue;
16117 
16118 		/* explored stack has more populated slots than current stack
16119 		 * and these slots were used
16120 		 */
16121 		if (i >= cur->allocated_stack)
16122 			return false;
16123 
16124 		/* if old state was safe with misc data in the stack
16125 		 * it will be safe with zero-initialized stack.
16126 		 * The opposite is not true
16127 		 */
16128 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16129 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16130 			continue;
16131 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16132 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16133 			/* Ex: old explored (safe) state has STACK_SPILL in
16134 			 * this stack slot, but current has STACK_MISC ->
16135 			 * this verifier states are not equivalent,
16136 			 * return false to continue verification of this path
16137 			 */
16138 			return false;
16139 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16140 			continue;
16141 		/* Both old and cur are having same slot_type */
16142 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16143 		case STACK_SPILL:
16144 			/* when explored and current stack slot are both storing
16145 			 * spilled registers, check that stored pointers types
16146 			 * are the same as well.
16147 			 * Ex: explored safe path could have stored
16148 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16149 			 * but current path has stored:
16150 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16151 			 * such verifier states are not equivalent.
16152 			 * return false to continue verification of this path
16153 			 */
16154 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16155 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16156 				return false;
16157 			break;
16158 		case STACK_DYNPTR:
16159 			old_reg = &old->stack[spi].spilled_ptr;
16160 			cur_reg = &cur->stack[spi].spilled_ptr;
16161 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16162 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16163 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16164 				return false;
16165 			break;
16166 		case STACK_ITER:
16167 			old_reg = &old->stack[spi].spilled_ptr;
16168 			cur_reg = &cur->stack[spi].spilled_ptr;
16169 			/* iter.depth is not compared between states as it
16170 			 * doesn't matter for correctness and would otherwise
16171 			 * prevent convergence; we maintain it only to prevent
16172 			 * infinite loop check triggering, see
16173 			 * iter_active_depths_differ()
16174 			 */
16175 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16176 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16177 			    old_reg->iter.state != cur_reg->iter.state ||
16178 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16179 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16180 				return false;
16181 			break;
16182 		case STACK_MISC:
16183 		case STACK_ZERO:
16184 		case STACK_INVALID:
16185 			continue;
16186 		/* Ensure that new unhandled slot types return false by default */
16187 		default:
16188 			return false;
16189 		}
16190 	}
16191 	return true;
16192 }
16193 
16194 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16195 		    struct bpf_idmap *idmap)
16196 {
16197 	int i;
16198 
16199 	if (old->acquired_refs != cur->acquired_refs)
16200 		return false;
16201 
16202 	for (i = 0; i < old->acquired_refs; i++) {
16203 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16204 			return false;
16205 	}
16206 
16207 	return true;
16208 }
16209 
16210 /* compare two verifier states
16211  *
16212  * all states stored in state_list are known to be valid, since
16213  * verifier reached 'bpf_exit' instruction through them
16214  *
16215  * this function is called when verifier exploring different branches of
16216  * execution popped from the state stack. If it sees an old state that has
16217  * more strict register state and more strict stack state then this execution
16218  * branch doesn't need to be explored further, since verifier already
16219  * concluded that more strict state leads to valid finish.
16220  *
16221  * Therefore two states are equivalent if register state is more conservative
16222  * and explored stack state is more conservative than the current one.
16223  * Example:
16224  *       explored                   current
16225  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16226  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16227  *
16228  * In other words if current stack state (one being explored) has more
16229  * valid slots than old one that already passed validation, it means
16230  * the verifier can stop exploring and conclude that current state is valid too
16231  *
16232  * Similarly with registers. If explored state has register type as invalid
16233  * whereas register type in current state is meaningful, it means that
16234  * the current state will reach 'bpf_exit' instruction safely
16235  */
16236 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16237 			      struct bpf_func_state *cur, bool exact)
16238 {
16239 	int i;
16240 
16241 	if (old->callback_depth > cur->callback_depth)
16242 		return false;
16243 
16244 	for (i = 0; i < MAX_BPF_REG; i++)
16245 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16246 			     &env->idmap_scratch, exact))
16247 			return false;
16248 
16249 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16250 		return false;
16251 
16252 	if (!refsafe(old, cur, &env->idmap_scratch))
16253 		return false;
16254 
16255 	return true;
16256 }
16257 
16258 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16259 {
16260 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16261 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16262 }
16263 
16264 static bool states_equal(struct bpf_verifier_env *env,
16265 			 struct bpf_verifier_state *old,
16266 			 struct bpf_verifier_state *cur,
16267 			 bool exact)
16268 {
16269 	int i;
16270 
16271 	if (old->curframe != cur->curframe)
16272 		return false;
16273 
16274 	reset_idmap_scratch(env);
16275 
16276 	/* Verification state from speculative execution simulation
16277 	 * must never prune a non-speculative execution one.
16278 	 */
16279 	if (old->speculative && !cur->speculative)
16280 		return false;
16281 
16282 	if (old->active_lock.ptr != cur->active_lock.ptr)
16283 		return false;
16284 
16285 	/* Old and cur active_lock's have to be either both present
16286 	 * or both absent.
16287 	 */
16288 	if (!!old->active_lock.id != !!cur->active_lock.id)
16289 		return false;
16290 
16291 	if (old->active_lock.id &&
16292 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16293 		return false;
16294 
16295 	if (old->active_rcu_lock != cur->active_rcu_lock)
16296 		return false;
16297 
16298 	/* for states to be equal callsites have to be the same
16299 	 * and all frame states need to be equivalent
16300 	 */
16301 	for (i = 0; i <= old->curframe; i++) {
16302 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16303 			return false;
16304 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16305 			return false;
16306 	}
16307 	return true;
16308 }
16309 
16310 /* Return 0 if no propagation happened. Return negative error code if error
16311  * happened. Otherwise, return the propagated bit.
16312  */
16313 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16314 				  struct bpf_reg_state *reg,
16315 				  struct bpf_reg_state *parent_reg)
16316 {
16317 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16318 	u8 flag = reg->live & REG_LIVE_READ;
16319 	int err;
16320 
16321 	/* When comes here, read flags of PARENT_REG or REG could be any of
16322 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16323 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16324 	 */
16325 	if (parent_flag == REG_LIVE_READ64 ||
16326 	    /* Or if there is no read flag from REG. */
16327 	    !flag ||
16328 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16329 	    parent_flag == flag)
16330 		return 0;
16331 
16332 	err = mark_reg_read(env, reg, parent_reg, flag);
16333 	if (err)
16334 		return err;
16335 
16336 	return flag;
16337 }
16338 
16339 /* A write screens off any subsequent reads; but write marks come from the
16340  * straight-line code between a state and its parent.  When we arrive at an
16341  * equivalent state (jump target or such) we didn't arrive by the straight-line
16342  * code, so read marks in the state must propagate to the parent regardless
16343  * of the state's write marks. That's what 'parent == state->parent' comparison
16344  * in mark_reg_read() is for.
16345  */
16346 static int propagate_liveness(struct bpf_verifier_env *env,
16347 			      const struct bpf_verifier_state *vstate,
16348 			      struct bpf_verifier_state *vparent)
16349 {
16350 	struct bpf_reg_state *state_reg, *parent_reg;
16351 	struct bpf_func_state *state, *parent;
16352 	int i, frame, err = 0;
16353 
16354 	if (vparent->curframe != vstate->curframe) {
16355 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16356 		     vparent->curframe, vstate->curframe);
16357 		return -EFAULT;
16358 	}
16359 	/* Propagate read liveness of registers... */
16360 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16361 	for (frame = 0; frame <= vstate->curframe; frame++) {
16362 		parent = vparent->frame[frame];
16363 		state = vstate->frame[frame];
16364 		parent_reg = parent->regs;
16365 		state_reg = state->regs;
16366 		/* We don't need to worry about FP liveness, it's read-only */
16367 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16368 			err = propagate_liveness_reg(env, &state_reg[i],
16369 						     &parent_reg[i]);
16370 			if (err < 0)
16371 				return err;
16372 			if (err == REG_LIVE_READ64)
16373 				mark_insn_zext(env, &parent_reg[i]);
16374 		}
16375 
16376 		/* Propagate stack slots. */
16377 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16378 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16379 			parent_reg = &parent->stack[i].spilled_ptr;
16380 			state_reg = &state->stack[i].spilled_ptr;
16381 			err = propagate_liveness_reg(env, state_reg,
16382 						     parent_reg);
16383 			if (err < 0)
16384 				return err;
16385 		}
16386 	}
16387 	return 0;
16388 }
16389 
16390 /* find precise scalars in the previous equivalent state and
16391  * propagate them into the current state
16392  */
16393 static int propagate_precision(struct bpf_verifier_env *env,
16394 			       const struct bpf_verifier_state *old)
16395 {
16396 	struct bpf_reg_state *state_reg;
16397 	struct bpf_func_state *state;
16398 	int i, err = 0, fr;
16399 	bool first;
16400 
16401 	for (fr = old->curframe; fr >= 0; fr--) {
16402 		state = old->frame[fr];
16403 		state_reg = state->regs;
16404 		first = true;
16405 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16406 			if (state_reg->type != SCALAR_VALUE ||
16407 			    !state_reg->precise ||
16408 			    !(state_reg->live & REG_LIVE_READ))
16409 				continue;
16410 			if (env->log.level & BPF_LOG_LEVEL2) {
16411 				if (first)
16412 					verbose(env, "frame %d: propagating r%d", fr, i);
16413 				else
16414 					verbose(env, ",r%d", i);
16415 			}
16416 			bt_set_frame_reg(&env->bt, fr, i);
16417 			first = false;
16418 		}
16419 
16420 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16421 			if (!is_spilled_reg(&state->stack[i]))
16422 				continue;
16423 			state_reg = &state->stack[i].spilled_ptr;
16424 			if (state_reg->type != SCALAR_VALUE ||
16425 			    !state_reg->precise ||
16426 			    !(state_reg->live & REG_LIVE_READ))
16427 				continue;
16428 			if (env->log.level & BPF_LOG_LEVEL2) {
16429 				if (first)
16430 					verbose(env, "frame %d: propagating fp%d",
16431 						fr, (-i - 1) * BPF_REG_SIZE);
16432 				else
16433 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16434 			}
16435 			bt_set_frame_slot(&env->bt, fr, i);
16436 			first = false;
16437 		}
16438 		if (!first)
16439 			verbose(env, "\n");
16440 	}
16441 
16442 	err = mark_chain_precision_batch(env);
16443 	if (err < 0)
16444 		return err;
16445 
16446 	return 0;
16447 }
16448 
16449 static bool states_maybe_looping(struct bpf_verifier_state *old,
16450 				 struct bpf_verifier_state *cur)
16451 {
16452 	struct bpf_func_state *fold, *fcur;
16453 	int i, fr = cur->curframe;
16454 
16455 	if (old->curframe != fr)
16456 		return false;
16457 
16458 	fold = old->frame[fr];
16459 	fcur = cur->frame[fr];
16460 	for (i = 0; i < MAX_BPF_REG; i++)
16461 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16462 			   offsetof(struct bpf_reg_state, parent)))
16463 			return false;
16464 	return true;
16465 }
16466 
16467 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16468 {
16469 	return env->insn_aux_data[insn_idx].is_iter_next;
16470 }
16471 
16472 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16473  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16474  * states to match, which otherwise would look like an infinite loop. So while
16475  * iter_next() calls are taken care of, we still need to be careful and
16476  * prevent erroneous and too eager declaration of "ininite loop", when
16477  * iterators are involved.
16478  *
16479  * Here's a situation in pseudo-BPF assembly form:
16480  *
16481  *   0: again:                          ; set up iter_next() call args
16482  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16483  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16484  *   3:   if r0 == 0 goto done
16485  *   4:   ... something useful here ...
16486  *   5:   goto again                    ; another iteration
16487  *   6: done:
16488  *   7:   r1 = &it
16489  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16490  *   9:   exit
16491  *
16492  * This is a typical loop. Let's assume that we have a prune point at 1:,
16493  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16494  * again`, assuming other heuristics don't get in a way).
16495  *
16496  * When we first time come to 1:, let's say we have some state X. We proceed
16497  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16498  * Now we come back to validate that forked ACTIVE state. We proceed through
16499  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16500  * are converging. But the problem is that we don't know that yet, as this
16501  * convergence has to happen at iter_next() call site only. So if nothing is
16502  * done, at 1: verifier will use bounded loop logic and declare infinite
16503  * looping (and would be *technically* correct, if not for iterator's
16504  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16505  * don't want that. So what we do in process_iter_next_call() when we go on
16506  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16507  * a different iteration. So when we suspect an infinite loop, we additionally
16508  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16509  * pretend we are not looping and wait for next iter_next() call.
16510  *
16511  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16512  * loop, because that would actually mean infinite loop, as DRAINED state is
16513  * "sticky", and so we'll keep returning into the same instruction with the
16514  * same state (at least in one of possible code paths).
16515  *
16516  * This approach allows to keep infinite loop heuristic even in the face of
16517  * active iterator. E.g., C snippet below is and will be detected as
16518  * inifintely looping:
16519  *
16520  *   struct bpf_iter_num it;
16521  *   int *p, x;
16522  *
16523  *   bpf_iter_num_new(&it, 0, 10);
16524  *   while ((p = bpf_iter_num_next(&t))) {
16525  *       x = p;
16526  *       while (x--) {} // <<-- infinite loop here
16527  *   }
16528  *
16529  */
16530 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16531 {
16532 	struct bpf_reg_state *slot, *cur_slot;
16533 	struct bpf_func_state *state;
16534 	int i, fr;
16535 
16536 	for (fr = old->curframe; fr >= 0; fr--) {
16537 		state = old->frame[fr];
16538 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16539 			if (state->stack[i].slot_type[0] != STACK_ITER)
16540 				continue;
16541 
16542 			slot = &state->stack[i].spilled_ptr;
16543 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16544 				continue;
16545 
16546 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16547 			if (cur_slot->iter.depth != slot->iter.depth)
16548 				return true;
16549 		}
16550 	}
16551 	return false;
16552 }
16553 
16554 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16555 {
16556 	struct bpf_verifier_state_list *new_sl;
16557 	struct bpf_verifier_state_list *sl, **pprev;
16558 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16559 	int i, j, n, err, states_cnt = 0;
16560 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16561 	bool add_new_state = force_new_state;
16562 	bool force_exact;
16563 
16564 	/* bpf progs typically have pruning point every 4 instructions
16565 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16566 	 * Do not add new state for future pruning if the verifier hasn't seen
16567 	 * at least 2 jumps and at least 8 instructions.
16568 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16569 	 * In tests that amounts to up to 50% reduction into total verifier
16570 	 * memory consumption and 20% verifier time speedup.
16571 	 */
16572 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16573 	    env->insn_processed - env->prev_insn_processed >= 8)
16574 		add_new_state = true;
16575 
16576 	pprev = explored_state(env, insn_idx);
16577 	sl = *pprev;
16578 
16579 	clean_live_states(env, insn_idx, cur);
16580 
16581 	while (sl) {
16582 		states_cnt++;
16583 		if (sl->state.insn_idx != insn_idx)
16584 			goto next;
16585 
16586 		if (sl->state.branches) {
16587 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16588 
16589 			if (frame->in_async_callback_fn &&
16590 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16591 				/* Different async_entry_cnt means that the verifier is
16592 				 * processing another entry into async callback.
16593 				 * Seeing the same state is not an indication of infinite
16594 				 * loop or infinite recursion.
16595 				 * But finding the same state doesn't mean that it's safe
16596 				 * to stop processing the current state. The previous state
16597 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16598 				 * Checking in_async_callback_fn alone is not enough either.
16599 				 * Since the verifier still needs to catch infinite loops
16600 				 * inside async callbacks.
16601 				 */
16602 				goto skip_inf_loop_check;
16603 			}
16604 			/* BPF open-coded iterators loop detection is special.
16605 			 * states_maybe_looping() logic is too simplistic in detecting
16606 			 * states that *might* be equivalent, because it doesn't know
16607 			 * about ID remapping, so don't even perform it.
16608 			 * See process_iter_next_call() and iter_active_depths_differ()
16609 			 * for overview of the logic. When current and one of parent
16610 			 * states are detected as equivalent, it's a good thing: we prove
16611 			 * convergence and can stop simulating further iterations.
16612 			 * It's safe to assume that iterator loop will finish, taking into
16613 			 * account iter_next() contract of eventually returning
16614 			 * sticky NULL result.
16615 			 *
16616 			 * Note, that states have to be compared exactly in this case because
16617 			 * read and precision marks might not be finalized inside the loop.
16618 			 * E.g. as in the program below:
16619 			 *
16620 			 *     1. r7 = -16
16621 			 *     2. r6 = bpf_get_prandom_u32()
16622 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16623 			 *     4.   if (r6 != 42) {
16624 			 *     5.     r7 = -32
16625 			 *     6.     r6 = bpf_get_prandom_u32()
16626 			 *     7.     continue
16627 			 *     8.   }
16628 			 *     9.   r0 = r10
16629 			 *    10.   r0 += r7
16630 			 *    11.   r8 = *(u64 *)(r0 + 0)
16631 			 *    12.   r6 = bpf_get_prandom_u32()
16632 			 *    13. }
16633 			 *
16634 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16635 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16636 			 * not have read or precision mark for r7 yet, thus inexact states
16637 			 * comparison would discard current state with r7=-32
16638 			 * => unsafe memory access at 11 would not be caught.
16639 			 */
16640 			if (is_iter_next_insn(env, insn_idx)) {
16641 				if (states_equal(env, &sl->state, cur, true)) {
16642 					struct bpf_func_state *cur_frame;
16643 					struct bpf_reg_state *iter_state, *iter_reg;
16644 					int spi;
16645 
16646 					cur_frame = cur->frame[cur->curframe];
16647 					/* btf_check_iter_kfuncs() enforces that
16648 					 * iter state pointer is always the first arg
16649 					 */
16650 					iter_reg = &cur_frame->regs[BPF_REG_1];
16651 					/* current state is valid due to states_equal(),
16652 					 * so we can assume valid iter and reg state,
16653 					 * no need for extra (re-)validations
16654 					 */
16655 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16656 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16657 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16658 						update_loop_entry(cur, &sl->state);
16659 						goto hit;
16660 					}
16661 				}
16662 				goto skip_inf_loop_check;
16663 			}
16664 			if (calls_callback(env, insn_idx)) {
16665 				if (states_equal(env, &sl->state, cur, true))
16666 					goto hit;
16667 				goto skip_inf_loop_check;
16668 			}
16669 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16670 			if (states_maybe_looping(&sl->state, cur) &&
16671 			    states_equal(env, &sl->state, cur, false) &&
16672 			    !iter_active_depths_differ(&sl->state, cur) &&
16673 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16674 				verbose_linfo(env, insn_idx, "; ");
16675 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16676 				verbose(env, "cur state:");
16677 				print_verifier_state(env, cur->frame[cur->curframe], true);
16678 				verbose(env, "old state:");
16679 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16680 				return -EINVAL;
16681 			}
16682 			/* if the verifier is processing a loop, avoid adding new state
16683 			 * too often, since different loop iterations have distinct
16684 			 * states and may not help future pruning.
16685 			 * This threshold shouldn't be too low to make sure that
16686 			 * a loop with large bound will be rejected quickly.
16687 			 * The most abusive loop will be:
16688 			 * r1 += 1
16689 			 * if r1 < 1000000 goto pc-2
16690 			 * 1M insn_procssed limit / 100 == 10k peak states.
16691 			 * This threshold shouldn't be too high either, since states
16692 			 * at the end of the loop are likely to be useful in pruning.
16693 			 */
16694 skip_inf_loop_check:
16695 			if (!force_new_state &&
16696 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16697 			    env->insn_processed - env->prev_insn_processed < 100)
16698 				add_new_state = false;
16699 			goto miss;
16700 		}
16701 		/* If sl->state is a part of a loop and this loop's entry is a part of
16702 		 * current verification path then states have to be compared exactly.
16703 		 * 'force_exact' is needed to catch the following case:
16704 		 *
16705 		 *                initial     Here state 'succ' was processed first,
16706 		 *                  |         it was eventually tracked to produce a
16707 		 *                  V         state identical to 'hdr'.
16708 		 *     .---------> hdr        All branches from 'succ' had been explored
16709 		 *     |            |         and thus 'succ' has its .branches == 0.
16710 		 *     |            V
16711 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16712 		 *     |    |       |         to the same instruction + callsites.
16713 		 *     |    V       V         In such case it is necessary to check
16714 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16715 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16716 		 *     |    V       V         same loop exact flag has to be set.
16717 		 *     |   succ <- cur        To check if that is the case, verify
16718 		 *     |    |                 if loop entry of 'succ' is in current
16719 		 *     |    V                 DFS path.
16720 		 *     |   ...
16721 		 *     |    |
16722 		 *     '----'
16723 		 *
16724 		 * Additional details are in the comment before get_loop_entry().
16725 		 */
16726 		loop_entry = get_loop_entry(&sl->state);
16727 		force_exact = loop_entry && loop_entry->branches > 0;
16728 		if (states_equal(env, &sl->state, cur, force_exact)) {
16729 			if (force_exact)
16730 				update_loop_entry(cur, loop_entry);
16731 hit:
16732 			sl->hit_cnt++;
16733 			/* reached equivalent register/stack state,
16734 			 * prune the search.
16735 			 * Registers read by the continuation are read by us.
16736 			 * If we have any write marks in env->cur_state, they
16737 			 * will prevent corresponding reads in the continuation
16738 			 * from reaching our parent (an explored_state).  Our
16739 			 * own state will get the read marks recorded, but
16740 			 * they'll be immediately forgotten as we're pruning
16741 			 * this state and will pop a new one.
16742 			 */
16743 			err = propagate_liveness(env, &sl->state, cur);
16744 
16745 			/* if previous state reached the exit with precision and
16746 			 * current state is equivalent to it (except precsion marks)
16747 			 * the precision needs to be propagated back in
16748 			 * the current state.
16749 			 */
16750 			err = err ? : push_jmp_history(env, cur);
16751 			err = err ? : propagate_precision(env, &sl->state);
16752 			if (err)
16753 				return err;
16754 			return 1;
16755 		}
16756 miss:
16757 		/* when new state is not going to be added do not increase miss count.
16758 		 * Otherwise several loop iterations will remove the state
16759 		 * recorded earlier. The goal of these heuristics is to have
16760 		 * states from some iterations of the loop (some in the beginning
16761 		 * and some at the end) to help pruning.
16762 		 */
16763 		if (add_new_state)
16764 			sl->miss_cnt++;
16765 		/* heuristic to determine whether this state is beneficial
16766 		 * to keep checking from state equivalence point of view.
16767 		 * Higher numbers increase max_states_per_insn and verification time,
16768 		 * but do not meaningfully decrease insn_processed.
16769 		 * 'n' controls how many times state could miss before eviction.
16770 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16771 		 * too early would hinder iterator convergence.
16772 		 */
16773 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16774 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16775 			/* the state is unlikely to be useful. Remove it to
16776 			 * speed up verification
16777 			 */
16778 			*pprev = sl->next;
16779 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16780 			    !sl->state.used_as_loop_entry) {
16781 				u32 br = sl->state.branches;
16782 
16783 				WARN_ONCE(br,
16784 					  "BUG live_done but branches_to_explore %d\n",
16785 					  br);
16786 				free_verifier_state(&sl->state, false);
16787 				kfree(sl);
16788 				env->peak_states--;
16789 			} else {
16790 				/* cannot free this state, since parentage chain may
16791 				 * walk it later. Add it for free_list instead to
16792 				 * be freed at the end of verification
16793 				 */
16794 				sl->next = env->free_list;
16795 				env->free_list = sl;
16796 			}
16797 			sl = *pprev;
16798 			continue;
16799 		}
16800 next:
16801 		pprev = &sl->next;
16802 		sl = *pprev;
16803 	}
16804 
16805 	if (env->max_states_per_insn < states_cnt)
16806 		env->max_states_per_insn = states_cnt;
16807 
16808 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16809 		return 0;
16810 
16811 	if (!add_new_state)
16812 		return 0;
16813 
16814 	/* There were no equivalent states, remember the current one.
16815 	 * Technically the current state is not proven to be safe yet,
16816 	 * but it will either reach outer most bpf_exit (which means it's safe)
16817 	 * or it will be rejected. When there are no loops the verifier won't be
16818 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16819 	 * again on the way to bpf_exit.
16820 	 * When looping the sl->state.branches will be > 0 and this state
16821 	 * will not be considered for equivalence until branches == 0.
16822 	 */
16823 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16824 	if (!new_sl)
16825 		return -ENOMEM;
16826 	env->total_states++;
16827 	env->peak_states++;
16828 	env->prev_jmps_processed = env->jmps_processed;
16829 	env->prev_insn_processed = env->insn_processed;
16830 
16831 	/* forget precise markings we inherited, see __mark_chain_precision */
16832 	if (env->bpf_capable)
16833 		mark_all_scalars_imprecise(env, cur);
16834 
16835 	/* add new state to the head of linked list */
16836 	new = &new_sl->state;
16837 	err = copy_verifier_state(new, cur);
16838 	if (err) {
16839 		free_verifier_state(new, false);
16840 		kfree(new_sl);
16841 		return err;
16842 	}
16843 	new->insn_idx = insn_idx;
16844 	WARN_ONCE(new->branches != 1,
16845 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16846 
16847 	cur->parent = new;
16848 	cur->first_insn_idx = insn_idx;
16849 	cur->dfs_depth = new->dfs_depth + 1;
16850 	clear_jmp_history(cur);
16851 	new_sl->next = *explored_state(env, insn_idx);
16852 	*explored_state(env, insn_idx) = new_sl;
16853 	/* connect new state to parentage chain. Current frame needs all
16854 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16855 	 * to the stack implicitly by JITs) so in callers' frames connect just
16856 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16857 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16858 	 * from callee with its full parentage chain, anyway.
16859 	 */
16860 	/* clear write marks in current state: the writes we did are not writes
16861 	 * our child did, so they don't screen off its reads from us.
16862 	 * (There are no read marks in current state, because reads always mark
16863 	 * their parent and current state never has children yet.  Only
16864 	 * explored_states can get read marks.)
16865 	 */
16866 	for (j = 0; j <= cur->curframe; j++) {
16867 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16868 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16869 		for (i = 0; i < BPF_REG_FP; i++)
16870 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16871 	}
16872 
16873 	/* all stack frames are accessible from callee, clear them all */
16874 	for (j = 0; j <= cur->curframe; j++) {
16875 		struct bpf_func_state *frame = cur->frame[j];
16876 		struct bpf_func_state *newframe = new->frame[j];
16877 
16878 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16879 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16880 			frame->stack[i].spilled_ptr.parent =
16881 						&newframe->stack[i].spilled_ptr;
16882 		}
16883 	}
16884 	return 0;
16885 }
16886 
16887 /* Return true if it's OK to have the same insn return a different type. */
16888 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16889 {
16890 	switch (base_type(type)) {
16891 	case PTR_TO_CTX:
16892 	case PTR_TO_SOCKET:
16893 	case PTR_TO_SOCK_COMMON:
16894 	case PTR_TO_TCP_SOCK:
16895 	case PTR_TO_XDP_SOCK:
16896 	case PTR_TO_BTF_ID:
16897 		return false;
16898 	default:
16899 		return true;
16900 	}
16901 }
16902 
16903 /* If an instruction was previously used with particular pointer types, then we
16904  * need to be careful to avoid cases such as the below, where it may be ok
16905  * for one branch accessing the pointer, but not ok for the other branch:
16906  *
16907  * R1 = sock_ptr
16908  * goto X;
16909  * ...
16910  * R1 = some_other_valid_ptr;
16911  * goto X;
16912  * ...
16913  * R2 = *(u32 *)(R1 + 0);
16914  */
16915 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16916 {
16917 	return src != prev && (!reg_type_mismatch_ok(src) ||
16918 			       !reg_type_mismatch_ok(prev));
16919 }
16920 
16921 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16922 			     bool allow_trust_missmatch)
16923 {
16924 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16925 
16926 	if (*prev_type == NOT_INIT) {
16927 		/* Saw a valid insn
16928 		 * dst_reg = *(u32 *)(src_reg + off)
16929 		 * save type to validate intersecting paths
16930 		 */
16931 		*prev_type = type;
16932 	} else if (reg_type_mismatch(type, *prev_type)) {
16933 		/* Abuser program is trying to use the same insn
16934 		 * dst_reg = *(u32*) (src_reg + off)
16935 		 * with different pointer types:
16936 		 * src_reg == ctx in one branch and
16937 		 * src_reg == stack|map in some other branch.
16938 		 * Reject it.
16939 		 */
16940 		if (allow_trust_missmatch &&
16941 		    base_type(type) == PTR_TO_BTF_ID &&
16942 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16943 			/*
16944 			 * Have to support a use case when one path through
16945 			 * the program yields TRUSTED pointer while another
16946 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16947 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16948 			 */
16949 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16950 		} else {
16951 			verbose(env, "same insn cannot be used with different pointers\n");
16952 			return -EINVAL;
16953 		}
16954 	}
16955 
16956 	return 0;
16957 }
16958 
16959 static int do_check(struct bpf_verifier_env *env)
16960 {
16961 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16962 	struct bpf_verifier_state *state = env->cur_state;
16963 	struct bpf_insn *insns = env->prog->insnsi;
16964 	struct bpf_reg_state *regs;
16965 	int insn_cnt = env->prog->len;
16966 	bool do_print_state = false;
16967 	int prev_insn_idx = -1;
16968 
16969 	for (;;) {
16970 		struct bpf_insn *insn;
16971 		u8 class;
16972 		int err;
16973 
16974 		env->prev_insn_idx = prev_insn_idx;
16975 		if (env->insn_idx >= insn_cnt) {
16976 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16977 				env->insn_idx, insn_cnt);
16978 			return -EFAULT;
16979 		}
16980 
16981 		insn = &insns[env->insn_idx];
16982 		class = BPF_CLASS(insn->code);
16983 
16984 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16985 			verbose(env,
16986 				"BPF program is too large. Processed %d insn\n",
16987 				env->insn_processed);
16988 			return -E2BIG;
16989 		}
16990 
16991 		state->last_insn_idx = env->prev_insn_idx;
16992 
16993 		if (is_prune_point(env, env->insn_idx)) {
16994 			err = is_state_visited(env, env->insn_idx);
16995 			if (err < 0)
16996 				return err;
16997 			if (err == 1) {
16998 				/* found equivalent state, can prune the search */
16999 				if (env->log.level & BPF_LOG_LEVEL) {
17000 					if (do_print_state)
17001 						verbose(env, "\nfrom %d to %d%s: safe\n",
17002 							env->prev_insn_idx, env->insn_idx,
17003 							env->cur_state->speculative ?
17004 							" (speculative execution)" : "");
17005 					else
17006 						verbose(env, "%d: safe\n", env->insn_idx);
17007 				}
17008 				goto process_bpf_exit;
17009 			}
17010 		}
17011 
17012 		if (is_jmp_point(env, env->insn_idx)) {
17013 			err = push_jmp_history(env, state);
17014 			if (err)
17015 				return err;
17016 		}
17017 
17018 		if (signal_pending(current))
17019 			return -EAGAIN;
17020 
17021 		if (need_resched())
17022 			cond_resched();
17023 
17024 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17025 			verbose(env, "\nfrom %d to %d%s:",
17026 				env->prev_insn_idx, env->insn_idx,
17027 				env->cur_state->speculative ?
17028 				" (speculative execution)" : "");
17029 			print_verifier_state(env, state->frame[state->curframe], true);
17030 			do_print_state = false;
17031 		}
17032 
17033 		if (env->log.level & BPF_LOG_LEVEL) {
17034 			const struct bpf_insn_cbs cbs = {
17035 				.cb_call	= disasm_kfunc_name,
17036 				.cb_print	= verbose,
17037 				.private_data	= env,
17038 			};
17039 
17040 			if (verifier_state_scratched(env))
17041 				print_insn_state(env, state->frame[state->curframe]);
17042 
17043 			verbose_linfo(env, env->insn_idx, "; ");
17044 			env->prev_log_pos = env->log.end_pos;
17045 			verbose(env, "%d: ", env->insn_idx);
17046 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17047 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17048 			env->prev_log_pos = env->log.end_pos;
17049 		}
17050 
17051 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17052 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17053 							   env->prev_insn_idx);
17054 			if (err)
17055 				return err;
17056 		}
17057 
17058 		regs = cur_regs(env);
17059 		sanitize_mark_insn_seen(env);
17060 		prev_insn_idx = env->insn_idx;
17061 
17062 		if (class == BPF_ALU || class == BPF_ALU64) {
17063 			err = check_alu_op(env, insn);
17064 			if (err)
17065 				return err;
17066 
17067 		} else if (class == BPF_LDX) {
17068 			enum bpf_reg_type src_reg_type;
17069 
17070 			/* check for reserved fields is already done */
17071 
17072 			/* check src operand */
17073 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17074 			if (err)
17075 				return err;
17076 
17077 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17078 			if (err)
17079 				return err;
17080 
17081 			src_reg_type = regs[insn->src_reg].type;
17082 
17083 			/* check that memory (src_reg + off) is readable,
17084 			 * the state of dst_reg will be updated by this func
17085 			 */
17086 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17087 					       insn->off, BPF_SIZE(insn->code),
17088 					       BPF_READ, insn->dst_reg, false,
17089 					       BPF_MODE(insn->code) == BPF_MEMSX);
17090 			if (err)
17091 				return err;
17092 
17093 			err = save_aux_ptr_type(env, src_reg_type, true);
17094 			if (err)
17095 				return err;
17096 		} else if (class == BPF_STX) {
17097 			enum bpf_reg_type dst_reg_type;
17098 
17099 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17100 				err = check_atomic(env, env->insn_idx, insn);
17101 				if (err)
17102 					return err;
17103 				env->insn_idx++;
17104 				continue;
17105 			}
17106 
17107 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17108 				verbose(env, "BPF_STX uses reserved fields\n");
17109 				return -EINVAL;
17110 			}
17111 
17112 			/* check src1 operand */
17113 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17114 			if (err)
17115 				return err;
17116 			/* check src2 operand */
17117 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17118 			if (err)
17119 				return err;
17120 
17121 			dst_reg_type = regs[insn->dst_reg].type;
17122 
17123 			/* check that memory (dst_reg + off) is writeable */
17124 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17125 					       insn->off, BPF_SIZE(insn->code),
17126 					       BPF_WRITE, insn->src_reg, false, false);
17127 			if (err)
17128 				return err;
17129 
17130 			err = save_aux_ptr_type(env, dst_reg_type, false);
17131 			if (err)
17132 				return err;
17133 		} else if (class == BPF_ST) {
17134 			enum bpf_reg_type dst_reg_type;
17135 
17136 			if (BPF_MODE(insn->code) != BPF_MEM ||
17137 			    insn->src_reg != BPF_REG_0) {
17138 				verbose(env, "BPF_ST uses reserved fields\n");
17139 				return -EINVAL;
17140 			}
17141 			/* check src operand */
17142 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17143 			if (err)
17144 				return err;
17145 
17146 			dst_reg_type = regs[insn->dst_reg].type;
17147 
17148 			/* check that memory (dst_reg + off) is writeable */
17149 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17150 					       insn->off, BPF_SIZE(insn->code),
17151 					       BPF_WRITE, -1, false, false);
17152 			if (err)
17153 				return err;
17154 
17155 			err = save_aux_ptr_type(env, dst_reg_type, false);
17156 			if (err)
17157 				return err;
17158 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17159 			u8 opcode = BPF_OP(insn->code);
17160 
17161 			env->jmps_processed++;
17162 			if (opcode == BPF_CALL) {
17163 				if (BPF_SRC(insn->code) != BPF_K ||
17164 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17165 				     && insn->off != 0) ||
17166 				    (insn->src_reg != BPF_REG_0 &&
17167 				     insn->src_reg != BPF_PSEUDO_CALL &&
17168 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17169 				    insn->dst_reg != BPF_REG_0 ||
17170 				    class == BPF_JMP32) {
17171 					verbose(env, "BPF_CALL uses reserved fields\n");
17172 					return -EINVAL;
17173 				}
17174 
17175 				if (env->cur_state->active_lock.ptr) {
17176 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17177 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17178 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17179 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17180 						verbose(env, "function calls are not allowed while holding a lock\n");
17181 						return -EINVAL;
17182 					}
17183 				}
17184 				if (insn->src_reg == BPF_PSEUDO_CALL)
17185 					err = check_func_call(env, insn, &env->insn_idx);
17186 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17187 					err = check_kfunc_call(env, insn, &env->insn_idx);
17188 				else
17189 					err = check_helper_call(env, insn, &env->insn_idx);
17190 				if (err)
17191 					return err;
17192 
17193 				mark_reg_scratched(env, BPF_REG_0);
17194 			} else if (opcode == BPF_JA) {
17195 				if (BPF_SRC(insn->code) != BPF_K ||
17196 				    insn->src_reg != BPF_REG_0 ||
17197 				    insn->dst_reg != BPF_REG_0 ||
17198 				    (class == BPF_JMP && insn->imm != 0) ||
17199 				    (class == BPF_JMP32 && insn->off != 0)) {
17200 					verbose(env, "BPF_JA uses reserved fields\n");
17201 					return -EINVAL;
17202 				}
17203 
17204 				if (class == BPF_JMP)
17205 					env->insn_idx += insn->off + 1;
17206 				else
17207 					env->insn_idx += insn->imm + 1;
17208 				continue;
17209 
17210 			} else if (opcode == BPF_EXIT) {
17211 				if (BPF_SRC(insn->code) != BPF_K ||
17212 				    insn->imm != 0 ||
17213 				    insn->src_reg != BPF_REG_0 ||
17214 				    insn->dst_reg != BPF_REG_0 ||
17215 				    class == BPF_JMP32) {
17216 					verbose(env, "BPF_EXIT uses reserved fields\n");
17217 					return -EINVAL;
17218 				}
17219 
17220 				if (env->cur_state->active_lock.ptr &&
17221 				    !in_rbtree_lock_required_cb(env)) {
17222 					verbose(env, "bpf_spin_unlock is missing\n");
17223 					return -EINVAL;
17224 				}
17225 
17226 				if (env->cur_state->active_rcu_lock &&
17227 				    !in_rbtree_lock_required_cb(env)) {
17228 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17229 					return -EINVAL;
17230 				}
17231 
17232 				/* We must do check_reference_leak here before
17233 				 * prepare_func_exit to handle the case when
17234 				 * state->curframe > 0, it may be a callback
17235 				 * function, for which reference_state must
17236 				 * match caller reference state when it exits.
17237 				 */
17238 				err = check_reference_leak(env);
17239 				if (err)
17240 					return err;
17241 
17242 				if (state->curframe) {
17243 					/* exit from nested function */
17244 					err = prepare_func_exit(env, &env->insn_idx);
17245 					if (err)
17246 						return err;
17247 					do_print_state = true;
17248 					continue;
17249 				}
17250 
17251 				err = check_return_code(env);
17252 				if (err)
17253 					return err;
17254 process_bpf_exit:
17255 				mark_verifier_state_scratched(env);
17256 				update_branch_counts(env, env->cur_state);
17257 				err = pop_stack(env, &prev_insn_idx,
17258 						&env->insn_idx, pop_log);
17259 				if (err < 0) {
17260 					if (err != -ENOENT)
17261 						return err;
17262 					break;
17263 				} else {
17264 					do_print_state = true;
17265 					continue;
17266 				}
17267 			} else {
17268 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17269 				if (err)
17270 					return err;
17271 			}
17272 		} else if (class == BPF_LD) {
17273 			u8 mode = BPF_MODE(insn->code);
17274 
17275 			if (mode == BPF_ABS || mode == BPF_IND) {
17276 				err = check_ld_abs(env, insn);
17277 				if (err)
17278 					return err;
17279 
17280 			} else if (mode == BPF_IMM) {
17281 				err = check_ld_imm(env, insn);
17282 				if (err)
17283 					return err;
17284 
17285 				env->insn_idx++;
17286 				sanitize_mark_insn_seen(env);
17287 			} else {
17288 				verbose(env, "invalid BPF_LD mode\n");
17289 				return -EINVAL;
17290 			}
17291 		} else {
17292 			verbose(env, "unknown insn class %d\n", class);
17293 			return -EINVAL;
17294 		}
17295 
17296 		env->insn_idx++;
17297 	}
17298 
17299 	return 0;
17300 }
17301 
17302 static int find_btf_percpu_datasec(struct btf *btf)
17303 {
17304 	const struct btf_type *t;
17305 	const char *tname;
17306 	int i, n;
17307 
17308 	/*
17309 	 * Both vmlinux and module each have their own ".data..percpu"
17310 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17311 	 * types to look at only module's own BTF types.
17312 	 */
17313 	n = btf_nr_types(btf);
17314 	if (btf_is_module(btf))
17315 		i = btf_nr_types(btf_vmlinux);
17316 	else
17317 		i = 1;
17318 
17319 	for(; i < n; i++) {
17320 		t = btf_type_by_id(btf, i);
17321 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17322 			continue;
17323 
17324 		tname = btf_name_by_offset(btf, t->name_off);
17325 		if (!strcmp(tname, ".data..percpu"))
17326 			return i;
17327 	}
17328 
17329 	return -ENOENT;
17330 }
17331 
17332 /* replace pseudo btf_id with kernel symbol address */
17333 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17334 			       struct bpf_insn *insn,
17335 			       struct bpf_insn_aux_data *aux)
17336 {
17337 	const struct btf_var_secinfo *vsi;
17338 	const struct btf_type *datasec;
17339 	struct btf_mod_pair *btf_mod;
17340 	const struct btf_type *t;
17341 	const char *sym_name;
17342 	bool percpu = false;
17343 	u32 type, id = insn->imm;
17344 	struct btf *btf;
17345 	s32 datasec_id;
17346 	u64 addr;
17347 	int i, btf_fd, err;
17348 
17349 	btf_fd = insn[1].imm;
17350 	if (btf_fd) {
17351 		btf = btf_get_by_fd(btf_fd);
17352 		if (IS_ERR(btf)) {
17353 			verbose(env, "invalid module BTF object FD specified.\n");
17354 			return -EINVAL;
17355 		}
17356 	} else {
17357 		if (!btf_vmlinux) {
17358 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17359 			return -EINVAL;
17360 		}
17361 		btf = btf_vmlinux;
17362 		btf_get(btf);
17363 	}
17364 
17365 	t = btf_type_by_id(btf, id);
17366 	if (!t) {
17367 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17368 		err = -ENOENT;
17369 		goto err_put;
17370 	}
17371 
17372 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17373 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17374 		err = -EINVAL;
17375 		goto err_put;
17376 	}
17377 
17378 	sym_name = btf_name_by_offset(btf, t->name_off);
17379 	addr = kallsyms_lookup_name(sym_name);
17380 	if (!addr) {
17381 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17382 			sym_name);
17383 		err = -ENOENT;
17384 		goto err_put;
17385 	}
17386 	insn[0].imm = (u32)addr;
17387 	insn[1].imm = addr >> 32;
17388 
17389 	if (btf_type_is_func(t)) {
17390 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17391 		aux->btf_var.mem_size = 0;
17392 		goto check_btf;
17393 	}
17394 
17395 	datasec_id = find_btf_percpu_datasec(btf);
17396 	if (datasec_id > 0) {
17397 		datasec = btf_type_by_id(btf, datasec_id);
17398 		for_each_vsi(i, datasec, vsi) {
17399 			if (vsi->type == id) {
17400 				percpu = true;
17401 				break;
17402 			}
17403 		}
17404 	}
17405 
17406 	type = t->type;
17407 	t = btf_type_skip_modifiers(btf, type, NULL);
17408 	if (percpu) {
17409 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17410 		aux->btf_var.btf = btf;
17411 		aux->btf_var.btf_id = type;
17412 	} else if (!btf_type_is_struct(t)) {
17413 		const struct btf_type *ret;
17414 		const char *tname;
17415 		u32 tsize;
17416 
17417 		/* resolve the type size of ksym. */
17418 		ret = btf_resolve_size(btf, t, &tsize);
17419 		if (IS_ERR(ret)) {
17420 			tname = btf_name_by_offset(btf, t->name_off);
17421 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17422 				tname, PTR_ERR(ret));
17423 			err = -EINVAL;
17424 			goto err_put;
17425 		}
17426 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17427 		aux->btf_var.mem_size = tsize;
17428 	} else {
17429 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17430 		aux->btf_var.btf = btf;
17431 		aux->btf_var.btf_id = type;
17432 	}
17433 check_btf:
17434 	/* check whether we recorded this BTF (and maybe module) already */
17435 	for (i = 0; i < env->used_btf_cnt; i++) {
17436 		if (env->used_btfs[i].btf == btf) {
17437 			btf_put(btf);
17438 			return 0;
17439 		}
17440 	}
17441 
17442 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17443 		err = -E2BIG;
17444 		goto err_put;
17445 	}
17446 
17447 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17448 	btf_mod->btf = btf;
17449 	btf_mod->module = NULL;
17450 
17451 	/* if we reference variables from kernel module, bump its refcount */
17452 	if (btf_is_module(btf)) {
17453 		btf_mod->module = btf_try_get_module(btf);
17454 		if (!btf_mod->module) {
17455 			err = -ENXIO;
17456 			goto err_put;
17457 		}
17458 	}
17459 
17460 	env->used_btf_cnt++;
17461 
17462 	return 0;
17463 err_put:
17464 	btf_put(btf);
17465 	return err;
17466 }
17467 
17468 static bool is_tracing_prog_type(enum bpf_prog_type type)
17469 {
17470 	switch (type) {
17471 	case BPF_PROG_TYPE_KPROBE:
17472 	case BPF_PROG_TYPE_TRACEPOINT:
17473 	case BPF_PROG_TYPE_PERF_EVENT:
17474 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17475 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17476 		return true;
17477 	default:
17478 		return false;
17479 	}
17480 }
17481 
17482 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17483 					struct bpf_map *map,
17484 					struct bpf_prog *prog)
17485 
17486 {
17487 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17488 
17489 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17490 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17491 		if (is_tracing_prog_type(prog_type)) {
17492 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17493 			return -EINVAL;
17494 		}
17495 	}
17496 
17497 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17498 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17499 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17500 			return -EINVAL;
17501 		}
17502 
17503 		if (is_tracing_prog_type(prog_type)) {
17504 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17505 			return -EINVAL;
17506 		}
17507 	}
17508 
17509 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17510 		if (is_tracing_prog_type(prog_type)) {
17511 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17512 			return -EINVAL;
17513 		}
17514 	}
17515 
17516 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17517 	    !bpf_offload_prog_map_match(prog, map)) {
17518 		verbose(env, "offload device mismatch between prog and map\n");
17519 		return -EINVAL;
17520 	}
17521 
17522 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17523 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17524 		return -EINVAL;
17525 	}
17526 
17527 	if (prog->aux->sleepable)
17528 		switch (map->map_type) {
17529 		case BPF_MAP_TYPE_HASH:
17530 		case BPF_MAP_TYPE_LRU_HASH:
17531 		case BPF_MAP_TYPE_ARRAY:
17532 		case BPF_MAP_TYPE_PERCPU_HASH:
17533 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17534 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17535 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17536 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17537 		case BPF_MAP_TYPE_RINGBUF:
17538 		case BPF_MAP_TYPE_USER_RINGBUF:
17539 		case BPF_MAP_TYPE_INODE_STORAGE:
17540 		case BPF_MAP_TYPE_SK_STORAGE:
17541 		case BPF_MAP_TYPE_TASK_STORAGE:
17542 		case BPF_MAP_TYPE_CGRP_STORAGE:
17543 			break;
17544 		default:
17545 			verbose(env,
17546 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17547 			return -EINVAL;
17548 		}
17549 
17550 	return 0;
17551 }
17552 
17553 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17554 {
17555 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17556 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17557 }
17558 
17559 /* find and rewrite pseudo imm in ld_imm64 instructions:
17560  *
17561  * 1. if it accesses map FD, replace it with actual map pointer.
17562  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17563  *
17564  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17565  */
17566 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17567 {
17568 	struct bpf_insn *insn = env->prog->insnsi;
17569 	int insn_cnt = env->prog->len;
17570 	int i, j, err;
17571 
17572 	err = bpf_prog_calc_tag(env->prog);
17573 	if (err)
17574 		return err;
17575 
17576 	for (i = 0; i < insn_cnt; i++, insn++) {
17577 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17578 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17579 		    insn->imm != 0)) {
17580 			verbose(env, "BPF_LDX uses reserved fields\n");
17581 			return -EINVAL;
17582 		}
17583 
17584 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17585 			struct bpf_insn_aux_data *aux;
17586 			struct bpf_map *map;
17587 			struct fd f;
17588 			u64 addr;
17589 			u32 fd;
17590 
17591 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17592 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17593 			    insn[1].off != 0) {
17594 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17595 				return -EINVAL;
17596 			}
17597 
17598 			if (insn[0].src_reg == 0)
17599 				/* valid generic load 64-bit imm */
17600 				goto next_insn;
17601 
17602 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17603 				aux = &env->insn_aux_data[i];
17604 				err = check_pseudo_btf_id(env, insn, aux);
17605 				if (err)
17606 					return err;
17607 				goto next_insn;
17608 			}
17609 
17610 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17611 				aux = &env->insn_aux_data[i];
17612 				aux->ptr_type = PTR_TO_FUNC;
17613 				goto next_insn;
17614 			}
17615 
17616 			/* In final convert_pseudo_ld_imm64() step, this is
17617 			 * converted into regular 64-bit imm load insn.
17618 			 */
17619 			switch (insn[0].src_reg) {
17620 			case BPF_PSEUDO_MAP_VALUE:
17621 			case BPF_PSEUDO_MAP_IDX_VALUE:
17622 				break;
17623 			case BPF_PSEUDO_MAP_FD:
17624 			case BPF_PSEUDO_MAP_IDX:
17625 				if (insn[1].imm == 0)
17626 					break;
17627 				fallthrough;
17628 			default:
17629 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17630 				return -EINVAL;
17631 			}
17632 
17633 			switch (insn[0].src_reg) {
17634 			case BPF_PSEUDO_MAP_IDX_VALUE:
17635 			case BPF_PSEUDO_MAP_IDX:
17636 				if (bpfptr_is_null(env->fd_array)) {
17637 					verbose(env, "fd_idx without fd_array is invalid\n");
17638 					return -EPROTO;
17639 				}
17640 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17641 							    insn[0].imm * sizeof(fd),
17642 							    sizeof(fd)))
17643 					return -EFAULT;
17644 				break;
17645 			default:
17646 				fd = insn[0].imm;
17647 				break;
17648 			}
17649 
17650 			f = fdget(fd);
17651 			map = __bpf_map_get(f);
17652 			if (IS_ERR(map)) {
17653 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
17654 					insn[0].imm);
17655 				return PTR_ERR(map);
17656 			}
17657 
17658 			err = check_map_prog_compatibility(env, map, env->prog);
17659 			if (err) {
17660 				fdput(f);
17661 				return err;
17662 			}
17663 
17664 			aux = &env->insn_aux_data[i];
17665 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17666 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17667 				addr = (unsigned long)map;
17668 			} else {
17669 				u32 off = insn[1].imm;
17670 
17671 				if (off >= BPF_MAX_VAR_OFF) {
17672 					verbose(env, "direct value offset of %u is not allowed\n", off);
17673 					fdput(f);
17674 					return -EINVAL;
17675 				}
17676 
17677 				if (!map->ops->map_direct_value_addr) {
17678 					verbose(env, "no direct value access support for this map type\n");
17679 					fdput(f);
17680 					return -EINVAL;
17681 				}
17682 
17683 				err = map->ops->map_direct_value_addr(map, &addr, off);
17684 				if (err) {
17685 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17686 						map->value_size, off);
17687 					fdput(f);
17688 					return err;
17689 				}
17690 
17691 				aux->map_off = off;
17692 				addr += off;
17693 			}
17694 
17695 			insn[0].imm = (u32)addr;
17696 			insn[1].imm = addr >> 32;
17697 
17698 			/* check whether we recorded this map already */
17699 			for (j = 0; j < env->used_map_cnt; j++) {
17700 				if (env->used_maps[j] == map) {
17701 					aux->map_index = j;
17702 					fdput(f);
17703 					goto next_insn;
17704 				}
17705 			}
17706 
17707 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17708 				fdput(f);
17709 				return -E2BIG;
17710 			}
17711 
17712 			/* hold the map. If the program is rejected by verifier,
17713 			 * the map will be released by release_maps() or it
17714 			 * will be used by the valid program until it's unloaded
17715 			 * and all maps are released in free_used_maps()
17716 			 */
17717 			bpf_map_inc(map);
17718 
17719 			aux->map_index = env->used_map_cnt;
17720 			env->used_maps[env->used_map_cnt++] = map;
17721 
17722 			if (bpf_map_is_cgroup_storage(map) &&
17723 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17724 				verbose(env, "only one cgroup storage of each type is allowed\n");
17725 				fdput(f);
17726 				return -EBUSY;
17727 			}
17728 
17729 			fdput(f);
17730 next_insn:
17731 			insn++;
17732 			i++;
17733 			continue;
17734 		}
17735 
17736 		/* Basic sanity check before we invest more work here. */
17737 		if (!bpf_opcode_in_insntable(insn->code)) {
17738 			verbose(env, "unknown opcode %02x\n", insn->code);
17739 			return -EINVAL;
17740 		}
17741 	}
17742 
17743 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17744 	 * 'struct bpf_map *' into a register instead of user map_fd.
17745 	 * These pointers will be used later by verifier to validate map access.
17746 	 */
17747 	return 0;
17748 }
17749 
17750 /* drop refcnt of maps used by the rejected program */
17751 static void release_maps(struct bpf_verifier_env *env)
17752 {
17753 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17754 			     env->used_map_cnt);
17755 }
17756 
17757 /* drop refcnt of maps used by the rejected program */
17758 static void release_btfs(struct bpf_verifier_env *env)
17759 {
17760 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17761 			     env->used_btf_cnt);
17762 }
17763 
17764 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17765 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17766 {
17767 	struct bpf_insn *insn = env->prog->insnsi;
17768 	int insn_cnt = env->prog->len;
17769 	int i;
17770 
17771 	for (i = 0; i < insn_cnt; i++, insn++) {
17772 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17773 			continue;
17774 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17775 			continue;
17776 		insn->src_reg = 0;
17777 	}
17778 }
17779 
17780 /* single env->prog->insni[off] instruction was replaced with the range
17781  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17782  * [0, off) and [off, end) to new locations, so the patched range stays zero
17783  */
17784 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17785 				 struct bpf_insn_aux_data *new_data,
17786 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17787 {
17788 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17789 	struct bpf_insn *insn = new_prog->insnsi;
17790 	u32 old_seen = old_data[off].seen;
17791 	u32 prog_len;
17792 	int i;
17793 
17794 	/* aux info at OFF always needs adjustment, no matter fast path
17795 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17796 	 * original insn at old prog.
17797 	 */
17798 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17799 
17800 	if (cnt == 1)
17801 		return;
17802 	prog_len = new_prog->len;
17803 
17804 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17805 	memcpy(new_data + off + cnt - 1, old_data + off,
17806 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17807 	for (i = off; i < off + cnt - 1; i++) {
17808 		/* Expand insni[off]'s seen count to the patched range. */
17809 		new_data[i].seen = old_seen;
17810 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17811 	}
17812 	env->insn_aux_data = new_data;
17813 	vfree(old_data);
17814 }
17815 
17816 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17817 {
17818 	int i;
17819 
17820 	if (len == 1)
17821 		return;
17822 	/* NOTE: fake 'exit' subprog should be updated as well. */
17823 	for (i = 0; i <= env->subprog_cnt; i++) {
17824 		if (env->subprog_info[i].start <= off)
17825 			continue;
17826 		env->subprog_info[i].start += len - 1;
17827 	}
17828 }
17829 
17830 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17831 {
17832 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17833 	int i, sz = prog->aux->size_poke_tab;
17834 	struct bpf_jit_poke_descriptor *desc;
17835 
17836 	for (i = 0; i < sz; i++) {
17837 		desc = &tab[i];
17838 		if (desc->insn_idx <= off)
17839 			continue;
17840 		desc->insn_idx += len - 1;
17841 	}
17842 }
17843 
17844 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17845 					    const struct bpf_insn *patch, u32 len)
17846 {
17847 	struct bpf_prog *new_prog;
17848 	struct bpf_insn_aux_data *new_data = NULL;
17849 
17850 	if (len > 1) {
17851 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17852 					      sizeof(struct bpf_insn_aux_data)));
17853 		if (!new_data)
17854 			return NULL;
17855 	}
17856 
17857 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17858 	if (IS_ERR(new_prog)) {
17859 		if (PTR_ERR(new_prog) == -ERANGE)
17860 			verbose(env,
17861 				"insn %d cannot be patched due to 16-bit range\n",
17862 				env->insn_aux_data[off].orig_idx);
17863 		vfree(new_data);
17864 		return NULL;
17865 	}
17866 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17867 	adjust_subprog_starts(env, off, len);
17868 	adjust_poke_descs(new_prog, off, len);
17869 	return new_prog;
17870 }
17871 
17872 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17873 					      u32 off, u32 cnt)
17874 {
17875 	int i, j;
17876 
17877 	/* find first prog starting at or after off (first to remove) */
17878 	for (i = 0; i < env->subprog_cnt; i++)
17879 		if (env->subprog_info[i].start >= off)
17880 			break;
17881 	/* find first prog starting at or after off + cnt (first to stay) */
17882 	for (j = i; j < env->subprog_cnt; j++)
17883 		if (env->subprog_info[j].start >= off + cnt)
17884 			break;
17885 	/* if j doesn't start exactly at off + cnt, we are just removing
17886 	 * the front of previous prog
17887 	 */
17888 	if (env->subprog_info[j].start != off + cnt)
17889 		j--;
17890 
17891 	if (j > i) {
17892 		struct bpf_prog_aux *aux = env->prog->aux;
17893 		int move;
17894 
17895 		/* move fake 'exit' subprog as well */
17896 		move = env->subprog_cnt + 1 - j;
17897 
17898 		memmove(env->subprog_info + i,
17899 			env->subprog_info + j,
17900 			sizeof(*env->subprog_info) * move);
17901 		env->subprog_cnt -= j - i;
17902 
17903 		/* remove func_info */
17904 		if (aux->func_info) {
17905 			move = aux->func_info_cnt - j;
17906 
17907 			memmove(aux->func_info + i,
17908 				aux->func_info + j,
17909 				sizeof(*aux->func_info) * move);
17910 			aux->func_info_cnt -= j - i;
17911 			/* func_info->insn_off is set after all code rewrites,
17912 			 * in adjust_btf_func() - no need to adjust
17913 			 */
17914 		}
17915 	} else {
17916 		/* convert i from "first prog to remove" to "first to adjust" */
17917 		if (env->subprog_info[i].start == off)
17918 			i++;
17919 	}
17920 
17921 	/* update fake 'exit' subprog as well */
17922 	for (; i <= env->subprog_cnt; i++)
17923 		env->subprog_info[i].start -= cnt;
17924 
17925 	return 0;
17926 }
17927 
17928 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17929 				      u32 cnt)
17930 {
17931 	struct bpf_prog *prog = env->prog;
17932 	u32 i, l_off, l_cnt, nr_linfo;
17933 	struct bpf_line_info *linfo;
17934 
17935 	nr_linfo = prog->aux->nr_linfo;
17936 	if (!nr_linfo)
17937 		return 0;
17938 
17939 	linfo = prog->aux->linfo;
17940 
17941 	/* find first line info to remove, count lines to be removed */
17942 	for (i = 0; i < nr_linfo; i++)
17943 		if (linfo[i].insn_off >= off)
17944 			break;
17945 
17946 	l_off = i;
17947 	l_cnt = 0;
17948 	for (; i < nr_linfo; i++)
17949 		if (linfo[i].insn_off < off + cnt)
17950 			l_cnt++;
17951 		else
17952 			break;
17953 
17954 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17955 	 * last removed linfo.  prog is already modified, so prog->len == off
17956 	 * means no live instructions after (tail of the program was removed).
17957 	 */
17958 	if (prog->len != off && l_cnt &&
17959 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17960 		l_cnt--;
17961 		linfo[--i].insn_off = off + cnt;
17962 	}
17963 
17964 	/* remove the line info which refer to the removed instructions */
17965 	if (l_cnt) {
17966 		memmove(linfo + l_off, linfo + i,
17967 			sizeof(*linfo) * (nr_linfo - i));
17968 
17969 		prog->aux->nr_linfo -= l_cnt;
17970 		nr_linfo = prog->aux->nr_linfo;
17971 	}
17972 
17973 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17974 	for (i = l_off; i < nr_linfo; i++)
17975 		linfo[i].insn_off -= cnt;
17976 
17977 	/* fix up all subprogs (incl. 'exit') which start >= off */
17978 	for (i = 0; i <= env->subprog_cnt; i++)
17979 		if (env->subprog_info[i].linfo_idx > l_off) {
17980 			/* program may have started in the removed region but
17981 			 * may not be fully removed
17982 			 */
17983 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17984 				env->subprog_info[i].linfo_idx -= l_cnt;
17985 			else
17986 				env->subprog_info[i].linfo_idx = l_off;
17987 		}
17988 
17989 	return 0;
17990 }
17991 
17992 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17993 {
17994 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17995 	unsigned int orig_prog_len = env->prog->len;
17996 	int err;
17997 
17998 	if (bpf_prog_is_offloaded(env->prog->aux))
17999 		bpf_prog_offload_remove_insns(env, off, cnt);
18000 
18001 	err = bpf_remove_insns(env->prog, off, cnt);
18002 	if (err)
18003 		return err;
18004 
18005 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18006 	if (err)
18007 		return err;
18008 
18009 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18010 	if (err)
18011 		return err;
18012 
18013 	memmove(aux_data + off,	aux_data + off + cnt,
18014 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18015 
18016 	return 0;
18017 }
18018 
18019 /* The verifier does more data flow analysis than llvm and will not
18020  * explore branches that are dead at run time. Malicious programs can
18021  * have dead code too. Therefore replace all dead at-run-time code
18022  * with 'ja -1'.
18023  *
18024  * Just nops are not optimal, e.g. if they would sit at the end of the
18025  * program and through another bug we would manage to jump there, then
18026  * we'd execute beyond program memory otherwise. Returning exception
18027  * code also wouldn't work since we can have subprogs where the dead
18028  * code could be located.
18029  */
18030 static void sanitize_dead_code(struct bpf_verifier_env *env)
18031 {
18032 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18033 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18034 	struct bpf_insn *insn = env->prog->insnsi;
18035 	const int insn_cnt = env->prog->len;
18036 	int i;
18037 
18038 	for (i = 0; i < insn_cnt; i++) {
18039 		if (aux_data[i].seen)
18040 			continue;
18041 		memcpy(insn + i, &trap, sizeof(trap));
18042 		aux_data[i].zext_dst = false;
18043 	}
18044 }
18045 
18046 static bool insn_is_cond_jump(u8 code)
18047 {
18048 	u8 op;
18049 
18050 	op = BPF_OP(code);
18051 	if (BPF_CLASS(code) == BPF_JMP32)
18052 		return op != BPF_JA;
18053 
18054 	if (BPF_CLASS(code) != BPF_JMP)
18055 		return false;
18056 
18057 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18058 }
18059 
18060 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18061 {
18062 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18063 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18064 	struct bpf_insn *insn = env->prog->insnsi;
18065 	const int insn_cnt = env->prog->len;
18066 	int i;
18067 
18068 	for (i = 0; i < insn_cnt; i++, insn++) {
18069 		if (!insn_is_cond_jump(insn->code))
18070 			continue;
18071 
18072 		if (!aux_data[i + 1].seen)
18073 			ja.off = insn->off;
18074 		else if (!aux_data[i + 1 + insn->off].seen)
18075 			ja.off = 0;
18076 		else
18077 			continue;
18078 
18079 		if (bpf_prog_is_offloaded(env->prog->aux))
18080 			bpf_prog_offload_replace_insn(env, i, &ja);
18081 
18082 		memcpy(insn, &ja, sizeof(ja));
18083 	}
18084 }
18085 
18086 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18087 {
18088 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18089 	int insn_cnt = env->prog->len;
18090 	int i, err;
18091 
18092 	for (i = 0; i < insn_cnt; i++) {
18093 		int j;
18094 
18095 		j = 0;
18096 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18097 			j++;
18098 		if (!j)
18099 			continue;
18100 
18101 		err = verifier_remove_insns(env, i, j);
18102 		if (err)
18103 			return err;
18104 		insn_cnt = env->prog->len;
18105 	}
18106 
18107 	return 0;
18108 }
18109 
18110 static int opt_remove_nops(struct bpf_verifier_env *env)
18111 {
18112 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18113 	struct bpf_insn *insn = env->prog->insnsi;
18114 	int insn_cnt = env->prog->len;
18115 	int i, err;
18116 
18117 	for (i = 0; i < insn_cnt; i++) {
18118 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18119 			continue;
18120 
18121 		err = verifier_remove_insns(env, i, 1);
18122 		if (err)
18123 			return err;
18124 		insn_cnt--;
18125 		i--;
18126 	}
18127 
18128 	return 0;
18129 }
18130 
18131 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18132 					 const union bpf_attr *attr)
18133 {
18134 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18135 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18136 	int i, patch_len, delta = 0, len = env->prog->len;
18137 	struct bpf_insn *insns = env->prog->insnsi;
18138 	struct bpf_prog *new_prog;
18139 	bool rnd_hi32;
18140 
18141 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18142 	zext_patch[1] = BPF_ZEXT_REG(0);
18143 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18144 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18145 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18146 	for (i = 0; i < len; i++) {
18147 		int adj_idx = i + delta;
18148 		struct bpf_insn insn;
18149 		int load_reg;
18150 
18151 		insn = insns[adj_idx];
18152 		load_reg = insn_def_regno(&insn);
18153 		if (!aux[adj_idx].zext_dst) {
18154 			u8 code, class;
18155 			u32 imm_rnd;
18156 
18157 			if (!rnd_hi32)
18158 				continue;
18159 
18160 			code = insn.code;
18161 			class = BPF_CLASS(code);
18162 			if (load_reg == -1)
18163 				continue;
18164 
18165 			/* NOTE: arg "reg" (the fourth one) is only used for
18166 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18167 			 *       here.
18168 			 */
18169 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18170 				if (class == BPF_LD &&
18171 				    BPF_MODE(code) == BPF_IMM)
18172 					i++;
18173 				continue;
18174 			}
18175 
18176 			/* ctx load could be transformed into wider load. */
18177 			if (class == BPF_LDX &&
18178 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18179 				continue;
18180 
18181 			imm_rnd = get_random_u32();
18182 			rnd_hi32_patch[0] = insn;
18183 			rnd_hi32_patch[1].imm = imm_rnd;
18184 			rnd_hi32_patch[3].dst_reg = load_reg;
18185 			patch = rnd_hi32_patch;
18186 			patch_len = 4;
18187 			goto apply_patch_buffer;
18188 		}
18189 
18190 		/* Add in an zero-extend instruction if a) the JIT has requested
18191 		 * it or b) it's a CMPXCHG.
18192 		 *
18193 		 * The latter is because: BPF_CMPXCHG always loads a value into
18194 		 * R0, therefore always zero-extends. However some archs'
18195 		 * equivalent instruction only does this load when the
18196 		 * comparison is successful. This detail of CMPXCHG is
18197 		 * orthogonal to the general zero-extension behaviour of the
18198 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18199 		 */
18200 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18201 			continue;
18202 
18203 		/* Zero-extension is done by the caller. */
18204 		if (bpf_pseudo_kfunc_call(&insn))
18205 			continue;
18206 
18207 		if (WARN_ON(load_reg == -1)) {
18208 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18209 			return -EFAULT;
18210 		}
18211 
18212 		zext_patch[0] = insn;
18213 		zext_patch[1].dst_reg = load_reg;
18214 		zext_patch[1].src_reg = load_reg;
18215 		patch = zext_patch;
18216 		patch_len = 2;
18217 apply_patch_buffer:
18218 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18219 		if (!new_prog)
18220 			return -ENOMEM;
18221 		env->prog = new_prog;
18222 		insns = new_prog->insnsi;
18223 		aux = env->insn_aux_data;
18224 		delta += patch_len - 1;
18225 	}
18226 
18227 	return 0;
18228 }
18229 
18230 /* convert load instructions that access fields of a context type into a
18231  * sequence of instructions that access fields of the underlying structure:
18232  *     struct __sk_buff    -> struct sk_buff
18233  *     struct bpf_sock_ops -> struct sock
18234  */
18235 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18236 {
18237 	const struct bpf_verifier_ops *ops = env->ops;
18238 	int i, cnt, size, ctx_field_size, delta = 0;
18239 	const int insn_cnt = env->prog->len;
18240 	struct bpf_insn insn_buf[16], *insn;
18241 	u32 target_size, size_default, off;
18242 	struct bpf_prog *new_prog;
18243 	enum bpf_access_type type;
18244 	bool is_narrower_load;
18245 
18246 	if (ops->gen_prologue || env->seen_direct_write) {
18247 		if (!ops->gen_prologue) {
18248 			verbose(env, "bpf verifier is misconfigured\n");
18249 			return -EINVAL;
18250 		}
18251 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18252 					env->prog);
18253 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18254 			verbose(env, "bpf verifier is misconfigured\n");
18255 			return -EINVAL;
18256 		} else if (cnt) {
18257 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18258 			if (!new_prog)
18259 				return -ENOMEM;
18260 
18261 			env->prog = new_prog;
18262 			delta += cnt - 1;
18263 		}
18264 	}
18265 
18266 	if (bpf_prog_is_offloaded(env->prog->aux))
18267 		return 0;
18268 
18269 	insn = env->prog->insnsi + delta;
18270 
18271 	for (i = 0; i < insn_cnt; i++, insn++) {
18272 		bpf_convert_ctx_access_t convert_ctx_access;
18273 		u8 mode;
18274 
18275 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18276 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18277 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18278 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18279 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18280 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18281 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18282 			type = BPF_READ;
18283 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18284 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18285 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18286 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18287 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18288 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18289 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18290 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18291 			type = BPF_WRITE;
18292 		} else {
18293 			continue;
18294 		}
18295 
18296 		if (type == BPF_WRITE &&
18297 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18298 			struct bpf_insn patch[] = {
18299 				*insn,
18300 				BPF_ST_NOSPEC(),
18301 			};
18302 
18303 			cnt = ARRAY_SIZE(patch);
18304 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18305 			if (!new_prog)
18306 				return -ENOMEM;
18307 
18308 			delta    += cnt - 1;
18309 			env->prog = new_prog;
18310 			insn      = new_prog->insnsi + i + delta;
18311 			continue;
18312 		}
18313 
18314 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18315 		case PTR_TO_CTX:
18316 			if (!ops->convert_ctx_access)
18317 				continue;
18318 			convert_ctx_access = ops->convert_ctx_access;
18319 			break;
18320 		case PTR_TO_SOCKET:
18321 		case PTR_TO_SOCK_COMMON:
18322 			convert_ctx_access = bpf_sock_convert_ctx_access;
18323 			break;
18324 		case PTR_TO_TCP_SOCK:
18325 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18326 			break;
18327 		case PTR_TO_XDP_SOCK:
18328 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18329 			break;
18330 		case PTR_TO_BTF_ID:
18331 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18332 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18333 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18334 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18335 		 * any faults for loads into such types. BPF_WRITE is disallowed
18336 		 * for this case.
18337 		 */
18338 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18339 			if (type == BPF_READ) {
18340 				if (BPF_MODE(insn->code) == BPF_MEM)
18341 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18342 						     BPF_SIZE((insn)->code);
18343 				else
18344 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18345 						     BPF_SIZE((insn)->code);
18346 				env->prog->aux->num_exentries++;
18347 			}
18348 			continue;
18349 		default:
18350 			continue;
18351 		}
18352 
18353 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18354 		size = BPF_LDST_BYTES(insn);
18355 		mode = BPF_MODE(insn->code);
18356 
18357 		/* If the read access is a narrower load of the field,
18358 		 * convert to a 4/8-byte load, to minimum program type specific
18359 		 * convert_ctx_access changes. If conversion is successful,
18360 		 * we will apply proper mask to the result.
18361 		 */
18362 		is_narrower_load = size < ctx_field_size;
18363 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18364 		off = insn->off;
18365 		if (is_narrower_load) {
18366 			u8 size_code;
18367 
18368 			if (type == BPF_WRITE) {
18369 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18370 				return -EINVAL;
18371 			}
18372 
18373 			size_code = BPF_H;
18374 			if (ctx_field_size == 4)
18375 				size_code = BPF_W;
18376 			else if (ctx_field_size == 8)
18377 				size_code = BPF_DW;
18378 
18379 			insn->off = off & ~(size_default - 1);
18380 			insn->code = BPF_LDX | BPF_MEM | size_code;
18381 		}
18382 
18383 		target_size = 0;
18384 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18385 					 &target_size);
18386 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18387 		    (ctx_field_size && !target_size)) {
18388 			verbose(env, "bpf verifier is misconfigured\n");
18389 			return -EINVAL;
18390 		}
18391 
18392 		if (is_narrower_load && size < target_size) {
18393 			u8 shift = bpf_ctx_narrow_access_offset(
18394 				off, size, size_default) * 8;
18395 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18396 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18397 				return -EINVAL;
18398 			}
18399 			if (ctx_field_size <= 4) {
18400 				if (shift)
18401 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18402 									insn->dst_reg,
18403 									shift);
18404 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18405 								(1 << size * 8) - 1);
18406 			} else {
18407 				if (shift)
18408 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18409 									insn->dst_reg,
18410 									shift);
18411 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18412 								(1ULL << size * 8) - 1);
18413 			}
18414 		}
18415 		if (mode == BPF_MEMSX)
18416 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18417 						       insn->dst_reg, insn->dst_reg,
18418 						       size * 8, 0);
18419 
18420 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18421 		if (!new_prog)
18422 			return -ENOMEM;
18423 
18424 		delta += cnt - 1;
18425 
18426 		/* keep walking new program and skip insns we just inserted */
18427 		env->prog = new_prog;
18428 		insn      = new_prog->insnsi + i + delta;
18429 	}
18430 
18431 	return 0;
18432 }
18433 
18434 static int jit_subprogs(struct bpf_verifier_env *env)
18435 {
18436 	struct bpf_prog *prog = env->prog, **func, *tmp;
18437 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18438 	struct bpf_map *map_ptr;
18439 	struct bpf_insn *insn;
18440 	void *old_bpf_func;
18441 	int err, num_exentries;
18442 
18443 	if (env->subprog_cnt <= 1)
18444 		return 0;
18445 
18446 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18447 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18448 			continue;
18449 
18450 		/* Upon error here we cannot fall back to interpreter but
18451 		 * need a hard reject of the program. Thus -EFAULT is
18452 		 * propagated in any case.
18453 		 */
18454 		subprog = find_subprog(env, i + insn->imm + 1);
18455 		if (subprog < 0) {
18456 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18457 				  i + insn->imm + 1);
18458 			return -EFAULT;
18459 		}
18460 		/* temporarily remember subprog id inside insn instead of
18461 		 * aux_data, since next loop will split up all insns into funcs
18462 		 */
18463 		insn->off = subprog;
18464 		/* remember original imm in case JIT fails and fallback
18465 		 * to interpreter will be needed
18466 		 */
18467 		env->insn_aux_data[i].call_imm = insn->imm;
18468 		/* point imm to __bpf_call_base+1 from JITs point of view */
18469 		insn->imm = 1;
18470 		if (bpf_pseudo_func(insn))
18471 			/* jit (e.g. x86_64) may emit fewer instructions
18472 			 * if it learns a u32 imm is the same as a u64 imm.
18473 			 * Force a non zero here.
18474 			 */
18475 			insn[1].imm = 1;
18476 	}
18477 
18478 	err = bpf_prog_alloc_jited_linfo(prog);
18479 	if (err)
18480 		goto out_undo_insn;
18481 
18482 	err = -ENOMEM;
18483 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18484 	if (!func)
18485 		goto out_undo_insn;
18486 
18487 	for (i = 0; i < env->subprog_cnt; i++) {
18488 		subprog_start = subprog_end;
18489 		subprog_end = env->subprog_info[i + 1].start;
18490 
18491 		len = subprog_end - subprog_start;
18492 		/* bpf_prog_run() doesn't call subprogs directly,
18493 		 * hence main prog stats include the runtime of subprogs.
18494 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18495 		 * func[i]->stats will never be accessed and stays NULL
18496 		 */
18497 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18498 		if (!func[i])
18499 			goto out_free;
18500 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18501 		       len * sizeof(struct bpf_insn));
18502 		func[i]->type = prog->type;
18503 		func[i]->len = len;
18504 		if (bpf_prog_calc_tag(func[i]))
18505 			goto out_free;
18506 		func[i]->is_func = 1;
18507 		func[i]->aux->func_idx = i;
18508 		/* Below members will be freed only at prog->aux */
18509 		func[i]->aux->btf = prog->aux->btf;
18510 		func[i]->aux->func_info = prog->aux->func_info;
18511 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18512 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18513 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18514 
18515 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18516 			struct bpf_jit_poke_descriptor *poke;
18517 
18518 			poke = &prog->aux->poke_tab[j];
18519 			if (poke->insn_idx < subprog_end &&
18520 			    poke->insn_idx >= subprog_start)
18521 				poke->aux = func[i]->aux;
18522 		}
18523 
18524 		func[i]->aux->name[0] = 'F';
18525 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18526 		func[i]->jit_requested = 1;
18527 		func[i]->blinding_requested = prog->blinding_requested;
18528 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18529 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18530 		func[i]->aux->linfo = prog->aux->linfo;
18531 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18532 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18533 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18534 		num_exentries = 0;
18535 		insn = func[i]->insnsi;
18536 		for (j = 0; j < func[i]->len; j++, insn++) {
18537 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18538 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18539 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18540 				num_exentries++;
18541 		}
18542 		func[i]->aux->num_exentries = num_exentries;
18543 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18544 		func[i] = bpf_int_jit_compile(func[i]);
18545 		if (!func[i]->jited) {
18546 			err = -ENOTSUPP;
18547 			goto out_free;
18548 		}
18549 		cond_resched();
18550 	}
18551 
18552 	/* at this point all bpf functions were successfully JITed
18553 	 * now populate all bpf_calls with correct addresses and
18554 	 * run last pass of JIT
18555 	 */
18556 	for (i = 0; i < env->subprog_cnt; i++) {
18557 		insn = func[i]->insnsi;
18558 		for (j = 0; j < func[i]->len; j++, insn++) {
18559 			if (bpf_pseudo_func(insn)) {
18560 				subprog = insn->off;
18561 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18562 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18563 				continue;
18564 			}
18565 			if (!bpf_pseudo_call(insn))
18566 				continue;
18567 			subprog = insn->off;
18568 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18569 		}
18570 
18571 		/* we use the aux data to keep a list of the start addresses
18572 		 * of the JITed images for each function in the program
18573 		 *
18574 		 * for some architectures, such as powerpc64, the imm field
18575 		 * might not be large enough to hold the offset of the start
18576 		 * address of the callee's JITed image from __bpf_call_base
18577 		 *
18578 		 * in such cases, we can lookup the start address of a callee
18579 		 * by using its subprog id, available from the off field of
18580 		 * the call instruction, as an index for this list
18581 		 */
18582 		func[i]->aux->func = func;
18583 		func[i]->aux->func_cnt = env->subprog_cnt;
18584 	}
18585 	for (i = 0; i < env->subprog_cnt; i++) {
18586 		old_bpf_func = func[i]->bpf_func;
18587 		tmp = bpf_int_jit_compile(func[i]);
18588 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18589 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18590 			err = -ENOTSUPP;
18591 			goto out_free;
18592 		}
18593 		cond_resched();
18594 	}
18595 
18596 	/* finally lock prog and jit images for all functions and
18597 	 * populate kallsysm. Begin at the first subprogram, since
18598 	 * bpf_prog_load will add the kallsyms for the main program.
18599 	 */
18600 	for (i = 1; i < env->subprog_cnt; i++) {
18601 		bpf_prog_lock_ro(func[i]);
18602 		bpf_prog_kallsyms_add(func[i]);
18603 	}
18604 
18605 	/* Last step: make now unused interpreter insns from main
18606 	 * prog consistent for later dump requests, so they can
18607 	 * later look the same as if they were interpreted only.
18608 	 */
18609 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18610 		if (bpf_pseudo_func(insn)) {
18611 			insn[0].imm = env->insn_aux_data[i].call_imm;
18612 			insn[1].imm = insn->off;
18613 			insn->off = 0;
18614 			continue;
18615 		}
18616 		if (!bpf_pseudo_call(insn))
18617 			continue;
18618 		insn->off = env->insn_aux_data[i].call_imm;
18619 		subprog = find_subprog(env, i + insn->off + 1);
18620 		insn->imm = subprog;
18621 	}
18622 
18623 	prog->jited = 1;
18624 	prog->bpf_func = func[0]->bpf_func;
18625 	prog->jited_len = func[0]->jited_len;
18626 	prog->aux->extable = func[0]->aux->extable;
18627 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18628 	prog->aux->func = func;
18629 	prog->aux->func_cnt = env->subprog_cnt;
18630 	bpf_prog_jit_attempt_done(prog);
18631 	return 0;
18632 out_free:
18633 	/* We failed JIT'ing, so at this point we need to unregister poke
18634 	 * descriptors from subprogs, so that kernel is not attempting to
18635 	 * patch it anymore as we're freeing the subprog JIT memory.
18636 	 */
18637 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18638 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18639 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18640 	}
18641 	/* At this point we're guaranteed that poke descriptors are not
18642 	 * live anymore. We can just unlink its descriptor table as it's
18643 	 * released with the main prog.
18644 	 */
18645 	for (i = 0; i < env->subprog_cnt; i++) {
18646 		if (!func[i])
18647 			continue;
18648 		func[i]->aux->poke_tab = NULL;
18649 		bpf_jit_free(func[i]);
18650 	}
18651 	kfree(func);
18652 out_undo_insn:
18653 	/* cleanup main prog to be interpreted */
18654 	prog->jit_requested = 0;
18655 	prog->blinding_requested = 0;
18656 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18657 		if (!bpf_pseudo_call(insn))
18658 			continue;
18659 		insn->off = 0;
18660 		insn->imm = env->insn_aux_data[i].call_imm;
18661 	}
18662 	bpf_prog_jit_attempt_done(prog);
18663 	return err;
18664 }
18665 
18666 static int fixup_call_args(struct bpf_verifier_env *env)
18667 {
18668 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18669 	struct bpf_prog *prog = env->prog;
18670 	struct bpf_insn *insn = prog->insnsi;
18671 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18672 	int i, depth;
18673 #endif
18674 	int err = 0;
18675 
18676 	if (env->prog->jit_requested &&
18677 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18678 		err = jit_subprogs(env);
18679 		if (err == 0)
18680 			return 0;
18681 		if (err == -EFAULT)
18682 			return err;
18683 	}
18684 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18685 	if (has_kfunc_call) {
18686 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18687 		return -EINVAL;
18688 	}
18689 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18690 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18691 		 * have to be rejected, since interpreter doesn't support them yet.
18692 		 */
18693 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18694 		return -EINVAL;
18695 	}
18696 	for (i = 0; i < prog->len; i++, insn++) {
18697 		if (bpf_pseudo_func(insn)) {
18698 			/* When JIT fails the progs with callback calls
18699 			 * have to be rejected, since interpreter doesn't support them yet.
18700 			 */
18701 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18702 			return -EINVAL;
18703 		}
18704 
18705 		if (!bpf_pseudo_call(insn))
18706 			continue;
18707 		depth = get_callee_stack_depth(env, insn, i);
18708 		if (depth < 0)
18709 			return depth;
18710 		bpf_patch_call_args(insn, depth);
18711 	}
18712 	err = 0;
18713 #endif
18714 	return err;
18715 }
18716 
18717 /* replace a generic kfunc with a specialized version if necessary */
18718 static void specialize_kfunc(struct bpf_verifier_env *env,
18719 			     u32 func_id, u16 offset, unsigned long *addr)
18720 {
18721 	struct bpf_prog *prog = env->prog;
18722 	bool seen_direct_write;
18723 	void *xdp_kfunc;
18724 	bool is_rdonly;
18725 
18726 	if (bpf_dev_bound_kfunc_id(func_id)) {
18727 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18728 		if (xdp_kfunc) {
18729 			*addr = (unsigned long)xdp_kfunc;
18730 			return;
18731 		}
18732 		/* fallback to default kfunc when not supported by netdev */
18733 	}
18734 
18735 	if (offset)
18736 		return;
18737 
18738 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18739 		seen_direct_write = env->seen_direct_write;
18740 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18741 
18742 		if (is_rdonly)
18743 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18744 
18745 		/* restore env->seen_direct_write to its original value, since
18746 		 * may_access_direct_pkt_data mutates it
18747 		 */
18748 		env->seen_direct_write = seen_direct_write;
18749 	}
18750 }
18751 
18752 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18753 					    u16 struct_meta_reg,
18754 					    u16 node_offset_reg,
18755 					    struct bpf_insn *insn,
18756 					    struct bpf_insn *insn_buf,
18757 					    int *cnt)
18758 {
18759 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18760 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18761 
18762 	insn_buf[0] = addr[0];
18763 	insn_buf[1] = addr[1];
18764 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18765 	insn_buf[3] = *insn;
18766 	*cnt = 4;
18767 }
18768 
18769 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18770 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18771 {
18772 	const struct bpf_kfunc_desc *desc;
18773 
18774 	if (!insn->imm) {
18775 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18776 		return -EINVAL;
18777 	}
18778 
18779 	*cnt = 0;
18780 
18781 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18782 	 * __bpf_call_base, unless the JIT needs to call functions that are
18783 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18784 	 */
18785 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18786 	if (!desc) {
18787 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18788 			insn->imm);
18789 		return -EFAULT;
18790 	}
18791 
18792 	if (!bpf_jit_supports_far_kfunc_call())
18793 		insn->imm = BPF_CALL_IMM(desc->addr);
18794 	if (insn->off)
18795 		return 0;
18796 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18797 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18798 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18799 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18800 
18801 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18802 		insn_buf[1] = addr[0];
18803 		insn_buf[2] = addr[1];
18804 		insn_buf[3] = *insn;
18805 		*cnt = 4;
18806 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18807 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18808 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18809 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18810 
18811 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18812 		    !kptr_struct_meta) {
18813 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18814 				insn_idx);
18815 			return -EFAULT;
18816 		}
18817 
18818 		insn_buf[0] = addr[0];
18819 		insn_buf[1] = addr[1];
18820 		insn_buf[2] = *insn;
18821 		*cnt = 3;
18822 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18823 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18824 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18825 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18826 		int struct_meta_reg = BPF_REG_3;
18827 		int node_offset_reg = BPF_REG_4;
18828 
18829 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18830 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18831 			struct_meta_reg = BPF_REG_4;
18832 			node_offset_reg = BPF_REG_5;
18833 		}
18834 
18835 		if (!kptr_struct_meta) {
18836 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18837 				insn_idx);
18838 			return -EFAULT;
18839 		}
18840 
18841 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18842 						node_offset_reg, insn, insn_buf, cnt);
18843 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18844 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18845 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18846 		*cnt = 1;
18847 	}
18848 	return 0;
18849 }
18850 
18851 /* Do various post-verification rewrites in a single program pass.
18852  * These rewrites simplify JIT and interpreter implementations.
18853  */
18854 static int do_misc_fixups(struct bpf_verifier_env *env)
18855 {
18856 	struct bpf_prog *prog = env->prog;
18857 	enum bpf_attach_type eatype = prog->expected_attach_type;
18858 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18859 	struct bpf_insn *insn = prog->insnsi;
18860 	const struct bpf_func_proto *fn;
18861 	const int insn_cnt = prog->len;
18862 	const struct bpf_map_ops *ops;
18863 	struct bpf_insn_aux_data *aux;
18864 	struct bpf_insn insn_buf[16];
18865 	struct bpf_prog *new_prog;
18866 	struct bpf_map *map_ptr;
18867 	int i, ret, cnt, delta = 0;
18868 
18869 	for (i = 0; i < insn_cnt; i++, insn++) {
18870 		/* Make divide-by-zero exceptions impossible. */
18871 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18872 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18873 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18874 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18875 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18876 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18877 			struct bpf_insn *patchlet;
18878 			struct bpf_insn chk_and_div[] = {
18879 				/* [R,W]x div 0 -> 0 */
18880 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18881 					     BPF_JNE | BPF_K, insn->src_reg,
18882 					     0, 2, 0),
18883 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18884 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18885 				*insn,
18886 			};
18887 			struct bpf_insn chk_and_mod[] = {
18888 				/* [R,W]x mod 0 -> [R,W]x */
18889 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18890 					     BPF_JEQ | BPF_K, insn->src_reg,
18891 					     0, 1 + (is64 ? 0 : 1), 0),
18892 				*insn,
18893 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18894 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18895 			};
18896 
18897 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18898 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18899 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18900 
18901 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18902 			if (!new_prog)
18903 				return -ENOMEM;
18904 
18905 			delta    += cnt - 1;
18906 			env->prog = prog = new_prog;
18907 			insn      = new_prog->insnsi + i + delta;
18908 			continue;
18909 		}
18910 
18911 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18912 		if (BPF_CLASS(insn->code) == BPF_LD &&
18913 		    (BPF_MODE(insn->code) == BPF_ABS ||
18914 		     BPF_MODE(insn->code) == BPF_IND)) {
18915 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18916 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18917 				verbose(env, "bpf verifier is misconfigured\n");
18918 				return -EINVAL;
18919 			}
18920 
18921 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18922 			if (!new_prog)
18923 				return -ENOMEM;
18924 
18925 			delta    += cnt - 1;
18926 			env->prog = prog = new_prog;
18927 			insn      = new_prog->insnsi + i + delta;
18928 			continue;
18929 		}
18930 
18931 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18932 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18933 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18934 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18935 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18936 			struct bpf_insn *patch = &insn_buf[0];
18937 			bool issrc, isneg, isimm;
18938 			u32 off_reg;
18939 
18940 			aux = &env->insn_aux_data[i + delta];
18941 			if (!aux->alu_state ||
18942 			    aux->alu_state == BPF_ALU_NON_POINTER)
18943 				continue;
18944 
18945 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18946 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18947 				BPF_ALU_SANITIZE_SRC;
18948 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18949 
18950 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18951 			if (isimm) {
18952 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18953 			} else {
18954 				if (isneg)
18955 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18956 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18957 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18958 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18959 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18960 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18961 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18962 			}
18963 			if (!issrc)
18964 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18965 			insn->src_reg = BPF_REG_AX;
18966 			if (isneg)
18967 				insn->code = insn->code == code_add ?
18968 					     code_sub : code_add;
18969 			*patch++ = *insn;
18970 			if (issrc && isneg && !isimm)
18971 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18972 			cnt = patch - insn_buf;
18973 
18974 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18975 			if (!new_prog)
18976 				return -ENOMEM;
18977 
18978 			delta    += cnt - 1;
18979 			env->prog = prog = new_prog;
18980 			insn      = new_prog->insnsi + i + delta;
18981 			continue;
18982 		}
18983 
18984 		if (insn->code != (BPF_JMP | BPF_CALL))
18985 			continue;
18986 		if (insn->src_reg == BPF_PSEUDO_CALL)
18987 			continue;
18988 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18989 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18990 			if (ret)
18991 				return ret;
18992 			if (cnt == 0)
18993 				continue;
18994 
18995 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18996 			if (!new_prog)
18997 				return -ENOMEM;
18998 
18999 			delta	 += cnt - 1;
19000 			env->prog = prog = new_prog;
19001 			insn	  = new_prog->insnsi + i + delta;
19002 			continue;
19003 		}
19004 
19005 		if (insn->imm == BPF_FUNC_get_route_realm)
19006 			prog->dst_needed = 1;
19007 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19008 			bpf_user_rnd_init_once();
19009 		if (insn->imm == BPF_FUNC_override_return)
19010 			prog->kprobe_override = 1;
19011 		if (insn->imm == BPF_FUNC_tail_call) {
19012 			/* If we tail call into other programs, we
19013 			 * cannot make any assumptions since they can
19014 			 * be replaced dynamically during runtime in
19015 			 * the program array.
19016 			 */
19017 			prog->cb_access = 1;
19018 			if (!allow_tail_call_in_subprogs(env))
19019 				prog->aux->stack_depth = MAX_BPF_STACK;
19020 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19021 
19022 			/* mark bpf_tail_call as different opcode to avoid
19023 			 * conditional branch in the interpreter for every normal
19024 			 * call and to prevent accidental JITing by JIT compiler
19025 			 * that doesn't support bpf_tail_call yet
19026 			 */
19027 			insn->imm = 0;
19028 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19029 
19030 			aux = &env->insn_aux_data[i + delta];
19031 			if (env->bpf_capable && !prog->blinding_requested &&
19032 			    prog->jit_requested &&
19033 			    !bpf_map_key_poisoned(aux) &&
19034 			    !bpf_map_ptr_poisoned(aux) &&
19035 			    !bpf_map_ptr_unpriv(aux)) {
19036 				struct bpf_jit_poke_descriptor desc = {
19037 					.reason = BPF_POKE_REASON_TAIL_CALL,
19038 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19039 					.tail_call.key = bpf_map_key_immediate(aux),
19040 					.insn_idx = i + delta,
19041 				};
19042 
19043 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19044 				if (ret < 0) {
19045 					verbose(env, "adding tail call poke descriptor failed\n");
19046 					return ret;
19047 				}
19048 
19049 				insn->imm = ret + 1;
19050 				continue;
19051 			}
19052 
19053 			if (!bpf_map_ptr_unpriv(aux))
19054 				continue;
19055 
19056 			/* instead of changing every JIT dealing with tail_call
19057 			 * emit two extra insns:
19058 			 * if (index >= max_entries) goto out;
19059 			 * index &= array->index_mask;
19060 			 * to avoid out-of-bounds cpu speculation
19061 			 */
19062 			if (bpf_map_ptr_poisoned(aux)) {
19063 				verbose(env, "tail_call abusing map_ptr\n");
19064 				return -EINVAL;
19065 			}
19066 
19067 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19068 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19069 						  map_ptr->max_entries, 2);
19070 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19071 						    container_of(map_ptr,
19072 								 struct bpf_array,
19073 								 map)->index_mask);
19074 			insn_buf[2] = *insn;
19075 			cnt = 3;
19076 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19077 			if (!new_prog)
19078 				return -ENOMEM;
19079 
19080 			delta    += cnt - 1;
19081 			env->prog = prog = new_prog;
19082 			insn      = new_prog->insnsi + i + delta;
19083 			continue;
19084 		}
19085 
19086 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19087 			/* The verifier will process callback_fn as many times as necessary
19088 			 * with different maps and the register states prepared by
19089 			 * set_timer_callback_state will be accurate.
19090 			 *
19091 			 * The following use case is valid:
19092 			 *   map1 is shared by prog1, prog2, prog3.
19093 			 *   prog1 calls bpf_timer_init for some map1 elements
19094 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19095 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19096 			 *   prog3 calls bpf_timer_start for some map1 elements.
19097 			 *     Those that were not both bpf_timer_init-ed and
19098 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19099 			 */
19100 			struct bpf_insn ld_addrs[2] = {
19101 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19102 			};
19103 
19104 			insn_buf[0] = ld_addrs[0];
19105 			insn_buf[1] = ld_addrs[1];
19106 			insn_buf[2] = *insn;
19107 			cnt = 3;
19108 
19109 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19110 			if (!new_prog)
19111 				return -ENOMEM;
19112 
19113 			delta    += cnt - 1;
19114 			env->prog = prog = new_prog;
19115 			insn      = new_prog->insnsi + i + delta;
19116 			goto patch_call_imm;
19117 		}
19118 
19119 		if (is_storage_get_function(insn->imm)) {
19120 			if (!env->prog->aux->sleepable ||
19121 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19122 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19123 			else
19124 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19125 			insn_buf[1] = *insn;
19126 			cnt = 2;
19127 
19128 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19129 			if (!new_prog)
19130 				return -ENOMEM;
19131 
19132 			delta += cnt - 1;
19133 			env->prog = prog = new_prog;
19134 			insn = new_prog->insnsi + i + delta;
19135 			goto patch_call_imm;
19136 		}
19137 
19138 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19139 		 * and other inlining handlers are currently limited to 64 bit
19140 		 * only.
19141 		 */
19142 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19143 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19144 		     insn->imm == BPF_FUNC_map_update_elem ||
19145 		     insn->imm == BPF_FUNC_map_delete_elem ||
19146 		     insn->imm == BPF_FUNC_map_push_elem   ||
19147 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19148 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19149 		     insn->imm == BPF_FUNC_redirect_map    ||
19150 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19151 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19152 			aux = &env->insn_aux_data[i + delta];
19153 			if (bpf_map_ptr_poisoned(aux))
19154 				goto patch_call_imm;
19155 
19156 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19157 			ops = map_ptr->ops;
19158 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19159 			    ops->map_gen_lookup) {
19160 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19161 				if (cnt == -EOPNOTSUPP)
19162 					goto patch_map_ops_generic;
19163 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19164 					verbose(env, "bpf verifier is misconfigured\n");
19165 					return -EINVAL;
19166 				}
19167 
19168 				new_prog = bpf_patch_insn_data(env, i + delta,
19169 							       insn_buf, cnt);
19170 				if (!new_prog)
19171 					return -ENOMEM;
19172 
19173 				delta    += cnt - 1;
19174 				env->prog = prog = new_prog;
19175 				insn      = new_prog->insnsi + i + delta;
19176 				continue;
19177 			}
19178 
19179 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19180 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19181 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19182 				     (long (*)(struct bpf_map *map, void *key))NULL));
19183 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19184 				     (long (*)(struct bpf_map *map, void *key, void *value,
19185 					      u64 flags))NULL));
19186 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19187 				     (long (*)(struct bpf_map *map, void *value,
19188 					      u64 flags))NULL));
19189 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19190 				     (long (*)(struct bpf_map *map, void *value))NULL));
19191 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19192 				     (long (*)(struct bpf_map *map, void *value))NULL));
19193 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19194 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19195 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19196 				     (long (*)(struct bpf_map *map,
19197 					      bpf_callback_t callback_fn,
19198 					      void *callback_ctx,
19199 					      u64 flags))NULL));
19200 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19201 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19202 
19203 patch_map_ops_generic:
19204 			switch (insn->imm) {
19205 			case BPF_FUNC_map_lookup_elem:
19206 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19207 				continue;
19208 			case BPF_FUNC_map_update_elem:
19209 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19210 				continue;
19211 			case BPF_FUNC_map_delete_elem:
19212 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19213 				continue;
19214 			case BPF_FUNC_map_push_elem:
19215 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19216 				continue;
19217 			case BPF_FUNC_map_pop_elem:
19218 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19219 				continue;
19220 			case BPF_FUNC_map_peek_elem:
19221 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19222 				continue;
19223 			case BPF_FUNC_redirect_map:
19224 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19225 				continue;
19226 			case BPF_FUNC_for_each_map_elem:
19227 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19228 				continue;
19229 			case BPF_FUNC_map_lookup_percpu_elem:
19230 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19231 				continue;
19232 			}
19233 
19234 			goto patch_call_imm;
19235 		}
19236 
19237 		/* Implement bpf_jiffies64 inline. */
19238 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19239 		    insn->imm == BPF_FUNC_jiffies64) {
19240 			struct bpf_insn ld_jiffies_addr[2] = {
19241 				BPF_LD_IMM64(BPF_REG_0,
19242 					     (unsigned long)&jiffies),
19243 			};
19244 
19245 			insn_buf[0] = ld_jiffies_addr[0];
19246 			insn_buf[1] = ld_jiffies_addr[1];
19247 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19248 						  BPF_REG_0, 0);
19249 			cnt = 3;
19250 
19251 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19252 						       cnt);
19253 			if (!new_prog)
19254 				return -ENOMEM;
19255 
19256 			delta    += cnt - 1;
19257 			env->prog = prog = new_prog;
19258 			insn      = new_prog->insnsi + i + delta;
19259 			continue;
19260 		}
19261 
19262 		/* Implement bpf_get_func_arg inline. */
19263 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19264 		    insn->imm == BPF_FUNC_get_func_arg) {
19265 			/* Load nr_args from ctx - 8 */
19266 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19267 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19268 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19269 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19270 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19271 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19272 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19273 			insn_buf[7] = BPF_JMP_A(1);
19274 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19275 			cnt = 9;
19276 
19277 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19278 			if (!new_prog)
19279 				return -ENOMEM;
19280 
19281 			delta    += cnt - 1;
19282 			env->prog = prog = new_prog;
19283 			insn      = new_prog->insnsi + i + delta;
19284 			continue;
19285 		}
19286 
19287 		/* Implement bpf_get_func_ret inline. */
19288 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19289 		    insn->imm == BPF_FUNC_get_func_ret) {
19290 			if (eatype == BPF_TRACE_FEXIT ||
19291 			    eatype == BPF_MODIFY_RETURN) {
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_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19295 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19296 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19297 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19298 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19299 				cnt = 6;
19300 			} else {
19301 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19302 				cnt = 1;
19303 			}
19304 
19305 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19306 			if (!new_prog)
19307 				return -ENOMEM;
19308 
19309 			delta    += cnt - 1;
19310 			env->prog = prog = new_prog;
19311 			insn      = new_prog->insnsi + i + delta;
19312 			continue;
19313 		}
19314 
19315 		/* Implement get_func_arg_cnt inline. */
19316 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19317 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19318 			/* Load nr_args from ctx - 8 */
19319 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19320 
19321 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19322 			if (!new_prog)
19323 				return -ENOMEM;
19324 
19325 			env->prog = prog = new_prog;
19326 			insn      = new_prog->insnsi + i + delta;
19327 			continue;
19328 		}
19329 
19330 		/* Implement bpf_get_func_ip inline. */
19331 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19332 		    insn->imm == BPF_FUNC_get_func_ip) {
19333 			/* Load IP address from ctx - 16 */
19334 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19335 
19336 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19337 			if (!new_prog)
19338 				return -ENOMEM;
19339 
19340 			env->prog = prog = new_prog;
19341 			insn      = new_prog->insnsi + i + delta;
19342 			continue;
19343 		}
19344 
19345 patch_call_imm:
19346 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19347 		/* all functions that have prototype and verifier allowed
19348 		 * programs to call them, must be real in-kernel functions
19349 		 */
19350 		if (!fn->func) {
19351 			verbose(env,
19352 				"kernel subsystem misconfigured func %s#%d\n",
19353 				func_id_name(insn->imm), insn->imm);
19354 			return -EFAULT;
19355 		}
19356 		insn->imm = fn->func - __bpf_call_base;
19357 	}
19358 
19359 	/* Since poke tab is now finalized, publish aux to tracker. */
19360 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19361 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19362 		if (!map_ptr->ops->map_poke_track ||
19363 		    !map_ptr->ops->map_poke_untrack ||
19364 		    !map_ptr->ops->map_poke_run) {
19365 			verbose(env, "bpf verifier is misconfigured\n");
19366 			return -EINVAL;
19367 		}
19368 
19369 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19370 		if (ret < 0) {
19371 			verbose(env, "tracking tail call prog failed\n");
19372 			return ret;
19373 		}
19374 	}
19375 
19376 	sort_kfunc_descs_by_imm_off(env->prog);
19377 
19378 	return 0;
19379 }
19380 
19381 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19382 					int position,
19383 					s32 stack_base,
19384 					u32 callback_subprogno,
19385 					u32 *cnt)
19386 {
19387 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19388 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19389 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19390 	int reg_loop_max = BPF_REG_6;
19391 	int reg_loop_cnt = BPF_REG_7;
19392 	int reg_loop_ctx = BPF_REG_8;
19393 
19394 	struct bpf_prog *new_prog;
19395 	u32 callback_start;
19396 	u32 call_insn_offset;
19397 	s32 callback_offset;
19398 
19399 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19400 	 * be careful to modify this code in sync.
19401 	 */
19402 	struct bpf_insn insn_buf[] = {
19403 		/* Return error and jump to the end of the patch if
19404 		 * expected number of iterations is too big.
19405 		 */
19406 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19407 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19408 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19409 		/* spill R6, R7, R8 to use these as loop vars */
19410 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19411 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19412 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19413 		/* initialize loop vars */
19414 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19415 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19416 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19417 		/* loop header,
19418 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19419 		 */
19420 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19421 		/* callback call,
19422 		 * correct callback offset would be set after patching
19423 		 */
19424 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19425 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19426 		BPF_CALL_REL(0),
19427 		/* increment loop counter */
19428 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19429 		/* jump to loop header if callback returned 0 */
19430 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19431 		/* return value of bpf_loop,
19432 		 * set R0 to the number of iterations
19433 		 */
19434 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19435 		/* restore original values of R6, R7, R8 */
19436 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19437 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19438 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19439 	};
19440 
19441 	*cnt = ARRAY_SIZE(insn_buf);
19442 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19443 	if (!new_prog)
19444 		return new_prog;
19445 
19446 	/* callback start is known only after patching */
19447 	callback_start = env->subprog_info[callback_subprogno].start;
19448 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19449 	call_insn_offset = position + 12;
19450 	callback_offset = callback_start - call_insn_offset - 1;
19451 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19452 
19453 	return new_prog;
19454 }
19455 
19456 static bool is_bpf_loop_call(struct bpf_insn *insn)
19457 {
19458 	return insn->code == (BPF_JMP | BPF_CALL) &&
19459 		insn->src_reg == 0 &&
19460 		insn->imm == BPF_FUNC_loop;
19461 }
19462 
19463 /* For all sub-programs in the program (including main) check
19464  * insn_aux_data to see if there are bpf_loop calls that require
19465  * inlining. If such calls are found the calls are replaced with a
19466  * sequence of instructions produced by `inline_bpf_loop` function and
19467  * subprog stack_depth is increased by the size of 3 registers.
19468  * This stack space is used to spill values of the R6, R7, R8.  These
19469  * registers are used to store the loop bound, counter and context
19470  * variables.
19471  */
19472 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19473 {
19474 	struct bpf_subprog_info *subprogs = env->subprog_info;
19475 	int i, cur_subprog = 0, cnt, delta = 0;
19476 	struct bpf_insn *insn = env->prog->insnsi;
19477 	int insn_cnt = env->prog->len;
19478 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19479 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19480 	u16 stack_depth_extra = 0;
19481 
19482 	for (i = 0; i < insn_cnt; i++, insn++) {
19483 		struct bpf_loop_inline_state *inline_state =
19484 			&env->insn_aux_data[i + delta].loop_inline_state;
19485 
19486 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19487 			struct bpf_prog *new_prog;
19488 
19489 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19490 			new_prog = inline_bpf_loop(env,
19491 						   i + delta,
19492 						   -(stack_depth + stack_depth_extra),
19493 						   inline_state->callback_subprogno,
19494 						   &cnt);
19495 			if (!new_prog)
19496 				return -ENOMEM;
19497 
19498 			delta     += cnt - 1;
19499 			env->prog  = new_prog;
19500 			insn       = new_prog->insnsi + i + delta;
19501 		}
19502 
19503 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19504 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19505 			cur_subprog++;
19506 			stack_depth = subprogs[cur_subprog].stack_depth;
19507 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19508 			stack_depth_extra = 0;
19509 		}
19510 	}
19511 
19512 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19513 
19514 	return 0;
19515 }
19516 
19517 static void free_states(struct bpf_verifier_env *env)
19518 {
19519 	struct bpf_verifier_state_list *sl, *sln;
19520 	int i;
19521 
19522 	sl = env->free_list;
19523 	while (sl) {
19524 		sln = sl->next;
19525 		free_verifier_state(&sl->state, false);
19526 		kfree(sl);
19527 		sl = sln;
19528 	}
19529 	env->free_list = NULL;
19530 
19531 	if (!env->explored_states)
19532 		return;
19533 
19534 	for (i = 0; i < state_htab_size(env); i++) {
19535 		sl = env->explored_states[i];
19536 
19537 		while (sl) {
19538 			sln = sl->next;
19539 			free_verifier_state(&sl->state, false);
19540 			kfree(sl);
19541 			sl = sln;
19542 		}
19543 		env->explored_states[i] = NULL;
19544 	}
19545 }
19546 
19547 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19548 {
19549 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19550 	struct bpf_verifier_state *state;
19551 	struct bpf_reg_state *regs;
19552 	int ret, i;
19553 
19554 	env->prev_linfo = NULL;
19555 	env->pass_cnt++;
19556 
19557 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19558 	if (!state)
19559 		return -ENOMEM;
19560 	state->curframe = 0;
19561 	state->speculative = false;
19562 	state->branches = 1;
19563 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19564 	if (!state->frame[0]) {
19565 		kfree(state);
19566 		return -ENOMEM;
19567 	}
19568 	env->cur_state = state;
19569 	init_func_state(env, state->frame[0],
19570 			BPF_MAIN_FUNC /* callsite */,
19571 			0 /* frameno */,
19572 			subprog);
19573 	state->first_insn_idx = env->subprog_info[subprog].start;
19574 	state->last_insn_idx = -1;
19575 
19576 	regs = state->frame[state->curframe]->regs;
19577 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19578 		ret = btf_prepare_func_args(env, subprog, regs);
19579 		if (ret)
19580 			goto out;
19581 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19582 			if (regs[i].type == PTR_TO_CTX)
19583 				mark_reg_known_zero(env, regs, i);
19584 			else if (regs[i].type == SCALAR_VALUE)
19585 				mark_reg_unknown(env, regs, i);
19586 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19587 				const u32 mem_size = regs[i].mem_size;
19588 
19589 				mark_reg_known_zero(env, regs, i);
19590 				regs[i].mem_size = mem_size;
19591 				regs[i].id = ++env->id_gen;
19592 			}
19593 		}
19594 	} else {
19595 		/* 1st arg to a function */
19596 		regs[BPF_REG_1].type = PTR_TO_CTX;
19597 		mark_reg_known_zero(env, regs, BPF_REG_1);
19598 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19599 		if (ret == -EFAULT)
19600 			/* unlikely verifier bug. abort.
19601 			 * ret == 0 and ret < 0 are sadly acceptable for
19602 			 * main() function due to backward compatibility.
19603 			 * Like socket filter program may be written as:
19604 			 * int bpf_prog(struct pt_regs *ctx)
19605 			 * and never dereference that ctx in the program.
19606 			 * 'struct pt_regs' is a type mismatch for socket
19607 			 * filter that should be using 'struct __sk_buff'.
19608 			 */
19609 			goto out;
19610 	}
19611 
19612 	ret = do_check(env);
19613 out:
19614 	/* check for NULL is necessary, since cur_state can be freed inside
19615 	 * do_check() under memory pressure.
19616 	 */
19617 	if (env->cur_state) {
19618 		free_verifier_state(env->cur_state, true);
19619 		env->cur_state = NULL;
19620 	}
19621 	while (!pop_stack(env, NULL, NULL, false));
19622 	if (!ret && pop_log)
19623 		bpf_vlog_reset(&env->log, 0);
19624 	free_states(env);
19625 	return ret;
19626 }
19627 
19628 /* Verify all global functions in a BPF program one by one based on their BTF.
19629  * All global functions must pass verification. Otherwise the whole program is rejected.
19630  * Consider:
19631  * int bar(int);
19632  * int foo(int f)
19633  * {
19634  *    return bar(f);
19635  * }
19636  * int bar(int b)
19637  * {
19638  *    ...
19639  * }
19640  * foo() will be verified first for R1=any_scalar_value. During verification it
19641  * will be assumed that bar() already verified successfully and call to bar()
19642  * from foo() will be checked for type match only. Later bar() will be verified
19643  * independently to check that it's safe for R1=any_scalar_value.
19644  */
19645 static int do_check_subprogs(struct bpf_verifier_env *env)
19646 {
19647 	struct bpf_prog_aux *aux = env->prog->aux;
19648 	int i, ret;
19649 
19650 	if (!aux->func_info)
19651 		return 0;
19652 
19653 	for (i = 1; i < env->subprog_cnt; i++) {
19654 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19655 			continue;
19656 		env->insn_idx = env->subprog_info[i].start;
19657 		WARN_ON_ONCE(env->insn_idx == 0);
19658 		ret = do_check_common(env, i);
19659 		if (ret) {
19660 			return ret;
19661 		} else if (env->log.level & BPF_LOG_LEVEL) {
19662 			verbose(env,
19663 				"Func#%d is safe for any args that match its prototype\n",
19664 				i);
19665 		}
19666 	}
19667 	return 0;
19668 }
19669 
19670 static int do_check_main(struct bpf_verifier_env *env)
19671 {
19672 	int ret;
19673 
19674 	env->insn_idx = 0;
19675 	ret = do_check_common(env, 0);
19676 	if (!ret)
19677 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19678 	return ret;
19679 }
19680 
19681 
19682 static void print_verification_stats(struct bpf_verifier_env *env)
19683 {
19684 	int i;
19685 
19686 	if (env->log.level & BPF_LOG_STATS) {
19687 		verbose(env, "verification time %lld usec\n",
19688 			div_u64(env->verification_time, 1000));
19689 		verbose(env, "stack depth ");
19690 		for (i = 0; i < env->subprog_cnt; i++) {
19691 			u32 depth = env->subprog_info[i].stack_depth;
19692 
19693 			verbose(env, "%d", depth);
19694 			if (i + 1 < env->subprog_cnt)
19695 				verbose(env, "+");
19696 		}
19697 		verbose(env, "\n");
19698 	}
19699 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19700 		"total_states %d peak_states %d mark_read %d\n",
19701 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19702 		env->max_states_per_insn, env->total_states,
19703 		env->peak_states, env->longest_mark_read_walk);
19704 }
19705 
19706 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19707 {
19708 	const struct btf_type *t, *func_proto;
19709 	const struct bpf_struct_ops *st_ops;
19710 	const struct btf_member *member;
19711 	struct bpf_prog *prog = env->prog;
19712 	u32 btf_id, member_idx;
19713 	const char *mname;
19714 
19715 	if (!prog->gpl_compatible) {
19716 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19717 		return -EINVAL;
19718 	}
19719 
19720 	btf_id = prog->aux->attach_btf_id;
19721 	st_ops = bpf_struct_ops_find(btf_id);
19722 	if (!st_ops) {
19723 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19724 			btf_id);
19725 		return -ENOTSUPP;
19726 	}
19727 
19728 	t = st_ops->type;
19729 	member_idx = prog->expected_attach_type;
19730 	if (member_idx >= btf_type_vlen(t)) {
19731 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19732 			member_idx, st_ops->name);
19733 		return -EINVAL;
19734 	}
19735 
19736 	member = &btf_type_member(t)[member_idx];
19737 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19738 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19739 					       NULL);
19740 	if (!func_proto) {
19741 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19742 			mname, member_idx, st_ops->name);
19743 		return -EINVAL;
19744 	}
19745 
19746 	if (st_ops->check_member) {
19747 		int err = st_ops->check_member(t, member, prog);
19748 
19749 		if (err) {
19750 			verbose(env, "attach to unsupported member %s of struct %s\n",
19751 				mname, st_ops->name);
19752 			return err;
19753 		}
19754 	}
19755 
19756 	prog->aux->attach_func_proto = func_proto;
19757 	prog->aux->attach_func_name = mname;
19758 	env->ops = st_ops->verifier_ops;
19759 
19760 	return 0;
19761 }
19762 #define SECURITY_PREFIX "security_"
19763 
19764 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19765 {
19766 	if (within_error_injection_list(addr) ||
19767 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19768 		return 0;
19769 
19770 	return -EINVAL;
19771 }
19772 
19773 /* list of non-sleepable functions that are otherwise on
19774  * ALLOW_ERROR_INJECTION list
19775  */
19776 BTF_SET_START(btf_non_sleepable_error_inject)
19777 /* Three functions below can be called from sleepable and non-sleepable context.
19778  * Assume non-sleepable from bpf safety point of view.
19779  */
19780 BTF_ID(func, __filemap_add_folio)
19781 BTF_ID(func, should_fail_alloc_page)
19782 BTF_ID(func, should_failslab)
19783 BTF_SET_END(btf_non_sleepable_error_inject)
19784 
19785 static int check_non_sleepable_error_inject(u32 btf_id)
19786 {
19787 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19788 }
19789 
19790 int bpf_check_attach_target(struct bpf_verifier_log *log,
19791 			    const struct bpf_prog *prog,
19792 			    const struct bpf_prog *tgt_prog,
19793 			    u32 btf_id,
19794 			    struct bpf_attach_target_info *tgt_info)
19795 {
19796 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19797 	const char prefix[] = "btf_trace_";
19798 	int ret = 0, subprog = -1, i;
19799 	const struct btf_type *t;
19800 	bool conservative = true;
19801 	const char *tname;
19802 	struct btf *btf;
19803 	long addr = 0;
19804 	struct module *mod = NULL;
19805 
19806 	if (!btf_id) {
19807 		bpf_log(log, "Tracing programs must provide btf_id\n");
19808 		return -EINVAL;
19809 	}
19810 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19811 	if (!btf) {
19812 		bpf_log(log,
19813 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19814 		return -EINVAL;
19815 	}
19816 	t = btf_type_by_id(btf, btf_id);
19817 	if (!t) {
19818 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19819 		return -EINVAL;
19820 	}
19821 	tname = btf_name_by_offset(btf, t->name_off);
19822 	if (!tname) {
19823 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19824 		return -EINVAL;
19825 	}
19826 	if (tgt_prog) {
19827 		struct bpf_prog_aux *aux = tgt_prog->aux;
19828 
19829 		if (bpf_prog_is_dev_bound(prog->aux) &&
19830 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19831 			bpf_log(log, "Target program bound device mismatch");
19832 			return -EINVAL;
19833 		}
19834 
19835 		for (i = 0; i < aux->func_info_cnt; i++)
19836 			if (aux->func_info[i].type_id == btf_id) {
19837 				subprog = i;
19838 				break;
19839 			}
19840 		if (subprog == -1) {
19841 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19842 			return -EINVAL;
19843 		}
19844 		conservative = aux->func_info_aux[subprog].unreliable;
19845 		if (prog_extension) {
19846 			if (conservative) {
19847 				bpf_log(log,
19848 					"Cannot replace static functions\n");
19849 				return -EINVAL;
19850 			}
19851 			if (!prog->jit_requested) {
19852 				bpf_log(log,
19853 					"Extension programs should be JITed\n");
19854 				return -EINVAL;
19855 			}
19856 		}
19857 		if (!tgt_prog->jited) {
19858 			bpf_log(log, "Can attach to only JITed progs\n");
19859 			return -EINVAL;
19860 		}
19861 		if (tgt_prog->type == prog->type) {
19862 			/* Cannot fentry/fexit another fentry/fexit program.
19863 			 * Cannot attach program extension to another extension.
19864 			 * It's ok to attach fentry/fexit to extension program.
19865 			 */
19866 			bpf_log(log, "Cannot recursively attach\n");
19867 			return -EINVAL;
19868 		}
19869 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19870 		    prog_extension &&
19871 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19872 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19873 			/* Program extensions can extend all program types
19874 			 * except fentry/fexit. The reason is the following.
19875 			 * The fentry/fexit programs are used for performance
19876 			 * analysis, stats and can be attached to any program
19877 			 * type except themselves. When extension program is
19878 			 * replacing XDP function it is necessary to allow
19879 			 * performance analysis of all functions. Both original
19880 			 * XDP program and its program extension. Hence
19881 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19882 			 * allowed. If extending of fentry/fexit was allowed it
19883 			 * would be possible to create long call chain
19884 			 * fentry->extension->fentry->extension beyond
19885 			 * reasonable stack size. Hence extending fentry is not
19886 			 * allowed.
19887 			 */
19888 			bpf_log(log, "Cannot extend fentry/fexit\n");
19889 			return -EINVAL;
19890 		}
19891 	} else {
19892 		if (prog_extension) {
19893 			bpf_log(log, "Cannot replace kernel functions\n");
19894 			return -EINVAL;
19895 		}
19896 	}
19897 
19898 	switch (prog->expected_attach_type) {
19899 	case BPF_TRACE_RAW_TP:
19900 		if (tgt_prog) {
19901 			bpf_log(log,
19902 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19903 			return -EINVAL;
19904 		}
19905 		if (!btf_type_is_typedef(t)) {
19906 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19907 				btf_id);
19908 			return -EINVAL;
19909 		}
19910 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19911 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19912 				btf_id, tname);
19913 			return -EINVAL;
19914 		}
19915 		tname += sizeof(prefix) - 1;
19916 		t = btf_type_by_id(btf, t->type);
19917 		if (!btf_type_is_ptr(t))
19918 			/* should never happen in valid vmlinux build */
19919 			return -EINVAL;
19920 		t = btf_type_by_id(btf, t->type);
19921 		if (!btf_type_is_func_proto(t))
19922 			/* should never happen in valid vmlinux build */
19923 			return -EINVAL;
19924 
19925 		break;
19926 	case BPF_TRACE_ITER:
19927 		if (!btf_type_is_func(t)) {
19928 			bpf_log(log, "attach_btf_id %u is not a function\n",
19929 				btf_id);
19930 			return -EINVAL;
19931 		}
19932 		t = btf_type_by_id(btf, t->type);
19933 		if (!btf_type_is_func_proto(t))
19934 			return -EINVAL;
19935 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19936 		if (ret)
19937 			return ret;
19938 		break;
19939 	default:
19940 		if (!prog_extension)
19941 			return -EINVAL;
19942 		fallthrough;
19943 	case BPF_MODIFY_RETURN:
19944 	case BPF_LSM_MAC:
19945 	case BPF_LSM_CGROUP:
19946 	case BPF_TRACE_FENTRY:
19947 	case BPF_TRACE_FEXIT:
19948 		if (!btf_type_is_func(t)) {
19949 			bpf_log(log, "attach_btf_id %u is not a function\n",
19950 				btf_id);
19951 			return -EINVAL;
19952 		}
19953 		if (prog_extension &&
19954 		    btf_check_type_match(log, prog, btf, t))
19955 			return -EINVAL;
19956 		t = btf_type_by_id(btf, t->type);
19957 		if (!btf_type_is_func_proto(t))
19958 			return -EINVAL;
19959 
19960 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19961 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19962 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19963 			return -EINVAL;
19964 
19965 		if (tgt_prog && conservative)
19966 			t = NULL;
19967 
19968 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19969 		if (ret < 0)
19970 			return ret;
19971 
19972 		if (tgt_prog) {
19973 			if (subprog == 0)
19974 				addr = (long) tgt_prog->bpf_func;
19975 			else
19976 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19977 		} else {
19978 			if (btf_is_module(btf)) {
19979 				mod = btf_try_get_module(btf);
19980 				if (mod)
19981 					addr = find_kallsyms_symbol_value(mod, tname);
19982 				else
19983 					addr = 0;
19984 			} else {
19985 				addr = kallsyms_lookup_name(tname);
19986 			}
19987 			if (!addr) {
19988 				module_put(mod);
19989 				bpf_log(log,
19990 					"The address of function %s cannot be found\n",
19991 					tname);
19992 				return -ENOENT;
19993 			}
19994 		}
19995 
19996 		if (prog->aux->sleepable) {
19997 			ret = -EINVAL;
19998 			switch (prog->type) {
19999 			case BPF_PROG_TYPE_TRACING:
20000 
20001 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20002 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20003 				 */
20004 				if (!check_non_sleepable_error_inject(btf_id) &&
20005 				    within_error_injection_list(addr))
20006 					ret = 0;
20007 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20008 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20009 				 */
20010 				else {
20011 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20012 										prog);
20013 
20014 					if (flags && (*flags & KF_SLEEPABLE))
20015 						ret = 0;
20016 				}
20017 				break;
20018 			case BPF_PROG_TYPE_LSM:
20019 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20020 				 * Only some of them are sleepable.
20021 				 */
20022 				if (bpf_lsm_is_sleepable_hook(btf_id))
20023 					ret = 0;
20024 				break;
20025 			default:
20026 				break;
20027 			}
20028 			if (ret) {
20029 				module_put(mod);
20030 				bpf_log(log, "%s is not sleepable\n", tname);
20031 				return ret;
20032 			}
20033 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20034 			if (tgt_prog) {
20035 				module_put(mod);
20036 				bpf_log(log, "can't modify return codes of BPF programs\n");
20037 				return -EINVAL;
20038 			}
20039 			ret = -EINVAL;
20040 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20041 			    !check_attach_modify_return(addr, tname))
20042 				ret = 0;
20043 			if (ret) {
20044 				module_put(mod);
20045 				bpf_log(log, "%s() is not modifiable\n", tname);
20046 				return ret;
20047 			}
20048 		}
20049 
20050 		break;
20051 	}
20052 	tgt_info->tgt_addr = addr;
20053 	tgt_info->tgt_name = tname;
20054 	tgt_info->tgt_type = t;
20055 	tgt_info->tgt_mod = mod;
20056 	return 0;
20057 }
20058 
20059 BTF_SET_START(btf_id_deny)
20060 BTF_ID_UNUSED
20061 #ifdef CONFIG_SMP
20062 BTF_ID(func, migrate_disable)
20063 BTF_ID(func, migrate_enable)
20064 #endif
20065 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20066 BTF_ID(func, rcu_read_unlock_strict)
20067 #endif
20068 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20069 BTF_ID(func, preempt_count_add)
20070 BTF_ID(func, preempt_count_sub)
20071 #endif
20072 #ifdef CONFIG_PREEMPT_RCU
20073 BTF_ID(func, __rcu_read_lock)
20074 BTF_ID(func, __rcu_read_unlock)
20075 #endif
20076 BTF_SET_END(btf_id_deny)
20077 
20078 static bool can_be_sleepable(struct bpf_prog *prog)
20079 {
20080 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20081 		switch (prog->expected_attach_type) {
20082 		case BPF_TRACE_FENTRY:
20083 		case BPF_TRACE_FEXIT:
20084 		case BPF_MODIFY_RETURN:
20085 		case BPF_TRACE_ITER:
20086 			return true;
20087 		default:
20088 			return false;
20089 		}
20090 	}
20091 	return prog->type == BPF_PROG_TYPE_LSM ||
20092 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20093 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20094 }
20095 
20096 static int check_attach_btf_id(struct bpf_verifier_env *env)
20097 {
20098 	struct bpf_prog *prog = env->prog;
20099 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20100 	struct bpf_attach_target_info tgt_info = {};
20101 	u32 btf_id = prog->aux->attach_btf_id;
20102 	struct bpf_trampoline *tr;
20103 	int ret;
20104 	u64 key;
20105 
20106 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20107 		if (prog->aux->sleepable)
20108 			/* attach_btf_id checked to be zero already */
20109 			return 0;
20110 		verbose(env, "Syscall programs can only be sleepable\n");
20111 		return -EINVAL;
20112 	}
20113 
20114 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20115 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20116 		return -EINVAL;
20117 	}
20118 
20119 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20120 		return check_struct_ops_btf_id(env);
20121 
20122 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20123 	    prog->type != BPF_PROG_TYPE_LSM &&
20124 	    prog->type != BPF_PROG_TYPE_EXT)
20125 		return 0;
20126 
20127 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20128 	if (ret)
20129 		return ret;
20130 
20131 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20132 		/* to make freplace equivalent to their targets, they need to
20133 		 * inherit env->ops and expected_attach_type for the rest of the
20134 		 * verification
20135 		 */
20136 		env->ops = bpf_verifier_ops[tgt_prog->type];
20137 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20138 	}
20139 
20140 	/* store info about the attachment target that will be used later */
20141 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20142 	prog->aux->attach_func_name = tgt_info.tgt_name;
20143 	prog->aux->mod = tgt_info.tgt_mod;
20144 
20145 	if (tgt_prog) {
20146 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20147 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20148 	}
20149 
20150 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20151 		prog->aux->attach_btf_trace = true;
20152 		return 0;
20153 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20154 		if (!bpf_iter_prog_supported(prog))
20155 			return -EINVAL;
20156 		return 0;
20157 	}
20158 
20159 	if (prog->type == BPF_PROG_TYPE_LSM) {
20160 		ret = bpf_lsm_verify_prog(&env->log, prog);
20161 		if (ret < 0)
20162 			return ret;
20163 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20164 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20165 		return -EINVAL;
20166 	}
20167 
20168 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20169 	tr = bpf_trampoline_get(key, &tgt_info);
20170 	if (!tr)
20171 		return -ENOMEM;
20172 
20173 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20174 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20175 
20176 	prog->aux->dst_trampoline = tr;
20177 	return 0;
20178 }
20179 
20180 struct btf *bpf_get_btf_vmlinux(void)
20181 {
20182 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20183 		mutex_lock(&bpf_verifier_lock);
20184 		if (!btf_vmlinux)
20185 			btf_vmlinux = btf_parse_vmlinux();
20186 		mutex_unlock(&bpf_verifier_lock);
20187 	}
20188 	return btf_vmlinux;
20189 }
20190 
20191 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20192 {
20193 	u64 start_time = ktime_get_ns();
20194 	struct bpf_verifier_env *env;
20195 	int i, len, ret = -EINVAL, err;
20196 	u32 log_true_size;
20197 	bool is_priv;
20198 
20199 	/* no program is valid */
20200 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20201 		return -EINVAL;
20202 
20203 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20204 	 * allocate/free it every time bpf_check() is called
20205 	 */
20206 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20207 	if (!env)
20208 		return -ENOMEM;
20209 
20210 	env->bt.env = env;
20211 
20212 	len = (*prog)->len;
20213 	env->insn_aux_data =
20214 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20215 	ret = -ENOMEM;
20216 	if (!env->insn_aux_data)
20217 		goto err_free_env;
20218 	for (i = 0; i < len; i++)
20219 		env->insn_aux_data[i].orig_idx = i;
20220 	env->prog = *prog;
20221 	env->ops = bpf_verifier_ops[env->prog->type];
20222 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20223 	is_priv = bpf_capable();
20224 
20225 	bpf_get_btf_vmlinux();
20226 
20227 	/* grab the mutex to protect few globals used by verifier */
20228 	if (!is_priv)
20229 		mutex_lock(&bpf_verifier_lock);
20230 
20231 	/* user could have requested verbose verifier output
20232 	 * and supplied buffer to store the verification trace
20233 	 */
20234 	ret = bpf_vlog_init(&env->log, attr->log_level,
20235 			    (char __user *) (unsigned long) attr->log_buf,
20236 			    attr->log_size);
20237 	if (ret)
20238 		goto err_unlock;
20239 
20240 	mark_verifier_state_clean(env);
20241 
20242 	if (IS_ERR(btf_vmlinux)) {
20243 		/* Either gcc or pahole or kernel are broken. */
20244 		verbose(env, "in-kernel BTF is malformed\n");
20245 		ret = PTR_ERR(btf_vmlinux);
20246 		goto skip_full_check;
20247 	}
20248 
20249 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20250 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20251 		env->strict_alignment = true;
20252 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20253 		env->strict_alignment = false;
20254 
20255 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20256 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20257 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20258 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20259 	env->bpf_capable = bpf_capable();
20260 
20261 	if (is_priv)
20262 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20263 
20264 	env->explored_states = kvcalloc(state_htab_size(env),
20265 				       sizeof(struct bpf_verifier_state_list *),
20266 				       GFP_USER);
20267 	ret = -ENOMEM;
20268 	if (!env->explored_states)
20269 		goto skip_full_check;
20270 
20271 	ret = add_subprog_and_kfunc(env);
20272 	if (ret < 0)
20273 		goto skip_full_check;
20274 
20275 	ret = check_subprogs(env);
20276 	if (ret < 0)
20277 		goto skip_full_check;
20278 
20279 	ret = check_btf_info(env, attr, uattr);
20280 	if (ret < 0)
20281 		goto skip_full_check;
20282 
20283 	ret = check_attach_btf_id(env);
20284 	if (ret)
20285 		goto skip_full_check;
20286 
20287 	ret = resolve_pseudo_ldimm64(env);
20288 	if (ret < 0)
20289 		goto skip_full_check;
20290 
20291 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20292 		ret = bpf_prog_offload_verifier_prep(env->prog);
20293 		if (ret)
20294 			goto skip_full_check;
20295 	}
20296 
20297 	ret = check_cfg(env);
20298 	if (ret < 0)
20299 		goto skip_full_check;
20300 
20301 	ret = do_check_subprogs(env);
20302 	ret = ret ?: do_check_main(env);
20303 
20304 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20305 		ret = bpf_prog_offload_finalize(env);
20306 
20307 skip_full_check:
20308 	kvfree(env->explored_states);
20309 
20310 	if (ret == 0)
20311 		ret = check_max_stack_depth(env);
20312 
20313 	/* instruction rewrites happen after this point */
20314 	if (ret == 0)
20315 		ret = optimize_bpf_loop(env);
20316 
20317 	if (is_priv) {
20318 		if (ret == 0)
20319 			opt_hard_wire_dead_code_branches(env);
20320 		if (ret == 0)
20321 			ret = opt_remove_dead_code(env);
20322 		if (ret == 0)
20323 			ret = opt_remove_nops(env);
20324 	} else {
20325 		if (ret == 0)
20326 			sanitize_dead_code(env);
20327 	}
20328 
20329 	if (ret == 0)
20330 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20331 		ret = convert_ctx_accesses(env);
20332 
20333 	if (ret == 0)
20334 		ret = do_misc_fixups(env);
20335 
20336 	/* do 32-bit optimization after insn patching has done so those patched
20337 	 * insns could be handled correctly.
20338 	 */
20339 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20340 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20341 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20342 								     : false;
20343 	}
20344 
20345 	if (ret == 0)
20346 		ret = fixup_call_args(env);
20347 
20348 	env->verification_time = ktime_get_ns() - start_time;
20349 	print_verification_stats(env);
20350 	env->prog->aux->verified_insns = env->insn_processed;
20351 
20352 	/* preserve original error even if log finalization is successful */
20353 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20354 	if (err)
20355 		ret = err;
20356 
20357 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20358 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20359 				  &log_true_size, sizeof(log_true_size))) {
20360 		ret = -EFAULT;
20361 		goto err_release_maps;
20362 	}
20363 
20364 	if (ret)
20365 		goto err_release_maps;
20366 
20367 	if (env->used_map_cnt) {
20368 		/* if program passed verifier, update used_maps in bpf_prog_info */
20369 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20370 							  sizeof(env->used_maps[0]),
20371 							  GFP_KERNEL);
20372 
20373 		if (!env->prog->aux->used_maps) {
20374 			ret = -ENOMEM;
20375 			goto err_release_maps;
20376 		}
20377 
20378 		memcpy(env->prog->aux->used_maps, env->used_maps,
20379 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20380 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20381 	}
20382 	if (env->used_btf_cnt) {
20383 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20384 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20385 							  sizeof(env->used_btfs[0]),
20386 							  GFP_KERNEL);
20387 		if (!env->prog->aux->used_btfs) {
20388 			ret = -ENOMEM;
20389 			goto err_release_maps;
20390 		}
20391 
20392 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20393 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20394 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20395 	}
20396 	if (env->used_map_cnt || env->used_btf_cnt) {
20397 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20398 		 * bpf_ld_imm64 instructions
20399 		 */
20400 		convert_pseudo_ld_imm64(env);
20401 	}
20402 
20403 	adjust_btf_func(env);
20404 
20405 err_release_maps:
20406 	if (!env->prog->aux->used_maps)
20407 		/* if we didn't copy map pointers into bpf_prog_info, release
20408 		 * them now. Otherwise free_used_maps() will release them.
20409 		 */
20410 		release_maps(env);
20411 	if (!env->prog->aux->used_btfs)
20412 		release_btfs(env);
20413 
20414 	/* extension progs temporarily inherit the attach_type of their targets
20415 	   for verification purposes, so set it back to zero before returning
20416 	 */
20417 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20418 		env->prog->expected_attach_type = 0;
20419 
20420 	*prog = env->prog;
20421 err_unlock:
20422 	if (!is_priv)
20423 		mutex_unlock(&bpf_verifier_lock);
20424 	vfree(env->insn_aux_data);
20425 err_free_env:
20426 	kfree(env);
20427 	return ret;
20428 }
20429