xref: /openbmc/linux/kernel/bpf/verifier.c (revision 8f91116f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 	if (type_may_be_null(flag))
2543 		regs[regno].id = ++env->id_gen;
2544 }
2545 
2546 #define DEF_NOT_SUBREG	(0)
2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 			   struct bpf_func_state *state)
2549 {
2550 	struct bpf_reg_state *regs = state->regs;
2551 	int i;
2552 
2553 	for (i = 0; i < MAX_BPF_REG; i++) {
2554 		mark_reg_not_init(env, regs, i);
2555 		regs[i].live = REG_LIVE_NONE;
2556 		regs[i].parent = NULL;
2557 		regs[i].subreg_def = DEF_NOT_SUBREG;
2558 	}
2559 
2560 	/* frame pointer */
2561 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2562 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2563 	regs[BPF_REG_FP].frameno = state->frameno;
2564 }
2565 
2566 #define BPF_MAIN_FUNC (-1)
2567 static void init_func_state(struct bpf_verifier_env *env,
2568 			    struct bpf_func_state *state,
2569 			    int callsite, int frameno, int subprogno)
2570 {
2571 	state->callsite = callsite;
2572 	state->frameno = frameno;
2573 	state->subprogno = subprogno;
2574 	state->callback_ret_range = tnum_range(0, 0);
2575 	init_reg_state(env, state);
2576 	mark_verifier_state_scratched(env);
2577 }
2578 
2579 /* Similar to push_stack(), but for async callbacks */
2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581 						int insn_idx, int prev_insn_idx,
2582 						int subprog)
2583 {
2584 	struct bpf_verifier_stack_elem *elem;
2585 	struct bpf_func_state *frame;
2586 
2587 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588 	if (!elem)
2589 		goto err;
2590 
2591 	elem->insn_idx = insn_idx;
2592 	elem->prev_insn_idx = prev_insn_idx;
2593 	elem->next = env->head;
2594 	elem->log_pos = env->log.end_pos;
2595 	env->head = elem;
2596 	env->stack_size++;
2597 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598 		verbose(env,
2599 			"The sequence of %d jumps is too complex for async cb.\n",
2600 			env->stack_size);
2601 		goto err;
2602 	}
2603 	/* Unlike push_stack() do not copy_verifier_state().
2604 	 * The caller state doesn't matter.
2605 	 * This is async callback. It starts in a fresh stack.
2606 	 * Initialize it similar to do_check_common().
2607 	 */
2608 	elem->st.branches = 1;
2609 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610 	if (!frame)
2611 		goto err;
2612 	init_func_state(env, frame,
2613 			BPF_MAIN_FUNC /* callsite */,
2614 			0 /* frameno within this callchain */,
2615 			subprog /* subprog number within this prog */);
2616 	elem->st.frame[0] = frame;
2617 	return &elem->st;
2618 err:
2619 	free_verifier_state(env->cur_state, true);
2620 	env->cur_state = NULL;
2621 	/* pop all elements and return */
2622 	while (!pop_stack(env, NULL, NULL, false));
2623 	return NULL;
2624 }
2625 
2626 
2627 enum reg_arg_type {
2628 	SRC_OP,		/* register is used as source operand */
2629 	DST_OP,		/* register is used as destination operand */
2630 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2631 };
2632 
2633 static int cmp_subprogs(const void *a, const void *b)
2634 {
2635 	return ((struct bpf_subprog_info *)a)->start -
2636 	       ((struct bpf_subprog_info *)b)->start;
2637 }
2638 
2639 static int find_subprog(struct bpf_verifier_env *env, int off)
2640 {
2641 	struct bpf_subprog_info *p;
2642 
2643 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2644 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2645 	if (!p)
2646 		return -ENOENT;
2647 	return p - env->subprog_info;
2648 
2649 }
2650 
2651 static int add_subprog(struct bpf_verifier_env *env, int off)
2652 {
2653 	int insn_cnt = env->prog->len;
2654 	int ret;
2655 
2656 	if (off >= insn_cnt || off < 0) {
2657 		verbose(env, "call to invalid destination\n");
2658 		return -EINVAL;
2659 	}
2660 	ret = find_subprog(env, off);
2661 	if (ret >= 0)
2662 		return ret;
2663 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2664 		verbose(env, "too many subprograms\n");
2665 		return -E2BIG;
2666 	}
2667 	/* determine subprog starts. The end is one before the next starts */
2668 	env->subprog_info[env->subprog_cnt++].start = off;
2669 	sort(env->subprog_info, env->subprog_cnt,
2670 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2671 	return env->subprog_cnt - 1;
2672 }
2673 
2674 #define MAX_KFUNC_DESCS 256
2675 #define MAX_KFUNC_BTFS	256
2676 
2677 struct bpf_kfunc_desc {
2678 	struct btf_func_model func_model;
2679 	u32 func_id;
2680 	s32 imm;
2681 	u16 offset;
2682 	unsigned long addr;
2683 };
2684 
2685 struct bpf_kfunc_btf {
2686 	struct btf *btf;
2687 	struct module *module;
2688 	u16 offset;
2689 };
2690 
2691 struct bpf_kfunc_desc_tab {
2692 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2693 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2694 	 * available, therefore at the end of verification do_misc_fixups()
2695 	 * sorts this by imm and offset.
2696 	 */
2697 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2698 	u32 nr_descs;
2699 };
2700 
2701 struct bpf_kfunc_btf_tab {
2702 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2703 	u32 nr_descs;
2704 };
2705 
2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2707 {
2708 	const struct bpf_kfunc_desc *d0 = a;
2709 	const struct bpf_kfunc_desc *d1 = b;
2710 
2711 	/* func_id is not greater than BTF_MAX_TYPE */
2712 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2713 }
2714 
2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2716 {
2717 	const struct bpf_kfunc_btf *d0 = a;
2718 	const struct bpf_kfunc_btf *d1 = b;
2719 
2720 	return d0->offset - d1->offset;
2721 }
2722 
2723 static const struct bpf_kfunc_desc *
2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2725 {
2726 	struct bpf_kfunc_desc desc = {
2727 		.func_id = func_id,
2728 		.offset = offset,
2729 	};
2730 	struct bpf_kfunc_desc_tab *tab;
2731 
2732 	tab = prog->aux->kfunc_tab;
2733 	return bsearch(&desc, tab->descs, tab->nr_descs,
2734 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2735 }
2736 
2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2738 		       u16 btf_fd_idx, u8 **func_addr)
2739 {
2740 	const struct bpf_kfunc_desc *desc;
2741 
2742 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2743 	if (!desc)
2744 		return -EFAULT;
2745 
2746 	*func_addr = (u8 *)desc->addr;
2747 	return 0;
2748 }
2749 
2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2751 					 s16 offset)
2752 {
2753 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2754 	struct bpf_kfunc_btf_tab *tab;
2755 	struct bpf_kfunc_btf *b;
2756 	struct module *mod;
2757 	struct btf *btf;
2758 	int btf_fd;
2759 
2760 	tab = env->prog->aux->kfunc_btf_tab;
2761 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2762 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2763 	if (!b) {
2764 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2765 			verbose(env, "too many different module BTFs\n");
2766 			return ERR_PTR(-E2BIG);
2767 		}
2768 
2769 		if (bpfptr_is_null(env->fd_array)) {
2770 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2771 			return ERR_PTR(-EPROTO);
2772 		}
2773 
2774 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2775 					    offset * sizeof(btf_fd),
2776 					    sizeof(btf_fd)))
2777 			return ERR_PTR(-EFAULT);
2778 
2779 		btf = btf_get_by_fd(btf_fd);
2780 		if (IS_ERR(btf)) {
2781 			verbose(env, "invalid module BTF fd specified\n");
2782 			return btf;
2783 		}
2784 
2785 		if (!btf_is_module(btf)) {
2786 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2787 			btf_put(btf);
2788 			return ERR_PTR(-EINVAL);
2789 		}
2790 
2791 		mod = btf_try_get_module(btf);
2792 		if (!mod) {
2793 			btf_put(btf);
2794 			return ERR_PTR(-ENXIO);
2795 		}
2796 
2797 		b = &tab->descs[tab->nr_descs++];
2798 		b->btf = btf;
2799 		b->module = mod;
2800 		b->offset = offset;
2801 
2802 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2803 		     kfunc_btf_cmp_by_off, NULL);
2804 	}
2805 	return b->btf;
2806 }
2807 
2808 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2809 {
2810 	if (!tab)
2811 		return;
2812 
2813 	while (tab->nr_descs--) {
2814 		module_put(tab->descs[tab->nr_descs].module);
2815 		btf_put(tab->descs[tab->nr_descs].btf);
2816 	}
2817 	kfree(tab);
2818 }
2819 
2820 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2821 {
2822 	if (offset) {
2823 		if (offset < 0) {
2824 			/* In the future, this can be allowed to increase limit
2825 			 * of fd index into fd_array, interpreted as u16.
2826 			 */
2827 			verbose(env, "negative offset disallowed for kernel module function call\n");
2828 			return ERR_PTR(-EINVAL);
2829 		}
2830 
2831 		return __find_kfunc_desc_btf(env, offset);
2832 	}
2833 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2834 }
2835 
2836 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2837 {
2838 	const struct btf_type *func, *func_proto;
2839 	struct bpf_kfunc_btf_tab *btf_tab;
2840 	struct bpf_kfunc_desc_tab *tab;
2841 	struct bpf_prog_aux *prog_aux;
2842 	struct bpf_kfunc_desc *desc;
2843 	const char *func_name;
2844 	struct btf *desc_btf;
2845 	unsigned long call_imm;
2846 	unsigned long addr;
2847 	int err;
2848 
2849 	prog_aux = env->prog->aux;
2850 	tab = prog_aux->kfunc_tab;
2851 	btf_tab = prog_aux->kfunc_btf_tab;
2852 	if (!tab) {
2853 		if (!btf_vmlinux) {
2854 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2855 			return -ENOTSUPP;
2856 		}
2857 
2858 		if (!env->prog->jit_requested) {
2859 			verbose(env, "JIT is required for calling kernel function\n");
2860 			return -ENOTSUPP;
2861 		}
2862 
2863 		if (!bpf_jit_supports_kfunc_call()) {
2864 			verbose(env, "JIT does not support calling kernel function\n");
2865 			return -ENOTSUPP;
2866 		}
2867 
2868 		if (!env->prog->gpl_compatible) {
2869 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2870 			return -EINVAL;
2871 		}
2872 
2873 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2874 		if (!tab)
2875 			return -ENOMEM;
2876 		prog_aux->kfunc_tab = tab;
2877 	}
2878 
2879 	/* func_id == 0 is always invalid, but instead of returning an error, be
2880 	 * conservative and wait until the code elimination pass before returning
2881 	 * error, so that invalid calls that get pruned out can be in BPF programs
2882 	 * loaded from userspace.  It is also required that offset be untouched
2883 	 * for such calls.
2884 	 */
2885 	if (!func_id && !offset)
2886 		return 0;
2887 
2888 	if (!btf_tab && offset) {
2889 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2890 		if (!btf_tab)
2891 			return -ENOMEM;
2892 		prog_aux->kfunc_btf_tab = btf_tab;
2893 	}
2894 
2895 	desc_btf = find_kfunc_desc_btf(env, offset);
2896 	if (IS_ERR(desc_btf)) {
2897 		verbose(env, "failed to find BTF for kernel function\n");
2898 		return PTR_ERR(desc_btf);
2899 	}
2900 
2901 	if (find_kfunc_desc(env->prog, func_id, offset))
2902 		return 0;
2903 
2904 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2905 		verbose(env, "too many different kernel function calls\n");
2906 		return -E2BIG;
2907 	}
2908 
2909 	func = btf_type_by_id(desc_btf, func_id);
2910 	if (!func || !btf_type_is_func(func)) {
2911 		verbose(env, "kernel btf_id %u is not a function\n",
2912 			func_id);
2913 		return -EINVAL;
2914 	}
2915 	func_proto = btf_type_by_id(desc_btf, func->type);
2916 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2917 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2918 			func_id);
2919 		return -EINVAL;
2920 	}
2921 
2922 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2923 	addr = kallsyms_lookup_name(func_name);
2924 	if (!addr) {
2925 		verbose(env, "cannot find address for kernel function %s\n",
2926 			func_name);
2927 		return -EINVAL;
2928 	}
2929 	specialize_kfunc(env, func_id, offset, &addr);
2930 
2931 	if (bpf_jit_supports_far_kfunc_call()) {
2932 		call_imm = func_id;
2933 	} else {
2934 		call_imm = BPF_CALL_IMM(addr);
2935 		/* Check whether the relative offset overflows desc->imm */
2936 		if ((unsigned long)(s32)call_imm != call_imm) {
2937 			verbose(env, "address of kernel function %s is out of range\n",
2938 				func_name);
2939 			return -EINVAL;
2940 		}
2941 	}
2942 
2943 	if (bpf_dev_bound_kfunc_id(func_id)) {
2944 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2945 		if (err)
2946 			return err;
2947 	}
2948 
2949 	desc = &tab->descs[tab->nr_descs++];
2950 	desc->func_id = func_id;
2951 	desc->imm = call_imm;
2952 	desc->offset = offset;
2953 	desc->addr = addr;
2954 	err = btf_distill_func_proto(&env->log, desc_btf,
2955 				     func_proto, func_name,
2956 				     &desc->func_model);
2957 	if (!err)
2958 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2959 		     kfunc_desc_cmp_by_id_off, NULL);
2960 	return err;
2961 }
2962 
2963 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2964 {
2965 	const struct bpf_kfunc_desc *d0 = a;
2966 	const struct bpf_kfunc_desc *d1 = b;
2967 
2968 	if (d0->imm != d1->imm)
2969 		return d0->imm < d1->imm ? -1 : 1;
2970 	if (d0->offset != d1->offset)
2971 		return d0->offset < d1->offset ? -1 : 1;
2972 	return 0;
2973 }
2974 
2975 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2976 {
2977 	struct bpf_kfunc_desc_tab *tab;
2978 
2979 	tab = prog->aux->kfunc_tab;
2980 	if (!tab)
2981 		return;
2982 
2983 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2984 	     kfunc_desc_cmp_by_imm_off, NULL);
2985 }
2986 
2987 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2988 {
2989 	return !!prog->aux->kfunc_tab;
2990 }
2991 
2992 const struct btf_func_model *
2993 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2994 			 const struct bpf_insn *insn)
2995 {
2996 	const struct bpf_kfunc_desc desc = {
2997 		.imm = insn->imm,
2998 		.offset = insn->off,
2999 	};
3000 	const struct bpf_kfunc_desc *res;
3001 	struct bpf_kfunc_desc_tab *tab;
3002 
3003 	tab = prog->aux->kfunc_tab;
3004 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3005 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3006 
3007 	return res ? &res->func_model : NULL;
3008 }
3009 
3010 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3011 {
3012 	struct bpf_subprog_info *subprog = env->subprog_info;
3013 	struct bpf_insn *insn = env->prog->insnsi;
3014 	int i, ret, insn_cnt = env->prog->len;
3015 
3016 	/* Add entry function. */
3017 	ret = add_subprog(env, 0);
3018 	if (ret)
3019 		return ret;
3020 
3021 	for (i = 0; i < insn_cnt; i++, insn++) {
3022 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3023 		    !bpf_pseudo_kfunc_call(insn))
3024 			continue;
3025 
3026 		if (!env->bpf_capable) {
3027 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3028 			return -EPERM;
3029 		}
3030 
3031 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3032 			ret = add_subprog(env, i + insn->imm + 1);
3033 		else
3034 			ret = add_kfunc_call(env, insn->imm, insn->off);
3035 
3036 		if (ret < 0)
3037 			return ret;
3038 	}
3039 
3040 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3041 	 * logic. 'subprog_cnt' should not be increased.
3042 	 */
3043 	subprog[env->subprog_cnt].start = insn_cnt;
3044 
3045 	if (env->log.level & BPF_LOG_LEVEL2)
3046 		for (i = 0; i < env->subprog_cnt; i++)
3047 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3048 
3049 	return 0;
3050 }
3051 
3052 static int check_subprogs(struct bpf_verifier_env *env)
3053 {
3054 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3055 	struct bpf_subprog_info *subprog = env->subprog_info;
3056 	struct bpf_insn *insn = env->prog->insnsi;
3057 	int insn_cnt = env->prog->len;
3058 
3059 	/* now check that all jumps are within the same subprog */
3060 	subprog_start = subprog[cur_subprog].start;
3061 	subprog_end = subprog[cur_subprog + 1].start;
3062 	for (i = 0; i < insn_cnt; i++) {
3063 		u8 code = insn[i].code;
3064 
3065 		if (code == (BPF_JMP | BPF_CALL) &&
3066 		    insn[i].src_reg == 0 &&
3067 		    insn[i].imm == BPF_FUNC_tail_call) {
3068 			subprog[cur_subprog].has_tail_call = true;
3069 			subprog[cur_subprog].tail_call_reachable = true;
3070 		}
3071 		if (BPF_CLASS(code) == BPF_LD &&
3072 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3073 			subprog[cur_subprog].has_ld_abs = true;
3074 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3075 			goto next;
3076 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3077 			goto next;
3078 		if (code == (BPF_JMP32 | BPF_JA))
3079 			off = i + insn[i].imm + 1;
3080 		else
3081 			off = i + insn[i].off + 1;
3082 		if (off < subprog_start || off >= subprog_end) {
3083 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3084 			return -EINVAL;
3085 		}
3086 next:
3087 		if (i == subprog_end - 1) {
3088 			/* to avoid fall-through from one subprog into another
3089 			 * the last insn of the subprog should be either exit
3090 			 * or unconditional jump back
3091 			 */
3092 			if (code != (BPF_JMP | BPF_EXIT) &&
3093 			    code != (BPF_JMP32 | BPF_JA) &&
3094 			    code != (BPF_JMP | BPF_JA)) {
3095 				verbose(env, "last insn is not an exit or jmp\n");
3096 				return -EINVAL;
3097 			}
3098 			subprog_start = subprog_end;
3099 			cur_subprog++;
3100 			if (cur_subprog < env->subprog_cnt)
3101 				subprog_end = subprog[cur_subprog + 1].start;
3102 		}
3103 	}
3104 	return 0;
3105 }
3106 
3107 /* Parentage chain of this register (or stack slot) should take care of all
3108  * issues like callee-saved registers, stack slot allocation time, etc.
3109  */
3110 static int mark_reg_read(struct bpf_verifier_env *env,
3111 			 const struct bpf_reg_state *state,
3112 			 struct bpf_reg_state *parent, u8 flag)
3113 {
3114 	bool writes = parent == state->parent; /* Observe write marks */
3115 	int cnt = 0;
3116 
3117 	while (parent) {
3118 		/* if read wasn't screened by an earlier write ... */
3119 		if (writes && state->live & REG_LIVE_WRITTEN)
3120 			break;
3121 		if (parent->live & REG_LIVE_DONE) {
3122 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3123 				reg_type_str(env, parent->type),
3124 				parent->var_off.value, parent->off);
3125 			return -EFAULT;
3126 		}
3127 		/* The first condition is more likely to be true than the
3128 		 * second, checked it first.
3129 		 */
3130 		if ((parent->live & REG_LIVE_READ) == flag ||
3131 		    parent->live & REG_LIVE_READ64)
3132 			/* The parentage chain never changes and
3133 			 * this parent was already marked as LIVE_READ.
3134 			 * There is no need to keep walking the chain again and
3135 			 * keep re-marking all parents as LIVE_READ.
3136 			 * This case happens when the same register is read
3137 			 * multiple times without writes into it in-between.
3138 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3139 			 * then no need to set the weak REG_LIVE_READ32.
3140 			 */
3141 			break;
3142 		/* ... then we depend on parent's value */
3143 		parent->live |= flag;
3144 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3145 		if (flag == REG_LIVE_READ64)
3146 			parent->live &= ~REG_LIVE_READ32;
3147 		state = parent;
3148 		parent = state->parent;
3149 		writes = true;
3150 		cnt++;
3151 	}
3152 
3153 	if (env->longest_mark_read_walk < cnt)
3154 		env->longest_mark_read_walk = cnt;
3155 	return 0;
3156 }
3157 
3158 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3159 {
3160 	struct bpf_func_state *state = func(env, reg);
3161 	int spi, ret;
3162 
3163 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3164 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3165 	 * check_kfunc_call.
3166 	 */
3167 	if (reg->type == CONST_PTR_TO_DYNPTR)
3168 		return 0;
3169 	spi = dynptr_get_spi(env, reg);
3170 	if (spi < 0)
3171 		return spi;
3172 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3173 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3174 	 * read.
3175 	 */
3176 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3177 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3178 	if (ret)
3179 		return ret;
3180 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3181 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3182 }
3183 
3184 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3185 			  int spi, int nr_slots)
3186 {
3187 	struct bpf_func_state *state = func(env, reg);
3188 	int err, i;
3189 
3190 	for (i = 0; i < nr_slots; i++) {
3191 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3192 
3193 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3194 		if (err)
3195 			return err;
3196 
3197 		mark_stack_slot_scratched(env, spi - i);
3198 	}
3199 
3200 	return 0;
3201 }
3202 
3203 /* This function is supposed to be used by the following 32-bit optimization
3204  * code only. It returns TRUE if the source or destination register operates
3205  * on 64-bit, otherwise return FALSE.
3206  */
3207 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3208 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3209 {
3210 	u8 code, class, op;
3211 
3212 	code = insn->code;
3213 	class = BPF_CLASS(code);
3214 	op = BPF_OP(code);
3215 	if (class == BPF_JMP) {
3216 		/* BPF_EXIT for "main" will reach here. Return TRUE
3217 		 * conservatively.
3218 		 */
3219 		if (op == BPF_EXIT)
3220 			return true;
3221 		if (op == BPF_CALL) {
3222 			/* BPF to BPF call will reach here because of marking
3223 			 * caller saved clobber with DST_OP_NO_MARK for which we
3224 			 * don't care the register def because they are anyway
3225 			 * marked as NOT_INIT already.
3226 			 */
3227 			if (insn->src_reg == BPF_PSEUDO_CALL)
3228 				return false;
3229 			/* Helper call will reach here because of arg type
3230 			 * check, conservatively return TRUE.
3231 			 */
3232 			if (t == SRC_OP)
3233 				return true;
3234 
3235 			return false;
3236 		}
3237 	}
3238 
3239 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3240 		return false;
3241 
3242 	if (class == BPF_ALU64 || class == BPF_JMP ||
3243 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3244 		return true;
3245 
3246 	if (class == BPF_ALU || class == BPF_JMP32)
3247 		return false;
3248 
3249 	if (class == BPF_LDX) {
3250 		if (t != SRC_OP)
3251 			return BPF_SIZE(code) == BPF_DW;
3252 		/* LDX source must be ptr. */
3253 		return true;
3254 	}
3255 
3256 	if (class == BPF_STX) {
3257 		/* BPF_STX (including atomic variants) has multiple source
3258 		 * operands, one of which is a ptr. Check whether the caller is
3259 		 * asking about it.
3260 		 */
3261 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3262 			return true;
3263 		return BPF_SIZE(code) == BPF_DW;
3264 	}
3265 
3266 	if (class == BPF_LD) {
3267 		u8 mode = BPF_MODE(code);
3268 
3269 		/* LD_IMM64 */
3270 		if (mode == BPF_IMM)
3271 			return true;
3272 
3273 		/* Both LD_IND and LD_ABS return 32-bit data. */
3274 		if (t != SRC_OP)
3275 			return  false;
3276 
3277 		/* Implicit ctx ptr. */
3278 		if (regno == BPF_REG_6)
3279 			return true;
3280 
3281 		/* Explicit source could be any width. */
3282 		return true;
3283 	}
3284 
3285 	if (class == BPF_ST)
3286 		/* The only source register for BPF_ST is a ptr. */
3287 		return true;
3288 
3289 	/* Conservatively return true at default. */
3290 	return true;
3291 }
3292 
3293 /* Return the regno defined by the insn, or -1. */
3294 static int insn_def_regno(const struct bpf_insn *insn)
3295 {
3296 	switch (BPF_CLASS(insn->code)) {
3297 	case BPF_JMP:
3298 	case BPF_JMP32:
3299 	case BPF_ST:
3300 		return -1;
3301 	case BPF_STX:
3302 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3303 		    (insn->imm & BPF_FETCH)) {
3304 			if (insn->imm == BPF_CMPXCHG)
3305 				return BPF_REG_0;
3306 			else
3307 				return insn->src_reg;
3308 		} else {
3309 			return -1;
3310 		}
3311 	default:
3312 		return insn->dst_reg;
3313 	}
3314 }
3315 
3316 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3317 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3318 {
3319 	int dst_reg = insn_def_regno(insn);
3320 
3321 	if (dst_reg == -1)
3322 		return false;
3323 
3324 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3325 }
3326 
3327 static void mark_insn_zext(struct bpf_verifier_env *env,
3328 			   struct bpf_reg_state *reg)
3329 {
3330 	s32 def_idx = reg->subreg_def;
3331 
3332 	if (def_idx == DEF_NOT_SUBREG)
3333 		return;
3334 
3335 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3336 	/* The dst will be zero extended, so won't be sub-register anymore. */
3337 	reg->subreg_def = DEF_NOT_SUBREG;
3338 }
3339 
3340 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3341 			   enum reg_arg_type t)
3342 {
3343 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3344 	struct bpf_reg_state *reg;
3345 	bool rw64;
3346 
3347 	if (regno >= MAX_BPF_REG) {
3348 		verbose(env, "R%d is invalid\n", regno);
3349 		return -EINVAL;
3350 	}
3351 
3352 	mark_reg_scratched(env, regno);
3353 
3354 	reg = &regs[regno];
3355 	rw64 = is_reg64(env, insn, regno, reg, t);
3356 	if (t == SRC_OP) {
3357 		/* check whether register used as source operand can be read */
3358 		if (reg->type == NOT_INIT) {
3359 			verbose(env, "R%d !read_ok\n", regno);
3360 			return -EACCES;
3361 		}
3362 		/* We don't need to worry about FP liveness because it's read-only */
3363 		if (regno == BPF_REG_FP)
3364 			return 0;
3365 
3366 		if (rw64)
3367 			mark_insn_zext(env, reg);
3368 
3369 		return mark_reg_read(env, reg, reg->parent,
3370 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3371 	} else {
3372 		/* check whether register used as dest operand can be written to */
3373 		if (regno == BPF_REG_FP) {
3374 			verbose(env, "frame pointer is read only\n");
3375 			return -EACCES;
3376 		}
3377 		reg->live |= REG_LIVE_WRITTEN;
3378 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3379 		if (t == DST_OP)
3380 			mark_reg_unknown(env, regs, regno);
3381 	}
3382 	return 0;
3383 }
3384 
3385 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3386 			 enum reg_arg_type t)
3387 {
3388 	struct bpf_verifier_state *vstate = env->cur_state;
3389 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3390 
3391 	return __check_reg_arg(env, state->regs, regno, t);
3392 }
3393 
3394 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3395 {
3396 	env->insn_aux_data[idx].jmp_point = true;
3397 }
3398 
3399 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3400 {
3401 	return env->insn_aux_data[insn_idx].jmp_point;
3402 }
3403 
3404 /* for any branch, call, exit record the history of jmps in the given state */
3405 static int push_jmp_history(struct bpf_verifier_env *env,
3406 			    struct bpf_verifier_state *cur)
3407 {
3408 	u32 cnt = cur->jmp_history_cnt;
3409 	struct bpf_idx_pair *p;
3410 	size_t alloc_size;
3411 
3412 	if (!is_jmp_point(env, env->insn_idx))
3413 		return 0;
3414 
3415 	cnt++;
3416 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3417 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3418 	if (!p)
3419 		return -ENOMEM;
3420 	p[cnt - 1].idx = env->insn_idx;
3421 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3422 	cur->jmp_history = p;
3423 	cur->jmp_history_cnt = cnt;
3424 	return 0;
3425 }
3426 
3427 /* Backtrack one insn at a time. If idx is not at the top of recorded
3428  * history then previous instruction came from straight line execution.
3429  * Return -ENOENT if we exhausted all instructions within given state.
3430  *
3431  * It's legal to have a bit of a looping with the same starting and ending
3432  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3433  * instruction index is the same as state's first_idx doesn't mean we are
3434  * done. If there is still some jump history left, we should keep going. We
3435  * need to take into account that we might have a jump history between given
3436  * state's parent and itself, due to checkpointing. In this case, we'll have
3437  * history entry recording a jump from last instruction of parent state and
3438  * first instruction of given state.
3439  */
3440 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3441 			     u32 *history)
3442 {
3443 	u32 cnt = *history;
3444 
3445 	if (i == st->first_insn_idx) {
3446 		if (cnt == 0)
3447 			return -ENOENT;
3448 		if (cnt == 1 && st->jmp_history[0].idx == i)
3449 			return -ENOENT;
3450 	}
3451 
3452 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3453 		i = st->jmp_history[cnt - 1].prev_idx;
3454 		(*history)--;
3455 	} else {
3456 		i--;
3457 	}
3458 	return i;
3459 }
3460 
3461 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3462 {
3463 	const struct btf_type *func;
3464 	struct btf *desc_btf;
3465 
3466 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3467 		return NULL;
3468 
3469 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3470 	if (IS_ERR(desc_btf))
3471 		return "<error>";
3472 
3473 	func = btf_type_by_id(desc_btf, insn->imm);
3474 	return btf_name_by_offset(desc_btf, func->name_off);
3475 }
3476 
3477 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3478 {
3479 	bt->frame = frame;
3480 }
3481 
3482 static inline void bt_reset(struct backtrack_state *bt)
3483 {
3484 	struct bpf_verifier_env *env = bt->env;
3485 
3486 	memset(bt, 0, sizeof(*bt));
3487 	bt->env = env;
3488 }
3489 
3490 static inline u32 bt_empty(struct backtrack_state *bt)
3491 {
3492 	u64 mask = 0;
3493 	int i;
3494 
3495 	for (i = 0; i <= bt->frame; i++)
3496 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3497 
3498 	return mask == 0;
3499 }
3500 
3501 static inline int bt_subprog_enter(struct backtrack_state *bt)
3502 {
3503 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3504 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3505 		WARN_ONCE(1, "verifier backtracking bug");
3506 		return -EFAULT;
3507 	}
3508 	bt->frame++;
3509 	return 0;
3510 }
3511 
3512 static inline int bt_subprog_exit(struct backtrack_state *bt)
3513 {
3514 	if (bt->frame == 0) {
3515 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3516 		WARN_ONCE(1, "verifier backtracking bug");
3517 		return -EFAULT;
3518 	}
3519 	bt->frame--;
3520 	return 0;
3521 }
3522 
3523 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3524 {
3525 	bt->reg_masks[frame] |= 1 << reg;
3526 }
3527 
3528 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3529 {
3530 	bt->reg_masks[frame] &= ~(1 << reg);
3531 }
3532 
3533 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3534 {
3535 	bt_set_frame_reg(bt, bt->frame, reg);
3536 }
3537 
3538 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3539 {
3540 	bt_clear_frame_reg(bt, bt->frame, reg);
3541 }
3542 
3543 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3544 {
3545 	bt->stack_masks[frame] |= 1ull << slot;
3546 }
3547 
3548 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3549 {
3550 	bt->stack_masks[frame] &= ~(1ull << slot);
3551 }
3552 
3553 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3554 {
3555 	bt_set_frame_slot(bt, bt->frame, slot);
3556 }
3557 
3558 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3559 {
3560 	bt_clear_frame_slot(bt, bt->frame, slot);
3561 }
3562 
3563 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3564 {
3565 	return bt->reg_masks[frame];
3566 }
3567 
3568 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3569 {
3570 	return bt->reg_masks[bt->frame];
3571 }
3572 
3573 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3574 {
3575 	return bt->stack_masks[frame];
3576 }
3577 
3578 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3579 {
3580 	return bt->stack_masks[bt->frame];
3581 }
3582 
3583 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3584 {
3585 	return bt->reg_masks[bt->frame] & (1 << reg);
3586 }
3587 
3588 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3589 {
3590 	return bt->stack_masks[bt->frame] & (1ull << slot);
3591 }
3592 
3593 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3594 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3595 {
3596 	DECLARE_BITMAP(mask, 64);
3597 	bool first = true;
3598 	int i, n;
3599 
3600 	buf[0] = '\0';
3601 
3602 	bitmap_from_u64(mask, reg_mask);
3603 	for_each_set_bit(i, mask, 32) {
3604 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3605 		first = false;
3606 		buf += n;
3607 		buf_sz -= n;
3608 		if (buf_sz < 0)
3609 			break;
3610 	}
3611 }
3612 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3613 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3614 {
3615 	DECLARE_BITMAP(mask, 64);
3616 	bool first = true;
3617 	int i, n;
3618 
3619 	buf[0] = '\0';
3620 
3621 	bitmap_from_u64(mask, stack_mask);
3622 	for_each_set_bit(i, mask, 64) {
3623 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3624 		first = false;
3625 		buf += n;
3626 		buf_sz -= n;
3627 		if (buf_sz < 0)
3628 			break;
3629 	}
3630 }
3631 
3632 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3633 
3634 /* For given verifier state backtrack_insn() is called from the last insn to
3635  * the first insn. Its purpose is to compute a bitmask of registers and
3636  * stack slots that needs precision in the parent verifier state.
3637  *
3638  * @idx is an index of the instruction we are currently processing;
3639  * @subseq_idx is an index of the subsequent instruction that:
3640  *   - *would be* executed next, if jump history is viewed in forward order;
3641  *   - *was* processed previously during backtracking.
3642  */
3643 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3644 			  struct backtrack_state *bt)
3645 {
3646 	const struct bpf_insn_cbs cbs = {
3647 		.cb_call	= disasm_kfunc_name,
3648 		.cb_print	= verbose,
3649 		.private_data	= env,
3650 	};
3651 	struct bpf_insn *insn = env->prog->insnsi + idx;
3652 	u8 class = BPF_CLASS(insn->code);
3653 	u8 opcode = BPF_OP(insn->code);
3654 	u8 mode = BPF_MODE(insn->code);
3655 	u32 dreg = insn->dst_reg;
3656 	u32 sreg = insn->src_reg;
3657 	u32 spi, i;
3658 
3659 	if (insn->code == 0)
3660 		return 0;
3661 	if (env->log.level & BPF_LOG_LEVEL2) {
3662 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3663 		verbose(env, "mark_precise: frame%d: regs=%s ",
3664 			bt->frame, env->tmp_str_buf);
3665 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3666 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3667 		verbose(env, "%d: ", idx);
3668 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3669 	}
3670 
3671 	if (class == BPF_ALU || class == BPF_ALU64) {
3672 		if (!bt_is_reg_set(bt, dreg))
3673 			return 0;
3674 		if (opcode == BPF_END || opcode == BPF_NEG) {
3675 			/* sreg is reserved and unused
3676 			 * dreg still need precision before this insn
3677 			 */
3678 			return 0;
3679 		} else if (opcode == BPF_MOV) {
3680 			if (BPF_SRC(insn->code) == BPF_X) {
3681 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3682 				 * dreg needs precision after this insn
3683 				 * sreg needs precision before this insn
3684 				 */
3685 				bt_clear_reg(bt, dreg);
3686 				if (sreg != BPF_REG_FP)
3687 					bt_set_reg(bt, sreg);
3688 			} else {
3689 				/* dreg = K
3690 				 * dreg needs precision after this insn.
3691 				 * Corresponding register is already marked
3692 				 * as precise=true in this verifier state.
3693 				 * No further markings in parent are necessary
3694 				 */
3695 				bt_clear_reg(bt, dreg);
3696 			}
3697 		} else {
3698 			if (BPF_SRC(insn->code) == BPF_X) {
3699 				/* dreg += sreg
3700 				 * both dreg and sreg need precision
3701 				 * before this insn
3702 				 */
3703 				if (sreg != BPF_REG_FP)
3704 					bt_set_reg(bt, sreg);
3705 			} /* else dreg += K
3706 			   * dreg still needs precision before this insn
3707 			   */
3708 		}
3709 	} else if (class == BPF_LDX) {
3710 		if (!bt_is_reg_set(bt, dreg))
3711 			return 0;
3712 		bt_clear_reg(bt, dreg);
3713 
3714 		/* scalars can only be spilled into stack w/o losing precision.
3715 		 * Load from any other memory can be zero extended.
3716 		 * The desire to keep that precision is already indicated
3717 		 * by 'precise' mark in corresponding register of this state.
3718 		 * No further tracking necessary.
3719 		 */
3720 		if (insn->src_reg != BPF_REG_FP)
3721 			return 0;
3722 
3723 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3724 		 * that [fp - off] slot contains scalar that needs to be
3725 		 * tracked with precision
3726 		 */
3727 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3728 		if (spi >= 64) {
3729 			verbose(env, "BUG spi %d\n", spi);
3730 			WARN_ONCE(1, "verifier backtracking bug");
3731 			return -EFAULT;
3732 		}
3733 		bt_set_slot(bt, spi);
3734 	} else if (class == BPF_STX || class == BPF_ST) {
3735 		if (bt_is_reg_set(bt, dreg))
3736 			/* stx & st shouldn't be using _scalar_ dst_reg
3737 			 * to access memory. It means backtracking
3738 			 * encountered a case of pointer subtraction.
3739 			 */
3740 			return -ENOTSUPP;
3741 		/* scalars can only be spilled into stack */
3742 		if (insn->dst_reg != BPF_REG_FP)
3743 			return 0;
3744 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3745 		if (spi >= 64) {
3746 			verbose(env, "BUG spi %d\n", spi);
3747 			WARN_ONCE(1, "verifier backtracking bug");
3748 			return -EFAULT;
3749 		}
3750 		if (!bt_is_slot_set(bt, spi))
3751 			return 0;
3752 		bt_clear_slot(bt, spi);
3753 		if (class == BPF_STX)
3754 			bt_set_reg(bt, sreg);
3755 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3756 		if (bpf_pseudo_call(insn)) {
3757 			int subprog_insn_idx, subprog;
3758 
3759 			subprog_insn_idx = idx + insn->imm + 1;
3760 			subprog = find_subprog(env, subprog_insn_idx);
3761 			if (subprog < 0)
3762 				return -EFAULT;
3763 
3764 			if (subprog_is_global(env, subprog)) {
3765 				/* check that jump history doesn't have any
3766 				 * extra instructions from subprog; the next
3767 				 * instruction after call to global subprog
3768 				 * should be literally next instruction in
3769 				 * caller program
3770 				 */
3771 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3772 				/* r1-r5 are invalidated after subprog call,
3773 				 * so for global func call it shouldn't be set
3774 				 * anymore
3775 				 */
3776 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3777 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3778 					WARN_ONCE(1, "verifier backtracking bug");
3779 					return -EFAULT;
3780 				}
3781 				/* global subprog always sets R0 */
3782 				bt_clear_reg(bt, BPF_REG_0);
3783 				return 0;
3784 			} else {
3785 				/* static subprog call instruction, which
3786 				 * means that we are exiting current subprog,
3787 				 * so only r1-r5 could be still requested as
3788 				 * precise, r0 and r6-r10 or any stack slot in
3789 				 * the current frame should be zero by now
3790 				 */
3791 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3792 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3793 					WARN_ONCE(1, "verifier backtracking bug");
3794 					return -EFAULT;
3795 				}
3796 				/* we don't track register spills perfectly,
3797 				 * so fallback to force-precise instead of failing */
3798 				if (bt_stack_mask(bt) != 0)
3799 					return -ENOTSUPP;
3800 				/* propagate r1-r5 to the caller */
3801 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3802 					if (bt_is_reg_set(bt, i)) {
3803 						bt_clear_reg(bt, i);
3804 						bt_set_frame_reg(bt, bt->frame - 1, i);
3805 					}
3806 				}
3807 				if (bt_subprog_exit(bt))
3808 					return -EFAULT;
3809 				return 0;
3810 			}
3811 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3812 			/* exit from callback subprog to callback-calling helper or
3813 			 * kfunc call. Use idx/subseq_idx check to discern it from
3814 			 * straight line code backtracking.
3815 			 * Unlike the subprog call handling above, we shouldn't
3816 			 * propagate precision of r1-r5 (if any requested), as they are
3817 			 * not actually arguments passed directly to callback subprogs
3818 			 */
3819 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3820 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3821 				WARN_ONCE(1, "verifier backtracking bug");
3822 				return -EFAULT;
3823 			}
3824 			if (bt_stack_mask(bt) != 0)
3825 				return -ENOTSUPP;
3826 			/* clear r1-r5 in callback subprog's mask */
3827 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3828 				bt_clear_reg(bt, i);
3829 			if (bt_subprog_exit(bt))
3830 				return -EFAULT;
3831 			return 0;
3832 		} else if (opcode == BPF_CALL) {
3833 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3834 			 * catch this error later. Make backtracking conservative
3835 			 * with ENOTSUPP.
3836 			 */
3837 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3838 				return -ENOTSUPP;
3839 			/* regular helper call sets R0 */
3840 			bt_clear_reg(bt, BPF_REG_0);
3841 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3842 				/* if backtracing was looking for registers R1-R5
3843 				 * they should have been found already.
3844 				 */
3845 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3846 				WARN_ONCE(1, "verifier backtracking bug");
3847 				return -EFAULT;
3848 			}
3849 		} else if (opcode == BPF_EXIT) {
3850 			bool r0_precise;
3851 
3852 			/* Backtracking to a nested function call, 'idx' is a part of
3853 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3854 			 * In case of a regular function call, instructions giving
3855 			 * precision to registers R1-R5 should have been found already.
3856 			 * In case of a callback, it is ok to have R1-R5 marked for
3857 			 * backtracking, as these registers are set by the function
3858 			 * invoking callback.
3859 			 */
3860 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3861 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3862 					bt_clear_reg(bt, i);
3863 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3864 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3865 				WARN_ONCE(1, "verifier backtracking bug");
3866 				return -EFAULT;
3867 			}
3868 
3869 			/* BPF_EXIT in subprog or callback always returns
3870 			 * right after the call instruction, so by checking
3871 			 * whether the instruction at subseq_idx-1 is subprog
3872 			 * call or not we can distinguish actual exit from
3873 			 * *subprog* from exit from *callback*. In the former
3874 			 * case, we need to propagate r0 precision, if
3875 			 * necessary. In the former we never do that.
3876 			 */
3877 			r0_precise = subseq_idx - 1 >= 0 &&
3878 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3879 				     bt_is_reg_set(bt, BPF_REG_0);
3880 
3881 			bt_clear_reg(bt, BPF_REG_0);
3882 			if (bt_subprog_enter(bt))
3883 				return -EFAULT;
3884 
3885 			if (r0_precise)
3886 				bt_set_reg(bt, BPF_REG_0);
3887 			/* r6-r9 and stack slots will stay set in caller frame
3888 			 * bitmasks until we return back from callee(s)
3889 			 */
3890 			return 0;
3891 		} else if (BPF_SRC(insn->code) == BPF_X) {
3892 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3893 				return 0;
3894 			/* dreg <cond> sreg
3895 			 * Both dreg and sreg need precision before
3896 			 * this insn. If only sreg was marked precise
3897 			 * before it would be equally necessary to
3898 			 * propagate it to dreg.
3899 			 */
3900 			bt_set_reg(bt, dreg);
3901 			bt_set_reg(bt, sreg);
3902 			 /* else dreg <cond> K
3903 			  * Only dreg still needs precision before
3904 			  * this insn, so for the K-based conditional
3905 			  * there is nothing new to be marked.
3906 			  */
3907 		}
3908 	} else if (class == BPF_LD) {
3909 		if (!bt_is_reg_set(bt, dreg))
3910 			return 0;
3911 		bt_clear_reg(bt, dreg);
3912 		/* It's ld_imm64 or ld_abs or ld_ind.
3913 		 * For ld_imm64 no further tracking of precision
3914 		 * into parent is necessary
3915 		 */
3916 		if (mode == BPF_IND || mode == BPF_ABS)
3917 			/* to be analyzed */
3918 			return -ENOTSUPP;
3919 	}
3920 	return 0;
3921 }
3922 
3923 /* the scalar precision tracking algorithm:
3924  * . at the start all registers have precise=false.
3925  * . scalar ranges are tracked as normal through alu and jmp insns.
3926  * . once precise value of the scalar register is used in:
3927  *   .  ptr + scalar alu
3928  *   . if (scalar cond K|scalar)
3929  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3930  *   backtrack through the verifier states and mark all registers and
3931  *   stack slots with spilled constants that these scalar regisers
3932  *   should be precise.
3933  * . during state pruning two registers (or spilled stack slots)
3934  *   are equivalent if both are not precise.
3935  *
3936  * Note the verifier cannot simply walk register parentage chain,
3937  * since many different registers and stack slots could have been
3938  * used to compute single precise scalar.
3939  *
3940  * The approach of starting with precise=true for all registers and then
3941  * backtrack to mark a register as not precise when the verifier detects
3942  * that program doesn't care about specific value (e.g., when helper
3943  * takes register as ARG_ANYTHING parameter) is not safe.
3944  *
3945  * It's ok to walk single parentage chain of the verifier states.
3946  * It's possible that this backtracking will go all the way till 1st insn.
3947  * All other branches will be explored for needing precision later.
3948  *
3949  * The backtracking needs to deal with cases like:
3950  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3951  * r9 -= r8
3952  * r5 = r9
3953  * if r5 > 0x79f goto pc+7
3954  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3955  * r5 += 1
3956  * ...
3957  * call bpf_perf_event_output#25
3958  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3959  *
3960  * and this case:
3961  * r6 = 1
3962  * call foo // uses callee's r6 inside to compute r0
3963  * r0 += r6
3964  * if r0 == 0 goto
3965  *
3966  * to track above reg_mask/stack_mask needs to be independent for each frame.
3967  *
3968  * Also if parent's curframe > frame where backtracking started,
3969  * the verifier need to mark registers in both frames, otherwise callees
3970  * may incorrectly prune callers. This is similar to
3971  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3972  *
3973  * For now backtracking falls back into conservative marking.
3974  */
3975 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3976 				     struct bpf_verifier_state *st)
3977 {
3978 	struct bpf_func_state *func;
3979 	struct bpf_reg_state *reg;
3980 	int i, j;
3981 
3982 	if (env->log.level & BPF_LOG_LEVEL2) {
3983 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3984 			st->curframe);
3985 	}
3986 
3987 	/* big hammer: mark all scalars precise in this path.
3988 	 * pop_stack may still get !precise scalars.
3989 	 * We also skip current state and go straight to first parent state,
3990 	 * because precision markings in current non-checkpointed state are
3991 	 * not needed. See why in the comment in __mark_chain_precision below.
3992 	 */
3993 	for (st = st->parent; st; st = st->parent) {
3994 		for (i = 0; i <= st->curframe; i++) {
3995 			func = st->frame[i];
3996 			for (j = 0; j < BPF_REG_FP; j++) {
3997 				reg = &func->regs[j];
3998 				if (reg->type != SCALAR_VALUE || reg->precise)
3999 					continue;
4000 				reg->precise = true;
4001 				if (env->log.level & BPF_LOG_LEVEL2) {
4002 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4003 						i, j);
4004 				}
4005 			}
4006 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4007 				if (!is_spilled_reg(&func->stack[j]))
4008 					continue;
4009 				reg = &func->stack[j].spilled_ptr;
4010 				if (reg->type != SCALAR_VALUE || reg->precise)
4011 					continue;
4012 				reg->precise = true;
4013 				if (env->log.level & BPF_LOG_LEVEL2) {
4014 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4015 						i, -(j + 1) * 8);
4016 				}
4017 			}
4018 		}
4019 	}
4020 }
4021 
4022 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4023 {
4024 	struct bpf_func_state *func;
4025 	struct bpf_reg_state *reg;
4026 	int i, j;
4027 
4028 	for (i = 0; i <= st->curframe; i++) {
4029 		func = st->frame[i];
4030 		for (j = 0; j < BPF_REG_FP; j++) {
4031 			reg = &func->regs[j];
4032 			if (reg->type != SCALAR_VALUE)
4033 				continue;
4034 			reg->precise = false;
4035 		}
4036 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4037 			if (!is_spilled_reg(&func->stack[j]))
4038 				continue;
4039 			reg = &func->stack[j].spilled_ptr;
4040 			if (reg->type != SCALAR_VALUE)
4041 				continue;
4042 			reg->precise = false;
4043 		}
4044 	}
4045 }
4046 
4047 static bool idset_contains(struct bpf_idset *s, u32 id)
4048 {
4049 	u32 i;
4050 
4051 	for (i = 0; i < s->count; ++i)
4052 		if (s->ids[i] == id)
4053 			return true;
4054 
4055 	return false;
4056 }
4057 
4058 static int idset_push(struct bpf_idset *s, u32 id)
4059 {
4060 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4061 		return -EFAULT;
4062 	s->ids[s->count++] = id;
4063 	return 0;
4064 }
4065 
4066 static void idset_reset(struct bpf_idset *s)
4067 {
4068 	s->count = 0;
4069 }
4070 
4071 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4072  * Mark all registers with these IDs as precise.
4073  */
4074 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4075 {
4076 	struct bpf_idset *precise_ids = &env->idset_scratch;
4077 	struct backtrack_state *bt = &env->bt;
4078 	struct bpf_func_state *func;
4079 	struct bpf_reg_state *reg;
4080 	DECLARE_BITMAP(mask, 64);
4081 	int i, fr;
4082 
4083 	idset_reset(precise_ids);
4084 
4085 	for (fr = bt->frame; fr >= 0; fr--) {
4086 		func = st->frame[fr];
4087 
4088 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4089 		for_each_set_bit(i, mask, 32) {
4090 			reg = &func->regs[i];
4091 			if (!reg->id || reg->type != SCALAR_VALUE)
4092 				continue;
4093 			if (idset_push(precise_ids, reg->id))
4094 				return -EFAULT;
4095 		}
4096 
4097 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4098 		for_each_set_bit(i, mask, 64) {
4099 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4100 				break;
4101 			if (!is_spilled_scalar_reg(&func->stack[i]))
4102 				continue;
4103 			reg = &func->stack[i].spilled_ptr;
4104 			if (!reg->id)
4105 				continue;
4106 			if (idset_push(precise_ids, reg->id))
4107 				return -EFAULT;
4108 		}
4109 	}
4110 
4111 	for (fr = 0; fr <= st->curframe; ++fr) {
4112 		func = st->frame[fr];
4113 
4114 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4115 			reg = &func->regs[i];
4116 			if (!reg->id)
4117 				continue;
4118 			if (!idset_contains(precise_ids, reg->id))
4119 				continue;
4120 			bt_set_frame_reg(bt, fr, i);
4121 		}
4122 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4123 			if (!is_spilled_scalar_reg(&func->stack[i]))
4124 				continue;
4125 			reg = &func->stack[i].spilled_ptr;
4126 			if (!reg->id)
4127 				continue;
4128 			if (!idset_contains(precise_ids, reg->id))
4129 				continue;
4130 			bt_set_frame_slot(bt, fr, i);
4131 		}
4132 	}
4133 
4134 	return 0;
4135 }
4136 
4137 /*
4138  * __mark_chain_precision() backtracks BPF program instruction sequence and
4139  * chain of verifier states making sure that register *regno* (if regno >= 0)
4140  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4141  * SCALARS, as well as any other registers and slots that contribute to
4142  * a tracked state of given registers/stack slots, depending on specific BPF
4143  * assembly instructions (see backtrack_insns() for exact instruction handling
4144  * logic). This backtracking relies on recorded jmp_history and is able to
4145  * traverse entire chain of parent states. This process ends only when all the
4146  * necessary registers/slots and their transitive dependencies are marked as
4147  * precise.
4148  *
4149  * One important and subtle aspect is that precise marks *do not matter* in
4150  * the currently verified state (current state). It is important to understand
4151  * why this is the case.
4152  *
4153  * First, note that current state is the state that is not yet "checkpointed",
4154  * i.e., it is not yet put into env->explored_states, and it has no children
4155  * states as well. It's ephemeral, and can end up either a) being discarded if
4156  * compatible explored state is found at some point or BPF_EXIT instruction is
4157  * reached or b) checkpointed and put into env->explored_states, branching out
4158  * into one or more children states.
4159  *
4160  * In the former case, precise markings in current state are completely
4161  * ignored by state comparison code (see regsafe() for details). Only
4162  * checkpointed ("old") state precise markings are important, and if old
4163  * state's register/slot is precise, regsafe() assumes current state's
4164  * register/slot as precise and checks value ranges exactly and precisely. If
4165  * states turn out to be compatible, current state's necessary precise
4166  * markings and any required parent states' precise markings are enforced
4167  * after the fact with propagate_precision() logic, after the fact. But it's
4168  * important to realize that in this case, even after marking current state
4169  * registers/slots as precise, we immediately discard current state. So what
4170  * actually matters is any of the precise markings propagated into current
4171  * state's parent states, which are always checkpointed (due to b) case above).
4172  * As such, for scenario a) it doesn't matter if current state has precise
4173  * markings set or not.
4174  *
4175  * Now, for the scenario b), checkpointing and forking into child(ren)
4176  * state(s). Note that before current state gets to checkpointing step, any
4177  * processed instruction always assumes precise SCALAR register/slot
4178  * knowledge: if precise value or range is useful to prune jump branch, BPF
4179  * verifier takes this opportunity enthusiastically. Similarly, when
4180  * register's value is used to calculate offset or memory address, exact
4181  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4182  * what we mentioned above about state comparison ignoring precise markings
4183  * during state comparison, BPF verifier ignores and also assumes precise
4184  * markings *at will* during instruction verification process. But as verifier
4185  * assumes precision, it also propagates any precision dependencies across
4186  * parent states, which are not yet finalized, so can be further restricted
4187  * based on new knowledge gained from restrictions enforced by their children
4188  * states. This is so that once those parent states are finalized, i.e., when
4189  * they have no more active children state, state comparison logic in
4190  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4191  * required for correctness.
4192  *
4193  * To build a bit more intuition, note also that once a state is checkpointed,
4194  * the path we took to get to that state is not important. This is crucial
4195  * property for state pruning. When state is checkpointed and finalized at
4196  * some instruction index, it can be correctly and safely used to "short
4197  * circuit" any *compatible* state that reaches exactly the same instruction
4198  * index. I.e., if we jumped to that instruction from a completely different
4199  * code path than original finalized state was derived from, it doesn't
4200  * matter, current state can be discarded because from that instruction
4201  * forward having a compatible state will ensure we will safely reach the
4202  * exit. States describe preconditions for further exploration, but completely
4203  * forget the history of how we got here.
4204  *
4205  * This also means that even if we needed precise SCALAR range to get to
4206  * finalized state, but from that point forward *that same* SCALAR register is
4207  * never used in a precise context (i.e., it's precise value is not needed for
4208  * correctness), it's correct and safe to mark such register as "imprecise"
4209  * (i.e., precise marking set to false). This is what we rely on when we do
4210  * not set precise marking in current state. If no child state requires
4211  * precision for any given SCALAR register, it's safe to dictate that it can
4212  * be imprecise. If any child state does require this register to be precise,
4213  * we'll mark it precise later retroactively during precise markings
4214  * propagation from child state to parent states.
4215  *
4216  * Skipping precise marking setting in current state is a mild version of
4217  * relying on the above observation. But we can utilize this property even
4218  * more aggressively by proactively forgetting any precise marking in the
4219  * current state (which we inherited from the parent state), right before we
4220  * checkpoint it and branch off into new child state. This is done by
4221  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4222  * finalized states which help in short circuiting more future states.
4223  */
4224 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4225 {
4226 	struct backtrack_state *bt = &env->bt;
4227 	struct bpf_verifier_state *st = env->cur_state;
4228 	int first_idx = st->first_insn_idx;
4229 	int last_idx = env->insn_idx;
4230 	int subseq_idx = -1;
4231 	struct bpf_func_state *func;
4232 	struct bpf_reg_state *reg;
4233 	bool skip_first = true;
4234 	int i, fr, err;
4235 
4236 	if (!env->bpf_capable)
4237 		return 0;
4238 
4239 	/* set frame number from which we are starting to backtrack */
4240 	bt_init(bt, env->cur_state->curframe);
4241 
4242 	/* Do sanity checks against current state of register and/or stack
4243 	 * slot, but don't set precise flag in current state, as precision
4244 	 * tracking in the current state is unnecessary.
4245 	 */
4246 	func = st->frame[bt->frame];
4247 	if (regno >= 0) {
4248 		reg = &func->regs[regno];
4249 		if (reg->type != SCALAR_VALUE) {
4250 			WARN_ONCE(1, "backtracing misuse");
4251 			return -EFAULT;
4252 		}
4253 		bt_set_reg(bt, regno);
4254 	}
4255 
4256 	if (bt_empty(bt))
4257 		return 0;
4258 
4259 	for (;;) {
4260 		DECLARE_BITMAP(mask, 64);
4261 		u32 history = st->jmp_history_cnt;
4262 
4263 		if (env->log.level & BPF_LOG_LEVEL2) {
4264 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4265 				bt->frame, last_idx, first_idx, subseq_idx);
4266 		}
4267 
4268 		/* If some register with scalar ID is marked as precise,
4269 		 * make sure that all registers sharing this ID are also precise.
4270 		 * This is needed to estimate effect of find_equal_scalars().
4271 		 * Do this at the last instruction of each state,
4272 		 * bpf_reg_state::id fields are valid for these instructions.
4273 		 *
4274 		 * Allows to track precision in situation like below:
4275 		 *
4276 		 *     r2 = unknown value
4277 		 *     ...
4278 		 *   --- state #0 ---
4279 		 *     ...
4280 		 *     r1 = r2                 // r1 and r2 now share the same ID
4281 		 *     ...
4282 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4283 		 *     ...
4284 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4285 		 *     ...
4286 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4287 		 *     r3 = r10
4288 		 *     r3 += r1                // need to mark both r1 and r2
4289 		 */
4290 		if (mark_precise_scalar_ids(env, st))
4291 			return -EFAULT;
4292 
4293 		if (last_idx < 0) {
4294 			/* we are at the entry into subprog, which
4295 			 * is expected for global funcs, but only if
4296 			 * requested precise registers are R1-R5
4297 			 * (which are global func's input arguments)
4298 			 */
4299 			if (st->curframe == 0 &&
4300 			    st->frame[0]->subprogno > 0 &&
4301 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4302 			    bt_stack_mask(bt) == 0 &&
4303 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4304 				bitmap_from_u64(mask, bt_reg_mask(bt));
4305 				for_each_set_bit(i, mask, 32) {
4306 					reg = &st->frame[0]->regs[i];
4307 					bt_clear_reg(bt, i);
4308 					if (reg->type == SCALAR_VALUE)
4309 						reg->precise = true;
4310 				}
4311 				return 0;
4312 			}
4313 
4314 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4315 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4316 			WARN_ONCE(1, "verifier backtracking bug");
4317 			return -EFAULT;
4318 		}
4319 
4320 		for (i = last_idx;;) {
4321 			if (skip_first) {
4322 				err = 0;
4323 				skip_first = false;
4324 			} else {
4325 				err = backtrack_insn(env, i, subseq_idx, bt);
4326 			}
4327 			if (err == -ENOTSUPP) {
4328 				mark_all_scalars_precise(env, env->cur_state);
4329 				bt_reset(bt);
4330 				return 0;
4331 			} else if (err) {
4332 				return err;
4333 			}
4334 			if (bt_empty(bt))
4335 				/* Found assignment(s) into tracked register in this state.
4336 				 * Since this state is already marked, just return.
4337 				 * Nothing to be tracked further in the parent state.
4338 				 */
4339 				return 0;
4340 			subseq_idx = i;
4341 			i = get_prev_insn_idx(st, i, &history);
4342 			if (i == -ENOENT)
4343 				break;
4344 			if (i >= env->prog->len) {
4345 				/* This can happen if backtracking reached insn 0
4346 				 * and there are still reg_mask or stack_mask
4347 				 * to backtrack.
4348 				 * It means the backtracking missed the spot where
4349 				 * particular register was initialized with a constant.
4350 				 */
4351 				verbose(env, "BUG backtracking idx %d\n", i);
4352 				WARN_ONCE(1, "verifier backtracking bug");
4353 				return -EFAULT;
4354 			}
4355 		}
4356 		st = st->parent;
4357 		if (!st)
4358 			break;
4359 
4360 		for (fr = bt->frame; fr >= 0; fr--) {
4361 			func = st->frame[fr];
4362 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4363 			for_each_set_bit(i, mask, 32) {
4364 				reg = &func->regs[i];
4365 				if (reg->type != SCALAR_VALUE) {
4366 					bt_clear_frame_reg(bt, fr, i);
4367 					continue;
4368 				}
4369 				if (reg->precise)
4370 					bt_clear_frame_reg(bt, fr, i);
4371 				else
4372 					reg->precise = true;
4373 			}
4374 
4375 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4376 			for_each_set_bit(i, mask, 64) {
4377 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4378 					/* the sequence of instructions:
4379 					 * 2: (bf) r3 = r10
4380 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4381 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4382 					 * doesn't contain jmps. It's backtracked
4383 					 * as a single block.
4384 					 * During backtracking insn 3 is not recognized as
4385 					 * stack access, so at the end of backtracking
4386 					 * stack slot fp-8 is still marked in stack_mask.
4387 					 * However the parent state may not have accessed
4388 					 * fp-8 and it's "unallocated" stack space.
4389 					 * In such case fallback to conservative.
4390 					 */
4391 					mark_all_scalars_precise(env, env->cur_state);
4392 					bt_reset(bt);
4393 					return 0;
4394 				}
4395 
4396 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4397 					bt_clear_frame_slot(bt, fr, i);
4398 					continue;
4399 				}
4400 				reg = &func->stack[i].spilled_ptr;
4401 				if (reg->precise)
4402 					bt_clear_frame_slot(bt, fr, i);
4403 				else
4404 					reg->precise = true;
4405 			}
4406 			if (env->log.level & BPF_LOG_LEVEL2) {
4407 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4408 					     bt_frame_reg_mask(bt, fr));
4409 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4410 					fr, env->tmp_str_buf);
4411 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4412 					       bt_frame_stack_mask(bt, fr));
4413 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4414 				print_verifier_state(env, func, true);
4415 			}
4416 		}
4417 
4418 		if (bt_empty(bt))
4419 			return 0;
4420 
4421 		subseq_idx = first_idx;
4422 		last_idx = st->last_insn_idx;
4423 		first_idx = st->first_insn_idx;
4424 	}
4425 
4426 	/* if we still have requested precise regs or slots, we missed
4427 	 * something (e.g., stack access through non-r10 register), so
4428 	 * fallback to marking all precise
4429 	 */
4430 	if (!bt_empty(bt)) {
4431 		mark_all_scalars_precise(env, env->cur_state);
4432 		bt_reset(bt);
4433 	}
4434 
4435 	return 0;
4436 }
4437 
4438 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4439 {
4440 	return __mark_chain_precision(env, regno);
4441 }
4442 
4443 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4444  * desired reg and stack masks across all relevant frames
4445  */
4446 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4447 {
4448 	return __mark_chain_precision(env, -1);
4449 }
4450 
4451 static bool is_spillable_regtype(enum bpf_reg_type type)
4452 {
4453 	switch (base_type(type)) {
4454 	case PTR_TO_MAP_VALUE:
4455 	case PTR_TO_STACK:
4456 	case PTR_TO_CTX:
4457 	case PTR_TO_PACKET:
4458 	case PTR_TO_PACKET_META:
4459 	case PTR_TO_PACKET_END:
4460 	case PTR_TO_FLOW_KEYS:
4461 	case CONST_PTR_TO_MAP:
4462 	case PTR_TO_SOCKET:
4463 	case PTR_TO_SOCK_COMMON:
4464 	case PTR_TO_TCP_SOCK:
4465 	case PTR_TO_XDP_SOCK:
4466 	case PTR_TO_BTF_ID:
4467 	case PTR_TO_BUF:
4468 	case PTR_TO_MEM:
4469 	case PTR_TO_FUNC:
4470 	case PTR_TO_MAP_KEY:
4471 		return true;
4472 	default:
4473 		return false;
4474 	}
4475 }
4476 
4477 /* Does this register contain a constant zero? */
4478 static bool register_is_null(struct bpf_reg_state *reg)
4479 {
4480 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4481 }
4482 
4483 static bool register_is_const(struct bpf_reg_state *reg)
4484 {
4485 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4486 }
4487 
4488 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4489 {
4490 	return tnum_is_unknown(reg->var_off) &&
4491 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4492 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4493 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4494 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4495 }
4496 
4497 static bool register_is_bounded(struct bpf_reg_state *reg)
4498 {
4499 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4500 }
4501 
4502 static bool __is_pointer_value(bool allow_ptr_leaks,
4503 			       const struct bpf_reg_state *reg)
4504 {
4505 	if (allow_ptr_leaks)
4506 		return false;
4507 
4508 	return reg->type != SCALAR_VALUE;
4509 }
4510 
4511 /* Copy src state preserving dst->parent and dst->live fields */
4512 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4513 {
4514 	struct bpf_reg_state *parent = dst->parent;
4515 	enum bpf_reg_liveness live = dst->live;
4516 
4517 	*dst = *src;
4518 	dst->parent = parent;
4519 	dst->live = live;
4520 }
4521 
4522 static void save_register_state(struct bpf_func_state *state,
4523 				int spi, struct bpf_reg_state *reg,
4524 				int size)
4525 {
4526 	int i;
4527 
4528 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4529 	if (size == BPF_REG_SIZE)
4530 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4531 
4532 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4533 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4534 
4535 	/* size < 8 bytes spill */
4536 	for (; i; i--)
4537 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4538 }
4539 
4540 static bool is_bpf_st_mem(struct bpf_insn *insn)
4541 {
4542 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4543 }
4544 
4545 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4546  * stack boundary and alignment are checked in check_mem_access()
4547  */
4548 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4549 				       /* stack frame we're writing to */
4550 				       struct bpf_func_state *state,
4551 				       int off, int size, int value_regno,
4552 				       int insn_idx)
4553 {
4554 	struct bpf_func_state *cur; /* state of the current function */
4555 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4556 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4557 	struct bpf_reg_state *reg = NULL;
4558 	u32 dst_reg = insn->dst_reg;
4559 
4560 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4561 	 * so it's aligned access and [off, off + size) are within stack limits
4562 	 */
4563 	if (!env->allow_ptr_leaks &&
4564 	    is_spilled_reg(&state->stack[spi]) &&
4565 	    size != BPF_REG_SIZE) {
4566 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4567 		return -EACCES;
4568 	}
4569 
4570 	cur = env->cur_state->frame[env->cur_state->curframe];
4571 	if (value_regno >= 0)
4572 		reg = &cur->regs[value_regno];
4573 	if (!env->bypass_spec_v4) {
4574 		bool sanitize = reg && is_spillable_regtype(reg->type);
4575 
4576 		for (i = 0; i < size; i++) {
4577 			u8 type = state->stack[spi].slot_type[i];
4578 
4579 			if (type != STACK_MISC && type != STACK_ZERO) {
4580 				sanitize = true;
4581 				break;
4582 			}
4583 		}
4584 
4585 		if (sanitize)
4586 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4587 	}
4588 
4589 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4590 	if (err)
4591 		return err;
4592 
4593 	mark_stack_slot_scratched(env, spi);
4594 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4595 	    !register_is_null(reg) && env->bpf_capable) {
4596 		if (dst_reg != BPF_REG_FP) {
4597 			/* The backtracking logic can only recognize explicit
4598 			 * stack slot address like [fp - 8]. Other spill of
4599 			 * scalar via different register has to be conservative.
4600 			 * Backtrack from here and mark all registers as precise
4601 			 * that contributed into 'reg' being a constant.
4602 			 */
4603 			err = mark_chain_precision(env, value_regno);
4604 			if (err)
4605 				return err;
4606 		}
4607 		save_register_state(state, spi, reg, size);
4608 		/* Break the relation on a narrowing spill. */
4609 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4610 			state->stack[spi].spilled_ptr.id = 0;
4611 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4612 		   insn->imm != 0 && env->bpf_capable) {
4613 		struct bpf_reg_state fake_reg = {};
4614 
4615 		__mark_reg_known(&fake_reg, insn->imm);
4616 		fake_reg.type = SCALAR_VALUE;
4617 		save_register_state(state, spi, &fake_reg, size);
4618 	} else if (reg && is_spillable_regtype(reg->type)) {
4619 		/* register containing pointer is being spilled into stack */
4620 		if (size != BPF_REG_SIZE) {
4621 			verbose_linfo(env, insn_idx, "; ");
4622 			verbose(env, "invalid size of register spill\n");
4623 			return -EACCES;
4624 		}
4625 		if (state != cur && reg->type == PTR_TO_STACK) {
4626 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4627 			return -EINVAL;
4628 		}
4629 		save_register_state(state, spi, reg, size);
4630 	} else {
4631 		u8 type = STACK_MISC;
4632 
4633 		/* regular write of data into stack destroys any spilled ptr */
4634 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4635 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4636 		if (is_stack_slot_special(&state->stack[spi]))
4637 			for (i = 0; i < BPF_REG_SIZE; i++)
4638 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4639 
4640 		/* only mark the slot as written if all 8 bytes were written
4641 		 * otherwise read propagation may incorrectly stop too soon
4642 		 * when stack slots are partially written.
4643 		 * This heuristic means that read propagation will be
4644 		 * conservative, since it will add reg_live_read marks
4645 		 * to stack slots all the way to first state when programs
4646 		 * writes+reads less than 8 bytes
4647 		 */
4648 		if (size == BPF_REG_SIZE)
4649 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4650 
4651 		/* when we zero initialize stack slots mark them as such */
4652 		if ((reg && register_is_null(reg)) ||
4653 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4654 			/* backtracking doesn't work for STACK_ZERO yet. */
4655 			err = mark_chain_precision(env, value_regno);
4656 			if (err)
4657 				return err;
4658 			type = STACK_ZERO;
4659 		}
4660 
4661 		/* Mark slots affected by this stack write. */
4662 		for (i = 0; i < size; i++)
4663 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4664 				type;
4665 	}
4666 	return 0;
4667 }
4668 
4669 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4670  * known to contain a variable offset.
4671  * This function checks whether the write is permitted and conservatively
4672  * tracks the effects of the write, considering that each stack slot in the
4673  * dynamic range is potentially written to.
4674  *
4675  * 'off' includes 'regno->off'.
4676  * 'value_regno' can be -1, meaning that an unknown value is being written to
4677  * the stack.
4678  *
4679  * Spilled pointers in range are not marked as written because we don't know
4680  * what's going to be actually written. This means that read propagation for
4681  * future reads cannot be terminated by this write.
4682  *
4683  * For privileged programs, uninitialized stack slots are considered
4684  * initialized by this write (even though we don't know exactly what offsets
4685  * are going to be written to). The idea is that we don't want the verifier to
4686  * reject future reads that access slots written to through variable offsets.
4687  */
4688 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4689 				     /* func where register points to */
4690 				     struct bpf_func_state *state,
4691 				     int ptr_regno, int off, int size,
4692 				     int value_regno, int insn_idx)
4693 {
4694 	struct bpf_func_state *cur; /* state of the current function */
4695 	int min_off, max_off;
4696 	int i, err;
4697 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4698 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4699 	bool writing_zero = false;
4700 	/* set if the fact that we're writing a zero is used to let any
4701 	 * stack slots remain STACK_ZERO
4702 	 */
4703 	bool zero_used = false;
4704 
4705 	cur = env->cur_state->frame[env->cur_state->curframe];
4706 	ptr_reg = &cur->regs[ptr_regno];
4707 	min_off = ptr_reg->smin_value + off;
4708 	max_off = ptr_reg->smax_value + off + size;
4709 	if (value_regno >= 0)
4710 		value_reg = &cur->regs[value_regno];
4711 	if ((value_reg && register_is_null(value_reg)) ||
4712 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4713 		writing_zero = true;
4714 
4715 	for (i = min_off; i < max_off; i++) {
4716 		int spi;
4717 
4718 		spi = __get_spi(i);
4719 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4720 		if (err)
4721 			return err;
4722 	}
4723 
4724 	/* Variable offset writes destroy any spilled pointers in range. */
4725 	for (i = min_off; i < max_off; i++) {
4726 		u8 new_type, *stype;
4727 		int slot, spi;
4728 
4729 		slot = -i - 1;
4730 		spi = slot / BPF_REG_SIZE;
4731 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4732 		mark_stack_slot_scratched(env, spi);
4733 
4734 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4735 			/* Reject the write if range we may write to has not
4736 			 * been initialized beforehand. If we didn't reject
4737 			 * here, the ptr status would be erased below (even
4738 			 * though not all slots are actually overwritten),
4739 			 * possibly opening the door to leaks.
4740 			 *
4741 			 * We do however catch STACK_INVALID case below, and
4742 			 * only allow reading possibly uninitialized memory
4743 			 * later for CAP_PERFMON, as the write may not happen to
4744 			 * that slot.
4745 			 */
4746 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4747 				insn_idx, i);
4748 			return -EINVAL;
4749 		}
4750 
4751 		/* Erase all spilled pointers. */
4752 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4753 
4754 		/* Update the slot type. */
4755 		new_type = STACK_MISC;
4756 		if (writing_zero && *stype == STACK_ZERO) {
4757 			new_type = STACK_ZERO;
4758 			zero_used = true;
4759 		}
4760 		/* If the slot is STACK_INVALID, we check whether it's OK to
4761 		 * pretend that it will be initialized by this write. The slot
4762 		 * might not actually be written to, and so if we mark it as
4763 		 * initialized future reads might leak uninitialized memory.
4764 		 * For privileged programs, we will accept such reads to slots
4765 		 * that may or may not be written because, if we're reject
4766 		 * them, the error would be too confusing.
4767 		 */
4768 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4769 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4770 					insn_idx, i);
4771 			return -EINVAL;
4772 		}
4773 		*stype = new_type;
4774 	}
4775 	if (zero_used) {
4776 		/* backtracking doesn't work for STACK_ZERO yet. */
4777 		err = mark_chain_precision(env, value_regno);
4778 		if (err)
4779 			return err;
4780 	}
4781 	return 0;
4782 }
4783 
4784 /* When register 'dst_regno' is assigned some values from stack[min_off,
4785  * max_off), we set the register's type according to the types of the
4786  * respective stack slots. If all the stack values are known to be zeros, then
4787  * so is the destination reg. Otherwise, the register is considered to be
4788  * SCALAR. This function does not deal with register filling; the caller must
4789  * ensure that all spilled registers in the stack range have been marked as
4790  * read.
4791  */
4792 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4793 				/* func where src register points to */
4794 				struct bpf_func_state *ptr_state,
4795 				int min_off, int max_off, int dst_regno)
4796 {
4797 	struct bpf_verifier_state *vstate = env->cur_state;
4798 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4799 	int i, slot, spi;
4800 	u8 *stype;
4801 	int zeros = 0;
4802 
4803 	for (i = min_off; i < max_off; i++) {
4804 		slot = -i - 1;
4805 		spi = slot / BPF_REG_SIZE;
4806 		mark_stack_slot_scratched(env, spi);
4807 		stype = ptr_state->stack[spi].slot_type;
4808 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4809 			break;
4810 		zeros++;
4811 	}
4812 	if (zeros == max_off - min_off) {
4813 		/* any access_size read into register is zero extended,
4814 		 * so the whole register == const_zero
4815 		 */
4816 		__mark_reg_const_zero(&state->regs[dst_regno]);
4817 		/* backtracking doesn't support STACK_ZERO yet,
4818 		 * so mark it precise here, so that later
4819 		 * backtracking can stop here.
4820 		 * Backtracking may not need this if this register
4821 		 * doesn't participate in pointer adjustment.
4822 		 * Forward propagation of precise flag is not
4823 		 * necessary either. This mark is only to stop
4824 		 * backtracking. Any register that contributed
4825 		 * to const 0 was marked precise before spill.
4826 		 */
4827 		state->regs[dst_regno].precise = true;
4828 	} else {
4829 		/* have read misc data from the stack */
4830 		mark_reg_unknown(env, state->regs, dst_regno);
4831 	}
4832 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4833 }
4834 
4835 /* Read the stack at 'off' and put the results into the register indicated by
4836  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4837  * spilled reg.
4838  *
4839  * 'dst_regno' can be -1, meaning that the read value is not going to a
4840  * register.
4841  *
4842  * The access is assumed to be within the current stack bounds.
4843  */
4844 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4845 				      /* func where src register points to */
4846 				      struct bpf_func_state *reg_state,
4847 				      int off, int size, int dst_regno)
4848 {
4849 	struct bpf_verifier_state *vstate = env->cur_state;
4850 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4851 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4852 	struct bpf_reg_state *reg;
4853 	u8 *stype, type;
4854 
4855 	stype = reg_state->stack[spi].slot_type;
4856 	reg = &reg_state->stack[spi].spilled_ptr;
4857 
4858 	mark_stack_slot_scratched(env, spi);
4859 
4860 	if (is_spilled_reg(&reg_state->stack[spi])) {
4861 		u8 spill_size = 1;
4862 
4863 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4864 			spill_size++;
4865 
4866 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4867 			if (reg->type != SCALAR_VALUE) {
4868 				verbose_linfo(env, env->insn_idx, "; ");
4869 				verbose(env, "invalid size of register fill\n");
4870 				return -EACCES;
4871 			}
4872 
4873 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4874 			if (dst_regno < 0)
4875 				return 0;
4876 
4877 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4878 				/* The earlier check_reg_arg() has decided the
4879 				 * subreg_def for this insn.  Save it first.
4880 				 */
4881 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4882 
4883 				copy_register_state(&state->regs[dst_regno], reg);
4884 				state->regs[dst_regno].subreg_def = subreg_def;
4885 			} else {
4886 				for (i = 0; i < size; i++) {
4887 					type = stype[(slot - i) % BPF_REG_SIZE];
4888 					if (type == STACK_SPILL)
4889 						continue;
4890 					if (type == STACK_MISC)
4891 						continue;
4892 					if (type == STACK_INVALID && env->allow_uninit_stack)
4893 						continue;
4894 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4895 						off, i, size);
4896 					return -EACCES;
4897 				}
4898 				mark_reg_unknown(env, state->regs, dst_regno);
4899 			}
4900 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4901 			return 0;
4902 		}
4903 
4904 		if (dst_regno >= 0) {
4905 			/* restore register state from stack */
4906 			copy_register_state(&state->regs[dst_regno], reg);
4907 			/* mark reg as written since spilled pointer state likely
4908 			 * has its liveness marks cleared by is_state_visited()
4909 			 * which resets stack/reg liveness for state transitions
4910 			 */
4911 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4912 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4913 			/* If dst_regno==-1, the caller is asking us whether
4914 			 * it is acceptable to use this value as a SCALAR_VALUE
4915 			 * (e.g. for XADD).
4916 			 * We must not allow unprivileged callers to do that
4917 			 * with spilled pointers.
4918 			 */
4919 			verbose(env, "leaking pointer from stack off %d\n",
4920 				off);
4921 			return -EACCES;
4922 		}
4923 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4924 	} else {
4925 		for (i = 0; i < size; i++) {
4926 			type = stype[(slot - i) % BPF_REG_SIZE];
4927 			if (type == STACK_MISC)
4928 				continue;
4929 			if (type == STACK_ZERO)
4930 				continue;
4931 			if (type == STACK_INVALID && env->allow_uninit_stack)
4932 				continue;
4933 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4934 				off, i, size);
4935 			return -EACCES;
4936 		}
4937 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4938 		if (dst_regno >= 0)
4939 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4940 	}
4941 	return 0;
4942 }
4943 
4944 enum bpf_access_src {
4945 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4946 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4947 };
4948 
4949 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4950 					 int regno, int off, int access_size,
4951 					 bool zero_size_allowed,
4952 					 enum bpf_access_src type,
4953 					 struct bpf_call_arg_meta *meta);
4954 
4955 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4956 {
4957 	return cur_regs(env) + regno;
4958 }
4959 
4960 /* Read the stack at 'ptr_regno + off' and put the result into the register
4961  * 'dst_regno'.
4962  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4963  * but not its variable offset.
4964  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4965  *
4966  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4967  * filling registers (i.e. reads of spilled register cannot be detected when
4968  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4969  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4970  * offset; for a fixed offset check_stack_read_fixed_off should be used
4971  * instead.
4972  */
4973 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4974 				    int ptr_regno, int off, int size, int dst_regno)
4975 {
4976 	/* The state of the source register. */
4977 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4978 	struct bpf_func_state *ptr_state = func(env, reg);
4979 	int err;
4980 	int min_off, max_off;
4981 
4982 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4983 	 */
4984 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4985 					    false, ACCESS_DIRECT, NULL);
4986 	if (err)
4987 		return err;
4988 
4989 	min_off = reg->smin_value + off;
4990 	max_off = reg->smax_value + off;
4991 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4992 	return 0;
4993 }
4994 
4995 /* check_stack_read dispatches to check_stack_read_fixed_off or
4996  * check_stack_read_var_off.
4997  *
4998  * The caller must ensure that the offset falls within the allocated stack
4999  * bounds.
5000  *
5001  * 'dst_regno' is a register which will receive the value from the stack. It
5002  * can be -1, meaning that the read value is not going to a register.
5003  */
5004 static int check_stack_read(struct bpf_verifier_env *env,
5005 			    int ptr_regno, int off, int size,
5006 			    int dst_regno)
5007 {
5008 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5009 	struct bpf_func_state *state = func(env, reg);
5010 	int err;
5011 	/* Some accesses are only permitted with a static offset. */
5012 	bool var_off = !tnum_is_const(reg->var_off);
5013 
5014 	/* The offset is required to be static when reads don't go to a
5015 	 * register, in order to not leak pointers (see
5016 	 * check_stack_read_fixed_off).
5017 	 */
5018 	if (dst_regno < 0 && var_off) {
5019 		char tn_buf[48];
5020 
5021 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5022 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5023 			tn_buf, off, size);
5024 		return -EACCES;
5025 	}
5026 	/* Variable offset is prohibited for unprivileged mode for simplicity
5027 	 * since it requires corresponding support in Spectre masking for stack
5028 	 * ALU. See also retrieve_ptr_limit(). The check in
5029 	 * check_stack_access_for_ptr_arithmetic() called by
5030 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5031 	 * with variable offsets, therefore no check is required here. Further,
5032 	 * just checking it here would be insufficient as speculative stack
5033 	 * writes could still lead to unsafe speculative behaviour.
5034 	 */
5035 	if (!var_off) {
5036 		off += reg->var_off.value;
5037 		err = check_stack_read_fixed_off(env, state, off, size,
5038 						 dst_regno);
5039 	} else {
5040 		/* Variable offset stack reads need more conservative handling
5041 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5042 		 * branch.
5043 		 */
5044 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5045 					       dst_regno);
5046 	}
5047 	return err;
5048 }
5049 
5050 
5051 /* check_stack_write dispatches to check_stack_write_fixed_off or
5052  * check_stack_write_var_off.
5053  *
5054  * 'ptr_regno' is the register used as a pointer into the stack.
5055  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5056  * 'value_regno' is the register whose value we're writing to the stack. It can
5057  * be -1, meaning that we're not writing from a register.
5058  *
5059  * The caller must ensure that the offset falls within the maximum stack size.
5060  */
5061 static int check_stack_write(struct bpf_verifier_env *env,
5062 			     int ptr_regno, int off, int size,
5063 			     int value_regno, int insn_idx)
5064 {
5065 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5066 	struct bpf_func_state *state = func(env, reg);
5067 	int err;
5068 
5069 	if (tnum_is_const(reg->var_off)) {
5070 		off += reg->var_off.value;
5071 		err = check_stack_write_fixed_off(env, state, off, size,
5072 						  value_regno, insn_idx);
5073 	} else {
5074 		/* Variable offset stack reads need more conservative handling
5075 		 * than fixed offset ones.
5076 		 */
5077 		err = check_stack_write_var_off(env, state,
5078 						ptr_regno, off, size,
5079 						value_regno, insn_idx);
5080 	}
5081 	return err;
5082 }
5083 
5084 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5085 				 int off, int size, enum bpf_access_type type)
5086 {
5087 	struct bpf_reg_state *regs = cur_regs(env);
5088 	struct bpf_map *map = regs[regno].map_ptr;
5089 	u32 cap = bpf_map_flags_to_cap(map);
5090 
5091 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5092 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5093 			map->value_size, off, size);
5094 		return -EACCES;
5095 	}
5096 
5097 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5098 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5099 			map->value_size, off, size);
5100 		return -EACCES;
5101 	}
5102 
5103 	return 0;
5104 }
5105 
5106 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5107 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5108 			      int off, int size, u32 mem_size,
5109 			      bool zero_size_allowed)
5110 {
5111 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5112 	struct bpf_reg_state *reg;
5113 
5114 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5115 		return 0;
5116 
5117 	reg = &cur_regs(env)[regno];
5118 	switch (reg->type) {
5119 	case PTR_TO_MAP_KEY:
5120 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5121 			mem_size, off, size);
5122 		break;
5123 	case PTR_TO_MAP_VALUE:
5124 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5125 			mem_size, off, size);
5126 		break;
5127 	case PTR_TO_PACKET:
5128 	case PTR_TO_PACKET_META:
5129 	case PTR_TO_PACKET_END:
5130 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5131 			off, size, regno, reg->id, off, mem_size);
5132 		break;
5133 	case PTR_TO_MEM:
5134 	default:
5135 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5136 			mem_size, off, size);
5137 	}
5138 
5139 	return -EACCES;
5140 }
5141 
5142 /* check read/write into a memory region with possible variable offset */
5143 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5144 				   int off, int size, u32 mem_size,
5145 				   bool zero_size_allowed)
5146 {
5147 	struct bpf_verifier_state *vstate = env->cur_state;
5148 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5149 	struct bpf_reg_state *reg = &state->regs[regno];
5150 	int err;
5151 
5152 	/* We may have adjusted the register pointing to memory region, so we
5153 	 * need to try adding each of min_value and max_value to off
5154 	 * to make sure our theoretical access will be safe.
5155 	 *
5156 	 * The minimum value is only important with signed
5157 	 * comparisons where we can't assume the floor of a
5158 	 * value is 0.  If we are using signed variables for our
5159 	 * index'es we need to make sure that whatever we use
5160 	 * will have a set floor within our range.
5161 	 */
5162 	if (reg->smin_value < 0 &&
5163 	    (reg->smin_value == S64_MIN ||
5164 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5165 	      reg->smin_value + off < 0)) {
5166 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5167 			regno);
5168 		return -EACCES;
5169 	}
5170 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5171 				 mem_size, zero_size_allowed);
5172 	if (err) {
5173 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5174 			regno);
5175 		return err;
5176 	}
5177 
5178 	/* If we haven't set a max value then we need to bail since we can't be
5179 	 * sure we won't do bad things.
5180 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5181 	 */
5182 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5183 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5184 			regno);
5185 		return -EACCES;
5186 	}
5187 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5188 				 mem_size, zero_size_allowed);
5189 	if (err) {
5190 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5191 			regno);
5192 		return err;
5193 	}
5194 
5195 	return 0;
5196 }
5197 
5198 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5199 			       const struct bpf_reg_state *reg, int regno,
5200 			       bool fixed_off_ok)
5201 {
5202 	/* Access to this pointer-typed register or passing it to a helper
5203 	 * is only allowed in its original, unmodified form.
5204 	 */
5205 
5206 	if (reg->off < 0) {
5207 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5208 			reg_type_str(env, reg->type), regno, reg->off);
5209 		return -EACCES;
5210 	}
5211 
5212 	if (!fixed_off_ok && reg->off) {
5213 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5214 			reg_type_str(env, reg->type), regno, reg->off);
5215 		return -EACCES;
5216 	}
5217 
5218 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5219 		char tn_buf[48];
5220 
5221 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5222 		verbose(env, "variable %s access var_off=%s disallowed\n",
5223 			reg_type_str(env, reg->type), tn_buf);
5224 		return -EACCES;
5225 	}
5226 
5227 	return 0;
5228 }
5229 
5230 int check_ptr_off_reg(struct bpf_verifier_env *env,
5231 		      const struct bpf_reg_state *reg, int regno)
5232 {
5233 	return __check_ptr_off_reg(env, reg, regno, false);
5234 }
5235 
5236 static int map_kptr_match_type(struct bpf_verifier_env *env,
5237 			       struct btf_field *kptr_field,
5238 			       struct bpf_reg_state *reg, u32 regno)
5239 {
5240 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5241 	int perm_flags;
5242 	const char *reg_name = "";
5243 
5244 	if (btf_is_kernel(reg->btf)) {
5245 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5246 
5247 		/* Only unreferenced case accepts untrusted pointers */
5248 		if (kptr_field->type == BPF_KPTR_UNREF)
5249 			perm_flags |= PTR_UNTRUSTED;
5250 	} else {
5251 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5252 	}
5253 
5254 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5255 		goto bad_type;
5256 
5257 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5258 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5259 
5260 	/* For ref_ptr case, release function check should ensure we get one
5261 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5262 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5263 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5264 	 * reg->off and reg->ref_obj_id are not needed here.
5265 	 */
5266 	if (__check_ptr_off_reg(env, reg, regno, true))
5267 		return -EACCES;
5268 
5269 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5270 	 * we also need to take into account the reg->off.
5271 	 *
5272 	 * We want to support cases like:
5273 	 *
5274 	 * struct foo {
5275 	 *         struct bar br;
5276 	 *         struct baz bz;
5277 	 * };
5278 	 *
5279 	 * struct foo *v;
5280 	 * v = func();	      // PTR_TO_BTF_ID
5281 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5282 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5283 	 *                    // first member type of struct after comparison fails
5284 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5285 	 *                    // to match type
5286 	 *
5287 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5288 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5289 	 * the struct to match type against first member of struct, i.e. reject
5290 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5291 	 * strict mode to true for type match.
5292 	 */
5293 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5294 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5295 				  kptr_field->type == BPF_KPTR_REF))
5296 		goto bad_type;
5297 	return 0;
5298 bad_type:
5299 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5300 		reg_type_str(env, reg->type), reg_name);
5301 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5302 	if (kptr_field->type == BPF_KPTR_UNREF)
5303 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5304 			targ_name);
5305 	else
5306 		verbose(env, "\n");
5307 	return -EINVAL;
5308 }
5309 
5310 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5311  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5312  */
5313 static bool in_rcu_cs(struct bpf_verifier_env *env)
5314 {
5315 	return env->cur_state->active_rcu_lock ||
5316 	       env->cur_state->active_lock.ptr ||
5317 	       !env->prog->aux->sleepable;
5318 }
5319 
5320 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5321 BTF_SET_START(rcu_protected_types)
5322 BTF_ID(struct, prog_test_ref_kfunc)
5323 BTF_ID(struct, cgroup)
5324 BTF_ID(struct, bpf_cpumask)
5325 BTF_ID(struct, task_struct)
5326 BTF_SET_END(rcu_protected_types)
5327 
5328 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5329 {
5330 	if (!btf_is_kernel(btf))
5331 		return false;
5332 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5333 }
5334 
5335 static bool rcu_safe_kptr(const struct btf_field *field)
5336 {
5337 	const struct btf_field_kptr *kptr = &field->kptr;
5338 
5339 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5340 }
5341 
5342 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5343 				 int value_regno, int insn_idx,
5344 				 struct btf_field *kptr_field)
5345 {
5346 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5347 	int class = BPF_CLASS(insn->code);
5348 	struct bpf_reg_state *val_reg;
5349 
5350 	/* Things we already checked for in check_map_access and caller:
5351 	 *  - Reject cases where variable offset may touch kptr
5352 	 *  - size of access (must be BPF_DW)
5353 	 *  - tnum_is_const(reg->var_off)
5354 	 *  - kptr_field->offset == off + reg->var_off.value
5355 	 */
5356 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5357 	if (BPF_MODE(insn->code) != BPF_MEM) {
5358 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5359 		return -EACCES;
5360 	}
5361 
5362 	/* We only allow loading referenced kptr, since it will be marked as
5363 	 * untrusted, similar to unreferenced kptr.
5364 	 */
5365 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5366 		verbose(env, "store to referenced kptr disallowed\n");
5367 		return -EACCES;
5368 	}
5369 
5370 	if (class == BPF_LDX) {
5371 		val_reg = reg_state(env, value_regno);
5372 		/* We can simply mark the value_regno receiving the pointer
5373 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5374 		 */
5375 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5376 				kptr_field->kptr.btf_id,
5377 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5378 				PTR_MAYBE_NULL | MEM_RCU :
5379 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5380 	} else if (class == BPF_STX) {
5381 		val_reg = reg_state(env, value_regno);
5382 		if (!register_is_null(val_reg) &&
5383 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5384 			return -EACCES;
5385 	} else if (class == BPF_ST) {
5386 		if (insn->imm) {
5387 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5388 				kptr_field->offset);
5389 			return -EACCES;
5390 		}
5391 	} else {
5392 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5393 		return -EACCES;
5394 	}
5395 	return 0;
5396 }
5397 
5398 /* check read/write into a map element with possible variable offset */
5399 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5400 			    int off, int size, bool zero_size_allowed,
5401 			    enum bpf_access_src src)
5402 {
5403 	struct bpf_verifier_state *vstate = env->cur_state;
5404 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5405 	struct bpf_reg_state *reg = &state->regs[regno];
5406 	struct bpf_map *map = reg->map_ptr;
5407 	struct btf_record *rec;
5408 	int err, i;
5409 
5410 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5411 				      zero_size_allowed);
5412 	if (err)
5413 		return err;
5414 
5415 	if (IS_ERR_OR_NULL(map->record))
5416 		return 0;
5417 	rec = map->record;
5418 	for (i = 0; i < rec->cnt; i++) {
5419 		struct btf_field *field = &rec->fields[i];
5420 		u32 p = field->offset;
5421 
5422 		/* If any part of a field  can be touched by load/store, reject
5423 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5424 		 * it is sufficient to check x1 < y2 && y1 < x2.
5425 		 */
5426 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5427 		    p < reg->umax_value + off + size) {
5428 			switch (field->type) {
5429 			case BPF_KPTR_UNREF:
5430 			case BPF_KPTR_REF:
5431 				if (src != ACCESS_DIRECT) {
5432 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5433 					return -EACCES;
5434 				}
5435 				if (!tnum_is_const(reg->var_off)) {
5436 					verbose(env, "kptr access cannot have variable offset\n");
5437 					return -EACCES;
5438 				}
5439 				if (p != off + reg->var_off.value) {
5440 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5441 						p, off + reg->var_off.value);
5442 					return -EACCES;
5443 				}
5444 				if (size != bpf_size_to_bytes(BPF_DW)) {
5445 					verbose(env, "kptr access size must be BPF_DW\n");
5446 					return -EACCES;
5447 				}
5448 				break;
5449 			default:
5450 				verbose(env, "%s cannot be accessed directly by load/store\n",
5451 					btf_field_type_name(field->type));
5452 				return -EACCES;
5453 			}
5454 		}
5455 	}
5456 	return 0;
5457 }
5458 
5459 #define MAX_PACKET_OFF 0xffff
5460 
5461 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5462 				       const struct bpf_call_arg_meta *meta,
5463 				       enum bpf_access_type t)
5464 {
5465 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5466 
5467 	switch (prog_type) {
5468 	/* Program types only with direct read access go here! */
5469 	case BPF_PROG_TYPE_LWT_IN:
5470 	case BPF_PROG_TYPE_LWT_OUT:
5471 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5472 	case BPF_PROG_TYPE_SK_REUSEPORT:
5473 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5474 	case BPF_PROG_TYPE_CGROUP_SKB:
5475 		if (t == BPF_WRITE)
5476 			return false;
5477 		fallthrough;
5478 
5479 	/* Program types with direct read + write access go here! */
5480 	case BPF_PROG_TYPE_SCHED_CLS:
5481 	case BPF_PROG_TYPE_SCHED_ACT:
5482 	case BPF_PROG_TYPE_XDP:
5483 	case BPF_PROG_TYPE_LWT_XMIT:
5484 	case BPF_PROG_TYPE_SK_SKB:
5485 	case BPF_PROG_TYPE_SK_MSG:
5486 		if (meta)
5487 			return meta->pkt_access;
5488 
5489 		env->seen_direct_write = true;
5490 		return true;
5491 
5492 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5493 		if (t == BPF_WRITE)
5494 			env->seen_direct_write = true;
5495 
5496 		return true;
5497 
5498 	default:
5499 		return false;
5500 	}
5501 }
5502 
5503 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5504 			       int size, bool zero_size_allowed)
5505 {
5506 	struct bpf_reg_state *regs = cur_regs(env);
5507 	struct bpf_reg_state *reg = &regs[regno];
5508 	int err;
5509 
5510 	/* We may have added a variable offset to the packet pointer; but any
5511 	 * reg->range we have comes after that.  We are only checking the fixed
5512 	 * offset.
5513 	 */
5514 
5515 	/* We don't allow negative numbers, because we aren't tracking enough
5516 	 * detail to prove they're safe.
5517 	 */
5518 	if (reg->smin_value < 0) {
5519 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5520 			regno);
5521 		return -EACCES;
5522 	}
5523 
5524 	err = reg->range < 0 ? -EINVAL :
5525 	      __check_mem_access(env, regno, off, size, reg->range,
5526 				 zero_size_allowed);
5527 	if (err) {
5528 		verbose(env, "R%d offset is outside of the packet\n", regno);
5529 		return err;
5530 	}
5531 
5532 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5533 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5534 	 * otherwise find_good_pkt_pointers would have refused to set range info
5535 	 * that __check_mem_access would have rejected this pkt access.
5536 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5537 	 */
5538 	env->prog->aux->max_pkt_offset =
5539 		max_t(u32, env->prog->aux->max_pkt_offset,
5540 		      off + reg->umax_value + size - 1);
5541 
5542 	return err;
5543 }
5544 
5545 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5546 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5547 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5548 			    struct btf **btf, u32 *btf_id)
5549 {
5550 	struct bpf_insn_access_aux info = {
5551 		.reg_type = *reg_type,
5552 		.log = &env->log,
5553 	};
5554 
5555 	if (env->ops->is_valid_access &&
5556 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5557 		/* A non zero info.ctx_field_size indicates that this field is a
5558 		 * candidate for later verifier transformation to load the whole
5559 		 * field and then apply a mask when accessed with a narrower
5560 		 * access than actual ctx access size. A zero info.ctx_field_size
5561 		 * will only allow for whole field access and rejects any other
5562 		 * type of narrower access.
5563 		 */
5564 		*reg_type = info.reg_type;
5565 
5566 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5567 			*btf = info.btf;
5568 			*btf_id = info.btf_id;
5569 		} else {
5570 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5571 		}
5572 		/* remember the offset of last byte accessed in ctx */
5573 		if (env->prog->aux->max_ctx_offset < off + size)
5574 			env->prog->aux->max_ctx_offset = off + size;
5575 		return 0;
5576 	}
5577 
5578 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5579 	return -EACCES;
5580 }
5581 
5582 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5583 				  int size)
5584 {
5585 	if (size < 0 || off < 0 ||
5586 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5587 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5588 			off, size);
5589 		return -EACCES;
5590 	}
5591 	return 0;
5592 }
5593 
5594 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5595 			     u32 regno, int off, int size,
5596 			     enum bpf_access_type t)
5597 {
5598 	struct bpf_reg_state *regs = cur_regs(env);
5599 	struct bpf_reg_state *reg = &regs[regno];
5600 	struct bpf_insn_access_aux info = {};
5601 	bool valid;
5602 
5603 	if (reg->smin_value < 0) {
5604 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5605 			regno);
5606 		return -EACCES;
5607 	}
5608 
5609 	switch (reg->type) {
5610 	case PTR_TO_SOCK_COMMON:
5611 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5612 		break;
5613 	case PTR_TO_SOCKET:
5614 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5615 		break;
5616 	case PTR_TO_TCP_SOCK:
5617 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5618 		break;
5619 	case PTR_TO_XDP_SOCK:
5620 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5621 		break;
5622 	default:
5623 		valid = false;
5624 	}
5625 
5626 
5627 	if (valid) {
5628 		env->insn_aux_data[insn_idx].ctx_field_size =
5629 			info.ctx_field_size;
5630 		return 0;
5631 	}
5632 
5633 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5634 		regno, reg_type_str(env, reg->type), off, size);
5635 
5636 	return -EACCES;
5637 }
5638 
5639 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5640 {
5641 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5642 }
5643 
5644 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5645 {
5646 	const struct bpf_reg_state *reg = reg_state(env, regno);
5647 
5648 	return reg->type == PTR_TO_CTX;
5649 }
5650 
5651 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5652 {
5653 	const struct bpf_reg_state *reg = reg_state(env, regno);
5654 
5655 	return type_is_sk_pointer(reg->type);
5656 }
5657 
5658 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5659 {
5660 	const struct bpf_reg_state *reg = reg_state(env, regno);
5661 
5662 	return type_is_pkt_pointer(reg->type);
5663 }
5664 
5665 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5666 {
5667 	const struct bpf_reg_state *reg = reg_state(env, regno);
5668 
5669 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5670 	return reg->type == PTR_TO_FLOW_KEYS;
5671 }
5672 
5673 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5674 #ifdef CONFIG_NET
5675 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5676 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5677 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5678 #endif
5679 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5680 };
5681 
5682 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5683 {
5684 	/* A referenced register is always trusted. */
5685 	if (reg->ref_obj_id)
5686 		return true;
5687 
5688 	/* Types listed in the reg2btf_ids are always trusted */
5689 	if (reg2btf_ids[base_type(reg->type)] &&
5690 	    !bpf_type_has_unsafe_modifiers(reg->type))
5691 		return true;
5692 
5693 	/* If a register is not referenced, it is trusted if it has the
5694 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5695 	 * other type modifiers may be safe, but we elect to take an opt-in
5696 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5697 	 * not.
5698 	 *
5699 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5700 	 * for whether a register is trusted.
5701 	 */
5702 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5703 	       !bpf_type_has_unsafe_modifiers(reg->type);
5704 }
5705 
5706 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5707 {
5708 	return reg->type & MEM_RCU;
5709 }
5710 
5711 static void clear_trusted_flags(enum bpf_type_flag *flag)
5712 {
5713 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5714 }
5715 
5716 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5717 				   const struct bpf_reg_state *reg,
5718 				   int off, int size, bool strict)
5719 {
5720 	struct tnum reg_off;
5721 	int ip_align;
5722 
5723 	/* Byte size accesses are always allowed. */
5724 	if (!strict || size == 1)
5725 		return 0;
5726 
5727 	/* For platforms that do not have a Kconfig enabling
5728 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5729 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5730 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5731 	 * to this code only in strict mode where we want to emulate
5732 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5733 	 * unconditional IP align value of '2'.
5734 	 */
5735 	ip_align = 2;
5736 
5737 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5738 	if (!tnum_is_aligned(reg_off, size)) {
5739 		char tn_buf[48];
5740 
5741 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5742 		verbose(env,
5743 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5744 			ip_align, tn_buf, reg->off, off, size);
5745 		return -EACCES;
5746 	}
5747 
5748 	return 0;
5749 }
5750 
5751 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5752 				       const struct bpf_reg_state *reg,
5753 				       const char *pointer_desc,
5754 				       int off, int size, bool strict)
5755 {
5756 	struct tnum reg_off;
5757 
5758 	/* Byte size accesses are always allowed. */
5759 	if (!strict || size == 1)
5760 		return 0;
5761 
5762 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5763 	if (!tnum_is_aligned(reg_off, size)) {
5764 		char tn_buf[48];
5765 
5766 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5767 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5768 			pointer_desc, tn_buf, reg->off, off, size);
5769 		return -EACCES;
5770 	}
5771 
5772 	return 0;
5773 }
5774 
5775 static int check_ptr_alignment(struct bpf_verifier_env *env,
5776 			       const struct bpf_reg_state *reg, int off,
5777 			       int size, bool strict_alignment_once)
5778 {
5779 	bool strict = env->strict_alignment || strict_alignment_once;
5780 	const char *pointer_desc = "";
5781 
5782 	switch (reg->type) {
5783 	case PTR_TO_PACKET:
5784 	case PTR_TO_PACKET_META:
5785 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5786 		 * right in front, treat it the very same way.
5787 		 */
5788 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5789 	case PTR_TO_FLOW_KEYS:
5790 		pointer_desc = "flow keys ";
5791 		break;
5792 	case PTR_TO_MAP_KEY:
5793 		pointer_desc = "key ";
5794 		break;
5795 	case PTR_TO_MAP_VALUE:
5796 		pointer_desc = "value ";
5797 		break;
5798 	case PTR_TO_CTX:
5799 		pointer_desc = "context ";
5800 		break;
5801 	case PTR_TO_STACK:
5802 		pointer_desc = "stack ";
5803 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5804 		 * and check_stack_read_fixed_off() relies on stack accesses being
5805 		 * aligned.
5806 		 */
5807 		strict = true;
5808 		break;
5809 	case PTR_TO_SOCKET:
5810 		pointer_desc = "sock ";
5811 		break;
5812 	case PTR_TO_SOCK_COMMON:
5813 		pointer_desc = "sock_common ";
5814 		break;
5815 	case PTR_TO_TCP_SOCK:
5816 		pointer_desc = "tcp_sock ";
5817 		break;
5818 	case PTR_TO_XDP_SOCK:
5819 		pointer_desc = "xdp_sock ";
5820 		break;
5821 	default:
5822 		break;
5823 	}
5824 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5825 					   strict);
5826 }
5827 
5828 /* starting from main bpf function walk all instructions of the function
5829  * and recursively walk all callees that given function can call.
5830  * Ignore jump and exit insns.
5831  * Since recursion is prevented by check_cfg() this algorithm
5832  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5833  */
5834 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5835 {
5836 	struct bpf_subprog_info *subprog = env->subprog_info;
5837 	struct bpf_insn *insn = env->prog->insnsi;
5838 	int depth = 0, frame = 0, i, subprog_end;
5839 	bool tail_call_reachable = false;
5840 	int ret_insn[MAX_CALL_FRAMES];
5841 	int ret_prog[MAX_CALL_FRAMES];
5842 	int j;
5843 
5844 	i = subprog[idx].start;
5845 process_func:
5846 	/* protect against potential stack overflow that might happen when
5847 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5848 	 * depth for such case down to 256 so that the worst case scenario
5849 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5850 	 * 8k).
5851 	 *
5852 	 * To get the idea what might happen, see an example:
5853 	 * func1 -> sub rsp, 128
5854 	 *  subfunc1 -> sub rsp, 256
5855 	 *  tailcall1 -> add rsp, 256
5856 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5857 	 *   subfunc2 -> sub rsp, 64
5858 	 *   subfunc22 -> sub rsp, 128
5859 	 *   tailcall2 -> add rsp, 128
5860 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5861 	 *
5862 	 * tailcall will unwind the current stack frame but it will not get rid
5863 	 * of caller's stack as shown on the example above.
5864 	 */
5865 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5866 		verbose(env,
5867 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5868 			depth);
5869 		return -EACCES;
5870 	}
5871 	/* round up to 32-bytes, since this is granularity
5872 	 * of interpreter stack size
5873 	 */
5874 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5875 	if (depth > MAX_BPF_STACK) {
5876 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5877 			frame + 1, depth);
5878 		return -EACCES;
5879 	}
5880 continue_func:
5881 	subprog_end = subprog[idx + 1].start;
5882 	for (; i < subprog_end; i++) {
5883 		int next_insn, sidx;
5884 
5885 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5886 			continue;
5887 		/* remember insn and function to return to */
5888 		ret_insn[frame] = i + 1;
5889 		ret_prog[frame] = idx;
5890 
5891 		/* find the callee */
5892 		next_insn = i + insn[i].imm + 1;
5893 		sidx = find_subprog(env, next_insn);
5894 		if (sidx < 0) {
5895 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5896 				  next_insn);
5897 			return -EFAULT;
5898 		}
5899 		if (subprog[sidx].is_async_cb) {
5900 			if (subprog[sidx].has_tail_call) {
5901 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5902 				return -EFAULT;
5903 			}
5904 			/* async callbacks don't increase bpf prog stack size unless called directly */
5905 			if (!bpf_pseudo_call(insn + i))
5906 				continue;
5907 		}
5908 		i = next_insn;
5909 		idx = sidx;
5910 
5911 		if (subprog[idx].has_tail_call)
5912 			tail_call_reachable = true;
5913 
5914 		frame++;
5915 		if (frame >= MAX_CALL_FRAMES) {
5916 			verbose(env, "the call stack of %d frames is too deep !\n",
5917 				frame);
5918 			return -E2BIG;
5919 		}
5920 		goto process_func;
5921 	}
5922 	/* if tail call got detected across bpf2bpf calls then mark each of the
5923 	 * currently present subprog frames as tail call reachable subprogs;
5924 	 * this info will be utilized by JIT so that we will be preserving the
5925 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5926 	 */
5927 	if (tail_call_reachable)
5928 		for (j = 0; j < frame; j++)
5929 			subprog[ret_prog[j]].tail_call_reachable = true;
5930 	if (subprog[0].tail_call_reachable)
5931 		env->prog->aux->tail_call_reachable = true;
5932 
5933 	/* end of for() loop means the last insn of the 'subprog'
5934 	 * was reached. Doesn't matter whether it was JA or EXIT
5935 	 */
5936 	if (frame == 0)
5937 		return 0;
5938 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5939 	frame--;
5940 	i = ret_insn[frame];
5941 	idx = ret_prog[frame];
5942 	goto continue_func;
5943 }
5944 
5945 static int check_max_stack_depth(struct bpf_verifier_env *env)
5946 {
5947 	struct bpf_subprog_info *si = env->subprog_info;
5948 	int ret;
5949 
5950 	for (int i = 0; i < env->subprog_cnt; i++) {
5951 		if (!i || si[i].is_async_cb) {
5952 			ret = check_max_stack_depth_subprog(env, i);
5953 			if (ret < 0)
5954 				return ret;
5955 		}
5956 		continue;
5957 	}
5958 	return 0;
5959 }
5960 
5961 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5962 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5963 				  const struct bpf_insn *insn, int idx)
5964 {
5965 	int start = idx + insn->imm + 1, subprog;
5966 
5967 	subprog = find_subprog(env, start);
5968 	if (subprog < 0) {
5969 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5970 			  start);
5971 		return -EFAULT;
5972 	}
5973 	return env->subprog_info[subprog].stack_depth;
5974 }
5975 #endif
5976 
5977 static int __check_buffer_access(struct bpf_verifier_env *env,
5978 				 const char *buf_info,
5979 				 const struct bpf_reg_state *reg,
5980 				 int regno, int off, int size)
5981 {
5982 	if (off < 0) {
5983 		verbose(env,
5984 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5985 			regno, buf_info, off, size);
5986 		return -EACCES;
5987 	}
5988 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5989 		char tn_buf[48];
5990 
5991 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5992 		verbose(env,
5993 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5994 			regno, off, tn_buf);
5995 		return -EACCES;
5996 	}
5997 
5998 	return 0;
5999 }
6000 
6001 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6002 				  const struct bpf_reg_state *reg,
6003 				  int regno, int off, int size)
6004 {
6005 	int err;
6006 
6007 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6008 	if (err)
6009 		return err;
6010 
6011 	if (off + size > env->prog->aux->max_tp_access)
6012 		env->prog->aux->max_tp_access = off + size;
6013 
6014 	return 0;
6015 }
6016 
6017 static int check_buffer_access(struct bpf_verifier_env *env,
6018 			       const struct bpf_reg_state *reg,
6019 			       int regno, int off, int size,
6020 			       bool zero_size_allowed,
6021 			       u32 *max_access)
6022 {
6023 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6024 	int err;
6025 
6026 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6027 	if (err)
6028 		return err;
6029 
6030 	if (off + size > *max_access)
6031 		*max_access = off + size;
6032 
6033 	return 0;
6034 }
6035 
6036 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6037 static void zext_32_to_64(struct bpf_reg_state *reg)
6038 {
6039 	reg->var_off = tnum_subreg(reg->var_off);
6040 	__reg_assign_32_into_64(reg);
6041 }
6042 
6043 /* truncate register to smaller size (in bytes)
6044  * must be called with size < BPF_REG_SIZE
6045  */
6046 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6047 {
6048 	u64 mask;
6049 
6050 	/* clear high bits in bit representation */
6051 	reg->var_off = tnum_cast(reg->var_off, size);
6052 
6053 	/* fix arithmetic bounds */
6054 	mask = ((u64)1 << (size * 8)) - 1;
6055 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6056 		reg->umin_value &= mask;
6057 		reg->umax_value &= mask;
6058 	} else {
6059 		reg->umin_value = 0;
6060 		reg->umax_value = mask;
6061 	}
6062 	reg->smin_value = reg->umin_value;
6063 	reg->smax_value = reg->umax_value;
6064 
6065 	/* If size is smaller than 32bit register the 32bit register
6066 	 * values are also truncated so we push 64-bit bounds into
6067 	 * 32-bit bounds. Above were truncated < 32-bits already.
6068 	 */
6069 	if (size >= 4)
6070 		return;
6071 	__reg_combine_64_into_32(reg);
6072 }
6073 
6074 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6075 {
6076 	if (size == 1) {
6077 		reg->smin_value = reg->s32_min_value = S8_MIN;
6078 		reg->smax_value = reg->s32_max_value = S8_MAX;
6079 	} else if (size == 2) {
6080 		reg->smin_value = reg->s32_min_value = S16_MIN;
6081 		reg->smax_value = reg->s32_max_value = S16_MAX;
6082 	} else {
6083 		/* size == 4 */
6084 		reg->smin_value = reg->s32_min_value = S32_MIN;
6085 		reg->smax_value = reg->s32_max_value = S32_MAX;
6086 	}
6087 	reg->umin_value = reg->u32_min_value = 0;
6088 	reg->umax_value = U64_MAX;
6089 	reg->u32_max_value = U32_MAX;
6090 	reg->var_off = tnum_unknown;
6091 }
6092 
6093 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6094 {
6095 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6096 	u64 top_smax_value, top_smin_value;
6097 	u64 num_bits = size * 8;
6098 
6099 	if (tnum_is_const(reg->var_off)) {
6100 		u64_cval = reg->var_off.value;
6101 		if (size == 1)
6102 			reg->var_off = tnum_const((s8)u64_cval);
6103 		else if (size == 2)
6104 			reg->var_off = tnum_const((s16)u64_cval);
6105 		else
6106 			/* size == 4 */
6107 			reg->var_off = tnum_const((s32)u64_cval);
6108 
6109 		u64_cval = reg->var_off.value;
6110 		reg->smax_value = reg->smin_value = u64_cval;
6111 		reg->umax_value = reg->umin_value = u64_cval;
6112 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6113 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6114 		return;
6115 	}
6116 
6117 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6118 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6119 
6120 	if (top_smax_value != top_smin_value)
6121 		goto out;
6122 
6123 	/* find the s64_min and s64_min after sign extension */
6124 	if (size == 1) {
6125 		init_s64_max = (s8)reg->smax_value;
6126 		init_s64_min = (s8)reg->smin_value;
6127 	} else if (size == 2) {
6128 		init_s64_max = (s16)reg->smax_value;
6129 		init_s64_min = (s16)reg->smin_value;
6130 	} else {
6131 		init_s64_max = (s32)reg->smax_value;
6132 		init_s64_min = (s32)reg->smin_value;
6133 	}
6134 
6135 	s64_max = max(init_s64_max, init_s64_min);
6136 	s64_min = min(init_s64_max, init_s64_min);
6137 
6138 	/* both of s64_max/s64_min positive or negative */
6139 	if ((s64_max >= 0) == (s64_min >= 0)) {
6140 		reg->smin_value = reg->s32_min_value = s64_min;
6141 		reg->smax_value = reg->s32_max_value = s64_max;
6142 		reg->umin_value = reg->u32_min_value = s64_min;
6143 		reg->umax_value = reg->u32_max_value = s64_max;
6144 		reg->var_off = tnum_range(s64_min, s64_max);
6145 		return;
6146 	}
6147 
6148 out:
6149 	set_sext64_default_val(reg, size);
6150 }
6151 
6152 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6153 {
6154 	if (size == 1) {
6155 		reg->s32_min_value = S8_MIN;
6156 		reg->s32_max_value = S8_MAX;
6157 	} else {
6158 		/* size == 2 */
6159 		reg->s32_min_value = S16_MIN;
6160 		reg->s32_max_value = S16_MAX;
6161 	}
6162 	reg->u32_min_value = 0;
6163 	reg->u32_max_value = U32_MAX;
6164 	reg->var_off = tnum_subreg(tnum_unknown);
6165 }
6166 
6167 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6168 {
6169 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6170 	u32 top_smax_value, top_smin_value;
6171 	u32 num_bits = size * 8;
6172 
6173 	if (tnum_is_const(reg->var_off)) {
6174 		u32_val = reg->var_off.value;
6175 		if (size == 1)
6176 			reg->var_off = tnum_const((s8)u32_val);
6177 		else
6178 			reg->var_off = tnum_const((s16)u32_val);
6179 
6180 		u32_val = reg->var_off.value;
6181 		reg->s32_min_value = reg->s32_max_value = u32_val;
6182 		reg->u32_min_value = reg->u32_max_value = u32_val;
6183 		return;
6184 	}
6185 
6186 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6187 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6188 
6189 	if (top_smax_value != top_smin_value)
6190 		goto out;
6191 
6192 	/* find the s32_min and s32_min after sign extension */
6193 	if (size == 1) {
6194 		init_s32_max = (s8)reg->s32_max_value;
6195 		init_s32_min = (s8)reg->s32_min_value;
6196 	} else {
6197 		/* size == 2 */
6198 		init_s32_max = (s16)reg->s32_max_value;
6199 		init_s32_min = (s16)reg->s32_min_value;
6200 	}
6201 	s32_max = max(init_s32_max, init_s32_min);
6202 	s32_min = min(init_s32_max, init_s32_min);
6203 
6204 	if ((s32_min >= 0) == (s32_max >= 0)) {
6205 		reg->s32_min_value = s32_min;
6206 		reg->s32_max_value = s32_max;
6207 		reg->u32_min_value = (u32)s32_min;
6208 		reg->u32_max_value = (u32)s32_max;
6209 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6210 		return;
6211 	}
6212 
6213 out:
6214 	set_sext32_default_val(reg, size);
6215 }
6216 
6217 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6218 {
6219 	/* A map is considered read-only if the following condition are true:
6220 	 *
6221 	 * 1) BPF program side cannot change any of the map content. The
6222 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6223 	 *    and was set at map creation time.
6224 	 * 2) The map value(s) have been initialized from user space by a
6225 	 *    loader and then "frozen", such that no new map update/delete
6226 	 *    operations from syscall side are possible for the rest of
6227 	 *    the map's lifetime from that point onwards.
6228 	 * 3) Any parallel/pending map update/delete operations from syscall
6229 	 *    side have been completed. Only after that point, it's safe to
6230 	 *    assume that map value(s) are immutable.
6231 	 */
6232 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6233 	       READ_ONCE(map->frozen) &&
6234 	       !bpf_map_write_active(map);
6235 }
6236 
6237 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6238 			       bool is_ldsx)
6239 {
6240 	void *ptr;
6241 	u64 addr;
6242 	int err;
6243 
6244 	err = map->ops->map_direct_value_addr(map, &addr, off);
6245 	if (err)
6246 		return err;
6247 	ptr = (void *)(long)addr + off;
6248 
6249 	switch (size) {
6250 	case sizeof(u8):
6251 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6252 		break;
6253 	case sizeof(u16):
6254 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6255 		break;
6256 	case sizeof(u32):
6257 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6258 		break;
6259 	case sizeof(u64):
6260 		*val = *(u64 *)ptr;
6261 		break;
6262 	default:
6263 		return -EINVAL;
6264 	}
6265 	return 0;
6266 }
6267 
6268 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6269 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6270 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6271 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6272 
6273 /*
6274  * Allow list few fields as RCU trusted or full trusted.
6275  * This logic doesn't allow mix tagging and will be removed once GCC supports
6276  * btf_type_tag.
6277  */
6278 
6279 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6280 BTF_TYPE_SAFE_RCU(struct task_struct) {
6281 	const cpumask_t *cpus_ptr;
6282 	struct css_set __rcu *cgroups;
6283 	struct task_struct __rcu *real_parent;
6284 	struct task_struct *group_leader;
6285 };
6286 
6287 BTF_TYPE_SAFE_RCU(struct cgroup) {
6288 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6289 	struct kernfs_node *kn;
6290 };
6291 
6292 BTF_TYPE_SAFE_RCU(struct css_set) {
6293 	struct cgroup *dfl_cgrp;
6294 };
6295 
6296 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6297 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6298 	struct file __rcu *exe_file;
6299 };
6300 
6301 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6302  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6303  */
6304 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6305 	struct sock *sk;
6306 };
6307 
6308 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6309 	struct sock *sk;
6310 };
6311 
6312 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6313 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6314 	struct seq_file *seq;
6315 };
6316 
6317 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6318 	struct bpf_iter_meta *meta;
6319 	struct task_struct *task;
6320 };
6321 
6322 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6323 	struct file *file;
6324 };
6325 
6326 BTF_TYPE_SAFE_TRUSTED(struct file) {
6327 	struct inode *f_inode;
6328 };
6329 
6330 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6331 	/* no negative dentry-s in places where bpf can see it */
6332 	struct inode *d_inode;
6333 };
6334 
6335 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6336 	struct sock *sk;
6337 };
6338 
6339 static bool type_is_rcu(struct bpf_verifier_env *env,
6340 			struct bpf_reg_state *reg,
6341 			const char *field_name, u32 btf_id)
6342 {
6343 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6344 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6345 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6346 
6347 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6348 }
6349 
6350 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6351 				struct bpf_reg_state *reg,
6352 				const char *field_name, u32 btf_id)
6353 {
6354 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6355 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6356 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6357 
6358 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6359 }
6360 
6361 static bool type_is_trusted(struct bpf_verifier_env *env,
6362 			    struct bpf_reg_state *reg,
6363 			    const char *field_name, u32 btf_id)
6364 {
6365 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6366 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6367 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6368 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6369 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6370 
6371 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6372 }
6373 
6374 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6375 				    struct bpf_reg_state *reg,
6376 				    const char *field_name, u32 btf_id)
6377 {
6378 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6379 
6380 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6381 					  "__safe_trusted_or_null");
6382 }
6383 
6384 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6385 				   struct bpf_reg_state *regs,
6386 				   int regno, int off, int size,
6387 				   enum bpf_access_type atype,
6388 				   int value_regno)
6389 {
6390 	struct bpf_reg_state *reg = regs + regno;
6391 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6392 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6393 	const char *field_name = NULL;
6394 	enum bpf_type_flag flag = 0;
6395 	u32 btf_id = 0;
6396 	int ret;
6397 
6398 	if (!env->allow_ptr_leaks) {
6399 		verbose(env,
6400 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6401 			tname);
6402 		return -EPERM;
6403 	}
6404 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6405 		verbose(env,
6406 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6407 			tname);
6408 		return -EINVAL;
6409 	}
6410 	if (off < 0) {
6411 		verbose(env,
6412 			"R%d is ptr_%s invalid negative access: off=%d\n",
6413 			regno, tname, off);
6414 		return -EACCES;
6415 	}
6416 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6417 		char tn_buf[48];
6418 
6419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6420 		verbose(env,
6421 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6422 			regno, tname, off, tn_buf);
6423 		return -EACCES;
6424 	}
6425 
6426 	if (reg->type & MEM_USER) {
6427 		verbose(env,
6428 			"R%d is ptr_%s access user memory: off=%d\n",
6429 			regno, tname, off);
6430 		return -EACCES;
6431 	}
6432 
6433 	if (reg->type & MEM_PERCPU) {
6434 		verbose(env,
6435 			"R%d is ptr_%s access percpu memory: off=%d\n",
6436 			regno, tname, off);
6437 		return -EACCES;
6438 	}
6439 
6440 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6441 		if (!btf_is_kernel(reg->btf)) {
6442 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6443 			return -EFAULT;
6444 		}
6445 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6446 	} else {
6447 		/* Writes are permitted with default btf_struct_access for
6448 		 * program allocated objects (which always have ref_obj_id > 0),
6449 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6450 		 */
6451 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6452 			verbose(env, "only read is supported\n");
6453 			return -EACCES;
6454 		}
6455 
6456 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6457 		    !reg->ref_obj_id) {
6458 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6459 			return -EFAULT;
6460 		}
6461 
6462 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6463 	}
6464 
6465 	if (ret < 0)
6466 		return ret;
6467 
6468 	if (ret != PTR_TO_BTF_ID) {
6469 		/* just mark; */
6470 
6471 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6472 		/* If this is an untrusted pointer, all pointers formed by walking it
6473 		 * also inherit the untrusted flag.
6474 		 */
6475 		flag = PTR_UNTRUSTED;
6476 
6477 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6478 		/* By default any pointer obtained from walking a trusted pointer is no
6479 		 * longer trusted, unless the field being accessed has explicitly been
6480 		 * marked as inheriting its parent's state of trust (either full or RCU).
6481 		 * For example:
6482 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6483 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6484 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6485 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6486 		 *
6487 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6488 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6489 		 */
6490 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6491 			flag |= PTR_TRUSTED;
6492 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6493 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6494 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6495 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6496 				/* ignore __rcu tag and mark it MEM_RCU */
6497 				flag |= MEM_RCU;
6498 			} else if (flag & MEM_RCU ||
6499 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6500 				/* __rcu tagged pointers can be NULL */
6501 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6502 
6503 				/* We always trust them */
6504 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6505 				    flag & PTR_UNTRUSTED)
6506 					flag &= ~PTR_UNTRUSTED;
6507 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6508 				/* keep as-is */
6509 			} else {
6510 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6511 				clear_trusted_flags(&flag);
6512 			}
6513 		} else {
6514 			/*
6515 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6516 			 * aggressively mark as untrusted otherwise such
6517 			 * pointers will be plain PTR_TO_BTF_ID without flags
6518 			 * and will be allowed to be passed into helpers for
6519 			 * compat reasons.
6520 			 */
6521 			flag = PTR_UNTRUSTED;
6522 		}
6523 	} else {
6524 		/* Old compat. Deprecated */
6525 		clear_trusted_flags(&flag);
6526 	}
6527 
6528 	if (atype == BPF_READ && value_regno >= 0)
6529 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6530 
6531 	return 0;
6532 }
6533 
6534 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6535 				   struct bpf_reg_state *regs,
6536 				   int regno, int off, int size,
6537 				   enum bpf_access_type atype,
6538 				   int value_regno)
6539 {
6540 	struct bpf_reg_state *reg = regs + regno;
6541 	struct bpf_map *map = reg->map_ptr;
6542 	struct bpf_reg_state map_reg;
6543 	enum bpf_type_flag flag = 0;
6544 	const struct btf_type *t;
6545 	const char *tname;
6546 	u32 btf_id;
6547 	int ret;
6548 
6549 	if (!btf_vmlinux) {
6550 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6551 		return -ENOTSUPP;
6552 	}
6553 
6554 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6555 		verbose(env, "map_ptr access not supported for map type %d\n",
6556 			map->map_type);
6557 		return -ENOTSUPP;
6558 	}
6559 
6560 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6561 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6562 
6563 	if (!env->allow_ptr_leaks) {
6564 		verbose(env,
6565 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6566 			tname);
6567 		return -EPERM;
6568 	}
6569 
6570 	if (off < 0) {
6571 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6572 			regno, tname, off);
6573 		return -EACCES;
6574 	}
6575 
6576 	if (atype != BPF_READ) {
6577 		verbose(env, "only read from %s is supported\n", tname);
6578 		return -EACCES;
6579 	}
6580 
6581 	/* Simulate access to a PTR_TO_BTF_ID */
6582 	memset(&map_reg, 0, sizeof(map_reg));
6583 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6584 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6585 	if (ret < 0)
6586 		return ret;
6587 
6588 	if (value_regno >= 0)
6589 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6590 
6591 	return 0;
6592 }
6593 
6594 /* Check that the stack access at the given offset is within bounds. The
6595  * maximum valid offset is -1.
6596  *
6597  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6598  * -state->allocated_stack for reads.
6599  */
6600 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6601                                           s64 off,
6602                                           struct bpf_func_state *state,
6603                                           enum bpf_access_type t)
6604 {
6605 	int min_valid_off;
6606 
6607 	if (t == BPF_WRITE || env->allow_uninit_stack)
6608 		min_valid_off = -MAX_BPF_STACK;
6609 	else
6610 		min_valid_off = -state->allocated_stack;
6611 
6612 	if (off < min_valid_off || off > -1)
6613 		return -EACCES;
6614 	return 0;
6615 }
6616 
6617 /* Check that the stack access at 'regno + off' falls within the maximum stack
6618  * bounds.
6619  *
6620  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6621  */
6622 static int check_stack_access_within_bounds(
6623 		struct bpf_verifier_env *env,
6624 		int regno, int off, int access_size,
6625 		enum bpf_access_src src, enum bpf_access_type type)
6626 {
6627 	struct bpf_reg_state *regs = cur_regs(env);
6628 	struct bpf_reg_state *reg = regs + regno;
6629 	struct bpf_func_state *state = func(env, reg);
6630 	s64 min_off, max_off;
6631 	int err;
6632 	char *err_extra;
6633 
6634 	if (src == ACCESS_HELPER)
6635 		/* We don't know if helpers are reading or writing (or both). */
6636 		err_extra = " indirect access to";
6637 	else if (type == BPF_READ)
6638 		err_extra = " read from";
6639 	else
6640 		err_extra = " write to";
6641 
6642 	if (tnum_is_const(reg->var_off)) {
6643 		min_off = (s64)reg->var_off.value + off;
6644 		max_off = min_off + access_size;
6645 	} else {
6646 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6647 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6648 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6649 				err_extra, regno);
6650 			return -EACCES;
6651 		}
6652 		min_off = reg->smin_value + off;
6653 		max_off = reg->smax_value + off + access_size;
6654 	}
6655 
6656 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6657 	if (!err && max_off > 0)
6658 		err = -EINVAL; /* out of stack access into non-negative offsets */
6659 	if (!err && access_size < 0)
6660 		/* access_size should not be negative (or overflow an int); others checks
6661 		 * along the way should have prevented such an access.
6662 		 */
6663 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6664 
6665 	if (err) {
6666 		if (tnum_is_const(reg->var_off)) {
6667 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6668 				err_extra, regno, off, access_size);
6669 		} else {
6670 			char tn_buf[48];
6671 
6672 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6673 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6674 				err_extra, regno, tn_buf, access_size);
6675 		}
6676 		return err;
6677 	}
6678 
6679 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6680 }
6681 
6682 /* check whether memory at (regno + off) is accessible for t = (read | write)
6683  * if t==write, value_regno is a register which value is stored into memory
6684  * if t==read, value_regno is a register which will receive the value from memory
6685  * if t==write && value_regno==-1, some unknown value is stored into memory
6686  * if t==read && value_regno==-1, don't care what we read from memory
6687  */
6688 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6689 			    int off, int bpf_size, enum bpf_access_type t,
6690 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6691 {
6692 	struct bpf_reg_state *regs = cur_regs(env);
6693 	struct bpf_reg_state *reg = regs + regno;
6694 	int size, err = 0;
6695 
6696 	size = bpf_size_to_bytes(bpf_size);
6697 	if (size < 0)
6698 		return size;
6699 
6700 	/* alignment checks will add in reg->off themselves */
6701 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6702 	if (err)
6703 		return err;
6704 
6705 	/* for access checks, reg->off is just part of off */
6706 	off += reg->off;
6707 
6708 	if (reg->type == PTR_TO_MAP_KEY) {
6709 		if (t == BPF_WRITE) {
6710 			verbose(env, "write to change key R%d not allowed\n", regno);
6711 			return -EACCES;
6712 		}
6713 
6714 		err = check_mem_region_access(env, regno, off, size,
6715 					      reg->map_ptr->key_size, false);
6716 		if (err)
6717 			return err;
6718 		if (value_regno >= 0)
6719 			mark_reg_unknown(env, regs, value_regno);
6720 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6721 		struct btf_field *kptr_field = NULL;
6722 
6723 		if (t == BPF_WRITE && value_regno >= 0 &&
6724 		    is_pointer_value(env, value_regno)) {
6725 			verbose(env, "R%d leaks addr into map\n", value_regno);
6726 			return -EACCES;
6727 		}
6728 		err = check_map_access_type(env, regno, off, size, t);
6729 		if (err)
6730 			return err;
6731 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6732 		if (err)
6733 			return err;
6734 		if (tnum_is_const(reg->var_off))
6735 			kptr_field = btf_record_find(reg->map_ptr->record,
6736 						     off + reg->var_off.value, BPF_KPTR);
6737 		if (kptr_field) {
6738 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6739 		} else if (t == BPF_READ && value_regno >= 0) {
6740 			struct bpf_map *map = reg->map_ptr;
6741 
6742 			/* if map is read-only, track its contents as scalars */
6743 			if (tnum_is_const(reg->var_off) &&
6744 			    bpf_map_is_rdonly(map) &&
6745 			    map->ops->map_direct_value_addr) {
6746 				int map_off = off + reg->var_off.value;
6747 				u64 val = 0;
6748 
6749 				err = bpf_map_direct_read(map, map_off, size,
6750 							  &val, is_ldsx);
6751 				if (err)
6752 					return err;
6753 
6754 				regs[value_regno].type = SCALAR_VALUE;
6755 				__mark_reg_known(&regs[value_regno], val);
6756 			} else {
6757 				mark_reg_unknown(env, regs, value_regno);
6758 			}
6759 		}
6760 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6761 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6762 
6763 		if (type_may_be_null(reg->type)) {
6764 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6765 				reg_type_str(env, reg->type));
6766 			return -EACCES;
6767 		}
6768 
6769 		if (t == BPF_WRITE && rdonly_mem) {
6770 			verbose(env, "R%d cannot write into %s\n",
6771 				regno, reg_type_str(env, reg->type));
6772 			return -EACCES;
6773 		}
6774 
6775 		if (t == BPF_WRITE && value_regno >= 0 &&
6776 		    is_pointer_value(env, value_regno)) {
6777 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6778 			return -EACCES;
6779 		}
6780 
6781 		err = check_mem_region_access(env, regno, off, size,
6782 					      reg->mem_size, false);
6783 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6784 			mark_reg_unknown(env, regs, value_regno);
6785 	} else if (reg->type == PTR_TO_CTX) {
6786 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6787 		struct btf *btf = NULL;
6788 		u32 btf_id = 0;
6789 
6790 		if (t == BPF_WRITE && value_regno >= 0 &&
6791 		    is_pointer_value(env, value_regno)) {
6792 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6793 			return -EACCES;
6794 		}
6795 
6796 		err = check_ptr_off_reg(env, reg, regno);
6797 		if (err < 0)
6798 			return err;
6799 
6800 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6801 				       &btf_id);
6802 		if (err)
6803 			verbose_linfo(env, insn_idx, "; ");
6804 		if (!err && t == BPF_READ && value_regno >= 0) {
6805 			/* ctx access returns either a scalar, or a
6806 			 * PTR_TO_PACKET[_META,_END]. In the latter
6807 			 * case, we know the offset is zero.
6808 			 */
6809 			if (reg_type == SCALAR_VALUE) {
6810 				mark_reg_unknown(env, regs, value_regno);
6811 			} else {
6812 				mark_reg_known_zero(env, regs,
6813 						    value_regno);
6814 				if (type_may_be_null(reg_type))
6815 					regs[value_regno].id = ++env->id_gen;
6816 				/* A load of ctx field could have different
6817 				 * actual load size with the one encoded in the
6818 				 * insn. When the dst is PTR, it is for sure not
6819 				 * a sub-register.
6820 				 */
6821 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6822 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6823 					regs[value_regno].btf = btf;
6824 					regs[value_regno].btf_id = btf_id;
6825 				}
6826 			}
6827 			regs[value_regno].type = reg_type;
6828 		}
6829 
6830 	} else if (reg->type == PTR_TO_STACK) {
6831 		/* Basic bounds checks. */
6832 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6833 		if (err)
6834 			return err;
6835 
6836 		if (t == BPF_READ)
6837 			err = check_stack_read(env, regno, off, size,
6838 					       value_regno);
6839 		else
6840 			err = check_stack_write(env, regno, off, size,
6841 						value_regno, insn_idx);
6842 	} else if (reg_is_pkt_pointer(reg)) {
6843 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6844 			verbose(env, "cannot write into packet\n");
6845 			return -EACCES;
6846 		}
6847 		if (t == BPF_WRITE && value_regno >= 0 &&
6848 		    is_pointer_value(env, value_regno)) {
6849 			verbose(env, "R%d leaks addr into packet\n",
6850 				value_regno);
6851 			return -EACCES;
6852 		}
6853 		err = check_packet_access(env, regno, off, size, false);
6854 		if (!err && t == BPF_READ && value_regno >= 0)
6855 			mark_reg_unknown(env, regs, value_regno);
6856 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6857 		if (t == BPF_WRITE && value_regno >= 0 &&
6858 		    is_pointer_value(env, value_regno)) {
6859 			verbose(env, "R%d leaks addr into flow keys\n",
6860 				value_regno);
6861 			return -EACCES;
6862 		}
6863 
6864 		err = check_flow_keys_access(env, off, size);
6865 		if (!err && t == BPF_READ && value_regno >= 0)
6866 			mark_reg_unknown(env, regs, value_regno);
6867 	} else if (type_is_sk_pointer(reg->type)) {
6868 		if (t == BPF_WRITE) {
6869 			verbose(env, "R%d cannot write into %s\n",
6870 				regno, reg_type_str(env, reg->type));
6871 			return -EACCES;
6872 		}
6873 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6874 		if (!err && value_regno >= 0)
6875 			mark_reg_unknown(env, regs, value_regno);
6876 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6877 		err = check_tp_buffer_access(env, reg, regno, off, size);
6878 		if (!err && t == BPF_READ && value_regno >= 0)
6879 			mark_reg_unknown(env, regs, value_regno);
6880 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6881 		   !type_may_be_null(reg->type)) {
6882 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6883 					      value_regno);
6884 	} else if (reg->type == CONST_PTR_TO_MAP) {
6885 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6886 					      value_regno);
6887 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6888 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6889 		u32 *max_access;
6890 
6891 		if (rdonly_mem) {
6892 			if (t == BPF_WRITE) {
6893 				verbose(env, "R%d cannot write into %s\n",
6894 					regno, reg_type_str(env, reg->type));
6895 				return -EACCES;
6896 			}
6897 			max_access = &env->prog->aux->max_rdonly_access;
6898 		} else {
6899 			max_access = &env->prog->aux->max_rdwr_access;
6900 		}
6901 
6902 		err = check_buffer_access(env, reg, regno, off, size, false,
6903 					  max_access);
6904 
6905 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6906 			mark_reg_unknown(env, regs, value_regno);
6907 	} else {
6908 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6909 			reg_type_str(env, reg->type));
6910 		return -EACCES;
6911 	}
6912 
6913 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6914 	    regs[value_regno].type == SCALAR_VALUE) {
6915 		if (!is_ldsx)
6916 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6917 			coerce_reg_to_size(&regs[value_regno], size);
6918 		else
6919 			coerce_reg_to_size_sx(&regs[value_regno], size);
6920 	}
6921 	return err;
6922 }
6923 
6924 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6925 {
6926 	int load_reg;
6927 	int err;
6928 
6929 	switch (insn->imm) {
6930 	case BPF_ADD:
6931 	case BPF_ADD | BPF_FETCH:
6932 	case BPF_AND:
6933 	case BPF_AND | BPF_FETCH:
6934 	case BPF_OR:
6935 	case BPF_OR | BPF_FETCH:
6936 	case BPF_XOR:
6937 	case BPF_XOR | BPF_FETCH:
6938 	case BPF_XCHG:
6939 	case BPF_CMPXCHG:
6940 		break;
6941 	default:
6942 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6943 		return -EINVAL;
6944 	}
6945 
6946 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6947 		verbose(env, "invalid atomic operand size\n");
6948 		return -EINVAL;
6949 	}
6950 
6951 	/* check src1 operand */
6952 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6953 	if (err)
6954 		return err;
6955 
6956 	/* check src2 operand */
6957 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6958 	if (err)
6959 		return err;
6960 
6961 	if (insn->imm == BPF_CMPXCHG) {
6962 		/* Check comparison of R0 with memory location */
6963 		const u32 aux_reg = BPF_REG_0;
6964 
6965 		err = check_reg_arg(env, aux_reg, SRC_OP);
6966 		if (err)
6967 			return err;
6968 
6969 		if (is_pointer_value(env, aux_reg)) {
6970 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6971 			return -EACCES;
6972 		}
6973 	}
6974 
6975 	if (is_pointer_value(env, insn->src_reg)) {
6976 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6977 		return -EACCES;
6978 	}
6979 
6980 	if (is_ctx_reg(env, insn->dst_reg) ||
6981 	    is_pkt_reg(env, insn->dst_reg) ||
6982 	    is_flow_key_reg(env, insn->dst_reg) ||
6983 	    is_sk_reg(env, insn->dst_reg)) {
6984 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6985 			insn->dst_reg,
6986 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6987 		return -EACCES;
6988 	}
6989 
6990 	if (insn->imm & BPF_FETCH) {
6991 		if (insn->imm == BPF_CMPXCHG)
6992 			load_reg = BPF_REG_0;
6993 		else
6994 			load_reg = insn->src_reg;
6995 
6996 		/* check and record load of old value */
6997 		err = check_reg_arg(env, load_reg, DST_OP);
6998 		if (err)
6999 			return err;
7000 	} else {
7001 		/* This instruction accesses a memory location but doesn't
7002 		 * actually load it into a register.
7003 		 */
7004 		load_reg = -1;
7005 	}
7006 
7007 	/* Check whether we can read the memory, with second call for fetch
7008 	 * case to simulate the register fill.
7009 	 */
7010 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7011 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7012 	if (!err && load_reg >= 0)
7013 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7014 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7015 				       true, false);
7016 	if (err)
7017 		return err;
7018 
7019 	/* Check whether we can write into the same memory. */
7020 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7021 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7022 	if (err)
7023 		return err;
7024 
7025 	return 0;
7026 }
7027 
7028 /* When register 'regno' is used to read the stack (either directly or through
7029  * a helper function) make sure that it's within stack boundary and, depending
7030  * on the access type and privileges, that all elements of the stack are
7031  * initialized.
7032  *
7033  * 'off' includes 'regno->off', but not its dynamic part (if any).
7034  *
7035  * All registers that have been spilled on the stack in the slots within the
7036  * read offsets are marked as read.
7037  */
7038 static int check_stack_range_initialized(
7039 		struct bpf_verifier_env *env, int regno, int off,
7040 		int access_size, bool zero_size_allowed,
7041 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7042 {
7043 	struct bpf_reg_state *reg = reg_state(env, regno);
7044 	struct bpf_func_state *state = func(env, reg);
7045 	int err, min_off, max_off, i, j, slot, spi;
7046 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7047 	enum bpf_access_type bounds_check_type;
7048 	/* Some accesses can write anything into the stack, others are
7049 	 * read-only.
7050 	 */
7051 	bool clobber = false;
7052 
7053 	if (access_size == 0 && !zero_size_allowed) {
7054 		verbose(env, "invalid zero-sized read\n");
7055 		return -EACCES;
7056 	}
7057 
7058 	if (type == ACCESS_HELPER) {
7059 		/* The bounds checks for writes are more permissive than for
7060 		 * reads. However, if raw_mode is not set, we'll do extra
7061 		 * checks below.
7062 		 */
7063 		bounds_check_type = BPF_WRITE;
7064 		clobber = true;
7065 	} else {
7066 		bounds_check_type = BPF_READ;
7067 	}
7068 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7069 					       type, bounds_check_type);
7070 	if (err)
7071 		return err;
7072 
7073 
7074 	if (tnum_is_const(reg->var_off)) {
7075 		min_off = max_off = reg->var_off.value + off;
7076 	} else {
7077 		/* Variable offset is prohibited for unprivileged mode for
7078 		 * simplicity since it requires corresponding support in
7079 		 * Spectre masking for stack ALU.
7080 		 * See also retrieve_ptr_limit().
7081 		 */
7082 		if (!env->bypass_spec_v1) {
7083 			char tn_buf[48];
7084 
7085 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7086 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7087 				regno, err_extra, tn_buf);
7088 			return -EACCES;
7089 		}
7090 		/* Only initialized buffer on stack is allowed to be accessed
7091 		 * with variable offset. With uninitialized buffer it's hard to
7092 		 * guarantee that whole memory is marked as initialized on
7093 		 * helper return since specific bounds are unknown what may
7094 		 * cause uninitialized stack leaking.
7095 		 */
7096 		if (meta && meta->raw_mode)
7097 			meta = NULL;
7098 
7099 		min_off = reg->smin_value + off;
7100 		max_off = reg->smax_value + off;
7101 	}
7102 
7103 	if (meta && meta->raw_mode) {
7104 		/* Ensure we won't be overwriting dynptrs when simulating byte
7105 		 * by byte access in check_helper_call using meta.access_size.
7106 		 * This would be a problem if we have a helper in the future
7107 		 * which takes:
7108 		 *
7109 		 *	helper(uninit_mem, len, dynptr)
7110 		 *
7111 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7112 		 * may end up writing to dynptr itself when touching memory from
7113 		 * arg 1. This can be relaxed on a case by case basis for known
7114 		 * safe cases, but reject due to the possibilitiy of aliasing by
7115 		 * default.
7116 		 */
7117 		for (i = min_off; i < max_off + access_size; i++) {
7118 			int stack_off = -i - 1;
7119 
7120 			spi = __get_spi(i);
7121 			/* raw_mode may write past allocated_stack */
7122 			if (state->allocated_stack <= stack_off)
7123 				continue;
7124 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7125 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7126 				return -EACCES;
7127 			}
7128 		}
7129 		meta->access_size = access_size;
7130 		meta->regno = regno;
7131 		return 0;
7132 	}
7133 
7134 	for (i = min_off; i < max_off + access_size; i++) {
7135 		u8 *stype;
7136 
7137 		slot = -i - 1;
7138 		spi = slot / BPF_REG_SIZE;
7139 		if (state->allocated_stack <= slot) {
7140 			verbose(env, "verifier bug: allocated_stack too small");
7141 			return -EFAULT;
7142 		}
7143 
7144 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7145 		if (*stype == STACK_MISC)
7146 			goto mark;
7147 		if ((*stype == STACK_ZERO) ||
7148 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7149 			if (clobber) {
7150 				/* helper can write anything into the stack */
7151 				*stype = STACK_MISC;
7152 			}
7153 			goto mark;
7154 		}
7155 
7156 		if (is_spilled_reg(&state->stack[spi]) &&
7157 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7158 		     env->allow_ptr_leaks)) {
7159 			if (clobber) {
7160 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7161 				for (j = 0; j < BPF_REG_SIZE; j++)
7162 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7163 			}
7164 			goto mark;
7165 		}
7166 
7167 		if (tnum_is_const(reg->var_off)) {
7168 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7169 				err_extra, regno, min_off, i - min_off, access_size);
7170 		} else {
7171 			char tn_buf[48];
7172 
7173 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7174 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7175 				err_extra, regno, tn_buf, i - min_off, access_size);
7176 		}
7177 		return -EACCES;
7178 mark:
7179 		/* reading any byte out of 8-byte 'spill_slot' will cause
7180 		 * the whole slot to be marked as 'read'
7181 		 */
7182 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7183 			      state->stack[spi].spilled_ptr.parent,
7184 			      REG_LIVE_READ64);
7185 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7186 		 * be sure that whether stack slot is written to or not. Hence,
7187 		 * we must still conservatively propagate reads upwards even if
7188 		 * helper may write to the entire memory range.
7189 		 */
7190 	}
7191 	return 0;
7192 }
7193 
7194 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7195 				   int access_size, bool zero_size_allowed,
7196 				   struct bpf_call_arg_meta *meta)
7197 {
7198 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7199 	u32 *max_access;
7200 
7201 	switch (base_type(reg->type)) {
7202 	case PTR_TO_PACKET:
7203 	case PTR_TO_PACKET_META:
7204 		return check_packet_access(env, regno, reg->off, access_size,
7205 					   zero_size_allowed);
7206 	case PTR_TO_MAP_KEY:
7207 		if (meta && meta->raw_mode) {
7208 			verbose(env, "R%d cannot write into %s\n", regno,
7209 				reg_type_str(env, reg->type));
7210 			return -EACCES;
7211 		}
7212 		return check_mem_region_access(env, regno, reg->off, access_size,
7213 					       reg->map_ptr->key_size, false);
7214 	case PTR_TO_MAP_VALUE:
7215 		if (check_map_access_type(env, regno, reg->off, access_size,
7216 					  meta && meta->raw_mode ? BPF_WRITE :
7217 					  BPF_READ))
7218 			return -EACCES;
7219 		return check_map_access(env, regno, reg->off, access_size,
7220 					zero_size_allowed, ACCESS_HELPER);
7221 	case PTR_TO_MEM:
7222 		if (type_is_rdonly_mem(reg->type)) {
7223 			if (meta && meta->raw_mode) {
7224 				verbose(env, "R%d cannot write into %s\n", regno,
7225 					reg_type_str(env, reg->type));
7226 				return -EACCES;
7227 			}
7228 		}
7229 		return check_mem_region_access(env, regno, reg->off,
7230 					       access_size, reg->mem_size,
7231 					       zero_size_allowed);
7232 	case PTR_TO_BUF:
7233 		if (type_is_rdonly_mem(reg->type)) {
7234 			if (meta && meta->raw_mode) {
7235 				verbose(env, "R%d cannot write into %s\n", regno,
7236 					reg_type_str(env, reg->type));
7237 				return -EACCES;
7238 			}
7239 
7240 			max_access = &env->prog->aux->max_rdonly_access;
7241 		} else {
7242 			max_access = &env->prog->aux->max_rdwr_access;
7243 		}
7244 		return check_buffer_access(env, reg, regno, reg->off,
7245 					   access_size, zero_size_allowed,
7246 					   max_access);
7247 	case PTR_TO_STACK:
7248 		return check_stack_range_initialized(
7249 				env,
7250 				regno, reg->off, access_size,
7251 				zero_size_allowed, ACCESS_HELPER, meta);
7252 	case PTR_TO_BTF_ID:
7253 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7254 					       access_size, BPF_READ, -1);
7255 	case PTR_TO_CTX:
7256 		/* in case the function doesn't know how to access the context,
7257 		 * (because we are in a program of type SYSCALL for example), we
7258 		 * can not statically check its size.
7259 		 * Dynamically check it now.
7260 		 */
7261 		if (!env->ops->convert_ctx_access) {
7262 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7263 			int offset = access_size - 1;
7264 
7265 			/* Allow zero-byte read from PTR_TO_CTX */
7266 			if (access_size == 0)
7267 				return zero_size_allowed ? 0 : -EACCES;
7268 
7269 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7270 						atype, -1, false, false);
7271 		}
7272 
7273 		fallthrough;
7274 	default: /* scalar_value or invalid ptr */
7275 		/* Allow zero-byte read from NULL, regardless of pointer type */
7276 		if (zero_size_allowed && access_size == 0 &&
7277 		    register_is_null(reg))
7278 			return 0;
7279 
7280 		verbose(env, "R%d type=%s ", regno,
7281 			reg_type_str(env, reg->type));
7282 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7283 		return -EACCES;
7284 	}
7285 }
7286 
7287 static int check_mem_size_reg(struct bpf_verifier_env *env,
7288 			      struct bpf_reg_state *reg, u32 regno,
7289 			      bool zero_size_allowed,
7290 			      struct bpf_call_arg_meta *meta)
7291 {
7292 	int err;
7293 
7294 	/* This is used to refine r0 return value bounds for helpers
7295 	 * that enforce this value as an upper bound on return values.
7296 	 * See do_refine_retval_range() for helpers that can refine
7297 	 * the return value. C type of helper is u32 so we pull register
7298 	 * bound from umax_value however, if negative verifier errors
7299 	 * out. Only upper bounds can be learned because retval is an
7300 	 * int type and negative retvals are allowed.
7301 	 */
7302 	meta->msize_max_value = reg->umax_value;
7303 
7304 	/* The register is SCALAR_VALUE; the access check
7305 	 * happens using its boundaries.
7306 	 */
7307 	if (!tnum_is_const(reg->var_off))
7308 		/* For unprivileged variable accesses, disable raw
7309 		 * mode so that the program is required to
7310 		 * initialize all the memory that the helper could
7311 		 * just partially fill up.
7312 		 */
7313 		meta = NULL;
7314 
7315 	if (reg->smin_value < 0) {
7316 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7317 			regno);
7318 		return -EACCES;
7319 	}
7320 
7321 	if (reg->umin_value == 0) {
7322 		err = check_helper_mem_access(env, regno - 1, 0,
7323 					      zero_size_allowed,
7324 					      meta);
7325 		if (err)
7326 			return err;
7327 	}
7328 
7329 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7330 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7331 			regno);
7332 		return -EACCES;
7333 	}
7334 	err = check_helper_mem_access(env, regno - 1,
7335 				      reg->umax_value,
7336 				      zero_size_allowed, meta);
7337 	if (!err)
7338 		err = mark_chain_precision(env, regno);
7339 	return err;
7340 }
7341 
7342 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7343 		   u32 regno, u32 mem_size)
7344 {
7345 	bool may_be_null = type_may_be_null(reg->type);
7346 	struct bpf_reg_state saved_reg;
7347 	struct bpf_call_arg_meta meta;
7348 	int err;
7349 
7350 	if (register_is_null(reg))
7351 		return 0;
7352 
7353 	memset(&meta, 0, sizeof(meta));
7354 	/* Assuming that the register contains a value check if the memory
7355 	 * access is safe. Temporarily save and restore the register's state as
7356 	 * the conversion shouldn't be visible to a caller.
7357 	 */
7358 	if (may_be_null) {
7359 		saved_reg = *reg;
7360 		mark_ptr_not_null_reg(reg);
7361 	}
7362 
7363 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7364 	/* Check access for BPF_WRITE */
7365 	meta.raw_mode = true;
7366 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7367 
7368 	if (may_be_null)
7369 		*reg = saved_reg;
7370 
7371 	return err;
7372 }
7373 
7374 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7375 				    u32 regno)
7376 {
7377 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7378 	bool may_be_null = type_may_be_null(mem_reg->type);
7379 	struct bpf_reg_state saved_reg;
7380 	struct bpf_call_arg_meta meta;
7381 	int err;
7382 
7383 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7384 
7385 	memset(&meta, 0, sizeof(meta));
7386 
7387 	if (may_be_null) {
7388 		saved_reg = *mem_reg;
7389 		mark_ptr_not_null_reg(mem_reg);
7390 	}
7391 
7392 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7393 	/* Check access for BPF_WRITE */
7394 	meta.raw_mode = true;
7395 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7396 
7397 	if (may_be_null)
7398 		*mem_reg = saved_reg;
7399 	return err;
7400 }
7401 
7402 /* Implementation details:
7403  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7404  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7405  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7406  * Two separate bpf_obj_new will also have different reg->id.
7407  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7408  * clears reg->id after value_or_null->value transition, since the verifier only
7409  * cares about the range of access to valid map value pointer and doesn't care
7410  * about actual address of the map element.
7411  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7412  * reg->id > 0 after value_or_null->value transition. By doing so
7413  * two bpf_map_lookups will be considered two different pointers that
7414  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7415  * returned from bpf_obj_new.
7416  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7417  * dead-locks.
7418  * Since only one bpf_spin_lock is allowed the checks are simpler than
7419  * reg_is_refcounted() logic. The verifier needs to remember only
7420  * one spin_lock instead of array of acquired_refs.
7421  * cur_state->active_lock remembers which map value element or allocated
7422  * object got locked and clears it after bpf_spin_unlock.
7423  */
7424 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7425 			     bool is_lock)
7426 {
7427 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7428 	struct bpf_verifier_state *cur = env->cur_state;
7429 	bool is_const = tnum_is_const(reg->var_off);
7430 	u64 val = reg->var_off.value;
7431 	struct bpf_map *map = NULL;
7432 	struct btf *btf = NULL;
7433 	struct btf_record *rec;
7434 
7435 	if (!is_const) {
7436 		verbose(env,
7437 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7438 			regno);
7439 		return -EINVAL;
7440 	}
7441 	if (reg->type == PTR_TO_MAP_VALUE) {
7442 		map = reg->map_ptr;
7443 		if (!map->btf) {
7444 			verbose(env,
7445 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7446 				map->name);
7447 			return -EINVAL;
7448 		}
7449 	} else {
7450 		btf = reg->btf;
7451 	}
7452 
7453 	rec = reg_btf_record(reg);
7454 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7455 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7456 			map ? map->name : "kptr");
7457 		return -EINVAL;
7458 	}
7459 	if (rec->spin_lock_off != val + reg->off) {
7460 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7461 			val + reg->off, rec->spin_lock_off);
7462 		return -EINVAL;
7463 	}
7464 	if (is_lock) {
7465 		if (cur->active_lock.ptr) {
7466 			verbose(env,
7467 				"Locking two bpf_spin_locks are not allowed\n");
7468 			return -EINVAL;
7469 		}
7470 		if (map)
7471 			cur->active_lock.ptr = map;
7472 		else
7473 			cur->active_lock.ptr = btf;
7474 		cur->active_lock.id = reg->id;
7475 	} else {
7476 		void *ptr;
7477 
7478 		if (map)
7479 			ptr = map;
7480 		else
7481 			ptr = btf;
7482 
7483 		if (!cur->active_lock.ptr) {
7484 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7485 			return -EINVAL;
7486 		}
7487 		if (cur->active_lock.ptr != ptr ||
7488 		    cur->active_lock.id != reg->id) {
7489 			verbose(env, "bpf_spin_unlock of different lock\n");
7490 			return -EINVAL;
7491 		}
7492 
7493 		invalidate_non_owning_refs(env);
7494 
7495 		cur->active_lock.ptr = NULL;
7496 		cur->active_lock.id = 0;
7497 	}
7498 	return 0;
7499 }
7500 
7501 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7502 			      struct bpf_call_arg_meta *meta)
7503 {
7504 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7505 	bool is_const = tnum_is_const(reg->var_off);
7506 	struct bpf_map *map = reg->map_ptr;
7507 	u64 val = reg->var_off.value;
7508 
7509 	if (!is_const) {
7510 		verbose(env,
7511 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7512 			regno);
7513 		return -EINVAL;
7514 	}
7515 	if (!map->btf) {
7516 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7517 			map->name);
7518 		return -EINVAL;
7519 	}
7520 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7521 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7522 		return -EINVAL;
7523 	}
7524 	if (map->record->timer_off != val + reg->off) {
7525 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7526 			val + reg->off, map->record->timer_off);
7527 		return -EINVAL;
7528 	}
7529 	if (meta->map_ptr) {
7530 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7531 		return -EFAULT;
7532 	}
7533 	meta->map_uid = reg->map_uid;
7534 	meta->map_ptr = map;
7535 	return 0;
7536 }
7537 
7538 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7539 			     struct bpf_call_arg_meta *meta)
7540 {
7541 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7542 	struct bpf_map *map_ptr = reg->map_ptr;
7543 	struct btf_field *kptr_field;
7544 	u32 kptr_off;
7545 
7546 	if (!tnum_is_const(reg->var_off)) {
7547 		verbose(env,
7548 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7549 			regno);
7550 		return -EINVAL;
7551 	}
7552 	if (!map_ptr->btf) {
7553 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7554 			map_ptr->name);
7555 		return -EINVAL;
7556 	}
7557 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7558 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7559 		return -EINVAL;
7560 	}
7561 
7562 	meta->map_ptr = map_ptr;
7563 	kptr_off = reg->off + reg->var_off.value;
7564 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7565 	if (!kptr_field) {
7566 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7567 		return -EACCES;
7568 	}
7569 	if (kptr_field->type != BPF_KPTR_REF) {
7570 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7571 		return -EACCES;
7572 	}
7573 	meta->kptr_field = kptr_field;
7574 	return 0;
7575 }
7576 
7577 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7578  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7579  *
7580  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7581  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7582  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7583  *
7584  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7585  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7586  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7587  * mutate the view of the dynptr and also possibly destroy it. In the latter
7588  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7589  * memory that dynptr points to.
7590  *
7591  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7592  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7593  * readonly dynptr view yet, hence only the first case is tracked and checked.
7594  *
7595  * This is consistent with how C applies the const modifier to a struct object,
7596  * where the pointer itself inside bpf_dynptr becomes const but not what it
7597  * points to.
7598  *
7599  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7600  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7601  */
7602 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7603 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7604 {
7605 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7606 	int err;
7607 
7608 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7609 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7610 	 */
7611 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7612 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7613 		return -EFAULT;
7614 	}
7615 
7616 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7617 	 *		 constructing a mutable bpf_dynptr object.
7618 	 *
7619 	 *		 Currently, this is only possible with PTR_TO_STACK
7620 	 *		 pointing to a region of at least 16 bytes which doesn't
7621 	 *		 contain an existing bpf_dynptr.
7622 	 *
7623 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7624 	 *		 mutated or destroyed. However, the memory it points to
7625 	 *		 may be mutated.
7626 	 *
7627 	 *  None       - Points to a initialized dynptr that can be mutated and
7628 	 *		 destroyed, including mutation of the memory it points
7629 	 *		 to.
7630 	 */
7631 	if (arg_type & MEM_UNINIT) {
7632 		int i;
7633 
7634 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7635 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7636 			return -EINVAL;
7637 		}
7638 
7639 		/* we write BPF_DW bits (8 bytes) at a time */
7640 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7641 			err = check_mem_access(env, insn_idx, regno,
7642 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7643 			if (err)
7644 				return err;
7645 		}
7646 
7647 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7648 	} else /* MEM_RDONLY and None case from above */ {
7649 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7650 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7651 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7652 			return -EINVAL;
7653 		}
7654 
7655 		if (!is_dynptr_reg_valid_init(env, reg)) {
7656 			verbose(env,
7657 				"Expected an initialized dynptr as arg #%d\n",
7658 				regno);
7659 			return -EINVAL;
7660 		}
7661 
7662 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7663 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7664 			verbose(env,
7665 				"Expected a dynptr of type %s as arg #%d\n",
7666 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7667 			return -EINVAL;
7668 		}
7669 
7670 		err = mark_dynptr_read(env, reg);
7671 	}
7672 	return err;
7673 }
7674 
7675 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7676 {
7677 	struct bpf_func_state *state = func(env, reg);
7678 
7679 	return state->stack[spi].spilled_ptr.ref_obj_id;
7680 }
7681 
7682 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7683 {
7684 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7685 }
7686 
7687 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7688 {
7689 	return meta->kfunc_flags & KF_ITER_NEW;
7690 }
7691 
7692 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7693 {
7694 	return meta->kfunc_flags & KF_ITER_NEXT;
7695 }
7696 
7697 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7698 {
7699 	return meta->kfunc_flags & KF_ITER_DESTROY;
7700 }
7701 
7702 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7703 {
7704 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7705 	 * kfunc is iter state pointer
7706 	 */
7707 	return arg == 0 && is_iter_kfunc(meta);
7708 }
7709 
7710 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7711 			    struct bpf_kfunc_call_arg_meta *meta)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7714 	const struct btf_type *t;
7715 	const struct btf_param *arg;
7716 	int spi, err, i, nr_slots;
7717 	u32 btf_id;
7718 
7719 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7720 	arg = &btf_params(meta->func_proto)[0];
7721 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7722 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7723 	nr_slots = t->size / BPF_REG_SIZE;
7724 
7725 	if (is_iter_new_kfunc(meta)) {
7726 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7727 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7728 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7729 				iter_type_str(meta->btf, btf_id), regno);
7730 			return -EINVAL;
7731 		}
7732 
7733 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7734 			err = check_mem_access(env, insn_idx, regno,
7735 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7736 			if (err)
7737 				return err;
7738 		}
7739 
7740 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7741 		if (err)
7742 			return err;
7743 	} else {
7744 		/* iter_next() or iter_destroy() expect initialized iter state*/
7745 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7746 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7747 				iter_type_str(meta->btf, btf_id), regno);
7748 			return -EINVAL;
7749 		}
7750 
7751 		spi = iter_get_spi(env, reg, nr_slots);
7752 		if (spi < 0)
7753 			return spi;
7754 
7755 		err = mark_iter_read(env, reg, spi, nr_slots);
7756 		if (err)
7757 			return err;
7758 
7759 		/* remember meta->iter info for process_iter_next_call() */
7760 		meta->iter.spi = spi;
7761 		meta->iter.frameno = reg->frameno;
7762 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7763 
7764 		if (is_iter_destroy_kfunc(meta)) {
7765 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7766 			if (err)
7767 				return err;
7768 		}
7769 	}
7770 
7771 	return 0;
7772 }
7773 
7774 /* Look for a previous loop entry at insn_idx: nearest parent state
7775  * stopped at insn_idx with callsites matching those in cur->frame.
7776  */
7777 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7778 						  struct bpf_verifier_state *cur,
7779 						  int insn_idx)
7780 {
7781 	struct bpf_verifier_state_list *sl;
7782 	struct bpf_verifier_state *st;
7783 
7784 	/* Explored states are pushed in stack order, most recent states come first */
7785 	sl = *explored_state(env, insn_idx);
7786 	for (; sl; sl = sl->next) {
7787 		/* If st->branches != 0 state is a part of current DFS verification path,
7788 		 * hence cur & st for a loop.
7789 		 */
7790 		st = &sl->state;
7791 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7792 		    st->dfs_depth < cur->dfs_depth)
7793 			return st;
7794 	}
7795 
7796 	return NULL;
7797 }
7798 
7799 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7800 static bool regs_exact(const struct bpf_reg_state *rold,
7801 		       const struct bpf_reg_state *rcur,
7802 		       struct bpf_idmap *idmap);
7803 
7804 static void maybe_widen_reg(struct bpf_verifier_env *env,
7805 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7806 			    struct bpf_idmap *idmap)
7807 {
7808 	if (rold->type != SCALAR_VALUE)
7809 		return;
7810 	if (rold->type != rcur->type)
7811 		return;
7812 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7813 		return;
7814 	__mark_reg_unknown(env, rcur);
7815 }
7816 
7817 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7818 				   struct bpf_verifier_state *old,
7819 				   struct bpf_verifier_state *cur)
7820 {
7821 	struct bpf_func_state *fold, *fcur;
7822 	int i, fr;
7823 
7824 	reset_idmap_scratch(env);
7825 	for (fr = old->curframe; fr >= 0; fr--) {
7826 		fold = old->frame[fr];
7827 		fcur = cur->frame[fr];
7828 
7829 		for (i = 0; i < MAX_BPF_REG; i++)
7830 			maybe_widen_reg(env,
7831 					&fold->regs[i],
7832 					&fcur->regs[i],
7833 					&env->idmap_scratch);
7834 
7835 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7836 			if (!is_spilled_reg(&fold->stack[i]) ||
7837 			    !is_spilled_reg(&fcur->stack[i]))
7838 				continue;
7839 
7840 			maybe_widen_reg(env,
7841 					&fold->stack[i].spilled_ptr,
7842 					&fcur->stack[i].spilled_ptr,
7843 					&env->idmap_scratch);
7844 		}
7845 	}
7846 	return 0;
7847 }
7848 
7849 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7850 						 struct bpf_kfunc_call_arg_meta *meta)
7851 {
7852 	int iter_frameno = meta->iter.frameno;
7853 	int iter_spi = meta->iter.spi;
7854 
7855 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7856 }
7857 
7858 /* process_iter_next_call() is called when verifier gets to iterator's next
7859  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7860  * to it as just "iter_next()" in comments below.
7861  *
7862  * BPF verifier relies on a crucial contract for any iter_next()
7863  * implementation: it should *eventually* return NULL, and once that happens
7864  * it should keep returning NULL. That is, once iterator exhausts elements to
7865  * iterate, it should never reset or spuriously return new elements.
7866  *
7867  * With the assumption of such contract, process_iter_next_call() simulates
7868  * a fork in the verifier state to validate loop logic correctness and safety
7869  * without having to simulate infinite amount of iterations.
7870  *
7871  * In current state, we first assume that iter_next() returned NULL and
7872  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7873  * conditions we should not form an infinite loop and should eventually reach
7874  * exit.
7875  *
7876  * Besides that, we also fork current state and enqueue it for later
7877  * verification. In a forked state we keep iterator state as ACTIVE
7878  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7879  * also bump iteration depth to prevent erroneous infinite loop detection
7880  * later on (see iter_active_depths_differ() comment for details). In this
7881  * state we assume that we'll eventually loop back to another iter_next()
7882  * calls (it could be in exactly same location or in some other instruction,
7883  * it doesn't matter, we don't make any unnecessary assumptions about this,
7884  * everything revolves around iterator state in a stack slot, not which
7885  * instruction is calling iter_next()). When that happens, we either will come
7886  * to iter_next() with equivalent state and can conclude that next iteration
7887  * will proceed in exactly the same way as we just verified, so it's safe to
7888  * assume that loop converges. If not, we'll go on another iteration
7889  * simulation with a different input state, until all possible starting states
7890  * are validated or we reach maximum number of instructions limit.
7891  *
7892  * This way, we will either exhaustively discover all possible input states
7893  * that iterator loop can start with and eventually will converge, or we'll
7894  * effectively regress into bounded loop simulation logic and either reach
7895  * maximum number of instructions if loop is not provably convergent, or there
7896  * is some statically known limit on number of iterations (e.g., if there is
7897  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7898  *
7899  * Iteration convergence logic in is_state_visited() relies on exact
7900  * states comparison, which ignores read and precision marks.
7901  * This is necessary because read and precision marks are not finalized
7902  * while in the loop. Exact comparison might preclude convergence for
7903  * simple programs like below:
7904  *
7905  *     i = 0;
7906  *     while(iter_next(&it))
7907  *       i++;
7908  *
7909  * At each iteration step i++ would produce a new distinct state and
7910  * eventually instruction processing limit would be reached.
7911  *
7912  * To avoid such behavior speculatively forget (widen) range for
7913  * imprecise scalar registers, if those registers were not precise at the
7914  * end of the previous iteration and do not match exactly.
7915  *
7916  * This is a conservative heuristic that allows to verify wide range of programs,
7917  * however it precludes verification of programs that conjure an
7918  * imprecise value on the first loop iteration and use it as precise on a second.
7919  * For example, the following safe program would fail to verify:
7920  *
7921  *     struct bpf_num_iter it;
7922  *     int arr[10];
7923  *     int i = 0, a = 0;
7924  *     bpf_iter_num_new(&it, 0, 10);
7925  *     while (bpf_iter_num_next(&it)) {
7926  *       if (a == 0) {
7927  *         a = 1;
7928  *         i = 7; // Because i changed verifier would forget
7929  *                // it's range on second loop entry.
7930  *       } else {
7931  *         arr[i] = 42; // This would fail to verify.
7932  *       }
7933  *     }
7934  *     bpf_iter_num_destroy(&it);
7935  */
7936 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7937 				  struct bpf_kfunc_call_arg_meta *meta)
7938 {
7939 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7940 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7941 	struct bpf_reg_state *cur_iter, *queued_iter;
7942 
7943 	BTF_TYPE_EMIT(struct bpf_iter);
7944 
7945 	cur_iter = get_iter_from_state(cur_st, meta);
7946 
7947 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7948 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7949 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7950 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7951 		return -EFAULT;
7952 	}
7953 
7954 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7955 		/* Because iter_next() call is a checkpoint is_state_visitied()
7956 		 * should guarantee parent state with same call sites and insn_idx.
7957 		 */
7958 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7959 		    !same_callsites(cur_st->parent, cur_st)) {
7960 			verbose(env, "bug: bad parent state for iter next call");
7961 			return -EFAULT;
7962 		}
7963 		/* Note cur_st->parent in the call below, it is necessary to skip
7964 		 * checkpoint created for cur_st by is_state_visited()
7965 		 * right at this instruction.
7966 		 */
7967 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7968 		/* branch out active iter state */
7969 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7970 		if (!queued_st)
7971 			return -ENOMEM;
7972 
7973 		queued_iter = get_iter_from_state(queued_st, meta);
7974 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7975 		queued_iter->iter.depth++;
7976 		if (prev_st)
7977 			widen_imprecise_scalars(env, prev_st, queued_st);
7978 
7979 		queued_fr = queued_st->frame[queued_st->curframe];
7980 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7981 	}
7982 
7983 	/* switch to DRAINED state, but keep the depth unchanged */
7984 	/* mark current iter state as drained and assume returned NULL */
7985 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7986 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7987 
7988 	return 0;
7989 }
7990 
7991 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7992 {
7993 	return type == ARG_CONST_SIZE ||
7994 	       type == ARG_CONST_SIZE_OR_ZERO;
7995 }
7996 
7997 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7998 {
7999 	return base_type(type) == ARG_PTR_TO_MEM &&
8000 	       type & MEM_UNINIT;
8001 }
8002 
8003 static bool arg_type_is_release(enum bpf_arg_type type)
8004 {
8005 	return type & OBJ_RELEASE;
8006 }
8007 
8008 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8009 {
8010 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8011 }
8012 
8013 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8014 				 const struct bpf_call_arg_meta *meta,
8015 				 enum bpf_arg_type *arg_type)
8016 {
8017 	if (!meta->map_ptr) {
8018 		/* kernel subsystem misconfigured verifier */
8019 		verbose(env, "invalid map_ptr to access map->type\n");
8020 		return -EACCES;
8021 	}
8022 
8023 	switch (meta->map_ptr->map_type) {
8024 	case BPF_MAP_TYPE_SOCKMAP:
8025 	case BPF_MAP_TYPE_SOCKHASH:
8026 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8027 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8028 		} else {
8029 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8030 			return -EINVAL;
8031 		}
8032 		break;
8033 	case BPF_MAP_TYPE_BLOOM_FILTER:
8034 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8035 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8036 		break;
8037 	default:
8038 		break;
8039 	}
8040 	return 0;
8041 }
8042 
8043 struct bpf_reg_types {
8044 	const enum bpf_reg_type types[10];
8045 	u32 *btf_id;
8046 };
8047 
8048 static const struct bpf_reg_types sock_types = {
8049 	.types = {
8050 		PTR_TO_SOCK_COMMON,
8051 		PTR_TO_SOCKET,
8052 		PTR_TO_TCP_SOCK,
8053 		PTR_TO_XDP_SOCK,
8054 	},
8055 };
8056 
8057 #ifdef CONFIG_NET
8058 static const struct bpf_reg_types btf_id_sock_common_types = {
8059 	.types = {
8060 		PTR_TO_SOCK_COMMON,
8061 		PTR_TO_SOCKET,
8062 		PTR_TO_TCP_SOCK,
8063 		PTR_TO_XDP_SOCK,
8064 		PTR_TO_BTF_ID,
8065 		PTR_TO_BTF_ID | PTR_TRUSTED,
8066 	},
8067 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8068 };
8069 #endif
8070 
8071 static const struct bpf_reg_types mem_types = {
8072 	.types = {
8073 		PTR_TO_STACK,
8074 		PTR_TO_PACKET,
8075 		PTR_TO_PACKET_META,
8076 		PTR_TO_MAP_KEY,
8077 		PTR_TO_MAP_VALUE,
8078 		PTR_TO_MEM,
8079 		PTR_TO_MEM | MEM_RINGBUF,
8080 		PTR_TO_BUF,
8081 		PTR_TO_BTF_ID | PTR_TRUSTED,
8082 	},
8083 };
8084 
8085 static const struct bpf_reg_types spin_lock_types = {
8086 	.types = {
8087 		PTR_TO_MAP_VALUE,
8088 		PTR_TO_BTF_ID | MEM_ALLOC,
8089 	}
8090 };
8091 
8092 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8093 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8094 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8095 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8096 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8097 static const struct bpf_reg_types btf_ptr_types = {
8098 	.types = {
8099 		PTR_TO_BTF_ID,
8100 		PTR_TO_BTF_ID | PTR_TRUSTED,
8101 		PTR_TO_BTF_ID | MEM_RCU,
8102 	},
8103 };
8104 static const struct bpf_reg_types percpu_btf_ptr_types = {
8105 	.types = {
8106 		PTR_TO_BTF_ID | MEM_PERCPU,
8107 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8108 	}
8109 };
8110 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8111 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8112 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8113 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8114 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8115 static const struct bpf_reg_types dynptr_types = {
8116 	.types = {
8117 		PTR_TO_STACK,
8118 		CONST_PTR_TO_DYNPTR,
8119 	}
8120 };
8121 
8122 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8123 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8124 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8125 	[ARG_CONST_SIZE]		= &scalar_types,
8126 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8127 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8128 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8129 	[ARG_PTR_TO_CTX]		= &context_types,
8130 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8131 #ifdef CONFIG_NET
8132 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8133 #endif
8134 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8135 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8136 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8137 	[ARG_PTR_TO_MEM]		= &mem_types,
8138 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8139 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8140 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8141 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8142 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8143 	[ARG_PTR_TO_TIMER]		= &timer_types,
8144 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8145 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8146 };
8147 
8148 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8149 			  enum bpf_arg_type arg_type,
8150 			  const u32 *arg_btf_id,
8151 			  struct bpf_call_arg_meta *meta)
8152 {
8153 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8154 	enum bpf_reg_type expected, type = reg->type;
8155 	const struct bpf_reg_types *compatible;
8156 	int i, j;
8157 
8158 	compatible = compatible_reg_types[base_type(arg_type)];
8159 	if (!compatible) {
8160 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8161 		return -EFAULT;
8162 	}
8163 
8164 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8165 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8166 	 *
8167 	 * Same for MAYBE_NULL:
8168 	 *
8169 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8170 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8171 	 *
8172 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8173 	 *
8174 	 * Therefore we fold these flags depending on the arg_type before comparison.
8175 	 */
8176 	if (arg_type & MEM_RDONLY)
8177 		type &= ~MEM_RDONLY;
8178 	if (arg_type & PTR_MAYBE_NULL)
8179 		type &= ~PTR_MAYBE_NULL;
8180 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8181 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8182 
8183 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8184 		type &= ~MEM_ALLOC;
8185 
8186 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8187 		expected = compatible->types[i];
8188 		if (expected == NOT_INIT)
8189 			break;
8190 
8191 		if (type == expected)
8192 			goto found;
8193 	}
8194 
8195 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8196 	for (j = 0; j + 1 < i; j++)
8197 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8198 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8199 	return -EACCES;
8200 
8201 found:
8202 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8203 		return 0;
8204 
8205 	if (compatible == &mem_types) {
8206 		if (!(arg_type & MEM_RDONLY)) {
8207 			verbose(env,
8208 				"%s() may write into memory pointed by R%d type=%s\n",
8209 				func_id_name(meta->func_id),
8210 				regno, reg_type_str(env, reg->type));
8211 			return -EACCES;
8212 		}
8213 		return 0;
8214 	}
8215 
8216 	switch ((int)reg->type) {
8217 	case PTR_TO_BTF_ID:
8218 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8219 	case PTR_TO_BTF_ID | MEM_RCU:
8220 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8221 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8222 	{
8223 		/* For bpf_sk_release, it needs to match against first member
8224 		 * 'struct sock_common', hence make an exception for it. This
8225 		 * allows bpf_sk_release to work for multiple socket types.
8226 		 */
8227 		bool strict_type_match = arg_type_is_release(arg_type) &&
8228 					 meta->func_id != BPF_FUNC_sk_release;
8229 
8230 		if (type_may_be_null(reg->type) &&
8231 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8232 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8233 			return -EACCES;
8234 		}
8235 
8236 		if (!arg_btf_id) {
8237 			if (!compatible->btf_id) {
8238 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8239 				return -EFAULT;
8240 			}
8241 			arg_btf_id = compatible->btf_id;
8242 		}
8243 
8244 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8245 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8246 				return -EACCES;
8247 		} else {
8248 			if (arg_btf_id == BPF_PTR_POISON) {
8249 				verbose(env, "verifier internal error:");
8250 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8251 					regno);
8252 				return -EACCES;
8253 			}
8254 
8255 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8256 						  btf_vmlinux, *arg_btf_id,
8257 						  strict_type_match)) {
8258 				verbose(env, "R%d is of type %s but %s is expected\n",
8259 					regno, btf_type_name(reg->btf, reg->btf_id),
8260 					btf_type_name(btf_vmlinux, *arg_btf_id));
8261 				return -EACCES;
8262 			}
8263 		}
8264 		break;
8265 	}
8266 	case PTR_TO_BTF_ID | MEM_ALLOC:
8267 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8268 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8269 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8270 			return -EFAULT;
8271 		}
8272 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8273 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8274 				return -EACCES;
8275 		}
8276 		break;
8277 	case PTR_TO_BTF_ID | MEM_PERCPU:
8278 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8279 		/* Handled by helper specific checks */
8280 		break;
8281 	default:
8282 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8283 		return -EFAULT;
8284 	}
8285 	return 0;
8286 }
8287 
8288 static struct btf_field *
8289 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8290 {
8291 	struct btf_field *field;
8292 	struct btf_record *rec;
8293 
8294 	rec = reg_btf_record(reg);
8295 	if (!rec)
8296 		return NULL;
8297 
8298 	field = btf_record_find(rec, off, fields);
8299 	if (!field)
8300 		return NULL;
8301 
8302 	return field;
8303 }
8304 
8305 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8306 			   const struct bpf_reg_state *reg, int regno,
8307 			   enum bpf_arg_type arg_type)
8308 {
8309 	u32 type = reg->type;
8310 
8311 	/* When referenced register is passed to release function, its fixed
8312 	 * offset must be 0.
8313 	 *
8314 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8315 	 * meta->release_regno.
8316 	 */
8317 	if (arg_type_is_release(arg_type)) {
8318 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8319 		 * may not directly point to the object being released, but to
8320 		 * dynptr pointing to such object, which might be at some offset
8321 		 * on the stack. In that case, we simply to fallback to the
8322 		 * default handling.
8323 		 */
8324 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8325 			return 0;
8326 
8327 		/* Doing check_ptr_off_reg check for the offset will catch this
8328 		 * because fixed_off_ok is false, but checking here allows us
8329 		 * to give the user a better error message.
8330 		 */
8331 		if (reg->off) {
8332 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8333 				regno);
8334 			return -EINVAL;
8335 		}
8336 		return __check_ptr_off_reg(env, reg, regno, false);
8337 	}
8338 
8339 	switch (type) {
8340 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8341 	case PTR_TO_STACK:
8342 	case PTR_TO_PACKET:
8343 	case PTR_TO_PACKET_META:
8344 	case PTR_TO_MAP_KEY:
8345 	case PTR_TO_MAP_VALUE:
8346 	case PTR_TO_MEM:
8347 	case PTR_TO_MEM | MEM_RDONLY:
8348 	case PTR_TO_MEM | MEM_RINGBUF:
8349 	case PTR_TO_BUF:
8350 	case PTR_TO_BUF | MEM_RDONLY:
8351 	case SCALAR_VALUE:
8352 		return 0;
8353 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8354 	 * fixed offset.
8355 	 */
8356 	case PTR_TO_BTF_ID:
8357 	case PTR_TO_BTF_ID | MEM_ALLOC:
8358 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8359 	case PTR_TO_BTF_ID | MEM_RCU:
8360 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8361 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8362 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8363 		 * its fixed offset must be 0. In the other cases, fixed offset
8364 		 * can be non-zero. This was already checked above. So pass
8365 		 * fixed_off_ok as true to allow fixed offset for all other
8366 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8367 		 * still need to do checks instead of returning.
8368 		 */
8369 		return __check_ptr_off_reg(env, reg, regno, true);
8370 	default:
8371 		return __check_ptr_off_reg(env, reg, regno, false);
8372 	}
8373 }
8374 
8375 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8376 						const struct bpf_func_proto *fn,
8377 						struct bpf_reg_state *regs)
8378 {
8379 	struct bpf_reg_state *state = NULL;
8380 	int i;
8381 
8382 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8383 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8384 			if (state) {
8385 				verbose(env, "verifier internal error: multiple dynptr args\n");
8386 				return NULL;
8387 			}
8388 			state = &regs[BPF_REG_1 + i];
8389 		}
8390 
8391 	if (!state)
8392 		verbose(env, "verifier internal error: no dynptr arg found\n");
8393 
8394 	return state;
8395 }
8396 
8397 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8398 {
8399 	struct bpf_func_state *state = func(env, reg);
8400 	int spi;
8401 
8402 	if (reg->type == CONST_PTR_TO_DYNPTR)
8403 		return reg->id;
8404 	spi = dynptr_get_spi(env, reg);
8405 	if (spi < 0)
8406 		return spi;
8407 	return state->stack[spi].spilled_ptr.id;
8408 }
8409 
8410 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8411 {
8412 	struct bpf_func_state *state = func(env, reg);
8413 	int spi;
8414 
8415 	if (reg->type == CONST_PTR_TO_DYNPTR)
8416 		return reg->ref_obj_id;
8417 	spi = dynptr_get_spi(env, reg);
8418 	if (spi < 0)
8419 		return spi;
8420 	return state->stack[spi].spilled_ptr.ref_obj_id;
8421 }
8422 
8423 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8424 					    struct bpf_reg_state *reg)
8425 {
8426 	struct bpf_func_state *state = func(env, reg);
8427 	int spi;
8428 
8429 	if (reg->type == CONST_PTR_TO_DYNPTR)
8430 		return reg->dynptr.type;
8431 
8432 	spi = __get_spi(reg->off);
8433 	if (spi < 0) {
8434 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8435 		return BPF_DYNPTR_TYPE_INVALID;
8436 	}
8437 
8438 	return state->stack[spi].spilled_ptr.dynptr.type;
8439 }
8440 
8441 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8442 			  struct bpf_call_arg_meta *meta,
8443 			  const struct bpf_func_proto *fn,
8444 			  int insn_idx)
8445 {
8446 	u32 regno = BPF_REG_1 + arg;
8447 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8448 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8449 	enum bpf_reg_type type = reg->type;
8450 	u32 *arg_btf_id = NULL;
8451 	int err = 0;
8452 
8453 	if (arg_type == ARG_DONTCARE)
8454 		return 0;
8455 
8456 	err = check_reg_arg(env, regno, SRC_OP);
8457 	if (err)
8458 		return err;
8459 
8460 	if (arg_type == ARG_ANYTHING) {
8461 		if (is_pointer_value(env, regno)) {
8462 			verbose(env, "R%d leaks addr into helper function\n",
8463 				regno);
8464 			return -EACCES;
8465 		}
8466 		return 0;
8467 	}
8468 
8469 	if (type_is_pkt_pointer(type) &&
8470 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8471 		verbose(env, "helper access to the packet is not allowed\n");
8472 		return -EACCES;
8473 	}
8474 
8475 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8476 		err = resolve_map_arg_type(env, meta, &arg_type);
8477 		if (err)
8478 			return err;
8479 	}
8480 
8481 	if (register_is_null(reg) && type_may_be_null(arg_type))
8482 		/* A NULL register has a SCALAR_VALUE type, so skip
8483 		 * type checking.
8484 		 */
8485 		goto skip_type_check;
8486 
8487 	/* arg_btf_id and arg_size are in a union. */
8488 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8489 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8490 		arg_btf_id = fn->arg_btf_id[arg];
8491 
8492 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8493 	if (err)
8494 		return err;
8495 
8496 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8497 	if (err)
8498 		return err;
8499 
8500 skip_type_check:
8501 	if (arg_type_is_release(arg_type)) {
8502 		if (arg_type_is_dynptr(arg_type)) {
8503 			struct bpf_func_state *state = func(env, reg);
8504 			int spi;
8505 
8506 			/* Only dynptr created on stack can be released, thus
8507 			 * the get_spi and stack state checks for spilled_ptr
8508 			 * should only be done before process_dynptr_func for
8509 			 * PTR_TO_STACK.
8510 			 */
8511 			if (reg->type == PTR_TO_STACK) {
8512 				spi = dynptr_get_spi(env, reg);
8513 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8514 					verbose(env, "arg %d is an unacquired reference\n", regno);
8515 					return -EINVAL;
8516 				}
8517 			} else {
8518 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8519 				return -EINVAL;
8520 			}
8521 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8522 			verbose(env, "R%d must be referenced when passed to release function\n",
8523 				regno);
8524 			return -EINVAL;
8525 		}
8526 		if (meta->release_regno) {
8527 			verbose(env, "verifier internal error: more than one release argument\n");
8528 			return -EFAULT;
8529 		}
8530 		meta->release_regno = regno;
8531 	}
8532 
8533 	if (reg->ref_obj_id) {
8534 		if (meta->ref_obj_id) {
8535 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8536 				regno, reg->ref_obj_id,
8537 				meta->ref_obj_id);
8538 			return -EFAULT;
8539 		}
8540 		meta->ref_obj_id = reg->ref_obj_id;
8541 	}
8542 
8543 	switch (base_type(arg_type)) {
8544 	case ARG_CONST_MAP_PTR:
8545 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8546 		if (meta->map_ptr) {
8547 			/* Use map_uid (which is unique id of inner map) to reject:
8548 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8549 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8550 			 * if (inner_map1 && inner_map2) {
8551 			 *     timer = bpf_map_lookup_elem(inner_map1);
8552 			 *     if (timer)
8553 			 *         // mismatch would have been allowed
8554 			 *         bpf_timer_init(timer, inner_map2);
8555 			 * }
8556 			 *
8557 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8558 			 */
8559 			if (meta->map_ptr != reg->map_ptr ||
8560 			    meta->map_uid != reg->map_uid) {
8561 				verbose(env,
8562 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8563 					meta->map_uid, reg->map_uid);
8564 				return -EINVAL;
8565 			}
8566 		}
8567 		meta->map_ptr = reg->map_ptr;
8568 		meta->map_uid = reg->map_uid;
8569 		break;
8570 	case ARG_PTR_TO_MAP_KEY:
8571 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8572 		 * check that [key, key + map->key_size) are within
8573 		 * stack limits and initialized
8574 		 */
8575 		if (!meta->map_ptr) {
8576 			/* in function declaration map_ptr must come before
8577 			 * map_key, so that it's verified and known before
8578 			 * we have to check map_key here. Otherwise it means
8579 			 * that kernel subsystem misconfigured verifier
8580 			 */
8581 			verbose(env, "invalid map_ptr to access map->key\n");
8582 			return -EACCES;
8583 		}
8584 		err = check_helper_mem_access(env, regno,
8585 					      meta->map_ptr->key_size, false,
8586 					      NULL);
8587 		break;
8588 	case ARG_PTR_TO_MAP_VALUE:
8589 		if (type_may_be_null(arg_type) && register_is_null(reg))
8590 			return 0;
8591 
8592 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8593 		 * check [value, value + map->value_size) validity
8594 		 */
8595 		if (!meta->map_ptr) {
8596 			/* kernel subsystem misconfigured verifier */
8597 			verbose(env, "invalid map_ptr to access map->value\n");
8598 			return -EACCES;
8599 		}
8600 		meta->raw_mode = arg_type & MEM_UNINIT;
8601 		err = check_helper_mem_access(env, regno,
8602 					      meta->map_ptr->value_size, false,
8603 					      meta);
8604 		break;
8605 	case ARG_PTR_TO_PERCPU_BTF_ID:
8606 		if (!reg->btf_id) {
8607 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8608 			return -EACCES;
8609 		}
8610 		meta->ret_btf = reg->btf;
8611 		meta->ret_btf_id = reg->btf_id;
8612 		break;
8613 	case ARG_PTR_TO_SPIN_LOCK:
8614 		if (in_rbtree_lock_required_cb(env)) {
8615 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8616 			return -EACCES;
8617 		}
8618 		if (meta->func_id == BPF_FUNC_spin_lock) {
8619 			err = process_spin_lock(env, regno, true);
8620 			if (err)
8621 				return err;
8622 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8623 			err = process_spin_lock(env, regno, false);
8624 			if (err)
8625 				return err;
8626 		} else {
8627 			verbose(env, "verifier internal error\n");
8628 			return -EFAULT;
8629 		}
8630 		break;
8631 	case ARG_PTR_TO_TIMER:
8632 		err = process_timer_func(env, regno, meta);
8633 		if (err)
8634 			return err;
8635 		break;
8636 	case ARG_PTR_TO_FUNC:
8637 		meta->subprogno = reg->subprogno;
8638 		break;
8639 	case ARG_PTR_TO_MEM:
8640 		/* The access to this pointer is only checked when we hit the
8641 		 * next is_mem_size argument below.
8642 		 */
8643 		meta->raw_mode = arg_type & MEM_UNINIT;
8644 		if (arg_type & MEM_FIXED_SIZE) {
8645 			err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
8646 			if (err)
8647 				return err;
8648 			if (arg_type & MEM_ALIGNED)
8649 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8650 		}
8651 		break;
8652 	case ARG_CONST_SIZE:
8653 		err = check_mem_size_reg(env, reg, regno, false, meta);
8654 		break;
8655 	case ARG_CONST_SIZE_OR_ZERO:
8656 		err = check_mem_size_reg(env, reg, regno, true, meta);
8657 		break;
8658 	case ARG_PTR_TO_DYNPTR:
8659 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8660 		if (err)
8661 			return err;
8662 		break;
8663 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8664 		if (!tnum_is_const(reg->var_off)) {
8665 			verbose(env, "R%d is not a known constant'\n",
8666 				regno);
8667 			return -EACCES;
8668 		}
8669 		meta->mem_size = reg->var_off.value;
8670 		err = mark_chain_precision(env, regno);
8671 		if (err)
8672 			return err;
8673 		break;
8674 	case ARG_PTR_TO_CONST_STR:
8675 	{
8676 		struct bpf_map *map = reg->map_ptr;
8677 		int map_off;
8678 		u64 map_addr;
8679 		char *str_ptr;
8680 
8681 		if (!bpf_map_is_rdonly(map)) {
8682 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8683 			return -EACCES;
8684 		}
8685 
8686 		if (!tnum_is_const(reg->var_off)) {
8687 			verbose(env, "R%d is not a constant address'\n", regno);
8688 			return -EACCES;
8689 		}
8690 
8691 		if (!map->ops->map_direct_value_addr) {
8692 			verbose(env, "no direct value access support for this map type\n");
8693 			return -EACCES;
8694 		}
8695 
8696 		err = check_map_access(env, regno, reg->off,
8697 				       map->value_size - reg->off, false,
8698 				       ACCESS_HELPER);
8699 		if (err)
8700 			return err;
8701 
8702 		map_off = reg->off + reg->var_off.value;
8703 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8704 		if (err) {
8705 			verbose(env, "direct value access on string failed\n");
8706 			return err;
8707 		}
8708 
8709 		str_ptr = (char *)(long)(map_addr);
8710 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8711 			verbose(env, "string is not zero-terminated\n");
8712 			return -EINVAL;
8713 		}
8714 		break;
8715 	}
8716 	case ARG_PTR_TO_KPTR:
8717 		err = process_kptr_func(env, regno, meta);
8718 		if (err)
8719 			return err;
8720 		break;
8721 	}
8722 
8723 	return err;
8724 }
8725 
8726 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8727 {
8728 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8729 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8730 
8731 	if (func_id != BPF_FUNC_map_update_elem &&
8732 	    func_id != BPF_FUNC_map_delete_elem)
8733 		return false;
8734 
8735 	/* It's not possible to get access to a locked struct sock in these
8736 	 * contexts, so updating is safe.
8737 	 */
8738 	switch (type) {
8739 	case BPF_PROG_TYPE_TRACING:
8740 		if (eatype == BPF_TRACE_ITER)
8741 			return true;
8742 		break;
8743 	case BPF_PROG_TYPE_SOCK_OPS:
8744 		/* map_update allowed only via dedicated helpers with event type checks */
8745 		if (func_id == BPF_FUNC_map_delete_elem)
8746 			return true;
8747 		break;
8748 	case BPF_PROG_TYPE_SOCKET_FILTER:
8749 	case BPF_PROG_TYPE_SCHED_CLS:
8750 	case BPF_PROG_TYPE_SCHED_ACT:
8751 	case BPF_PROG_TYPE_XDP:
8752 	case BPF_PROG_TYPE_SK_REUSEPORT:
8753 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8754 	case BPF_PROG_TYPE_SK_LOOKUP:
8755 		return true;
8756 	default:
8757 		break;
8758 	}
8759 
8760 	verbose(env, "cannot update sockmap in this context\n");
8761 	return false;
8762 }
8763 
8764 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8765 {
8766 	return env->prog->jit_requested &&
8767 	       bpf_jit_supports_subprog_tailcalls();
8768 }
8769 
8770 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8771 					struct bpf_map *map, int func_id)
8772 {
8773 	if (!map)
8774 		return 0;
8775 
8776 	/* We need a two way check, first is from map perspective ... */
8777 	switch (map->map_type) {
8778 	case BPF_MAP_TYPE_PROG_ARRAY:
8779 		if (func_id != BPF_FUNC_tail_call)
8780 			goto error;
8781 		break;
8782 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8783 		if (func_id != BPF_FUNC_perf_event_read &&
8784 		    func_id != BPF_FUNC_perf_event_output &&
8785 		    func_id != BPF_FUNC_skb_output &&
8786 		    func_id != BPF_FUNC_perf_event_read_value &&
8787 		    func_id != BPF_FUNC_xdp_output)
8788 			goto error;
8789 		break;
8790 	case BPF_MAP_TYPE_RINGBUF:
8791 		if (func_id != BPF_FUNC_ringbuf_output &&
8792 		    func_id != BPF_FUNC_ringbuf_reserve &&
8793 		    func_id != BPF_FUNC_ringbuf_query &&
8794 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8795 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8796 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8797 			goto error;
8798 		break;
8799 	case BPF_MAP_TYPE_USER_RINGBUF:
8800 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8801 			goto error;
8802 		break;
8803 	case BPF_MAP_TYPE_STACK_TRACE:
8804 		if (func_id != BPF_FUNC_get_stackid)
8805 			goto error;
8806 		break;
8807 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8808 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8809 		    func_id != BPF_FUNC_current_task_under_cgroup)
8810 			goto error;
8811 		break;
8812 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8813 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8814 		if (func_id != BPF_FUNC_get_local_storage)
8815 			goto error;
8816 		break;
8817 	case BPF_MAP_TYPE_DEVMAP:
8818 	case BPF_MAP_TYPE_DEVMAP_HASH:
8819 		if (func_id != BPF_FUNC_redirect_map &&
8820 		    func_id != BPF_FUNC_map_lookup_elem)
8821 			goto error;
8822 		break;
8823 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8824 	 * appear.
8825 	 */
8826 	case BPF_MAP_TYPE_CPUMAP:
8827 		if (func_id != BPF_FUNC_redirect_map)
8828 			goto error;
8829 		break;
8830 	case BPF_MAP_TYPE_XSKMAP:
8831 		if (func_id != BPF_FUNC_redirect_map &&
8832 		    func_id != BPF_FUNC_map_lookup_elem)
8833 			goto error;
8834 		break;
8835 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8836 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8837 		if (func_id != BPF_FUNC_map_lookup_elem)
8838 			goto error;
8839 		break;
8840 	case BPF_MAP_TYPE_SOCKMAP:
8841 		if (func_id != BPF_FUNC_sk_redirect_map &&
8842 		    func_id != BPF_FUNC_sock_map_update &&
8843 		    func_id != BPF_FUNC_msg_redirect_map &&
8844 		    func_id != BPF_FUNC_sk_select_reuseport &&
8845 		    func_id != BPF_FUNC_map_lookup_elem &&
8846 		    !may_update_sockmap(env, func_id))
8847 			goto error;
8848 		break;
8849 	case BPF_MAP_TYPE_SOCKHASH:
8850 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8851 		    func_id != BPF_FUNC_sock_hash_update &&
8852 		    func_id != BPF_FUNC_msg_redirect_hash &&
8853 		    func_id != BPF_FUNC_sk_select_reuseport &&
8854 		    func_id != BPF_FUNC_map_lookup_elem &&
8855 		    !may_update_sockmap(env, func_id))
8856 			goto error;
8857 		break;
8858 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8859 		if (func_id != BPF_FUNC_sk_select_reuseport)
8860 			goto error;
8861 		break;
8862 	case BPF_MAP_TYPE_QUEUE:
8863 	case BPF_MAP_TYPE_STACK:
8864 		if (func_id != BPF_FUNC_map_peek_elem &&
8865 		    func_id != BPF_FUNC_map_pop_elem &&
8866 		    func_id != BPF_FUNC_map_push_elem)
8867 			goto error;
8868 		break;
8869 	case BPF_MAP_TYPE_SK_STORAGE:
8870 		if (func_id != BPF_FUNC_sk_storage_get &&
8871 		    func_id != BPF_FUNC_sk_storage_delete &&
8872 		    func_id != BPF_FUNC_kptr_xchg)
8873 			goto error;
8874 		break;
8875 	case BPF_MAP_TYPE_INODE_STORAGE:
8876 		if (func_id != BPF_FUNC_inode_storage_get &&
8877 		    func_id != BPF_FUNC_inode_storage_delete &&
8878 		    func_id != BPF_FUNC_kptr_xchg)
8879 			goto error;
8880 		break;
8881 	case BPF_MAP_TYPE_TASK_STORAGE:
8882 		if (func_id != BPF_FUNC_task_storage_get &&
8883 		    func_id != BPF_FUNC_task_storage_delete &&
8884 		    func_id != BPF_FUNC_kptr_xchg)
8885 			goto error;
8886 		break;
8887 	case BPF_MAP_TYPE_CGRP_STORAGE:
8888 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8889 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8890 		    func_id != BPF_FUNC_kptr_xchg)
8891 			goto error;
8892 		break;
8893 	case BPF_MAP_TYPE_BLOOM_FILTER:
8894 		if (func_id != BPF_FUNC_map_peek_elem &&
8895 		    func_id != BPF_FUNC_map_push_elem)
8896 			goto error;
8897 		break;
8898 	default:
8899 		break;
8900 	}
8901 
8902 	/* ... and second from the function itself. */
8903 	switch (func_id) {
8904 	case BPF_FUNC_tail_call:
8905 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8906 			goto error;
8907 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8908 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8909 			return -EINVAL;
8910 		}
8911 		break;
8912 	case BPF_FUNC_perf_event_read:
8913 	case BPF_FUNC_perf_event_output:
8914 	case BPF_FUNC_perf_event_read_value:
8915 	case BPF_FUNC_skb_output:
8916 	case BPF_FUNC_xdp_output:
8917 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8918 			goto error;
8919 		break;
8920 	case BPF_FUNC_ringbuf_output:
8921 	case BPF_FUNC_ringbuf_reserve:
8922 	case BPF_FUNC_ringbuf_query:
8923 	case BPF_FUNC_ringbuf_reserve_dynptr:
8924 	case BPF_FUNC_ringbuf_submit_dynptr:
8925 	case BPF_FUNC_ringbuf_discard_dynptr:
8926 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8927 			goto error;
8928 		break;
8929 	case BPF_FUNC_user_ringbuf_drain:
8930 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8931 			goto error;
8932 		break;
8933 	case BPF_FUNC_get_stackid:
8934 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8935 			goto error;
8936 		break;
8937 	case BPF_FUNC_current_task_under_cgroup:
8938 	case BPF_FUNC_skb_under_cgroup:
8939 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8940 			goto error;
8941 		break;
8942 	case BPF_FUNC_redirect_map:
8943 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8944 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8945 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8946 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8947 			goto error;
8948 		break;
8949 	case BPF_FUNC_sk_redirect_map:
8950 	case BPF_FUNC_msg_redirect_map:
8951 	case BPF_FUNC_sock_map_update:
8952 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8953 			goto error;
8954 		break;
8955 	case BPF_FUNC_sk_redirect_hash:
8956 	case BPF_FUNC_msg_redirect_hash:
8957 	case BPF_FUNC_sock_hash_update:
8958 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8959 			goto error;
8960 		break;
8961 	case BPF_FUNC_get_local_storage:
8962 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8963 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8964 			goto error;
8965 		break;
8966 	case BPF_FUNC_sk_select_reuseport:
8967 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8968 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8969 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8970 			goto error;
8971 		break;
8972 	case BPF_FUNC_map_pop_elem:
8973 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8974 		    map->map_type != BPF_MAP_TYPE_STACK)
8975 			goto error;
8976 		break;
8977 	case BPF_FUNC_map_peek_elem:
8978 	case BPF_FUNC_map_push_elem:
8979 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8980 		    map->map_type != BPF_MAP_TYPE_STACK &&
8981 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8982 			goto error;
8983 		break;
8984 	case BPF_FUNC_map_lookup_percpu_elem:
8985 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8986 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8987 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8988 			goto error;
8989 		break;
8990 	case BPF_FUNC_sk_storage_get:
8991 	case BPF_FUNC_sk_storage_delete:
8992 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8993 			goto error;
8994 		break;
8995 	case BPF_FUNC_inode_storage_get:
8996 	case BPF_FUNC_inode_storage_delete:
8997 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8998 			goto error;
8999 		break;
9000 	case BPF_FUNC_task_storage_get:
9001 	case BPF_FUNC_task_storage_delete:
9002 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9003 			goto error;
9004 		break;
9005 	case BPF_FUNC_cgrp_storage_get:
9006 	case BPF_FUNC_cgrp_storage_delete:
9007 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9008 			goto error;
9009 		break;
9010 	default:
9011 		break;
9012 	}
9013 
9014 	return 0;
9015 error:
9016 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9017 		map->map_type, func_id_name(func_id), func_id);
9018 	return -EINVAL;
9019 }
9020 
9021 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9022 {
9023 	int count = 0;
9024 
9025 	if (arg_type_is_raw_mem(fn->arg1_type))
9026 		count++;
9027 	if (arg_type_is_raw_mem(fn->arg2_type))
9028 		count++;
9029 	if (arg_type_is_raw_mem(fn->arg3_type))
9030 		count++;
9031 	if (arg_type_is_raw_mem(fn->arg4_type))
9032 		count++;
9033 	if (arg_type_is_raw_mem(fn->arg5_type))
9034 		count++;
9035 
9036 	/* We only support one arg being in raw mode at the moment,
9037 	 * which is sufficient for the helper functions we have
9038 	 * right now.
9039 	 */
9040 	return count <= 1;
9041 }
9042 
9043 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9044 {
9045 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9046 	bool has_size = fn->arg_size[arg] != 0;
9047 	bool is_next_size = false;
9048 
9049 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9050 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9051 
9052 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9053 		return is_next_size;
9054 
9055 	return has_size == is_next_size || is_next_size == is_fixed;
9056 }
9057 
9058 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9059 {
9060 	/* bpf_xxx(..., buf, len) call will access 'len'
9061 	 * bytes from memory 'buf'. Both arg types need
9062 	 * to be paired, so make sure there's no buggy
9063 	 * helper function specification.
9064 	 */
9065 	if (arg_type_is_mem_size(fn->arg1_type) ||
9066 	    check_args_pair_invalid(fn, 0) ||
9067 	    check_args_pair_invalid(fn, 1) ||
9068 	    check_args_pair_invalid(fn, 2) ||
9069 	    check_args_pair_invalid(fn, 3) ||
9070 	    check_args_pair_invalid(fn, 4))
9071 		return false;
9072 
9073 	return true;
9074 }
9075 
9076 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9077 {
9078 	int i;
9079 
9080 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9081 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9082 			return !!fn->arg_btf_id[i];
9083 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9084 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9085 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9086 		    /* arg_btf_id and arg_size are in a union. */
9087 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9088 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9089 			return false;
9090 	}
9091 
9092 	return true;
9093 }
9094 
9095 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9096 {
9097 	return check_raw_mode_ok(fn) &&
9098 	       check_arg_pair_ok(fn) &&
9099 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9100 }
9101 
9102 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9103  * are now invalid, so turn them into unknown SCALAR_VALUE.
9104  *
9105  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9106  * since these slices point to packet data.
9107  */
9108 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9109 {
9110 	struct bpf_func_state *state;
9111 	struct bpf_reg_state *reg;
9112 
9113 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9114 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9115 			mark_reg_invalid(env, reg);
9116 	}));
9117 }
9118 
9119 enum {
9120 	AT_PKT_END = -1,
9121 	BEYOND_PKT_END = -2,
9122 };
9123 
9124 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9125 {
9126 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9127 	struct bpf_reg_state *reg = &state->regs[regn];
9128 
9129 	if (reg->type != PTR_TO_PACKET)
9130 		/* PTR_TO_PACKET_META is not supported yet */
9131 		return;
9132 
9133 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9134 	 * How far beyond pkt_end it goes is unknown.
9135 	 * if (!range_open) it's the case of pkt >= pkt_end
9136 	 * if (range_open) it's the case of pkt > pkt_end
9137 	 * hence this pointer is at least 1 byte bigger than pkt_end
9138 	 */
9139 	if (range_open)
9140 		reg->range = BEYOND_PKT_END;
9141 	else
9142 		reg->range = AT_PKT_END;
9143 }
9144 
9145 /* The pointer with the specified id has released its reference to kernel
9146  * resources. Identify all copies of the same pointer and clear the reference.
9147  */
9148 static int release_reference(struct bpf_verifier_env *env,
9149 			     int ref_obj_id)
9150 {
9151 	struct bpf_func_state *state;
9152 	struct bpf_reg_state *reg;
9153 	int err;
9154 
9155 	err = release_reference_state(cur_func(env), ref_obj_id);
9156 	if (err)
9157 		return err;
9158 
9159 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9160 		if (reg->ref_obj_id == ref_obj_id)
9161 			mark_reg_invalid(env, reg);
9162 	}));
9163 
9164 	return 0;
9165 }
9166 
9167 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9168 {
9169 	struct bpf_func_state *unused;
9170 	struct bpf_reg_state *reg;
9171 
9172 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9173 		if (type_is_non_owning_ref(reg->type))
9174 			mark_reg_invalid(env, reg);
9175 	}));
9176 }
9177 
9178 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9179 				    struct bpf_reg_state *regs)
9180 {
9181 	int i;
9182 
9183 	/* after the call registers r0 - r5 were scratched */
9184 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9185 		mark_reg_not_init(env, regs, caller_saved[i]);
9186 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9187 	}
9188 }
9189 
9190 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9191 				   struct bpf_func_state *caller,
9192 				   struct bpf_func_state *callee,
9193 				   int insn_idx);
9194 
9195 static int set_callee_state(struct bpf_verifier_env *env,
9196 			    struct bpf_func_state *caller,
9197 			    struct bpf_func_state *callee, int insn_idx);
9198 
9199 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9200 			    set_callee_state_fn set_callee_state_cb,
9201 			    struct bpf_verifier_state *state)
9202 {
9203 	struct bpf_func_state *caller, *callee;
9204 	int err;
9205 
9206 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9207 		verbose(env, "the call stack of %d frames is too deep\n",
9208 			state->curframe + 2);
9209 		return -E2BIG;
9210 	}
9211 
9212 	if (state->frame[state->curframe + 1]) {
9213 		verbose(env, "verifier bug. Frame %d already allocated\n",
9214 			state->curframe + 1);
9215 		return -EFAULT;
9216 	}
9217 
9218 	caller = state->frame[state->curframe];
9219 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9220 	if (!callee)
9221 		return -ENOMEM;
9222 	state->frame[state->curframe + 1] = callee;
9223 
9224 	/* callee cannot access r0, r6 - r9 for reading and has to write
9225 	 * into its own stack before reading from it.
9226 	 * callee can read/write into caller's stack
9227 	 */
9228 	init_func_state(env, callee,
9229 			/* remember the callsite, it will be used by bpf_exit */
9230 			callsite,
9231 			state->curframe + 1 /* frameno within this callchain */,
9232 			subprog /* subprog number within this prog */);
9233 	/* Transfer references to the callee */
9234 	err = copy_reference_state(callee, caller);
9235 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9236 	if (err)
9237 		goto err_out;
9238 
9239 	/* only increment it after check_reg_arg() finished */
9240 	state->curframe++;
9241 
9242 	return 0;
9243 
9244 err_out:
9245 	free_func_state(callee);
9246 	state->frame[state->curframe + 1] = NULL;
9247 	return err;
9248 }
9249 
9250 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9251 			      int insn_idx, int subprog,
9252 			      set_callee_state_fn set_callee_state_cb)
9253 {
9254 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9255 	struct bpf_func_state *caller, *callee;
9256 	int err;
9257 
9258 	caller = state->frame[state->curframe];
9259 	err = btf_check_subprog_call(env, subprog, caller->regs);
9260 	if (err == -EFAULT)
9261 		return err;
9262 
9263 	/* set_callee_state is used for direct subprog calls, but we are
9264 	 * interested in validating only BPF helpers that can call subprogs as
9265 	 * callbacks
9266 	 */
9267 	if (bpf_pseudo_kfunc_call(insn) &&
9268 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9269 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9270 			func_id_name(insn->imm), insn->imm);
9271 		return -EFAULT;
9272 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9273 		   !is_callback_calling_function(insn->imm)) { /* helper */
9274 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9275 			func_id_name(insn->imm), insn->imm);
9276 		return -EFAULT;
9277 	}
9278 
9279 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9280 	    insn->src_reg == 0 &&
9281 	    insn->imm == BPF_FUNC_timer_set_callback) {
9282 		struct bpf_verifier_state *async_cb;
9283 
9284 		/* there is no real recursion here. timer callbacks are async */
9285 		env->subprog_info[subprog].is_async_cb = true;
9286 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9287 					 insn_idx, subprog);
9288 		if (!async_cb)
9289 			return -EFAULT;
9290 		callee = async_cb->frame[0];
9291 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9292 
9293 		/* Convert bpf_timer_set_callback() args into timer callback args */
9294 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9295 		if (err)
9296 			return err;
9297 
9298 		return 0;
9299 	}
9300 
9301 	/* for callback functions enqueue entry to callback and
9302 	 * proceed with next instruction within current frame.
9303 	 */
9304 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9305 	if (!callback_state)
9306 		return -ENOMEM;
9307 
9308 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9309 			       callback_state);
9310 	if (err)
9311 		return err;
9312 
9313 	callback_state->callback_unroll_depth++;
9314 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9315 	caller->callback_depth = 0;
9316 	return 0;
9317 }
9318 
9319 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9320 			   int *insn_idx)
9321 {
9322 	struct bpf_verifier_state *state = env->cur_state;
9323 	struct bpf_func_state *caller;
9324 	int err, subprog, target_insn;
9325 
9326 	target_insn = *insn_idx + insn->imm + 1;
9327 	subprog = find_subprog(env, target_insn);
9328 	if (subprog < 0) {
9329 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9330 		return -EFAULT;
9331 	}
9332 
9333 	caller = state->frame[state->curframe];
9334 	err = btf_check_subprog_call(env, subprog, caller->regs);
9335 	if (err == -EFAULT)
9336 		return err;
9337 	if (subprog_is_global(env, subprog)) {
9338 		if (err) {
9339 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9340 			return err;
9341 		}
9342 
9343 		if (env->log.level & BPF_LOG_LEVEL)
9344 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9345 		clear_caller_saved_regs(env, caller->regs);
9346 
9347 		/* All global functions return a 64-bit SCALAR_VALUE */
9348 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9349 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9350 
9351 		/* continue with next insn after call */
9352 		return 0;
9353 	}
9354 
9355 	/* for regular function entry setup new frame and continue
9356 	 * from that frame.
9357 	 */
9358 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9359 	if (err)
9360 		return err;
9361 
9362 	clear_caller_saved_regs(env, caller->regs);
9363 
9364 	/* and go analyze first insn of the callee */
9365 	*insn_idx = env->subprog_info[subprog].start - 1;
9366 
9367 	if (env->log.level & BPF_LOG_LEVEL) {
9368 		verbose(env, "caller:\n");
9369 		print_verifier_state(env, caller, true);
9370 		verbose(env, "callee:\n");
9371 		print_verifier_state(env, state->frame[state->curframe], true);
9372 	}
9373 
9374 	return 0;
9375 }
9376 
9377 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9378 				   struct bpf_func_state *caller,
9379 				   struct bpf_func_state *callee)
9380 {
9381 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9382 	 *      void *callback_ctx, u64 flags);
9383 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9384 	 *      void *callback_ctx);
9385 	 */
9386 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9387 
9388 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9389 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9390 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9391 
9392 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9393 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9394 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9395 
9396 	/* pointer to stack or null */
9397 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9398 
9399 	/* unused */
9400 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9401 	return 0;
9402 }
9403 
9404 static int set_callee_state(struct bpf_verifier_env *env,
9405 			    struct bpf_func_state *caller,
9406 			    struct bpf_func_state *callee, int insn_idx)
9407 {
9408 	int i;
9409 
9410 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9411 	 * pointers, which connects us up to the liveness chain
9412 	 */
9413 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9414 		callee->regs[i] = caller->regs[i];
9415 	return 0;
9416 }
9417 
9418 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9419 				       struct bpf_func_state *caller,
9420 				       struct bpf_func_state *callee,
9421 				       int insn_idx)
9422 {
9423 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9424 	struct bpf_map *map;
9425 	int err;
9426 
9427 	if (bpf_map_ptr_poisoned(insn_aux)) {
9428 		verbose(env, "tail_call abusing map_ptr\n");
9429 		return -EINVAL;
9430 	}
9431 
9432 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9433 	if (!map->ops->map_set_for_each_callback_args ||
9434 	    !map->ops->map_for_each_callback) {
9435 		verbose(env, "callback function not allowed for map\n");
9436 		return -ENOTSUPP;
9437 	}
9438 
9439 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9440 	if (err)
9441 		return err;
9442 
9443 	callee->in_callback_fn = true;
9444 	callee->callback_ret_range = tnum_range(0, 1);
9445 	return 0;
9446 }
9447 
9448 static int set_loop_callback_state(struct bpf_verifier_env *env,
9449 				   struct bpf_func_state *caller,
9450 				   struct bpf_func_state *callee,
9451 				   int insn_idx)
9452 {
9453 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9454 	 *	    u64 flags);
9455 	 * callback_fn(u32 index, void *callback_ctx);
9456 	 */
9457 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9458 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9459 
9460 	/* unused */
9461 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9462 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9463 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9464 
9465 	callee->in_callback_fn = true;
9466 	callee->callback_ret_range = tnum_range(0, 1);
9467 	return 0;
9468 }
9469 
9470 static int set_timer_callback_state(struct bpf_verifier_env *env,
9471 				    struct bpf_func_state *caller,
9472 				    struct bpf_func_state *callee,
9473 				    int insn_idx)
9474 {
9475 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9476 
9477 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9478 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9479 	 */
9480 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9481 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9482 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9483 
9484 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9485 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9486 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9487 
9488 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9489 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9490 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9491 
9492 	/* unused */
9493 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9494 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9495 	callee->in_async_callback_fn = true;
9496 	callee->callback_ret_range = tnum_range(0, 1);
9497 	return 0;
9498 }
9499 
9500 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9501 				       struct bpf_func_state *caller,
9502 				       struct bpf_func_state *callee,
9503 				       int insn_idx)
9504 {
9505 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9506 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9507 	 * (callback_fn)(struct task_struct *task,
9508 	 *               struct vm_area_struct *vma, void *callback_ctx);
9509 	 */
9510 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9511 
9512 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9513 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9514 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9515 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9516 
9517 	/* pointer to stack or null */
9518 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9519 
9520 	/* unused */
9521 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9522 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9523 	callee->in_callback_fn = true;
9524 	callee->callback_ret_range = tnum_range(0, 1);
9525 	return 0;
9526 }
9527 
9528 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9529 					   struct bpf_func_state *caller,
9530 					   struct bpf_func_state *callee,
9531 					   int insn_idx)
9532 {
9533 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9534 	 *			  callback_ctx, u64 flags);
9535 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9536 	 */
9537 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9538 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9539 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9540 
9541 	/* unused */
9542 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9543 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9544 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9545 
9546 	callee->in_callback_fn = true;
9547 	callee->callback_ret_range = tnum_range(0, 1);
9548 	return 0;
9549 }
9550 
9551 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9552 					 struct bpf_func_state *caller,
9553 					 struct bpf_func_state *callee,
9554 					 int insn_idx)
9555 {
9556 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9557 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9558 	 *
9559 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9560 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9561 	 * by this point, so look at 'root'
9562 	 */
9563 	struct btf_field *field;
9564 
9565 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9566 				      BPF_RB_ROOT);
9567 	if (!field || !field->graph_root.value_btf_id)
9568 		return -EFAULT;
9569 
9570 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9571 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9572 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9573 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9574 
9575 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9576 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9577 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9578 	callee->in_callback_fn = true;
9579 	callee->callback_ret_range = tnum_range(0, 1);
9580 	return 0;
9581 }
9582 
9583 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9584 
9585 /* Are we currently verifying the callback for a rbtree helper that must
9586  * be called with lock held? If so, no need to complain about unreleased
9587  * lock
9588  */
9589 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9590 {
9591 	struct bpf_verifier_state *state = env->cur_state;
9592 	struct bpf_insn *insn = env->prog->insnsi;
9593 	struct bpf_func_state *callee;
9594 	int kfunc_btf_id;
9595 
9596 	if (!state->curframe)
9597 		return false;
9598 
9599 	callee = state->frame[state->curframe];
9600 
9601 	if (!callee->in_callback_fn)
9602 		return false;
9603 
9604 	kfunc_btf_id = insn[callee->callsite].imm;
9605 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9606 }
9607 
9608 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9609 {
9610 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9611 	struct bpf_func_state *caller, *callee;
9612 	struct bpf_reg_state *r0;
9613 	bool in_callback_fn;
9614 	int err;
9615 
9616 	callee = state->frame[state->curframe];
9617 	r0 = &callee->regs[BPF_REG_0];
9618 	if (r0->type == PTR_TO_STACK) {
9619 		/* technically it's ok to return caller's stack pointer
9620 		 * (or caller's caller's pointer) back to the caller,
9621 		 * since these pointers are valid. Only current stack
9622 		 * pointer will be invalid as soon as function exits,
9623 		 * but let's be conservative
9624 		 */
9625 		verbose(env, "cannot return stack pointer to the caller\n");
9626 		return -EINVAL;
9627 	}
9628 
9629 	caller = state->frame[state->curframe - 1];
9630 	if (callee->in_callback_fn) {
9631 		/* enforce R0 return value range [0, 1]. */
9632 		struct tnum range = callee->callback_ret_range;
9633 
9634 		if (r0->type != SCALAR_VALUE) {
9635 			verbose(env, "R0 not a scalar value\n");
9636 			return -EACCES;
9637 		}
9638 
9639 		/* we are going to rely on register's precise value */
9640 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9641 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9642 		if (err)
9643 			return err;
9644 
9645 		if (!tnum_in(range, r0->var_off)) {
9646 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9647 			return -EINVAL;
9648 		}
9649 		if (!calls_callback(env, callee->callsite)) {
9650 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9651 				*insn_idx, callee->callsite);
9652 			return -EFAULT;
9653 		}
9654 	} else {
9655 		/* return to the caller whatever r0 had in the callee */
9656 		caller->regs[BPF_REG_0] = *r0;
9657 	}
9658 
9659 	/* callback_fn frame should have released its own additions to parent's
9660 	 * reference state at this point, or check_reference_leak would
9661 	 * complain, hence it must be the same as the caller. There is no need
9662 	 * to copy it back.
9663 	 */
9664 	if (!callee->in_callback_fn) {
9665 		/* Transfer references to the caller */
9666 		err = copy_reference_state(caller, callee);
9667 		if (err)
9668 			return err;
9669 	}
9670 
9671 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9672 	 * there function call logic would reschedule callback visit. If iteration
9673 	 * converges is_state_visited() would prune that visit eventually.
9674 	 */
9675 	in_callback_fn = callee->in_callback_fn;
9676 	if (in_callback_fn)
9677 		*insn_idx = callee->callsite;
9678 	else
9679 		*insn_idx = callee->callsite + 1;
9680 
9681 	if (env->log.level & BPF_LOG_LEVEL) {
9682 		verbose(env, "returning from callee:\n");
9683 		print_verifier_state(env, callee, true);
9684 		verbose(env, "to caller at %d:\n", *insn_idx);
9685 		print_verifier_state(env, caller, true);
9686 	}
9687 	/* clear everything in the callee */
9688 	free_func_state(callee);
9689 	state->frame[state->curframe--] = NULL;
9690 
9691 	/* for callbacks widen imprecise scalars to make programs like below verify:
9692 	 *
9693 	 *   struct ctx { int i; }
9694 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9695 	 *   ...
9696 	 *   struct ctx = { .i = 0; }
9697 	 *   bpf_loop(100, cb, &ctx, 0);
9698 	 *
9699 	 * This is similar to what is done in process_iter_next_call() for open
9700 	 * coded iterators.
9701 	 */
9702 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9703 	if (prev_st) {
9704 		err = widen_imprecise_scalars(env, prev_st, state);
9705 		if (err)
9706 			return err;
9707 	}
9708 	return 0;
9709 }
9710 
9711 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9712 				   int func_id,
9713 				   struct bpf_call_arg_meta *meta)
9714 {
9715 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9716 
9717 	if (ret_type != RET_INTEGER)
9718 		return;
9719 
9720 	switch (func_id) {
9721 	case BPF_FUNC_get_stack:
9722 	case BPF_FUNC_get_task_stack:
9723 	case BPF_FUNC_probe_read_str:
9724 	case BPF_FUNC_probe_read_kernel_str:
9725 	case BPF_FUNC_probe_read_user_str:
9726 		ret_reg->smax_value = meta->msize_max_value;
9727 		ret_reg->s32_max_value = meta->msize_max_value;
9728 		ret_reg->smin_value = -MAX_ERRNO;
9729 		ret_reg->s32_min_value = -MAX_ERRNO;
9730 		reg_bounds_sync(ret_reg);
9731 		break;
9732 	case BPF_FUNC_get_smp_processor_id:
9733 		ret_reg->umax_value = nr_cpu_ids - 1;
9734 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9735 		ret_reg->smax_value = nr_cpu_ids - 1;
9736 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9737 		ret_reg->umin_value = 0;
9738 		ret_reg->u32_min_value = 0;
9739 		ret_reg->smin_value = 0;
9740 		ret_reg->s32_min_value = 0;
9741 		reg_bounds_sync(ret_reg);
9742 		break;
9743 	}
9744 }
9745 
9746 static int
9747 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9748 		int func_id, int insn_idx)
9749 {
9750 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9751 	struct bpf_map *map = meta->map_ptr;
9752 
9753 	if (func_id != BPF_FUNC_tail_call &&
9754 	    func_id != BPF_FUNC_map_lookup_elem &&
9755 	    func_id != BPF_FUNC_map_update_elem &&
9756 	    func_id != BPF_FUNC_map_delete_elem &&
9757 	    func_id != BPF_FUNC_map_push_elem &&
9758 	    func_id != BPF_FUNC_map_pop_elem &&
9759 	    func_id != BPF_FUNC_map_peek_elem &&
9760 	    func_id != BPF_FUNC_for_each_map_elem &&
9761 	    func_id != BPF_FUNC_redirect_map &&
9762 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9763 		return 0;
9764 
9765 	if (map == NULL) {
9766 		verbose(env, "kernel subsystem misconfigured verifier\n");
9767 		return -EINVAL;
9768 	}
9769 
9770 	/* In case of read-only, some additional restrictions
9771 	 * need to be applied in order to prevent altering the
9772 	 * state of the map from program side.
9773 	 */
9774 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9775 	    (func_id == BPF_FUNC_map_delete_elem ||
9776 	     func_id == BPF_FUNC_map_update_elem ||
9777 	     func_id == BPF_FUNC_map_push_elem ||
9778 	     func_id == BPF_FUNC_map_pop_elem)) {
9779 		verbose(env, "write into map forbidden\n");
9780 		return -EACCES;
9781 	}
9782 
9783 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9784 		bpf_map_ptr_store(aux, meta->map_ptr,
9785 				  !meta->map_ptr->bypass_spec_v1);
9786 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9787 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9788 				  !meta->map_ptr->bypass_spec_v1);
9789 	return 0;
9790 }
9791 
9792 static int
9793 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9794 		int func_id, int insn_idx)
9795 {
9796 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9797 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9798 	struct bpf_map *map = meta->map_ptr;
9799 	u64 val, max;
9800 	int err;
9801 
9802 	if (func_id != BPF_FUNC_tail_call)
9803 		return 0;
9804 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9805 		verbose(env, "kernel subsystem misconfigured verifier\n");
9806 		return -EINVAL;
9807 	}
9808 
9809 	reg = &regs[BPF_REG_3];
9810 	val = reg->var_off.value;
9811 	max = map->max_entries;
9812 
9813 	if (!(register_is_const(reg) && val < max)) {
9814 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9815 		return 0;
9816 	}
9817 
9818 	err = mark_chain_precision(env, BPF_REG_3);
9819 	if (err)
9820 		return err;
9821 	if (bpf_map_key_unseen(aux))
9822 		bpf_map_key_store(aux, val);
9823 	else if (!bpf_map_key_poisoned(aux) &&
9824 		  bpf_map_key_immediate(aux) != val)
9825 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9826 	return 0;
9827 }
9828 
9829 static int check_reference_leak(struct bpf_verifier_env *env)
9830 {
9831 	struct bpf_func_state *state = cur_func(env);
9832 	bool refs_lingering = false;
9833 	int i;
9834 
9835 	if (state->frameno && !state->in_callback_fn)
9836 		return 0;
9837 
9838 	for (i = 0; i < state->acquired_refs; i++) {
9839 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9840 			continue;
9841 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9842 			state->refs[i].id, state->refs[i].insn_idx);
9843 		refs_lingering = true;
9844 	}
9845 	return refs_lingering ? -EINVAL : 0;
9846 }
9847 
9848 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9849 				   struct bpf_reg_state *regs)
9850 {
9851 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9852 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9853 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9854 	struct bpf_bprintf_data data = {};
9855 	int err, fmt_map_off, num_args;
9856 	u64 fmt_addr;
9857 	char *fmt;
9858 
9859 	/* data must be an array of u64 */
9860 	if (data_len_reg->var_off.value % 8)
9861 		return -EINVAL;
9862 	num_args = data_len_reg->var_off.value / 8;
9863 
9864 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9865 	 * and map_direct_value_addr is set.
9866 	 */
9867 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9868 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9869 						  fmt_map_off);
9870 	if (err) {
9871 		verbose(env, "verifier bug\n");
9872 		return -EFAULT;
9873 	}
9874 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9875 
9876 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9877 	 * can focus on validating the format specifiers.
9878 	 */
9879 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9880 	if (err < 0)
9881 		verbose(env, "Invalid format string\n");
9882 
9883 	return err;
9884 }
9885 
9886 static int check_get_func_ip(struct bpf_verifier_env *env)
9887 {
9888 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9889 	int func_id = BPF_FUNC_get_func_ip;
9890 
9891 	if (type == BPF_PROG_TYPE_TRACING) {
9892 		if (!bpf_prog_has_trampoline(env->prog)) {
9893 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9894 				func_id_name(func_id), func_id);
9895 			return -ENOTSUPP;
9896 		}
9897 		return 0;
9898 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9899 		return 0;
9900 	}
9901 
9902 	verbose(env, "func %s#%d not supported for program type %d\n",
9903 		func_id_name(func_id), func_id, type);
9904 	return -ENOTSUPP;
9905 }
9906 
9907 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9908 {
9909 	return &env->insn_aux_data[env->insn_idx];
9910 }
9911 
9912 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9913 {
9914 	struct bpf_reg_state *regs = cur_regs(env);
9915 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9916 	bool reg_is_null = register_is_null(reg);
9917 
9918 	if (reg_is_null)
9919 		mark_chain_precision(env, BPF_REG_4);
9920 
9921 	return reg_is_null;
9922 }
9923 
9924 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9925 {
9926 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9927 
9928 	if (!state->initialized) {
9929 		state->initialized = 1;
9930 		state->fit_for_inline = loop_flag_is_zero(env);
9931 		state->callback_subprogno = subprogno;
9932 		return;
9933 	}
9934 
9935 	if (!state->fit_for_inline)
9936 		return;
9937 
9938 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9939 				 state->callback_subprogno == subprogno);
9940 }
9941 
9942 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9943 			     int *insn_idx_p)
9944 {
9945 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9946 	const struct bpf_func_proto *fn = NULL;
9947 	enum bpf_return_type ret_type;
9948 	enum bpf_type_flag ret_flag;
9949 	struct bpf_reg_state *regs;
9950 	struct bpf_call_arg_meta meta;
9951 	int insn_idx = *insn_idx_p;
9952 	bool changes_data;
9953 	int i, err, func_id;
9954 
9955 	/* find function prototype */
9956 	func_id = insn->imm;
9957 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9958 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9959 			func_id);
9960 		return -EINVAL;
9961 	}
9962 
9963 	if (env->ops->get_func_proto)
9964 		fn = env->ops->get_func_proto(func_id, env->prog);
9965 	if (!fn) {
9966 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9967 			func_id);
9968 		return -EINVAL;
9969 	}
9970 
9971 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9972 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9973 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9974 		return -EINVAL;
9975 	}
9976 
9977 	if (fn->allowed && !fn->allowed(env->prog)) {
9978 		verbose(env, "helper call is not allowed in probe\n");
9979 		return -EINVAL;
9980 	}
9981 
9982 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9983 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9984 		return -EINVAL;
9985 	}
9986 
9987 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9988 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9989 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9990 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9991 			func_id_name(func_id), func_id);
9992 		return -EINVAL;
9993 	}
9994 
9995 	memset(&meta, 0, sizeof(meta));
9996 	meta.pkt_access = fn->pkt_access;
9997 
9998 	err = check_func_proto(fn, func_id);
9999 	if (err) {
10000 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10001 			func_id_name(func_id), func_id);
10002 		return err;
10003 	}
10004 
10005 	if (env->cur_state->active_rcu_lock) {
10006 		if (fn->might_sleep) {
10007 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10008 				func_id_name(func_id), func_id);
10009 			return -EINVAL;
10010 		}
10011 
10012 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10013 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10014 	}
10015 
10016 	meta.func_id = func_id;
10017 	/* check args */
10018 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10019 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10020 		if (err)
10021 			return err;
10022 	}
10023 
10024 	err = record_func_map(env, &meta, func_id, insn_idx);
10025 	if (err)
10026 		return err;
10027 
10028 	err = record_func_key(env, &meta, func_id, insn_idx);
10029 	if (err)
10030 		return err;
10031 
10032 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10033 	 * is inferred from register state.
10034 	 */
10035 	for (i = 0; i < meta.access_size; i++) {
10036 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10037 				       BPF_WRITE, -1, false, false);
10038 		if (err)
10039 			return err;
10040 	}
10041 
10042 	regs = cur_regs(env);
10043 
10044 	if (meta.release_regno) {
10045 		err = -EINVAL;
10046 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10047 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10048 		 * is safe to do directly.
10049 		 */
10050 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10051 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10052 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10053 				return -EFAULT;
10054 			}
10055 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10056 		} else if (meta.ref_obj_id) {
10057 			err = release_reference(env, meta.ref_obj_id);
10058 		} else if (register_is_null(&regs[meta.release_regno])) {
10059 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10060 			 * released is NULL, which must be > R0.
10061 			 */
10062 			err = 0;
10063 		}
10064 		if (err) {
10065 			verbose(env, "func %s#%d reference has not been acquired before\n",
10066 				func_id_name(func_id), func_id);
10067 			return err;
10068 		}
10069 	}
10070 
10071 	switch (func_id) {
10072 	case BPF_FUNC_tail_call:
10073 		err = check_reference_leak(env);
10074 		if (err) {
10075 			verbose(env, "tail_call would lead to reference leak\n");
10076 			return err;
10077 		}
10078 		break;
10079 	case BPF_FUNC_get_local_storage:
10080 		/* check that flags argument in get_local_storage(map, flags) is 0,
10081 		 * this is required because get_local_storage() can't return an error.
10082 		 */
10083 		if (!register_is_null(&regs[BPF_REG_2])) {
10084 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10085 			return -EINVAL;
10086 		}
10087 		break;
10088 	case BPF_FUNC_for_each_map_elem:
10089 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10090 					 set_map_elem_callback_state);
10091 		break;
10092 	case BPF_FUNC_timer_set_callback:
10093 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10094 					 set_timer_callback_state);
10095 		break;
10096 	case BPF_FUNC_find_vma:
10097 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10098 					 set_find_vma_callback_state);
10099 		break;
10100 	case BPF_FUNC_snprintf:
10101 		err = check_bpf_snprintf_call(env, regs);
10102 		break;
10103 	case BPF_FUNC_loop:
10104 		update_loop_inline_state(env, meta.subprogno);
10105 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10106 		 * is finished, thus mark it precise.
10107 		 */
10108 		err = mark_chain_precision(env, BPF_REG_1);
10109 		if (err)
10110 			return err;
10111 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10112 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10113 						 set_loop_callback_state);
10114 		} else {
10115 			cur_func(env)->callback_depth = 0;
10116 			if (env->log.level & BPF_LOG_LEVEL2)
10117 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10118 					env->cur_state->curframe);
10119 		}
10120 		break;
10121 	case BPF_FUNC_dynptr_from_mem:
10122 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10123 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10124 				reg_type_str(env, regs[BPF_REG_1].type));
10125 			return -EACCES;
10126 		}
10127 		break;
10128 	case BPF_FUNC_set_retval:
10129 		if (prog_type == BPF_PROG_TYPE_LSM &&
10130 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10131 			if (!env->prog->aux->attach_func_proto->type) {
10132 				/* Make sure programs that attach to void
10133 				 * hooks don't try to modify return value.
10134 				 */
10135 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10136 				return -EINVAL;
10137 			}
10138 		}
10139 		break;
10140 	case BPF_FUNC_dynptr_data:
10141 	{
10142 		struct bpf_reg_state *reg;
10143 		int id, ref_obj_id;
10144 
10145 		reg = get_dynptr_arg_reg(env, fn, regs);
10146 		if (!reg)
10147 			return -EFAULT;
10148 
10149 
10150 		if (meta.dynptr_id) {
10151 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10152 			return -EFAULT;
10153 		}
10154 		if (meta.ref_obj_id) {
10155 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10156 			return -EFAULT;
10157 		}
10158 
10159 		id = dynptr_id(env, reg);
10160 		if (id < 0) {
10161 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10162 			return id;
10163 		}
10164 
10165 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10166 		if (ref_obj_id < 0) {
10167 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10168 			return ref_obj_id;
10169 		}
10170 
10171 		meta.dynptr_id = id;
10172 		meta.ref_obj_id = ref_obj_id;
10173 
10174 		break;
10175 	}
10176 	case BPF_FUNC_dynptr_write:
10177 	{
10178 		enum bpf_dynptr_type dynptr_type;
10179 		struct bpf_reg_state *reg;
10180 
10181 		reg = get_dynptr_arg_reg(env, fn, regs);
10182 		if (!reg)
10183 			return -EFAULT;
10184 
10185 		dynptr_type = dynptr_get_type(env, reg);
10186 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10187 			return -EFAULT;
10188 
10189 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10190 			/* this will trigger clear_all_pkt_pointers(), which will
10191 			 * invalidate all dynptr slices associated with the skb
10192 			 */
10193 			changes_data = true;
10194 
10195 		break;
10196 	}
10197 	case BPF_FUNC_user_ringbuf_drain:
10198 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10199 					 set_user_ringbuf_callback_state);
10200 		break;
10201 	}
10202 
10203 	if (err)
10204 		return err;
10205 
10206 	/* reset caller saved regs */
10207 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10208 		mark_reg_not_init(env, regs, caller_saved[i]);
10209 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10210 	}
10211 
10212 	/* helper call returns 64-bit value. */
10213 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10214 
10215 	/* update return register (already marked as written above) */
10216 	ret_type = fn->ret_type;
10217 	ret_flag = type_flag(ret_type);
10218 
10219 	switch (base_type(ret_type)) {
10220 	case RET_INTEGER:
10221 		/* sets type to SCALAR_VALUE */
10222 		mark_reg_unknown(env, regs, BPF_REG_0);
10223 		break;
10224 	case RET_VOID:
10225 		regs[BPF_REG_0].type = NOT_INIT;
10226 		break;
10227 	case RET_PTR_TO_MAP_VALUE:
10228 		/* There is no offset yet applied, variable or fixed */
10229 		mark_reg_known_zero(env, regs, BPF_REG_0);
10230 		/* remember map_ptr, so that check_map_access()
10231 		 * can check 'value_size' boundary of memory access
10232 		 * to map element returned from bpf_map_lookup_elem()
10233 		 */
10234 		if (meta.map_ptr == NULL) {
10235 			verbose(env,
10236 				"kernel subsystem misconfigured verifier\n");
10237 			return -EINVAL;
10238 		}
10239 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10240 		regs[BPF_REG_0].map_uid = meta.map_uid;
10241 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10242 		if (!type_may_be_null(ret_type) &&
10243 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10244 			regs[BPF_REG_0].id = ++env->id_gen;
10245 		}
10246 		break;
10247 	case RET_PTR_TO_SOCKET:
10248 		mark_reg_known_zero(env, regs, BPF_REG_0);
10249 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10250 		break;
10251 	case RET_PTR_TO_SOCK_COMMON:
10252 		mark_reg_known_zero(env, regs, BPF_REG_0);
10253 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10254 		break;
10255 	case RET_PTR_TO_TCP_SOCK:
10256 		mark_reg_known_zero(env, regs, BPF_REG_0);
10257 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10258 		break;
10259 	case RET_PTR_TO_MEM:
10260 		mark_reg_known_zero(env, regs, BPF_REG_0);
10261 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10262 		regs[BPF_REG_0].mem_size = meta.mem_size;
10263 		break;
10264 	case RET_PTR_TO_MEM_OR_BTF_ID:
10265 	{
10266 		const struct btf_type *t;
10267 
10268 		mark_reg_known_zero(env, regs, BPF_REG_0);
10269 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10270 		if (!btf_type_is_struct(t)) {
10271 			u32 tsize;
10272 			const struct btf_type *ret;
10273 			const char *tname;
10274 
10275 			/* resolve the type size of ksym. */
10276 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10277 			if (IS_ERR(ret)) {
10278 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10279 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10280 					tname, PTR_ERR(ret));
10281 				return -EINVAL;
10282 			}
10283 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10284 			regs[BPF_REG_0].mem_size = tsize;
10285 		} else {
10286 			/* MEM_RDONLY may be carried from ret_flag, but it
10287 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10288 			 * it will confuse the check of PTR_TO_BTF_ID in
10289 			 * check_mem_access().
10290 			 */
10291 			ret_flag &= ~MEM_RDONLY;
10292 
10293 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10294 			regs[BPF_REG_0].btf = meta.ret_btf;
10295 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10296 		}
10297 		break;
10298 	}
10299 	case RET_PTR_TO_BTF_ID:
10300 	{
10301 		struct btf *ret_btf;
10302 		int ret_btf_id;
10303 
10304 		mark_reg_known_zero(env, regs, BPF_REG_0);
10305 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10306 		if (func_id == BPF_FUNC_kptr_xchg) {
10307 			ret_btf = meta.kptr_field->kptr.btf;
10308 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10309 			if (!btf_is_kernel(ret_btf))
10310 				regs[BPF_REG_0].type |= MEM_ALLOC;
10311 		} else {
10312 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10313 				verbose(env, "verifier internal error:");
10314 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10315 					func_id_name(func_id));
10316 				return -EINVAL;
10317 			}
10318 			ret_btf = btf_vmlinux;
10319 			ret_btf_id = *fn->ret_btf_id;
10320 		}
10321 		if (ret_btf_id == 0) {
10322 			verbose(env, "invalid return type %u of func %s#%d\n",
10323 				base_type(ret_type), func_id_name(func_id),
10324 				func_id);
10325 			return -EINVAL;
10326 		}
10327 		regs[BPF_REG_0].btf = ret_btf;
10328 		regs[BPF_REG_0].btf_id = ret_btf_id;
10329 		break;
10330 	}
10331 	default:
10332 		verbose(env, "unknown return type %u of func %s#%d\n",
10333 			base_type(ret_type), func_id_name(func_id), func_id);
10334 		return -EINVAL;
10335 	}
10336 
10337 	if (type_may_be_null(regs[BPF_REG_0].type))
10338 		regs[BPF_REG_0].id = ++env->id_gen;
10339 
10340 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10341 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10342 			func_id_name(func_id), func_id);
10343 		return -EFAULT;
10344 	}
10345 
10346 	if (is_dynptr_ref_function(func_id))
10347 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10348 
10349 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10350 		/* For release_reference() */
10351 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10352 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10353 		int id = acquire_reference_state(env, insn_idx);
10354 
10355 		if (id < 0)
10356 			return id;
10357 		/* For mark_ptr_or_null_reg() */
10358 		regs[BPF_REG_0].id = id;
10359 		/* For release_reference() */
10360 		regs[BPF_REG_0].ref_obj_id = id;
10361 	}
10362 
10363 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10364 
10365 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10366 	if (err)
10367 		return err;
10368 
10369 	if ((func_id == BPF_FUNC_get_stack ||
10370 	     func_id == BPF_FUNC_get_task_stack) &&
10371 	    !env->prog->has_callchain_buf) {
10372 		const char *err_str;
10373 
10374 #ifdef CONFIG_PERF_EVENTS
10375 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10376 		err_str = "cannot get callchain buffer for func %s#%d\n";
10377 #else
10378 		err = -ENOTSUPP;
10379 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10380 #endif
10381 		if (err) {
10382 			verbose(env, err_str, func_id_name(func_id), func_id);
10383 			return err;
10384 		}
10385 
10386 		env->prog->has_callchain_buf = true;
10387 	}
10388 
10389 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10390 		env->prog->call_get_stack = true;
10391 
10392 	if (func_id == BPF_FUNC_get_func_ip) {
10393 		if (check_get_func_ip(env))
10394 			return -ENOTSUPP;
10395 		env->prog->call_get_func_ip = true;
10396 	}
10397 
10398 	if (changes_data)
10399 		clear_all_pkt_pointers(env);
10400 	return 0;
10401 }
10402 
10403 /* mark_btf_func_reg_size() is used when the reg size is determined by
10404  * the BTF func_proto's return value size and argument.
10405  */
10406 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10407 				   size_t reg_size)
10408 {
10409 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10410 
10411 	if (regno == BPF_REG_0) {
10412 		/* Function return value */
10413 		reg->live |= REG_LIVE_WRITTEN;
10414 		reg->subreg_def = reg_size == sizeof(u64) ?
10415 			DEF_NOT_SUBREG : env->insn_idx + 1;
10416 	} else {
10417 		/* Function argument */
10418 		if (reg_size == sizeof(u64)) {
10419 			mark_insn_zext(env, reg);
10420 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10421 		} else {
10422 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10423 		}
10424 	}
10425 }
10426 
10427 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10428 {
10429 	return meta->kfunc_flags & KF_ACQUIRE;
10430 }
10431 
10432 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10433 {
10434 	return meta->kfunc_flags & KF_RELEASE;
10435 }
10436 
10437 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10438 {
10439 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10440 }
10441 
10442 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10443 {
10444 	return meta->kfunc_flags & KF_SLEEPABLE;
10445 }
10446 
10447 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10448 {
10449 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10450 }
10451 
10452 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10453 {
10454 	return meta->kfunc_flags & KF_RCU;
10455 }
10456 
10457 static bool __kfunc_param_match_suffix(const struct btf *btf,
10458 				       const struct btf_param *arg,
10459 				       const char *suffix)
10460 {
10461 	int suffix_len = strlen(suffix), len;
10462 	const char *param_name;
10463 
10464 	/* In the future, this can be ported to use BTF tagging */
10465 	param_name = btf_name_by_offset(btf, arg->name_off);
10466 	if (str_is_empty(param_name))
10467 		return false;
10468 	len = strlen(param_name);
10469 	if (len < suffix_len)
10470 		return false;
10471 	param_name += len - suffix_len;
10472 	return !strncmp(param_name, suffix, suffix_len);
10473 }
10474 
10475 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10476 				  const struct btf_param *arg,
10477 				  const struct bpf_reg_state *reg)
10478 {
10479 	const struct btf_type *t;
10480 
10481 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10482 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10483 		return false;
10484 
10485 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10486 }
10487 
10488 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10489 					const struct btf_param *arg,
10490 					const struct bpf_reg_state *reg)
10491 {
10492 	const struct btf_type *t;
10493 
10494 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10495 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10496 		return false;
10497 
10498 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10499 }
10500 
10501 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10502 {
10503 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10504 }
10505 
10506 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10507 {
10508 	return __kfunc_param_match_suffix(btf, arg, "__k");
10509 }
10510 
10511 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10512 {
10513 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10514 }
10515 
10516 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10517 {
10518 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10519 }
10520 
10521 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10522 {
10523 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10524 }
10525 
10526 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10527 {
10528 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10529 }
10530 
10531 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10532 					  const struct btf_param *arg,
10533 					  const char *name)
10534 {
10535 	int len, target_len = strlen(name);
10536 	const char *param_name;
10537 
10538 	param_name = btf_name_by_offset(btf, arg->name_off);
10539 	if (str_is_empty(param_name))
10540 		return false;
10541 	len = strlen(param_name);
10542 	if (len != target_len)
10543 		return false;
10544 	if (strcmp(param_name, name))
10545 		return false;
10546 
10547 	return true;
10548 }
10549 
10550 enum {
10551 	KF_ARG_DYNPTR_ID,
10552 	KF_ARG_LIST_HEAD_ID,
10553 	KF_ARG_LIST_NODE_ID,
10554 	KF_ARG_RB_ROOT_ID,
10555 	KF_ARG_RB_NODE_ID,
10556 };
10557 
10558 BTF_ID_LIST(kf_arg_btf_ids)
10559 BTF_ID(struct, bpf_dynptr_kern)
10560 BTF_ID(struct, bpf_list_head)
10561 BTF_ID(struct, bpf_list_node)
10562 BTF_ID(struct, bpf_rb_root)
10563 BTF_ID(struct, bpf_rb_node)
10564 
10565 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10566 				    const struct btf_param *arg, int type)
10567 {
10568 	const struct btf_type *t;
10569 	u32 res_id;
10570 
10571 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10572 	if (!t)
10573 		return false;
10574 	if (!btf_type_is_ptr(t))
10575 		return false;
10576 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10577 	if (!t)
10578 		return false;
10579 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10580 }
10581 
10582 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10583 {
10584 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10585 }
10586 
10587 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10588 {
10589 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10590 }
10591 
10592 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10593 {
10594 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10595 }
10596 
10597 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10598 {
10599 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10600 }
10601 
10602 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10603 {
10604 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10605 }
10606 
10607 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10608 				  const struct btf_param *arg)
10609 {
10610 	const struct btf_type *t;
10611 
10612 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10613 	if (!t)
10614 		return false;
10615 
10616 	return true;
10617 }
10618 
10619 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10620 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10621 					const struct btf *btf,
10622 					const struct btf_type *t, int rec)
10623 {
10624 	const struct btf_type *member_type;
10625 	const struct btf_member *member;
10626 	u32 i;
10627 
10628 	if (!btf_type_is_struct(t))
10629 		return false;
10630 
10631 	for_each_member(i, t, member) {
10632 		const struct btf_array *array;
10633 
10634 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10635 		if (btf_type_is_struct(member_type)) {
10636 			if (rec >= 3) {
10637 				verbose(env, "max struct nesting depth exceeded\n");
10638 				return false;
10639 			}
10640 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10641 				return false;
10642 			continue;
10643 		}
10644 		if (btf_type_is_array(member_type)) {
10645 			array = btf_array(member_type);
10646 			if (!array->nelems)
10647 				return false;
10648 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10649 			if (!btf_type_is_scalar(member_type))
10650 				return false;
10651 			continue;
10652 		}
10653 		if (!btf_type_is_scalar(member_type))
10654 			return false;
10655 	}
10656 	return true;
10657 }
10658 
10659 enum kfunc_ptr_arg_type {
10660 	KF_ARG_PTR_TO_CTX,
10661 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10662 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10663 	KF_ARG_PTR_TO_DYNPTR,
10664 	KF_ARG_PTR_TO_ITER,
10665 	KF_ARG_PTR_TO_LIST_HEAD,
10666 	KF_ARG_PTR_TO_LIST_NODE,
10667 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10668 	KF_ARG_PTR_TO_MEM,
10669 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10670 	KF_ARG_PTR_TO_CALLBACK,
10671 	KF_ARG_PTR_TO_RB_ROOT,
10672 	KF_ARG_PTR_TO_RB_NODE,
10673 };
10674 
10675 enum special_kfunc_type {
10676 	KF_bpf_obj_new_impl,
10677 	KF_bpf_obj_drop_impl,
10678 	KF_bpf_refcount_acquire_impl,
10679 	KF_bpf_list_push_front_impl,
10680 	KF_bpf_list_push_back_impl,
10681 	KF_bpf_list_pop_front,
10682 	KF_bpf_list_pop_back,
10683 	KF_bpf_cast_to_kern_ctx,
10684 	KF_bpf_rdonly_cast,
10685 	KF_bpf_rcu_read_lock,
10686 	KF_bpf_rcu_read_unlock,
10687 	KF_bpf_rbtree_remove,
10688 	KF_bpf_rbtree_add_impl,
10689 	KF_bpf_rbtree_first,
10690 	KF_bpf_dynptr_from_skb,
10691 	KF_bpf_dynptr_from_xdp,
10692 	KF_bpf_dynptr_slice,
10693 	KF_bpf_dynptr_slice_rdwr,
10694 	KF_bpf_dynptr_clone,
10695 };
10696 
10697 BTF_SET_START(special_kfunc_set)
10698 BTF_ID(func, bpf_obj_new_impl)
10699 BTF_ID(func, bpf_obj_drop_impl)
10700 BTF_ID(func, bpf_refcount_acquire_impl)
10701 BTF_ID(func, bpf_list_push_front_impl)
10702 BTF_ID(func, bpf_list_push_back_impl)
10703 BTF_ID(func, bpf_list_pop_front)
10704 BTF_ID(func, bpf_list_pop_back)
10705 BTF_ID(func, bpf_cast_to_kern_ctx)
10706 BTF_ID(func, bpf_rdonly_cast)
10707 BTF_ID(func, bpf_rbtree_remove)
10708 BTF_ID(func, bpf_rbtree_add_impl)
10709 BTF_ID(func, bpf_rbtree_first)
10710 BTF_ID(func, bpf_dynptr_from_skb)
10711 BTF_ID(func, bpf_dynptr_from_xdp)
10712 BTF_ID(func, bpf_dynptr_slice)
10713 BTF_ID(func, bpf_dynptr_slice_rdwr)
10714 BTF_ID(func, bpf_dynptr_clone)
10715 BTF_SET_END(special_kfunc_set)
10716 
10717 BTF_ID_LIST(special_kfunc_list)
10718 BTF_ID(func, bpf_obj_new_impl)
10719 BTF_ID(func, bpf_obj_drop_impl)
10720 BTF_ID(func, bpf_refcount_acquire_impl)
10721 BTF_ID(func, bpf_list_push_front_impl)
10722 BTF_ID(func, bpf_list_push_back_impl)
10723 BTF_ID(func, bpf_list_pop_front)
10724 BTF_ID(func, bpf_list_pop_back)
10725 BTF_ID(func, bpf_cast_to_kern_ctx)
10726 BTF_ID(func, bpf_rdonly_cast)
10727 BTF_ID(func, bpf_rcu_read_lock)
10728 BTF_ID(func, bpf_rcu_read_unlock)
10729 BTF_ID(func, bpf_rbtree_remove)
10730 BTF_ID(func, bpf_rbtree_add_impl)
10731 BTF_ID(func, bpf_rbtree_first)
10732 BTF_ID(func, bpf_dynptr_from_skb)
10733 BTF_ID(func, bpf_dynptr_from_xdp)
10734 BTF_ID(func, bpf_dynptr_slice)
10735 BTF_ID(func, bpf_dynptr_slice_rdwr)
10736 BTF_ID(func, bpf_dynptr_clone)
10737 
10738 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10739 {
10740 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10741 	    meta->arg_owning_ref) {
10742 		return false;
10743 	}
10744 
10745 	return meta->kfunc_flags & KF_RET_NULL;
10746 }
10747 
10748 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10749 {
10750 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10751 }
10752 
10753 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10754 {
10755 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10756 }
10757 
10758 static enum kfunc_ptr_arg_type
10759 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10760 		       struct bpf_kfunc_call_arg_meta *meta,
10761 		       const struct btf_type *t, const struct btf_type *ref_t,
10762 		       const char *ref_tname, const struct btf_param *args,
10763 		       int argno, int nargs)
10764 {
10765 	u32 regno = argno + 1;
10766 	struct bpf_reg_state *regs = cur_regs(env);
10767 	struct bpf_reg_state *reg = &regs[regno];
10768 	bool arg_mem_size = false;
10769 
10770 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10771 		return KF_ARG_PTR_TO_CTX;
10772 
10773 	/* In this function, we verify the kfunc's BTF as per the argument type,
10774 	 * leaving the rest of the verification with respect to the register
10775 	 * type to our caller. When a set of conditions hold in the BTF type of
10776 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10777 	 */
10778 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10779 		return KF_ARG_PTR_TO_CTX;
10780 
10781 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10782 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10783 
10784 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10785 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10786 
10787 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10788 		return KF_ARG_PTR_TO_DYNPTR;
10789 
10790 	if (is_kfunc_arg_iter(meta, argno))
10791 		return KF_ARG_PTR_TO_ITER;
10792 
10793 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10794 		return KF_ARG_PTR_TO_LIST_HEAD;
10795 
10796 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10797 		return KF_ARG_PTR_TO_LIST_NODE;
10798 
10799 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10800 		return KF_ARG_PTR_TO_RB_ROOT;
10801 
10802 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10803 		return KF_ARG_PTR_TO_RB_NODE;
10804 
10805 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10806 		if (!btf_type_is_struct(ref_t)) {
10807 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10808 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10809 			return -EINVAL;
10810 		}
10811 		return KF_ARG_PTR_TO_BTF_ID;
10812 	}
10813 
10814 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10815 		return KF_ARG_PTR_TO_CALLBACK;
10816 
10817 
10818 	if (argno + 1 < nargs &&
10819 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10820 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10821 		arg_mem_size = true;
10822 
10823 	/* This is the catch all argument type of register types supported by
10824 	 * check_helper_mem_access. However, we only allow when argument type is
10825 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10826 	 * arg_mem_size is true, the pointer can be void *.
10827 	 */
10828 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10829 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10830 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10831 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10832 		return -EINVAL;
10833 	}
10834 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10835 }
10836 
10837 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10838 					struct bpf_reg_state *reg,
10839 					const struct btf_type *ref_t,
10840 					const char *ref_tname, u32 ref_id,
10841 					struct bpf_kfunc_call_arg_meta *meta,
10842 					int argno)
10843 {
10844 	const struct btf_type *reg_ref_t;
10845 	bool strict_type_match = false;
10846 	const struct btf *reg_btf;
10847 	const char *reg_ref_tname;
10848 	u32 reg_ref_id;
10849 
10850 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10851 		reg_btf = reg->btf;
10852 		reg_ref_id = reg->btf_id;
10853 	} else {
10854 		reg_btf = btf_vmlinux;
10855 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10856 	}
10857 
10858 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10859 	 * or releasing a reference, or are no-cast aliases. We do _not_
10860 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10861 	 * as we want to enable BPF programs to pass types that are bitwise
10862 	 * equivalent without forcing them to explicitly cast with something
10863 	 * like bpf_cast_to_kern_ctx().
10864 	 *
10865 	 * For example, say we had a type like the following:
10866 	 *
10867 	 * struct bpf_cpumask {
10868 	 *	cpumask_t cpumask;
10869 	 *	refcount_t usage;
10870 	 * };
10871 	 *
10872 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10873 	 * to a struct cpumask, so it would be safe to pass a struct
10874 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10875 	 *
10876 	 * The philosophy here is similar to how we allow scalars of different
10877 	 * types to be passed to kfuncs as long as the size is the same. The
10878 	 * only difference here is that we're simply allowing
10879 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10880 	 * resolve types.
10881 	 */
10882 	if (is_kfunc_acquire(meta) ||
10883 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10884 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10885 		strict_type_match = true;
10886 
10887 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10888 
10889 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10890 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10891 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10892 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10893 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10894 			btf_type_str(reg_ref_t), reg_ref_tname);
10895 		return -EINVAL;
10896 	}
10897 	return 0;
10898 }
10899 
10900 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10901 {
10902 	struct bpf_verifier_state *state = env->cur_state;
10903 	struct btf_record *rec = reg_btf_record(reg);
10904 
10905 	if (!state->active_lock.ptr) {
10906 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10907 		return -EFAULT;
10908 	}
10909 
10910 	if (type_flag(reg->type) & NON_OWN_REF) {
10911 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10912 		return -EFAULT;
10913 	}
10914 
10915 	reg->type |= NON_OWN_REF;
10916 	if (rec->refcount_off >= 0)
10917 		reg->type |= MEM_RCU;
10918 
10919 	return 0;
10920 }
10921 
10922 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10923 {
10924 	struct bpf_func_state *state, *unused;
10925 	struct bpf_reg_state *reg;
10926 	int i;
10927 
10928 	state = cur_func(env);
10929 
10930 	if (!ref_obj_id) {
10931 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10932 			     "owning -> non-owning conversion\n");
10933 		return -EFAULT;
10934 	}
10935 
10936 	for (i = 0; i < state->acquired_refs; i++) {
10937 		if (state->refs[i].id != ref_obj_id)
10938 			continue;
10939 
10940 		/* Clear ref_obj_id here so release_reference doesn't clobber
10941 		 * the whole reg
10942 		 */
10943 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10944 			if (reg->ref_obj_id == ref_obj_id) {
10945 				reg->ref_obj_id = 0;
10946 				ref_set_non_owning(env, reg);
10947 			}
10948 		}));
10949 		return 0;
10950 	}
10951 
10952 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10953 	return -EFAULT;
10954 }
10955 
10956 /* Implementation details:
10957  *
10958  * Each register points to some region of memory, which we define as an
10959  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10960  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10961  * allocation. The lock and the data it protects are colocated in the same
10962  * memory region.
10963  *
10964  * Hence, everytime a register holds a pointer value pointing to such
10965  * allocation, the verifier preserves a unique reg->id for it.
10966  *
10967  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10968  * bpf_spin_lock is called.
10969  *
10970  * To enable this, lock state in the verifier captures two values:
10971  *	active_lock.ptr = Register's type specific pointer
10972  *	active_lock.id  = A unique ID for each register pointer value
10973  *
10974  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10975  * supported register types.
10976  *
10977  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10978  * allocated objects is the reg->btf pointer.
10979  *
10980  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10981  * can establish the provenance of the map value statically for each distinct
10982  * lookup into such maps. They always contain a single map value hence unique
10983  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10984  *
10985  * So, in case of global variables, they use array maps with max_entries = 1,
10986  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10987  * into the same map value as max_entries is 1, as described above).
10988  *
10989  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10990  * outer map pointer (in verifier context), but each lookup into an inner map
10991  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10992  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10993  * will get different reg->id assigned to each lookup, hence different
10994  * active_lock.id.
10995  *
10996  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10997  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10998  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10999  */
11000 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11001 {
11002 	void *ptr;
11003 	u32 id;
11004 
11005 	switch ((int)reg->type) {
11006 	case PTR_TO_MAP_VALUE:
11007 		ptr = reg->map_ptr;
11008 		break;
11009 	case PTR_TO_BTF_ID | MEM_ALLOC:
11010 		ptr = reg->btf;
11011 		break;
11012 	default:
11013 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11014 		return -EFAULT;
11015 	}
11016 	id = reg->id;
11017 
11018 	if (!env->cur_state->active_lock.ptr)
11019 		return -EINVAL;
11020 	if (env->cur_state->active_lock.ptr != ptr ||
11021 	    env->cur_state->active_lock.id != id) {
11022 		verbose(env, "held lock and object are not in the same allocation\n");
11023 		return -EINVAL;
11024 	}
11025 	return 0;
11026 }
11027 
11028 static bool is_bpf_list_api_kfunc(u32 btf_id)
11029 {
11030 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11031 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11032 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11033 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11034 }
11035 
11036 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11037 {
11038 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11039 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11040 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11041 }
11042 
11043 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11044 {
11045 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11046 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11047 }
11048 
11049 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11050 {
11051 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11052 }
11053 
11054 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11055 {
11056 	return is_bpf_rbtree_api_kfunc(btf_id);
11057 }
11058 
11059 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11060 					  enum btf_field_type head_field_type,
11061 					  u32 kfunc_btf_id)
11062 {
11063 	bool ret;
11064 
11065 	switch (head_field_type) {
11066 	case BPF_LIST_HEAD:
11067 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11068 		break;
11069 	case BPF_RB_ROOT:
11070 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11071 		break;
11072 	default:
11073 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11074 			btf_field_type_name(head_field_type));
11075 		return false;
11076 	}
11077 
11078 	if (!ret)
11079 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11080 			btf_field_type_name(head_field_type));
11081 	return ret;
11082 }
11083 
11084 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11085 					  enum btf_field_type node_field_type,
11086 					  u32 kfunc_btf_id)
11087 {
11088 	bool ret;
11089 
11090 	switch (node_field_type) {
11091 	case BPF_LIST_NODE:
11092 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11093 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11094 		break;
11095 	case BPF_RB_NODE:
11096 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11097 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11098 		break;
11099 	default:
11100 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11101 			btf_field_type_name(node_field_type));
11102 		return false;
11103 	}
11104 
11105 	if (!ret)
11106 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11107 			btf_field_type_name(node_field_type));
11108 	return ret;
11109 }
11110 
11111 static int
11112 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11113 				   struct bpf_reg_state *reg, u32 regno,
11114 				   struct bpf_kfunc_call_arg_meta *meta,
11115 				   enum btf_field_type head_field_type,
11116 				   struct btf_field **head_field)
11117 {
11118 	const char *head_type_name;
11119 	struct btf_field *field;
11120 	struct btf_record *rec;
11121 	u32 head_off;
11122 
11123 	if (meta->btf != btf_vmlinux) {
11124 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11125 		return -EFAULT;
11126 	}
11127 
11128 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11129 		return -EFAULT;
11130 
11131 	head_type_name = btf_field_type_name(head_field_type);
11132 	if (!tnum_is_const(reg->var_off)) {
11133 		verbose(env,
11134 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11135 			regno, head_type_name);
11136 		return -EINVAL;
11137 	}
11138 
11139 	rec = reg_btf_record(reg);
11140 	head_off = reg->off + reg->var_off.value;
11141 	field = btf_record_find(rec, head_off, head_field_type);
11142 	if (!field) {
11143 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11144 		return -EINVAL;
11145 	}
11146 
11147 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11148 	if (check_reg_allocation_locked(env, reg)) {
11149 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11150 			rec->spin_lock_off, head_type_name);
11151 		return -EINVAL;
11152 	}
11153 
11154 	if (*head_field) {
11155 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11156 		return -EFAULT;
11157 	}
11158 	*head_field = field;
11159 	return 0;
11160 }
11161 
11162 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11163 					   struct bpf_reg_state *reg, u32 regno,
11164 					   struct bpf_kfunc_call_arg_meta *meta)
11165 {
11166 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11167 							  &meta->arg_list_head.field);
11168 }
11169 
11170 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11171 					     struct bpf_reg_state *reg, u32 regno,
11172 					     struct bpf_kfunc_call_arg_meta *meta)
11173 {
11174 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11175 							  &meta->arg_rbtree_root.field);
11176 }
11177 
11178 static int
11179 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11180 				   struct bpf_reg_state *reg, u32 regno,
11181 				   struct bpf_kfunc_call_arg_meta *meta,
11182 				   enum btf_field_type head_field_type,
11183 				   enum btf_field_type node_field_type,
11184 				   struct btf_field **node_field)
11185 {
11186 	const char *node_type_name;
11187 	const struct btf_type *et, *t;
11188 	struct btf_field *field;
11189 	u32 node_off;
11190 
11191 	if (meta->btf != btf_vmlinux) {
11192 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11193 		return -EFAULT;
11194 	}
11195 
11196 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11197 		return -EFAULT;
11198 
11199 	node_type_name = btf_field_type_name(node_field_type);
11200 	if (!tnum_is_const(reg->var_off)) {
11201 		verbose(env,
11202 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11203 			regno, node_type_name);
11204 		return -EINVAL;
11205 	}
11206 
11207 	node_off = reg->off + reg->var_off.value;
11208 	field = reg_find_field_offset(reg, node_off, node_field_type);
11209 	if (!field || field->offset != node_off) {
11210 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11211 		return -EINVAL;
11212 	}
11213 
11214 	field = *node_field;
11215 
11216 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11217 	t = btf_type_by_id(reg->btf, reg->btf_id);
11218 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11219 				  field->graph_root.value_btf_id, true)) {
11220 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11221 			"in struct %s, but arg is at offset=%d in struct %s\n",
11222 			btf_field_type_name(head_field_type),
11223 			btf_field_type_name(node_field_type),
11224 			field->graph_root.node_offset,
11225 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11226 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11227 		return -EINVAL;
11228 	}
11229 	meta->arg_btf = reg->btf;
11230 	meta->arg_btf_id = reg->btf_id;
11231 
11232 	if (node_off != field->graph_root.node_offset) {
11233 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11234 			node_off, btf_field_type_name(node_field_type),
11235 			field->graph_root.node_offset,
11236 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11237 		return -EINVAL;
11238 	}
11239 
11240 	return 0;
11241 }
11242 
11243 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11244 					   struct bpf_reg_state *reg, u32 regno,
11245 					   struct bpf_kfunc_call_arg_meta *meta)
11246 {
11247 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11248 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11249 						  &meta->arg_list_head.field);
11250 }
11251 
11252 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11253 					     struct bpf_reg_state *reg, u32 regno,
11254 					     struct bpf_kfunc_call_arg_meta *meta)
11255 {
11256 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11257 						  BPF_RB_ROOT, BPF_RB_NODE,
11258 						  &meta->arg_rbtree_root.field);
11259 }
11260 
11261 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11262 			    int insn_idx)
11263 {
11264 	const char *func_name = meta->func_name, *ref_tname;
11265 	const struct btf *btf = meta->btf;
11266 	const struct btf_param *args;
11267 	struct btf_record *rec;
11268 	u32 i, nargs;
11269 	int ret;
11270 
11271 	args = (const struct btf_param *)(meta->func_proto + 1);
11272 	nargs = btf_type_vlen(meta->func_proto);
11273 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11274 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11275 			MAX_BPF_FUNC_REG_ARGS);
11276 		return -EINVAL;
11277 	}
11278 
11279 	/* Check that BTF function arguments match actual types that the
11280 	 * verifier sees.
11281 	 */
11282 	for (i = 0; i < nargs; i++) {
11283 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11284 		const struct btf_type *t, *ref_t, *resolve_ret;
11285 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11286 		u32 regno = i + 1, ref_id, type_size;
11287 		bool is_ret_buf_sz = false;
11288 		int kf_arg_type;
11289 
11290 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11291 
11292 		if (is_kfunc_arg_ignore(btf, &args[i]))
11293 			continue;
11294 
11295 		if (btf_type_is_scalar(t)) {
11296 			if (reg->type != SCALAR_VALUE) {
11297 				verbose(env, "R%d is not a scalar\n", regno);
11298 				return -EINVAL;
11299 			}
11300 
11301 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11302 				if (meta->arg_constant.found) {
11303 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11304 					return -EFAULT;
11305 				}
11306 				if (!tnum_is_const(reg->var_off)) {
11307 					verbose(env, "R%d must be a known constant\n", regno);
11308 					return -EINVAL;
11309 				}
11310 				ret = mark_chain_precision(env, regno);
11311 				if (ret < 0)
11312 					return ret;
11313 				meta->arg_constant.found = true;
11314 				meta->arg_constant.value = reg->var_off.value;
11315 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11316 				meta->r0_rdonly = true;
11317 				is_ret_buf_sz = true;
11318 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11319 				is_ret_buf_sz = true;
11320 			}
11321 
11322 			if (is_ret_buf_sz) {
11323 				if (meta->r0_size) {
11324 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11325 					return -EINVAL;
11326 				}
11327 
11328 				if (!tnum_is_const(reg->var_off)) {
11329 					verbose(env, "R%d is not a const\n", regno);
11330 					return -EINVAL;
11331 				}
11332 
11333 				meta->r0_size = reg->var_off.value;
11334 				ret = mark_chain_precision(env, regno);
11335 				if (ret)
11336 					return ret;
11337 			}
11338 			continue;
11339 		}
11340 
11341 		if (!btf_type_is_ptr(t)) {
11342 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11343 			return -EINVAL;
11344 		}
11345 
11346 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11347 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11348 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11349 			return -EACCES;
11350 		}
11351 
11352 		if (reg->ref_obj_id) {
11353 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11354 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11355 					regno, reg->ref_obj_id,
11356 					meta->ref_obj_id);
11357 				return -EFAULT;
11358 			}
11359 			meta->ref_obj_id = reg->ref_obj_id;
11360 			if (is_kfunc_release(meta))
11361 				meta->release_regno = regno;
11362 		}
11363 
11364 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11365 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11366 
11367 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11368 		if (kf_arg_type < 0)
11369 			return kf_arg_type;
11370 
11371 		switch (kf_arg_type) {
11372 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11373 		case KF_ARG_PTR_TO_BTF_ID:
11374 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11375 				break;
11376 
11377 			if (!is_trusted_reg(reg)) {
11378 				if (!is_kfunc_rcu(meta)) {
11379 					verbose(env, "R%d must be referenced or trusted\n", regno);
11380 					return -EINVAL;
11381 				}
11382 				if (!is_rcu_reg(reg)) {
11383 					verbose(env, "R%d must be a rcu pointer\n", regno);
11384 					return -EINVAL;
11385 				}
11386 			}
11387 
11388 			fallthrough;
11389 		case KF_ARG_PTR_TO_CTX:
11390 			/* Trusted arguments have the same offset checks as release arguments */
11391 			arg_type |= OBJ_RELEASE;
11392 			break;
11393 		case KF_ARG_PTR_TO_DYNPTR:
11394 		case KF_ARG_PTR_TO_ITER:
11395 		case KF_ARG_PTR_TO_LIST_HEAD:
11396 		case KF_ARG_PTR_TO_LIST_NODE:
11397 		case KF_ARG_PTR_TO_RB_ROOT:
11398 		case KF_ARG_PTR_TO_RB_NODE:
11399 		case KF_ARG_PTR_TO_MEM:
11400 		case KF_ARG_PTR_TO_MEM_SIZE:
11401 		case KF_ARG_PTR_TO_CALLBACK:
11402 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11403 			/* Trusted by default */
11404 			break;
11405 		default:
11406 			WARN_ON_ONCE(1);
11407 			return -EFAULT;
11408 		}
11409 
11410 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11411 			arg_type |= OBJ_RELEASE;
11412 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11413 		if (ret < 0)
11414 			return ret;
11415 
11416 		switch (kf_arg_type) {
11417 		case KF_ARG_PTR_TO_CTX:
11418 			if (reg->type != PTR_TO_CTX) {
11419 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11420 				return -EINVAL;
11421 			}
11422 
11423 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11424 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11425 				if (ret < 0)
11426 					return -EINVAL;
11427 				meta->ret_btf_id  = ret;
11428 			}
11429 			break;
11430 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11431 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11432 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11433 				return -EINVAL;
11434 			}
11435 			if (!reg->ref_obj_id) {
11436 				verbose(env, "allocated object must be referenced\n");
11437 				return -EINVAL;
11438 			}
11439 			if (meta->btf == btf_vmlinux &&
11440 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11441 				meta->arg_btf = reg->btf;
11442 				meta->arg_btf_id = reg->btf_id;
11443 			}
11444 			break;
11445 		case KF_ARG_PTR_TO_DYNPTR:
11446 		{
11447 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11448 			int clone_ref_obj_id = 0;
11449 
11450 			if (reg->type != PTR_TO_STACK &&
11451 			    reg->type != CONST_PTR_TO_DYNPTR) {
11452 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11453 				return -EINVAL;
11454 			}
11455 
11456 			if (reg->type == CONST_PTR_TO_DYNPTR)
11457 				dynptr_arg_type |= MEM_RDONLY;
11458 
11459 			if (is_kfunc_arg_uninit(btf, &args[i]))
11460 				dynptr_arg_type |= MEM_UNINIT;
11461 
11462 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11463 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11464 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11465 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11466 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11467 				   (dynptr_arg_type & MEM_UNINIT)) {
11468 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11469 
11470 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11471 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11472 					return -EFAULT;
11473 				}
11474 
11475 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11476 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11477 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11478 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11479 					return -EFAULT;
11480 				}
11481 			}
11482 
11483 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11484 			if (ret < 0)
11485 				return ret;
11486 
11487 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11488 				int id = dynptr_id(env, reg);
11489 
11490 				if (id < 0) {
11491 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11492 					return id;
11493 				}
11494 				meta->initialized_dynptr.id = id;
11495 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11496 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11497 			}
11498 
11499 			break;
11500 		}
11501 		case KF_ARG_PTR_TO_ITER:
11502 			ret = process_iter_arg(env, regno, insn_idx, meta);
11503 			if (ret < 0)
11504 				return ret;
11505 			break;
11506 		case KF_ARG_PTR_TO_LIST_HEAD:
11507 			if (reg->type != PTR_TO_MAP_VALUE &&
11508 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11509 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11510 				return -EINVAL;
11511 			}
11512 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11513 				verbose(env, "allocated object must be referenced\n");
11514 				return -EINVAL;
11515 			}
11516 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11517 			if (ret < 0)
11518 				return ret;
11519 			break;
11520 		case KF_ARG_PTR_TO_RB_ROOT:
11521 			if (reg->type != PTR_TO_MAP_VALUE &&
11522 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11523 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11524 				return -EINVAL;
11525 			}
11526 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11527 				verbose(env, "allocated object must be referenced\n");
11528 				return -EINVAL;
11529 			}
11530 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11531 			if (ret < 0)
11532 				return ret;
11533 			break;
11534 		case KF_ARG_PTR_TO_LIST_NODE:
11535 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11536 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11537 				return -EINVAL;
11538 			}
11539 			if (!reg->ref_obj_id) {
11540 				verbose(env, "allocated object must be referenced\n");
11541 				return -EINVAL;
11542 			}
11543 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11544 			if (ret < 0)
11545 				return ret;
11546 			break;
11547 		case KF_ARG_PTR_TO_RB_NODE:
11548 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11549 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11550 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11551 					return -EINVAL;
11552 				}
11553 				if (in_rbtree_lock_required_cb(env)) {
11554 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11555 					return -EINVAL;
11556 				}
11557 			} else {
11558 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11559 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11560 					return -EINVAL;
11561 				}
11562 				if (!reg->ref_obj_id) {
11563 					verbose(env, "allocated object must be referenced\n");
11564 					return -EINVAL;
11565 				}
11566 			}
11567 
11568 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11569 			if (ret < 0)
11570 				return ret;
11571 			break;
11572 		case KF_ARG_PTR_TO_BTF_ID:
11573 			/* Only base_type is checked, further checks are done here */
11574 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11575 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11576 			    !reg2btf_ids[base_type(reg->type)]) {
11577 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11578 				verbose(env, "expected %s or socket\n",
11579 					reg_type_str(env, base_type(reg->type) |
11580 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11581 				return -EINVAL;
11582 			}
11583 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11584 			if (ret < 0)
11585 				return ret;
11586 			break;
11587 		case KF_ARG_PTR_TO_MEM:
11588 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11589 			if (IS_ERR(resolve_ret)) {
11590 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11591 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11592 				return -EINVAL;
11593 			}
11594 			ret = check_mem_reg(env, reg, regno, type_size);
11595 			if (ret < 0)
11596 				return ret;
11597 			break;
11598 		case KF_ARG_PTR_TO_MEM_SIZE:
11599 		{
11600 			struct bpf_reg_state *buff_reg = &regs[regno];
11601 			const struct btf_param *buff_arg = &args[i];
11602 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11603 			const struct btf_param *size_arg = &args[i + 1];
11604 
11605 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11606 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11607 				if (ret < 0) {
11608 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11609 					return ret;
11610 				}
11611 			}
11612 
11613 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11614 				if (meta->arg_constant.found) {
11615 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11616 					return -EFAULT;
11617 				}
11618 				if (!tnum_is_const(size_reg->var_off)) {
11619 					verbose(env, "R%d must be a known constant\n", regno + 1);
11620 					return -EINVAL;
11621 				}
11622 				meta->arg_constant.found = true;
11623 				meta->arg_constant.value = size_reg->var_off.value;
11624 			}
11625 
11626 			/* Skip next '__sz' or '__szk' argument */
11627 			i++;
11628 			break;
11629 		}
11630 		case KF_ARG_PTR_TO_CALLBACK:
11631 			if (reg->type != PTR_TO_FUNC) {
11632 				verbose(env, "arg%d expected pointer to func\n", i);
11633 				return -EINVAL;
11634 			}
11635 			meta->subprogno = reg->subprogno;
11636 			break;
11637 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11638 			if (!type_is_ptr_alloc_obj(reg->type)) {
11639 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11640 				return -EINVAL;
11641 			}
11642 			if (!type_is_non_owning_ref(reg->type))
11643 				meta->arg_owning_ref = true;
11644 
11645 			rec = reg_btf_record(reg);
11646 			if (!rec) {
11647 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11648 				return -EFAULT;
11649 			}
11650 
11651 			if (rec->refcount_off < 0) {
11652 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11653 				return -EINVAL;
11654 			}
11655 
11656 			meta->arg_btf = reg->btf;
11657 			meta->arg_btf_id = reg->btf_id;
11658 			break;
11659 		}
11660 	}
11661 
11662 	if (is_kfunc_release(meta) && !meta->release_regno) {
11663 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11664 			func_name);
11665 		return -EINVAL;
11666 	}
11667 
11668 	return 0;
11669 }
11670 
11671 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11672 			    struct bpf_insn *insn,
11673 			    struct bpf_kfunc_call_arg_meta *meta,
11674 			    const char **kfunc_name)
11675 {
11676 	const struct btf_type *func, *func_proto;
11677 	u32 func_id, *kfunc_flags;
11678 	const char *func_name;
11679 	struct btf *desc_btf;
11680 
11681 	if (kfunc_name)
11682 		*kfunc_name = NULL;
11683 
11684 	if (!insn->imm)
11685 		return -EINVAL;
11686 
11687 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11688 	if (IS_ERR(desc_btf))
11689 		return PTR_ERR(desc_btf);
11690 
11691 	func_id = insn->imm;
11692 	func = btf_type_by_id(desc_btf, func_id);
11693 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11694 	if (kfunc_name)
11695 		*kfunc_name = func_name;
11696 	func_proto = btf_type_by_id(desc_btf, func->type);
11697 
11698 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11699 	if (!kfunc_flags) {
11700 		return -EACCES;
11701 	}
11702 
11703 	memset(meta, 0, sizeof(*meta));
11704 	meta->btf = desc_btf;
11705 	meta->func_id = func_id;
11706 	meta->kfunc_flags = *kfunc_flags;
11707 	meta->func_proto = func_proto;
11708 	meta->func_name = func_name;
11709 
11710 	return 0;
11711 }
11712 
11713 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11714 			    int *insn_idx_p)
11715 {
11716 	const struct btf_type *t, *ptr_type;
11717 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11718 	struct bpf_reg_state *regs = cur_regs(env);
11719 	const char *func_name, *ptr_type_name;
11720 	bool sleepable, rcu_lock, rcu_unlock;
11721 	struct bpf_kfunc_call_arg_meta meta;
11722 	struct bpf_insn_aux_data *insn_aux;
11723 	int err, insn_idx = *insn_idx_p;
11724 	const struct btf_param *args;
11725 	const struct btf_type *ret_t;
11726 	struct btf *desc_btf;
11727 
11728 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11729 	if (!insn->imm)
11730 		return 0;
11731 
11732 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11733 	if (err == -EACCES && func_name)
11734 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11735 	if (err)
11736 		return err;
11737 	desc_btf = meta.btf;
11738 	insn_aux = &env->insn_aux_data[insn_idx];
11739 
11740 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11741 
11742 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11743 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11744 		return -EACCES;
11745 	}
11746 
11747 	sleepable = is_kfunc_sleepable(&meta);
11748 	if (sleepable && !env->prog->aux->sleepable) {
11749 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11750 		return -EACCES;
11751 	}
11752 
11753 	/* Check the arguments */
11754 	err = check_kfunc_args(env, &meta, insn_idx);
11755 	if (err < 0)
11756 		return err;
11757 
11758 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11759 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11760 					 set_rbtree_add_callback_state);
11761 		if (err) {
11762 			verbose(env, "kfunc %s#%d failed callback verification\n",
11763 				func_name, meta.func_id);
11764 			return err;
11765 		}
11766 	}
11767 
11768 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11769 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11770 
11771 	if (env->cur_state->active_rcu_lock) {
11772 		struct bpf_func_state *state;
11773 		struct bpf_reg_state *reg;
11774 
11775 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11776 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11777 			return -EACCES;
11778 		}
11779 
11780 		if (rcu_lock) {
11781 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11782 			return -EINVAL;
11783 		} else if (rcu_unlock) {
11784 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11785 				if (reg->type & MEM_RCU) {
11786 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11787 					reg->type |= PTR_UNTRUSTED;
11788 				}
11789 			}));
11790 			env->cur_state->active_rcu_lock = false;
11791 		} else if (sleepable) {
11792 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11793 			return -EACCES;
11794 		}
11795 	} else if (rcu_lock) {
11796 		env->cur_state->active_rcu_lock = true;
11797 	} else if (rcu_unlock) {
11798 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11799 		return -EINVAL;
11800 	}
11801 
11802 	/* In case of release function, we get register number of refcounted
11803 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11804 	 */
11805 	if (meta.release_regno) {
11806 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11807 		if (err) {
11808 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11809 				func_name, meta.func_id);
11810 			return err;
11811 		}
11812 	}
11813 
11814 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11815 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11816 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11817 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11818 		insn_aux->insert_off = regs[BPF_REG_2].off;
11819 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11820 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11821 		if (err) {
11822 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11823 				func_name, meta.func_id);
11824 			return err;
11825 		}
11826 
11827 		err = release_reference(env, release_ref_obj_id);
11828 		if (err) {
11829 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11830 				func_name, meta.func_id);
11831 			return err;
11832 		}
11833 	}
11834 
11835 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11836 		mark_reg_not_init(env, regs, caller_saved[i]);
11837 
11838 	/* Check return type */
11839 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11840 
11841 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11842 		/* Only exception is bpf_obj_new_impl */
11843 		if (meta.btf != btf_vmlinux ||
11844 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11845 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11846 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11847 			return -EINVAL;
11848 		}
11849 	}
11850 
11851 	if (btf_type_is_scalar(t)) {
11852 		mark_reg_unknown(env, regs, BPF_REG_0);
11853 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11854 	} else if (btf_type_is_ptr(t)) {
11855 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11856 
11857 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11858 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11859 				struct btf *ret_btf;
11860 				u32 ret_btf_id;
11861 
11862 				if (unlikely(!bpf_global_ma_set))
11863 					return -ENOMEM;
11864 
11865 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11866 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11867 					return -EINVAL;
11868 				}
11869 
11870 				ret_btf = env->prog->aux->btf;
11871 				ret_btf_id = meta.arg_constant.value;
11872 
11873 				/* This may be NULL due to user not supplying a BTF */
11874 				if (!ret_btf) {
11875 					verbose(env, "bpf_obj_new requires prog BTF\n");
11876 					return -EINVAL;
11877 				}
11878 
11879 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11880 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11881 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11882 					return -EINVAL;
11883 				}
11884 
11885 				mark_reg_known_zero(env, regs, BPF_REG_0);
11886 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11887 				regs[BPF_REG_0].btf = ret_btf;
11888 				regs[BPF_REG_0].btf_id = ret_btf_id;
11889 
11890 				insn_aux->obj_new_size = ret_t->size;
11891 				insn_aux->kptr_struct_meta =
11892 					btf_find_struct_meta(ret_btf, ret_btf_id);
11893 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11894 				mark_reg_known_zero(env, regs, BPF_REG_0);
11895 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11896 				regs[BPF_REG_0].btf = meta.arg_btf;
11897 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11898 
11899 				insn_aux->kptr_struct_meta =
11900 					btf_find_struct_meta(meta.arg_btf,
11901 							     meta.arg_btf_id);
11902 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11903 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11904 				struct btf_field *field = meta.arg_list_head.field;
11905 
11906 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11907 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11908 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11909 				struct btf_field *field = meta.arg_rbtree_root.field;
11910 
11911 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11912 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11913 				mark_reg_known_zero(env, regs, BPF_REG_0);
11914 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11915 				regs[BPF_REG_0].btf = desc_btf;
11916 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11917 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11918 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11919 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11920 					verbose(env,
11921 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11922 					return -EINVAL;
11923 				}
11924 
11925 				mark_reg_known_zero(env, regs, BPF_REG_0);
11926 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11927 				regs[BPF_REG_0].btf = desc_btf;
11928 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11929 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11930 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11931 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11932 
11933 				mark_reg_known_zero(env, regs, BPF_REG_0);
11934 
11935 				if (!meta.arg_constant.found) {
11936 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11937 					return -EFAULT;
11938 				}
11939 
11940 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11941 
11942 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11943 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11944 
11945 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11946 					regs[BPF_REG_0].type |= MEM_RDONLY;
11947 				} else {
11948 					/* this will set env->seen_direct_write to true */
11949 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11950 						verbose(env, "the prog does not allow writes to packet data\n");
11951 						return -EINVAL;
11952 					}
11953 				}
11954 
11955 				if (!meta.initialized_dynptr.id) {
11956 					verbose(env, "verifier internal error: no dynptr id\n");
11957 					return -EFAULT;
11958 				}
11959 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11960 
11961 				/* we don't need to set BPF_REG_0's ref obj id
11962 				 * because packet slices are not refcounted (see
11963 				 * dynptr_type_refcounted)
11964 				 */
11965 			} else {
11966 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11967 					meta.func_name);
11968 				return -EFAULT;
11969 			}
11970 		} else if (!__btf_type_is_struct(ptr_type)) {
11971 			if (!meta.r0_size) {
11972 				__u32 sz;
11973 
11974 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11975 					meta.r0_size = sz;
11976 					meta.r0_rdonly = true;
11977 				}
11978 			}
11979 			if (!meta.r0_size) {
11980 				ptr_type_name = btf_name_by_offset(desc_btf,
11981 								   ptr_type->name_off);
11982 				verbose(env,
11983 					"kernel function %s returns pointer type %s %s is not supported\n",
11984 					func_name,
11985 					btf_type_str(ptr_type),
11986 					ptr_type_name);
11987 				return -EINVAL;
11988 			}
11989 
11990 			mark_reg_known_zero(env, regs, BPF_REG_0);
11991 			regs[BPF_REG_0].type = PTR_TO_MEM;
11992 			regs[BPF_REG_0].mem_size = meta.r0_size;
11993 
11994 			if (meta.r0_rdonly)
11995 				regs[BPF_REG_0].type |= MEM_RDONLY;
11996 
11997 			/* Ensures we don't access the memory after a release_reference() */
11998 			if (meta.ref_obj_id)
11999 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12000 		} else {
12001 			mark_reg_known_zero(env, regs, BPF_REG_0);
12002 			regs[BPF_REG_0].btf = desc_btf;
12003 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12004 			regs[BPF_REG_0].btf_id = ptr_type_id;
12005 
12006 			if (is_iter_next_kfunc(&meta)) {
12007 				struct bpf_reg_state *cur_iter;
12008 
12009 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12010 
12011 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12012 					regs[BPF_REG_0].type |= MEM_RCU;
12013 				else
12014 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12015 			}
12016 		}
12017 
12018 		if (is_kfunc_ret_null(&meta)) {
12019 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12020 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12021 			regs[BPF_REG_0].id = ++env->id_gen;
12022 		}
12023 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12024 		if (is_kfunc_acquire(&meta)) {
12025 			int id = acquire_reference_state(env, insn_idx);
12026 
12027 			if (id < 0)
12028 				return id;
12029 			if (is_kfunc_ret_null(&meta))
12030 				regs[BPF_REG_0].id = id;
12031 			regs[BPF_REG_0].ref_obj_id = id;
12032 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12033 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12034 		}
12035 
12036 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12037 			regs[BPF_REG_0].id = ++env->id_gen;
12038 	} else if (btf_type_is_void(t)) {
12039 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12040 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12041 				insn_aux->kptr_struct_meta =
12042 					btf_find_struct_meta(meta.arg_btf,
12043 							     meta.arg_btf_id);
12044 			}
12045 		}
12046 	}
12047 
12048 	nargs = btf_type_vlen(meta.func_proto);
12049 	args = (const struct btf_param *)(meta.func_proto + 1);
12050 	for (i = 0; i < nargs; i++) {
12051 		u32 regno = i + 1;
12052 
12053 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12054 		if (btf_type_is_ptr(t))
12055 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12056 		else
12057 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12058 			mark_btf_func_reg_size(env, regno, t->size);
12059 	}
12060 
12061 	if (is_iter_next_kfunc(&meta)) {
12062 		err = process_iter_next_call(env, insn_idx, &meta);
12063 		if (err)
12064 			return err;
12065 	}
12066 
12067 	return 0;
12068 }
12069 
12070 static bool signed_add_overflows(s64 a, s64 b)
12071 {
12072 	/* Do the add in u64, where overflow is well-defined */
12073 	s64 res = (s64)((u64)a + (u64)b);
12074 
12075 	if (b < 0)
12076 		return res > a;
12077 	return res < a;
12078 }
12079 
12080 static bool signed_add32_overflows(s32 a, s32 b)
12081 {
12082 	/* Do the add in u32, where overflow is well-defined */
12083 	s32 res = (s32)((u32)a + (u32)b);
12084 
12085 	if (b < 0)
12086 		return res > a;
12087 	return res < a;
12088 }
12089 
12090 static bool signed_sub_overflows(s64 a, s64 b)
12091 {
12092 	/* Do the sub in u64, where overflow is well-defined */
12093 	s64 res = (s64)((u64)a - (u64)b);
12094 
12095 	if (b < 0)
12096 		return res < a;
12097 	return res > a;
12098 }
12099 
12100 static bool signed_sub32_overflows(s32 a, s32 b)
12101 {
12102 	/* Do the sub in u32, where overflow is well-defined */
12103 	s32 res = (s32)((u32)a - (u32)b);
12104 
12105 	if (b < 0)
12106 		return res < a;
12107 	return res > a;
12108 }
12109 
12110 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12111 				  const struct bpf_reg_state *reg,
12112 				  enum bpf_reg_type type)
12113 {
12114 	bool known = tnum_is_const(reg->var_off);
12115 	s64 val = reg->var_off.value;
12116 	s64 smin = reg->smin_value;
12117 
12118 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12119 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12120 			reg_type_str(env, type), val);
12121 		return false;
12122 	}
12123 
12124 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12125 		verbose(env, "%s pointer offset %d is not allowed\n",
12126 			reg_type_str(env, type), reg->off);
12127 		return false;
12128 	}
12129 
12130 	if (smin == S64_MIN) {
12131 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12132 			reg_type_str(env, type));
12133 		return false;
12134 	}
12135 
12136 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12137 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12138 			smin, reg_type_str(env, type));
12139 		return false;
12140 	}
12141 
12142 	return true;
12143 }
12144 
12145 enum {
12146 	REASON_BOUNDS	= -1,
12147 	REASON_TYPE	= -2,
12148 	REASON_PATHS	= -3,
12149 	REASON_LIMIT	= -4,
12150 	REASON_STACK	= -5,
12151 };
12152 
12153 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12154 			      u32 *alu_limit, bool mask_to_left)
12155 {
12156 	u32 max = 0, ptr_limit = 0;
12157 
12158 	switch (ptr_reg->type) {
12159 	case PTR_TO_STACK:
12160 		/* Offset 0 is out-of-bounds, but acceptable start for the
12161 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12162 		 * offset where we would need to deal with min/max bounds is
12163 		 * currently prohibited for unprivileged.
12164 		 */
12165 		max = MAX_BPF_STACK + mask_to_left;
12166 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12167 		break;
12168 	case PTR_TO_MAP_VALUE:
12169 		max = ptr_reg->map_ptr->value_size;
12170 		ptr_limit = (mask_to_left ?
12171 			     ptr_reg->smin_value :
12172 			     ptr_reg->umax_value) + ptr_reg->off;
12173 		break;
12174 	default:
12175 		return REASON_TYPE;
12176 	}
12177 
12178 	if (ptr_limit >= max)
12179 		return REASON_LIMIT;
12180 	*alu_limit = ptr_limit;
12181 	return 0;
12182 }
12183 
12184 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12185 				    const struct bpf_insn *insn)
12186 {
12187 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12188 }
12189 
12190 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12191 				       u32 alu_state, u32 alu_limit)
12192 {
12193 	/* If we arrived here from different branches with different
12194 	 * state or limits to sanitize, then this won't work.
12195 	 */
12196 	if (aux->alu_state &&
12197 	    (aux->alu_state != alu_state ||
12198 	     aux->alu_limit != alu_limit))
12199 		return REASON_PATHS;
12200 
12201 	/* Corresponding fixup done in do_misc_fixups(). */
12202 	aux->alu_state = alu_state;
12203 	aux->alu_limit = alu_limit;
12204 	return 0;
12205 }
12206 
12207 static int sanitize_val_alu(struct bpf_verifier_env *env,
12208 			    struct bpf_insn *insn)
12209 {
12210 	struct bpf_insn_aux_data *aux = cur_aux(env);
12211 
12212 	if (can_skip_alu_sanitation(env, insn))
12213 		return 0;
12214 
12215 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12216 }
12217 
12218 static bool sanitize_needed(u8 opcode)
12219 {
12220 	return opcode == BPF_ADD || opcode == BPF_SUB;
12221 }
12222 
12223 struct bpf_sanitize_info {
12224 	struct bpf_insn_aux_data aux;
12225 	bool mask_to_left;
12226 };
12227 
12228 static struct bpf_verifier_state *
12229 sanitize_speculative_path(struct bpf_verifier_env *env,
12230 			  const struct bpf_insn *insn,
12231 			  u32 next_idx, u32 curr_idx)
12232 {
12233 	struct bpf_verifier_state *branch;
12234 	struct bpf_reg_state *regs;
12235 
12236 	branch = push_stack(env, next_idx, curr_idx, true);
12237 	if (branch && insn) {
12238 		regs = branch->frame[branch->curframe]->regs;
12239 		if (BPF_SRC(insn->code) == BPF_K) {
12240 			mark_reg_unknown(env, regs, insn->dst_reg);
12241 		} else if (BPF_SRC(insn->code) == BPF_X) {
12242 			mark_reg_unknown(env, regs, insn->dst_reg);
12243 			mark_reg_unknown(env, regs, insn->src_reg);
12244 		}
12245 	}
12246 	return branch;
12247 }
12248 
12249 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12250 			    struct bpf_insn *insn,
12251 			    const struct bpf_reg_state *ptr_reg,
12252 			    const struct bpf_reg_state *off_reg,
12253 			    struct bpf_reg_state *dst_reg,
12254 			    struct bpf_sanitize_info *info,
12255 			    const bool commit_window)
12256 {
12257 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12258 	struct bpf_verifier_state *vstate = env->cur_state;
12259 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12260 	bool off_is_neg = off_reg->smin_value < 0;
12261 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12262 	u8 opcode = BPF_OP(insn->code);
12263 	u32 alu_state, alu_limit;
12264 	struct bpf_reg_state tmp;
12265 	bool ret;
12266 	int err;
12267 
12268 	if (can_skip_alu_sanitation(env, insn))
12269 		return 0;
12270 
12271 	/* We already marked aux for masking from non-speculative
12272 	 * paths, thus we got here in the first place. We only care
12273 	 * to explore bad access from here.
12274 	 */
12275 	if (vstate->speculative)
12276 		goto do_sim;
12277 
12278 	if (!commit_window) {
12279 		if (!tnum_is_const(off_reg->var_off) &&
12280 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12281 			return REASON_BOUNDS;
12282 
12283 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12284 				     (opcode == BPF_SUB && !off_is_neg);
12285 	}
12286 
12287 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12288 	if (err < 0)
12289 		return err;
12290 
12291 	if (commit_window) {
12292 		/* In commit phase we narrow the masking window based on
12293 		 * the observed pointer move after the simulated operation.
12294 		 */
12295 		alu_state = info->aux.alu_state;
12296 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12297 	} else {
12298 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12299 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12300 		alu_state |= ptr_is_dst_reg ?
12301 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12302 
12303 		/* Limit pruning on unknown scalars to enable deep search for
12304 		 * potential masking differences from other program paths.
12305 		 */
12306 		if (!off_is_imm)
12307 			env->explore_alu_limits = true;
12308 	}
12309 
12310 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12311 	if (err < 0)
12312 		return err;
12313 do_sim:
12314 	/* If we're in commit phase, we're done here given we already
12315 	 * pushed the truncated dst_reg into the speculative verification
12316 	 * stack.
12317 	 *
12318 	 * Also, when register is a known constant, we rewrite register-based
12319 	 * operation to immediate-based, and thus do not need masking (and as
12320 	 * a consequence, do not need to simulate the zero-truncation either).
12321 	 */
12322 	if (commit_window || off_is_imm)
12323 		return 0;
12324 
12325 	/* Simulate and find potential out-of-bounds access under
12326 	 * speculative execution from truncation as a result of
12327 	 * masking when off was not within expected range. If off
12328 	 * sits in dst, then we temporarily need to move ptr there
12329 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12330 	 * for cases where we use K-based arithmetic in one direction
12331 	 * and truncated reg-based in the other in order to explore
12332 	 * bad access.
12333 	 */
12334 	if (!ptr_is_dst_reg) {
12335 		tmp = *dst_reg;
12336 		copy_register_state(dst_reg, ptr_reg);
12337 	}
12338 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12339 					env->insn_idx);
12340 	if (!ptr_is_dst_reg && ret)
12341 		*dst_reg = tmp;
12342 	return !ret ? REASON_STACK : 0;
12343 }
12344 
12345 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12346 {
12347 	struct bpf_verifier_state *vstate = env->cur_state;
12348 
12349 	/* If we simulate paths under speculation, we don't update the
12350 	 * insn as 'seen' such that when we verify unreachable paths in
12351 	 * the non-speculative domain, sanitize_dead_code() can still
12352 	 * rewrite/sanitize them.
12353 	 */
12354 	if (!vstate->speculative)
12355 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12356 }
12357 
12358 static int sanitize_err(struct bpf_verifier_env *env,
12359 			const struct bpf_insn *insn, int reason,
12360 			const struct bpf_reg_state *off_reg,
12361 			const struct bpf_reg_state *dst_reg)
12362 {
12363 	static const char *err = "pointer arithmetic with it prohibited for !root";
12364 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12365 	u32 dst = insn->dst_reg, src = insn->src_reg;
12366 
12367 	switch (reason) {
12368 	case REASON_BOUNDS:
12369 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12370 			off_reg == dst_reg ? dst : src, err);
12371 		break;
12372 	case REASON_TYPE:
12373 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12374 			off_reg == dst_reg ? src : dst, err);
12375 		break;
12376 	case REASON_PATHS:
12377 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12378 			dst, op, err);
12379 		break;
12380 	case REASON_LIMIT:
12381 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12382 			dst, op, err);
12383 		break;
12384 	case REASON_STACK:
12385 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12386 			dst, err);
12387 		break;
12388 	default:
12389 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12390 			reason);
12391 		break;
12392 	}
12393 
12394 	return -EACCES;
12395 }
12396 
12397 /* check that stack access falls within stack limits and that 'reg' doesn't
12398  * have a variable offset.
12399  *
12400  * Variable offset is prohibited for unprivileged mode for simplicity since it
12401  * requires corresponding support in Spectre masking for stack ALU.  See also
12402  * retrieve_ptr_limit().
12403  *
12404  *
12405  * 'off' includes 'reg->off'.
12406  */
12407 static int check_stack_access_for_ptr_arithmetic(
12408 				struct bpf_verifier_env *env,
12409 				int regno,
12410 				const struct bpf_reg_state *reg,
12411 				int off)
12412 {
12413 	if (!tnum_is_const(reg->var_off)) {
12414 		char tn_buf[48];
12415 
12416 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12417 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12418 			regno, tn_buf, off);
12419 		return -EACCES;
12420 	}
12421 
12422 	if (off >= 0 || off < -MAX_BPF_STACK) {
12423 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12424 			"prohibited for !root; off=%d\n", regno, off);
12425 		return -EACCES;
12426 	}
12427 
12428 	return 0;
12429 }
12430 
12431 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12432 				 const struct bpf_insn *insn,
12433 				 const struct bpf_reg_state *dst_reg)
12434 {
12435 	u32 dst = insn->dst_reg;
12436 
12437 	/* For unprivileged we require that resulting offset must be in bounds
12438 	 * in order to be able to sanitize access later on.
12439 	 */
12440 	if (env->bypass_spec_v1)
12441 		return 0;
12442 
12443 	switch (dst_reg->type) {
12444 	case PTR_TO_STACK:
12445 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12446 					dst_reg->off + dst_reg->var_off.value))
12447 			return -EACCES;
12448 		break;
12449 	case PTR_TO_MAP_VALUE:
12450 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12451 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12452 				"prohibited for !root\n", dst);
12453 			return -EACCES;
12454 		}
12455 		break;
12456 	default:
12457 		break;
12458 	}
12459 
12460 	return 0;
12461 }
12462 
12463 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12464  * Caller should also handle BPF_MOV case separately.
12465  * If we return -EACCES, caller may want to try again treating pointer as a
12466  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12467  */
12468 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12469 				   struct bpf_insn *insn,
12470 				   const struct bpf_reg_state *ptr_reg,
12471 				   const struct bpf_reg_state *off_reg)
12472 {
12473 	struct bpf_verifier_state *vstate = env->cur_state;
12474 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12475 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12476 	bool known = tnum_is_const(off_reg->var_off);
12477 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12478 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12479 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12480 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12481 	struct bpf_sanitize_info info = {};
12482 	u8 opcode = BPF_OP(insn->code);
12483 	u32 dst = insn->dst_reg;
12484 	int ret;
12485 
12486 	dst_reg = &regs[dst];
12487 
12488 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12489 	    smin_val > smax_val || umin_val > umax_val) {
12490 		/* Taint dst register if offset had invalid bounds derived from
12491 		 * e.g. dead branches.
12492 		 */
12493 		__mark_reg_unknown(env, dst_reg);
12494 		return 0;
12495 	}
12496 
12497 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12498 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12499 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12500 			__mark_reg_unknown(env, dst_reg);
12501 			return 0;
12502 		}
12503 
12504 		verbose(env,
12505 			"R%d 32-bit pointer arithmetic prohibited\n",
12506 			dst);
12507 		return -EACCES;
12508 	}
12509 
12510 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12511 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12512 			dst, reg_type_str(env, ptr_reg->type));
12513 		return -EACCES;
12514 	}
12515 
12516 	switch (base_type(ptr_reg->type)) {
12517 	case PTR_TO_FLOW_KEYS:
12518 		if (known)
12519 			break;
12520 		fallthrough;
12521 	case CONST_PTR_TO_MAP:
12522 		/* smin_val represents the known value */
12523 		if (known && smin_val == 0 && opcode == BPF_ADD)
12524 			break;
12525 		fallthrough;
12526 	case PTR_TO_PACKET_END:
12527 	case PTR_TO_SOCKET:
12528 	case PTR_TO_SOCK_COMMON:
12529 	case PTR_TO_TCP_SOCK:
12530 	case PTR_TO_XDP_SOCK:
12531 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12532 			dst, reg_type_str(env, ptr_reg->type));
12533 		return -EACCES;
12534 	default:
12535 		break;
12536 	}
12537 
12538 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12539 	 * The id may be overwritten later if we create a new variable offset.
12540 	 */
12541 	dst_reg->type = ptr_reg->type;
12542 	dst_reg->id = ptr_reg->id;
12543 
12544 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12545 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12546 		return -EINVAL;
12547 
12548 	/* pointer types do not carry 32-bit bounds at the moment. */
12549 	__mark_reg32_unbounded(dst_reg);
12550 
12551 	if (sanitize_needed(opcode)) {
12552 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12553 				       &info, false);
12554 		if (ret < 0)
12555 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12556 	}
12557 
12558 	switch (opcode) {
12559 	case BPF_ADD:
12560 		/* We can take a fixed offset as long as it doesn't overflow
12561 		 * the s32 'off' field
12562 		 */
12563 		if (known && (ptr_reg->off + smin_val ==
12564 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12565 			/* pointer += K.  Accumulate it into fixed offset */
12566 			dst_reg->smin_value = smin_ptr;
12567 			dst_reg->smax_value = smax_ptr;
12568 			dst_reg->umin_value = umin_ptr;
12569 			dst_reg->umax_value = umax_ptr;
12570 			dst_reg->var_off = ptr_reg->var_off;
12571 			dst_reg->off = ptr_reg->off + smin_val;
12572 			dst_reg->raw = ptr_reg->raw;
12573 			break;
12574 		}
12575 		/* A new variable offset is created.  Note that off_reg->off
12576 		 * == 0, since it's a scalar.
12577 		 * dst_reg gets the pointer type and since some positive
12578 		 * integer value was added to the pointer, give it a new 'id'
12579 		 * if it's a PTR_TO_PACKET.
12580 		 * this creates a new 'base' pointer, off_reg (variable) gets
12581 		 * added into the variable offset, and we copy the fixed offset
12582 		 * from ptr_reg.
12583 		 */
12584 		if (signed_add_overflows(smin_ptr, smin_val) ||
12585 		    signed_add_overflows(smax_ptr, smax_val)) {
12586 			dst_reg->smin_value = S64_MIN;
12587 			dst_reg->smax_value = S64_MAX;
12588 		} else {
12589 			dst_reg->smin_value = smin_ptr + smin_val;
12590 			dst_reg->smax_value = smax_ptr + smax_val;
12591 		}
12592 		if (umin_ptr + umin_val < umin_ptr ||
12593 		    umax_ptr + umax_val < umax_ptr) {
12594 			dst_reg->umin_value = 0;
12595 			dst_reg->umax_value = U64_MAX;
12596 		} else {
12597 			dst_reg->umin_value = umin_ptr + umin_val;
12598 			dst_reg->umax_value = umax_ptr + umax_val;
12599 		}
12600 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12601 		dst_reg->off = ptr_reg->off;
12602 		dst_reg->raw = ptr_reg->raw;
12603 		if (reg_is_pkt_pointer(ptr_reg)) {
12604 			dst_reg->id = ++env->id_gen;
12605 			/* something was added to pkt_ptr, set range to zero */
12606 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12607 		}
12608 		break;
12609 	case BPF_SUB:
12610 		if (dst_reg == off_reg) {
12611 			/* scalar -= pointer.  Creates an unknown scalar */
12612 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12613 				dst);
12614 			return -EACCES;
12615 		}
12616 		/* We don't allow subtraction from FP, because (according to
12617 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12618 		 * be able to deal with it.
12619 		 */
12620 		if (ptr_reg->type == PTR_TO_STACK) {
12621 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12622 				dst);
12623 			return -EACCES;
12624 		}
12625 		if (known && (ptr_reg->off - smin_val ==
12626 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12627 			/* pointer -= K.  Subtract it from fixed offset */
12628 			dst_reg->smin_value = smin_ptr;
12629 			dst_reg->smax_value = smax_ptr;
12630 			dst_reg->umin_value = umin_ptr;
12631 			dst_reg->umax_value = umax_ptr;
12632 			dst_reg->var_off = ptr_reg->var_off;
12633 			dst_reg->id = ptr_reg->id;
12634 			dst_reg->off = ptr_reg->off - smin_val;
12635 			dst_reg->raw = ptr_reg->raw;
12636 			break;
12637 		}
12638 		/* A new variable offset is created.  If the subtrahend is known
12639 		 * nonnegative, then any reg->range we had before is still good.
12640 		 */
12641 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12642 		    signed_sub_overflows(smax_ptr, smin_val)) {
12643 			/* Overflow possible, we know nothing */
12644 			dst_reg->smin_value = S64_MIN;
12645 			dst_reg->smax_value = S64_MAX;
12646 		} else {
12647 			dst_reg->smin_value = smin_ptr - smax_val;
12648 			dst_reg->smax_value = smax_ptr - smin_val;
12649 		}
12650 		if (umin_ptr < umax_val) {
12651 			/* Overflow possible, we know nothing */
12652 			dst_reg->umin_value = 0;
12653 			dst_reg->umax_value = U64_MAX;
12654 		} else {
12655 			/* Cannot overflow (as long as bounds are consistent) */
12656 			dst_reg->umin_value = umin_ptr - umax_val;
12657 			dst_reg->umax_value = umax_ptr - umin_val;
12658 		}
12659 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12660 		dst_reg->off = ptr_reg->off;
12661 		dst_reg->raw = ptr_reg->raw;
12662 		if (reg_is_pkt_pointer(ptr_reg)) {
12663 			dst_reg->id = ++env->id_gen;
12664 			/* something was added to pkt_ptr, set range to zero */
12665 			if (smin_val < 0)
12666 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12667 		}
12668 		break;
12669 	case BPF_AND:
12670 	case BPF_OR:
12671 	case BPF_XOR:
12672 		/* bitwise ops on pointers are troublesome, prohibit. */
12673 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12674 			dst, bpf_alu_string[opcode >> 4]);
12675 		return -EACCES;
12676 	default:
12677 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12678 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12679 			dst, bpf_alu_string[opcode >> 4]);
12680 		return -EACCES;
12681 	}
12682 
12683 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12684 		return -EINVAL;
12685 	reg_bounds_sync(dst_reg);
12686 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12687 		return -EACCES;
12688 	if (sanitize_needed(opcode)) {
12689 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12690 				       &info, true);
12691 		if (ret < 0)
12692 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12693 	}
12694 
12695 	return 0;
12696 }
12697 
12698 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12699 				 struct bpf_reg_state *src_reg)
12700 {
12701 	s32 smin_val = src_reg->s32_min_value;
12702 	s32 smax_val = src_reg->s32_max_value;
12703 	u32 umin_val = src_reg->u32_min_value;
12704 	u32 umax_val = src_reg->u32_max_value;
12705 
12706 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12707 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12708 		dst_reg->s32_min_value = S32_MIN;
12709 		dst_reg->s32_max_value = S32_MAX;
12710 	} else {
12711 		dst_reg->s32_min_value += smin_val;
12712 		dst_reg->s32_max_value += smax_val;
12713 	}
12714 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12715 	    dst_reg->u32_max_value + umax_val < umax_val) {
12716 		dst_reg->u32_min_value = 0;
12717 		dst_reg->u32_max_value = U32_MAX;
12718 	} else {
12719 		dst_reg->u32_min_value += umin_val;
12720 		dst_reg->u32_max_value += umax_val;
12721 	}
12722 }
12723 
12724 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12725 			       struct bpf_reg_state *src_reg)
12726 {
12727 	s64 smin_val = src_reg->smin_value;
12728 	s64 smax_val = src_reg->smax_value;
12729 	u64 umin_val = src_reg->umin_value;
12730 	u64 umax_val = src_reg->umax_value;
12731 
12732 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12733 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12734 		dst_reg->smin_value = S64_MIN;
12735 		dst_reg->smax_value = S64_MAX;
12736 	} else {
12737 		dst_reg->smin_value += smin_val;
12738 		dst_reg->smax_value += smax_val;
12739 	}
12740 	if (dst_reg->umin_value + umin_val < umin_val ||
12741 	    dst_reg->umax_value + umax_val < umax_val) {
12742 		dst_reg->umin_value = 0;
12743 		dst_reg->umax_value = U64_MAX;
12744 	} else {
12745 		dst_reg->umin_value += umin_val;
12746 		dst_reg->umax_value += umax_val;
12747 	}
12748 }
12749 
12750 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12751 				 struct bpf_reg_state *src_reg)
12752 {
12753 	s32 smin_val = src_reg->s32_min_value;
12754 	s32 smax_val = src_reg->s32_max_value;
12755 	u32 umin_val = src_reg->u32_min_value;
12756 	u32 umax_val = src_reg->u32_max_value;
12757 
12758 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12759 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12760 		/* Overflow possible, we know nothing */
12761 		dst_reg->s32_min_value = S32_MIN;
12762 		dst_reg->s32_max_value = S32_MAX;
12763 	} else {
12764 		dst_reg->s32_min_value -= smax_val;
12765 		dst_reg->s32_max_value -= smin_val;
12766 	}
12767 	if (dst_reg->u32_min_value < umax_val) {
12768 		/* Overflow possible, we know nothing */
12769 		dst_reg->u32_min_value = 0;
12770 		dst_reg->u32_max_value = U32_MAX;
12771 	} else {
12772 		/* Cannot overflow (as long as bounds are consistent) */
12773 		dst_reg->u32_min_value -= umax_val;
12774 		dst_reg->u32_max_value -= umin_val;
12775 	}
12776 }
12777 
12778 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12779 			       struct bpf_reg_state *src_reg)
12780 {
12781 	s64 smin_val = src_reg->smin_value;
12782 	s64 smax_val = src_reg->smax_value;
12783 	u64 umin_val = src_reg->umin_value;
12784 	u64 umax_val = src_reg->umax_value;
12785 
12786 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12787 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12788 		/* Overflow possible, we know nothing */
12789 		dst_reg->smin_value = S64_MIN;
12790 		dst_reg->smax_value = S64_MAX;
12791 	} else {
12792 		dst_reg->smin_value -= smax_val;
12793 		dst_reg->smax_value -= smin_val;
12794 	}
12795 	if (dst_reg->umin_value < umax_val) {
12796 		/* Overflow possible, we know nothing */
12797 		dst_reg->umin_value = 0;
12798 		dst_reg->umax_value = U64_MAX;
12799 	} else {
12800 		/* Cannot overflow (as long as bounds are consistent) */
12801 		dst_reg->umin_value -= umax_val;
12802 		dst_reg->umax_value -= umin_val;
12803 	}
12804 }
12805 
12806 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12807 				 struct bpf_reg_state *src_reg)
12808 {
12809 	s32 smin_val = src_reg->s32_min_value;
12810 	u32 umin_val = src_reg->u32_min_value;
12811 	u32 umax_val = src_reg->u32_max_value;
12812 
12813 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12814 		/* Ain't nobody got time to multiply that sign */
12815 		__mark_reg32_unbounded(dst_reg);
12816 		return;
12817 	}
12818 	/* Both values are positive, so we can work with unsigned and
12819 	 * copy the result to signed (unless it exceeds S32_MAX).
12820 	 */
12821 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12822 		/* Potential overflow, we know nothing */
12823 		__mark_reg32_unbounded(dst_reg);
12824 		return;
12825 	}
12826 	dst_reg->u32_min_value *= umin_val;
12827 	dst_reg->u32_max_value *= umax_val;
12828 	if (dst_reg->u32_max_value > S32_MAX) {
12829 		/* Overflow possible, we know nothing */
12830 		dst_reg->s32_min_value = S32_MIN;
12831 		dst_reg->s32_max_value = S32_MAX;
12832 	} else {
12833 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12834 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12835 	}
12836 }
12837 
12838 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12839 			       struct bpf_reg_state *src_reg)
12840 {
12841 	s64 smin_val = src_reg->smin_value;
12842 	u64 umin_val = src_reg->umin_value;
12843 	u64 umax_val = src_reg->umax_value;
12844 
12845 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12846 		/* Ain't nobody got time to multiply that sign */
12847 		__mark_reg64_unbounded(dst_reg);
12848 		return;
12849 	}
12850 	/* Both values are positive, so we can work with unsigned and
12851 	 * copy the result to signed (unless it exceeds S64_MAX).
12852 	 */
12853 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12854 		/* Potential overflow, we know nothing */
12855 		__mark_reg64_unbounded(dst_reg);
12856 		return;
12857 	}
12858 	dst_reg->umin_value *= umin_val;
12859 	dst_reg->umax_value *= umax_val;
12860 	if (dst_reg->umax_value > S64_MAX) {
12861 		/* Overflow possible, we know nothing */
12862 		dst_reg->smin_value = S64_MIN;
12863 		dst_reg->smax_value = S64_MAX;
12864 	} else {
12865 		dst_reg->smin_value = dst_reg->umin_value;
12866 		dst_reg->smax_value = dst_reg->umax_value;
12867 	}
12868 }
12869 
12870 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12871 				 struct bpf_reg_state *src_reg)
12872 {
12873 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12874 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12875 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12876 	s32 smin_val = src_reg->s32_min_value;
12877 	u32 umax_val = src_reg->u32_max_value;
12878 
12879 	if (src_known && dst_known) {
12880 		__mark_reg32_known(dst_reg, var32_off.value);
12881 		return;
12882 	}
12883 
12884 	/* We get our minimum from the var_off, since that's inherently
12885 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12886 	 */
12887 	dst_reg->u32_min_value = var32_off.value;
12888 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12889 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12890 		/* Lose signed bounds when ANDing negative numbers,
12891 		 * ain't nobody got time for that.
12892 		 */
12893 		dst_reg->s32_min_value = S32_MIN;
12894 		dst_reg->s32_max_value = S32_MAX;
12895 	} else {
12896 		/* ANDing two positives gives a positive, so safe to
12897 		 * cast result into s64.
12898 		 */
12899 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12900 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12901 	}
12902 }
12903 
12904 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12905 			       struct bpf_reg_state *src_reg)
12906 {
12907 	bool src_known = tnum_is_const(src_reg->var_off);
12908 	bool dst_known = tnum_is_const(dst_reg->var_off);
12909 	s64 smin_val = src_reg->smin_value;
12910 	u64 umax_val = src_reg->umax_value;
12911 
12912 	if (src_known && dst_known) {
12913 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12914 		return;
12915 	}
12916 
12917 	/* We get our minimum from the var_off, since that's inherently
12918 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12919 	 */
12920 	dst_reg->umin_value = dst_reg->var_off.value;
12921 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12922 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12923 		/* Lose signed bounds when ANDing negative numbers,
12924 		 * ain't nobody got time for that.
12925 		 */
12926 		dst_reg->smin_value = S64_MIN;
12927 		dst_reg->smax_value = S64_MAX;
12928 	} else {
12929 		/* ANDing two positives gives a positive, so safe to
12930 		 * cast result into s64.
12931 		 */
12932 		dst_reg->smin_value = dst_reg->umin_value;
12933 		dst_reg->smax_value = dst_reg->umax_value;
12934 	}
12935 	/* We may learn something more from the var_off */
12936 	__update_reg_bounds(dst_reg);
12937 }
12938 
12939 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12940 				struct bpf_reg_state *src_reg)
12941 {
12942 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12943 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12944 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12945 	s32 smin_val = src_reg->s32_min_value;
12946 	u32 umin_val = src_reg->u32_min_value;
12947 
12948 	if (src_known && dst_known) {
12949 		__mark_reg32_known(dst_reg, var32_off.value);
12950 		return;
12951 	}
12952 
12953 	/* We get our maximum from the var_off, and our minimum is the
12954 	 * maximum of the operands' minima
12955 	 */
12956 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12957 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12958 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12959 		/* Lose signed bounds when ORing negative numbers,
12960 		 * ain't nobody got time for that.
12961 		 */
12962 		dst_reg->s32_min_value = S32_MIN;
12963 		dst_reg->s32_max_value = S32_MAX;
12964 	} else {
12965 		/* ORing two positives gives a positive, so safe to
12966 		 * cast result into s64.
12967 		 */
12968 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12969 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12970 	}
12971 }
12972 
12973 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12974 			      struct bpf_reg_state *src_reg)
12975 {
12976 	bool src_known = tnum_is_const(src_reg->var_off);
12977 	bool dst_known = tnum_is_const(dst_reg->var_off);
12978 	s64 smin_val = src_reg->smin_value;
12979 	u64 umin_val = src_reg->umin_value;
12980 
12981 	if (src_known && dst_known) {
12982 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12983 		return;
12984 	}
12985 
12986 	/* We get our maximum from the var_off, and our minimum is the
12987 	 * maximum of the operands' minima
12988 	 */
12989 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12990 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12991 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12992 		/* Lose signed bounds when ORing negative numbers,
12993 		 * ain't nobody got time for that.
12994 		 */
12995 		dst_reg->smin_value = S64_MIN;
12996 		dst_reg->smax_value = S64_MAX;
12997 	} else {
12998 		/* ORing two positives gives a positive, so safe to
12999 		 * cast result into s64.
13000 		 */
13001 		dst_reg->smin_value = dst_reg->umin_value;
13002 		dst_reg->smax_value = dst_reg->umax_value;
13003 	}
13004 	/* We may learn something more from the var_off */
13005 	__update_reg_bounds(dst_reg);
13006 }
13007 
13008 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13009 				 struct bpf_reg_state *src_reg)
13010 {
13011 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13012 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13013 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13014 	s32 smin_val = src_reg->s32_min_value;
13015 
13016 	if (src_known && dst_known) {
13017 		__mark_reg32_known(dst_reg, var32_off.value);
13018 		return;
13019 	}
13020 
13021 	/* We get both minimum and maximum from the var32_off. */
13022 	dst_reg->u32_min_value = var32_off.value;
13023 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13024 
13025 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13026 		/* XORing two positive sign numbers gives a positive,
13027 		 * so safe to cast u32 result into s32.
13028 		 */
13029 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13030 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13031 	} else {
13032 		dst_reg->s32_min_value = S32_MIN;
13033 		dst_reg->s32_max_value = S32_MAX;
13034 	}
13035 }
13036 
13037 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13038 			       struct bpf_reg_state *src_reg)
13039 {
13040 	bool src_known = tnum_is_const(src_reg->var_off);
13041 	bool dst_known = tnum_is_const(dst_reg->var_off);
13042 	s64 smin_val = src_reg->smin_value;
13043 
13044 	if (src_known && dst_known) {
13045 		/* dst_reg->var_off.value has been updated earlier */
13046 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13047 		return;
13048 	}
13049 
13050 	/* We get both minimum and maximum from the var_off. */
13051 	dst_reg->umin_value = dst_reg->var_off.value;
13052 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13053 
13054 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13055 		/* XORing two positive sign numbers gives a positive,
13056 		 * so safe to cast u64 result into s64.
13057 		 */
13058 		dst_reg->smin_value = dst_reg->umin_value;
13059 		dst_reg->smax_value = dst_reg->umax_value;
13060 	} else {
13061 		dst_reg->smin_value = S64_MIN;
13062 		dst_reg->smax_value = S64_MAX;
13063 	}
13064 
13065 	__update_reg_bounds(dst_reg);
13066 }
13067 
13068 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13069 				   u64 umin_val, u64 umax_val)
13070 {
13071 	/* We lose all sign bit information (except what we can pick
13072 	 * up from var_off)
13073 	 */
13074 	dst_reg->s32_min_value = S32_MIN;
13075 	dst_reg->s32_max_value = S32_MAX;
13076 	/* If we might shift our top bit out, then we know nothing */
13077 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13078 		dst_reg->u32_min_value = 0;
13079 		dst_reg->u32_max_value = U32_MAX;
13080 	} else {
13081 		dst_reg->u32_min_value <<= umin_val;
13082 		dst_reg->u32_max_value <<= umax_val;
13083 	}
13084 }
13085 
13086 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13087 				 struct bpf_reg_state *src_reg)
13088 {
13089 	u32 umax_val = src_reg->u32_max_value;
13090 	u32 umin_val = src_reg->u32_min_value;
13091 	/* u32 alu operation will zext upper bits */
13092 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13093 
13094 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13095 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13096 	/* Not required but being careful mark reg64 bounds as unknown so
13097 	 * that we are forced to pick them up from tnum and zext later and
13098 	 * if some path skips this step we are still safe.
13099 	 */
13100 	__mark_reg64_unbounded(dst_reg);
13101 	__update_reg32_bounds(dst_reg);
13102 }
13103 
13104 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13105 				   u64 umin_val, u64 umax_val)
13106 {
13107 	/* Special case <<32 because it is a common compiler pattern to sign
13108 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13109 	 * positive we know this shift will also be positive so we can track
13110 	 * bounds correctly. Otherwise we lose all sign bit information except
13111 	 * what we can pick up from var_off. Perhaps we can generalize this
13112 	 * later to shifts of any length.
13113 	 */
13114 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13115 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13116 	else
13117 		dst_reg->smax_value = S64_MAX;
13118 
13119 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13120 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13121 	else
13122 		dst_reg->smin_value = S64_MIN;
13123 
13124 	/* If we might shift our top bit out, then we know nothing */
13125 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13126 		dst_reg->umin_value = 0;
13127 		dst_reg->umax_value = U64_MAX;
13128 	} else {
13129 		dst_reg->umin_value <<= umin_val;
13130 		dst_reg->umax_value <<= umax_val;
13131 	}
13132 }
13133 
13134 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13135 			       struct bpf_reg_state *src_reg)
13136 {
13137 	u64 umax_val = src_reg->umax_value;
13138 	u64 umin_val = src_reg->umin_value;
13139 
13140 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13141 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13142 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13143 
13144 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13145 	/* We may learn something more from the var_off */
13146 	__update_reg_bounds(dst_reg);
13147 }
13148 
13149 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13150 				 struct bpf_reg_state *src_reg)
13151 {
13152 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13153 	u32 umax_val = src_reg->u32_max_value;
13154 	u32 umin_val = src_reg->u32_min_value;
13155 
13156 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13157 	 * be negative, then either:
13158 	 * 1) src_reg might be zero, so the sign bit of the result is
13159 	 *    unknown, so we lose our signed bounds
13160 	 * 2) it's known negative, thus the unsigned bounds capture the
13161 	 *    signed bounds
13162 	 * 3) the signed bounds cross zero, so they tell us nothing
13163 	 *    about the result
13164 	 * If the value in dst_reg is known nonnegative, then again the
13165 	 * unsigned bounds capture the signed bounds.
13166 	 * Thus, in all cases it suffices to blow away our signed bounds
13167 	 * and rely on inferring new ones from the unsigned bounds and
13168 	 * var_off of the result.
13169 	 */
13170 	dst_reg->s32_min_value = S32_MIN;
13171 	dst_reg->s32_max_value = S32_MAX;
13172 
13173 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13174 	dst_reg->u32_min_value >>= umax_val;
13175 	dst_reg->u32_max_value >>= umin_val;
13176 
13177 	__mark_reg64_unbounded(dst_reg);
13178 	__update_reg32_bounds(dst_reg);
13179 }
13180 
13181 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13182 			       struct bpf_reg_state *src_reg)
13183 {
13184 	u64 umax_val = src_reg->umax_value;
13185 	u64 umin_val = src_reg->umin_value;
13186 
13187 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13188 	 * be negative, then either:
13189 	 * 1) src_reg might be zero, so the sign bit of the result is
13190 	 *    unknown, so we lose our signed bounds
13191 	 * 2) it's known negative, thus the unsigned bounds capture the
13192 	 *    signed bounds
13193 	 * 3) the signed bounds cross zero, so they tell us nothing
13194 	 *    about the result
13195 	 * If the value in dst_reg is known nonnegative, then again the
13196 	 * unsigned bounds capture the signed bounds.
13197 	 * Thus, in all cases it suffices to blow away our signed bounds
13198 	 * and rely on inferring new ones from the unsigned bounds and
13199 	 * var_off of the result.
13200 	 */
13201 	dst_reg->smin_value = S64_MIN;
13202 	dst_reg->smax_value = S64_MAX;
13203 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13204 	dst_reg->umin_value >>= umax_val;
13205 	dst_reg->umax_value >>= umin_val;
13206 
13207 	/* Its not easy to operate on alu32 bounds here because it depends
13208 	 * on bits being shifted in. Take easy way out and mark unbounded
13209 	 * so we can recalculate later from tnum.
13210 	 */
13211 	__mark_reg32_unbounded(dst_reg);
13212 	__update_reg_bounds(dst_reg);
13213 }
13214 
13215 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13216 				  struct bpf_reg_state *src_reg)
13217 {
13218 	u64 umin_val = src_reg->u32_min_value;
13219 
13220 	/* Upon reaching here, src_known is true and
13221 	 * umax_val is equal to umin_val.
13222 	 */
13223 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13224 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13225 
13226 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13227 
13228 	/* blow away the dst_reg umin_value/umax_value and rely on
13229 	 * dst_reg var_off to refine the result.
13230 	 */
13231 	dst_reg->u32_min_value = 0;
13232 	dst_reg->u32_max_value = U32_MAX;
13233 
13234 	__mark_reg64_unbounded(dst_reg);
13235 	__update_reg32_bounds(dst_reg);
13236 }
13237 
13238 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13239 				struct bpf_reg_state *src_reg)
13240 {
13241 	u64 umin_val = src_reg->umin_value;
13242 
13243 	/* Upon reaching here, src_known is true and umax_val is equal
13244 	 * to umin_val.
13245 	 */
13246 	dst_reg->smin_value >>= umin_val;
13247 	dst_reg->smax_value >>= umin_val;
13248 
13249 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13250 
13251 	/* blow away the dst_reg umin_value/umax_value and rely on
13252 	 * dst_reg var_off to refine the result.
13253 	 */
13254 	dst_reg->umin_value = 0;
13255 	dst_reg->umax_value = U64_MAX;
13256 
13257 	/* Its not easy to operate on alu32 bounds here because it depends
13258 	 * on bits being shifted in from upper 32-bits. Take easy way out
13259 	 * and mark unbounded so we can recalculate later from tnum.
13260 	 */
13261 	__mark_reg32_unbounded(dst_reg);
13262 	__update_reg_bounds(dst_reg);
13263 }
13264 
13265 /* WARNING: This function does calculations on 64-bit values, but the actual
13266  * execution may occur on 32-bit values. Therefore, things like bitshifts
13267  * need extra checks in the 32-bit case.
13268  */
13269 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13270 				      struct bpf_insn *insn,
13271 				      struct bpf_reg_state *dst_reg,
13272 				      struct bpf_reg_state src_reg)
13273 {
13274 	struct bpf_reg_state *regs = cur_regs(env);
13275 	u8 opcode = BPF_OP(insn->code);
13276 	bool src_known;
13277 	s64 smin_val, smax_val;
13278 	u64 umin_val, umax_val;
13279 	s32 s32_min_val, s32_max_val;
13280 	u32 u32_min_val, u32_max_val;
13281 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13282 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13283 	int ret;
13284 
13285 	smin_val = src_reg.smin_value;
13286 	smax_val = src_reg.smax_value;
13287 	umin_val = src_reg.umin_value;
13288 	umax_val = src_reg.umax_value;
13289 
13290 	s32_min_val = src_reg.s32_min_value;
13291 	s32_max_val = src_reg.s32_max_value;
13292 	u32_min_val = src_reg.u32_min_value;
13293 	u32_max_val = src_reg.u32_max_value;
13294 
13295 	if (alu32) {
13296 		src_known = tnum_subreg_is_const(src_reg.var_off);
13297 		if ((src_known &&
13298 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13299 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13300 			/* Taint dst register if offset had invalid bounds
13301 			 * derived from e.g. dead branches.
13302 			 */
13303 			__mark_reg_unknown(env, dst_reg);
13304 			return 0;
13305 		}
13306 	} else {
13307 		src_known = tnum_is_const(src_reg.var_off);
13308 		if ((src_known &&
13309 		     (smin_val != smax_val || umin_val != umax_val)) ||
13310 		    smin_val > smax_val || umin_val > umax_val) {
13311 			/* Taint dst register if offset had invalid bounds
13312 			 * derived from e.g. dead branches.
13313 			 */
13314 			__mark_reg_unknown(env, dst_reg);
13315 			return 0;
13316 		}
13317 	}
13318 
13319 	if (!src_known &&
13320 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13321 		__mark_reg_unknown(env, dst_reg);
13322 		return 0;
13323 	}
13324 
13325 	if (sanitize_needed(opcode)) {
13326 		ret = sanitize_val_alu(env, insn);
13327 		if (ret < 0)
13328 			return sanitize_err(env, insn, ret, NULL, NULL);
13329 	}
13330 
13331 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13332 	 * There are two classes of instructions: The first class we track both
13333 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13334 	 * greatest amount of precision when alu operations are mixed with jmp32
13335 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13336 	 * and BPF_OR. This is possible because these ops have fairly easy to
13337 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13338 	 * See alu32 verifier tests for examples. The second class of
13339 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13340 	 * with regards to tracking sign/unsigned bounds because the bits may
13341 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13342 	 * the reg unbounded in the subreg bound space and use the resulting
13343 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13344 	 */
13345 	switch (opcode) {
13346 	case BPF_ADD:
13347 		scalar32_min_max_add(dst_reg, &src_reg);
13348 		scalar_min_max_add(dst_reg, &src_reg);
13349 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13350 		break;
13351 	case BPF_SUB:
13352 		scalar32_min_max_sub(dst_reg, &src_reg);
13353 		scalar_min_max_sub(dst_reg, &src_reg);
13354 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13355 		break;
13356 	case BPF_MUL:
13357 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13358 		scalar32_min_max_mul(dst_reg, &src_reg);
13359 		scalar_min_max_mul(dst_reg, &src_reg);
13360 		break;
13361 	case BPF_AND:
13362 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13363 		scalar32_min_max_and(dst_reg, &src_reg);
13364 		scalar_min_max_and(dst_reg, &src_reg);
13365 		break;
13366 	case BPF_OR:
13367 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13368 		scalar32_min_max_or(dst_reg, &src_reg);
13369 		scalar_min_max_or(dst_reg, &src_reg);
13370 		break;
13371 	case BPF_XOR:
13372 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13373 		scalar32_min_max_xor(dst_reg, &src_reg);
13374 		scalar_min_max_xor(dst_reg, &src_reg);
13375 		break;
13376 	case BPF_LSH:
13377 		if (umax_val >= insn_bitness) {
13378 			/* Shifts greater than 31 or 63 are undefined.
13379 			 * This includes shifts by a negative number.
13380 			 */
13381 			mark_reg_unknown(env, regs, insn->dst_reg);
13382 			break;
13383 		}
13384 		if (alu32)
13385 			scalar32_min_max_lsh(dst_reg, &src_reg);
13386 		else
13387 			scalar_min_max_lsh(dst_reg, &src_reg);
13388 		break;
13389 	case BPF_RSH:
13390 		if (umax_val >= insn_bitness) {
13391 			/* Shifts greater than 31 or 63 are undefined.
13392 			 * This includes shifts by a negative number.
13393 			 */
13394 			mark_reg_unknown(env, regs, insn->dst_reg);
13395 			break;
13396 		}
13397 		if (alu32)
13398 			scalar32_min_max_rsh(dst_reg, &src_reg);
13399 		else
13400 			scalar_min_max_rsh(dst_reg, &src_reg);
13401 		break;
13402 	case BPF_ARSH:
13403 		if (umax_val >= insn_bitness) {
13404 			/* Shifts greater than 31 or 63 are undefined.
13405 			 * This includes shifts by a negative number.
13406 			 */
13407 			mark_reg_unknown(env, regs, insn->dst_reg);
13408 			break;
13409 		}
13410 		if (alu32)
13411 			scalar32_min_max_arsh(dst_reg, &src_reg);
13412 		else
13413 			scalar_min_max_arsh(dst_reg, &src_reg);
13414 		break;
13415 	default:
13416 		mark_reg_unknown(env, regs, insn->dst_reg);
13417 		break;
13418 	}
13419 
13420 	/* ALU32 ops are zero extended into 64bit register */
13421 	if (alu32)
13422 		zext_32_to_64(dst_reg);
13423 	reg_bounds_sync(dst_reg);
13424 	return 0;
13425 }
13426 
13427 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13428  * and var_off.
13429  */
13430 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13431 				   struct bpf_insn *insn)
13432 {
13433 	struct bpf_verifier_state *vstate = env->cur_state;
13434 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13435 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13436 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13437 	u8 opcode = BPF_OP(insn->code);
13438 	int err;
13439 
13440 	dst_reg = &regs[insn->dst_reg];
13441 	src_reg = NULL;
13442 	if (dst_reg->type != SCALAR_VALUE)
13443 		ptr_reg = dst_reg;
13444 	else
13445 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13446 		 * incorrectly propagated into other registers by find_equal_scalars()
13447 		 */
13448 		dst_reg->id = 0;
13449 	if (BPF_SRC(insn->code) == BPF_X) {
13450 		src_reg = &regs[insn->src_reg];
13451 		if (src_reg->type != SCALAR_VALUE) {
13452 			if (dst_reg->type != SCALAR_VALUE) {
13453 				/* Combining two pointers by any ALU op yields
13454 				 * an arbitrary scalar. Disallow all math except
13455 				 * pointer subtraction
13456 				 */
13457 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13458 					mark_reg_unknown(env, regs, insn->dst_reg);
13459 					return 0;
13460 				}
13461 				verbose(env, "R%d pointer %s pointer prohibited\n",
13462 					insn->dst_reg,
13463 					bpf_alu_string[opcode >> 4]);
13464 				return -EACCES;
13465 			} else {
13466 				/* scalar += pointer
13467 				 * This is legal, but we have to reverse our
13468 				 * src/dest handling in computing the range
13469 				 */
13470 				err = mark_chain_precision(env, insn->dst_reg);
13471 				if (err)
13472 					return err;
13473 				return adjust_ptr_min_max_vals(env, insn,
13474 							       src_reg, dst_reg);
13475 			}
13476 		} else if (ptr_reg) {
13477 			/* pointer += scalar */
13478 			err = mark_chain_precision(env, insn->src_reg);
13479 			if (err)
13480 				return err;
13481 			return adjust_ptr_min_max_vals(env, insn,
13482 						       dst_reg, src_reg);
13483 		} else if (dst_reg->precise) {
13484 			/* if dst_reg is precise, src_reg should be precise as well */
13485 			err = mark_chain_precision(env, insn->src_reg);
13486 			if (err)
13487 				return err;
13488 		}
13489 	} else {
13490 		/* Pretend the src is a reg with a known value, since we only
13491 		 * need to be able to read from this state.
13492 		 */
13493 		off_reg.type = SCALAR_VALUE;
13494 		__mark_reg_known(&off_reg, insn->imm);
13495 		src_reg = &off_reg;
13496 		if (ptr_reg) /* pointer += K */
13497 			return adjust_ptr_min_max_vals(env, insn,
13498 						       ptr_reg, src_reg);
13499 	}
13500 
13501 	/* Got here implies adding two SCALAR_VALUEs */
13502 	if (WARN_ON_ONCE(ptr_reg)) {
13503 		print_verifier_state(env, state, true);
13504 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13505 		return -EINVAL;
13506 	}
13507 	if (WARN_ON(!src_reg)) {
13508 		print_verifier_state(env, state, true);
13509 		verbose(env, "verifier internal error: no src_reg\n");
13510 		return -EINVAL;
13511 	}
13512 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13513 }
13514 
13515 /* check validity of 32-bit and 64-bit arithmetic operations */
13516 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13517 {
13518 	struct bpf_reg_state *regs = cur_regs(env);
13519 	u8 opcode = BPF_OP(insn->code);
13520 	int err;
13521 
13522 	if (opcode == BPF_END || opcode == BPF_NEG) {
13523 		if (opcode == BPF_NEG) {
13524 			if (BPF_SRC(insn->code) != BPF_K ||
13525 			    insn->src_reg != BPF_REG_0 ||
13526 			    insn->off != 0 || insn->imm != 0) {
13527 				verbose(env, "BPF_NEG uses reserved fields\n");
13528 				return -EINVAL;
13529 			}
13530 		} else {
13531 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13532 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13533 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13534 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13535 				verbose(env, "BPF_END uses reserved fields\n");
13536 				return -EINVAL;
13537 			}
13538 		}
13539 
13540 		/* check src operand */
13541 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13542 		if (err)
13543 			return err;
13544 
13545 		if (is_pointer_value(env, insn->dst_reg)) {
13546 			verbose(env, "R%d pointer arithmetic prohibited\n",
13547 				insn->dst_reg);
13548 			return -EACCES;
13549 		}
13550 
13551 		/* check dest operand */
13552 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13553 		if (err)
13554 			return err;
13555 
13556 	} else if (opcode == BPF_MOV) {
13557 
13558 		if (BPF_SRC(insn->code) == BPF_X) {
13559 			if (insn->imm != 0) {
13560 				verbose(env, "BPF_MOV uses reserved fields\n");
13561 				return -EINVAL;
13562 			}
13563 
13564 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13565 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13566 					verbose(env, "BPF_MOV uses reserved fields\n");
13567 					return -EINVAL;
13568 				}
13569 			} else {
13570 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13571 				    insn->off != 32) {
13572 					verbose(env, "BPF_MOV uses reserved fields\n");
13573 					return -EINVAL;
13574 				}
13575 			}
13576 
13577 			/* check src operand */
13578 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13579 			if (err)
13580 				return err;
13581 		} else {
13582 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13583 				verbose(env, "BPF_MOV uses reserved fields\n");
13584 				return -EINVAL;
13585 			}
13586 		}
13587 
13588 		/* check dest operand, mark as required later */
13589 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13590 		if (err)
13591 			return err;
13592 
13593 		if (BPF_SRC(insn->code) == BPF_X) {
13594 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13595 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13596 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13597 				       !tnum_is_const(src_reg->var_off);
13598 
13599 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13600 				if (insn->off == 0) {
13601 					/* case: R1 = R2
13602 					 * copy register state to dest reg
13603 					 */
13604 					if (need_id)
13605 						/* Assign src and dst registers the same ID
13606 						 * that will be used by find_equal_scalars()
13607 						 * to propagate min/max range.
13608 						 */
13609 						src_reg->id = ++env->id_gen;
13610 					copy_register_state(dst_reg, src_reg);
13611 					dst_reg->live |= REG_LIVE_WRITTEN;
13612 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13613 				} else {
13614 					/* case: R1 = (s8, s16 s32)R2 */
13615 					if (is_pointer_value(env, insn->src_reg)) {
13616 						verbose(env,
13617 							"R%d sign-extension part of pointer\n",
13618 							insn->src_reg);
13619 						return -EACCES;
13620 					} else if (src_reg->type == SCALAR_VALUE) {
13621 						bool no_sext;
13622 
13623 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13624 						if (no_sext && need_id)
13625 							src_reg->id = ++env->id_gen;
13626 						copy_register_state(dst_reg, src_reg);
13627 						if (!no_sext)
13628 							dst_reg->id = 0;
13629 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13630 						dst_reg->live |= REG_LIVE_WRITTEN;
13631 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13632 					} else {
13633 						mark_reg_unknown(env, regs, insn->dst_reg);
13634 					}
13635 				}
13636 			} else {
13637 				/* R1 = (u32) R2 */
13638 				if (is_pointer_value(env, insn->src_reg)) {
13639 					verbose(env,
13640 						"R%d partial copy of pointer\n",
13641 						insn->src_reg);
13642 					return -EACCES;
13643 				} else if (src_reg->type == SCALAR_VALUE) {
13644 					if (insn->off == 0) {
13645 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13646 
13647 						if (is_src_reg_u32 && need_id)
13648 							src_reg->id = ++env->id_gen;
13649 						copy_register_state(dst_reg, src_reg);
13650 						/* Make sure ID is cleared if src_reg is not in u32
13651 						 * range otherwise dst_reg min/max could be incorrectly
13652 						 * propagated into src_reg by find_equal_scalars()
13653 						 */
13654 						if (!is_src_reg_u32)
13655 							dst_reg->id = 0;
13656 						dst_reg->live |= REG_LIVE_WRITTEN;
13657 						dst_reg->subreg_def = env->insn_idx + 1;
13658 					} else {
13659 						/* case: W1 = (s8, s16)W2 */
13660 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13661 
13662 						if (no_sext && need_id)
13663 							src_reg->id = ++env->id_gen;
13664 						copy_register_state(dst_reg, src_reg);
13665 						if (!no_sext)
13666 							dst_reg->id = 0;
13667 						dst_reg->live |= REG_LIVE_WRITTEN;
13668 						dst_reg->subreg_def = env->insn_idx + 1;
13669 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13670 					}
13671 				} else {
13672 					mark_reg_unknown(env, regs,
13673 							 insn->dst_reg);
13674 				}
13675 				zext_32_to_64(dst_reg);
13676 				reg_bounds_sync(dst_reg);
13677 			}
13678 		} else {
13679 			/* case: R = imm
13680 			 * remember the value we stored into this reg
13681 			 */
13682 			/* clear any state __mark_reg_known doesn't set */
13683 			mark_reg_unknown(env, regs, insn->dst_reg);
13684 			regs[insn->dst_reg].type = SCALAR_VALUE;
13685 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13686 				__mark_reg_known(regs + insn->dst_reg,
13687 						 insn->imm);
13688 			} else {
13689 				__mark_reg_known(regs + insn->dst_reg,
13690 						 (u32)insn->imm);
13691 			}
13692 		}
13693 
13694 	} else if (opcode > BPF_END) {
13695 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13696 		return -EINVAL;
13697 
13698 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13699 
13700 		if (BPF_SRC(insn->code) == BPF_X) {
13701 			if (insn->imm != 0 || insn->off > 1 ||
13702 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13703 				verbose(env, "BPF_ALU uses reserved fields\n");
13704 				return -EINVAL;
13705 			}
13706 			/* check src1 operand */
13707 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13708 			if (err)
13709 				return err;
13710 		} else {
13711 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13712 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13713 				verbose(env, "BPF_ALU uses reserved fields\n");
13714 				return -EINVAL;
13715 			}
13716 		}
13717 
13718 		/* check src2 operand */
13719 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13720 		if (err)
13721 			return err;
13722 
13723 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13724 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13725 			verbose(env, "div by zero\n");
13726 			return -EINVAL;
13727 		}
13728 
13729 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13730 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13731 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13732 
13733 			if (insn->imm < 0 || insn->imm >= size) {
13734 				verbose(env, "invalid shift %d\n", insn->imm);
13735 				return -EINVAL;
13736 			}
13737 		}
13738 
13739 		/* check dest operand */
13740 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13741 		if (err)
13742 			return err;
13743 
13744 		return adjust_reg_min_max_vals(env, insn);
13745 	}
13746 
13747 	return 0;
13748 }
13749 
13750 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13751 				   struct bpf_reg_state *dst_reg,
13752 				   enum bpf_reg_type type,
13753 				   bool range_right_open)
13754 {
13755 	struct bpf_func_state *state;
13756 	struct bpf_reg_state *reg;
13757 	int new_range;
13758 
13759 	if (dst_reg->off < 0 ||
13760 	    (dst_reg->off == 0 && range_right_open))
13761 		/* This doesn't give us any range */
13762 		return;
13763 
13764 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13765 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13766 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13767 		 * than pkt_end, but that's because it's also less than pkt.
13768 		 */
13769 		return;
13770 
13771 	new_range = dst_reg->off;
13772 	if (range_right_open)
13773 		new_range++;
13774 
13775 	/* Examples for register markings:
13776 	 *
13777 	 * pkt_data in dst register:
13778 	 *
13779 	 *   r2 = r3;
13780 	 *   r2 += 8;
13781 	 *   if (r2 > pkt_end) goto <handle exception>
13782 	 *   <access okay>
13783 	 *
13784 	 *   r2 = r3;
13785 	 *   r2 += 8;
13786 	 *   if (r2 < pkt_end) goto <access okay>
13787 	 *   <handle exception>
13788 	 *
13789 	 *   Where:
13790 	 *     r2 == dst_reg, pkt_end == src_reg
13791 	 *     r2=pkt(id=n,off=8,r=0)
13792 	 *     r3=pkt(id=n,off=0,r=0)
13793 	 *
13794 	 * pkt_data in src register:
13795 	 *
13796 	 *   r2 = r3;
13797 	 *   r2 += 8;
13798 	 *   if (pkt_end >= r2) goto <access okay>
13799 	 *   <handle exception>
13800 	 *
13801 	 *   r2 = r3;
13802 	 *   r2 += 8;
13803 	 *   if (pkt_end <= r2) goto <handle exception>
13804 	 *   <access okay>
13805 	 *
13806 	 *   Where:
13807 	 *     pkt_end == dst_reg, r2 == src_reg
13808 	 *     r2=pkt(id=n,off=8,r=0)
13809 	 *     r3=pkt(id=n,off=0,r=0)
13810 	 *
13811 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13812 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13813 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13814 	 * the check.
13815 	 */
13816 
13817 	/* If our ids match, then we must have the same max_value.  And we
13818 	 * don't care about the other reg's fixed offset, since if it's too big
13819 	 * the range won't allow anything.
13820 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13821 	 */
13822 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13823 		if (reg->type == type && reg->id == dst_reg->id)
13824 			/* keep the maximum range already checked */
13825 			reg->range = max(reg->range, new_range);
13826 	}));
13827 }
13828 
13829 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13830 {
13831 	struct tnum subreg = tnum_subreg(reg->var_off);
13832 	s32 sval = (s32)val;
13833 
13834 	switch (opcode) {
13835 	case BPF_JEQ:
13836 		if (tnum_is_const(subreg))
13837 			return !!tnum_equals_const(subreg, val);
13838 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13839 			return 0;
13840 		break;
13841 	case BPF_JNE:
13842 		if (tnum_is_const(subreg))
13843 			return !tnum_equals_const(subreg, val);
13844 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13845 			return 1;
13846 		break;
13847 	case BPF_JSET:
13848 		if ((~subreg.mask & subreg.value) & val)
13849 			return 1;
13850 		if (!((subreg.mask | subreg.value) & val))
13851 			return 0;
13852 		break;
13853 	case BPF_JGT:
13854 		if (reg->u32_min_value > val)
13855 			return 1;
13856 		else if (reg->u32_max_value <= val)
13857 			return 0;
13858 		break;
13859 	case BPF_JSGT:
13860 		if (reg->s32_min_value > sval)
13861 			return 1;
13862 		else if (reg->s32_max_value <= sval)
13863 			return 0;
13864 		break;
13865 	case BPF_JLT:
13866 		if (reg->u32_max_value < val)
13867 			return 1;
13868 		else if (reg->u32_min_value >= val)
13869 			return 0;
13870 		break;
13871 	case BPF_JSLT:
13872 		if (reg->s32_max_value < sval)
13873 			return 1;
13874 		else if (reg->s32_min_value >= sval)
13875 			return 0;
13876 		break;
13877 	case BPF_JGE:
13878 		if (reg->u32_min_value >= val)
13879 			return 1;
13880 		else if (reg->u32_max_value < val)
13881 			return 0;
13882 		break;
13883 	case BPF_JSGE:
13884 		if (reg->s32_min_value >= sval)
13885 			return 1;
13886 		else if (reg->s32_max_value < sval)
13887 			return 0;
13888 		break;
13889 	case BPF_JLE:
13890 		if (reg->u32_max_value <= val)
13891 			return 1;
13892 		else if (reg->u32_min_value > val)
13893 			return 0;
13894 		break;
13895 	case BPF_JSLE:
13896 		if (reg->s32_max_value <= sval)
13897 			return 1;
13898 		else if (reg->s32_min_value > sval)
13899 			return 0;
13900 		break;
13901 	}
13902 
13903 	return -1;
13904 }
13905 
13906 
13907 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13908 {
13909 	s64 sval = (s64)val;
13910 
13911 	switch (opcode) {
13912 	case BPF_JEQ:
13913 		if (tnum_is_const(reg->var_off))
13914 			return !!tnum_equals_const(reg->var_off, val);
13915 		else if (val < reg->umin_value || val > reg->umax_value)
13916 			return 0;
13917 		break;
13918 	case BPF_JNE:
13919 		if (tnum_is_const(reg->var_off))
13920 			return !tnum_equals_const(reg->var_off, val);
13921 		else if (val < reg->umin_value || val > reg->umax_value)
13922 			return 1;
13923 		break;
13924 	case BPF_JSET:
13925 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13926 			return 1;
13927 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13928 			return 0;
13929 		break;
13930 	case BPF_JGT:
13931 		if (reg->umin_value > val)
13932 			return 1;
13933 		else if (reg->umax_value <= val)
13934 			return 0;
13935 		break;
13936 	case BPF_JSGT:
13937 		if (reg->smin_value > sval)
13938 			return 1;
13939 		else if (reg->smax_value <= sval)
13940 			return 0;
13941 		break;
13942 	case BPF_JLT:
13943 		if (reg->umax_value < val)
13944 			return 1;
13945 		else if (reg->umin_value >= val)
13946 			return 0;
13947 		break;
13948 	case BPF_JSLT:
13949 		if (reg->smax_value < sval)
13950 			return 1;
13951 		else if (reg->smin_value >= sval)
13952 			return 0;
13953 		break;
13954 	case BPF_JGE:
13955 		if (reg->umin_value >= val)
13956 			return 1;
13957 		else if (reg->umax_value < val)
13958 			return 0;
13959 		break;
13960 	case BPF_JSGE:
13961 		if (reg->smin_value >= sval)
13962 			return 1;
13963 		else if (reg->smax_value < sval)
13964 			return 0;
13965 		break;
13966 	case BPF_JLE:
13967 		if (reg->umax_value <= val)
13968 			return 1;
13969 		else if (reg->umin_value > val)
13970 			return 0;
13971 		break;
13972 	case BPF_JSLE:
13973 		if (reg->smax_value <= sval)
13974 			return 1;
13975 		else if (reg->smin_value > sval)
13976 			return 0;
13977 		break;
13978 	}
13979 
13980 	return -1;
13981 }
13982 
13983 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13984  * and return:
13985  *  1 - branch will be taken and "goto target" will be executed
13986  *  0 - branch will not be taken and fall-through to next insn
13987  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13988  *      range [0,10]
13989  */
13990 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13991 			   bool is_jmp32)
13992 {
13993 	if (__is_pointer_value(false, reg)) {
13994 		if (!reg_not_null(reg))
13995 			return -1;
13996 
13997 		/* If pointer is valid tests against zero will fail so we can
13998 		 * use this to direct branch taken.
13999 		 */
14000 		if (val != 0)
14001 			return -1;
14002 
14003 		switch (opcode) {
14004 		case BPF_JEQ:
14005 			return 0;
14006 		case BPF_JNE:
14007 			return 1;
14008 		default:
14009 			return -1;
14010 		}
14011 	}
14012 
14013 	if (is_jmp32)
14014 		return is_branch32_taken(reg, val, opcode);
14015 	return is_branch64_taken(reg, val, opcode);
14016 }
14017 
14018 static int flip_opcode(u32 opcode)
14019 {
14020 	/* How can we transform "a <op> b" into "b <op> a"? */
14021 	static const u8 opcode_flip[16] = {
14022 		/* these stay the same */
14023 		[BPF_JEQ  >> 4] = BPF_JEQ,
14024 		[BPF_JNE  >> 4] = BPF_JNE,
14025 		[BPF_JSET >> 4] = BPF_JSET,
14026 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14027 		[BPF_JGE  >> 4] = BPF_JLE,
14028 		[BPF_JGT  >> 4] = BPF_JLT,
14029 		[BPF_JLE  >> 4] = BPF_JGE,
14030 		[BPF_JLT  >> 4] = BPF_JGT,
14031 		[BPF_JSGE >> 4] = BPF_JSLE,
14032 		[BPF_JSGT >> 4] = BPF_JSLT,
14033 		[BPF_JSLE >> 4] = BPF_JSGE,
14034 		[BPF_JSLT >> 4] = BPF_JSGT
14035 	};
14036 	return opcode_flip[opcode >> 4];
14037 }
14038 
14039 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14040 				   struct bpf_reg_state *src_reg,
14041 				   u8 opcode)
14042 {
14043 	struct bpf_reg_state *pkt;
14044 
14045 	if (src_reg->type == PTR_TO_PACKET_END) {
14046 		pkt = dst_reg;
14047 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14048 		pkt = src_reg;
14049 		opcode = flip_opcode(opcode);
14050 	} else {
14051 		return -1;
14052 	}
14053 
14054 	if (pkt->range >= 0)
14055 		return -1;
14056 
14057 	switch (opcode) {
14058 	case BPF_JLE:
14059 		/* pkt <= pkt_end */
14060 		fallthrough;
14061 	case BPF_JGT:
14062 		/* pkt > pkt_end */
14063 		if (pkt->range == BEYOND_PKT_END)
14064 			/* pkt has at last one extra byte beyond pkt_end */
14065 			return opcode == BPF_JGT;
14066 		break;
14067 	case BPF_JLT:
14068 		/* pkt < pkt_end */
14069 		fallthrough;
14070 	case BPF_JGE:
14071 		/* pkt >= pkt_end */
14072 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14073 			return opcode == BPF_JGE;
14074 		break;
14075 	}
14076 	return -1;
14077 }
14078 
14079 /* Adjusts the register min/max values in the case that the dst_reg is the
14080  * variable register that we are working on, and src_reg is a constant or we're
14081  * simply doing a BPF_K check.
14082  * In JEQ/JNE cases we also adjust the var_off values.
14083  */
14084 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14085 			    struct bpf_reg_state *false_reg,
14086 			    u64 val, u32 val32,
14087 			    u8 opcode, bool is_jmp32)
14088 {
14089 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14090 	struct tnum false_64off = false_reg->var_off;
14091 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14092 	struct tnum true_64off = true_reg->var_off;
14093 	s64 sval = (s64)val;
14094 	s32 sval32 = (s32)val32;
14095 
14096 	/* If the dst_reg is a pointer, we can't learn anything about its
14097 	 * variable offset from the compare (unless src_reg were a pointer into
14098 	 * the same object, but we don't bother with that.
14099 	 * Since false_reg and true_reg have the same type by construction, we
14100 	 * only need to check one of them for pointerness.
14101 	 */
14102 	if (__is_pointer_value(false, false_reg))
14103 		return;
14104 
14105 	switch (opcode) {
14106 	/* JEQ/JNE comparison doesn't change the register equivalence.
14107 	 *
14108 	 * r1 = r2;
14109 	 * if (r1 == 42) goto label;
14110 	 * ...
14111 	 * label: // here both r1 and r2 are known to be 42.
14112 	 *
14113 	 * Hence when marking register as known preserve it's ID.
14114 	 */
14115 	case BPF_JEQ:
14116 		if (is_jmp32) {
14117 			__mark_reg32_known(true_reg, val32);
14118 			true_32off = tnum_subreg(true_reg->var_off);
14119 		} else {
14120 			___mark_reg_known(true_reg, val);
14121 			true_64off = true_reg->var_off;
14122 		}
14123 		break;
14124 	case BPF_JNE:
14125 		if (is_jmp32) {
14126 			__mark_reg32_known(false_reg, val32);
14127 			false_32off = tnum_subreg(false_reg->var_off);
14128 		} else {
14129 			___mark_reg_known(false_reg, val);
14130 			false_64off = false_reg->var_off;
14131 		}
14132 		break;
14133 	case BPF_JSET:
14134 		if (is_jmp32) {
14135 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14136 			if (is_power_of_2(val32))
14137 				true_32off = tnum_or(true_32off,
14138 						     tnum_const(val32));
14139 		} else {
14140 			false_64off = tnum_and(false_64off, tnum_const(~val));
14141 			if (is_power_of_2(val))
14142 				true_64off = tnum_or(true_64off,
14143 						     tnum_const(val));
14144 		}
14145 		break;
14146 	case BPF_JGE:
14147 	case BPF_JGT:
14148 	{
14149 		if (is_jmp32) {
14150 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14151 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14152 
14153 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14154 						       false_umax);
14155 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14156 						      true_umin);
14157 		} else {
14158 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14159 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14160 
14161 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14162 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14163 		}
14164 		break;
14165 	}
14166 	case BPF_JSGE:
14167 	case BPF_JSGT:
14168 	{
14169 		if (is_jmp32) {
14170 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14171 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14172 
14173 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14174 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14175 		} else {
14176 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14177 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14178 
14179 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14180 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14181 		}
14182 		break;
14183 	}
14184 	case BPF_JLE:
14185 	case BPF_JLT:
14186 	{
14187 		if (is_jmp32) {
14188 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14189 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14190 
14191 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14192 						       false_umin);
14193 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14194 						      true_umax);
14195 		} else {
14196 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14197 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14198 
14199 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14200 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14201 		}
14202 		break;
14203 	}
14204 	case BPF_JSLE:
14205 	case BPF_JSLT:
14206 	{
14207 		if (is_jmp32) {
14208 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14209 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14210 
14211 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14212 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14213 		} else {
14214 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14215 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14216 
14217 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14218 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14219 		}
14220 		break;
14221 	}
14222 	default:
14223 		return;
14224 	}
14225 
14226 	if (is_jmp32) {
14227 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14228 					     tnum_subreg(false_32off));
14229 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14230 					    tnum_subreg(true_32off));
14231 		__reg_combine_32_into_64(false_reg);
14232 		__reg_combine_32_into_64(true_reg);
14233 	} else {
14234 		false_reg->var_off = false_64off;
14235 		true_reg->var_off = true_64off;
14236 		__reg_combine_64_into_32(false_reg);
14237 		__reg_combine_64_into_32(true_reg);
14238 	}
14239 }
14240 
14241 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14242  * the variable reg.
14243  */
14244 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14245 				struct bpf_reg_state *false_reg,
14246 				u64 val, u32 val32,
14247 				u8 opcode, bool is_jmp32)
14248 {
14249 	opcode = flip_opcode(opcode);
14250 	/* This uses zero as "not present in table"; luckily the zero opcode,
14251 	 * BPF_JA, can't get here.
14252 	 */
14253 	if (opcode)
14254 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14255 }
14256 
14257 /* Regs are known to be equal, so intersect their min/max/var_off */
14258 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14259 				  struct bpf_reg_state *dst_reg)
14260 {
14261 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14262 							dst_reg->umin_value);
14263 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14264 							dst_reg->umax_value);
14265 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14266 							dst_reg->smin_value);
14267 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14268 							dst_reg->smax_value);
14269 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14270 							     dst_reg->var_off);
14271 	reg_bounds_sync(src_reg);
14272 	reg_bounds_sync(dst_reg);
14273 }
14274 
14275 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14276 				struct bpf_reg_state *true_dst,
14277 				struct bpf_reg_state *false_src,
14278 				struct bpf_reg_state *false_dst,
14279 				u8 opcode)
14280 {
14281 	switch (opcode) {
14282 	case BPF_JEQ:
14283 		__reg_combine_min_max(true_src, true_dst);
14284 		break;
14285 	case BPF_JNE:
14286 		__reg_combine_min_max(false_src, false_dst);
14287 		break;
14288 	}
14289 }
14290 
14291 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14292 				 struct bpf_reg_state *reg, u32 id,
14293 				 bool is_null)
14294 {
14295 	if (type_may_be_null(reg->type) && reg->id == id &&
14296 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14297 		/* Old offset (both fixed and variable parts) should have been
14298 		 * known-zero, because we don't allow pointer arithmetic on
14299 		 * pointers that might be NULL. If we see this happening, don't
14300 		 * convert the register.
14301 		 *
14302 		 * But in some cases, some helpers that return local kptrs
14303 		 * advance offset for the returned pointer. In those cases, it
14304 		 * is fine to expect to see reg->off.
14305 		 */
14306 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14307 			return;
14308 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14309 		    WARN_ON_ONCE(reg->off))
14310 			return;
14311 
14312 		if (is_null) {
14313 			reg->type = SCALAR_VALUE;
14314 			/* We don't need id and ref_obj_id from this point
14315 			 * onwards anymore, thus we should better reset it,
14316 			 * so that state pruning has chances to take effect.
14317 			 */
14318 			reg->id = 0;
14319 			reg->ref_obj_id = 0;
14320 
14321 			return;
14322 		}
14323 
14324 		mark_ptr_not_null_reg(reg);
14325 
14326 		if (!reg_may_point_to_spin_lock(reg)) {
14327 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14328 			 * in release_reference().
14329 			 *
14330 			 * reg->id is still used by spin_lock ptr. Other
14331 			 * than spin_lock ptr type, reg->id can be reset.
14332 			 */
14333 			reg->id = 0;
14334 		}
14335 	}
14336 }
14337 
14338 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14339  * be folded together at some point.
14340  */
14341 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14342 				  bool is_null)
14343 {
14344 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14345 	struct bpf_reg_state *regs = state->regs, *reg;
14346 	u32 ref_obj_id = regs[regno].ref_obj_id;
14347 	u32 id = regs[regno].id;
14348 
14349 	if (ref_obj_id && ref_obj_id == id && is_null)
14350 		/* regs[regno] is in the " == NULL" branch.
14351 		 * No one could have freed the reference state before
14352 		 * doing the NULL check.
14353 		 */
14354 		WARN_ON_ONCE(release_reference_state(state, id));
14355 
14356 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14357 		mark_ptr_or_null_reg(state, reg, id, is_null);
14358 	}));
14359 }
14360 
14361 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14362 				   struct bpf_reg_state *dst_reg,
14363 				   struct bpf_reg_state *src_reg,
14364 				   struct bpf_verifier_state *this_branch,
14365 				   struct bpf_verifier_state *other_branch)
14366 {
14367 	if (BPF_SRC(insn->code) != BPF_X)
14368 		return false;
14369 
14370 	/* Pointers are always 64-bit. */
14371 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14372 		return false;
14373 
14374 	switch (BPF_OP(insn->code)) {
14375 	case BPF_JGT:
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(this_branch, dst_reg,
14382 					       dst_reg->type, false);
14383 			mark_pkt_end(other_branch, insn->dst_reg, true);
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(other_branch, src_reg,
14390 					       src_reg->type, true);
14391 			mark_pkt_end(this_branch, insn->src_reg, false);
14392 		} else {
14393 			return false;
14394 		}
14395 		break;
14396 	case BPF_JLT:
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(other_branch, dst_reg,
14403 					       dst_reg->type, true);
14404 			mark_pkt_end(this_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(this_branch, src_reg,
14411 					       src_reg->type, false);
14412 			mark_pkt_end(other_branch, insn->src_reg, true);
14413 		} else {
14414 			return false;
14415 		}
14416 		break;
14417 	case BPF_JGE:
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(this_branch, dst_reg,
14424 					       dst_reg->type, true);
14425 			mark_pkt_end(other_branch, insn->dst_reg, false);
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(other_branch, src_reg,
14432 					       src_reg->type, false);
14433 			mark_pkt_end(this_branch, insn->src_reg, true);
14434 		} else {
14435 			return false;
14436 		}
14437 		break;
14438 	case BPF_JLE:
14439 		if ((dst_reg->type == PTR_TO_PACKET &&
14440 		     src_reg->type == PTR_TO_PACKET_END) ||
14441 		    (dst_reg->type == PTR_TO_PACKET_META &&
14442 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14443 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14444 			find_good_pkt_pointers(other_branch, dst_reg,
14445 					       dst_reg->type, false);
14446 			mark_pkt_end(this_branch, insn->dst_reg, true);
14447 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14448 			    src_reg->type == PTR_TO_PACKET) ||
14449 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14450 			    src_reg->type == PTR_TO_PACKET_META)) {
14451 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14452 			find_good_pkt_pointers(this_branch, src_reg,
14453 					       src_reg->type, true);
14454 			mark_pkt_end(other_branch, insn->src_reg, false);
14455 		} else {
14456 			return false;
14457 		}
14458 		break;
14459 	default:
14460 		return false;
14461 	}
14462 
14463 	return true;
14464 }
14465 
14466 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14467 			       struct bpf_reg_state *known_reg)
14468 {
14469 	struct bpf_func_state *state;
14470 	struct bpf_reg_state *reg;
14471 
14472 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14473 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14474 			copy_register_state(reg, known_reg);
14475 	}));
14476 }
14477 
14478 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14479 			     struct bpf_insn *insn, int *insn_idx)
14480 {
14481 	struct bpf_verifier_state *this_branch = env->cur_state;
14482 	struct bpf_verifier_state *other_branch;
14483 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14484 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14485 	struct bpf_reg_state *eq_branch_regs;
14486 	u8 opcode = BPF_OP(insn->code);
14487 	bool is_jmp32;
14488 	int pred = -1;
14489 	int err;
14490 
14491 	/* Only conditional jumps are expected to reach here. */
14492 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14493 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14494 		return -EINVAL;
14495 	}
14496 
14497 	/* check src2 operand */
14498 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14499 	if (err)
14500 		return err;
14501 
14502 	dst_reg = &regs[insn->dst_reg];
14503 	if (BPF_SRC(insn->code) == BPF_X) {
14504 		if (insn->imm != 0) {
14505 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14506 			return -EINVAL;
14507 		}
14508 
14509 		/* check src1 operand */
14510 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14511 		if (err)
14512 			return err;
14513 
14514 		src_reg = &regs[insn->src_reg];
14515 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14516 		    is_pointer_value(env, insn->src_reg)) {
14517 			verbose(env, "R%d pointer comparison prohibited\n",
14518 				insn->src_reg);
14519 			return -EACCES;
14520 		}
14521 	} else {
14522 		if (insn->src_reg != BPF_REG_0) {
14523 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14524 			return -EINVAL;
14525 		}
14526 	}
14527 
14528 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14529 
14530 	if (BPF_SRC(insn->code) == BPF_K) {
14531 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14532 	} else if (src_reg->type == SCALAR_VALUE &&
14533 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14534 		pred = is_branch_taken(dst_reg,
14535 				       tnum_subreg(src_reg->var_off).value,
14536 				       opcode,
14537 				       is_jmp32);
14538 	} else if (src_reg->type == SCALAR_VALUE &&
14539 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14540 		pred = is_branch_taken(dst_reg,
14541 				       src_reg->var_off.value,
14542 				       opcode,
14543 				       is_jmp32);
14544 	} else if (dst_reg->type == SCALAR_VALUE &&
14545 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14546 		pred = is_branch_taken(src_reg,
14547 				       tnum_subreg(dst_reg->var_off).value,
14548 				       flip_opcode(opcode),
14549 				       is_jmp32);
14550 	} else if (dst_reg->type == SCALAR_VALUE &&
14551 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14552 		pred = is_branch_taken(src_reg,
14553 				       dst_reg->var_off.value,
14554 				       flip_opcode(opcode),
14555 				       is_jmp32);
14556 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14557 		   reg_is_pkt_pointer_any(src_reg) &&
14558 		   !is_jmp32) {
14559 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14560 	}
14561 
14562 	if (pred >= 0) {
14563 		/* If we get here with a dst_reg pointer type it is because
14564 		 * above is_branch_taken() special cased the 0 comparison.
14565 		 */
14566 		if (!__is_pointer_value(false, dst_reg))
14567 			err = mark_chain_precision(env, insn->dst_reg);
14568 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14569 		    !__is_pointer_value(false, src_reg))
14570 			err = mark_chain_precision(env, insn->src_reg);
14571 		if (err)
14572 			return err;
14573 	}
14574 
14575 	if (pred == 1) {
14576 		/* Only follow the goto, ignore fall-through. If needed, push
14577 		 * the fall-through branch for simulation under speculative
14578 		 * execution.
14579 		 */
14580 		if (!env->bypass_spec_v1 &&
14581 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14582 					       *insn_idx))
14583 			return -EFAULT;
14584 		if (env->log.level & BPF_LOG_LEVEL)
14585 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14586 		*insn_idx += insn->off;
14587 		return 0;
14588 	} else if (pred == 0) {
14589 		/* Only follow the fall-through branch, since that's where the
14590 		 * program will go. If needed, push the goto branch for
14591 		 * simulation under speculative execution.
14592 		 */
14593 		if (!env->bypass_spec_v1 &&
14594 		    !sanitize_speculative_path(env, insn,
14595 					       *insn_idx + insn->off + 1,
14596 					       *insn_idx))
14597 			return -EFAULT;
14598 		if (env->log.level & BPF_LOG_LEVEL)
14599 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14600 		return 0;
14601 	}
14602 
14603 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14604 				  false);
14605 	if (!other_branch)
14606 		return -EFAULT;
14607 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14608 
14609 	/* detect if we are comparing against a constant value so we can adjust
14610 	 * our min/max values for our dst register.
14611 	 * this is only legit if both are scalars (or pointers to the same
14612 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14613 	 * because otherwise the different base pointers mean the offsets aren't
14614 	 * comparable.
14615 	 */
14616 	if (BPF_SRC(insn->code) == BPF_X) {
14617 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14618 
14619 		if (dst_reg->type == SCALAR_VALUE &&
14620 		    src_reg->type == SCALAR_VALUE) {
14621 			if (tnum_is_const(src_reg->var_off) ||
14622 			    (is_jmp32 &&
14623 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14624 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14625 						dst_reg,
14626 						src_reg->var_off.value,
14627 						tnum_subreg(src_reg->var_off).value,
14628 						opcode, is_jmp32);
14629 			else if (tnum_is_const(dst_reg->var_off) ||
14630 				 (is_jmp32 &&
14631 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14632 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14633 						    src_reg,
14634 						    dst_reg->var_off.value,
14635 						    tnum_subreg(dst_reg->var_off).value,
14636 						    opcode, is_jmp32);
14637 			else if (!is_jmp32 &&
14638 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14639 				/* Comparing for equality, we can combine knowledge */
14640 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14641 						    &other_branch_regs[insn->dst_reg],
14642 						    src_reg, dst_reg, opcode);
14643 			if (src_reg->id &&
14644 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14645 				find_equal_scalars(this_branch, src_reg);
14646 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14647 			}
14648 
14649 		}
14650 	} else if (dst_reg->type == SCALAR_VALUE) {
14651 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14652 					dst_reg, insn->imm, (u32)insn->imm,
14653 					opcode, is_jmp32);
14654 	}
14655 
14656 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14657 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14658 		find_equal_scalars(this_branch, dst_reg);
14659 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14660 	}
14661 
14662 	/* if one pointer register is compared to another pointer
14663 	 * register check if PTR_MAYBE_NULL could be lifted.
14664 	 * E.g. register A - maybe null
14665 	 *      register B - not null
14666 	 * for JNE A, B, ... - A is not null in the false branch;
14667 	 * for JEQ A, B, ... - A is not null in the true branch.
14668 	 *
14669 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14670 	 * not need to be null checked by the BPF program, i.e.,
14671 	 * could be null even without PTR_MAYBE_NULL marking, so
14672 	 * only propagate nullness when neither reg is that type.
14673 	 */
14674 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14675 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14676 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14677 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14678 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14679 		eq_branch_regs = NULL;
14680 		switch (opcode) {
14681 		case BPF_JEQ:
14682 			eq_branch_regs = other_branch_regs;
14683 			break;
14684 		case BPF_JNE:
14685 			eq_branch_regs = regs;
14686 			break;
14687 		default:
14688 			/* do nothing */
14689 			break;
14690 		}
14691 		if (eq_branch_regs) {
14692 			if (type_may_be_null(src_reg->type))
14693 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14694 			else
14695 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14696 		}
14697 	}
14698 
14699 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14700 	 * NOTE: these optimizations below are related with pointer comparison
14701 	 *       which will never be JMP32.
14702 	 */
14703 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14704 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14705 	    type_may_be_null(dst_reg->type)) {
14706 		/* Mark all identical registers in each branch as either
14707 		 * safe or unknown depending R == 0 or R != 0 conditional.
14708 		 */
14709 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14710 				      opcode == BPF_JNE);
14711 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14712 				      opcode == BPF_JEQ);
14713 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14714 					   this_branch, other_branch) &&
14715 		   is_pointer_value(env, insn->dst_reg)) {
14716 		verbose(env, "R%d pointer comparison prohibited\n",
14717 			insn->dst_reg);
14718 		return -EACCES;
14719 	}
14720 	if (env->log.level & BPF_LOG_LEVEL)
14721 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14722 	return 0;
14723 }
14724 
14725 /* verify BPF_LD_IMM64 instruction */
14726 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14727 {
14728 	struct bpf_insn_aux_data *aux = cur_aux(env);
14729 	struct bpf_reg_state *regs = cur_regs(env);
14730 	struct bpf_reg_state *dst_reg;
14731 	struct bpf_map *map;
14732 	int err;
14733 
14734 	if (BPF_SIZE(insn->code) != BPF_DW) {
14735 		verbose(env, "invalid BPF_LD_IMM insn\n");
14736 		return -EINVAL;
14737 	}
14738 	if (insn->off != 0) {
14739 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14740 		return -EINVAL;
14741 	}
14742 
14743 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14744 	if (err)
14745 		return err;
14746 
14747 	dst_reg = &regs[insn->dst_reg];
14748 	if (insn->src_reg == 0) {
14749 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14750 
14751 		dst_reg->type = SCALAR_VALUE;
14752 		__mark_reg_known(&regs[insn->dst_reg], imm);
14753 		return 0;
14754 	}
14755 
14756 	/* All special src_reg cases are listed below. From this point onwards
14757 	 * we either succeed and assign a corresponding dst_reg->type after
14758 	 * zeroing the offset, or fail and reject the program.
14759 	 */
14760 	mark_reg_known_zero(env, regs, insn->dst_reg);
14761 
14762 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14763 		dst_reg->type = aux->btf_var.reg_type;
14764 		switch (base_type(dst_reg->type)) {
14765 		case PTR_TO_MEM:
14766 			dst_reg->mem_size = aux->btf_var.mem_size;
14767 			break;
14768 		case PTR_TO_BTF_ID:
14769 			dst_reg->btf = aux->btf_var.btf;
14770 			dst_reg->btf_id = aux->btf_var.btf_id;
14771 			break;
14772 		default:
14773 			verbose(env, "bpf verifier is misconfigured\n");
14774 			return -EFAULT;
14775 		}
14776 		return 0;
14777 	}
14778 
14779 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14780 		struct bpf_prog_aux *aux = env->prog->aux;
14781 		u32 subprogno = find_subprog(env,
14782 					     env->insn_idx + insn->imm + 1);
14783 
14784 		if (!aux->func_info) {
14785 			verbose(env, "missing btf func_info\n");
14786 			return -EINVAL;
14787 		}
14788 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14789 			verbose(env, "callback function not static\n");
14790 			return -EINVAL;
14791 		}
14792 
14793 		dst_reg->type = PTR_TO_FUNC;
14794 		dst_reg->subprogno = subprogno;
14795 		return 0;
14796 	}
14797 
14798 	map = env->used_maps[aux->map_index];
14799 	dst_reg->map_ptr = map;
14800 
14801 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14802 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14803 		dst_reg->type = PTR_TO_MAP_VALUE;
14804 		dst_reg->off = aux->map_off;
14805 		WARN_ON_ONCE(map->max_entries != 1);
14806 		/* We want reg->id to be same (0) as map_value is not distinct */
14807 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14808 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14809 		dst_reg->type = CONST_PTR_TO_MAP;
14810 	} else {
14811 		verbose(env, "bpf verifier is misconfigured\n");
14812 		return -EINVAL;
14813 	}
14814 
14815 	return 0;
14816 }
14817 
14818 static bool may_access_skb(enum bpf_prog_type type)
14819 {
14820 	switch (type) {
14821 	case BPF_PROG_TYPE_SOCKET_FILTER:
14822 	case BPF_PROG_TYPE_SCHED_CLS:
14823 	case BPF_PROG_TYPE_SCHED_ACT:
14824 		return true;
14825 	default:
14826 		return false;
14827 	}
14828 }
14829 
14830 /* verify safety of LD_ABS|LD_IND instructions:
14831  * - they can only appear in the programs where ctx == skb
14832  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14833  *   preserve R6-R9, and store return value into R0
14834  *
14835  * Implicit input:
14836  *   ctx == skb == R6 == CTX
14837  *
14838  * Explicit input:
14839  *   SRC == any register
14840  *   IMM == 32-bit immediate
14841  *
14842  * Output:
14843  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14844  */
14845 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14846 {
14847 	struct bpf_reg_state *regs = cur_regs(env);
14848 	static const int ctx_reg = BPF_REG_6;
14849 	u8 mode = BPF_MODE(insn->code);
14850 	int i, err;
14851 
14852 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14853 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14854 		return -EINVAL;
14855 	}
14856 
14857 	if (!env->ops->gen_ld_abs) {
14858 		verbose(env, "bpf verifier is misconfigured\n");
14859 		return -EINVAL;
14860 	}
14861 
14862 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14863 	    BPF_SIZE(insn->code) == BPF_DW ||
14864 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14865 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14866 		return -EINVAL;
14867 	}
14868 
14869 	/* check whether implicit source operand (register R6) is readable */
14870 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14871 	if (err)
14872 		return err;
14873 
14874 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14875 	 * gen_ld_abs() may terminate the program at runtime, leading to
14876 	 * reference leak.
14877 	 */
14878 	err = check_reference_leak(env);
14879 	if (err) {
14880 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14881 		return err;
14882 	}
14883 
14884 	if (env->cur_state->active_lock.ptr) {
14885 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14886 		return -EINVAL;
14887 	}
14888 
14889 	if (env->cur_state->active_rcu_lock) {
14890 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14891 		return -EINVAL;
14892 	}
14893 
14894 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14895 		verbose(env,
14896 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14897 		return -EINVAL;
14898 	}
14899 
14900 	if (mode == BPF_IND) {
14901 		/* check explicit source operand */
14902 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14903 		if (err)
14904 			return err;
14905 	}
14906 
14907 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14908 	if (err < 0)
14909 		return err;
14910 
14911 	/* reset caller saved regs to unreadable */
14912 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14913 		mark_reg_not_init(env, regs, caller_saved[i]);
14914 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14915 	}
14916 
14917 	/* mark destination R0 register as readable, since it contains
14918 	 * the value fetched from the packet.
14919 	 * Already marked as written above.
14920 	 */
14921 	mark_reg_unknown(env, regs, BPF_REG_0);
14922 	/* ld_abs load up to 32-bit skb data. */
14923 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14924 	return 0;
14925 }
14926 
14927 static int check_return_code(struct bpf_verifier_env *env)
14928 {
14929 	struct tnum enforce_attach_type_range = tnum_unknown;
14930 	const struct bpf_prog *prog = env->prog;
14931 	struct bpf_reg_state *reg;
14932 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14933 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14934 	int err;
14935 	struct bpf_func_state *frame = env->cur_state->frame[0];
14936 	const bool is_subprog = frame->subprogno;
14937 
14938 	/* LSM and struct_ops func-ptr's return type could be "void" */
14939 	if (!is_subprog) {
14940 		switch (prog_type) {
14941 		case BPF_PROG_TYPE_LSM:
14942 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14943 				/* See below, can be 0 or 0-1 depending on hook. */
14944 				break;
14945 			fallthrough;
14946 		case BPF_PROG_TYPE_STRUCT_OPS:
14947 			if (!prog->aux->attach_func_proto->type)
14948 				return 0;
14949 			break;
14950 		default:
14951 			break;
14952 		}
14953 	}
14954 
14955 	/* eBPF calling convention is such that R0 is used
14956 	 * to return the value from eBPF program.
14957 	 * Make sure that it's readable at this time
14958 	 * of bpf_exit, which means that program wrote
14959 	 * something into it earlier
14960 	 */
14961 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14962 	if (err)
14963 		return err;
14964 
14965 	if (is_pointer_value(env, BPF_REG_0)) {
14966 		verbose(env, "R0 leaks addr as return value\n");
14967 		return -EACCES;
14968 	}
14969 
14970 	reg = cur_regs(env) + BPF_REG_0;
14971 
14972 	if (frame->in_async_callback_fn) {
14973 		/* enforce return zero from async callbacks like timer */
14974 		if (reg->type != SCALAR_VALUE) {
14975 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14976 				reg_type_str(env, reg->type));
14977 			return -EINVAL;
14978 		}
14979 
14980 		if (!tnum_in(const_0, reg->var_off)) {
14981 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14982 			return -EINVAL;
14983 		}
14984 		return 0;
14985 	}
14986 
14987 	if (is_subprog) {
14988 		if (reg->type != SCALAR_VALUE) {
14989 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14990 				reg_type_str(env, reg->type));
14991 			return -EINVAL;
14992 		}
14993 		return 0;
14994 	}
14995 
14996 	switch (prog_type) {
14997 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14998 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14999 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15000 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15001 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15002 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15003 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15004 			range = tnum_range(1, 1);
15005 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15006 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15007 			range = tnum_range(0, 3);
15008 		break;
15009 	case BPF_PROG_TYPE_CGROUP_SKB:
15010 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15011 			range = tnum_range(0, 3);
15012 			enforce_attach_type_range = tnum_range(2, 3);
15013 		}
15014 		break;
15015 	case BPF_PROG_TYPE_CGROUP_SOCK:
15016 	case BPF_PROG_TYPE_SOCK_OPS:
15017 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15018 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15019 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15020 		break;
15021 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15022 		if (!env->prog->aux->attach_btf_id)
15023 			return 0;
15024 		range = tnum_const(0);
15025 		break;
15026 	case BPF_PROG_TYPE_TRACING:
15027 		switch (env->prog->expected_attach_type) {
15028 		case BPF_TRACE_FENTRY:
15029 		case BPF_TRACE_FEXIT:
15030 			range = tnum_const(0);
15031 			break;
15032 		case BPF_TRACE_RAW_TP:
15033 		case BPF_MODIFY_RETURN:
15034 			return 0;
15035 		case BPF_TRACE_ITER:
15036 			break;
15037 		default:
15038 			return -ENOTSUPP;
15039 		}
15040 		break;
15041 	case BPF_PROG_TYPE_SK_LOOKUP:
15042 		range = tnum_range(SK_DROP, SK_PASS);
15043 		break;
15044 
15045 	case BPF_PROG_TYPE_LSM:
15046 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15047 			/* Regular BPF_PROG_TYPE_LSM programs can return
15048 			 * any value.
15049 			 */
15050 			return 0;
15051 		}
15052 		if (!env->prog->aux->attach_func_proto->type) {
15053 			/* Make sure programs that attach to void
15054 			 * hooks don't try to modify return value.
15055 			 */
15056 			range = tnum_range(1, 1);
15057 		}
15058 		break;
15059 
15060 	case BPF_PROG_TYPE_NETFILTER:
15061 		range = tnum_range(NF_DROP, NF_ACCEPT);
15062 		break;
15063 	case BPF_PROG_TYPE_EXT:
15064 		/* freplace program can return anything as its return value
15065 		 * depends on the to-be-replaced kernel func or bpf program.
15066 		 */
15067 	default:
15068 		return 0;
15069 	}
15070 
15071 	if (reg->type != SCALAR_VALUE) {
15072 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15073 			reg_type_str(env, reg->type));
15074 		return -EINVAL;
15075 	}
15076 
15077 	if (!tnum_in(range, reg->var_off)) {
15078 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15079 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15080 		    prog_type == BPF_PROG_TYPE_LSM &&
15081 		    !prog->aux->attach_func_proto->type)
15082 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15083 		return -EINVAL;
15084 	}
15085 
15086 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15087 	    tnum_in(enforce_attach_type_range, reg->var_off))
15088 		env->prog->enforce_expected_attach_type = 1;
15089 	return 0;
15090 }
15091 
15092 /* non-recursive DFS pseudo code
15093  * 1  procedure DFS-iterative(G,v):
15094  * 2      label v as discovered
15095  * 3      let S be a stack
15096  * 4      S.push(v)
15097  * 5      while S is not empty
15098  * 6            t <- S.peek()
15099  * 7            if t is what we're looking for:
15100  * 8                return t
15101  * 9            for all edges e in G.adjacentEdges(t) do
15102  * 10               if edge e is already labelled
15103  * 11                   continue with the next edge
15104  * 12               w <- G.adjacentVertex(t,e)
15105  * 13               if vertex w is not discovered and not explored
15106  * 14                   label e as tree-edge
15107  * 15                   label w as discovered
15108  * 16                   S.push(w)
15109  * 17                   continue at 5
15110  * 18               else if vertex w is discovered
15111  * 19                   label e as back-edge
15112  * 20               else
15113  * 21                   // vertex w is explored
15114  * 22                   label e as forward- or cross-edge
15115  * 23           label t as explored
15116  * 24           S.pop()
15117  *
15118  * convention:
15119  * 0x10 - discovered
15120  * 0x11 - discovered and fall-through edge labelled
15121  * 0x12 - discovered and fall-through and branch edges labelled
15122  * 0x20 - explored
15123  */
15124 
15125 enum {
15126 	DISCOVERED = 0x10,
15127 	EXPLORED = 0x20,
15128 	FALLTHROUGH = 1,
15129 	BRANCH = 2,
15130 };
15131 
15132 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15133 {
15134 	env->insn_aux_data[idx].prune_point = true;
15135 }
15136 
15137 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15138 {
15139 	return env->insn_aux_data[insn_idx].prune_point;
15140 }
15141 
15142 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15143 {
15144 	env->insn_aux_data[idx].force_checkpoint = true;
15145 }
15146 
15147 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15148 {
15149 	return env->insn_aux_data[insn_idx].force_checkpoint;
15150 }
15151 
15152 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15153 {
15154 	env->insn_aux_data[idx].calls_callback = true;
15155 }
15156 
15157 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15158 {
15159 	return env->insn_aux_data[insn_idx].calls_callback;
15160 }
15161 
15162 enum {
15163 	DONE_EXPLORING = 0,
15164 	KEEP_EXPLORING = 1,
15165 };
15166 
15167 /* t, w, e - match pseudo-code above:
15168  * t - index of current instruction
15169  * w - next instruction
15170  * e - edge
15171  */
15172 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15173 {
15174 	int *insn_stack = env->cfg.insn_stack;
15175 	int *insn_state = env->cfg.insn_state;
15176 
15177 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15178 		return DONE_EXPLORING;
15179 
15180 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15181 		return DONE_EXPLORING;
15182 
15183 	if (w < 0 || w >= env->prog->len) {
15184 		verbose_linfo(env, t, "%d: ", t);
15185 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15186 		return -EINVAL;
15187 	}
15188 
15189 	if (e == BRANCH) {
15190 		/* mark branch target for state pruning */
15191 		mark_prune_point(env, w);
15192 		mark_jmp_point(env, w);
15193 	}
15194 
15195 	if (insn_state[w] == 0) {
15196 		/* tree-edge */
15197 		insn_state[t] = DISCOVERED | e;
15198 		insn_state[w] = DISCOVERED;
15199 		if (env->cfg.cur_stack >= env->prog->len)
15200 			return -E2BIG;
15201 		insn_stack[env->cfg.cur_stack++] = w;
15202 		return KEEP_EXPLORING;
15203 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15204 		if (env->bpf_capable)
15205 			return DONE_EXPLORING;
15206 		verbose_linfo(env, t, "%d: ", t);
15207 		verbose_linfo(env, w, "%d: ", w);
15208 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15209 		return -EINVAL;
15210 	} else if (insn_state[w] == EXPLORED) {
15211 		/* forward- or cross-edge */
15212 		insn_state[t] = DISCOVERED | e;
15213 	} else {
15214 		verbose(env, "insn state internal bug\n");
15215 		return -EFAULT;
15216 	}
15217 	return DONE_EXPLORING;
15218 }
15219 
15220 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15221 				struct bpf_verifier_env *env,
15222 				bool visit_callee)
15223 {
15224 	int ret, insn_sz;
15225 
15226 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15227 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15228 	if (ret)
15229 		return ret;
15230 
15231 	mark_prune_point(env, t + insn_sz);
15232 	/* when we exit from subprog, we need to record non-linear history */
15233 	mark_jmp_point(env, t + insn_sz);
15234 
15235 	if (visit_callee) {
15236 		mark_prune_point(env, t);
15237 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15238 	}
15239 	return ret;
15240 }
15241 
15242 /* Visits the instruction at index t and returns one of the following:
15243  *  < 0 - an error occurred
15244  *  DONE_EXPLORING - the instruction was fully explored
15245  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15246  */
15247 static int visit_insn(int t, struct bpf_verifier_env *env)
15248 {
15249 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15250 	int ret, off, insn_sz;
15251 
15252 	if (bpf_pseudo_func(insn))
15253 		return visit_func_call_insn(t, insns, env, true);
15254 
15255 	/* All non-branch instructions have a single fall-through edge. */
15256 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15257 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15258 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15259 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15260 	}
15261 
15262 	switch (BPF_OP(insn->code)) {
15263 	case BPF_EXIT:
15264 		return DONE_EXPLORING;
15265 
15266 	case BPF_CALL:
15267 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15268 			/* Mark this call insn as a prune point to trigger
15269 			 * is_state_visited() check before call itself is
15270 			 * processed by __check_func_call(). Otherwise new
15271 			 * async state will be pushed for further exploration.
15272 			 */
15273 			mark_prune_point(env, t);
15274 		/* For functions that invoke callbacks it is not known how many times
15275 		 * callback would be called. Verifier models callback calling functions
15276 		 * by repeatedly visiting callback bodies and returning to origin call
15277 		 * instruction.
15278 		 * In order to stop such iteration verifier needs to identify when a
15279 		 * state identical some state from a previous iteration is reached.
15280 		 * Check below forces creation of checkpoint before callback calling
15281 		 * instruction to allow search for such identical states.
15282 		 */
15283 		if (is_sync_callback_calling_insn(insn)) {
15284 			mark_calls_callback(env, t);
15285 			mark_force_checkpoint(env, t);
15286 			mark_prune_point(env, t);
15287 			mark_jmp_point(env, t);
15288 		}
15289 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15290 			struct bpf_kfunc_call_arg_meta meta;
15291 
15292 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15293 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15294 				mark_prune_point(env, t);
15295 				/* Checking and saving state checkpoints at iter_next() call
15296 				 * is crucial for fast convergence of open-coded iterator loop
15297 				 * logic, so we need to force it. If we don't do that,
15298 				 * is_state_visited() might skip saving a checkpoint, causing
15299 				 * unnecessarily long sequence of not checkpointed
15300 				 * instructions and jumps, leading to exhaustion of jump
15301 				 * history buffer, and potentially other undesired outcomes.
15302 				 * It is expected that with correct open-coded iterators
15303 				 * convergence will happen quickly, so we don't run a risk of
15304 				 * exhausting memory.
15305 				 */
15306 				mark_force_checkpoint(env, t);
15307 			}
15308 		}
15309 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15310 
15311 	case BPF_JA:
15312 		if (BPF_SRC(insn->code) != BPF_K)
15313 			return -EINVAL;
15314 
15315 		if (BPF_CLASS(insn->code) == BPF_JMP)
15316 			off = insn->off;
15317 		else
15318 			off = insn->imm;
15319 
15320 		/* unconditional jump with single edge */
15321 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15322 		if (ret)
15323 			return ret;
15324 
15325 		mark_prune_point(env, t + off + 1);
15326 		mark_jmp_point(env, t + off + 1);
15327 
15328 		return ret;
15329 
15330 	default:
15331 		/* conditional jump with two edges */
15332 		mark_prune_point(env, t);
15333 
15334 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15335 		if (ret)
15336 			return ret;
15337 
15338 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15339 	}
15340 }
15341 
15342 /* non-recursive depth-first-search to detect loops in BPF program
15343  * loop == back-edge in directed graph
15344  */
15345 static int check_cfg(struct bpf_verifier_env *env)
15346 {
15347 	int insn_cnt = env->prog->len;
15348 	int *insn_stack, *insn_state;
15349 	int ret = 0;
15350 	int i;
15351 
15352 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15353 	if (!insn_state)
15354 		return -ENOMEM;
15355 
15356 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15357 	if (!insn_stack) {
15358 		kvfree(insn_state);
15359 		return -ENOMEM;
15360 	}
15361 
15362 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15363 	insn_stack[0] = 0; /* 0 is the first instruction */
15364 	env->cfg.cur_stack = 1;
15365 
15366 	while (env->cfg.cur_stack > 0) {
15367 		int t = insn_stack[env->cfg.cur_stack - 1];
15368 
15369 		ret = visit_insn(t, env);
15370 		switch (ret) {
15371 		case DONE_EXPLORING:
15372 			insn_state[t] = EXPLORED;
15373 			env->cfg.cur_stack--;
15374 			break;
15375 		case KEEP_EXPLORING:
15376 			break;
15377 		default:
15378 			if (ret > 0) {
15379 				verbose(env, "visit_insn internal bug\n");
15380 				ret = -EFAULT;
15381 			}
15382 			goto err_free;
15383 		}
15384 	}
15385 
15386 	if (env->cfg.cur_stack < 0) {
15387 		verbose(env, "pop stack internal bug\n");
15388 		ret = -EFAULT;
15389 		goto err_free;
15390 	}
15391 
15392 	for (i = 0; i < insn_cnt; i++) {
15393 		struct bpf_insn *insn = &env->prog->insnsi[i];
15394 
15395 		if (insn_state[i] != EXPLORED) {
15396 			verbose(env, "unreachable insn %d\n", i);
15397 			ret = -EINVAL;
15398 			goto err_free;
15399 		}
15400 		if (bpf_is_ldimm64(insn)) {
15401 			if (insn_state[i + 1] != 0) {
15402 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15403 				ret = -EINVAL;
15404 				goto err_free;
15405 			}
15406 			i++; /* skip second half of ldimm64 */
15407 		}
15408 	}
15409 	ret = 0; /* cfg looks good */
15410 
15411 err_free:
15412 	kvfree(insn_state);
15413 	kvfree(insn_stack);
15414 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15415 	return ret;
15416 }
15417 
15418 static int check_abnormal_return(struct bpf_verifier_env *env)
15419 {
15420 	int i;
15421 
15422 	for (i = 1; i < env->subprog_cnt; i++) {
15423 		if (env->subprog_info[i].has_ld_abs) {
15424 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15425 			return -EINVAL;
15426 		}
15427 		if (env->subprog_info[i].has_tail_call) {
15428 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15429 			return -EINVAL;
15430 		}
15431 	}
15432 	return 0;
15433 }
15434 
15435 /* The minimum supported BTF func info size */
15436 #define MIN_BPF_FUNCINFO_SIZE	8
15437 #define MAX_FUNCINFO_REC_SIZE	252
15438 
15439 static int check_btf_func(struct bpf_verifier_env *env,
15440 			  const union bpf_attr *attr,
15441 			  bpfptr_t uattr)
15442 {
15443 	const struct btf_type *type, *func_proto, *ret_type;
15444 	u32 i, nfuncs, urec_size, min_size;
15445 	u32 krec_size = sizeof(struct bpf_func_info);
15446 	struct bpf_func_info *krecord;
15447 	struct bpf_func_info_aux *info_aux = NULL;
15448 	struct bpf_prog *prog;
15449 	const struct btf *btf;
15450 	bpfptr_t urecord;
15451 	u32 prev_offset = 0;
15452 	bool scalar_return;
15453 	int ret = -ENOMEM;
15454 
15455 	nfuncs = attr->func_info_cnt;
15456 	if (!nfuncs) {
15457 		if (check_abnormal_return(env))
15458 			return -EINVAL;
15459 		return 0;
15460 	}
15461 
15462 	if (nfuncs != env->subprog_cnt) {
15463 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15464 		return -EINVAL;
15465 	}
15466 
15467 	urec_size = attr->func_info_rec_size;
15468 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15469 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15470 	    urec_size % sizeof(u32)) {
15471 		verbose(env, "invalid func info rec size %u\n", urec_size);
15472 		return -EINVAL;
15473 	}
15474 
15475 	prog = env->prog;
15476 	btf = prog->aux->btf;
15477 
15478 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15479 	min_size = min_t(u32, krec_size, urec_size);
15480 
15481 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15482 	if (!krecord)
15483 		return -ENOMEM;
15484 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15485 	if (!info_aux)
15486 		goto err_free;
15487 
15488 	for (i = 0; i < nfuncs; i++) {
15489 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15490 		if (ret) {
15491 			if (ret == -E2BIG) {
15492 				verbose(env, "nonzero tailing record in func info");
15493 				/* set the size kernel expects so loader can zero
15494 				 * out the rest of the record.
15495 				 */
15496 				if (copy_to_bpfptr_offset(uattr,
15497 							  offsetof(union bpf_attr, func_info_rec_size),
15498 							  &min_size, sizeof(min_size)))
15499 					ret = -EFAULT;
15500 			}
15501 			goto err_free;
15502 		}
15503 
15504 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15505 			ret = -EFAULT;
15506 			goto err_free;
15507 		}
15508 
15509 		/* check insn_off */
15510 		ret = -EINVAL;
15511 		if (i == 0) {
15512 			if (krecord[i].insn_off) {
15513 				verbose(env,
15514 					"nonzero insn_off %u for the first func info record",
15515 					krecord[i].insn_off);
15516 				goto err_free;
15517 			}
15518 		} else if (krecord[i].insn_off <= prev_offset) {
15519 			verbose(env,
15520 				"same or smaller insn offset (%u) than previous func info record (%u)",
15521 				krecord[i].insn_off, prev_offset);
15522 			goto err_free;
15523 		}
15524 
15525 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15526 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15527 			goto err_free;
15528 		}
15529 
15530 		/* check type_id */
15531 		type = btf_type_by_id(btf, krecord[i].type_id);
15532 		if (!type || !btf_type_is_func(type)) {
15533 			verbose(env, "invalid type id %d in func info",
15534 				krecord[i].type_id);
15535 			goto err_free;
15536 		}
15537 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15538 
15539 		func_proto = btf_type_by_id(btf, type->type);
15540 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15541 			/* btf_func_check() already verified it during BTF load */
15542 			goto err_free;
15543 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15544 		scalar_return =
15545 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15546 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15547 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15548 			goto err_free;
15549 		}
15550 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15551 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15552 			goto err_free;
15553 		}
15554 
15555 		prev_offset = krecord[i].insn_off;
15556 		bpfptr_add(&urecord, urec_size);
15557 	}
15558 
15559 	prog->aux->func_info = krecord;
15560 	prog->aux->func_info_cnt = nfuncs;
15561 	prog->aux->func_info_aux = info_aux;
15562 	return 0;
15563 
15564 err_free:
15565 	kvfree(krecord);
15566 	kfree(info_aux);
15567 	return ret;
15568 }
15569 
15570 static void adjust_btf_func(struct bpf_verifier_env *env)
15571 {
15572 	struct bpf_prog_aux *aux = env->prog->aux;
15573 	int i;
15574 
15575 	if (!aux->func_info)
15576 		return;
15577 
15578 	for (i = 0; i < env->subprog_cnt; i++)
15579 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15580 }
15581 
15582 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15583 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15584 
15585 static int check_btf_line(struct bpf_verifier_env *env,
15586 			  const union bpf_attr *attr,
15587 			  bpfptr_t uattr)
15588 {
15589 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15590 	struct bpf_subprog_info *sub;
15591 	struct bpf_line_info *linfo;
15592 	struct bpf_prog *prog;
15593 	const struct btf *btf;
15594 	bpfptr_t ulinfo;
15595 	int err;
15596 
15597 	nr_linfo = attr->line_info_cnt;
15598 	if (!nr_linfo)
15599 		return 0;
15600 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15601 		return -EINVAL;
15602 
15603 	rec_size = attr->line_info_rec_size;
15604 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15605 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15606 	    rec_size & (sizeof(u32) - 1))
15607 		return -EINVAL;
15608 
15609 	/* Need to zero it in case the userspace may
15610 	 * pass in a smaller bpf_line_info object.
15611 	 */
15612 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15613 			 GFP_KERNEL | __GFP_NOWARN);
15614 	if (!linfo)
15615 		return -ENOMEM;
15616 
15617 	prog = env->prog;
15618 	btf = prog->aux->btf;
15619 
15620 	s = 0;
15621 	sub = env->subprog_info;
15622 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15623 	expected_size = sizeof(struct bpf_line_info);
15624 	ncopy = min_t(u32, expected_size, rec_size);
15625 	for (i = 0; i < nr_linfo; i++) {
15626 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15627 		if (err) {
15628 			if (err == -E2BIG) {
15629 				verbose(env, "nonzero tailing record in line_info");
15630 				if (copy_to_bpfptr_offset(uattr,
15631 							  offsetof(union bpf_attr, line_info_rec_size),
15632 							  &expected_size, sizeof(expected_size)))
15633 					err = -EFAULT;
15634 			}
15635 			goto err_free;
15636 		}
15637 
15638 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15639 			err = -EFAULT;
15640 			goto err_free;
15641 		}
15642 
15643 		/*
15644 		 * Check insn_off to ensure
15645 		 * 1) strictly increasing AND
15646 		 * 2) bounded by prog->len
15647 		 *
15648 		 * The linfo[0].insn_off == 0 check logically falls into
15649 		 * the later "missing bpf_line_info for func..." case
15650 		 * because the first linfo[0].insn_off must be the
15651 		 * first sub also and the first sub must have
15652 		 * subprog_info[0].start == 0.
15653 		 */
15654 		if ((i && linfo[i].insn_off <= prev_offset) ||
15655 		    linfo[i].insn_off >= prog->len) {
15656 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15657 				i, linfo[i].insn_off, prev_offset,
15658 				prog->len);
15659 			err = -EINVAL;
15660 			goto err_free;
15661 		}
15662 
15663 		if (!prog->insnsi[linfo[i].insn_off].code) {
15664 			verbose(env,
15665 				"Invalid insn code at line_info[%u].insn_off\n",
15666 				i);
15667 			err = -EINVAL;
15668 			goto err_free;
15669 		}
15670 
15671 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15672 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15673 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15674 			err = -EINVAL;
15675 			goto err_free;
15676 		}
15677 
15678 		if (s != env->subprog_cnt) {
15679 			if (linfo[i].insn_off == sub[s].start) {
15680 				sub[s].linfo_idx = i;
15681 				s++;
15682 			} else if (sub[s].start < linfo[i].insn_off) {
15683 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15684 				err = -EINVAL;
15685 				goto err_free;
15686 			}
15687 		}
15688 
15689 		prev_offset = linfo[i].insn_off;
15690 		bpfptr_add(&ulinfo, rec_size);
15691 	}
15692 
15693 	if (s != env->subprog_cnt) {
15694 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15695 			env->subprog_cnt - s, s);
15696 		err = -EINVAL;
15697 		goto err_free;
15698 	}
15699 
15700 	prog->aux->linfo = linfo;
15701 	prog->aux->nr_linfo = nr_linfo;
15702 
15703 	return 0;
15704 
15705 err_free:
15706 	kvfree(linfo);
15707 	return err;
15708 }
15709 
15710 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15711 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15712 
15713 static int check_core_relo(struct bpf_verifier_env *env,
15714 			   const union bpf_attr *attr,
15715 			   bpfptr_t uattr)
15716 {
15717 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15718 	struct bpf_core_relo core_relo = {};
15719 	struct bpf_prog *prog = env->prog;
15720 	const struct btf *btf = prog->aux->btf;
15721 	struct bpf_core_ctx ctx = {
15722 		.log = &env->log,
15723 		.btf = btf,
15724 	};
15725 	bpfptr_t u_core_relo;
15726 	int err;
15727 
15728 	nr_core_relo = attr->core_relo_cnt;
15729 	if (!nr_core_relo)
15730 		return 0;
15731 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15732 		return -EINVAL;
15733 
15734 	rec_size = attr->core_relo_rec_size;
15735 	if (rec_size < MIN_CORE_RELO_SIZE ||
15736 	    rec_size > MAX_CORE_RELO_SIZE ||
15737 	    rec_size % sizeof(u32))
15738 		return -EINVAL;
15739 
15740 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15741 	expected_size = sizeof(struct bpf_core_relo);
15742 	ncopy = min_t(u32, expected_size, rec_size);
15743 
15744 	/* Unlike func_info and line_info, copy and apply each CO-RE
15745 	 * relocation record one at a time.
15746 	 */
15747 	for (i = 0; i < nr_core_relo; i++) {
15748 		/* future proofing when sizeof(bpf_core_relo) changes */
15749 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15750 		if (err) {
15751 			if (err == -E2BIG) {
15752 				verbose(env, "nonzero tailing record in core_relo");
15753 				if (copy_to_bpfptr_offset(uattr,
15754 							  offsetof(union bpf_attr, core_relo_rec_size),
15755 							  &expected_size, sizeof(expected_size)))
15756 					err = -EFAULT;
15757 			}
15758 			break;
15759 		}
15760 
15761 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15762 			err = -EFAULT;
15763 			break;
15764 		}
15765 
15766 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15767 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15768 				i, core_relo.insn_off, prog->len);
15769 			err = -EINVAL;
15770 			break;
15771 		}
15772 
15773 		err = bpf_core_apply(&ctx, &core_relo, i,
15774 				     &prog->insnsi[core_relo.insn_off / 8]);
15775 		if (err)
15776 			break;
15777 		bpfptr_add(&u_core_relo, rec_size);
15778 	}
15779 	return err;
15780 }
15781 
15782 static int check_btf_info(struct bpf_verifier_env *env,
15783 			  const union bpf_attr *attr,
15784 			  bpfptr_t uattr)
15785 {
15786 	struct btf *btf;
15787 	int err;
15788 
15789 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15790 		if (check_abnormal_return(env))
15791 			return -EINVAL;
15792 		return 0;
15793 	}
15794 
15795 	btf = btf_get_by_fd(attr->prog_btf_fd);
15796 	if (IS_ERR(btf))
15797 		return PTR_ERR(btf);
15798 	if (btf_is_kernel(btf)) {
15799 		btf_put(btf);
15800 		return -EACCES;
15801 	}
15802 	env->prog->aux->btf = btf;
15803 
15804 	err = check_btf_func(env, attr, uattr);
15805 	if (err)
15806 		return err;
15807 
15808 	err = check_btf_line(env, attr, uattr);
15809 	if (err)
15810 		return err;
15811 
15812 	err = check_core_relo(env, attr, uattr);
15813 	if (err)
15814 		return err;
15815 
15816 	return 0;
15817 }
15818 
15819 /* check %cur's range satisfies %old's */
15820 static bool range_within(struct bpf_reg_state *old,
15821 			 struct bpf_reg_state *cur)
15822 {
15823 	return old->umin_value <= cur->umin_value &&
15824 	       old->umax_value >= cur->umax_value &&
15825 	       old->smin_value <= cur->smin_value &&
15826 	       old->smax_value >= cur->smax_value &&
15827 	       old->u32_min_value <= cur->u32_min_value &&
15828 	       old->u32_max_value >= cur->u32_max_value &&
15829 	       old->s32_min_value <= cur->s32_min_value &&
15830 	       old->s32_max_value >= cur->s32_max_value;
15831 }
15832 
15833 /* If in the old state two registers had the same id, then they need to have
15834  * the same id in the new state as well.  But that id could be different from
15835  * the old state, so we need to track the mapping from old to new ids.
15836  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15837  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15838  * regs with a different old id could still have new id 9, we don't care about
15839  * that.
15840  * So we look through our idmap to see if this old id has been seen before.  If
15841  * so, we require the new id to match; otherwise, we add the id pair to the map.
15842  */
15843 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15844 {
15845 	struct bpf_id_pair *map = idmap->map;
15846 	unsigned int i;
15847 
15848 	/* either both IDs should be set or both should be zero */
15849 	if (!!old_id != !!cur_id)
15850 		return false;
15851 
15852 	if (old_id == 0) /* cur_id == 0 as well */
15853 		return true;
15854 
15855 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15856 		if (!map[i].old) {
15857 			/* Reached an empty slot; haven't seen this id before */
15858 			map[i].old = old_id;
15859 			map[i].cur = cur_id;
15860 			return true;
15861 		}
15862 		if (map[i].old == old_id)
15863 			return map[i].cur == cur_id;
15864 		if (map[i].cur == cur_id)
15865 			return false;
15866 	}
15867 	/* We ran out of idmap slots, which should be impossible */
15868 	WARN_ON_ONCE(1);
15869 	return false;
15870 }
15871 
15872 /* Similar to check_ids(), but allocate a unique temporary ID
15873  * for 'old_id' or 'cur_id' of zero.
15874  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15875  */
15876 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15877 {
15878 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15879 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15880 
15881 	return check_ids(old_id, cur_id, idmap);
15882 }
15883 
15884 static void clean_func_state(struct bpf_verifier_env *env,
15885 			     struct bpf_func_state *st)
15886 {
15887 	enum bpf_reg_liveness live;
15888 	int i, j;
15889 
15890 	for (i = 0; i < BPF_REG_FP; i++) {
15891 		live = st->regs[i].live;
15892 		/* liveness must not touch this register anymore */
15893 		st->regs[i].live |= REG_LIVE_DONE;
15894 		if (!(live & REG_LIVE_READ))
15895 			/* since the register is unused, clear its state
15896 			 * to make further comparison simpler
15897 			 */
15898 			__mark_reg_not_init(env, &st->regs[i]);
15899 	}
15900 
15901 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15902 		live = st->stack[i].spilled_ptr.live;
15903 		/* liveness must not touch this stack slot anymore */
15904 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15905 		if (!(live & REG_LIVE_READ)) {
15906 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15907 			for (j = 0; j < BPF_REG_SIZE; j++)
15908 				st->stack[i].slot_type[j] = STACK_INVALID;
15909 		}
15910 	}
15911 }
15912 
15913 static void clean_verifier_state(struct bpf_verifier_env *env,
15914 				 struct bpf_verifier_state *st)
15915 {
15916 	int i;
15917 
15918 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15919 		/* all regs in this state in all frames were already marked */
15920 		return;
15921 
15922 	for (i = 0; i <= st->curframe; i++)
15923 		clean_func_state(env, st->frame[i]);
15924 }
15925 
15926 /* the parentage chains form a tree.
15927  * the verifier states are added to state lists at given insn and
15928  * pushed into state stack for future exploration.
15929  * when the verifier reaches bpf_exit insn some of the verifer states
15930  * stored in the state lists have their final liveness state already,
15931  * but a lot of states will get revised from liveness point of view when
15932  * the verifier explores other branches.
15933  * Example:
15934  * 1: r0 = 1
15935  * 2: if r1 == 100 goto pc+1
15936  * 3: r0 = 2
15937  * 4: exit
15938  * when the verifier reaches exit insn the register r0 in the state list of
15939  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15940  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15941  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15942  *
15943  * Since the verifier pushes the branch states as it sees them while exploring
15944  * the program the condition of walking the branch instruction for the second
15945  * time means that all states below this branch were already explored and
15946  * their final liveness marks are already propagated.
15947  * Hence when the verifier completes the search of state list in is_state_visited()
15948  * we can call this clean_live_states() function to mark all liveness states
15949  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15950  * will not be used.
15951  * This function also clears the registers and stack for states that !READ
15952  * to simplify state merging.
15953  *
15954  * Important note here that walking the same branch instruction in the callee
15955  * doesn't meant that the states are DONE. The verifier has to compare
15956  * the callsites
15957  */
15958 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15959 			      struct bpf_verifier_state *cur)
15960 {
15961 	struct bpf_verifier_state_list *sl;
15962 
15963 	sl = *explored_state(env, insn);
15964 	while (sl) {
15965 		if (sl->state.branches)
15966 			goto next;
15967 		if (sl->state.insn_idx != insn ||
15968 		    !same_callsites(&sl->state, cur))
15969 			goto next;
15970 		clean_verifier_state(env, &sl->state);
15971 next:
15972 		sl = sl->next;
15973 	}
15974 }
15975 
15976 static bool regs_exact(const struct bpf_reg_state *rold,
15977 		       const struct bpf_reg_state *rcur,
15978 		       struct bpf_idmap *idmap)
15979 {
15980 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15981 	       check_ids(rold->id, rcur->id, idmap) &&
15982 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15983 }
15984 
15985 /* Returns true if (rold safe implies rcur safe) */
15986 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15987 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15988 {
15989 	if (exact)
15990 		return regs_exact(rold, rcur, idmap);
15991 
15992 	if (!(rold->live & REG_LIVE_READ))
15993 		/* explored state didn't use this */
15994 		return true;
15995 	if (rold->type == NOT_INIT)
15996 		/* explored state can't have used this */
15997 		return true;
15998 	if (rcur->type == NOT_INIT)
15999 		return false;
16000 
16001 	/* Enforce that register types have to match exactly, including their
16002 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16003 	 * rule.
16004 	 *
16005 	 * One can make a point that using a pointer register as unbounded
16006 	 * SCALAR would be technically acceptable, but this could lead to
16007 	 * pointer leaks because scalars are allowed to leak while pointers
16008 	 * are not. We could make this safe in special cases if root is
16009 	 * calling us, but it's probably not worth the hassle.
16010 	 *
16011 	 * Also, register types that are *not* MAYBE_NULL could technically be
16012 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16013 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16014 	 * to the same map).
16015 	 * However, if the old MAYBE_NULL register then got NULL checked,
16016 	 * doing so could have affected others with the same id, and we can't
16017 	 * check for that because we lost the id when we converted to
16018 	 * a non-MAYBE_NULL variant.
16019 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16020 	 * non-MAYBE_NULL registers as well.
16021 	 */
16022 	if (rold->type != rcur->type)
16023 		return false;
16024 
16025 	switch (base_type(rold->type)) {
16026 	case SCALAR_VALUE:
16027 		if (env->explore_alu_limits) {
16028 			/* explore_alu_limits disables tnum_in() and range_within()
16029 			 * logic and requires everything to be strict
16030 			 */
16031 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16032 			       check_scalar_ids(rold->id, rcur->id, idmap);
16033 		}
16034 		if (!rold->precise)
16035 			return true;
16036 		/* Why check_ids() for scalar registers?
16037 		 *
16038 		 * Consider the following BPF code:
16039 		 *   1: r6 = ... unbound scalar, ID=a ...
16040 		 *   2: r7 = ... unbound scalar, ID=b ...
16041 		 *   3: if (r6 > r7) goto +1
16042 		 *   4: r6 = r7
16043 		 *   5: if (r6 > X) goto ...
16044 		 *   6: ... memory operation using r7 ...
16045 		 *
16046 		 * First verification path is [1-6]:
16047 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16048 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16049 		 *   r7 <= X, because r6 and r7 share same id.
16050 		 * Next verification path is [1-4, 6].
16051 		 *
16052 		 * Instruction (6) would be reached in two states:
16053 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16054 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16055 		 *
16056 		 * Use check_ids() to distinguish these states.
16057 		 * ---
16058 		 * Also verify that new value satisfies old value range knowledge.
16059 		 */
16060 		return range_within(rold, rcur) &&
16061 		       tnum_in(rold->var_off, rcur->var_off) &&
16062 		       check_scalar_ids(rold->id, rcur->id, idmap);
16063 	case PTR_TO_MAP_KEY:
16064 	case PTR_TO_MAP_VALUE:
16065 	case PTR_TO_MEM:
16066 	case PTR_TO_BUF:
16067 	case PTR_TO_TP_BUFFER:
16068 		/* If the new min/max/var_off satisfy the old ones and
16069 		 * everything else matches, we are OK.
16070 		 */
16071 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16072 		       range_within(rold, rcur) &&
16073 		       tnum_in(rold->var_off, rcur->var_off) &&
16074 		       check_ids(rold->id, rcur->id, idmap) &&
16075 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16076 	case PTR_TO_PACKET_META:
16077 	case PTR_TO_PACKET:
16078 		/* We must have at least as much range as the old ptr
16079 		 * did, so that any accesses which were safe before are
16080 		 * still safe.  This is true even if old range < old off,
16081 		 * since someone could have accessed through (ptr - k), or
16082 		 * even done ptr -= k in a register, to get a safe access.
16083 		 */
16084 		if (rold->range > rcur->range)
16085 			return false;
16086 		/* If the offsets don't match, we can't trust our alignment;
16087 		 * nor can we be sure that we won't fall out of range.
16088 		 */
16089 		if (rold->off != rcur->off)
16090 			return false;
16091 		/* id relations must be preserved */
16092 		if (!check_ids(rold->id, rcur->id, idmap))
16093 			return false;
16094 		/* new val must satisfy old val knowledge */
16095 		return range_within(rold, rcur) &&
16096 		       tnum_in(rold->var_off, rcur->var_off);
16097 	case PTR_TO_STACK:
16098 		/* two stack pointers are equal only if they're pointing to
16099 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16100 		 */
16101 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16102 	default:
16103 		return regs_exact(rold, rcur, idmap);
16104 	}
16105 }
16106 
16107 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16108 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16109 {
16110 	int i, spi;
16111 
16112 	/* walk slots of the explored stack and ignore any additional
16113 	 * slots in the current stack, since explored(safe) state
16114 	 * didn't use them
16115 	 */
16116 	for (i = 0; i < old->allocated_stack; i++) {
16117 		struct bpf_reg_state *old_reg, *cur_reg;
16118 
16119 		spi = i / BPF_REG_SIZE;
16120 
16121 		if (exact &&
16122 		    (i >= cur->allocated_stack ||
16123 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16124 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16125 			return false;
16126 
16127 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16128 			i += BPF_REG_SIZE - 1;
16129 			/* explored state didn't use this */
16130 			continue;
16131 		}
16132 
16133 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16134 			continue;
16135 
16136 		if (env->allow_uninit_stack &&
16137 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16138 			continue;
16139 
16140 		/* explored stack has more populated slots than current stack
16141 		 * and these slots were used
16142 		 */
16143 		if (i >= cur->allocated_stack)
16144 			return false;
16145 
16146 		/* if old state was safe with misc data in the stack
16147 		 * it will be safe with zero-initialized stack.
16148 		 * The opposite is not true
16149 		 */
16150 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16151 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16152 			continue;
16153 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16154 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16155 			/* Ex: old explored (safe) state has STACK_SPILL in
16156 			 * this stack slot, but current has STACK_MISC ->
16157 			 * this verifier states are not equivalent,
16158 			 * return false to continue verification of this path
16159 			 */
16160 			return false;
16161 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16162 			continue;
16163 		/* Both old and cur are having same slot_type */
16164 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16165 		case STACK_SPILL:
16166 			/* when explored and current stack slot are both storing
16167 			 * spilled registers, check that stored pointers types
16168 			 * are the same as well.
16169 			 * Ex: explored safe path could have stored
16170 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16171 			 * but current path has stored:
16172 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16173 			 * such verifier states are not equivalent.
16174 			 * return false to continue verification of this path
16175 			 */
16176 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16177 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16178 				return false;
16179 			break;
16180 		case STACK_DYNPTR:
16181 			old_reg = &old->stack[spi].spilled_ptr;
16182 			cur_reg = &cur->stack[spi].spilled_ptr;
16183 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16184 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16185 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16186 				return false;
16187 			break;
16188 		case STACK_ITER:
16189 			old_reg = &old->stack[spi].spilled_ptr;
16190 			cur_reg = &cur->stack[spi].spilled_ptr;
16191 			/* iter.depth is not compared between states as it
16192 			 * doesn't matter for correctness and would otherwise
16193 			 * prevent convergence; we maintain it only to prevent
16194 			 * infinite loop check triggering, see
16195 			 * iter_active_depths_differ()
16196 			 */
16197 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16198 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16199 			    old_reg->iter.state != cur_reg->iter.state ||
16200 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16201 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16202 				return false;
16203 			break;
16204 		case STACK_MISC:
16205 		case STACK_ZERO:
16206 		case STACK_INVALID:
16207 			continue;
16208 		/* Ensure that new unhandled slot types return false by default */
16209 		default:
16210 			return false;
16211 		}
16212 	}
16213 	return true;
16214 }
16215 
16216 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16217 		    struct bpf_idmap *idmap)
16218 {
16219 	int i;
16220 
16221 	if (old->acquired_refs != cur->acquired_refs)
16222 		return false;
16223 
16224 	for (i = 0; i < old->acquired_refs; i++) {
16225 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16226 			return false;
16227 	}
16228 
16229 	return true;
16230 }
16231 
16232 /* compare two verifier states
16233  *
16234  * all states stored in state_list are known to be valid, since
16235  * verifier reached 'bpf_exit' instruction through them
16236  *
16237  * this function is called when verifier exploring different branches of
16238  * execution popped from the state stack. If it sees an old state that has
16239  * more strict register state and more strict stack state then this execution
16240  * branch doesn't need to be explored further, since verifier already
16241  * concluded that more strict state leads to valid finish.
16242  *
16243  * Therefore two states are equivalent if register state is more conservative
16244  * and explored stack state is more conservative than the current one.
16245  * Example:
16246  *       explored                   current
16247  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16248  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16249  *
16250  * In other words if current stack state (one being explored) has more
16251  * valid slots than old one that already passed validation, it means
16252  * the verifier can stop exploring and conclude that current state is valid too
16253  *
16254  * Similarly with registers. If explored state has register type as invalid
16255  * whereas register type in current state is meaningful, it means that
16256  * the current state will reach 'bpf_exit' instruction safely
16257  */
16258 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16259 			      struct bpf_func_state *cur, bool exact)
16260 {
16261 	int i;
16262 
16263 	if (old->callback_depth > cur->callback_depth)
16264 		return false;
16265 
16266 	for (i = 0; i < MAX_BPF_REG; i++)
16267 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16268 			     &env->idmap_scratch, exact))
16269 			return false;
16270 
16271 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16272 		return false;
16273 
16274 	if (!refsafe(old, cur, &env->idmap_scratch))
16275 		return false;
16276 
16277 	return true;
16278 }
16279 
16280 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16281 {
16282 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16283 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16284 }
16285 
16286 static bool states_equal(struct bpf_verifier_env *env,
16287 			 struct bpf_verifier_state *old,
16288 			 struct bpf_verifier_state *cur,
16289 			 bool exact)
16290 {
16291 	int i;
16292 
16293 	if (old->curframe != cur->curframe)
16294 		return false;
16295 
16296 	reset_idmap_scratch(env);
16297 
16298 	/* Verification state from speculative execution simulation
16299 	 * must never prune a non-speculative execution one.
16300 	 */
16301 	if (old->speculative && !cur->speculative)
16302 		return false;
16303 
16304 	if (old->active_lock.ptr != cur->active_lock.ptr)
16305 		return false;
16306 
16307 	/* Old and cur active_lock's have to be either both present
16308 	 * or both absent.
16309 	 */
16310 	if (!!old->active_lock.id != !!cur->active_lock.id)
16311 		return false;
16312 
16313 	if (old->active_lock.id &&
16314 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16315 		return false;
16316 
16317 	if (old->active_rcu_lock != cur->active_rcu_lock)
16318 		return false;
16319 
16320 	/* for states to be equal callsites have to be the same
16321 	 * and all frame states need to be equivalent
16322 	 */
16323 	for (i = 0; i <= old->curframe; i++) {
16324 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16325 			return false;
16326 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16327 			return false;
16328 	}
16329 	return true;
16330 }
16331 
16332 /* Return 0 if no propagation happened. Return negative error code if error
16333  * happened. Otherwise, return the propagated bit.
16334  */
16335 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16336 				  struct bpf_reg_state *reg,
16337 				  struct bpf_reg_state *parent_reg)
16338 {
16339 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16340 	u8 flag = reg->live & REG_LIVE_READ;
16341 	int err;
16342 
16343 	/* When comes here, read flags of PARENT_REG or REG could be any of
16344 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16345 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16346 	 */
16347 	if (parent_flag == REG_LIVE_READ64 ||
16348 	    /* Or if there is no read flag from REG. */
16349 	    !flag ||
16350 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16351 	    parent_flag == flag)
16352 		return 0;
16353 
16354 	err = mark_reg_read(env, reg, parent_reg, flag);
16355 	if (err)
16356 		return err;
16357 
16358 	return flag;
16359 }
16360 
16361 /* A write screens off any subsequent reads; but write marks come from the
16362  * straight-line code between a state and its parent.  When we arrive at an
16363  * equivalent state (jump target or such) we didn't arrive by the straight-line
16364  * code, so read marks in the state must propagate to the parent regardless
16365  * of the state's write marks. That's what 'parent == state->parent' comparison
16366  * in mark_reg_read() is for.
16367  */
16368 static int propagate_liveness(struct bpf_verifier_env *env,
16369 			      const struct bpf_verifier_state *vstate,
16370 			      struct bpf_verifier_state *vparent)
16371 {
16372 	struct bpf_reg_state *state_reg, *parent_reg;
16373 	struct bpf_func_state *state, *parent;
16374 	int i, frame, err = 0;
16375 
16376 	if (vparent->curframe != vstate->curframe) {
16377 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16378 		     vparent->curframe, vstate->curframe);
16379 		return -EFAULT;
16380 	}
16381 	/* Propagate read liveness of registers... */
16382 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16383 	for (frame = 0; frame <= vstate->curframe; frame++) {
16384 		parent = vparent->frame[frame];
16385 		state = vstate->frame[frame];
16386 		parent_reg = parent->regs;
16387 		state_reg = state->regs;
16388 		/* We don't need to worry about FP liveness, it's read-only */
16389 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16390 			err = propagate_liveness_reg(env, &state_reg[i],
16391 						     &parent_reg[i]);
16392 			if (err < 0)
16393 				return err;
16394 			if (err == REG_LIVE_READ64)
16395 				mark_insn_zext(env, &parent_reg[i]);
16396 		}
16397 
16398 		/* Propagate stack slots. */
16399 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16400 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16401 			parent_reg = &parent->stack[i].spilled_ptr;
16402 			state_reg = &state->stack[i].spilled_ptr;
16403 			err = propagate_liveness_reg(env, state_reg,
16404 						     parent_reg);
16405 			if (err < 0)
16406 				return err;
16407 		}
16408 	}
16409 	return 0;
16410 }
16411 
16412 /* find precise scalars in the previous equivalent state and
16413  * propagate them into the current state
16414  */
16415 static int propagate_precision(struct bpf_verifier_env *env,
16416 			       const struct bpf_verifier_state *old)
16417 {
16418 	struct bpf_reg_state *state_reg;
16419 	struct bpf_func_state *state;
16420 	int i, err = 0, fr;
16421 	bool first;
16422 
16423 	for (fr = old->curframe; fr >= 0; fr--) {
16424 		state = old->frame[fr];
16425 		state_reg = state->regs;
16426 		first = true;
16427 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16428 			if (state_reg->type != SCALAR_VALUE ||
16429 			    !state_reg->precise ||
16430 			    !(state_reg->live & REG_LIVE_READ))
16431 				continue;
16432 			if (env->log.level & BPF_LOG_LEVEL2) {
16433 				if (first)
16434 					verbose(env, "frame %d: propagating r%d", fr, i);
16435 				else
16436 					verbose(env, ",r%d", i);
16437 			}
16438 			bt_set_frame_reg(&env->bt, fr, i);
16439 			first = false;
16440 		}
16441 
16442 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16443 			if (!is_spilled_reg(&state->stack[i]))
16444 				continue;
16445 			state_reg = &state->stack[i].spilled_ptr;
16446 			if (state_reg->type != SCALAR_VALUE ||
16447 			    !state_reg->precise ||
16448 			    !(state_reg->live & REG_LIVE_READ))
16449 				continue;
16450 			if (env->log.level & BPF_LOG_LEVEL2) {
16451 				if (first)
16452 					verbose(env, "frame %d: propagating fp%d",
16453 						fr, (-i - 1) * BPF_REG_SIZE);
16454 				else
16455 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16456 			}
16457 			bt_set_frame_slot(&env->bt, fr, i);
16458 			first = false;
16459 		}
16460 		if (!first)
16461 			verbose(env, "\n");
16462 	}
16463 
16464 	err = mark_chain_precision_batch(env);
16465 	if (err < 0)
16466 		return err;
16467 
16468 	return 0;
16469 }
16470 
16471 static bool states_maybe_looping(struct bpf_verifier_state *old,
16472 				 struct bpf_verifier_state *cur)
16473 {
16474 	struct bpf_func_state *fold, *fcur;
16475 	int i, fr = cur->curframe;
16476 
16477 	if (old->curframe != fr)
16478 		return false;
16479 
16480 	fold = old->frame[fr];
16481 	fcur = cur->frame[fr];
16482 	for (i = 0; i < MAX_BPF_REG; i++)
16483 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16484 			   offsetof(struct bpf_reg_state, parent)))
16485 			return false;
16486 	return true;
16487 }
16488 
16489 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16490 {
16491 	return env->insn_aux_data[insn_idx].is_iter_next;
16492 }
16493 
16494 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16495  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16496  * states to match, which otherwise would look like an infinite loop. So while
16497  * iter_next() calls are taken care of, we still need to be careful and
16498  * prevent erroneous and too eager declaration of "ininite loop", when
16499  * iterators are involved.
16500  *
16501  * Here's a situation in pseudo-BPF assembly form:
16502  *
16503  *   0: again:                          ; set up iter_next() call args
16504  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16505  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16506  *   3:   if r0 == 0 goto done
16507  *   4:   ... something useful here ...
16508  *   5:   goto again                    ; another iteration
16509  *   6: done:
16510  *   7:   r1 = &it
16511  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16512  *   9:   exit
16513  *
16514  * This is a typical loop. Let's assume that we have a prune point at 1:,
16515  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16516  * again`, assuming other heuristics don't get in a way).
16517  *
16518  * When we first time come to 1:, let's say we have some state X. We proceed
16519  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16520  * Now we come back to validate that forked ACTIVE state. We proceed through
16521  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16522  * are converging. But the problem is that we don't know that yet, as this
16523  * convergence has to happen at iter_next() call site only. So if nothing is
16524  * done, at 1: verifier will use bounded loop logic and declare infinite
16525  * looping (and would be *technically* correct, if not for iterator's
16526  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16527  * don't want that. So what we do in process_iter_next_call() when we go on
16528  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16529  * a different iteration. So when we suspect an infinite loop, we additionally
16530  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16531  * pretend we are not looping and wait for next iter_next() call.
16532  *
16533  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16534  * loop, because that would actually mean infinite loop, as DRAINED state is
16535  * "sticky", and so we'll keep returning into the same instruction with the
16536  * same state (at least in one of possible code paths).
16537  *
16538  * This approach allows to keep infinite loop heuristic even in the face of
16539  * active iterator. E.g., C snippet below is and will be detected as
16540  * inifintely looping:
16541  *
16542  *   struct bpf_iter_num it;
16543  *   int *p, x;
16544  *
16545  *   bpf_iter_num_new(&it, 0, 10);
16546  *   while ((p = bpf_iter_num_next(&t))) {
16547  *       x = p;
16548  *       while (x--) {} // <<-- infinite loop here
16549  *   }
16550  *
16551  */
16552 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16553 {
16554 	struct bpf_reg_state *slot, *cur_slot;
16555 	struct bpf_func_state *state;
16556 	int i, fr;
16557 
16558 	for (fr = old->curframe; fr >= 0; fr--) {
16559 		state = old->frame[fr];
16560 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16561 			if (state->stack[i].slot_type[0] != STACK_ITER)
16562 				continue;
16563 
16564 			slot = &state->stack[i].spilled_ptr;
16565 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16566 				continue;
16567 
16568 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16569 			if (cur_slot->iter.depth != slot->iter.depth)
16570 				return true;
16571 		}
16572 	}
16573 	return false;
16574 }
16575 
16576 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16577 {
16578 	struct bpf_verifier_state_list *new_sl;
16579 	struct bpf_verifier_state_list *sl, **pprev;
16580 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16581 	int i, j, n, err, states_cnt = 0;
16582 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16583 	bool add_new_state = force_new_state;
16584 	bool force_exact;
16585 
16586 	/* bpf progs typically have pruning point every 4 instructions
16587 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16588 	 * Do not add new state for future pruning if the verifier hasn't seen
16589 	 * at least 2 jumps and at least 8 instructions.
16590 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16591 	 * In tests that amounts to up to 50% reduction into total verifier
16592 	 * memory consumption and 20% verifier time speedup.
16593 	 */
16594 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16595 	    env->insn_processed - env->prev_insn_processed >= 8)
16596 		add_new_state = true;
16597 
16598 	pprev = explored_state(env, insn_idx);
16599 	sl = *pprev;
16600 
16601 	clean_live_states(env, insn_idx, cur);
16602 
16603 	while (sl) {
16604 		states_cnt++;
16605 		if (sl->state.insn_idx != insn_idx)
16606 			goto next;
16607 
16608 		if (sl->state.branches) {
16609 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16610 
16611 			if (frame->in_async_callback_fn &&
16612 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16613 				/* Different async_entry_cnt means that the verifier is
16614 				 * processing another entry into async callback.
16615 				 * Seeing the same state is not an indication of infinite
16616 				 * loop or infinite recursion.
16617 				 * But finding the same state doesn't mean that it's safe
16618 				 * to stop processing the current state. The previous state
16619 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16620 				 * Checking in_async_callback_fn alone is not enough either.
16621 				 * Since the verifier still needs to catch infinite loops
16622 				 * inside async callbacks.
16623 				 */
16624 				goto skip_inf_loop_check;
16625 			}
16626 			/* BPF open-coded iterators loop detection is special.
16627 			 * states_maybe_looping() logic is too simplistic in detecting
16628 			 * states that *might* be equivalent, because it doesn't know
16629 			 * about ID remapping, so don't even perform it.
16630 			 * See process_iter_next_call() and iter_active_depths_differ()
16631 			 * for overview of the logic. When current and one of parent
16632 			 * states are detected as equivalent, it's a good thing: we prove
16633 			 * convergence and can stop simulating further iterations.
16634 			 * It's safe to assume that iterator loop will finish, taking into
16635 			 * account iter_next() contract of eventually returning
16636 			 * sticky NULL result.
16637 			 *
16638 			 * Note, that states have to be compared exactly in this case because
16639 			 * read and precision marks might not be finalized inside the loop.
16640 			 * E.g. as in the program below:
16641 			 *
16642 			 *     1. r7 = -16
16643 			 *     2. r6 = bpf_get_prandom_u32()
16644 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16645 			 *     4.   if (r6 != 42) {
16646 			 *     5.     r7 = -32
16647 			 *     6.     r6 = bpf_get_prandom_u32()
16648 			 *     7.     continue
16649 			 *     8.   }
16650 			 *     9.   r0 = r10
16651 			 *    10.   r0 += r7
16652 			 *    11.   r8 = *(u64 *)(r0 + 0)
16653 			 *    12.   r6 = bpf_get_prandom_u32()
16654 			 *    13. }
16655 			 *
16656 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16657 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16658 			 * not have read or precision mark for r7 yet, thus inexact states
16659 			 * comparison would discard current state with r7=-32
16660 			 * => unsafe memory access at 11 would not be caught.
16661 			 */
16662 			if (is_iter_next_insn(env, insn_idx)) {
16663 				if (states_equal(env, &sl->state, cur, true)) {
16664 					struct bpf_func_state *cur_frame;
16665 					struct bpf_reg_state *iter_state, *iter_reg;
16666 					int spi;
16667 
16668 					cur_frame = cur->frame[cur->curframe];
16669 					/* btf_check_iter_kfuncs() enforces that
16670 					 * iter state pointer is always the first arg
16671 					 */
16672 					iter_reg = &cur_frame->regs[BPF_REG_1];
16673 					/* current state is valid due to states_equal(),
16674 					 * so we can assume valid iter and reg state,
16675 					 * no need for extra (re-)validations
16676 					 */
16677 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16678 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16679 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16680 						update_loop_entry(cur, &sl->state);
16681 						goto hit;
16682 					}
16683 				}
16684 				goto skip_inf_loop_check;
16685 			}
16686 			if (calls_callback(env, insn_idx)) {
16687 				if (states_equal(env, &sl->state, cur, true))
16688 					goto hit;
16689 				goto skip_inf_loop_check;
16690 			}
16691 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16692 			if (states_maybe_looping(&sl->state, cur) &&
16693 			    states_equal(env, &sl->state, cur, false) &&
16694 			    !iter_active_depths_differ(&sl->state, cur) &&
16695 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16696 				verbose_linfo(env, insn_idx, "; ");
16697 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16698 				verbose(env, "cur state:");
16699 				print_verifier_state(env, cur->frame[cur->curframe], true);
16700 				verbose(env, "old state:");
16701 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16702 				return -EINVAL;
16703 			}
16704 			/* if the verifier is processing a loop, avoid adding new state
16705 			 * too often, since different loop iterations have distinct
16706 			 * states and may not help future pruning.
16707 			 * This threshold shouldn't be too low to make sure that
16708 			 * a loop with large bound will be rejected quickly.
16709 			 * The most abusive loop will be:
16710 			 * r1 += 1
16711 			 * if r1 < 1000000 goto pc-2
16712 			 * 1M insn_procssed limit / 100 == 10k peak states.
16713 			 * This threshold shouldn't be too high either, since states
16714 			 * at the end of the loop are likely to be useful in pruning.
16715 			 */
16716 skip_inf_loop_check:
16717 			if (!force_new_state &&
16718 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16719 			    env->insn_processed - env->prev_insn_processed < 100)
16720 				add_new_state = false;
16721 			goto miss;
16722 		}
16723 		/* If sl->state is a part of a loop and this loop's entry is a part of
16724 		 * current verification path then states have to be compared exactly.
16725 		 * 'force_exact' is needed to catch the following case:
16726 		 *
16727 		 *                initial     Here state 'succ' was processed first,
16728 		 *                  |         it was eventually tracked to produce a
16729 		 *                  V         state identical to 'hdr'.
16730 		 *     .---------> hdr        All branches from 'succ' had been explored
16731 		 *     |            |         and thus 'succ' has its .branches == 0.
16732 		 *     |            V
16733 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16734 		 *     |    |       |         to the same instruction + callsites.
16735 		 *     |    V       V         In such case it is necessary to check
16736 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16737 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16738 		 *     |    V       V         same loop exact flag has to be set.
16739 		 *     |   succ <- cur        To check if that is the case, verify
16740 		 *     |    |                 if loop entry of 'succ' is in current
16741 		 *     |    V                 DFS path.
16742 		 *     |   ...
16743 		 *     |    |
16744 		 *     '----'
16745 		 *
16746 		 * Additional details are in the comment before get_loop_entry().
16747 		 */
16748 		loop_entry = get_loop_entry(&sl->state);
16749 		force_exact = loop_entry && loop_entry->branches > 0;
16750 		if (states_equal(env, &sl->state, cur, force_exact)) {
16751 			if (force_exact)
16752 				update_loop_entry(cur, loop_entry);
16753 hit:
16754 			sl->hit_cnt++;
16755 			/* reached equivalent register/stack state,
16756 			 * prune the search.
16757 			 * Registers read by the continuation are read by us.
16758 			 * If we have any write marks in env->cur_state, they
16759 			 * will prevent corresponding reads in the continuation
16760 			 * from reaching our parent (an explored_state).  Our
16761 			 * own state will get the read marks recorded, but
16762 			 * they'll be immediately forgotten as we're pruning
16763 			 * this state and will pop a new one.
16764 			 */
16765 			err = propagate_liveness(env, &sl->state, cur);
16766 
16767 			/* if previous state reached the exit with precision and
16768 			 * current state is equivalent to it (except precsion marks)
16769 			 * the precision needs to be propagated back in
16770 			 * the current state.
16771 			 */
16772 			err = err ? : push_jmp_history(env, cur);
16773 			err = err ? : propagate_precision(env, &sl->state);
16774 			if (err)
16775 				return err;
16776 			return 1;
16777 		}
16778 miss:
16779 		/* when new state is not going to be added do not increase miss count.
16780 		 * Otherwise several loop iterations will remove the state
16781 		 * recorded earlier. The goal of these heuristics is to have
16782 		 * states from some iterations of the loop (some in the beginning
16783 		 * and some at the end) to help pruning.
16784 		 */
16785 		if (add_new_state)
16786 			sl->miss_cnt++;
16787 		/* heuristic to determine whether this state is beneficial
16788 		 * to keep checking from state equivalence point of view.
16789 		 * Higher numbers increase max_states_per_insn and verification time,
16790 		 * but do not meaningfully decrease insn_processed.
16791 		 * 'n' controls how many times state could miss before eviction.
16792 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16793 		 * too early would hinder iterator convergence.
16794 		 */
16795 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16796 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16797 			/* the state is unlikely to be useful. Remove it to
16798 			 * speed up verification
16799 			 */
16800 			*pprev = sl->next;
16801 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16802 			    !sl->state.used_as_loop_entry) {
16803 				u32 br = sl->state.branches;
16804 
16805 				WARN_ONCE(br,
16806 					  "BUG live_done but branches_to_explore %d\n",
16807 					  br);
16808 				free_verifier_state(&sl->state, false);
16809 				kfree(sl);
16810 				env->peak_states--;
16811 			} else {
16812 				/* cannot free this state, since parentage chain may
16813 				 * walk it later. Add it for free_list instead to
16814 				 * be freed at the end of verification
16815 				 */
16816 				sl->next = env->free_list;
16817 				env->free_list = sl;
16818 			}
16819 			sl = *pprev;
16820 			continue;
16821 		}
16822 next:
16823 		pprev = &sl->next;
16824 		sl = *pprev;
16825 	}
16826 
16827 	if (env->max_states_per_insn < states_cnt)
16828 		env->max_states_per_insn = states_cnt;
16829 
16830 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16831 		return 0;
16832 
16833 	if (!add_new_state)
16834 		return 0;
16835 
16836 	/* There were no equivalent states, remember the current one.
16837 	 * Technically the current state is not proven to be safe yet,
16838 	 * but it will either reach outer most bpf_exit (which means it's safe)
16839 	 * or it will be rejected. When there are no loops the verifier won't be
16840 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16841 	 * again on the way to bpf_exit.
16842 	 * When looping the sl->state.branches will be > 0 and this state
16843 	 * will not be considered for equivalence until branches == 0.
16844 	 */
16845 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16846 	if (!new_sl)
16847 		return -ENOMEM;
16848 	env->total_states++;
16849 	env->peak_states++;
16850 	env->prev_jmps_processed = env->jmps_processed;
16851 	env->prev_insn_processed = env->insn_processed;
16852 
16853 	/* forget precise markings we inherited, see __mark_chain_precision */
16854 	if (env->bpf_capable)
16855 		mark_all_scalars_imprecise(env, cur);
16856 
16857 	/* add new state to the head of linked list */
16858 	new = &new_sl->state;
16859 	err = copy_verifier_state(new, cur);
16860 	if (err) {
16861 		free_verifier_state(new, false);
16862 		kfree(new_sl);
16863 		return err;
16864 	}
16865 	new->insn_idx = insn_idx;
16866 	WARN_ONCE(new->branches != 1,
16867 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16868 
16869 	cur->parent = new;
16870 	cur->first_insn_idx = insn_idx;
16871 	cur->dfs_depth = new->dfs_depth + 1;
16872 	clear_jmp_history(cur);
16873 	new_sl->next = *explored_state(env, insn_idx);
16874 	*explored_state(env, insn_idx) = new_sl;
16875 	/* connect new state to parentage chain. Current frame needs all
16876 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16877 	 * to the stack implicitly by JITs) so in callers' frames connect just
16878 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16879 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16880 	 * from callee with its full parentage chain, anyway.
16881 	 */
16882 	/* clear write marks in current state: the writes we did are not writes
16883 	 * our child did, so they don't screen off its reads from us.
16884 	 * (There are no read marks in current state, because reads always mark
16885 	 * their parent and current state never has children yet.  Only
16886 	 * explored_states can get read marks.)
16887 	 */
16888 	for (j = 0; j <= cur->curframe; j++) {
16889 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16890 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16891 		for (i = 0; i < BPF_REG_FP; i++)
16892 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16893 	}
16894 
16895 	/* all stack frames are accessible from callee, clear them all */
16896 	for (j = 0; j <= cur->curframe; j++) {
16897 		struct bpf_func_state *frame = cur->frame[j];
16898 		struct bpf_func_state *newframe = new->frame[j];
16899 
16900 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16901 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16902 			frame->stack[i].spilled_ptr.parent =
16903 						&newframe->stack[i].spilled_ptr;
16904 		}
16905 	}
16906 	return 0;
16907 }
16908 
16909 /* Return true if it's OK to have the same insn return a different type. */
16910 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16911 {
16912 	switch (base_type(type)) {
16913 	case PTR_TO_CTX:
16914 	case PTR_TO_SOCKET:
16915 	case PTR_TO_SOCK_COMMON:
16916 	case PTR_TO_TCP_SOCK:
16917 	case PTR_TO_XDP_SOCK:
16918 	case PTR_TO_BTF_ID:
16919 		return false;
16920 	default:
16921 		return true;
16922 	}
16923 }
16924 
16925 /* If an instruction was previously used with particular pointer types, then we
16926  * need to be careful to avoid cases such as the below, where it may be ok
16927  * for one branch accessing the pointer, but not ok for the other branch:
16928  *
16929  * R1 = sock_ptr
16930  * goto X;
16931  * ...
16932  * R1 = some_other_valid_ptr;
16933  * goto X;
16934  * ...
16935  * R2 = *(u32 *)(R1 + 0);
16936  */
16937 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16938 {
16939 	return src != prev && (!reg_type_mismatch_ok(src) ||
16940 			       !reg_type_mismatch_ok(prev));
16941 }
16942 
16943 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16944 			     bool allow_trust_missmatch)
16945 {
16946 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16947 
16948 	if (*prev_type == NOT_INIT) {
16949 		/* Saw a valid insn
16950 		 * dst_reg = *(u32 *)(src_reg + off)
16951 		 * save type to validate intersecting paths
16952 		 */
16953 		*prev_type = type;
16954 	} else if (reg_type_mismatch(type, *prev_type)) {
16955 		/* Abuser program is trying to use the same insn
16956 		 * dst_reg = *(u32*) (src_reg + off)
16957 		 * with different pointer types:
16958 		 * src_reg == ctx in one branch and
16959 		 * src_reg == stack|map in some other branch.
16960 		 * Reject it.
16961 		 */
16962 		if (allow_trust_missmatch &&
16963 		    base_type(type) == PTR_TO_BTF_ID &&
16964 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16965 			/*
16966 			 * Have to support a use case when one path through
16967 			 * the program yields TRUSTED pointer while another
16968 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16969 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16970 			 */
16971 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16972 		} else {
16973 			verbose(env, "same insn cannot be used with different pointers\n");
16974 			return -EINVAL;
16975 		}
16976 	}
16977 
16978 	return 0;
16979 }
16980 
16981 static int do_check(struct bpf_verifier_env *env)
16982 {
16983 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16984 	struct bpf_verifier_state *state = env->cur_state;
16985 	struct bpf_insn *insns = env->prog->insnsi;
16986 	struct bpf_reg_state *regs;
16987 	int insn_cnt = env->prog->len;
16988 	bool do_print_state = false;
16989 	int prev_insn_idx = -1;
16990 
16991 	for (;;) {
16992 		struct bpf_insn *insn;
16993 		u8 class;
16994 		int err;
16995 
16996 		env->prev_insn_idx = prev_insn_idx;
16997 		if (env->insn_idx >= insn_cnt) {
16998 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16999 				env->insn_idx, insn_cnt);
17000 			return -EFAULT;
17001 		}
17002 
17003 		insn = &insns[env->insn_idx];
17004 		class = BPF_CLASS(insn->code);
17005 
17006 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17007 			verbose(env,
17008 				"BPF program is too large. Processed %d insn\n",
17009 				env->insn_processed);
17010 			return -E2BIG;
17011 		}
17012 
17013 		state->last_insn_idx = env->prev_insn_idx;
17014 
17015 		if (is_prune_point(env, env->insn_idx)) {
17016 			err = is_state_visited(env, env->insn_idx);
17017 			if (err < 0)
17018 				return err;
17019 			if (err == 1) {
17020 				/* found equivalent state, can prune the search */
17021 				if (env->log.level & BPF_LOG_LEVEL) {
17022 					if (do_print_state)
17023 						verbose(env, "\nfrom %d to %d%s: safe\n",
17024 							env->prev_insn_idx, env->insn_idx,
17025 							env->cur_state->speculative ?
17026 							" (speculative execution)" : "");
17027 					else
17028 						verbose(env, "%d: safe\n", env->insn_idx);
17029 				}
17030 				goto process_bpf_exit;
17031 			}
17032 		}
17033 
17034 		if (is_jmp_point(env, env->insn_idx)) {
17035 			err = push_jmp_history(env, state);
17036 			if (err)
17037 				return err;
17038 		}
17039 
17040 		if (signal_pending(current))
17041 			return -EAGAIN;
17042 
17043 		if (need_resched())
17044 			cond_resched();
17045 
17046 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17047 			verbose(env, "\nfrom %d to %d%s:",
17048 				env->prev_insn_idx, env->insn_idx,
17049 				env->cur_state->speculative ?
17050 				" (speculative execution)" : "");
17051 			print_verifier_state(env, state->frame[state->curframe], true);
17052 			do_print_state = false;
17053 		}
17054 
17055 		if (env->log.level & BPF_LOG_LEVEL) {
17056 			const struct bpf_insn_cbs cbs = {
17057 				.cb_call	= disasm_kfunc_name,
17058 				.cb_print	= verbose,
17059 				.private_data	= env,
17060 			};
17061 
17062 			if (verifier_state_scratched(env))
17063 				print_insn_state(env, state->frame[state->curframe]);
17064 
17065 			verbose_linfo(env, env->insn_idx, "; ");
17066 			env->prev_log_pos = env->log.end_pos;
17067 			verbose(env, "%d: ", env->insn_idx);
17068 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17069 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17070 			env->prev_log_pos = env->log.end_pos;
17071 		}
17072 
17073 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17074 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17075 							   env->prev_insn_idx);
17076 			if (err)
17077 				return err;
17078 		}
17079 
17080 		regs = cur_regs(env);
17081 		sanitize_mark_insn_seen(env);
17082 		prev_insn_idx = env->insn_idx;
17083 
17084 		if (class == BPF_ALU || class == BPF_ALU64) {
17085 			err = check_alu_op(env, insn);
17086 			if (err)
17087 				return err;
17088 
17089 		} else if (class == BPF_LDX) {
17090 			enum bpf_reg_type src_reg_type;
17091 
17092 			/* check for reserved fields is already done */
17093 
17094 			/* check src operand */
17095 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17096 			if (err)
17097 				return err;
17098 
17099 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17100 			if (err)
17101 				return err;
17102 
17103 			src_reg_type = regs[insn->src_reg].type;
17104 
17105 			/* check that memory (src_reg + off) is readable,
17106 			 * the state of dst_reg will be updated by this func
17107 			 */
17108 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17109 					       insn->off, BPF_SIZE(insn->code),
17110 					       BPF_READ, insn->dst_reg, false,
17111 					       BPF_MODE(insn->code) == BPF_MEMSX);
17112 			if (err)
17113 				return err;
17114 
17115 			err = save_aux_ptr_type(env, src_reg_type, true);
17116 			if (err)
17117 				return err;
17118 		} else if (class == BPF_STX) {
17119 			enum bpf_reg_type dst_reg_type;
17120 
17121 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17122 				err = check_atomic(env, env->insn_idx, insn);
17123 				if (err)
17124 					return err;
17125 				env->insn_idx++;
17126 				continue;
17127 			}
17128 
17129 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17130 				verbose(env, "BPF_STX uses reserved fields\n");
17131 				return -EINVAL;
17132 			}
17133 
17134 			/* check src1 operand */
17135 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17136 			if (err)
17137 				return err;
17138 			/* check src2 operand */
17139 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17140 			if (err)
17141 				return err;
17142 
17143 			dst_reg_type = regs[insn->dst_reg].type;
17144 
17145 			/* check that memory (dst_reg + off) is writeable */
17146 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17147 					       insn->off, BPF_SIZE(insn->code),
17148 					       BPF_WRITE, insn->src_reg, false, false);
17149 			if (err)
17150 				return err;
17151 
17152 			err = save_aux_ptr_type(env, dst_reg_type, false);
17153 			if (err)
17154 				return err;
17155 		} else if (class == BPF_ST) {
17156 			enum bpf_reg_type dst_reg_type;
17157 
17158 			if (BPF_MODE(insn->code) != BPF_MEM ||
17159 			    insn->src_reg != BPF_REG_0) {
17160 				verbose(env, "BPF_ST uses reserved fields\n");
17161 				return -EINVAL;
17162 			}
17163 			/* check src operand */
17164 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17165 			if (err)
17166 				return err;
17167 
17168 			dst_reg_type = regs[insn->dst_reg].type;
17169 
17170 			/* check that memory (dst_reg + off) is writeable */
17171 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17172 					       insn->off, BPF_SIZE(insn->code),
17173 					       BPF_WRITE, -1, false, false);
17174 			if (err)
17175 				return err;
17176 
17177 			err = save_aux_ptr_type(env, dst_reg_type, false);
17178 			if (err)
17179 				return err;
17180 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17181 			u8 opcode = BPF_OP(insn->code);
17182 
17183 			env->jmps_processed++;
17184 			if (opcode == BPF_CALL) {
17185 				if (BPF_SRC(insn->code) != BPF_K ||
17186 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17187 				     && insn->off != 0) ||
17188 				    (insn->src_reg != BPF_REG_0 &&
17189 				     insn->src_reg != BPF_PSEUDO_CALL &&
17190 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17191 				    insn->dst_reg != BPF_REG_0 ||
17192 				    class == BPF_JMP32) {
17193 					verbose(env, "BPF_CALL uses reserved fields\n");
17194 					return -EINVAL;
17195 				}
17196 
17197 				if (env->cur_state->active_lock.ptr) {
17198 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17199 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17200 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17201 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17202 						verbose(env, "function calls are not allowed while holding a lock\n");
17203 						return -EINVAL;
17204 					}
17205 				}
17206 				if (insn->src_reg == BPF_PSEUDO_CALL)
17207 					err = check_func_call(env, insn, &env->insn_idx);
17208 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17209 					err = check_kfunc_call(env, insn, &env->insn_idx);
17210 				else
17211 					err = check_helper_call(env, insn, &env->insn_idx);
17212 				if (err)
17213 					return err;
17214 
17215 				mark_reg_scratched(env, BPF_REG_0);
17216 			} else if (opcode == BPF_JA) {
17217 				if (BPF_SRC(insn->code) != BPF_K ||
17218 				    insn->src_reg != BPF_REG_0 ||
17219 				    insn->dst_reg != BPF_REG_0 ||
17220 				    (class == BPF_JMP && insn->imm != 0) ||
17221 				    (class == BPF_JMP32 && insn->off != 0)) {
17222 					verbose(env, "BPF_JA uses reserved fields\n");
17223 					return -EINVAL;
17224 				}
17225 
17226 				if (class == BPF_JMP)
17227 					env->insn_idx += insn->off + 1;
17228 				else
17229 					env->insn_idx += insn->imm + 1;
17230 				continue;
17231 
17232 			} else if (opcode == BPF_EXIT) {
17233 				if (BPF_SRC(insn->code) != BPF_K ||
17234 				    insn->imm != 0 ||
17235 				    insn->src_reg != BPF_REG_0 ||
17236 				    insn->dst_reg != BPF_REG_0 ||
17237 				    class == BPF_JMP32) {
17238 					verbose(env, "BPF_EXIT uses reserved fields\n");
17239 					return -EINVAL;
17240 				}
17241 
17242 				if (env->cur_state->active_lock.ptr &&
17243 				    !in_rbtree_lock_required_cb(env)) {
17244 					verbose(env, "bpf_spin_unlock is missing\n");
17245 					return -EINVAL;
17246 				}
17247 
17248 				if (env->cur_state->active_rcu_lock &&
17249 				    !in_rbtree_lock_required_cb(env)) {
17250 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17251 					return -EINVAL;
17252 				}
17253 
17254 				/* We must do check_reference_leak here before
17255 				 * prepare_func_exit to handle the case when
17256 				 * state->curframe > 0, it may be a callback
17257 				 * function, for which reference_state must
17258 				 * match caller reference state when it exits.
17259 				 */
17260 				err = check_reference_leak(env);
17261 				if (err)
17262 					return err;
17263 
17264 				if (state->curframe) {
17265 					/* exit from nested function */
17266 					err = prepare_func_exit(env, &env->insn_idx);
17267 					if (err)
17268 						return err;
17269 					do_print_state = true;
17270 					continue;
17271 				}
17272 
17273 				err = check_return_code(env);
17274 				if (err)
17275 					return err;
17276 process_bpf_exit:
17277 				mark_verifier_state_scratched(env);
17278 				update_branch_counts(env, env->cur_state);
17279 				err = pop_stack(env, &prev_insn_idx,
17280 						&env->insn_idx, pop_log);
17281 				if (err < 0) {
17282 					if (err != -ENOENT)
17283 						return err;
17284 					break;
17285 				} else {
17286 					do_print_state = true;
17287 					continue;
17288 				}
17289 			} else {
17290 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17291 				if (err)
17292 					return err;
17293 			}
17294 		} else if (class == BPF_LD) {
17295 			u8 mode = BPF_MODE(insn->code);
17296 
17297 			if (mode == BPF_ABS || mode == BPF_IND) {
17298 				err = check_ld_abs(env, insn);
17299 				if (err)
17300 					return err;
17301 
17302 			} else if (mode == BPF_IMM) {
17303 				err = check_ld_imm(env, insn);
17304 				if (err)
17305 					return err;
17306 
17307 				env->insn_idx++;
17308 				sanitize_mark_insn_seen(env);
17309 			} else {
17310 				verbose(env, "invalid BPF_LD mode\n");
17311 				return -EINVAL;
17312 			}
17313 		} else {
17314 			verbose(env, "unknown insn class %d\n", class);
17315 			return -EINVAL;
17316 		}
17317 
17318 		env->insn_idx++;
17319 	}
17320 
17321 	return 0;
17322 }
17323 
17324 static int find_btf_percpu_datasec(struct btf *btf)
17325 {
17326 	const struct btf_type *t;
17327 	const char *tname;
17328 	int i, n;
17329 
17330 	/*
17331 	 * Both vmlinux and module each have their own ".data..percpu"
17332 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17333 	 * types to look at only module's own BTF types.
17334 	 */
17335 	n = btf_nr_types(btf);
17336 	if (btf_is_module(btf))
17337 		i = btf_nr_types(btf_vmlinux);
17338 	else
17339 		i = 1;
17340 
17341 	for(; i < n; i++) {
17342 		t = btf_type_by_id(btf, i);
17343 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17344 			continue;
17345 
17346 		tname = btf_name_by_offset(btf, t->name_off);
17347 		if (!strcmp(tname, ".data..percpu"))
17348 			return i;
17349 	}
17350 
17351 	return -ENOENT;
17352 }
17353 
17354 /* replace pseudo btf_id with kernel symbol address */
17355 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17356 			       struct bpf_insn *insn,
17357 			       struct bpf_insn_aux_data *aux)
17358 {
17359 	const struct btf_var_secinfo *vsi;
17360 	const struct btf_type *datasec;
17361 	struct btf_mod_pair *btf_mod;
17362 	const struct btf_type *t;
17363 	const char *sym_name;
17364 	bool percpu = false;
17365 	u32 type, id = insn->imm;
17366 	struct btf *btf;
17367 	s32 datasec_id;
17368 	u64 addr;
17369 	int i, btf_fd, err;
17370 
17371 	btf_fd = insn[1].imm;
17372 	if (btf_fd) {
17373 		btf = btf_get_by_fd(btf_fd);
17374 		if (IS_ERR(btf)) {
17375 			verbose(env, "invalid module BTF object FD specified.\n");
17376 			return -EINVAL;
17377 		}
17378 	} else {
17379 		if (!btf_vmlinux) {
17380 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17381 			return -EINVAL;
17382 		}
17383 		btf = btf_vmlinux;
17384 		btf_get(btf);
17385 	}
17386 
17387 	t = btf_type_by_id(btf, id);
17388 	if (!t) {
17389 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17390 		err = -ENOENT;
17391 		goto err_put;
17392 	}
17393 
17394 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17395 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17396 		err = -EINVAL;
17397 		goto err_put;
17398 	}
17399 
17400 	sym_name = btf_name_by_offset(btf, t->name_off);
17401 	addr = kallsyms_lookup_name(sym_name);
17402 	if (!addr) {
17403 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17404 			sym_name);
17405 		err = -ENOENT;
17406 		goto err_put;
17407 	}
17408 	insn[0].imm = (u32)addr;
17409 	insn[1].imm = addr >> 32;
17410 
17411 	if (btf_type_is_func(t)) {
17412 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17413 		aux->btf_var.mem_size = 0;
17414 		goto check_btf;
17415 	}
17416 
17417 	datasec_id = find_btf_percpu_datasec(btf);
17418 	if (datasec_id > 0) {
17419 		datasec = btf_type_by_id(btf, datasec_id);
17420 		for_each_vsi(i, datasec, vsi) {
17421 			if (vsi->type == id) {
17422 				percpu = true;
17423 				break;
17424 			}
17425 		}
17426 	}
17427 
17428 	type = t->type;
17429 	t = btf_type_skip_modifiers(btf, type, NULL);
17430 	if (percpu) {
17431 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17432 		aux->btf_var.btf = btf;
17433 		aux->btf_var.btf_id = type;
17434 	} else if (!btf_type_is_struct(t)) {
17435 		const struct btf_type *ret;
17436 		const char *tname;
17437 		u32 tsize;
17438 
17439 		/* resolve the type size of ksym. */
17440 		ret = btf_resolve_size(btf, t, &tsize);
17441 		if (IS_ERR(ret)) {
17442 			tname = btf_name_by_offset(btf, t->name_off);
17443 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17444 				tname, PTR_ERR(ret));
17445 			err = -EINVAL;
17446 			goto err_put;
17447 		}
17448 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17449 		aux->btf_var.mem_size = tsize;
17450 	} else {
17451 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17452 		aux->btf_var.btf = btf;
17453 		aux->btf_var.btf_id = type;
17454 	}
17455 check_btf:
17456 	/* check whether we recorded this BTF (and maybe module) already */
17457 	for (i = 0; i < env->used_btf_cnt; i++) {
17458 		if (env->used_btfs[i].btf == btf) {
17459 			btf_put(btf);
17460 			return 0;
17461 		}
17462 	}
17463 
17464 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17465 		err = -E2BIG;
17466 		goto err_put;
17467 	}
17468 
17469 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17470 	btf_mod->btf = btf;
17471 	btf_mod->module = NULL;
17472 
17473 	/* if we reference variables from kernel module, bump its refcount */
17474 	if (btf_is_module(btf)) {
17475 		btf_mod->module = btf_try_get_module(btf);
17476 		if (!btf_mod->module) {
17477 			err = -ENXIO;
17478 			goto err_put;
17479 		}
17480 	}
17481 
17482 	env->used_btf_cnt++;
17483 
17484 	return 0;
17485 err_put:
17486 	btf_put(btf);
17487 	return err;
17488 }
17489 
17490 static bool is_tracing_prog_type(enum bpf_prog_type type)
17491 {
17492 	switch (type) {
17493 	case BPF_PROG_TYPE_KPROBE:
17494 	case BPF_PROG_TYPE_TRACEPOINT:
17495 	case BPF_PROG_TYPE_PERF_EVENT:
17496 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17497 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17498 		return true;
17499 	default:
17500 		return false;
17501 	}
17502 }
17503 
17504 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17505 					struct bpf_map *map,
17506 					struct bpf_prog *prog)
17507 
17508 {
17509 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17510 
17511 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17512 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17513 		if (is_tracing_prog_type(prog_type)) {
17514 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17515 			return -EINVAL;
17516 		}
17517 	}
17518 
17519 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17520 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17521 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17522 			return -EINVAL;
17523 		}
17524 
17525 		if (is_tracing_prog_type(prog_type)) {
17526 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17527 			return -EINVAL;
17528 		}
17529 	}
17530 
17531 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17532 		if (is_tracing_prog_type(prog_type)) {
17533 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17534 			return -EINVAL;
17535 		}
17536 	}
17537 
17538 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17539 	    !bpf_offload_prog_map_match(prog, map)) {
17540 		verbose(env, "offload device mismatch between prog and map\n");
17541 		return -EINVAL;
17542 	}
17543 
17544 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17545 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17546 		return -EINVAL;
17547 	}
17548 
17549 	if (prog->aux->sleepable)
17550 		switch (map->map_type) {
17551 		case BPF_MAP_TYPE_HASH:
17552 		case BPF_MAP_TYPE_LRU_HASH:
17553 		case BPF_MAP_TYPE_ARRAY:
17554 		case BPF_MAP_TYPE_PERCPU_HASH:
17555 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17556 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17557 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17558 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17559 		case BPF_MAP_TYPE_RINGBUF:
17560 		case BPF_MAP_TYPE_USER_RINGBUF:
17561 		case BPF_MAP_TYPE_INODE_STORAGE:
17562 		case BPF_MAP_TYPE_SK_STORAGE:
17563 		case BPF_MAP_TYPE_TASK_STORAGE:
17564 		case BPF_MAP_TYPE_CGRP_STORAGE:
17565 			break;
17566 		default:
17567 			verbose(env,
17568 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17569 			return -EINVAL;
17570 		}
17571 
17572 	return 0;
17573 }
17574 
17575 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17576 {
17577 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17578 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17579 }
17580 
17581 /* find and rewrite pseudo imm in ld_imm64 instructions:
17582  *
17583  * 1. if it accesses map FD, replace it with actual map pointer.
17584  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17585  *
17586  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17587  */
17588 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17589 {
17590 	struct bpf_insn *insn = env->prog->insnsi;
17591 	int insn_cnt = env->prog->len;
17592 	int i, j, err;
17593 
17594 	err = bpf_prog_calc_tag(env->prog);
17595 	if (err)
17596 		return err;
17597 
17598 	for (i = 0; i < insn_cnt; i++, insn++) {
17599 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17600 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17601 		    insn->imm != 0)) {
17602 			verbose(env, "BPF_LDX uses reserved fields\n");
17603 			return -EINVAL;
17604 		}
17605 
17606 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17607 			struct bpf_insn_aux_data *aux;
17608 			struct bpf_map *map;
17609 			struct fd f;
17610 			u64 addr;
17611 			u32 fd;
17612 
17613 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17614 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17615 			    insn[1].off != 0) {
17616 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17617 				return -EINVAL;
17618 			}
17619 
17620 			if (insn[0].src_reg == 0)
17621 				/* valid generic load 64-bit imm */
17622 				goto next_insn;
17623 
17624 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17625 				aux = &env->insn_aux_data[i];
17626 				err = check_pseudo_btf_id(env, insn, aux);
17627 				if (err)
17628 					return err;
17629 				goto next_insn;
17630 			}
17631 
17632 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17633 				aux = &env->insn_aux_data[i];
17634 				aux->ptr_type = PTR_TO_FUNC;
17635 				goto next_insn;
17636 			}
17637 
17638 			/* In final convert_pseudo_ld_imm64() step, this is
17639 			 * converted into regular 64-bit imm load insn.
17640 			 */
17641 			switch (insn[0].src_reg) {
17642 			case BPF_PSEUDO_MAP_VALUE:
17643 			case BPF_PSEUDO_MAP_IDX_VALUE:
17644 				break;
17645 			case BPF_PSEUDO_MAP_FD:
17646 			case BPF_PSEUDO_MAP_IDX:
17647 				if (insn[1].imm == 0)
17648 					break;
17649 				fallthrough;
17650 			default:
17651 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17652 				return -EINVAL;
17653 			}
17654 
17655 			switch (insn[0].src_reg) {
17656 			case BPF_PSEUDO_MAP_IDX_VALUE:
17657 			case BPF_PSEUDO_MAP_IDX:
17658 				if (bpfptr_is_null(env->fd_array)) {
17659 					verbose(env, "fd_idx without fd_array is invalid\n");
17660 					return -EPROTO;
17661 				}
17662 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17663 							    insn[0].imm * sizeof(fd),
17664 							    sizeof(fd)))
17665 					return -EFAULT;
17666 				break;
17667 			default:
17668 				fd = insn[0].imm;
17669 				break;
17670 			}
17671 
17672 			f = fdget(fd);
17673 			map = __bpf_map_get(f);
17674 			if (IS_ERR(map)) {
17675 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17676 				return PTR_ERR(map);
17677 			}
17678 
17679 			err = check_map_prog_compatibility(env, map, env->prog);
17680 			if (err) {
17681 				fdput(f);
17682 				return err;
17683 			}
17684 
17685 			aux = &env->insn_aux_data[i];
17686 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17687 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17688 				addr = (unsigned long)map;
17689 			} else {
17690 				u32 off = insn[1].imm;
17691 
17692 				if (off >= BPF_MAX_VAR_OFF) {
17693 					verbose(env, "direct value offset of %u is not allowed\n", off);
17694 					fdput(f);
17695 					return -EINVAL;
17696 				}
17697 
17698 				if (!map->ops->map_direct_value_addr) {
17699 					verbose(env, "no direct value access support for this map type\n");
17700 					fdput(f);
17701 					return -EINVAL;
17702 				}
17703 
17704 				err = map->ops->map_direct_value_addr(map, &addr, off);
17705 				if (err) {
17706 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17707 						map->value_size, off);
17708 					fdput(f);
17709 					return err;
17710 				}
17711 
17712 				aux->map_off = off;
17713 				addr += off;
17714 			}
17715 
17716 			insn[0].imm = (u32)addr;
17717 			insn[1].imm = addr >> 32;
17718 
17719 			/* check whether we recorded this map already */
17720 			for (j = 0; j < env->used_map_cnt; j++) {
17721 				if (env->used_maps[j] == map) {
17722 					aux->map_index = j;
17723 					fdput(f);
17724 					goto next_insn;
17725 				}
17726 			}
17727 
17728 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17729 				fdput(f);
17730 				return -E2BIG;
17731 			}
17732 
17733 			if (env->prog->aux->sleepable)
17734 				atomic64_inc(&map->sleepable_refcnt);
17735 			/* hold the map. If the program is rejected by verifier,
17736 			 * the map will be released by release_maps() or it
17737 			 * will be used by the valid program until it's unloaded
17738 			 * and all maps are released in bpf_free_used_maps()
17739 			 */
17740 			bpf_map_inc(map);
17741 
17742 			aux->map_index = env->used_map_cnt;
17743 			env->used_maps[env->used_map_cnt++] = map;
17744 
17745 			if (bpf_map_is_cgroup_storage(map) &&
17746 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17747 				verbose(env, "only one cgroup storage of each type is allowed\n");
17748 				fdput(f);
17749 				return -EBUSY;
17750 			}
17751 
17752 			fdput(f);
17753 next_insn:
17754 			insn++;
17755 			i++;
17756 			continue;
17757 		}
17758 
17759 		/* Basic sanity check before we invest more work here. */
17760 		if (!bpf_opcode_in_insntable(insn->code)) {
17761 			verbose(env, "unknown opcode %02x\n", insn->code);
17762 			return -EINVAL;
17763 		}
17764 	}
17765 
17766 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17767 	 * 'struct bpf_map *' into a register instead of user map_fd.
17768 	 * These pointers will be used later by verifier to validate map access.
17769 	 */
17770 	return 0;
17771 }
17772 
17773 /* drop refcnt of maps used by the rejected program */
17774 static void release_maps(struct bpf_verifier_env *env)
17775 {
17776 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17777 			     env->used_map_cnt);
17778 }
17779 
17780 /* drop refcnt of maps used by the rejected program */
17781 static void release_btfs(struct bpf_verifier_env *env)
17782 {
17783 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17784 			     env->used_btf_cnt);
17785 }
17786 
17787 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17788 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17789 {
17790 	struct bpf_insn *insn = env->prog->insnsi;
17791 	int insn_cnt = env->prog->len;
17792 	int i;
17793 
17794 	for (i = 0; i < insn_cnt; i++, insn++) {
17795 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17796 			continue;
17797 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17798 			continue;
17799 		insn->src_reg = 0;
17800 	}
17801 }
17802 
17803 /* single env->prog->insni[off] instruction was replaced with the range
17804  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17805  * [0, off) and [off, end) to new locations, so the patched range stays zero
17806  */
17807 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17808 				 struct bpf_insn_aux_data *new_data,
17809 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17810 {
17811 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17812 	struct bpf_insn *insn = new_prog->insnsi;
17813 	u32 old_seen = old_data[off].seen;
17814 	u32 prog_len;
17815 	int i;
17816 
17817 	/* aux info at OFF always needs adjustment, no matter fast path
17818 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17819 	 * original insn at old prog.
17820 	 */
17821 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17822 
17823 	if (cnt == 1)
17824 		return;
17825 	prog_len = new_prog->len;
17826 
17827 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17828 	memcpy(new_data + off + cnt - 1, old_data + off,
17829 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17830 	for (i = off; i < off + cnt - 1; i++) {
17831 		/* Expand insni[off]'s seen count to the patched range. */
17832 		new_data[i].seen = old_seen;
17833 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17834 	}
17835 	env->insn_aux_data = new_data;
17836 	vfree(old_data);
17837 }
17838 
17839 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17840 {
17841 	int i;
17842 
17843 	if (len == 1)
17844 		return;
17845 	/* NOTE: fake 'exit' subprog should be updated as well. */
17846 	for (i = 0; i <= env->subprog_cnt; i++) {
17847 		if (env->subprog_info[i].start <= off)
17848 			continue;
17849 		env->subprog_info[i].start += len - 1;
17850 	}
17851 }
17852 
17853 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17854 {
17855 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17856 	int i, sz = prog->aux->size_poke_tab;
17857 	struct bpf_jit_poke_descriptor *desc;
17858 
17859 	for (i = 0; i < sz; i++) {
17860 		desc = &tab[i];
17861 		if (desc->insn_idx <= off)
17862 			continue;
17863 		desc->insn_idx += len - 1;
17864 	}
17865 }
17866 
17867 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17868 					    const struct bpf_insn *patch, u32 len)
17869 {
17870 	struct bpf_prog *new_prog;
17871 	struct bpf_insn_aux_data *new_data = NULL;
17872 
17873 	if (len > 1) {
17874 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17875 					      sizeof(struct bpf_insn_aux_data)));
17876 		if (!new_data)
17877 			return NULL;
17878 	}
17879 
17880 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17881 	if (IS_ERR(new_prog)) {
17882 		if (PTR_ERR(new_prog) == -ERANGE)
17883 			verbose(env,
17884 				"insn %d cannot be patched due to 16-bit range\n",
17885 				env->insn_aux_data[off].orig_idx);
17886 		vfree(new_data);
17887 		return NULL;
17888 	}
17889 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17890 	adjust_subprog_starts(env, off, len);
17891 	adjust_poke_descs(new_prog, off, len);
17892 	return new_prog;
17893 }
17894 
17895 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17896 					      u32 off, u32 cnt)
17897 {
17898 	int i, j;
17899 
17900 	/* find first prog starting at or after off (first to remove) */
17901 	for (i = 0; i < env->subprog_cnt; i++)
17902 		if (env->subprog_info[i].start >= off)
17903 			break;
17904 	/* find first prog starting at or after off + cnt (first to stay) */
17905 	for (j = i; j < env->subprog_cnt; j++)
17906 		if (env->subprog_info[j].start >= off + cnt)
17907 			break;
17908 	/* if j doesn't start exactly at off + cnt, we are just removing
17909 	 * the front of previous prog
17910 	 */
17911 	if (env->subprog_info[j].start != off + cnt)
17912 		j--;
17913 
17914 	if (j > i) {
17915 		struct bpf_prog_aux *aux = env->prog->aux;
17916 		int move;
17917 
17918 		/* move fake 'exit' subprog as well */
17919 		move = env->subprog_cnt + 1 - j;
17920 
17921 		memmove(env->subprog_info + i,
17922 			env->subprog_info + j,
17923 			sizeof(*env->subprog_info) * move);
17924 		env->subprog_cnt -= j - i;
17925 
17926 		/* remove func_info */
17927 		if (aux->func_info) {
17928 			move = aux->func_info_cnt - j;
17929 
17930 			memmove(aux->func_info + i,
17931 				aux->func_info + j,
17932 				sizeof(*aux->func_info) * move);
17933 			aux->func_info_cnt -= j - i;
17934 			/* func_info->insn_off is set after all code rewrites,
17935 			 * in adjust_btf_func() - no need to adjust
17936 			 */
17937 		}
17938 	} else {
17939 		/* convert i from "first prog to remove" to "first to adjust" */
17940 		if (env->subprog_info[i].start == off)
17941 			i++;
17942 	}
17943 
17944 	/* update fake 'exit' subprog as well */
17945 	for (; i <= env->subprog_cnt; i++)
17946 		env->subprog_info[i].start -= cnt;
17947 
17948 	return 0;
17949 }
17950 
17951 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17952 				      u32 cnt)
17953 {
17954 	struct bpf_prog *prog = env->prog;
17955 	u32 i, l_off, l_cnt, nr_linfo;
17956 	struct bpf_line_info *linfo;
17957 
17958 	nr_linfo = prog->aux->nr_linfo;
17959 	if (!nr_linfo)
17960 		return 0;
17961 
17962 	linfo = prog->aux->linfo;
17963 
17964 	/* find first line info to remove, count lines to be removed */
17965 	for (i = 0; i < nr_linfo; i++)
17966 		if (linfo[i].insn_off >= off)
17967 			break;
17968 
17969 	l_off = i;
17970 	l_cnt = 0;
17971 	for (; i < nr_linfo; i++)
17972 		if (linfo[i].insn_off < off + cnt)
17973 			l_cnt++;
17974 		else
17975 			break;
17976 
17977 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17978 	 * last removed linfo.  prog is already modified, so prog->len == off
17979 	 * means no live instructions after (tail of the program was removed).
17980 	 */
17981 	if (prog->len != off && l_cnt &&
17982 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17983 		l_cnt--;
17984 		linfo[--i].insn_off = off + cnt;
17985 	}
17986 
17987 	/* remove the line info which refer to the removed instructions */
17988 	if (l_cnt) {
17989 		memmove(linfo + l_off, linfo + i,
17990 			sizeof(*linfo) * (nr_linfo - i));
17991 
17992 		prog->aux->nr_linfo -= l_cnt;
17993 		nr_linfo = prog->aux->nr_linfo;
17994 	}
17995 
17996 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17997 	for (i = l_off; i < nr_linfo; i++)
17998 		linfo[i].insn_off -= cnt;
17999 
18000 	/* fix up all subprogs (incl. 'exit') which start >= off */
18001 	for (i = 0; i <= env->subprog_cnt; i++)
18002 		if (env->subprog_info[i].linfo_idx > l_off) {
18003 			/* program may have started in the removed region but
18004 			 * may not be fully removed
18005 			 */
18006 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18007 				env->subprog_info[i].linfo_idx -= l_cnt;
18008 			else
18009 				env->subprog_info[i].linfo_idx = l_off;
18010 		}
18011 
18012 	return 0;
18013 }
18014 
18015 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18016 {
18017 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18018 	unsigned int orig_prog_len = env->prog->len;
18019 	int err;
18020 
18021 	if (bpf_prog_is_offloaded(env->prog->aux))
18022 		bpf_prog_offload_remove_insns(env, off, cnt);
18023 
18024 	err = bpf_remove_insns(env->prog, off, cnt);
18025 	if (err)
18026 		return err;
18027 
18028 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18029 	if (err)
18030 		return err;
18031 
18032 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18033 	if (err)
18034 		return err;
18035 
18036 	memmove(aux_data + off,	aux_data + off + cnt,
18037 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18038 
18039 	return 0;
18040 }
18041 
18042 /* The verifier does more data flow analysis than llvm and will not
18043  * explore branches that are dead at run time. Malicious programs can
18044  * have dead code too. Therefore replace all dead at-run-time code
18045  * with 'ja -1'.
18046  *
18047  * Just nops are not optimal, e.g. if they would sit at the end of the
18048  * program and through another bug we would manage to jump there, then
18049  * we'd execute beyond program memory otherwise. Returning exception
18050  * code also wouldn't work since we can have subprogs where the dead
18051  * code could be located.
18052  */
18053 static void sanitize_dead_code(struct bpf_verifier_env *env)
18054 {
18055 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18056 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18057 	struct bpf_insn *insn = env->prog->insnsi;
18058 	const int insn_cnt = env->prog->len;
18059 	int i;
18060 
18061 	for (i = 0; i < insn_cnt; i++) {
18062 		if (aux_data[i].seen)
18063 			continue;
18064 		memcpy(insn + i, &trap, sizeof(trap));
18065 		aux_data[i].zext_dst = false;
18066 	}
18067 }
18068 
18069 static bool insn_is_cond_jump(u8 code)
18070 {
18071 	u8 op;
18072 
18073 	op = BPF_OP(code);
18074 	if (BPF_CLASS(code) == BPF_JMP32)
18075 		return op != BPF_JA;
18076 
18077 	if (BPF_CLASS(code) != BPF_JMP)
18078 		return false;
18079 
18080 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18081 }
18082 
18083 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18084 {
18085 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18086 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18087 	struct bpf_insn *insn = env->prog->insnsi;
18088 	const int insn_cnt = env->prog->len;
18089 	int i;
18090 
18091 	for (i = 0; i < insn_cnt; i++, insn++) {
18092 		if (!insn_is_cond_jump(insn->code))
18093 			continue;
18094 
18095 		if (!aux_data[i + 1].seen)
18096 			ja.off = insn->off;
18097 		else if (!aux_data[i + 1 + insn->off].seen)
18098 			ja.off = 0;
18099 		else
18100 			continue;
18101 
18102 		if (bpf_prog_is_offloaded(env->prog->aux))
18103 			bpf_prog_offload_replace_insn(env, i, &ja);
18104 
18105 		memcpy(insn, &ja, sizeof(ja));
18106 	}
18107 }
18108 
18109 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18110 {
18111 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18112 	int insn_cnt = env->prog->len;
18113 	int i, err;
18114 
18115 	for (i = 0; i < insn_cnt; i++) {
18116 		int j;
18117 
18118 		j = 0;
18119 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18120 			j++;
18121 		if (!j)
18122 			continue;
18123 
18124 		err = verifier_remove_insns(env, i, j);
18125 		if (err)
18126 			return err;
18127 		insn_cnt = env->prog->len;
18128 	}
18129 
18130 	return 0;
18131 }
18132 
18133 static int opt_remove_nops(struct bpf_verifier_env *env)
18134 {
18135 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18136 	struct bpf_insn *insn = env->prog->insnsi;
18137 	int insn_cnt = env->prog->len;
18138 	int i, err;
18139 
18140 	for (i = 0; i < insn_cnt; i++) {
18141 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18142 			continue;
18143 
18144 		err = verifier_remove_insns(env, i, 1);
18145 		if (err)
18146 			return err;
18147 		insn_cnt--;
18148 		i--;
18149 	}
18150 
18151 	return 0;
18152 }
18153 
18154 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18155 					 const union bpf_attr *attr)
18156 {
18157 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18158 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18159 	int i, patch_len, delta = 0, len = env->prog->len;
18160 	struct bpf_insn *insns = env->prog->insnsi;
18161 	struct bpf_prog *new_prog;
18162 	bool rnd_hi32;
18163 
18164 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18165 	zext_patch[1] = BPF_ZEXT_REG(0);
18166 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18167 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18168 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18169 	for (i = 0; i < len; i++) {
18170 		int adj_idx = i + delta;
18171 		struct bpf_insn insn;
18172 		int load_reg;
18173 
18174 		insn = insns[adj_idx];
18175 		load_reg = insn_def_regno(&insn);
18176 		if (!aux[adj_idx].zext_dst) {
18177 			u8 code, class;
18178 			u32 imm_rnd;
18179 
18180 			if (!rnd_hi32)
18181 				continue;
18182 
18183 			code = insn.code;
18184 			class = BPF_CLASS(code);
18185 			if (load_reg == -1)
18186 				continue;
18187 
18188 			/* NOTE: arg "reg" (the fourth one) is only used for
18189 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18190 			 *       here.
18191 			 */
18192 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18193 				if (class == BPF_LD &&
18194 				    BPF_MODE(code) == BPF_IMM)
18195 					i++;
18196 				continue;
18197 			}
18198 
18199 			/* ctx load could be transformed into wider load. */
18200 			if (class == BPF_LDX &&
18201 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18202 				continue;
18203 
18204 			imm_rnd = get_random_u32();
18205 			rnd_hi32_patch[0] = insn;
18206 			rnd_hi32_patch[1].imm = imm_rnd;
18207 			rnd_hi32_patch[3].dst_reg = load_reg;
18208 			patch = rnd_hi32_patch;
18209 			patch_len = 4;
18210 			goto apply_patch_buffer;
18211 		}
18212 
18213 		/* Add in an zero-extend instruction if a) the JIT has requested
18214 		 * it or b) it's a CMPXCHG.
18215 		 *
18216 		 * The latter is because: BPF_CMPXCHG always loads a value into
18217 		 * R0, therefore always zero-extends. However some archs'
18218 		 * equivalent instruction only does this load when the
18219 		 * comparison is successful. This detail of CMPXCHG is
18220 		 * orthogonal to the general zero-extension behaviour of the
18221 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18222 		 */
18223 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18224 			continue;
18225 
18226 		/* Zero-extension is done by the caller. */
18227 		if (bpf_pseudo_kfunc_call(&insn))
18228 			continue;
18229 
18230 		if (WARN_ON(load_reg == -1)) {
18231 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18232 			return -EFAULT;
18233 		}
18234 
18235 		zext_patch[0] = insn;
18236 		zext_patch[1].dst_reg = load_reg;
18237 		zext_patch[1].src_reg = load_reg;
18238 		patch = zext_patch;
18239 		patch_len = 2;
18240 apply_patch_buffer:
18241 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18242 		if (!new_prog)
18243 			return -ENOMEM;
18244 		env->prog = new_prog;
18245 		insns = new_prog->insnsi;
18246 		aux = env->insn_aux_data;
18247 		delta += patch_len - 1;
18248 	}
18249 
18250 	return 0;
18251 }
18252 
18253 /* convert load instructions that access fields of a context type into a
18254  * sequence of instructions that access fields of the underlying structure:
18255  *     struct __sk_buff    -> struct sk_buff
18256  *     struct bpf_sock_ops -> struct sock
18257  */
18258 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18259 {
18260 	const struct bpf_verifier_ops *ops = env->ops;
18261 	int i, cnt, size, ctx_field_size, delta = 0;
18262 	const int insn_cnt = env->prog->len;
18263 	struct bpf_insn insn_buf[16], *insn;
18264 	u32 target_size, size_default, off;
18265 	struct bpf_prog *new_prog;
18266 	enum bpf_access_type type;
18267 	bool is_narrower_load;
18268 
18269 	if (ops->gen_prologue || env->seen_direct_write) {
18270 		if (!ops->gen_prologue) {
18271 			verbose(env, "bpf verifier is misconfigured\n");
18272 			return -EINVAL;
18273 		}
18274 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18275 					env->prog);
18276 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18277 			verbose(env, "bpf verifier is misconfigured\n");
18278 			return -EINVAL;
18279 		} else if (cnt) {
18280 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18281 			if (!new_prog)
18282 				return -ENOMEM;
18283 
18284 			env->prog = new_prog;
18285 			delta += cnt - 1;
18286 		}
18287 	}
18288 
18289 	if (bpf_prog_is_offloaded(env->prog->aux))
18290 		return 0;
18291 
18292 	insn = env->prog->insnsi + delta;
18293 
18294 	for (i = 0; i < insn_cnt; i++, insn++) {
18295 		bpf_convert_ctx_access_t convert_ctx_access;
18296 		u8 mode;
18297 
18298 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18299 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18300 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18301 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18302 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18303 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18304 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18305 			type = BPF_READ;
18306 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18307 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18308 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18309 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18310 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18311 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18312 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18313 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18314 			type = BPF_WRITE;
18315 		} else {
18316 			continue;
18317 		}
18318 
18319 		if (type == BPF_WRITE &&
18320 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18321 			struct bpf_insn patch[] = {
18322 				*insn,
18323 				BPF_ST_NOSPEC(),
18324 			};
18325 
18326 			cnt = ARRAY_SIZE(patch);
18327 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18328 			if (!new_prog)
18329 				return -ENOMEM;
18330 
18331 			delta    += cnt - 1;
18332 			env->prog = new_prog;
18333 			insn      = new_prog->insnsi + i + delta;
18334 			continue;
18335 		}
18336 
18337 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18338 		case PTR_TO_CTX:
18339 			if (!ops->convert_ctx_access)
18340 				continue;
18341 			convert_ctx_access = ops->convert_ctx_access;
18342 			break;
18343 		case PTR_TO_SOCKET:
18344 		case PTR_TO_SOCK_COMMON:
18345 			convert_ctx_access = bpf_sock_convert_ctx_access;
18346 			break;
18347 		case PTR_TO_TCP_SOCK:
18348 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18349 			break;
18350 		case PTR_TO_XDP_SOCK:
18351 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18352 			break;
18353 		case PTR_TO_BTF_ID:
18354 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18355 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18356 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18357 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18358 		 * any faults for loads into such types. BPF_WRITE is disallowed
18359 		 * for this case.
18360 		 */
18361 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18362 			if (type == BPF_READ) {
18363 				if (BPF_MODE(insn->code) == BPF_MEM)
18364 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18365 						     BPF_SIZE((insn)->code);
18366 				else
18367 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18368 						     BPF_SIZE((insn)->code);
18369 				env->prog->aux->num_exentries++;
18370 			}
18371 			continue;
18372 		default:
18373 			continue;
18374 		}
18375 
18376 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18377 		size = BPF_LDST_BYTES(insn);
18378 		mode = BPF_MODE(insn->code);
18379 
18380 		/* If the read access is a narrower load of the field,
18381 		 * convert to a 4/8-byte load, to minimum program type specific
18382 		 * convert_ctx_access changes. If conversion is successful,
18383 		 * we will apply proper mask to the result.
18384 		 */
18385 		is_narrower_load = size < ctx_field_size;
18386 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18387 		off = insn->off;
18388 		if (is_narrower_load) {
18389 			u8 size_code;
18390 
18391 			if (type == BPF_WRITE) {
18392 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18393 				return -EINVAL;
18394 			}
18395 
18396 			size_code = BPF_H;
18397 			if (ctx_field_size == 4)
18398 				size_code = BPF_W;
18399 			else if (ctx_field_size == 8)
18400 				size_code = BPF_DW;
18401 
18402 			insn->off = off & ~(size_default - 1);
18403 			insn->code = BPF_LDX | BPF_MEM | size_code;
18404 		}
18405 
18406 		target_size = 0;
18407 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18408 					 &target_size);
18409 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18410 		    (ctx_field_size && !target_size)) {
18411 			verbose(env, "bpf verifier is misconfigured\n");
18412 			return -EINVAL;
18413 		}
18414 
18415 		if (is_narrower_load && size < target_size) {
18416 			u8 shift = bpf_ctx_narrow_access_offset(
18417 				off, size, size_default) * 8;
18418 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18419 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18420 				return -EINVAL;
18421 			}
18422 			if (ctx_field_size <= 4) {
18423 				if (shift)
18424 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18425 									insn->dst_reg,
18426 									shift);
18427 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18428 								(1 << size * 8) - 1);
18429 			} else {
18430 				if (shift)
18431 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18432 									insn->dst_reg,
18433 									shift);
18434 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18435 								(1ULL << size * 8) - 1);
18436 			}
18437 		}
18438 		if (mode == BPF_MEMSX)
18439 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18440 						       insn->dst_reg, insn->dst_reg,
18441 						       size * 8, 0);
18442 
18443 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18444 		if (!new_prog)
18445 			return -ENOMEM;
18446 
18447 		delta += cnt - 1;
18448 
18449 		/* keep walking new program and skip insns we just inserted */
18450 		env->prog = new_prog;
18451 		insn      = new_prog->insnsi + i + delta;
18452 	}
18453 
18454 	return 0;
18455 }
18456 
18457 static int jit_subprogs(struct bpf_verifier_env *env)
18458 {
18459 	struct bpf_prog *prog = env->prog, **func, *tmp;
18460 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18461 	struct bpf_map *map_ptr;
18462 	struct bpf_insn *insn;
18463 	void *old_bpf_func;
18464 	int err, num_exentries;
18465 
18466 	if (env->subprog_cnt <= 1)
18467 		return 0;
18468 
18469 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18470 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18471 			continue;
18472 
18473 		/* Upon error here we cannot fall back to interpreter but
18474 		 * need a hard reject of the program. Thus -EFAULT is
18475 		 * propagated in any case.
18476 		 */
18477 		subprog = find_subprog(env, i + insn->imm + 1);
18478 		if (subprog < 0) {
18479 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18480 				  i + insn->imm + 1);
18481 			return -EFAULT;
18482 		}
18483 		/* temporarily remember subprog id inside insn instead of
18484 		 * aux_data, since next loop will split up all insns into funcs
18485 		 */
18486 		insn->off = subprog;
18487 		/* remember original imm in case JIT fails and fallback
18488 		 * to interpreter will be needed
18489 		 */
18490 		env->insn_aux_data[i].call_imm = insn->imm;
18491 		/* point imm to __bpf_call_base+1 from JITs point of view */
18492 		insn->imm = 1;
18493 		if (bpf_pseudo_func(insn))
18494 			/* jit (e.g. x86_64) may emit fewer instructions
18495 			 * if it learns a u32 imm is the same as a u64 imm.
18496 			 * Force a non zero here.
18497 			 */
18498 			insn[1].imm = 1;
18499 	}
18500 
18501 	err = bpf_prog_alloc_jited_linfo(prog);
18502 	if (err)
18503 		goto out_undo_insn;
18504 
18505 	err = -ENOMEM;
18506 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18507 	if (!func)
18508 		goto out_undo_insn;
18509 
18510 	for (i = 0; i < env->subprog_cnt; i++) {
18511 		subprog_start = subprog_end;
18512 		subprog_end = env->subprog_info[i + 1].start;
18513 
18514 		len = subprog_end - subprog_start;
18515 		/* bpf_prog_run() doesn't call subprogs directly,
18516 		 * hence main prog stats include the runtime of subprogs.
18517 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18518 		 * func[i]->stats will never be accessed and stays NULL
18519 		 */
18520 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18521 		if (!func[i])
18522 			goto out_free;
18523 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18524 		       len * sizeof(struct bpf_insn));
18525 		func[i]->type = prog->type;
18526 		func[i]->len = len;
18527 		if (bpf_prog_calc_tag(func[i]))
18528 			goto out_free;
18529 		func[i]->is_func = 1;
18530 		func[i]->aux->func_idx = i;
18531 		/* Below members will be freed only at prog->aux */
18532 		func[i]->aux->btf = prog->aux->btf;
18533 		func[i]->aux->func_info = prog->aux->func_info;
18534 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18535 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18536 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18537 
18538 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18539 			struct bpf_jit_poke_descriptor *poke;
18540 
18541 			poke = &prog->aux->poke_tab[j];
18542 			if (poke->insn_idx < subprog_end &&
18543 			    poke->insn_idx >= subprog_start)
18544 				poke->aux = func[i]->aux;
18545 		}
18546 
18547 		func[i]->aux->name[0] = 'F';
18548 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18549 		func[i]->jit_requested = 1;
18550 		func[i]->blinding_requested = prog->blinding_requested;
18551 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18552 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18553 		func[i]->aux->linfo = prog->aux->linfo;
18554 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18555 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18556 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18557 		num_exentries = 0;
18558 		insn = func[i]->insnsi;
18559 		for (j = 0; j < func[i]->len; j++, insn++) {
18560 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18561 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18562 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18563 				num_exentries++;
18564 		}
18565 		func[i]->aux->num_exentries = num_exentries;
18566 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18567 		func[i] = bpf_int_jit_compile(func[i]);
18568 		if (!func[i]->jited) {
18569 			err = -ENOTSUPP;
18570 			goto out_free;
18571 		}
18572 		cond_resched();
18573 	}
18574 
18575 	/* at this point all bpf functions were successfully JITed
18576 	 * now populate all bpf_calls with correct addresses and
18577 	 * run last pass of JIT
18578 	 */
18579 	for (i = 0; i < env->subprog_cnt; i++) {
18580 		insn = func[i]->insnsi;
18581 		for (j = 0; j < func[i]->len; j++, insn++) {
18582 			if (bpf_pseudo_func(insn)) {
18583 				subprog = insn->off;
18584 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18585 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18586 				continue;
18587 			}
18588 			if (!bpf_pseudo_call(insn))
18589 				continue;
18590 			subprog = insn->off;
18591 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18592 		}
18593 
18594 		/* we use the aux data to keep a list of the start addresses
18595 		 * of the JITed images for each function in the program
18596 		 *
18597 		 * for some architectures, such as powerpc64, the imm field
18598 		 * might not be large enough to hold the offset of the start
18599 		 * address of the callee's JITed image from __bpf_call_base
18600 		 *
18601 		 * in such cases, we can lookup the start address of a callee
18602 		 * by using its subprog id, available from the off field of
18603 		 * the call instruction, as an index for this list
18604 		 */
18605 		func[i]->aux->func = func;
18606 		func[i]->aux->func_cnt = env->subprog_cnt;
18607 	}
18608 	for (i = 0; i < env->subprog_cnt; i++) {
18609 		old_bpf_func = func[i]->bpf_func;
18610 		tmp = bpf_int_jit_compile(func[i]);
18611 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18612 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18613 			err = -ENOTSUPP;
18614 			goto out_free;
18615 		}
18616 		cond_resched();
18617 	}
18618 
18619 	/* finally lock prog and jit images for all functions and
18620 	 * populate kallsysm. Begin at the first subprogram, since
18621 	 * bpf_prog_load will add the kallsyms for the main program.
18622 	 */
18623 	for (i = 1; i < env->subprog_cnt; i++) {
18624 		bpf_prog_lock_ro(func[i]);
18625 		bpf_prog_kallsyms_add(func[i]);
18626 	}
18627 
18628 	/* Last step: make now unused interpreter insns from main
18629 	 * prog consistent for later dump requests, so they can
18630 	 * later look the same as if they were interpreted only.
18631 	 */
18632 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18633 		if (bpf_pseudo_func(insn)) {
18634 			insn[0].imm = env->insn_aux_data[i].call_imm;
18635 			insn[1].imm = insn->off;
18636 			insn->off = 0;
18637 			continue;
18638 		}
18639 		if (!bpf_pseudo_call(insn))
18640 			continue;
18641 		insn->off = env->insn_aux_data[i].call_imm;
18642 		subprog = find_subprog(env, i + insn->off + 1);
18643 		insn->imm = subprog;
18644 	}
18645 
18646 	prog->jited = 1;
18647 	prog->bpf_func = func[0]->bpf_func;
18648 	prog->jited_len = func[0]->jited_len;
18649 	prog->aux->extable = func[0]->aux->extable;
18650 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18651 	prog->aux->func = func;
18652 	prog->aux->func_cnt = env->subprog_cnt;
18653 	bpf_prog_jit_attempt_done(prog);
18654 	return 0;
18655 out_free:
18656 	/* We failed JIT'ing, so at this point we need to unregister poke
18657 	 * descriptors from subprogs, so that kernel is not attempting to
18658 	 * patch it anymore as we're freeing the subprog JIT memory.
18659 	 */
18660 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18661 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18662 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18663 	}
18664 	/* At this point we're guaranteed that poke descriptors are not
18665 	 * live anymore. We can just unlink its descriptor table as it's
18666 	 * released with the main prog.
18667 	 */
18668 	for (i = 0; i < env->subprog_cnt; i++) {
18669 		if (!func[i])
18670 			continue;
18671 		func[i]->aux->poke_tab = NULL;
18672 		bpf_jit_free(func[i]);
18673 	}
18674 	kfree(func);
18675 out_undo_insn:
18676 	/* cleanup main prog to be interpreted */
18677 	prog->jit_requested = 0;
18678 	prog->blinding_requested = 0;
18679 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18680 		if (!bpf_pseudo_call(insn))
18681 			continue;
18682 		insn->off = 0;
18683 		insn->imm = env->insn_aux_data[i].call_imm;
18684 	}
18685 	bpf_prog_jit_attempt_done(prog);
18686 	return err;
18687 }
18688 
18689 static int fixup_call_args(struct bpf_verifier_env *env)
18690 {
18691 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18692 	struct bpf_prog *prog = env->prog;
18693 	struct bpf_insn *insn = prog->insnsi;
18694 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18695 	int i, depth;
18696 #endif
18697 	int err = 0;
18698 
18699 	if (env->prog->jit_requested &&
18700 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18701 		err = jit_subprogs(env);
18702 		if (err == 0)
18703 			return 0;
18704 		if (err == -EFAULT)
18705 			return err;
18706 	}
18707 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18708 	if (has_kfunc_call) {
18709 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18710 		return -EINVAL;
18711 	}
18712 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18713 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18714 		 * have to be rejected, since interpreter doesn't support them yet.
18715 		 */
18716 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18717 		return -EINVAL;
18718 	}
18719 	for (i = 0; i < prog->len; i++, insn++) {
18720 		if (bpf_pseudo_func(insn)) {
18721 			/* When JIT fails the progs with callback calls
18722 			 * have to be rejected, since interpreter doesn't support them yet.
18723 			 */
18724 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18725 			return -EINVAL;
18726 		}
18727 
18728 		if (!bpf_pseudo_call(insn))
18729 			continue;
18730 		depth = get_callee_stack_depth(env, insn, i);
18731 		if (depth < 0)
18732 			return depth;
18733 		bpf_patch_call_args(insn, depth);
18734 	}
18735 	err = 0;
18736 #endif
18737 	return err;
18738 }
18739 
18740 /* replace a generic kfunc with a specialized version if necessary */
18741 static void specialize_kfunc(struct bpf_verifier_env *env,
18742 			     u32 func_id, u16 offset, unsigned long *addr)
18743 {
18744 	struct bpf_prog *prog = env->prog;
18745 	bool seen_direct_write;
18746 	void *xdp_kfunc;
18747 	bool is_rdonly;
18748 
18749 	if (bpf_dev_bound_kfunc_id(func_id)) {
18750 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18751 		if (xdp_kfunc) {
18752 			*addr = (unsigned long)xdp_kfunc;
18753 			return;
18754 		}
18755 		/* fallback to default kfunc when not supported by netdev */
18756 	}
18757 
18758 	if (offset)
18759 		return;
18760 
18761 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18762 		seen_direct_write = env->seen_direct_write;
18763 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18764 
18765 		if (is_rdonly)
18766 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18767 
18768 		/* restore env->seen_direct_write to its original value, since
18769 		 * may_access_direct_pkt_data mutates it
18770 		 */
18771 		env->seen_direct_write = seen_direct_write;
18772 	}
18773 }
18774 
18775 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18776 					    u16 struct_meta_reg,
18777 					    u16 node_offset_reg,
18778 					    struct bpf_insn *insn,
18779 					    struct bpf_insn *insn_buf,
18780 					    int *cnt)
18781 {
18782 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18783 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18784 
18785 	insn_buf[0] = addr[0];
18786 	insn_buf[1] = addr[1];
18787 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18788 	insn_buf[3] = *insn;
18789 	*cnt = 4;
18790 }
18791 
18792 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18793 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18794 {
18795 	const struct bpf_kfunc_desc *desc;
18796 
18797 	if (!insn->imm) {
18798 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18799 		return -EINVAL;
18800 	}
18801 
18802 	*cnt = 0;
18803 
18804 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18805 	 * __bpf_call_base, unless the JIT needs to call functions that are
18806 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18807 	 */
18808 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18809 	if (!desc) {
18810 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18811 			insn->imm);
18812 		return -EFAULT;
18813 	}
18814 
18815 	if (!bpf_jit_supports_far_kfunc_call())
18816 		insn->imm = BPF_CALL_IMM(desc->addr);
18817 	if (insn->off)
18818 		return 0;
18819 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18820 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18821 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18822 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18823 
18824 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18825 		insn_buf[1] = addr[0];
18826 		insn_buf[2] = addr[1];
18827 		insn_buf[3] = *insn;
18828 		*cnt = 4;
18829 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18830 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18831 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18832 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18833 
18834 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18835 		    !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 		insn_buf[0] = addr[0];
18842 		insn_buf[1] = addr[1];
18843 		insn_buf[2] = *insn;
18844 		*cnt = 3;
18845 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18846 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18847 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18848 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18849 		int struct_meta_reg = BPF_REG_3;
18850 		int node_offset_reg = BPF_REG_4;
18851 
18852 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18853 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18854 			struct_meta_reg = BPF_REG_4;
18855 			node_offset_reg = BPF_REG_5;
18856 		}
18857 
18858 		if (!kptr_struct_meta) {
18859 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18860 				insn_idx);
18861 			return -EFAULT;
18862 		}
18863 
18864 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18865 						node_offset_reg, insn, insn_buf, cnt);
18866 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18867 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18868 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18869 		*cnt = 1;
18870 	}
18871 	return 0;
18872 }
18873 
18874 /* Do various post-verification rewrites in a single program pass.
18875  * These rewrites simplify JIT and interpreter implementations.
18876  */
18877 static int do_misc_fixups(struct bpf_verifier_env *env)
18878 {
18879 	struct bpf_prog *prog = env->prog;
18880 	enum bpf_attach_type eatype = prog->expected_attach_type;
18881 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18882 	struct bpf_insn *insn = prog->insnsi;
18883 	const struct bpf_func_proto *fn;
18884 	const int insn_cnt = prog->len;
18885 	const struct bpf_map_ops *ops;
18886 	struct bpf_insn_aux_data *aux;
18887 	struct bpf_insn insn_buf[16];
18888 	struct bpf_prog *new_prog;
18889 	struct bpf_map *map_ptr;
18890 	int i, ret, cnt, delta = 0;
18891 
18892 	for (i = 0; i < insn_cnt; i++, insn++) {
18893 		/* Make divide-by-zero exceptions impossible. */
18894 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18895 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18896 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18897 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18898 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18899 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18900 			struct bpf_insn *patchlet;
18901 			struct bpf_insn chk_and_div[] = {
18902 				/* [R,W]x div 0 -> 0 */
18903 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18904 					     BPF_JNE | BPF_K, insn->src_reg,
18905 					     0, 2, 0),
18906 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18907 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18908 				*insn,
18909 			};
18910 			struct bpf_insn chk_and_mod[] = {
18911 				/* [R,W]x mod 0 -> [R,W]x */
18912 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18913 					     BPF_JEQ | BPF_K, insn->src_reg,
18914 					     0, 1 + (is64 ? 0 : 1), 0),
18915 				*insn,
18916 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18917 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18918 			};
18919 
18920 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18921 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18922 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18923 
18924 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18925 			if (!new_prog)
18926 				return -ENOMEM;
18927 
18928 			delta    += cnt - 1;
18929 			env->prog = prog = new_prog;
18930 			insn      = new_prog->insnsi + i + delta;
18931 			continue;
18932 		}
18933 
18934 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18935 		if (BPF_CLASS(insn->code) == BPF_LD &&
18936 		    (BPF_MODE(insn->code) == BPF_ABS ||
18937 		     BPF_MODE(insn->code) == BPF_IND)) {
18938 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18939 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18940 				verbose(env, "bpf verifier is misconfigured\n");
18941 				return -EINVAL;
18942 			}
18943 
18944 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18945 			if (!new_prog)
18946 				return -ENOMEM;
18947 
18948 			delta    += cnt - 1;
18949 			env->prog = prog = new_prog;
18950 			insn      = new_prog->insnsi + i + delta;
18951 			continue;
18952 		}
18953 
18954 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18955 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18956 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18957 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18958 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18959 			struct bpf_insn *patch = &insn_buf[0];
18960 			bool issrc, isneg, isimm;
18961 			u32 off_reg;
18962 
18963 			aux = &env->insn_aux_data[i + delta];
18964 			if (!aux->alu_state ||
18965 			    aux->alu_state == BPF_ALU_NON_POINTER)
18966 				continue;
18967 
18968 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18969 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18970 				BPF_ALU_SANITIZE_SRC;
18971 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18972 
18973 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18974 			if (isimm) {
18975 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18976 			} else {
18977 				if (isneg)
18978 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18979 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18980 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18981 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18982 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18983 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18984 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18985 			}
18986 			if (!issrc)
18987 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18988 			insn->src_reg = BPF_REG_AX;
18989 			if (isneg)
18990 				insn->code = insn->code == code_add ?
18991 					     code_sub : code_add;
18992 			*patch++ = *insn;
18993 			if (issrc && isneg && !isimm)
18994 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18995 			cnt = patch - insn_buf;
18996 
18997 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18998 			if (!new_prog)
18999 				return -ENOMEM;
19000 
19001 			delta    += cnt - 1;
19002 			env->prog = prog = new_prog;
19003 			insn      = new_prog->insnsi + i + delta;
19004 			continue;
19005 		}
19006 
19007 		if (insn->code != (BPF_JMP | BPF_CALL))
19008 			continue;
19009 		if (insn->src_reg == BPF_PSEUDO_CALL)
19010 			continue;
19011 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19012 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19013 			if (ret)
19014 				return ret;
19015 			if (cnt == 0)
19016 				continue;
19017 
19018 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19019 			if (!new_prog)
19020 				return -ENOMEM;
19021 
19022 			delta	 += cnt - 1;
19023 			env->prog = prog = new_prog;
19024 			insn	  = new_prog->insnsi + i + delta;
19025 			continue;
19026 		}
19027 
19028 		if (insn->imm == BPF_FUNC_get_route_realm)
19029 			prog->dst_needed = 1;
19030 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19031 			bpf_user_rnd_init_once();
19032 		if (insn->imm == BPF_FUNC_override_return)
19033 			prog->kprobe_override = 1;
19034 		if (insn->imm == BPF_FUNC_tail_call) {
19035 			/* If we tail call into other programs, we
19036 			 * cannot make any assumptions since they can
19037 			 * be replaced dynamically during runtime in
19038 			 * the program array.
19039 			 */
19040 			prog->cb_access = 1;
19041 			if (!allow_tail_call_in_subprogs(env))
19042 				prog->aux->stack_depth = MAX_BPF_STACK;
19043 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19044 
19045 			/* mark bpf_tail_call as different opcode to avoid
19046 			 * conditional branch in the interpreter for every normal
19047 			 * call and to prevent accidental JITing by JIT compiler
19048 			 * that doesn't support bpf_tail_call yet
19049 			 */
19050 			insn->imm = 0;
19051 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19052 
19053 			aux = &env->insn_aux_data[i + delta];
19054 			if (env->bpf_capable && !prog->blinding_requested &&
19055 			    prog->jit_requested &&
19056 			    !bpf_map_key_poisoned(aux) &&
19057 			    !bpf_map_ptr_poisoned(aux) &&
19058 			    !bpf_map_ptr_unpriv(aux)) {
19059 				struct bpf_jit_poke_descriptor desc = {
19060 					.reason = BPF_POKE_REASON_TAIL_CALL,
19061 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19062 					.tail_call.key = bpf_map_key_immediate(aux),
19063 					.insn_idx = i + delta,
19064 				};
19065 
19066 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19067 				if (ret < 0) {
19068 					verbose(env, "adding tail call poke descriptor failed\n");
19069 					return ret;
19070 				}
19071 
19072 				insn->imm = ret + 1;
19073 				continue;
19074 			}
19075 
19076 			if (!bpf_map_ptr_unpriv(aux))
19077 				continue;
19078 
19079 			/* instead of changing every JIT dealing with tail_call
19080 			 * emit two extra insns:
19081 			 * if (index >= max_entries) goto out;
19082 			 * index &= array->index_mask;
19083 			 * to avoid out-of-bounds cpu speculation
19084 			 */
19085 			if (bpf_map_ptr_poisoned(aux)) {
19086 				verbose(env, "tail_call abusing map_ptr\n");
19087 				return -EINVAL;
19088 			}
19089 
19090 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19091 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19092 						  map_ptr->max_entries, 2);
19093 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19094 						    container_of(map_ptr,
19095 								 struct bpf_array,
19096 								 map)->index_mask);
19097 			insn_buf[2] = *insn;
19098 			cnt = 3;
19099 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19100 			if (!new_prog)
19101 				return -ENOMEM;
19102 
19103 			delta    += cnt - 1;
19104 			env->prog = prog = new_prog;
19105 			insn      = new_prog->insnsi + i + delta;
19106 			continue;
19107 		}
19108 
19109 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19110 			/* The verifier will process callback_fn as many times as necessary
19111 			 * with different maps and the register states prepared by
19112 			 * set_timer_callback_state will be accurate.
19113 			 *
19114 			 * The following use case is valid:
19115 			 *   map1 is shared by prog1, prog2, prog3.
19116 			 *   prog1 calls bpf_timer_init for some map1 elements
19117 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19118 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19119 			 *   prog3 calls bpf_timer_start for some map1 elements.
19120 			 *     Those that were not both bpf_timer_init-ed and
19121 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19122 			 */
19123 			struct bpf_insn ld_addrs[2] = {
19124 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19125 			};
19126 
19127 			insn_buf[0] = ld_addrs[0];
19128 			insn_buf[1] = ld_addrs[1];
19129 			insn_buf[2] = *insn;
19130 			cnt = 3;
19131 
19132 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19133 			if (!new_prog)
19134 				return -ENOMEM;
19135 
19136 			delta    += cnt - 1;
19137 			env->prog = prog = new_prog;
19138 			insn      = new_prog->insnsi + i + delta;
19139 			goto patch_call_imm;
19140 		}
19141 
19142 		if (is_storage_get_function(insn->imm)) {
19143 			if (!env->prog->aux->sleepable ||
19144 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19145 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19146 			else
19147 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19148 			insn_buf[1] = *insn;
19149 			cnt = 2;
19150 
19151 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19152 			if (!new_prog)
19153 				return -ENOMEM;
19154 
19155 			delta += cnt - 1;
19156 			env->prog = prog = new_prog;
19157 			insn = new_prog->insnsi + i + delta;
19158 			goto patch_call_imm;
19159 		}
19160 
19161 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19162 		 * and other inlining handlers are currently limited to 64 bit
19163 		 * only.
19164 		 */
19165 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19166 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19167 		     insn->imm == BPF_FUNC_map_update_elem ||
19168 		     insn->imm == BPF_FUNC_map_delete_elem ||
19169 		     insn->imm == BPF_FUNC_map_push_elem   ||
19170 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19171 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19172 		     insn->imm == BPF_FUNC_redirect_map    ||
19173 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19174 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19175 			aux = &env->insn_aux_data[i + delta];
19176 			if (bpf_map_ptr_poisoned(aux))
19177 				goto patch_call_imm;
19178 
19179 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19180 			ops = map_ptr->ops;
19181 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19182 			    ops->map_gen_lookup) {
19183 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19184 				if (cnt == -EOPNOTSUPP)
19185 					goto patch_map_ops_generic;
19186 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19187 					verbose(env, "bpf verifier is misconfigured\n");
19188 					return -EINVAL;
19189 				}
19190 
19191 				new_prog = bpf_patch_insn_data(env, i + delta,
19192 							       insn_buf, cnt);
19193 				if (!new_prog)
19194 					return -ENOMEM;
19195 
19196 				delta    += cnt - 1;
19197 				env->prog = prog = new_prog;
19198 				insn      = new_prog->insnsi + i + delta;
19199 				continue;
19200 			}
19201 
19202 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19203 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19204 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19205 				     (long (*)(struct bpf_map *map, void *key))NULL));
19206 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19207 				     (long (*)(struct bpf_map *map, void *key, void *value,
19208 					      u64 flags))NULL));
19209 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19210 				     (long (*)(struct bpf_map *map, void *value,
19211 					      u64 flags))NULL));
19212 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19213 				     (long (*)(struct bpf_map *map, void *value))NULL));
19214 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19215 				     (long (*)(struct bpf_map *map, void *value))NULL));
19216 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19217 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19218 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19219 				     (long (*)(struct bpf_map *map,
19220 					      bpf_callback_t callback_fn,
19221 					      void *callback_ctx,
19222 					      u64 flags))NULL));
19223 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19224 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19225 
19226 patch_map_ops_generic:
19227 			switch (insn->imm) {
19228 			case BPF_FUNC_map_lookup_elem:
19229 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19230 				continue;
19231 			case BPF_FUNC_map_update_elem:
19232 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19233 				continue;
19234 			case BPF_FUNC_map_delete_elem:
19235 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19236 				continue;
19237 			case BPF_FUNC_map_push_elem:
19238 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19239 				continue;
19240 			case BPF_FUNC_map_pop_elem:
19241 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19242 				continue;
19243 			case BPF_FUNC_map_peek_elem:
19244 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19245 				continue;
19246 			case BPF_FUNC_redirect_map:
19247 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19248 				continue;
19249 			case BPF_FUNC_for_each_map_elem:
19250 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19251 				continue;
19252 			case BPF_FUNC_map_lookup_percpu_elem:
19253 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19254 				continue;
19255 			}
19256 
19257 			goto patch_call_imm;
19258 		}
19259 
19260 		/* Implement bpf_jiffies64 inline. */
19261 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19262 		    insn->imm == BPF_FUNC_jiffies64) {
19263 			struct bpf_insn ld_jiffies_addr[2] = {
19264 				BPF_LD_IMM64(BPF_REG_0,
19265 					     (unsigned long)&jiffies),
19266 			};
19267 
19268 			insn_buf[0] = ld_jiffies_addr[0];
19269 			insn_buf[1] = ld_jiffies_addr[1];
19270 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19271 						  BPF_REG_0, 0);
19272 			cnt = 3;
19273 
19274 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19275 						       cnt);
19276 			if (!new_prog)
19277 				return -ENOMEM;
19278 
19279 			delta    += cnt - 1;
19280 			env->prog = prog = new_prog;
19281 			insn      = new_prog->insnsi + i + delta;
19282 			continue;
19283 		}
19284 
19285 		/* Implement bpf_get_func_arg inline. */
19286 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19287 		    insn->imm == BPF_FUNC_get_func_arg) {
19288 			/* Load nr_args from ctx - 8 */
19289 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19290 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19291 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19292 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19293 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19294 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19295 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19296 			insn_buf[7] = BPF_JMP_A(1);
19297 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19298 			cnt = 9;
19299 
19300 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19301 			if (!new_prog)
19302 				return -ENOMEM;
19303 
19304 			delta    += cnt - 1;
19305 			env->prog = prog = new_prog;
19306 			insn      = new_prog->insnsi + i + delta;
19307 			continue;
19308 		}
19309 
19310 		/* Implement bpf_get_func_ret inline. */
19311 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19312 		    insn->imm == BPF_FUNC_get_func_ret) {
19313 			if (eatype == BPF_TRACE_FEXIT ||
19314 			    eatype == BPF_MODIFY_RETURN) {
19315 				/* Load nr_args from ctx - 8 */
19316 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19317 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19318 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19319 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19320 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19321 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19322 				cnt = 6;
19323 			} else {
19324 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19325 				cnt = 1;
19326 			}
19327 
19328 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19329 			if (!new_prog)
19330 				return -ENOMEM;
19331 
19332 			delta    += cnt - 1;
19333 			env->prog = prog = new_prog;
19334 			insn      = new_prog->insnsi + i + delta;
19335 			continue;
19336 		}
19337 
19338 		/* Implement get_func_arg_cnt inline. */
19339 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19340 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19341 			/* Load nr_args from ctx - 8 */
19342 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19343 
19344 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19345 			if (!new_prog)
19346 				return -ENOMEM;
19347 
19348 			env->prog = prog = new_prog;
19349 			insn      = new_prog->insnsi + i + delta;
19350 			continue;
19351 		}
19352 
19353 		/* Implement bpf_get_func_ip inline. */
19354 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19355 		    insn->imm == BPF_FUNC_get_func_ip) {
19356 			/* Load IP address from ctx - 16 */
19357 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19358 
19359 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19360 			if (!new_prog)
19361 				return -ENOMEM;
19362 
19363 			env->prog = prog = new_prog;
19364 			insn      = new_prog->insnsi + i + delta;
19365 			continue;
19366 		}
19367 
19368 patch_call_imm:
19369 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19370 		/* all functions that have prototype and verifier allowed
19371 		 * programs to call them, must be real in-kernel functions
19372 		 */
19373 		if (!fn->func) {
19374 			verbose(env,
19375 				"kernel subsystem misconfigured func %s#%d\n",
19376 				func_id_name(insn->imm), insn->imm);
19377 			return -EFAULT;
19378 		}
19379 		insn->imm = fn->func - __bpf_call_base;
19380 	}
19381 
19382 	/* Since poke tab is now finalized, publish aux to tracker. */
19383 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19384 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19385 		if (!map_ptr->ops->map_poke_track ||
19386 		    !map_ptr->ops->map_poke_untrack ||
19387 		    !map_ptr->ops->map_poke_run) {
19388 			verbose(env, "bpf verifier is misconfigured\n");
19389 			return -EINVAL;
19390 		}
19391 
19392 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19393 		if (ret < 0) {
19394 			verbose(env, "tracking tail call prog failed\n");
19395 			return ret;
19396 		}
19397 	}
19398 
19399 	sort_kfunc_descs_by_imm_off(env->prog);
19400 
19401 	return 0;
19402 }
19403 
19404 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19405 					int position,
19406 					s32 stack_base,
19407 					u32 callback_subprogno,
19408 					u32 *cnt)
19409 {
19410 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19411 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19412 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19413 	int reg_loop_max = BPF_REG_6;
19414 	int reg_loop_cnt = BPF_REG_7;
19415 	int reg_loop_ctx = BPF_REG_8;
19416 
19417 	struct bpf_prog *new_prog;
19418 	u32 callback_start;
19419 	u32 call_insn_offset;
19420 	s32 callback_offset;
19421 
19422 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19423 	 * be careful to modify this code in sync.
19424 	 */
19425 	struct bpf_insn insn_buf[] = {
19426 		/* Return error and jump to the end of the patch if
19427 		 * expected number of iterations is too big.
19428 		 */
19429 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19430 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19431 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19432 		/* spill R6, R7, R8 to use these as loop vars */
19433 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19434 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19435 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19436 		/* initialize loop vars */
19437 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19438 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19439 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19440 		/* loop header,
19441 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19442 		 */
19443 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19444 		/* callback call,
19445 		 * correct callback offset would be set after patching
19446 		 */
19447 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19448 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19449 		BPF_CALL_REL(0),
19450 		/* increment loop counter */
19451 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19452 		/* jump to loop header if callback returned 0 */
19453 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19454 		/* return value of bpf_loop,
19455 		 * set R0 to the number of iterations
19456 		 */
19457 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19458 		/* restore original values of R6, R7, R8 */
19459 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19460 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19461 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19462 	};
19463 
19464 	*cnt = ARRAY_SIZE(insn_buf);
19465 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19466 	if (!new_prog)
19467 		return new_prog;
19468 
19469 	/* callback start is known only after patching */
19470 	callback_start = env->subprog_info[callback_subprogno].start;
19471 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19472 	call_insn_offset = position + 12;
19473 	callback_offset = callback_start - call_insn_offset - 1;
19474 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19475 
19476 	return new_prog;
19477 }
19478 
19479 static bool is_bpf_loop_call(struct bpf_insn *insn)
19480 {
19481 	return insn->code == (BPF_JMP | BPF_CALL) &&
19482 		insn->src_reg == 0 &&
19483 		insn->imm == BPF_FUNC_loop;
19484 }
19485 
19486 /* For all sub-programs in the program (including main) check
19487  * insn_aux_data to see if there are bpf_loop calls that require
19488  * inlining. If such calls are found the calls are replaced with a
19489  * sequence of instructions produced by `inline_bpf_loop` function and
19490  * subprog stack_depth is increased by the size of 3 registers.
19491  * This stack space is used to spill values of the R6, R7, R8.  These
19492  * registers are used to store the loop bound, counter and context
19493  * variables.
19494  */
19495 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19496 {
19497 	struct bpf_subprog_info *subprogs = env->subprog_info;
19498 	int i, cur_subprog = 0, cnt, delta = 0;
19499 	struct bpf_insn *insn = env->prog->insnsi;
19500 	int insn_cnt = env->prog->len;
19501 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19502 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19503 	u16 stack_depth_extra = 0;
19504 
19505 	for (i = 0; i < insn_cnt; i++, insn++) {
19506 		struct bpf_loop_inline_state *inline_state =
19507 			&env->insn_aux_data[i + delta].loop_inline_state;
19508 
19509 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19510 			struct bpf_prog *new_prog;
19511 
19512 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19513 			new_prog = inline_bpf_loop(env,
19514 						   i + delta,
19515 						   -(stack_depth + stack_depth_extra),
19516 						   inline_state->callback_subprogno,
19517 						   &cnt);
19518 			if (!new_prog)
19519 				return -ENOMEM;
19520 
19521 			delta     += cnt - 1;
19522 			env->prog  = new_prog;
19523 			insn       = new_prog->insnsi + i + delta;
19524 		}
19525 
19526 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19527 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19528 			cur_subprog++;
19529 			stack_depth = subprogs[cur_subprog].stack_depth;
19530 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19531 			stack_depth_extra = 0;
19532 		}
19533 	}
19534 
19535 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19536 
19537 	return 0;
19538 }
19539 
19540 static void free_states(struct bpf_verifier_env *env)
19541 {
19542 	struct bpf_verifier_state_list *sl, *sln;
19543 	int i;
19544 
19545 	sl = env->free_list;
19546 	while (sl) {
19547 		sln = sl->next;
19548 		free_verifier_state(&sl->state, false);
19549 		kfree(sl);
19550 		sl = sln;
19551 	}
19552 	env->free_list = NULL;
19553 
19554 	if (!env->explored_states)
19555 		return;
19556 
19557 	for (i = 0; i < state_htab_size(env); i++) {
19558 		sl = env->explored_states[i];
19559 
19560 		while (sl) {
19561 			sln = sl->next;
19562 			free_verifier_state(&sl->state, false);
19563 			kfree(sl);
19564 			sl = sln;
19565 		}
19566 		env->explored_states[i] = NULL;
19567 	}
19568 }
19569 
19570 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19571 {
19572 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19573 	struct bpf_verifier_state *state;
19574 	struct bpf_reg_state *regs;
19575 	int ret, i;
19576 
19577 	env->prev_linfo = NULL;
19578 	env->pass_cnt++;
19579 
19580 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19581 	if (!state)
19582 		return -ENOMEM;
19583 	state->curframe = 0;
19584 	state->speculative = false;
19585 	state->branches = 1;
19586 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19587 	if (!state->frame[0]) {
19588 		kfree(state);
19589 		return -ENOMEM;
19590 	}
19591 	env->cur_state = state;
19592 	init_func_state(env, state->frame[0],
19593 			BPF_MAIN_FUNC /* callsite */,
19594 			0 /* frameno */,
19595 			subprog);
19596 	state->first_insn_idx = env->subprog_info[subprog].start;
19597 	state->last_insn_idx = -1;
19598 
19599 	regs = state->frame[state->curframe]->regs;
19600 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19601 		ret = btf_prepare_func_args(env, subprog, regs);
19602 		if (ret)
19603 			goto out;
19604 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19605 			if (regs[i].type == PTR_TO_CTX)
19606 				mark_reg_known_zero(env, regs, i);
19607 			else if (regs[i].type == SCALAR_VALUE)
19608 				mark_reg_unknown(env, regs, i);
19609 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19610 				const u32 mem_size = regs[i].mem_size;
19611 
19612 				mark_reg_known_zero(env, regs, i);
19613 				regs[i].mem_size = mem_size;
19614 				regs[i].id = ++env->id_gen;
19615 			}
19616 		}
19617 	} else {
19618 		/* 1st arg to a function */
19619 		regs[BPF_REG_1].type = PTR_TO_CTX;
19620 		mark_reg_known_zero(env, regs, BPF_REG_1);
19621 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19622 		if (ret == -EFAULT)
19623 			/* unlikely verifier bug. abort.
19624 			 * ret == 0 and ret < 0 are sadly acceptable for
19625 			 * main() function due to backward compatibility.
19626 			 * Like socket filter program may be written as:
19627 			 * int bpf_prog(struct pt_regs *ctx)
19628 			 * and never dereference that ctx in the program.
19629 			 * 'struct pt_regs' is a type mismatch for socket
19630 			 * filter that should be using 'struct __sk_buff'.
19631 			 */
19632 			goto out;
19633 	}
19634 
19635 	ret = do_check(env);
19636 out:
19637 	/* check for NULL is necessary, since cur_state can be freed inside
19638 	 * do_check() under memory pressure.
19639 	 */
19640 	if (env->cur_state) {
19641 		free_verifier_state(env->cur_state, true);
19642 		env->cur_state = NULL;
19643 	}
19644 	while (!pop_stack(env, NULL, NULL, false));
19645 	if (!ret && pop_log)
19646 		bpf_vlog_reset(&env->log, 0);
19647 	free_states(env);
19648 	return ret;
19649 }
19650 
19651 /* Verify all global functions in a BPF program one by one based on their BTF.
19652  * All global functions must pass verification. Otherwise the whole program is rejected.
19653  * Consider:
19654  * int bar(int);
19655  * int foo(int f)
19656  * {
19657  *    return bar(f);
19658  * }
19659  * int bar(int b)
19660  * {
19661  *    ...
19662  * }
19663  * foo() will be verified first for R1=any_scalar_value. During verification it
19664  * will be assumed that bar() already verified successfully and call to bar()
19665  * from foo() will be checked for type match only. Later bar() will be verified
19666  * independently to check that it's safe for R1=any_scalar_value.
19667  */
19668 static int do_check_subprogs(struct bpf_verifier_env *env)
19669 {
19670 	struct bpf_prog_aux *aux = env->prog->aux;
19671 	int i, ret;
19672 
19673 	if (!aux->func_info)
19674 		return 0;
19675 
19676 	for (i = 1; i < env->subprog_cnt; i++) {
19677 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19678 			continue;
19679 		env->insn_idx = env->subprog_info[i].start;
19680 		WARN_ON_ONCE(env->insn_idx == 0);
19681 		ret = do_check_common(env, i);
19682 		if (ret) {
19683 			return ret;
19684 		} else if (env->log.level & BPF_LOG_LEVEL) {
19685 			verbose(env,
19686 				"Func#%d is safe for any args that match its prototype\n",
19687 				i);
19688 		}
19689 	}
19690 	return 0;
19691 }
19692 
19693 static int do_check_main(struct bpf_verifier_env *env)
19694 {
19695 	int ret;
19696 
19697 	env->insn_idx = 0;
19698 	ret = do_check_common(env, 0);
19699 	if (!ret)
19700 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19701 	return ret;
19702 }
19703 
19704 
19705 static void print_verification_stats(struct bpf_verifier_env *env)
19706 {
19707 	int i;
19708 
19709 	if (env->log.level & BPF_LOG_STATS) {
19710 		verbose(env, "verification time %lld usec\n",
19711 			div_u64(env->verification_time, 1000));
19712 		verbose(env, "stack depth ");
19713 		for (i = 0; i < env->subprog_cnt; i++) {
19714 			u32 depth = env->subprog_info[i].stack_depth;
19715 
19716 			verbose(env, "%d", depth);
19717 			if (i + 1 < env->subprog_cnt)
19718 				verbose(env, "+");
19719 		}
19720 		verbose(env, "\n");
19721 	}
19722 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19723 		"total_states %d peak_states %d mark_read %d\n",
19724 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19725 		env->max_states_per_insn, env->total_states,
19726 		env->peak_states, env->longest_mark_read_walk);
19727 }
19728 
19729 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19730 {
19731 	const struct btf_type *t, *func_proto;
19732 	const struct bpf_struct_ops *st_ops;
19733 	const struct btf_member *member;
19734 	struct bpf_prog *prog = env->prog;
19735 	u32 btf_id, member_idx;
19736 	const char *mname;
19737 
19738 	if (!prog->gpl_compatible) {
19739 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19740 		return -EINVAL;
19741 	}
19742 
19743 	btf_id = prog->aux->attach_btf_id;
19744 	st_ops = bpf_struct_ops_find(btf_id);
19745 	if (!st_ops) {
19746 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19747 			btf_id);
19748 		return -ENOTSUPP;
19749 	}
19750 
19751 	t = st_ops->type;
19752 	member_idx = prog->expected_attach_type;
19753 	if (member_idx >= btf_type_vlen(t)) {
19754 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19755 			member_idx, st_ops->name);
19756 		return -EINVAL;
19757 	}
19758 
19759 	member = &btf_type_member(t)[member_idx];
19760 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19761 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19762 					       NULL);
19763 	if (!func_proto) {
19764 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19765 			mname, member_idx, st_ops->name);
19766 		return -EINVAL;
19767 	}
19768 
19769 	if (st_ops->check_member) {
19770 		int err = st_ops->check_member(t, member, prog);
19771 
19772 		if (err) {
19773 			verbose(env, "attach to unsupported member %s of struct %s\n",
19774 				mname, st_ops->name);
19775 			return err;
19776 		}
19777 	}
19778 
19779 	prog->aux->attach_func_proto = func_proto;
19780 	prog->aux->attach_func_name = mname;
19781 	env->ops = st_ops->verifier_ops;
19782 
19783 	return 0;
19784 }
19785 #define SECURITY_PREFIX "security_"
19786 
19787 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19788 {
19789 	if (within_error_injection_list(addr) ||
19790 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19791 		return 0;
19792 
19793 	return -EINVAL;
19794 }
19795 
19796 /* list of non-sleepable functions that are otherwise on
19797  * ALLOW_ERROR_INJECTION list
19798  */
19799 BTF_SET_START(btf_non_sleepable_error_inject)
19800 /* Three functions below can be called from sleepable and non-sleepable context.
19801  * Assume non-sleepable from bpf safety point of view.
19802  */
19803 BTF_ID(func, __filemap_add_folio)
19804 BTF_ID(func, should_fail_alloc_page)
19805 BTF_ID(func, should_failslab)
19806 BTF_SET_END(btf_non_sleepable_error_inject)
19807 
19808 static int check_non_sleepable_error_inject(u32 btf_id)
19809 {
19810 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19811 }
19812 
19813 int bpf_check_attach_target(struct bpf_verifier_log *log,
19814 			    const struct bpf_prog *prog,
19815 			    const struct bpf_prog *tgt_prog,
19816 			    u32 btf_id,
19817 			    struct bpf_attach_target_info *tgt_info)
19818 {
19819 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19820 	const char prefix[] = "btf_trace_";
19821 	int ret = 0, subprog = -1, i;
19822 	const struct btf_type *t;
19823 	bool conservative = true;
19824 	const char *tname;
19825 	struct btf *btf;
19826 	long addr = 0;
19827 	struct module *mod = NULL;
19828 
19829 	if (!btf_id) {
19830 		bpf_log(log, "Tracing programs must provide btf_id\n");
19831 		return -EINVAL;
19832 	}
19833 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19834 	if (!btf) {
19835 		bpf_log(log,
19836 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19837 		return -EINVAL;
19838 	}
19839 	t = btf_type_by_id(btf, btf_id);
19840 	if (!t) {
19841 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19842 		return -EINVAL;
19843 	}
19844 	tname = btf_name_by_offset(btf, t->name_off);
19845 	if (!tname) {
19846 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19847 		return -EINVAL;
19848 	}
19849 	if (tgt_prog) {
19850 		struct bpf_prog_aux *aux = tgt_prog->aux;
19851 
19852 		if (bpf_prog_is_dev_bound(prog->aux) &&
19853 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19854 			bpf_log(log, "Target program bound device mismatch");
19855 			return -EINVAL;
19856 		}
19857 
19858 		for (i = 0; i < aux->func_info_cnt; i++)
19859 			if (aux->func_info[i].type_id == btf_id) {
19860 				subprog = i;
19861 				break;
19862 			}
19863 		if (subprog == -1) {
19864 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19865 			return -EINVAL;
19866 		}
19867 		conservative = aux->func_info_aux[subprog].unreliable;
19868 		if (prog_extension) {
19869 			if (conservative) {
19870 				bpf_log(log,
19871 					"Cannot replace static functions\n");
19872 				return -EINVAL;
19873 			}
19874 			if (!prog->jit_requested) {
19875 				bpf_log(log,
19876 					"Extension programs should be JITed\n");
19877 				return -EINVAL;
19878 			}
19879 		}
19880 		if (!tgt_prog->jited) {
19881 			bpf_log(log, "Can attach to only JITed progs\n");
19882 			return -EINVAL;
19883 		}
19884 		if (tgt_prog->type == prog->type) {
19885 			/* Cannot fentry/fexit another fentry/fexit program.
19886 			 * Cannot attach program extension to another extension.
19887 			 * It's ok to attach fentry/fexit to extension program.
19888 			 */
19889 			bpf_log(log, "Cannot recursively attach\n");
19890 			return -EINVAL;
19891 		}
19892 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19893 		    prog_extension &&
19894 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19895 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19896 			/* Program extensions can extend all program types
19897 			 * except fentry/fexit. The reason is the following.
19898 			 * The fentry/fexit programs are used for performance
19899 			 * analysis, stats and can be attached to any program
19900 			 * type except themselves. When extension program is
19901 			 * replacing XDP function it is necessary to allow
19902 			 * performance analysis of all functions. Both original
19903 			 * XDP program and its program extension. Hence
19904 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19905 			 * allowed. If extending of fentry/fexit was allowed it
19906 			 * would be possible to create long call chain
19907 			 * fentry->extension->fentry->extension beyond
19908 			 * reasonable stack size. Hence extending fentry is not
19909 			 * allowed.
19910 			 */
19911 			bpf_log(log, "Cannot extend fentry/fexit\n");
19912 			return -EINVAL;
19913 		}
19914 	} else {
19915 		if (prog_extension) {
19916 			bpf_log(log, "Cannot replace kernel functions\n");
19917 			return -EINVAL;
19918 		}
19919 	}
19920 
19921 	switch (prog->expected_attach_type) {
19922 	case BPF_TRACE_RAW_TP:
19923 		if (tgt_prog) {
19924 			bpf_log(log,
19925 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19926 			return -EINVAL;
19927 		}
19928 		if (!btf_type_is_typedef(t)) {
19929 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19930 				btf_id);
19931 			return -EINVAL;
19932 		}
19933 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19934 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19935 				btf_id, tname);
19936 			return -EINVAL;
19937 		}
19938 		tname += sizeof(prefix) - 1;
19939 		t = btf_type_by_id(btf, t->type);
19940 		if (!btf_type_is_ptr(t))
19941 			/* should never happen in valid vmlinux build */
19942 			return -EINVAL;
19943 		t = btf_type_by_id(btf, t->type);
19944 		if (!btf_type_is_func_proto(t))
19945 			/* should never happen in valid vmlinux build */
19946 			return -EINVAL;
19947 
19948 		break;
19949 	case BPF_TRACE_ITER:
19950 		if (!btf_type_is_func(t)) {
19951 			bpf_log(log, "attach_btf_id %u is not a function\n",
19952 				btf_id);
19953 			return -EINVAL;
19954 		}
19955 		t = btf_type_by_id(btf, t->type);
19956 		if (!btf_type_is_func_proto(t))
19957 			return -EINVAL;
19958 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19959 		if (ret)
19960 			return ret;
19961 		break;
19962 	default:
19963 		if (!prog_extension)
19964 			return -EINVAL;
19965 		fallthrough;
19966 	case BPF_MODIFY_RETURN:
19967 	case BPF_LSM_MAC:
19968 	case BPF_LSM_CGROUP:
19969 	case BPF_TRACE_FENTRY:
19970 	case BPF_TRACE_FEXIT:
19971 		if (!btf_type_is_func(t)) {
19972 			bpf_log(log, "attach_btf_id %u is not a function\n",
19973 				btf_id);
19974 			return -EINVAL;
19975 		}
19976 		if (prog_extension &&
19977 		    btf_check_type_match(log, prog, btf, t))
19978 			return -EINVAL;
19979 		t = btf_type_by_id(btf, t->type);
19980 		if (!btf_type_is_func_proto(t))
19981 			return -EINVAL;
19982 
19983 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19984 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19985 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19986 			return -EINVAL;
19987 
19988 		if (tgt_prog && conservative)
19989 			t = NULL;
19990 
19991 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19992 		if (ret < 0)
19993 			return ret;
19994 
19995 		if (tgt_prog) {
19996 			if (subprog == 0)
19997 				addr = (long) tgt_prog->bpf_func;
19998 			else
19999 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20000 		} else {
20001 			if (btf_is_module(btf)) {
20002 				mod = btf_try_get_module(btf);
20003 				if (mod)
20004 					addr = find_kallsyms_symbol_value(mod, tname);
20005 				else
20006 					addr = 0;
20007 			} else {
20008 				addr = kallsyms_lookup_name(tname);
20009 			}
20010 			if (!addr) {
20011 				module_put(mod);
20012 				bpf_log(log,
20013 					"The address of function %s cannot be found\n",
20014 					tname);
20015 				return -ENOENT;
20016 			}
20017 		}
20018 
20019 		if (prog->aux->sleepable) {
20020 			ret = -EINVAL;
20021 			switch (prog->type) {
20022 			case BPF_PROG_TYPE_TRACING:
20023 
20024 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20025 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20026 				 */
20027 				if (!check_non_sleepable_error_inject(btf_id) &&
20028 				    within_error_injection_list(addr))
20029 					ret = 0;
20030 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20031 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20032 				 */
20033 				else {
20034 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20035 										prog);
20036 
20037 					if (flags && (*flags & KF_SLEEPABLE))
20038 						ret = 0;
20039 				}
20040 				break;
20041 			case BPF_PROG_TYPE_LSM:
20042 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20043 				 * Only some of them are sleepable.
20044 				 */
20045 				if (bpf_lsm_is_sleepable_hook(btf_id))
20046 					ret = 0;
20047 				break;
20048 			default:
20049 				break;
20050 			}
20051 			if (ret) {
20052 				module_put(mod);
20053 				bpf_log(log, "%s is not sleepable\n", tname);
20054 				return ret;
20055 			}
20056 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20057 			if (tgt_prog) {
20058 				module_put(mod);
20059 				bpf_log(log, "can't modify return codes of BPF programs\n");
20060 				return -EINVAL;
20061 			}
20062 			ret = -EINVAL;
20063 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20064 			    !check_attach_modify_return(addr, tname))
20065 				ret = 0;
20066 			if (ret) {
20067 				module_put(mod);
20068 				bpf_log(log, "%s() is not modifiable\n", tname);
20069 				return ret;
20070 			}
20071 		}
20072 
20073 		break;
20074 	}
20075 	tgt_info->tgt_addr = addr;
20076 	tgt_info->tgt_name = tname;
20077 	tgt_info->tgt_type = t;
20078 	tgt_info->tgt_mod = mod;
20079 	return 0;
20080 }
20081 
20082 BTF_SET_START(btf_id_deny)
20083 BTF_ID_UNUSED
20084 #ifdef CONFIG_SMP
20085 BTF_ID(func, migrate_disable)
20086 BTF_ID(func, migrate_enable)
20087 #endif
20088 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20089 BTF_ID(func, rcu_read_unlock_strict)
20090 #endif
20091 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20092 BTF_ID(func, preempt_count_add)
20093 BTF_ID(func, preempt_count_sub)
20094 #endif
20095 #ifdef CONFIG_PREEMPT_RCU
20096 BTF_ID(func, __rcu_read_lock)
20097 BTF_ID(func, __rcu_read_unlock)
20098 #endif
20099 BTF_SET_END(btf_id_deny)
20100 
20101 static bool can_be_sleepable(struct bpf_prog *prog)
20102 {
20103 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20104 		switch (prog->expected_attach_type) {
20105 		case BPF_TRACE_FENTRY:
20106 		case BPF_TRACE_FEXIT:
20107 		case BPF_MODIFY_RETURN:
20108 		case BPF_TRACE_ITER:
20109 			return true;
20110 		default:
20111 			return false;
20112 		}
20113 	}
20114 	return prog->type == BPF_PROG_TYPE_LSM ||
20115 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20116 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20117 }
20118 
20119 static int check_attach_btf_id(struct bpf_verifier_env *env)
20120 {
20121 	struct bpf_prog *prog = env->prog;
20122 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20123 	struct bpf_attach_target_info tgt_info = {};
20124 	u32 btf_id = prog->aux->attach_btf_id;
20125 	struct bpf_trampoline *tr;
20126 	int ret;
20127 	u64 key;
20128 
20129 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20130 		if (prog->aux->sleepable)
20131 			/* attach_btf_id checked to be zero already */
20132 			return 0;
20133 		verbose(env, "Syscall programs can only be sleepable\n");
20134 		return -EINVAL;
20135 	}
20136 
20137 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20138 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20139 		return -EINVAL;
20140 	}
20141 
20142 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20143 		return check_struct_ops_btf_id(env);
20144 
20145 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20146 	    prog->type != BPF_PROG_TYPE_LSM &&
20147 	    prog->type != BPF_PROG_TYPE_EXT)
20148 		return 0;
20149 
20150 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20151 	if (ret)
20152 		return ret;
20153 
20154 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20155 		/* to make freplace equivalent to their targets, they need to
20156 		 * inherit env->ops and expected_attach_type for the rest of the
20157 		 * verification
20158 		 */
20159 		env->ops = bpf_verifier_ops[tgt_prog->type];
20160 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20161 	}
20162 
20163 	/* store info about the attachment target that will be used later */
20164 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20165 	prog->aux->attach_func_name = tgt_info.tgt_name;
20166 	prog->aux->mod = tgt_info.tgt_mod;
20167 
20168 	if (tgt_prog) {
20169 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20170 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20171 	}
20172 
20173 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20174 		prog->aux->attach_btf_trace = true;
20175 		return 0;
20176 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20177 		if (!bpf_iter_prog_supported(prog))
20178 			return -EINVAL;
20179 		return 0;
20180 	}
20181 
20182 	if (prog->type == BPF_PROG_TYPE_LSM) {
20183 		ret = bpf_lsm_verify_prog(&env->log, prog);
20184 		if (ret < 0)
20185 			return ret;
20186 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20187 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20188 		return -EINVAL;
20189 	}
20190 
20191 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20192 	tr = bpf_trampoline_get(key, &tgt_info);
20193 	if (!tr)
20194 		return -ENOMEM;
20195 
20196 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20197 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20198 
20199 	prog->aux->dst_trampoline = tr;
20200 	return 0;
20201 }
20202 
20203 struct btf *bpf_get_btf_vmlinux(void)
20204 {
20205 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20206 		mutex_lock(&bpf_verifier_lock);
20207 		if (!btf_vmlinux)
20208 			btf_vmlinux = btf_parse_vmlinux();
20209 		mutex_unlock(&bpf_verifier_lock);
20210 	}
20211 	return btf_vmlinux;
20212 }
20213 
20214 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20215 {
20216 	u64 start_time = ktime_get_ns();
20217 	struct bpf_verifier_env *env;
20218 	int i, len, ret = -EINVAL, err;
20219 	u32 log_true_size;
20220 	bool is_priv;
20221 
20222 	/* no program is valid */
20223 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20224 		return -EINVAL;
20225 
20226 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20227 	 * allocate/free it every time bpf_check() is called
20228 	 */
20229 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20230 	if (!env)
20231 		return -ENOMEM;
20232 
20233 	env->bt.env = env;
20234 
20235 	len = (*prog)->len;
20236 	env->insn_aux_data =
20237 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20238 	ret = -ENOMEM;
20239 	if (!env->insn_aux_data)
20240 		goto err_free_env;
20241 	for (i = 0; i < len; i++)
20242 		env->insn_aux_data[i].orig_idx = i;
20243 	env->prog = *prog;
20244 	env->ops = bpf_verifier_ops[env->prog->type];
20245 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20246 	is_priv = bpf_capable();
20247 
20248 	bpf_get_btf_vmlinux();
20249 
20250 	/* grab the mutex to protect few globals used by verifier */
20251 	if (!is_priv)
20252 		mutex_lock(&bpf_verifier_lock);
20253 
20254 	/* user could have requested verbose verifier output
20255 	 * and supplied buffer to store the verification trace
20256 	 */
20257 	ret = bpf_vlog_init(&env->log, attr->log_level,
20258 			    (char __user *) (unsigned long) attr->log_buf,
20259 			    attr->log_size);
20260 	if (ret)
20261 		goto err_unlock;
20262 
20263 	mark_verifier_state_clean(env);
20264 
20265 	if (IS_ERR(btf_vmlinux)) {
20266 		/* Either gcc or pahole or kernel are broken. */
20267 		verbose(env, "in-kernel BTF is malformed\n");
20268 		ret = PTR_ERR(btf_vmlinux);
20269 		goto skip_full_check;
20270 	}
20271 
20272 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20273 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20274 		env->strict_alignment = true;
20275 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20276 		env->strict_alignment = false;
20277 
20278 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20279 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20280 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20281 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20282 	env->bpf_capable = bpf_capable();
20283 
20284 	if (is_priv)
20285 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20286 
20287 	env->explored_states = kvcalloc(state_htab_size(env),
20288 				       sizeof(struct bpf_verifier_state_list *),
20289 				       GFP_USER);
20290 	ret = -ENOMEM;
20291 	if (!env->explored_states)
20292 		goto skip_full_check;
20293 
20294 	ret = add_subprog_and_kfunc(env);
20295 	if (ret < 0)
20296 		goto skip_full_check;
20297 
20298 	ret = check_subprogs(env);
20299 	if (ret < 0)
20300 		goto skip_full_check;
20301 
20302 	ret = check_btf_info(env, attr, uattr);
20303 	if (ret < 0)
20304 		goto skip_full_check;
20305 
20306 	ret = check_attach_btf_id(env);
20307 	if (ret)
20308 		goto skip_full_check;
20309 
20310 	ret = resolve_pseudo_ldimm64(env);
20311 	if (ret < 0)
20312 		goto skip_full_check;
20313 
20314 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20315 		ret = bpf_prog_offload_verifier_prep(env->prog);
20316 		if (ret)
20317 			goto skip_full_check;
20318 	}
20319 
20320 	ret = check_cfg(env);
20321 	if (ret < 0)
20322 		goto skip_full_check;
20323 
20324 	ret = do_check_subprogs(env);
20325 	ret = ret ?: do_check_main(env);
20326 
20327 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20328 		ret = bpf_prog_offload_finalize(env);
20329 
20330 skip_full_check:
20331 	kvfree(env->explored_states);
20332 
20333 	if (ret == 0)
20334 		ret = check_max_stack_depth(env);
20335 
20336 	/* instruction rewrites happen after this point */
20337 	if (ret == 0)
20338 		ret = optimize_bpf_loop(env);
20339 
20340 	if (is_priv) {
20341 		if (ret == 0)
20342 			opt_hard_wire_dead_code_branches(env);
20343 		if (ret == 0)
20344 			ret = opt_remove_dead_code(env);
20345 		if (ret == 0)
20346 			ret = opt_remove_nops(env);
20347 	} else {
20348 		if (ret == 0)
20349 			sanitize_dead_code(env);
20350 	}
20351 
20352 	if (ret == 0)
20353 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20354 		ret = convert_ctx_accesses(env);
20355 
20356 	if (ret == 0)
20357 		ret = do_misc_fixups(env);
20358 
20359 	/* do 32-bit optimization after insn patching has done so those patched
20360 	 * insns could be handled correctly.
20361 	 */
20362 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20363 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20364 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20365 								     : false;
20366 	}
20367 
20368 	if (ret == 0)
20369 		ret = fixup_call_args(env);
20370 
20371 	env->verification_time = ktime_get_ns() - start_time;
20372 	print_verification_stats(env);
20373 	env->prog->aux->verified_insns = env->insn_processed;
20374 
20375 	/* preserve original error even if log finalization is successful */
20376 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20377 	if (err)
20378 		ret = err;
20379 
20380 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20381 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20382 				  &log_true_size, sizeof(log_true_size))) {
20383 		ret = -EFAULT;
20384 		goto err_release_maps;
20385 	}
20386 
20387 	if (ret)
20388 		goto err_release_maps;
20389 
20390 	if (env->used_map_cnt) {
20391 		/* if program passed verifier, update used_maps in bpf_prog_info */
20392 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20393 							  sizeof(env->used_maps[0]),
20394 							  GFP_KERNEL);
20395 
20396 		if (!env->prog->aux->used_maps) {
20397 			ret = -ENOMEM;
20398 			goto err_release_maps;
20399 		}
20400 
20401 		memcpy(env->prog->aux->used_maps, env->used_maps,
20402 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20403 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20404 	}
20405 	if (env->used_btf_cnt) {
20406 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20407 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20408 							  sizeof(env->used_btfs[0]),
20409 							  GFP_KERNEL);
20410 		if (!env->prog->aux->used_btfs) {
20411 			ret = -ENOMEM;
20412 			goto err_release_maps;
20413 		}
20414 
20415 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20416 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20417 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20418 	}
20419 	if (env->used_map_cnt || env->used_btf_cnt) {
20420 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20421 		 * bpf_ld_imm64 instructions
20422 		 */
20423 		convert_pseudo_ld_imm64(env);
20424 	}
20425 
20426 	adjust_btf_func(env);
20427 
20428 err_release_maps:
20429 	if (!env->prog->aux->used_maps)
20430 		/* if we didn't copy map pointers into bpf_prog_info, release
20431 		 * them now. Otherwise free_used_maps() will release them.
20432 		 */
20433 		release_maps(env);
20434 	if (!env->prog->aux->used_btfs)
20435 		release_btfs(env);
20436 
20437 	/* extension progs temporarily inherit the attach_type of their targets
20438 	   for verification purposes, so set it back to zero before returning
20439 	 */
20440 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20441 		env->prog->expected_attach_type = 0;
20442 
20443 	*prog = env->prog;
20444 err_unlock:
20445 	if (!is_priv)
20446 		mutex_unlock(&bpf_verifier_lock);
20447 	vfree(env->insn_aux_data);
20448 err_free_env:
20449 	kfree(env);
20450 	return ret;
20451 }
20452