xref: /openbmc/linux/kernel/bpf/verifier.c (revision 8f01dda1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 }
2543 
2544 #define DEF_NOT_SUBREG	(0)
2545 static void init_reg_state(struct bpf_verifier_env *env,
2546 			   struct bpf_func_state *state)
2547 {
2548 	struct bpf_reg_state *regs = state->regs;
2549 	int i;
2550 
2551 	for (i = 0; i < MAX_BPF_REG; i++) {
2552 		mark_reg_not_init(env, regs, i);
2553 		regs[i].live = REG_LIVE_NONE;
2554 		regs[i].parent = NULL;
2555 		regs[i].subreg_def = DEF_NOT_SUBREG;
2556 	}
2557 
2558 	/* frame pointer */
2559 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2560 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2561 	regs[BPF_REG_FP].frameno = state->frameno;
2562 }
2563 
2564 #define BPF_MAIN_FUNC (-1)
2565 static void init_func_state(struct bpf_verifier_env *env,
2566 			    struct bpf_func_state *state,
2567 			    int callsite, int frameno, int subprogno)
2568 {
2569 	state->callsite = callsite;
2570 	state->frameno = frameno;
2571 	state->subprogno = subprogno;
2572 	state->callback_ret_range = tnum_range(0, 0);
2573 	init_reg_state(env, state);
2574 	mark_verifier_state_scratched(env);
2575 }
2576 
2577 /* Similar to push_stack(), but for async callbacks */
2578 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2579 						int insn_idx, int prev_insn_idx,
2580 						int subprog)
2581 {
2582 	struct bpf_verifier_stack_elem *elem;
2583 	struct bpf_func_state *frame;
2584 
2585 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2586 	if (!elem)
2587 		goto err;
2588 
2589 	elem->insn_idx = insn_idx;
2590 	elem->prev_insn_idx = prev_insn_idx;
2591 	elem->next = env->head;
2592 	elem->log_pos = env->log.end_pos;
2593 	env->head = elem;
2594 	env->stack_size++;
2595 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2596 		verbose(env,
2597 			"The sequence of %d jumps is too complex for async cb.\n",
2598 			env->stack_size);
2599 		goto err;
2600 	}
2601 	/* Unlike push_stack() do not copy_verifier_state().
2602 	 * The caller state doesn't matter.
2603 	 * This is async callback. It starts in a fresh stack.
2604 	 * Initialize it similar to do_check_common().
2605 	 */
2606 	elem->st.branches = 1;
2607 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2608 	if (!frame)
2609 		goto err;
2610 	init_func_state(env, frame,
2611 			BPF_MAIN_FUNC /* callsite */,
2612 			0 /* frameno within this callchain */,
2613 			subprog /* subprog number within this prog */);
2614 	elem->st.frame[0] = frame;
2615 	return &elem->st;
2616 err:
2617 	free_verifier_state(env->cur_state, true);
2618 	env->cur_state = NULL;
2619 	/* pop all elements and return */
2620 	while (!pop_stack(env, NULL, NULL, false));
2621 	return NULL;
2622 }
2623 
2624 
2625 enum reg_arg_type {
2626 	SRC_OP,		/* register is used as source operand */
2627 	DST_OP,		/* register is used as destination operand */
2628 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2629 };
2630 
2631 static int cmp_subprogs(const void *a, const void *b)
2632 {
2633 	return ((struct bpf_subprog_info *)a)->start -
2634 	       ((struct bpf_subprog_info *)b)->start;
2635 }
2636 
2637 static int find_subprog(struct bpf_verifier_env *env, int off)
2638 {
2639 	struct bpf_subprog_info *p;
2640 
2641 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2642 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2643 	if (!p)
2644 		return -ENOENT;
2645 	return p - env->subprog_info;
2646 
2647 }
2648 
2649 static int add_subprog(struct bpf_verifier_env *env, int off)
2650 {
2651 	int insn_cnt = env->prog->len;
2652 	int ret;
2653 
2654 	if (off >= insn_cnt || off < 0) {
2655 		verbose(env, "call to invalid destination\n");
2656 		return -EINVAL;
2657 	}
2658 	ret = find_subprog(env, off);
2659 	if (ret >= 0)
2660 		return ret;
2661 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2662 		verbose(env, "too many subprograms\n");
2663 		return -E2BIG;
2664 	}
2665 	/* determine subprog starts. The end is one before the next starts */
2666 	env->subprog_info[env->subprog_cnt++].start = off;
2667 	sort(env->subprog_info, env->subprog_cnt,
2668 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2669 	return env->subprog_cnt - 1;
2670 }
2671 
2672 #define MAX_KFUNC_DESCS 256
2673 #define MAX_KFUNC_BTFS	256
2674 
2675 struct bpf_kfunc_desc {
2676 	struct btf_func_model func_model;
2677 	u32 func_id;
2678 	s32 imm;
2679 	u16 offset;
2680 	unsigned long addr;
2681 };
2682 
2683 struct bpf_kfunc_btf {
2684 	struct btf *btf;
2685 	struct module *module;
2686 	u16 offset;
2687 };
2688 
2689 struct bpf_kfunc_desc_tab {
2690 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2691 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2692 	 * available, therefore at the end of verification do_misc_fixups()
2693 	 * sorts this by imm and offset.
2694 	 */
2695 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2696 	u32 nr_descs;
2697 };
2698 
2699 struct bpf_kfunc_btf_tab {
2700 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2701 	u32 nr_descs;
2702 };
2703 
2704 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2705 {
2706 	const struct bpf_kfunc_desc *d0 = a;
2707 	const struct bpf_kfunc_desc *d1 = b;
2708 
2709 	/* func_id is not greater than BTF_MAX_TYPE */
2710 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2711 }
2712 
2713 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2714 {
2715 	const struct bpf_kfunc_btf *d0 = a;
2716 	const struct bpf_kfunc_btf *d1 = b;
2717 
2718 	return d0->offset - d1->offset;
2719 }
2720 
2721 static const struct bpf_kfunc_desc *
2722 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2723 {
2724 	struct bpf_kfunc_desc desc = {
2725 		.func_id = func_id,
2726 		.offset = offset,
2727 	};
2728 	struct bpf_kfunc_desc_tab *tab;
2729 
2730 	tab = prog->aux->kfunc_tab;
2731 	return bsearch(&desc, tab->descs, tab->nr_descs,
2732 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2733 }
2734 
2735 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2736 		       u16 btf_fd_idx, u8 **func_addr)
2737 {
2738 	const struct bpf_kfunc_desc *desc;
2739 
2740 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2741 	if (!desc)
2742 		return -EFAULT;
2743 
2744 	*func_addr = (u8 *)desc->addr;
2745 	return 0;
2746 }
2747 
2748 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2749 					 s16 offset)
2750 {
2751 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2752 	struct bpf_kfunc_btf_tab *tab;
2753 	struct bpf_kfunc_btf *b;
2754 	struct module *mod;
2755 	struct btf *btf;
2756 	int btf_fd;
2757 
2758 	tab = env->prog->aux->kfunc_btf_tab;
2759 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2760 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2761 	if (!b) {
2762 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2763 			verbose(env, "too many different module BTFs\n");
2764 			return ERR_PTR(-E2BIG);
2765 		}
2766 
2767 		if (bpfptr_is_null(env->fd_array)) {
2768 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2769 			return ERR_PTR(-EPROTO);
2770 		}
2771 
2772 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2773 					    offset * sizeof(btf_fd),
2774 					    sizeof(btf_fd)))
2775 			return ERR_PTR(-EFAULT);
2776 
2777 		btf = btf_get_by_fd(btf_fd);
2778 		if (IS_ERR(btf)) {
2779 			verbose(env, "invalid module BTF fd specified\n");
2780 			return btf;
2781 		}
2782 
2783 		if (!btf_is_module(btf)) {
2784 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2785 			btf_put(btf);
2786 			return ERR_PTR(-EINVAL);
2787 		}
2788 
2789 		mod = btf_try_get_module(btf);
2790 		if (!mod) {
2791 			btf_put(btf);
2792 			return ERR_PTR(-ENXIO);
2793 		}
2794 
2795 		b = &tab->descs[tab->nr_descs++];
2796 		b->btf = btf;
2797 		b->module = mod;
2798 		b->offset = offset;
2799 
2800 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2801 		     kfunc_btf_cmp_by_off, NULL);
2802 	}
2803 	return b->btf;
2804 }
2805 
2806 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2807 {
2808 	if (!tab)
2809 		return;
2810 
2811 	while (tab->nr_descs--) {
2812 		module_put(tab->descs[tab->nr_descs].module);
2813 		btf_put(tab->descs[tab->nr_descs].btf);
2814 	}
2815 	kfree(tab);
2816 }
2817 
2818 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2819 {
2820 	if (offset) {
2821 		if (offset < 0) {
2822 			/* In the future, this can be allowed to increase limit
2823 			 * of fd index into fd_array, interpreted as u16.
2824 			 */
2825 			verbose(env, "negative offset disallowed for kernel module function call\n");
2826 			return ERR_PTR(-EINVAL);
2827 		}
2828 
2829 		return __find_kfunc_desc_btf(env, offset);
2830 	}
2831 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2832 }
2833 
2834 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2835 {
2836 	const struct btf_type *func, *func_proto;
2837 	struct bpf_kfunc_btf_tab *btf_tab;
2838 	struct bpf_kfunc_desc_tab *tab;
2839 	struct bpf_prog_aux *prog_aux;
2840 	struct bpf_kfunc_desc *desc;
2841 	const char *func_name;
2842 	struct btf *desc_btf;
2843 	unsigned long call_imm;
2844 	unsigned long addr;
2845 	int err;
2846 
2847 	prog_aux = env->prog->aux;
2848 	tab = prog_aux->kfunc_tab;
2849 	btf_tab = prog_aux->kfunc_btf_tab;
2850 	if (!tab) {
2851 		if (!btf_vmlinux) {
2852 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2853 			return -ENOTSUPP;
2854 		}
2855 
2856 		if (!env->prog->jit_requested) {
2857 			verbose(env, "JIT is required for calling kernel function\n");
2858 			return -ENOTSUPP;
2859 		}
2860 
2861 		if (!bpf_jit_supports_kfunc_call()) {
2862 			verbose(env, "JIT does not support calling kernel function\n");
2863 			return -ENOTSUPP;
2864 		}
2865 
2866 		if (!env->prog->gpl_compatible) {
2867 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2868 			return -EINVAL;
2869 		}
2870 
2871 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2872 		if (!tab)
2873 			return -ENOMEM;
2874 		prog_aux->kfunc_tab = tab;
2875 	}
2876 
2877 	/* func_id == 0 is always invalid, but instead of returning an error, be
2878 	 * conservative and wait until the code elimination pass before returning
2879 	 * error, so that invalid calls that get pruned out can be in BPF programs
2880 	 * loaded from userspace.  It is also required that offset be untouched
2881 	 * for such calls.
2882 	 */
2883 	if (!func_id && !offset)
2884 		return 0;
2885 
2886 	if (!btf_tab && offset) {
2887 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2888 		if (!btf_tab)
2889 			return -ENOMEM;
2890 		prog_aux->kfunc_btf_tab = btf_tab;
2891 	}
2892 
2893 	desc_btf = find_kfunc_desc_btf(env, offset);
2894 	if (IS_ERR(desc_btf)) {
2895 		verbose(env, "failed to find BTF for kernel function\n");
2896 		return PTR_ERR(desc_btf);
2897 	}
2898 
2899 	if (find_kfunc_desc(env->prog, func_id, offset))
2900 		return 0;
2901 
2902 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2903 		verbose(env, "too many different kernel function calls\n");
2904 		return -E2BIG;
2905 	}
2906 
2907 	func = btf_type_by_id(desc_btf, func_id);
2908 	if (!func || !btf_type_is_func(func)) {
2909 		verbose(env, "kernel btf_id %u is not a function\n",
2910 			func_id);
2911 		return -EINVAL;
2912 	}
2913 	func_proto = btf_type_by_id(desc_btf, func->type);
2914 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2915 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2916 			func_id);
2917 		return -EINVAL;
2918 	}
2919 
2920 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2921 	addr = kallsyms_lookup_name(func_name);
2922 	if (!addr) {
2923 		verbose(env, "cannot find address for kernel function %s\n",
2924 			func_name);
2925 		return -EINVAL;
2926 	}
2927 	specialize_kfunc(env, func_id, offset, &addr);
2928 
2929 	if (bpf_jit_supports_far_kfunc_call()) {
2930 		call_imm = func_id;
2931 	} else {
2932 		call_imm = BPF_CALL_IMM(addr);
2933 		/* Check whether the relative offset overflows desc->imm */
2934 		if ((unsigned long)(s32)call_imm != call_imm) {
2935 			verbose(env, "address of kernel function %s is out of range\n",
2936 				func_name);
2937 			return -EINVAL;
2938 		}
2939 	}
2940 
2941 	if (bpf_dev_bound_kfunc_id(func_id)) {
2942 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2943 		if (err)
2944 			return err;
2945 	}
2946 
2947 	desc = &tab->descs[tab->nr_descs++];
2948 	desc->func_id = func_id;
2949 	desc->imm = call_imm;
2950 	desc->offset = offset;
2951 	desc->addr = addr;
2952 	err = btf_distill_func_proto(&env->log, desc_btf,
2953 				     func_proto, func_name,
2954 				     &desc->func_model);
2955 	if (!err)
2956 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2957 		     kfunc_desc_cmp_by_id_off, NULL);
2958 	return err;
2959 }
2960 
2961 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2962 {
2963 	const struct bpf_kfunc_desc *d0 = a;
2964 	const struct bpf_kfunc_desc *d1 = b;
2965 
2966 	if (d0->imm != d1->imm)
2967 		return d0->imm < d1->imm ? -1 : 1;
2968 	if (d0->offset != d1->offset)
2969 		return d0->offset < d1->offset ? -1 : 1;
2970 	return 0;
2971 }
2972 
2973 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2974 {
2975 	struct bpf_kfunc_desc_tab *tab;
2976 
2977 	tab = prog->aux->kfunc_tab;
2978 	if (!tab)
2979 		return;
2980 
2981 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2982 	     kfunc_desc_cmp_by_imm_off, NULL);
2983 }
2984 
2985 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2986 {
2987 	return !!prog->aux->kfunc_tab;
2988 }
2989 
2990 const struct btf_func_model *
2991 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2992 			 const struct bpf_insn *insn)
2993 {
2994 	const struct bpf_kfunc_desc desc = {
2995 		.imm = insn->imm,
2996 		.offset = insn->off,
2997 	};
2998 	const struct bpf_kfunc_desc *res;
2999 	struct bpf_kfunc_desc_tab *tab;
3000 
3001 	tab = prog->aux->kfunc_tab;
3002 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3003 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3004 
3005 	return res ? &res->func_model : NULL;
3006 }
3007 
3008 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3009 {
3010 	struct bpf_subprog_info *subprog = env->subprog_info;
3011 	struct bpf_insn *insn = env->prog->insnsi;
3012 	int i, ret, insn_cnt = env->prog->len;
3013 
3014 	/* Add entry function. */
3015 	ret = add_subprog(env, 0);
3016 	if (ret)
3017 		return ret;
3018 
3019 	for (i = 0; i < insn_cnt; i++, insn++) {
3020 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3021 		    !bpf_pseudo_kfunc_call(insn))
3022 			continue;
3023 
3024 		if (!env->bpf_capable) {
3025 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3026 			return -EPERM;
3027 		}
3028 
3029 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3030 			ret = add_subprog(env, i + insn->imm + 1);
3031 		else
3032 			ret = add_kfunc_call(env, insn->imm, insn->off);
3033 
3034 		if (ret < 0)
3035 			return ret;
3036 	}
3037 
3038 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3039 	 * logic. 'subprog_cnt' should not be increased.
3040 	 */
3041 	subprog[env->subprog_cnt].start = insn_cnt;
3042 
3043 	if (env->log.level & BPF_LOG_LEVEL2)
3044 		for (i = 0; i < env->subprog_cnt; i++)
3045 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3046 
3047 	return 0;
3048 }
3049 
3050 static int check_subprogs(struct bpf_verifier_env *env)
3051 {
3052 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3053 	struct bpf_subprog_info *subprog = env->subprog_info;
3054 	struct bpf_insn *insn = env->prog->insnsi;
3055 	int insn_cnt = env->prog->len;
3056 
3057 	/* now check that all jumps are within the same subprog */
3058 	subprog_start = subprog[cur_subprog].start;
3059 	subprog_end = subprog[cur_subprog + 1].start;
3060 	for (i = 0; i < insn_cnt; i++) {
3061 		u8 code = insn[i].code;
3062 
3063 		if (code == (BPF_JMP | BPF_CALL) &&
3064 		    insn[i].src_reg == 0 &&
3065 		    insn[i].imm == BPF_FUNC_tail_call)
3066 			subprog[cur_subprog].has_tail_call = true;
3067 		if (BPF_CLASS(code) == BPF_LD &&
3068 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3069 			subprog[cur_subprog].has_ld_abs = true;
3070 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3071 			goto next;
3072 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3073 			goto next;
3074 		if (code == (BPF_JMP32 | BPF_JA))
3075 			off = i + insn[i].imm + 1;
3076 		else
3077 			off = i + insn[i].off + 1;
3078 		if (off < subprog_start || off >= subprog_end) {
3079 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3080 			return -EINVAL;
3081 		}
3082 next:
3083 		if (i == subprog_end - 1) {
3084 			/* to avoid fall-through from one subprog into another
3085 			 * the last insn of the subprog should be either exit
3086 			 * or unconditional jump back
3087 			 */
3088 			if (code != (BPF_JMP | BPF_EXIT) &&
3089 			    code != (BPF_JMP32 | BPF_JA) &&
3090 			    code != (BPF_JMP | BPF_JA)) {
3091 				verbose(env, "last insn is not an exit or jmp\n");
3092 				return -EINVAL;
3093 			}
3094 			subprog_start = subprog_end;
3095 			cur_subprog++;
3096 			if (cur_subprog < env->subprog_cnt)
3097 				subprog_end = subprog[cur_subprog + 1].start;
3098 		}
3099 	}
3100 	return 0;
3101 }
3102 
3103 /* Parentage chain of this register (or stack slot) should take care of all
3104  * issues like callee-saved registers, stack slot allocation time, etc.
3105  */
3106 static int mark_reg_read(struct bpf_verifier_env *env,
3107 			 const struct bpf_reg_state *state,
3108 			 struct bpf_reg_state *parent, u8 flag)
3109 {
3110 	bool writes = parent == state->parent; /* Observe write marks */
3111 	int cnt = 0;
3112 
3113 	while (parent) {
3114 		/* if read wasn't screened by an earlier write ... */
3115 		if (writes && state->live & REG_LIVE_WRITTEN)
3116 			break;
3117 		if (parent->live & REG_LIVE_DONE) {
3118 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3119 				reg_type_str(env, parent->type),
3120 				parent->var_off.value, parent->off);
3121 			return -EFAULT;
3122 		}
3123 		/* The first condition is more likely to be true than the
3124 		 * second, checked it first.
3125 		 */
3126 		if ((parent->live & REG_LIVE_READ) == flag ||
3127 		    parent->live & REG_LIVE_READ64)
3128 			/* The parentage chain never changes and
3129 			 * this parent was already marked as LIVE_READ.
3130 			 * There is no need to keep walking the chain again and
3131 			 * keep re-marking all parents as LIVE_READ.
3132 			 * This case happens when the same register is read
3133 			 * multiple times without writes into it in-between.
3134 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3135 			 * then no need to set the weak REG_LIVE_READ32.
3136 			 */
3137 			break;
3138 		/* ... then we depend on parent's value */
3139 		parent->live |= flag;
3140 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3141 		if (flag == REG_LIVE_READ64)
3142 			parent->live &= ~REG_LIVE_READ32;
3143 		state = parent;
3144 		parent = state->parent;
3145 		writes = true;
3146 		cnt++;
3147 	}
3148 
3149 	if (env->longest_mark_read_walk < cnt)
3150 		env->longest_mark_read_walk = cnt;
3151 	return 0;
3152 }
3153 
3154 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3155 {
3156 	struct bpf_func_state *state = func(env, reg);
3157 	int spi, ret;
3158 
3159 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3160 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3161 	 * check_kfunc_call.
3162 	 */
3163 	if (reg->type == CONST_PTR_TO_DYNPTR)
3164 		return 0;
3165 	spi = dynptr_get_spi(env, reg);
3166 	if (spi < 0)
3167 		return spi;
3168 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3169 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3170 	 * read.
3171 	 */
3172 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3173 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3174 	if (ret)
3175 		return ret;
3176 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3177 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3178 }
3179 
3180 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3181 			  int spi, int nr_slots)
3182 {
3183 	struct bpf_func_state *state = func(env, reg);
3184 	int err, i;
3185 
3186 	for (i = 0; i < nr_slots; i++) {
3187 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3188 
3189 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3190 		if (err)
3191 			return err;
3192 
3193 		mark_stack_slot_scratched(env, spi - i);
3194 	}
3195 
3196 	return 0;
3197 }
3198 
3199 /* This function is supposed to be used by the following 32-bit optimization
3200  * code only. It returns TRUE if the source or destination register operates
3201  * on 64-bit, otherwise return FALSE.
3202  */
3203 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3204 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3205 {
3206 	u8 code, class, op;
3207 
3208 	code = insn->code;
3209 	class = BPF_CLASS(code);
3210 	op = BPF_OP(code);
3211 	if (class == BPF_JMP) {
3212 		/* BPF_EXIT for "main" will reach here. Return TRUE
3213 		 * conservatively.
3214 		 */
3215 		if (op == BPF_EXIT)
3216 			return true;
3217 		if (op == BPF_CALL) {
3218 			/* BPF to BPF call will reach here because of marking
3219 			 * caller saved clobber with DST_OP_NO_MARK for which we
3220 			 * don't care the register def because they are anyway
3221 			 * marked as NOT_INIT already.
3222 			 */
3223 			if (insn->src_reg == BPF_PSEUDO_CALL)
3224 				return false;
3225 			/* Helper call will reach here because of arg type
3226 			 * check, conservatively return TRUE.
3227 			 */
3228 			if (t == SRC_OP)
3229 				return true;
3230 
3231 			return false;
3232 		}
3233 	}
3234 
3235 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3236 		return false;
3237 
3238 	if (class == BPF_ALU64 || class == BPF_JMP ||
3239 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3240 		return true;
3241 
3242 	if (class == BPF_ALU || class == BPF_JMP32)
3243 		return false;
3244 
3245 	if (class == BPF_LDX) {
3246 		if (t != SRC_OP)
3247 			return BPF_SIZE(code) == BPF_DW;
3248 		/* LDX source must be ptr. */
3249 		return true;
3250 	}
3251 
3252 	if (class == BPF_STX) {
3253 		/* BPF_STX (including atomic variants) has multiple source
3254 		 * operands, one of which is a ptr. Check whether the caller is
3255 		 * asking about it.
3256 		 */
3257 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3258 			return true;
3259 		return BPF_SIZE(code) == BPF_DW;
3260 	}
3261 
3262 	if (class == BPF_LD) {
3263 		u8 mode = BPF_MODE(code);
3264 
3265 		/* LD_IMM64 */
3266 		if (mode == BPF_IMM)
3267 			return true;
3268 
3269 		/* Both LD_IND and LD_ABS return 32-bit data. */
3270 		if (t != SRC_OP)
3271 			return  false;
3272 
3273 		/* Implicit ctx ptr. */
3274 		if (regno == BPF_REG_6)
3275 			return true;
3276 
3277 		/* Explicit source could be any width. */
3278 		return true;
3279 	}
3280 
3281 	if (class == BPF_ST)
3282 		/* The only source register for BPF_ST is a ptr. */
3283 		return true;
3284 
3285 	/* Conservatively return true at default. */
3286 	return true;
3287 }
3288 
3289 /* Return the regno defined by the insn, or -1. */
3290 static int insn_def_regno(const struct bpf_insn *insn)
3291 {
3292 	switch (BPF_CLASS(insn->code)) {
3293 	case BPF_JMP:
3294 	case BPF_JMP32:
3295 	case BPF_ST:
3296 		return -1;
3297 	case BPF_STX:
3298 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3299 		    (insn->imm & BPF_FETCH)) {
3300 			if (insn->imm == BPF_CMPXCHG)
3301 				return BPF_REG_0;
3302 			else
3303 				return insn->src_reg;
3304 		} else {
3305 			return -1;
3306 		}
3307 	default:
3308 		return insn->dst_reg;
3309 	}
3310 }
3311 
3312 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3313 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3314 {
3315 	int dst_reg = insn_def_regno(insn);
3316 
3317 	if (dst_reg == -1)
3318 		return false;
3319 
3320 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3321 }
3322 
3323 static void mark_insn_zext(struct bpf_verifier_env *env,
3324 			   struct bpf_reg_state *reg)
3325 {
3326 	s32 def_idx = reg->subreg_def;
3327 
3328 	if (def_idx == DEF_NOT_SUBREG)
3329 		return;
3330 
3331 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3332 	/* The dst will be zero extended, so won't be sub-register anymore. */
3333 	reg->subreg_def = DEF_NOT_SUBREG;
3334 }
3335 
3336 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3337 			   enum reg_arg_type t)
3338 {
3339 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3340 	struct bpf_reg_state *reg;
3341 	bool rw64;
3342 
3343 	if (regno >= MAX_BPF_REG) {
3344 		verbose(env, "R%d is invalid\n", regno);
3345 		return -EINVAL;
3346 	}
3347 
3348 	mark_reg_scratched(env, regno);
3349 
3350 	reg = &regs[regno];
3351 	rw64 = is_reg64(env, insn, regno, reg, t);
3352 	if (t == SRC_OP) {
3353 		/* check whether register used as source operand can be read */
3354 		if (reg->type == NOT_INIT) {
3355 			verbose(env, "R%d !read_ok\n", regno);
3356 			return -EACCES;
3357 		}
3358 		/* We don't need to worry about FP liveness because it's read-only */
3359 		if (regno == BPF_REG_FP)
3360 			return 0;
3361 
3362 		if (rw64)
3363 			mark_insn_zext(env, reg);
3364 
3365 		return mark_reg_read(env, reg, reg->parent,
3366 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3367 	} else {
3368 		/* check whether register used as dest operand can be written to */
3369 		if (regno == BPF_REG_FP) {
3370 			verbose(env, "frame pointer is read only\n");
3371 			return -EACCES;
3372 		}
3373 		reg->live |= REG_LIVE_WRITTEN;
3374 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3375 		if (t == DST_OP)
3376 			mark_reg_unknown(env, regs, regno);
3377 	}
3378 	return 0;
3379 }
3380 
3381 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3382 			 enum reg_arg_type t)
3383 {
3384 	struct bpf_verifier_state *vstate = env->cur_state;
3385 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3386 
3387 	return __check_reg_arg(env, state->regs, regno, t);
3388 }
3389 
3390 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3391 {
3392 	env->insn_aux_data[idx].jmp_point = true;
3393 }
3394 
3395 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3396 {
3397 	return env->insn_aux_data[insn_idx].jmp_point;
3398 }
3399 
3400 /* for any branch, call, exit record the history of jmps in the given state */
3401 static int push_jmp_history(struct bpf_verifier_env *env,
3402 			    struct bpf_verifier_state *cur)
3403 {
3404 	u32 cnt = cur->jmp_history_cnt;
3405 	struct bpf_idx_pair *p;
3406 	size_t alloc_size;
3407 
3408 	if (!is_jmp_point(env, env->insn_idx))
3409 		return 0;
3410 
3411 	cnt++;
3412 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3413 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3414 	if (!p)
3415 		return -ENOMEM;
3416 	p[cnt - 1].idx = env->insn_idx;
3417 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3418 	cur->jmp_history = p;
3419 	cur->jmp_history_cnt = cnt;
3420 	return 0;
3421 }
3422 
3423 /* Backtrack one insn at a time. If idx is not at the top of recorded
3424  * history then previous instruction came from straight line execution.
3425  * Return -ENOENT if we exhausted all instructions within given state.
3426  *
3427  * It's legal to have a bit of a looping with the same starting and ending
3428  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3429  * instruction index is the same as state's first_idx doesn't mean we are
3430  * done. If there is still some jump history left, we should keep going. We
3431  * need to take into account that we might have a jump history between given
3432  * state's parent and itself, due to checkpointing. In this case, we'll have
3433  * history entry recording a jump from last instruction of parent state and
3434  * first instruction of given state.
3435  */
3436 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3437 			     u32 *history)
3438 {
3439 	u32 cnt = *history;
3440 
3441 	if (i == st->first_insn_idx) {
3442 		if (cnt == 0)
3443 			return -ENOENT;
3444 		if (cnt == 1 && st->jmp_history[0].idx == i)
3445 			return -ENOENT;
3446 	}
3447 
3448 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3449 		i = st->jmp_history[cnt - 1].prev_idx;
3450 		(*history)--;
3451 	} else {
3452 		i--;
3453 	}
3454 	return i;
3455 }
3456 
3457 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3458 {
3459 	const struct btf_type *func;
3460 	struct btf *desc_btf;
3461 
3462 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3463 		return NULL;
3464 
3465 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3466 	if (IS_ERR(desc_btf))
3467 		return "<error>";
3468 
3469 	func = btf_type_by_id(desc_btf, insn->imm);
3470 	return btf_name_by_offset(desc_btf, func->name_off);
3471 }
3472 
3473 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3474 {
3475 	bt->frame = frame;
3476 }
3477 
3478 static inline void bt_reset(struct backtrack_state *bt)
3479 {
3480 	struct bpf_verifier_env *env = bt->env;
3481 
3482 	memset(bt, 0, sizeof(*bt));
3483 	bt->env = env;
3484 }
3485 
3486 static inline u32 bt_empty(struct backtrack_state *bt)
3487 {
3488 	u64 mask = 0;
3489 	int i;
3490 
3491 	for (i = 0; i <= bt->frame; i++)
3492 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3493 
3494 	return mask == 0;
3495 }
3496 
3497 static inline int bt_subprog_enter(struct backtrack_state *bt)
3498 {
3499 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3500 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3501 		WARN_ONCE(1, "verifier backtracking bug");
3502 		return -EFAULT;
3503 	}
3504 	bt->frame++;
3505 	return 0;
3506 }
3507 
3508 static inline int bt_subprog_exit(struct backtrack_state *bt)
3509 {
3510 	if (bt->frame == 0) {
3511 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3512 		WARN_ONCE(1, "verifier backtracking bug");
3513 		return -EFAULT;
3514 	}
3515 	bt->frame--;
3516 	return 0;
3517 }
3518 
3519 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3520 {
3521 	bt->reg_masks[frame] |= 1 << reg;
3522 }
3523 
3524 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3525 {
3526 	bt->reg_masks[frame] &= ~(1 << reg);
3527 }
3528 
3529 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3530 {
3531 	bt_set_frame_reg(bt, bt->frame, reg);
3532 }
3533 
3534 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3535 {
3536 	bt_clear_frame_reg(bt, bt->frame, reg);
3537 }
3538 
3539 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3540 {
3541 	bt->stack_masks[frame] |= 1ull << slot;
3542 }
3543 
3544 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3545 {
3546 	bt->stack_masks[frame] &= ~(1ull << slot);
3547 }
3548 
3549 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3550 {
3551 	bt_set_frame_slot(bt, bt->frame, slot);
3552 }
3553 
3554 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3555 {
3556 	bt_clear_frame_slot(bt, bt->frame, slot);
3557 }
3558 
3559 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3560 {
3561 	return bt->reg_masks[frame];
3562 }
3563 
3564 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3565 {
3566 	return bt->reg_masks[bt->frame];
3567 }
3568 
3569 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3570 {
3571 	return bt->stack_masks[frame];
3572 }
3573 
3574 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3575 {
3576 	return bt->stack_masks[bt->frame];
3577 }
3578 
3579 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3580 {
3581 	return bt->reg_masks[bt->frame] & (1 << reg);
3582 }
3583 
3584 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3585 {
3586 	return bt->stack_masks[bt->frame] & (1ull << slot);
3587 }
3588 
3589 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3590 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3591 {
3592 	DECLARE_BITMAP(mask, 64);
3593 	bool first = true;
3594 	int i, n;
3595 
3596 	buf[0] = '\0';
3597 
3598 	bitmap_from_u64(mask, reg_mask);
3599 	for_each_set_bit(i, mask, 32) {
3600 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3601 		first = false;
3602 		buf += n;
3603 		buf_sz -= n;
3604 		if (buf_sz < 0)
3605 			break;
3606 	}
3607 }
3608 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3609 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3610 {
3611 	DECLARE_BITMAP(mask, 64);
3612 	bool first = true;
3613 	int i, n;
3614 
3615 	buf[0] = '\0';
3616 
3617 	bitmap_from_u64(mask, stack_mask);
3618 	for_each_set_bit(i, mask, 64) {
3619 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3620 		first = false;
3621 		buf += n;
3622 		buf_sz -= n;
3623 		if (buf_sz < 0)
3624 			break;
3625 	}
3626 }
3627 
3628 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3629 
3630 /* For given verifier state backtrack_insn() is called from the last insn to
3631  * the first insn. Its purpose is to compute a bitmask of registers and
3632  * stack slots that needs precision in the parent verifier state.
3633  *
3634  * @idx is an index of the instruction we are currently processing;
3635  * @subseq_idx is an index of the subsequent instruction that:
3636  *   - *would be* executed next, if jump history is viewed in forward order;
3637  *   - *was* processed previously during backtracking.
3638  */
3639 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3640 			  struct backtrack_state *bt)
3641 {
3642 	const struct bpf_insn_cbs cbs = {
3643 		.cb_call	= disasm_kfunc_name,
3644 		.cb_print	= verbose,
3645 		.private_data	= env,
3646 	};
3647 	struct bpf_insn *insn = env->prog->insnsi + idx;
3648 	u8 class = BPF_CLASS(insn->code);
3649 	u8 opcode = BPF_OP(insn->code);
3650 	u8 mode = BPF_MODE(insn->code);
3651 	u32 dreg = insn->dst_reg;
3652 	u32 sreg = insn->src_reg;
3653 	u32 spi, i;
3654 
3655 	if (insn->code == 0)
3656 		return 0;
3657 	if (env->log.level & BPF_LOG_LEVEL2) {
3658 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3659 		verbose(env, "mark_precise: frame%d: regs=%s ",
3660 			bt->frame, env->tmp_str_buf);
3661 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3662 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3663 		verbose(env, "%d: ", idx);
3664 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3665 	}
3666 
3667 	if (class == BPF_ALU || class == BPF_ALU64) {
3668 		if (!bt_is_reg_set(bt, dreg))
3669 			return 0;
3670 		if (opcode == BPF_END || opcode == BPF_NEG) {
3671 			/* sreg is reserved and unused
3672 			 * dreg still need precision before this insn
3673 			 */
3674 			return 0;
3675 		} else if (opcode == BPF_MOV) {
3676 			if (BPF_SRC(insn->code) == BPF_X) {
3677 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3678 				 * dreg needs precision after this insn
3679 				 * sreg needs precision before this insn
3680 				 */
3681 				bt_clear_reg(bt, dreg);
3682 				if (sreg != BPF_REG_FP)
3683 					bt_set_reg(bt, sreg);
3684 			} else {
3685 				/* dreg = K
3686 				 * dreg needs precision after this insn.
3687 				 * Corresponding register is already marked
3688 				 * as precise=true in this verifier state.
3689 				 * No further markings in parent are necessary
3690 				 */
3691 				bt_clear_reg(bt, dreg);
3692 			}
3693 		} else {
3694 			if (BPF_SRC(insn->code) == BPF_X) {
3695 				/* dreg += sreg
3696 				 * both dreg and sreg need precision
3697 				 * before this insn
3698 				 */
3699 				if (sreg != BPF_REG_FP)
3700 					bt_set_reg(bt, sreg);
3701 			} /* else dreg += K
3702 			   * dreg still needs precision before this insn
3703 			   */
3704 		}
3705 	} else if (class == BPF_LDX) {
3706 		if (!bt_is_reg_set(bt, dreg))
3707 			return 0;
3708 		bt_clear_reg(bt, dreg);
3709 
3710 		/* scalars can only be spilled into stack w/o losing precision.
3711 		 * Load from any other memory can be zero extended.
3712 		 * The desire to keep that precision is already indicated
3713 		 * by 'precise' mark in corresponding register of this state.
3714 		 * No further tracking necessary.
3715 		 */
3716 		if (insn->src_reg != BPF_REG_FP)
3717 			return 0;
3718 
3719 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3720 		 * that [fp - off] slot contains scalar that needs to be
3721 		 * tracked with precision
3722 		 */
3723 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3724 		if (spi >= 64) {
3725 			verbose(env, "BUG spi %d\n", spi);
3726 			WARN_ONCE(1, "verifier backtracking bug");
3727 			return -EFAULT;
3728 		}
3729 		bt_set_slot(bt, spi);
3730 	} else if (class == BPF_STX || class == BPF_ST) {
3731 		if (bt_is_reg_set(bt, dreg))
3732 			/* stx & st shouldn't be using _scalar_ dst_reg
3733 			 * to access memory. It means backtracking
3734 			 * encountered a case of pointer subtraction.
3735 			 */
3736 			return -ENOTSUPP;
3737 		/* scalars can only be spilled into stack */
3738 		if (insn->dst_reg != BPF_REG_FP)
3739 			return 0;
3740 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3741 		if (spi >= 64) {
3742 			verbose(env, "BUG spi %d\n", spi);
3743 			WARN_ONCE(1, "verifier backtracking bug");
3744 			return -EFAULT;
3745 		}
3746 		if (!bt_is_slot_set(bt, spi))
3747 			return 0;
3748 		bt_clear_slot(bt, spi);
3749 		if (class == BPF_STX)
3750 			bt_set_reg(bt, sreg);
3751 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3752 		if (bpf_pseudo_call(insn)) {
3753 			int subprog_insn_idx, subprog;
3754 
3755 			subprog_insn_idx = idx + insn->imm + 1;
3756 			subprog = find_subprog(env, subprog_insn_idx);
3757 			if (subprog < 0)
3758 				return -EFAULT;
3759 
3760 			if (subprog_is_global(env, subprog)) {
3761 				/* check that jump history doesn't have any
3762 				 * extra instructions from subprog; the next
3763 				 * instruction after call to global subprog
3764 				 * should be literally next instruction in
3765 				 * caller program
3766 				 */
3767 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3768 				/* r1-r5 are invalidated after subprog call,
3769 				 * so for global func call it shouldn't be set
3770 				 * anymore
3771 				 */
3772 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3773 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3774 					WARN_ONCE(1, "verifier backtracking bug");
3775 					return -EFAULT;
3776 				}
3777 				/* global subprog always sets R0 */
3778 				bt_clear_reg(bt, BPF_REG_0);
3779 				return 0;
3780 			} else {
3781 				/* static subprog call instruction, which
3782 				 * means that we are exiting current subprog,
3783 				 * so only r1-r5 could be still requested as
3784 				 * precise, r0 and r6-r10 or any stack slot in
3785 				 * the current frame should be zero by now
3786 				 */
3787 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3788 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3789 					WARN_ONCE(1, "verifier backtracking bug");
3790 					return -EFAULT;
3791 				}
3792 				/* we don't track register spills perfectly,
3793 				 * so fallback to force-precise instead of failing */
3794 				if (bt_stack_mask(bt) != 0)
3795 					return -ENOTSUPP;
3796 				/* propagate r1-r5 to the caller */
3797 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3798 					if (bt_is_reg_set(bt, i)) {
3799 						bt_clear_reg(bt, i);
3800 						bt_set_frame_reg(bt, bt->frame - 1, i);
3801 					}
3802 				}
3803 				if (bt_subprog_exit(bt))
3804 					return -EFAULT;
3805 				return 0;
3806 			}
3807 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3808 			/* exit from callback subprog to callback-calling helper or
3809 			 * kfunc call. Use idx/subseq_idx check to discern it from
3810 			 * straight line code backtracking.
3811 			 * Unlike the subprog call handling above, we shouldn't
3812 			 * propagate precision of r1-r5 (if any requested), as they are
3813 			 * not actually arguments passed directly to callback subprogs
3814 			 */
3815 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3816 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3817 				WARN_ONCE(1, "verifier backtracking bug");
3818 				return -EFAULT;
3819 			}
3820 			if (bt_stack_mask(bt) != 0)
3821 				return -ENOTSUPP;
3822 			/* clear r1-r5 in callback subprog's mask */
3823 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3824 				bt_clear_reg(bt, i);
3825 			if (bt_subprog_exit(bt))
3826 				return -EFAULT;
3827 			return 0;
3828 		} else if (opcode == BPF_CALL) {
3829 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3830 			 * catch this error later. Make backtracking conservative
3831 			 * with ENOTSUPP.
3832 			 */
3833 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3834 				return -ENOTSUPP;
3835 			/* regular helper call sets R0 */
3836 			bt_clear_reg(bt, BPF_REG_0);
3837 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3838 				/* if backtracing was looking for registers R1-R5
3839 				 * they should have been found already.
3840 				 */
3841 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3842 				WARN_ONCE(1, "verifier backtracking bug");
3843 				return -EFAULT;
3844 			}
3845 		} else if (opcode == BPF_EXIT) {
3846 			bool r0_precise;
3847 
3848 			/* Backtracking to a nested function call, 'idx' is a part of
3849 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3850 			 * In case of a regular function call, instructions giving
3851 			 * precision to registers R1-R5 should have been found already.
3852 			 * In case of a callback, it is ok to have R1-R5 marked for
3853 			 * backtracking, as these registers are set by the function
3854 			 * invoking callback.
3855 			 */
3856 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3857 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3858 					bt_clear_reg(bt, i);
3859 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3860 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3861 				WARN_ONCE(1, "verifier backtracking bug");
3862 				return -EFAULT;
3863 			}
3864 
3865 			/* BPF_EXIT in subprog or callback always returns
3866 			 * right after the call instruction, so by checking
3867 			 * whether the instruction at subseq_idx-1 is subprog
3868 			 * call or not we can distinguish actual exit from
3869 			 * *subprog* from exit from *callback*. In the former
3870 			 * case, we need to propagate r0 precision, if
3871 			 * necessary. In the former we never do that.
3872 			 */
3873 			r0_precise = subseq_idx - 1 >= 0 &&
3874 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3875 				     bt_is_reg_set(bt, BPF_REG_0);
3876 
3877 			bt_clear_reg(bt, BPF_REG_0);
3878 			if (bt_subprog_enter(bt))
3879 				return -EFAULT;
3880 
3881 			if (r0_precise)
3882 				bt_set_reg(bt, BPF_REG_0);
3883 			/* r6-r9 and stack slots will stay set in caller frame
3884 			 * bitmasks until we return back from callee(s)
3885 			 */
3886 			return 0;
3887 		} else if (BPF_SRC(insn->code) == BPF_X) {
3888 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3889 				return 0;
3890 			/* dreg <cond> sreg
3891 			 * Both dreg and sreg need precision before
3892 			 * this insn. If only sreg was marked precise
3893 			 * before it would be equally necessary to
3894 			 * propagate it to dreg.
3895 			 */
3896 			bt_set_reg(bt, dreg);
3897 			bt_set_reg(bt, sreg);
3898 			 /* else dreg <cond> K
3899 			  * Only dreg still needs precision before
3900 			  * this insn, so for the K-based conditional
3901 			  * there is nothing new to be marked.
3902 			  */
3903 		}
3904 	} else if (class == BPF_LD) {
3905 		if (!bt_is_reg_set(bt, dreg))
3906 			return 0;
3907 		bt_clear_reg(bt, dreg);
3908 		/* It's ld_imm64 or ld_abs or ld_ind.
3909 		 * For ld_imm64 no further tracking of precision
3910 		 * into parent is necessary
3911 		 */
3912 		if (mode == BPF_IND || mode == BPF_ABS)
3913 			/* to be analyzed */
3914 			return -ENOTSUPP;
3915 	}
3916 	return 0;
3917 }
3918 
3919 /* the scalar precision tracking algorithm:
3920  * . at the start all registers have precise=false.
3921  * . scalar ranges are tracked as normal through alu and jmp insns.
3922  * . once precise value of the scalar register is used in:
3923  *   .  ptr + scalar alu
3924  *   . if (scalar cond K|scalar)
3925  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3926  *   backtrack through the verifier states and mark all registers and
3927  *   stack slots with spilled constants that these scalar regisers
3928  *   should be precise.
3929  * . during state pruning two registers (or spilled stack slots)
3930  *   are equivalent if both are not precise.
3931  *
3932  * Note the verifier cannot simply walk register parentage chain,
3933  * since many different registers and stack slots could have been
3934  * used to compute single precise scalar.
3935  *
3936  * The approach of starting with precise=true for all registers and then
3937  * backtrack to mark a register as not precise when the verifier detects
3938  * that program doesn't care about specific value (e.g., when helper
3939  * takes register as ARG_ANYTHING parameter) is not safe.
3940  *
3941  * It's ok to walk single parentage chain of the verifier states.
3942  * It's possible that this backtracking will go all the way till 1st insn.
3943  * All other branches will be explored for needing precision later.
3944  *
3945  * The backtracking needs to deal with cases like:
3946  *   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)
3947  * r9 -= r8
3948  * r5 = r9
3949  * if r5 > 0x79f goto pc+7
3950  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3951  * r5 += 1
3952  * ...
3953  * call bpf_perf_event_output#25
3954  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3955  *
3956  * and this case:
3957  * r6 = 1
3958  * call foo // uses callee's r6 inside to compute r0
3959  * r0 += r6
3960  * if r0 == 0 goto
3961  *
3962  * to track above reg_mask/stack_mask needs to be independent for each frame.
3963  *
3964  * Also if parent's curframe > frame where backtracking started,
3965  * the verifier need to mark registers in both frames, otherwise callees
3966  * may incorrectly prune callers. This is similar to
3967  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3968  *
3969  * For now backtracking falls back into conservative marking.
3970  */
3971 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3972 				     struct bpf_verifier_state *st)
3973 {
3974 	struct bpf_func_state *func;
3975 	struct bpf_reg_state *reg;
3976 	int i, j;
3977 
3978 	if (env->log.level & BPF_LOG_LEVEL2) {
3979 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3980 			st->curframe);
3981 	}
3982 
3983 	/* big hammer: mark all scalars precise in this path.
3984 	 * pop_stack may still get !precise scalars.
3985 	 * We also skip current state and go straight to first parent state,
3986 	 * because precision markings in current non-checkpointed state are
3987 	 * not needed. See why in the comment in __mark_chain_precision below.
3988 	 */
3989 	for (st = st->parent; st; st = st->parent) {
3990 		for (i = 0; i <= st->curframe; i++) {
3991 			func = st->frame[i];
3992 			for (j = 0; j < BPF_REG_FP; j++) {
3993 				reg = &func->regs[j];
3994 				if (reg->type != SCALAR_VALUE || reg->precise)
3995 					continue;
3996 				reg->precise = true;
3997 				if (env->log.level & BPF_LOG_LEVEL2) {
3998 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3999 						i, j);
4000 				}
4001 			}
4002 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4003 				if (!is_spilled_reg(&func->stack[j]))
4004 					continue;
4005 				reg = &func->stack[j].spilled_ptr;
4006 				if (reg->type != SCALAR_VALUE || reg->precise)
4007 					continue;
4008 				reg->precise = true;
4009 				if (env->log.level & BPF_LOG_LEVEL2) {
4010 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4011 						i, -(j + 1) * 8);
4012 				}
4013 			}
4014 		}
4015 	}
4016 }
4017 
4018 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4019 {
4020 	struct bpf_func_state *func;
4021 	struct bpf_reg_state *reg;
4022 	int i, j;
4023 
4024 	for (i = 0; i <= st->curframe; i++) {
4025 		func = st->frame[i];
4026 		for (j = 0; j < BPF_REG_FP; j++) {
4027 			reg = &func->regs[j];
4028 			if (reg->type != SCALAR_VALUE)
4029 				continue;
4030 			reg->precise = false;
4031 		}
4032 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4033 			if (!is_spilled_reg(&func->stack[j]))
4034 				continue;
4035 			reg = &func->stack[j].spilled_ptr;
4036 			if (reg->type != SCALAR_VALUE)
4037 				continue;
4038 			reg->precise = false;
4039 		}
4040 	}
4041 }
4042 
4043 static bool idset_contains(struct bpf_idset *s, u32 id)
4044 {
4045 	u32 i;
4046 
4047 	for (i = 0; i < s->count; ++i)
4048 		if (s->ids[i] == id)
4049 			return true;
4050 
4051 	return false;
4052 }
4053 
4054 static int idset_push(struct bpf_idset *s, u32 id)
4055 {
4056 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4057 		return -EFAULT;
4058 	s->ids[s->count++] = id;
4059 	return 0;
4060 }
4061 
4062 static void idset_reset(struct bpf_idset *s)
4063 {
4064 	s->count = 0;
4065 }
4066 
4067 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4068  * Mark all registers with these IDs as precise.
4069  */
4070 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4071 {
4072 	struct bpf_idset *precise_ids = &env->idset_scratch;
4073 	struct backtrack_state *bt = &env->bt;
4074 	struct bpf_func_state *func;
4075 	struct bpf_reg_state *reg;
4076 	DECLARE_BITMAP(mask, 64);
4077 	int i, fr;
4078 
4079 	idset_reset(precise_ids);
4080 
4081 	for (fr = bt->frame; fr >= 0; fr--) {
4082 		func = st->frame[fr];
4083 
4084 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4085 		for_each_set_bit(i, mask, 32) {
4086 			reg = &func->regs[i];
4087 			if (!reg->id || reg->type != SCALAR_VALUE)
4088 				continue;
4089 			if (idset_push(precise_ids, reg->id))
4090 				return -EFAULT;
4091 		}
4092 
4093 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4094 		for_each_set_bit(i, mask, 64) {
4095 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4096 				break;
4097 			if (!is_spilled_scalar_reg(&func->stack[i]))
4098 				continue;
4099 			reg = &func->stack[i].spilled_ptr;
4100 			if (!reg->id)
4101 				continue;
4102 			if (idset_push(precise_ids, reg->id))
4103 				return -EFAULT;
4104 		}
4105 	}
4106 
4107 	for (fr = 0; fr <= st->curframe; ++fr) {
4108 		func = st->frame[fr];
4109 
4110 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4111 			reg = &func->regs[i];
4112 			if (!reg->id)
4113 				continue;
4114 			if (!idset_contains(precise_ids, reg->id))
4115 				continue;
4116 			bt_set_frame_reg(bt, fr, i);
4117 		}
4118 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4119 			if (!is_spilled_scalar_reg(&func->stack[i]))
4120 				continue;
4121 			reg = &func->stack[i].spilled_ptr;
4122 			if (!reg->id)
4123 				continue;
4124 			if (!idset_contains(precise_ids, reg->id))
4125 				continue;
4126 			bt_set_frame_slot(bt, fr, i);
4127 		}
4128 	}
4129 
4130 	return 0;
4131 }
4132 
4133 /*
4134  * __mark_chain_precision() backtracks BPF program instruction sequence and
4135  * chain of verifier states making sure that register *regno* (if regno >= 0)
4136  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4137  * SCALARS, as well as any other registers and slots that contribute to
4138  * a tracked state of given registers/stack slots, depending on specific BPF
4139  * assembly instructions (see backtrack_insns() for exact instruction handling
4140  * logic). This backtracking relies on recorded jmp_history and is able to
4141  * traverse entire chain of parent states. This process ends only when all the
4142  * necessary registers/slots and their transitive dependencies are marked as
4143  * precise.
4144  *
4145  * One important and subtle aspect is that precise marks *do not matter* in
4146  * the currently verified state (current state). It is important to understand
4147  * why this is the case.
4148  *
4149  * First, note that current state is the state that is not yet "checkpointed",
4150  * i.e., it is not yet put into env->explored_states, and it has no children
4151  * states as well. It's ephemeral, and can end up either a) being discarded if
4152  * compatible explored state is found at some point or BPF_EXIT instruction is
4153  * reached or b) checkpointed and put into env->explored_states, branching out
4154  * into one or more children states.
4155  *
4156  * In the former case, precise markings in current state are completely
4157  * ignored by state comparison code (see regsafe() for details). Only
4158  * checkpointed ("old") state precise markings are important, and if old
4159  * state's register/slot is precise, regsafe() assumes current state's
4160  * register/slot as precise and checks value ranges exactly and precisely. If
4161  * states turn out to be compatible, current state's necessary precise
4162  * markings and any required parent states' precise markings are enforced
4163  * after the fact with propagate_precision() logic, after the fact. But it's
4164  * important to realize that in this case, even after marking current state
4165  * registers/slots as precise, we immediately discard current state. So what
4166  * actually matters is any of the precise markings propagated into current
4167  * state's parent states, which are always checkpointed (due to b) case above).
4168  * As such, for scenario a) it doesn't matter if current state has precise
4169  * markings set or not.
4170  *
4171  * Now, for the scenario b), checkpointing and forking into child(ren)
4172  * state(s). Note that before current state gets to checkpointing step, any
4173  * processed instruction always assumes precise SCALAR register/slot
4174  * knowledge: if precise value or range is useful to prune jump branch, BPF
4175  * verifier takes this opportunity enthusiastically. Similarly, when
4176  * register's value is used to calculate offset or memory address, exact
4177  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4178  * what we mentioned above about state comparison ignoring precise markings
4179  * during state comparison, BPF verifier ignores and also assumes precise
4180  * markings *at will* during instruction verification process. But as verifier
4181  * assumes precision, it also propagates any precision dependencies across
4182  * parent states, which are not yet finalized, so can be further restricted
4183  * based on new knowledge gained from restrictions enforced by their children
4184  * states. This is so that once those parent states are finalized, i.e., when
4185  * they have no more active children state, state comparison logic in
4186  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4187  * required for correctness.
4188  *
4189  * To build a bit more intuition, note also that once a state is checkpointed,
4190  * the path we took to get to that state is not important. This is crucial
4191  * property for state pruning. When state is checkpointed and finalized at
4192  * some instruction index, it can be correctly and safely used to "short
4193  * circuit" any *compatible* state that reaches exactly the same instruction
4194  * index. I.e., if we jumped to that instruction from a completely different
4195  * code path than original finalized state was derived from, it doesn't
4196  * matter, current state can be discarded because from that instruction
4197  * forward having a compatible state will ensure we will safely reach the
4198  * exit. States describe preconditions for further exploration, but completely
4199  * forget the history of how we got here.
4200  *
4201  * This also means that even if we needed precise SCALAR range to get to
4202  * finalized state, but from that point forward *that same* SCALAR register is
4203  * never used in a precise context (i.e., it's precise value is not needed for
4204  * correctness), it's correct and safe to mark such register as "imprecise"
4205  * (i.e., precise marking set to false). This is what we rely on when we do
4206  * not set precise marking in current state. If no child state requires
4207  * precision for any given SCALAR register, it's safe to dictate that it can
4208  * be imprecise. If any child state does require this register to be precise,
4209  * we'll mark it precise later retroactively during precise markings
4210  * propagation from child state to parent states.
4211  *
4212  * Skipping precise marking setting in current state is a mild version of
4213  * relying on the above observation. But we can utilize this property even
4214  * more aggressively by proactively forgetting any precise marking in the
4215  * current state (which we inherited from the parent state), right before we
4216  * checkpoint it and branch off into new child state. This is done by
4217  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4218  * finalized states which help in short circuiting more future states.
4219  */
4220 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4221 {
4222 	struct backtrack_state *bt = &env->bt;
4223 	struct bpf_verifier_state *st = env->cur_state;
4224 	int first_idx = st->first_insn_idx;
4225 	int last_idx = env->insn_idx;
4226 	int subseq_idx = -1;
4227 	struct bpf_func_state *func;
4228 	struct bpf_reg_state *reg;
4229 	bool skip_first = true;
4230 	int i, fr, err;
4231 
4232 	if (!env->bpf_capable)
4233 		return 0;
4234 
4235 	/* set frame number from which we are starting to backtrack */
4236 	bt_init(bt, env->cur_state->curframe);
4237 
4238 	/* Do sanity checks against current state of register and/or stack
4239 	 * slot, but don't set precise flag in current state, as precision
4240 	 * tracking in the current state is unnecessary.
4241 	 */
4242 	func = st->frame[bt->frame];
4243 	if (regno >= 0) {
4244 		reg = &func->regs[regno];
4245 		if (reg->type != SCALAR_VALUE) {
4246 			WARN_ONCE(1, "backtracing misuse");
4247 			return -EFAULT;
4248 		}
4249 		bt_set_reg(bt, regno);
4250 	}
4251 
4252 	if (bt_empty(bt))
4253 		return 0;
4254 
4255 	for (;;) {
4256 		DECLARE_BITMAP(mask, 64);
4257 		u32 history = st->jmp_history_cnt;
4258 
4259 		if (env->log.level & BPF_LOG_LEVEL2) {
4260 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4261 				bt->frame, last_idx, first_idx, subseq_idx);
4262 		}
4263 
4264 		/* If some register with scalar ID is marked as precise,
4265 		 * make sure that all registers sharing this ID are also precise.
4266 		 * This is needed to estimate effect of find_equal_scalars().
4267 		 * Do this at the last instruction of each state,
4268 		 * bpf_reg_state::id fields are valid for these instructions.
4269 		 *
4270 		 * Allows to track precision in situation like below:
4271 		 *
4272 		 *     r2 = unknown value
4273 		 *     ...
4274 		 *   --- state #0 ---
4275 		 *     ...
4276 		 *     r1 = r2                 // r1 and r2 now share the same ID
4277 		 *     ...
4278 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4279 		 *     ...
4280 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4281 		 *     ...
4282 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4283 		 *     r3 = r10
4284 		 *     r3 += r1                // need to mark both r1 and r2
4285 		 */
4286 		if (mark_precise_scalar_ids(env, st))
4287 			return -EFAULT;
4288 
4289 		if (last_idx < 0) {
4290 			/* we are at the entry into subprog, which
4291 			 * is expected for global funcs, but only if
4292 			 * requested precise registers are R1-R5
4293 			 * (which are global func's input arguments)
4294 			 */
4295 			if (st->curframe == 0 &&
4296 			    st->frame[0]->subprogno > 0 &&
4297 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4298 			    bt_stack_mask(bt) == 0 &&
4299 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4300 				bitmap_from_u64(mask, bt_reg_mask(bt));
4301 				for_each_set_bit(i, mask, 32) {
4302 					reg = &st->frame[0]->regs[i];
4303 					bt_clear_reg(bt, i);
4304 					if (reg->type == SCALAR_VALUE)
4305 						reg->precise = true;
4306 				}
4307 				return 0;
4308 			}
4309 
4310 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4311 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4312 			WARN_ONCE(1, "verifier backtracking bug");
4313 			return -EFAULT;
4314 		}
4315 
4316 		for (i = last_idx;;) {
4317 			if (skip_first) {
4318 				err = 0;
4319 				skip_first = false;
4320 			} else {
4321 				err = backtrack_insn(env, i, subseq_idx, bt);
4322 			}
4323 			if (err == -ENOTSUPP) {
4324 				mark_all_scalars_precise(env, env->cur_state);
4325 				bt_reset(bt);
4326 				return 0;
4327 			} else if (err) {
4328 				return err;
4329 			}
4330 			if (bt_empty(bt))
4331 				/* Found assignment(s) into tracked register in this state.
4332 				 * Since this state is already marked, just return.
4333 				 * Nothing to be tracked further in the parent state.
4334 				 */
4335 				return 0;
4336 			subseq_idx = i;
4337 			i = get_prev_insn_idx(st, i, &history);
4338 			if (i == -ENOENT)
4339 				break;
4340 			if (i >= env->prog->len) {
4341 				/* This can happen if backtracking reached insn 0
4342 				 * and there are still reg_mask or stack_mask
4343 				 * to backtrack.
4344 				 * It means the backtracking missed the spot where
4345 				 * particular register was initialized with a constant.
4346 				 */
4347 				verbose(env, "BUG backtracking idx %d\n", i);
4348 				WARN_ONCE(1, "verifier backtracking bug");
4349 				return -EFAULT;
4350 			}
4351 		}
4352 		st = st->parent;
4353 		if (!st)
4354 			break;
4355 
4356 		for (fr = bt->frame; fr >= 0; fr--) {
4357 			func = st->frame[fr];
4358 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4359 			for_each_set_bit(i, mask, 32) {
4360 				reg = &func->regs[i];
4361 				if (reg->type != SCALAR_VALUE) {
4362 					bt_clear_frame_reg(bt, fr, i);
4363 					continue;
4364 				}
4365 				if (reg->precise)
4366 					bt_clear_frame_reg(bt, fr, i);
4367 				else
4368 					reg->precise = true;
4369 			}
4370 
4371 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4372 			for_each_set_bit(i, mask, 64) {
4373 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4374 					/* the sequence of instructions:
4375 					 * 2: (bf) r3 = r10
4376 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4377 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4378 					 * doesn't contain jmps. It's backtracked
4379 					 * as a single block.
4380 					 * During backtracking insn 3 is not recognized as
4381 					 * stack access, so at the end of backtracking
4382 					 * stack slot fp-8 is still marked in stack_mask.
4383 					 * However the parent state may not have accessed
4384 					 * fp-8 and it's "unallocated" stack space.
4385 					 * In such case fallback to conservative.
4386 					 */
4387 					mark_all_scalars_precise(env, env->cur_state);
4388 					bt_reset(bt);
4389 					return 0;
4390 				}
4391 
4392 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4393 					bt_clear_frame_slot(bt, fr, i);
4394 					continue;
4395 				}
4396 				reg = &func->stack[i].spilled_ptr;
4397 				if (reg->precise)
4398 					bt_clear_frame_slot(bt, fr, i);
4399 				else
4400 					reg->precise = true;
4401 			}
4402 			if (env->log.level & BPF_LOG_LEVEL2) {
4403 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4404 					     bt_frame_reg_mask(bt, fr));
4405 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4406 					fr, env->tmp_str_buf);
4407 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4408 					       bt_frame_stack_mask(bt, fr));
4409 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4410 				print_verifier_state(env, func, true);
4411 			}
4412 		}
4413 
4414 		if (bt_empty(bt))
4415 			return 0;
4416 
4417 		subseq_idx = first_idx;
4418 		last_idx = st->last_insn_idx;
4419 		first_idx = st->first_insn_idx;
4420 	}
4421 
4422 	/* if we still have requested precise regs or slots, we missed
4423 	 * something (e.g., stack access through non-r10 register), so
4424 	 * fallback to marking all precise
4425 	 */
4426 	if (!bt_empty(bt)) {
4427 		mark_all_scalars_precise(env, env->cur_state);
4428 		bt_reset(bt);
4429 	}
4430 
4431 	return 0;
4432 }
4433 
4434 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4435 {
4436 	return __mark_chain_precision(env, regno);
4437 }
4438 
4439 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4440  * desired reg and stack masks across all relevant frames
4441  */
4442 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4443 {
4444 	return __mark_chain_precision(env, -1);
4445 }
4446 
4447 static bool is_spillable_regtype(enum bpf_reg_type type)
4448 {
4449 	switch (base_type(type)) {
4450 	case PTR_TO_MAP_VALUE:
4451 	case PTR_TO_STACK:
4452 	case PTR_TO_CTX:
4453 	case PTR_TO_PACKET:
4454 	case PTR_TO_PACKET_META:
4455 	case PTR_TO_PACKET_END:
4456 	case PTR_TO_FLOW_KEYS:
4457 	case CONST_PTR_TO_MAP:
4458 	case PTR_TO_SOCKET:
4459 	case PTR_TO_SOCK_COMMON:
4460 	case PTR_TO_TCP_SOCK:
4461 	case PTR_TO_XDP_SOCK:
4462 	case PTR_TO_BTF_ID:
4463 	case PTR_TO_BUF:
4464 	case PTR_TO_MEM:
4465 	case PTR_TO_FUNC:
4466 	case PTR_TO_MAP_KEY:
4467 		return true;
4468 	default:
4469 		return false;
4470 	}
4471 }
4472 
4473 /* Does this register contain a constant zero? */
4474 static bool register_is_null(struct bpf_reg_state *reg)
4475 {
4476 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4477 }
4478 
4479 static bool register_is_const(struct bpf_reg_state *reg)
4480 {
4481 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4482 }
4483 
4484 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4485 {
4486 	return tnum_is_unknown(reg->var_off) &&
4487 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4488 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4489 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4490 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4491 }
4492 
4493 static bool register_is_bounded(struct bpf_reg_state *reg)
4494 {
4495 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4496 }
4497 
4498 static bool __is_pointer_value(bool allow_ptr_leaks,
4499 			       const struct bpf_reg_state *reg)
4500 {
4501 	if (allow_ptr_leaks)
4502 		return false;
4503 
4504 	return reg->type != SCALAR_VALUE;
4505 }
4506 
4507 /* Copy src state preserving dst->parent and dst->live fields */
4508 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4509 {
4510 	struct bpf_reg_state *parent = dst->parent;
4511 	enum bpf_reg_liveness live = dst->live;
4512 
4513 	*dst = *src;
4514 	dst->parent = parent;
4515 	dst->live = live;
4516 }
4517 
4518 static void save_register_state(struct bpf_func_state *state,
4519 				int spi, struct bpf_reg_state *reg,
4520 				int size)
4521 {
4522 	int i;
4523 
4524 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4525 	if (size == BPF_REG_SIZE)
4526 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4527 
4528 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4529 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4530 
4531 	/* size < 8 bytes spill */
4532 	for (; i; i--)
4533 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4534 }
4535 
4536 static bool is_bpf_st_mem(struct bpf_insn *insn)
4537 {
4538 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4539 }
4540 
4541 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4542  * stack boundary and alignment are checked in check_mem_access()
4543  */
4544 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4545 				       /* stack frame we're writing to */
4546 				       struct bpf_func_state *state,
4547 				       int off, int size, int value_regno,
4548 				       int insn_idx)
4549 {
4550 	struct bpf_func_state *cur; /* state of the current function */
4551 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4552 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4553 	struct bpf_reg_state *reg = NULL;
4554 	u32 dst_reg = insn->dst_reg;
4555 
4556 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4557 	 * so it's aligned access and [off, off + size) are within stack limits
4558 	 */
4559 	if (!env->allow_ptr_leaks &&
4560 	    is_spilled_reg(&state->stack[spi]) &&
4561 	    size != BPF_REG_SIZE) {
4562 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4563 		return -EACCES;
4564 	}
4565 
4566 	cur = env->cur_state->frame[env->cur_state->curframe];
4567 	if (value_regno >= 0)
4568 		reg = &cur->regs[value_regno];
4569 	if (!env->bypass_spec_v4) {
4570 		bool sanitize = reg && is_spillable_regtype(reg->type);
4571 
4572 		for (i = 0; i < size; i++) {
4573 			u8 type = state->stack[spi].slot_type[i];
4574 
4575 			if (type != STACK_MISC && type != STACK_ZERO) {
4576 				sanitize = true;
4577 				break;
4578 			}
4579 		}
4580 
4581 		if (sanitize)
4582 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4583 	}
4584 
4585 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4586 	if (err)
4587 		return err;
4588 
4589 	mark_stack_slot_scratched(env, spi);
4590 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4591 	    !register_is_null(reg) && env->bpf_capable) {
4592 		if (dst_reg != BPF_REG_FP) {
4593 			/* The backtracking logic can only recognize explicit
4594 			 * stack slot address like [fp - 8]. Other spill of
4595 			 * scalar via different register has to be conservative.
4596 			 * Backtrack from here and mark all registers as precise
4597 			 * that contributed into 'reg' being a constant.
4598 			 */
4599 			err = mark_chain_precision(env, value_regno);
4600 			if (err)
4601 				return err;
4602 		}
4603 		save_register_state(state, spi, reg, size);
4604 		/* Break the relation on a narrowing spill. */
4605 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4606 			state->stack[spi].spilled_ptr.id = 0;
4607 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4608 		   insn->imm != 0 && env->bpf_capable) {
4609 		struct bpf_reg_state fake_reg = {};
4610 
4611 		__mark_reg_known(&fake_reg, insn->imm);
4612 		fake_reg.type = SCALAR_VALUE;
4613 		save_register_state(state, spi, &fake_reg, size);
4614 	} else if (reg && is_spillable_regtype(reg->type)) {
4615 		/* register containing pointer is being spilled into stack */
4616 		if (size != BPF_REG_SIZE) {
4617 			verbose_linfo(env, insn_idx, "; ");
4618 			verbose(env, "invalid size of register spill\n");
4619 			return -EACCES;
4620 		}
4621 		if (state != cur && reg->type == PTR_TO_STACK) {
4622 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4623 			return -EINVAL;
4624 		}
4625 		save_register_state(state, spi, reg, size);
4626 	} else {
4627 		u8 type = STACK_MISC;
4628 
4629 		/* regular write of data into stack destroys any spilled ptr */
4630 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4631 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4632 		if (is_stack_slot_special(&state->stack[spi]))
4633 			for (i = 0; i < BPF_REG_SIZE; i++)
4634 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4635 
4636 		/* only mark the slot as written if all 8 bytes were written
4637 		 * otherwise read propagation may incorrectly stop too soon
4638 		 * when stack slots are partially written.
4639 		 * This heuristic means that read propagation will be
4640 		 * conservative, since it will add reg_live_read marks
4641 		 * to stack slots all the way to first state when programs
4642 		 * writes+reads less than 8 bytes
4643 		 */
4644 		if (size == BPF_REG_SIZE)
4645 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4646 
4647 		/* when we zero initialize stack slots mark them as such */
4648 		if ((reg && register_is_null(reg)) ||
4649 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4650 			/* backtracking doesn't work for STACK_ZERO yet. */
4651 			err = mark_chain_precision(env, value_regno);
4652 			if (err)
4653 				return err;
4654 			type = STACK_ZERO;
4655 		}
4656 
4657 		/* Mark slots affected by this stack write. */
4658 		for (i = 0; i < size; i++)
4659 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4660 				type;
4661 	}
4662 	return 0;
4663 }
4664 
4665 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4666  * known to contain a variable offset.
4667  * This function checks whether the write is permitted and conservatively
4668  * tracks the effects of the write, considering that each stack slot in the
4669  * dynamic range is potentially written to.
4670  *
4671  * 'off' includes 'regno->off'.
4672  * 'value_regno' can be -1, meaning that an unknown value is being written to
4673  * the stack.
4674  *
4675  * Spilled pointers in range are not marked as written because we don't know
4676  * what's going to be actually written. This means that read propagation for
4677  * future reads cannot be terminated by this write.
4678  *
4679  * For privileged programs, uninitialized stack slots are considered
4680  * initialized by this write (even though we don't know exactly what offsets
4681  * are going to be written to). The idea is that we don't want the verifier to
4682  * reject future reads that access slots written to through variable offsets.
4683  */
4684 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4685 				     /* func where register points to */
4686 				     struct bpf_func_state *state,
4687 				     int ptr_regno, int off, int size,
4688 				     int value_regno, int insn_idx)
4689 {
4690 	struct bpf_func_state *cur; /* state of the current function */
4691 	int min_off, max_off;
4692 	int i, err;
4693 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4694 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4695 	bool writing_zero = false;
4696 	/* set if the fact that we're writing a zero is used to let any
4697 	 * stack slots remain STACK_ZERO
4698 	 */
4699 	bool zero_used = false;
4700 
4701 	cur = env->cur_state->frame[env->cur_state->curframe];
4702 	ptr_reg = &cur->regs[ptr_regno];
4703 	min_off = ptr_reg->smin_value + off;
4704 	max_off = ptr_reg->smax_value + off + size;
4705 	if (value_regno >= 0)
4706 		value_reg = &cur->regs[value_regno];
4707 	if ((value_reg && register_is_null(value_reg)) ||
4708 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4709 		writing_zero = true;
4710 
4711 	for (i = min_off; i < max_off; i++) {
4712 		int spi;
4713 
4714 		spi = __get_spi(i);
4715 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4716 		if (err)
4717 			return err;
4718 	}
4719 
4720 	/* Variable offset writes destroy any spilled pointers in range. */
4721 	for (i = min_off; i < max_off; i++) {
4722 		u8 new_type, *stype;
4723 		int slot, spi;
4724 
4725 		slot = -i - 1;
4726 		spi = slot / BPF_REG_SIZE;
4727 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4728 		mark_stack_slot_scratched(env, spi);
4729 
4730 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4731 			/* Reject the write if range we may write to has not
4732 			 * been initialized beforehand. If we didn't reject
4733 			 * here, the ptr status would be erased below (even
4734 			 * though not all slots are actually overwritten),
4735 			 * possibly opening the door to leaks.
4736 			 *
4737 			 * We do however catch STACK_INVALID case below, and
4738 			 * only allow reading possibly uninitialized memory
4739 			 * later for CAP_PERFMON, as the write may not happen to
4740 			 * that slot.
4741 			 */
4742 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4743 				insn_idx, i);
4744 			return -EINVAL;
4745 		}
4746 
4747 		/* Erase all spilled pointers. */
4748 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4749 
4750 		/* Update the slot type. */
4751 		new_type = STACK_MISC;
4752 		if (writing_zero && *stype == STACK_ZERO) {
4753 			new_type = STACK_ZERO;
4754 			zero_used = true;
4755 		}
4756 		/* If the slot is STACK_INVALID, we check whether it's OK to
4757 		 * pretend that it will be initialized by this write. The slot
4758 		 * might not actually be written to, and so if we mark it as
4759 		 * initialized future reads might leak uninitialized memory.
4760 		 * For privileged programs, we will accept such reads to slots
4761 		 * that may or may not be written because, if we're reject
4762 		 * them, the error would be too confusing.
4763 		 */
4764 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4765 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4766 					insn_idx, i);
4767 			return -EINVAL;
4768 		}
4769 		*stype = new_type;
4770 	}
4771 	if (zero_used) {
4772 		/* backtracking doesn't work for STACK_ZERO yet. */
4773 		err = mark_chain_precision(env, value_regno);
4774 		if (err)
4775 			return err;
4776 	}
4777 	return 0;
4778 }
4779 
4780 /* When register 'dst_regno' is assigned some values from stack[min_off,
4781  * max_off), we set the register's type according to the types of the
4782  * respective stack slots. If all the stack values are known to be zeros, then
4783  * so is the destination reg. Otherwise, the register is considered to be
4784  * SCALAR. This function does not deal with register filling; the caller must
4785  * ensure that all spilled registers in the stack range have been marked as
4786  * read.
4787  */
4788 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4789 				/* func where src register points to */
4790 				struct bpf_func_state *ptr_state,
4791 				int min_off, int max_off, int dst_regno)
4792 {
4793 	struct bpf_verifier_state *vstate = env->cur_state;
4794 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4795 	int i, slot, spi;
4796 	u8 *stype;
4797 	int zeros = 0;
4798 
4799 	for (i = min_off; i < max_off; i++) {
4800 		slot = -i - 1;
4801 		spi = slot / BPF_REG_SIZE;
4802 		mark_stack_slot_scratched(env, spi);
4803 		stype = ptr_state->stack[spi].slot_type;
4804 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4805 			break;
4806 		zeros++;
4807 	}
4808 	if (zeros == max_off - min_off) {
4809 		/* any access_size read into register is zero extended,
4810 		 * so the whole register == const_zero
4811 		 */
4812 		__mark_reg_const_zero(&state->regs[dst_regno]);
4813 		/* backtracking doesn't support STACK_ZERO yet,
4814 		 * so mark it precise here, so that later
4815 		 * backtracking can stop here.
4816 		 * Backtracking may not need this if this register
4817 		 * doesn't participate in pointer adjustment.
4818 		 * Forward propagation of precise flag is not
4819 		 * necessary either. This mark is only to stop
4820 		 * backtracking. Any register that contributed
4821 		 * to const 0 was marked precise before spill.
4822 		 */
4823 		state->regs[dst_regno].precise = true;
4824 	} else {
4825 		/* have read misc data from the stack */
4826 		mark_reg_unknown(env, state->regs, dst_regno);
4827 	}
4828 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4829 }
4830 
4831 /* Read the stack at 'off' and put the results into the register indicated by
4832  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4833  * spilled reg.
4834  *
4835  * 'dst_regno' can be -1, meaning that the read value is not going to a
4836  * register.
4837  *
4838  * The access is assumed to be within the current stack bounds.
4839  */
4840 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4841 				      /* func where src register points to */
4842 				      struct bpf_func_state *reg_state,
4843 				      int off, int size, int dst_regno)
4844 {
4845 	struct bpf_verifier_state *vstate = env->cur_state;
4846 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4847 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4848 	struct bpf_reg_state *reg;
4849 	u8 *stype, type;
4850 
4851 	stype = reg_state->stack[spi].slot_type;
4852 	reg = &reg_state->stack[spi].spilled_ptr;
4853 
4854 	mark_stack_slot_scratched(env, spi);
4855 
4856 	if (is_spilled_reg(&reg_state->stack[spi])) {
4857 		u8 spill_size = 1;
4858 
4859 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4860 			spill_size++;
4861 
4862 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4863 			if (reg->type != SCALAR_VALUE) {
4864 				verbose_linfo(env, env->insn_idx, "; ");
4865 				verbose(env, "invalid size of register fill\n");
4866 				return -EACCES;
4867 			}
4868 
4869 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4870 			if (dst_regno < 0)
4871 				return 0;
4872 
4873 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4874 				/* The earlier check_reg_arg() has decided the
4875 				 * subreg_def for this insn.  Save it first.
4876 				 */
4877 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4878 
4879 				copy_register_state(&state->regs[dst_regno], reg);
4880 				state->regs[dst_regno].subreg_def = subreg_def;
4881 			} else {
4882 				for (i = 0; i < size; i++) {
4883 					type = stype[(slot - i) % BPF_REG_SIZE];
4884 					if (type == STACK_SPILL)
4885 						continue;
4886 					if (type == STACK_MISC)
4887 						continue;
4888 					if (type == STACK_INVALID && env->allow_uninit_stack)
4889 						continue;
4890 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4891 						off, i, size);
4892 					return -EACCES;
4893 				}
4894 				mark_reg_unknown(env, state->regs, dst_regno);
4895 			}
4896 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4897 			return 0;
4898 		}
4899 
4900 		if (dst_regno >= 0) {
4901 			/* restore register state from stack */
4902 			copy_register_state(&state->regs[dst_regno], reg);
4903 			/* mark reg as written since spilled pointer state likely
4904 			 * has its liveness marks cleared by is_state_visited()
4905 			 * which resets stack/reg liveness for state transitions
4906 			 */
4907 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4908 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4909 			/* If dst_regno==-1, the caller is asking us whether
4910 			 * it is acceptable to use this value as a SCALAR_VALUE
4911 			 * (e.g. for XADD).
4912 			 * We must not allow unprivileged callers to do that
4913 			 * with spilled pointers.
4914 			 */
4915 			verbose(env, "leaking pointer from stack off %d\n",
4916 				off);
4917 			return -EACCES;
4918 		}
4919 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4920 	} else {
4921 		for (i = 0; i < size; i++) {
4922 			type = stype[(slot - i) % BPF_REG_SIZE];
4923 			if (type == STACK_MISC)
4924 				continue;
4925 			if (type == STACK_ZERO)
4926 				continue;
4927 			if (type == STACK_INVALID && env->allow_uninit_stack)
4928 				continue;
4929 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4930 				off, i, size);
4931 			return -EACCES;
4932 		}
4933 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4934 		if (dst_regno >= 0)
4935 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4936 	}
4937 	return 0;
4938 }
4939 
4940 enum bpf_access_src {
4941 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4942 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4943 };
4944 
4945 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4946 					 int regno, int off, int access_size,
4947 					 bool zero_size_allowed,
4948 					 enum bpf_access_src type,
4949 					 struct bpf_call_arg_meta *meta);
4950 
4951 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4952 {
4953 	return cur_regs(env) + regno;
4954 }
4955 
4956 /* Read the stack at 'ptr_regno + off' and put the result into the register
4957  * 'dst_regno'.
4958  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4959  * but not its variable offset.
4960  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4961  *
4962  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4963  * filling registers (i.e. reads of spilled register cannot be detected when
4964  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4965  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4966  * offset; for a fixed offset check_stack_read_fixed_off should be used
4967  * instead.
4968  */
4969 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4970 				    int ptr_regno, int off, int size, int dst_regno)
4971 {
4972 	/* The state of the source register. */
4973 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4974 	struct bpf_func_state *ptr_state = func(env, reg);
4975 	int err;
4976 	int min_off, max_off;
4977 
4978 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4979 	 */
4980 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4981 					    false, ACCESS_DIRECT, NULL);
4982 	if (err)
4983 		return err;
4984 
4985 	min_off = reg->smin_value + off;
4986 	max_off = reg->smax_value + off;
4987 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4988 	return 0;
4989 }
4990 
4991 /* check_stack_read dispatches to check_stack_read_fixed_off or
4992  * check_stack_read_var_off.
4993  *
4994  * The caller must ensure that the offset falls within the allocated stack
4995  * bounds.
4996  *
4997  * 'dst_regno' is a register which will receive the value from the stack. It
4998  * can be -1, meaning that the read value is not going to a register.
4999  */
5000 static int check_stack_read(struct bpf_verifier_env *env,
5001 			    int ptr_regno, int off, int size,
5002 			    int dst_regno)
5003 {
5004 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5005 	struct bpf_func_state *state = func(env, reg);
5006 	int err;
5007 	/* Some accesses are only permitted with a static offset. */
5008 	bool var_off = !tnum_is_const(reg->var_off);
5009 
5010 	/* The offset is required to be static when reads don't go to a
5011 	 * register, in order to not leak pointers (see
5012 	 * check_stack_read_fixed_off).
5013 	 */
5014 	if (dst_regno < 0 && var_off) {
5015 		char tn_buf[48];
5016 
5017 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5018 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5019 			tn_buf, off, size);
5020 		return -EACCES;
5021 	}
5022 	/* Variable offset is prohibited for unprivileged mode for simplicity
5023 	 * since it requires corresponding support in Spectre masking for stack
5024 	 * ALU. See also retrieve_ptr_limit(). The check in
5025 	 * check_stack_access_for_ptr_arithmetic() called by
5026 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5027 	 * with variable offsets, therefore no check is required here. Further,
5028 	 * just checking it here would be insufficient as speculative stack
5029 	 * writes could still lead to unsafe speculative behaviour.
5030 	 */
5031 	if (!var_off) {
5032 		off += reg->var_off.value;
5033 		err = check_stack_read_fixed_off(env, state, off, size,
5034 						 dst_regno);
5035 	} else {
5036 		/* Variable offset stack reads need more conservative handling
5037 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5038 		 * branch.
5039 		 */
5040 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5041 					       dst_regno);
5042 	}
5043 	return err;
5044 }
5045 
5046 
5047 /* check_stack_write dispatches to check_stack_write_fixed_off or
5048  * check_stack_write_var_off.
5049  *
5050  * 'ptr_regno' is the register used as a pointer into the stack.
5051  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5052  * 'value_regno' is the register whose value we're writing to the stack. It can
5053  * be -1, meaning that we're not writing from a register.
5054  *
5055  * The caller must ensure that the offset falls within the maximum stack size.
5056  */
5057 static int check_stack_write(struct bpf_verifier_env *env,
5058 			     int ptr_regno, int off, int size,
5059 			     int value_regno, int insn_idx)
5060 {
5061 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5062 	struct bpf_func_state *state = func(env, reg);
5063 	int err;
5064 
5065 	if (tnum_is_const(reg->var_off)) {
5066 		off += reg->var_off.value;
5067 		err = check_stack_write_fixed_off(env, state, off, size,
5068 						  value_regno, insn_idx);
5069 	} else {
5070 		/* Variable offset stack reads need more conservative handling
5071 		 * than fixed offset ones.
5072 		 */
5073 		err = check_stack_write_var_off(env, state,
5074 						ptr_regno, off, size,
5075 						value_regno, insn_idx);
5076 	}
5077 	return err;
5078 }
5079 
5080 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5081 				 int off, int size, enum bpf_access_type type)
5082 {
5083 	struct bpf_reg_state *regs = cur_regs(env);
5084 	struct bpf_map *map = regs[regno].map_ptr;
5085 	u32 cap = bpf_map_flags_to_cap(map);
5086 
5087 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5088 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5089 			map->value_size, off, size);
5090 		return -EACCES;
5091 	}
5092 
5093 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5094 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5095 			map->value_size, off, size);
5096 		return -EACCES;
5097 	}
5098 
5099 	return 0;
5100 }
5101 
5102 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5103 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5104 			      int off, int size, u32 mem_size,
5105 			      bool zero_size_allowed)
5106 {
5107 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5108 	struct bpf_reg_state *reg;
5109 
5110 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5111 		return 0;
5112 
5113 	reg = &cur_regs(env)[regno];
5114 	switch (reg->type) {
5115 	case PTR_TO_MAP_KEY:
5116 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5117 			mem_size, off, size);
5118 		break;
5119 	case PTR_TO_MAP_VALUE:
5120 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5121 			mem_size, off, size);
5122 		break;
5123 	case PTR_TO_PACKET:
5124 	case PTR_TO_PACKET_META:
5125 	case PTR_TO_PACKET_END:
5126 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5127 			off, size, regno, reg->id, off, mem_size);
5128 		break;
5129 	case PTR_TO_MEM:
5130 	default:
5131 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5132 			mem_size, off, size);
5133 	}
5134 
5135 	return -EACCES;
5136 }
5137 
5138 /* check read/write into a memory region with possible variable offset */
5139 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5140 				   int off, int size, u32 mem_size,
5141 				   bool zero_size_allowed)
5142 {
5143 	struct bpf_verifier_state *vstate = env->cur_state;
5144 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5145 	struct bpf_reg_state *reg = &state->regs[regno];
5146 	int err;
5147 
5148 	/* We may have adjusted the register pointing to memory region, so we
5149 	 * need to try adding each of min_value and max_value to off
5150 	 * to make sure our theoretical access will be safe.
5151 	 *
5152 	 * The minimum value is only important with signed
5153 	 * comparisons where we can't assume the floor of a
5154 	 * value is 0.  If we are using signed variables for our
5155 	 * index'es we need to make sure that whatever we use
5156 	 * will have a set floor within our range.
5157 	 */
5158 	if (reg->smin_value < 0 &&
5159 	    (reg->smin_value == S64_MIN ||
5160 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5161 	      reg->smin_value + off < 0)) {
5162 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5163 			regno);
5164 		return -EACCES;
5165 	}
5166 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5167 				 mem_size, zero_size_allowed);
5168 	if (err) {
5169 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5170 			regno);
5171 		return err;
5172 	}
5173 
5174 	/* If we haven't set a max value then we need to bail since we can't be
5175 	 * sure we won't do bad things.
5176 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5177 	 */
5178 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5179 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5180 			regno);
5181 		return -EACCES;
5182 	}
5183 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5184 				 mem_size, zero_size_allowed);
5185 	if (err) {
5186 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5187 			regno);
5188 		return err;
5189 	}
5190 
5191 	return 0;
5192 }
5193 
5194 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5195 			       const struct bpf_reg_state *reg, int regno,
5196 			       bool fixed_off_ok)
5197 {
5198 	/* Access to this pointer-typed register or passing it to a helper
5199 	 * is only allowed in its original, unmodified form.
5200 	 */
5201 
5202 	if (reg->off < 0) {
5203 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5204 			reg_type_str(env, reg->type), regno, reg->off);
5205 		return -EACCES;
5206 	}
5207 
5208 	if (!fixed_off_ok && reg->off) {
5209 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5210 			reg_type_str(env, reg->type), regno, reg->off);
5211 		return -EACCES;
5212 	}
5213 
5214 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5215 		char tn_buf[48];
5216 
5217 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5218 		verbose(env, "variable %s access var_off=%s disallowed\n",
5219 			reg_type_str(env, reg->type), tn_buf);
5220 		return -EACCES;
5221 	}
5222 
5223 	return 0;
5224 }
5225 
5226 int check_ptr_off_reg(struct bpf_verifier_env *env,
5227 		      const struct bpf_reg_state *reg, int regno)
5228 {
5229 	return __check_ptr_off_reg(env, reg, regno, false);
5230 }
5231 
5232 static int map_kptr_match_type(struct bpf_verifier_env *env,
5233 			       struct btf_field *kptr_field,
5234 			       struct bpf_reg_state *reg, u32 regno)
5235 {
5236 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5237 	int perm_flags;
5238 	const char *reg_name = "";
5239 
5240 	if (btf_is_kernel(reg->btf)) {
5241 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5242 
5243 		/* Only unreferenced case accepts untrusted pointers */
5244 		if (kptr_field->type == BPF_KPTR_UNREF)
5245 			perm_flags |= PTR_UNTRUSTED;
5246 	} else {
5247 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5248 	}
5249 
5250 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5251 		goto bad_type;
5252 
5253 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5254 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5255 
5256 	/* For ref_ptr case, release function check should ensure we get one
5257 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5258 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5259 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5260 	 * reg->off and reg->ref_obj_id are not needed here.
5261 	 */
5262 	if (__check_ptr_off_reg(env, reg, regno, true))
5263 		return -EACCES;
5264 
5265 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5266 	 * we also need to take into account the reg->off.
5267 	 *
5268 	 * We want to support cases like:
5269 	 *
5270 	 * struct foo {
5271 	 *         struct bar br;
5272 	 *         struct baz bz;
5273 	 * };
5274 	 *
5275 	 * struct foo *v;
5276 	 * v = func();	      // PTR_TO_BTF_ID
5277 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5278 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5279 	 *                    // first member type of struct after comparison fails
5280 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5281 	 *                    // to match type
5282 	 *
5283 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5284 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5285 	 * the struct to match type against first member of struct, i.e. reject
5286 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5287 	 * strict mode to true for type match.
5288 	 */
5289 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5290 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5291 				  kptr_field->type == BPF_KPTR_REF))
5292 		goto bad_type;
5293 	return 0;
5294 bad_type:
5295 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5296 		reg_type_str(env, reg->type), reg_name);
5297 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5298 	if (kptr_field->type == BPF_KPTR_UNREF)
5299 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5300 			targ_name);
5301 	else
5302 		verbose(env, "\n");
5303 	return -EINVAL;
5304 }
5305 
5306 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5307  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5308  */
5309 static bool in_rcu_cs(struct bpf_verifier_env *env)
5310 {
5311 	return env->cur_state->active_rcu_lock ||
5312 	       env->cur_state->active_lock.ptr ||
5313 	       !env->prog->aux->sleepable;
5314 }
5315 
5316 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5317 BTF_SET_START(rcu_protected_types)
5318 BTF_ID(struct, prog_test_ref_kfunc)
5319 BTF_ID(struct, cgroup)
5320 BTF_ID(struct, bpf_cpumask)
5321 BTF_ID(struct, task_struct)
5322 BTF_SET_END(rcu_protected_types)
5323 
5324 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5325 {
5326 	if (!btf_is_kernel(btf))
5327 		return false;
5328 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5329 }
5330 
5331 static bool rcu_safe_kptr(const struct btf_field *field)
5332 {
5333 	const struct btf_field_kptr *kptr = &field->kptr;
5334 
5335 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5336 }
5337 
5338 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5339 				 int value_regno, int insn_idx,
5340 				 struct btf_field *kptr_field)
5341 {
5342 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5343 	int class = BPF_CLASS(insn->code);
5344 	struct bpf_reg_state *val_reg;
5345 
5346 	/* Things we already checked for in check_map_access and caller:
5347 	 *  - Reject cases where variable offset may touch kptr
5348 	 *  - size of access (must be BPF_DW)
5349 	 *  - tnum_is_const(reg->var_off)
5350 	 *  - kptr_field->offset == off + reg->var_off.value
5351 	 */
5352 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5353 	if (BPF_MODE(insn->code) != BPF_MEM) {
5354 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5355 		return -EACCES;
5356 	}
5357 
5358 	/* We only allow loading referenced kptr, since it will be marked as
5359 	 * untrusted, similar to unreferenced kptr.
5360 	 */
5361 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5362 		verbose(env, "store to referenced kptr disallowed\n");
5363 		return -EACCES;
5364 	}
5365 
5366 	if (class == BPF_LDX) {
5367 		val_reg = reg_state(env, value_regno);
5368 		/* We can simply mark the value_regno receiving the pointer
5369 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5370 		 */
5371 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5372 				kptr_field->kptr.btf_id,
5373 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5374 				PTR_MAYBE_NULL | MEM_RCU :
5375 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5376 		/* For mark_ptr_or_null_reg */
5377 		val_reg->id = ++env->id_gen;
5378 	} else if (class == BPF_STX) {
5379 		val_reg = reg_state(env, value_regno);
5380 		if (!register_is_null(val_reg) &&
5381 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5382 			return -EACCES;
5383 	} else if (class == BPF_ST) {
5384 		if (insn->imm) {
5385 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5386 				kptr_field->offset);
5387 			return -EACCES;
5388 		}
5389 	} else {
5390 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5391 		return -EACCES;
5392 	}
5393 	return 0;
5394 }
5395 
5396 /* check read/write into a map element with possible variable offset */
5397 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5398 			    int off, int size, bool zero_size_allowed,
5399 			    enum bpf_access_src src)
5400 {
5401 	struct bpf_verifier_state *vstate = env->cur_state;
5402 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5403 	struct bpf_reg_state *reg = &state->regs[regno];
5404 	struct bpf_map *map = reg->map_ptr;
5405 	struct btf_record *rec;
5406 	int err, i;
5407 
5408 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5409 				      zero_size_allowed);
5410 	if (err)
5411 		return err;
5412 
5413 	if (IS_ERR_OR_NULL(map->record))
5414 		return 0;
5415 	rec = map->record;
5416 	for (i = 0; i < rec->cnt; i++) {
5417 		struct btf_field *field = &rec->fields[i];
5418 		u32 p = field->offset;
5419 
5420 		/* If any part of a field  can be touched by load/store, reject
5421 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5422 		 * it is sufficient to check x1 < y2 && y1 < x2.
5423 		 */
5424 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5425 		    p < reg->umax_value + off + size) {
5426 			switch (field->type) {
5427 			case BPF_KPTR_UNREF:
5428 			case BPF_KPTR_REF:
5429 				if (src != ACCESS_DIRECT) {
5430 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5431 					return -EACCES;
5432 				}
5433 				if (!tnum_is_const(reg->var_off)) {
5434 					verbose(env, "kptr access cannot have variable offset\n");
5435 					return -EACCES;
5436 				}
5437 				if (p != off + reg->var_off.value) {
5438 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5439 						p, off + reg->var_off.value);
5440 					return -EACCES;
5441 				}
5442 				if (size != bpf_size_to_bytes(BPF_DW)) {
5443 					verbose(env, "kptr access size must be BPF_DW\n");
5444 					return -EACCES;
5445 				}
5446 				break;
5447 			default:
5448 				verbose(env, "%s cannot be accessed directly by load/store\n",
5449 					btf_field_type_name(field->type));
5450 				return -EACCES;
5451 			}
5452 		}
5453 	}
5454 	return 0;
5455 }
5456 
5457 #define MAX_PACKET_OFF 0xffff
5458 
5459 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5460 				       const struct bpf_call_arg_meta *meta,
5461 				       enum bpf_access_type t)
5462 {
5463 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5464 
5465 	switch (prog_type) {
5466 	/* Program types only with direct read access go here! */
5467 	case BPF_PROG_TYPE_LWT_IN:
5468 	case BPF_PROG_TYPE_LWT_OUT:
5469 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5470 	case BPF_PROG_TYPE_SK_REUSEPORT:
5471 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5472 	case BPF_PROG_TYPE_CGROUP_SKB:
5473 		if (t == BPF_WRITE)
5474 			return false;
5475 		fallthrough;
5476 
5477 	/* Program types with direct read + write access go here! */
5478 	case BPF_PROG_TYPE_SCHED_CLS:
5479 	case BPF_PROG_TYPE_SCHED_ACT:
5480 	case BPF_PROG_TYPE_XDP:
5481 	case BPF_PROG_TYPE_LWT_XMIT:
5482 	case BPF_PROG_TYPE_SK_SKB:
5483 	case BPF_PROG_TYPE_SK_MSG:
5484 		if (meta)
5485 			return meta->pkt_access;
5486 
5487 		env->seen_direct_write = true;
5488 		return true;
5489 
5490 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5491 		if (t == BPF_WRITE)
5492 			env->seen_direct_write = true;
5493 
5494 		return true;
5495 
5496 	default:
5497 		return false;
5498 	}
5499 }
5500 
5501 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5502 			       int size, bool zero_size_allowed)
5503 {
5504 	struct bpf_reg_state *regs = cur_regs(env);
5505 	struct bpf_reg_state *reg = &regs[regno];
5506 	int err;
5507 
5508 	/* We may have added a variable offset to the packet pointer; but any
5509 	 * reg->range we have comes after that.  We are only checking the fixed
5510 	 * offset.
5511 	 */
5512 
5513 	/* We don't allow negative numbers, because we aren't tracking enough
5514 	 * detail to prove they're safe.
5515 	 */
5516 	if (reg->smin_value < 0) {
5517 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5518 			regno);
5519 		return -EACCES;
5520 	}
5521 
5522 	err = reg->range < 0 ? -EINVAL :
5523 	      __check_mem_access(env, regno, off, size, reg->range,
5524 				 zero_size_allowed);
5525 	if (err) {
5526 		verbose(env, "R%d offset is outside of the packet\n", regno);
5527 		return err;
5528 	}
5529 
5530 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5531 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5532 	 * otherwise find_good_pkt_pointers would have refused to set range info
5533 	 * that __check_mem_access would have rejected this pkt access.
5534 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5535 	 */
5536 	env->prog->aux->max_pkt_offset =
5537 		max_t(u32, env->prog->aux->max_pkt_offset,
5538 		      off + reg->umax_value + size - 1);
5539 
5540 	return err;
5541 }
5542 
5543 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5544 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5545 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5546 			    struct btf **btf, u32 *btf_id)
5547 {
5548 	struct bpf_insn_access_aux info = {
5549 		.reg_type = *reg_type,
5550 		.log = &env->log,
5551 	};
5552 
5553 	if (env->ops->is_valid_access &&
5554 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5555 		/* A non zero info.ctx_field_size indicates that this field is a
5556 		 * candidate for later verifier transformation to load the whole
5557 		 * field and then apply a mask when accessed with a narrower
5558 		 * access than actual ctx access size. A zero info.ctx_field_size
5559 		 * will only allow for whole field access and rejects any other
5560 		 * type of narrower access.
5561 		 */
5562 		*reg_type = info.reg_type;
5563 
5564 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5565 			*btf = info.btf;
5566 			*btf_id = info.btf_id;
5567 		} else {
5568 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5569 		}
5570 		/* remember the offset of last byte accessed in ctx */
5571 		if (env->prog->aux->max_ctx_offset < off + size)
5572 			env->prog->aux->max_ctx_offset = off + size;
5573 		return 0;
5574 	}
5575 
5576 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5577 	return -EACCES;
5578 }
5579 
5580 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5581 				  int size)
5582 {
5583 	if (size < 0 || off < 0 ||
5584 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5585 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5586 			off, size);
5587 		return -EACCES;
5588 	}
5589 	return 0;
5590 }
5591 
5592 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5593 			     u32 regno, int off, int size,
5594 			     enum bpf_access_type t)
5595 {
5596 	struct bpf_reg_state *regs = cur_regs(env);
5597 	struct bpf_reg_state *reg = &regs[regno];
5598 	struct bpf_insn_access_aux info = {};
5599 	bool valid;
5600 
5601 	if (reg->smin_value < 0) {
5602 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5603 			regno);
5604 		return -EACCES;
5605 	}
5606 
5607 	switch (reg->type) {
5608 	case PTR_TO_SOCK_COMMON:
5609 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5610 		break;
5611 	case PTR_TO_SOCKET:
5612 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5613 		break;
5614 	case PTR_TO_TCP_SOCK:
5615 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5616 		break;
5617 	case PTR_TO_XDP_SOCK:
5618 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5619 		break;
5620 	default:
5621 		valid = false;
5622 	}
5623 
5624 
5625 	if (valid) {
5626 		env->insn_aux_data[insn_idx].ctx_field_size =
5627 			info.ctx_field_size;
5628 		return 0;
5629 	}
5630 
5631 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5632 		regno, reg_type_str(env, reg->type), off, size);
5633 
5634 	return -EACCES;
5635 }
5636 
5637 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5638 {
5639 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5640 }
5641 
5642 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5643 {
5644 	const struct bpf_reg_state *reg = reg_state(env, regno);
5645 
5646 	return reg->type == PTR_TO_CTX;
5647 }
5648 
5649 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5650 {
5651 	const struct bpf_reg_state *reg = reg_state(env, regno);
5652 
5653 	return type_is_sk_pointer(reg->type);
5654 }
5655 
5656 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5657 {
5658 	const struct bpf_reg_state *reg = reg_state(env, regno);
5659 
5660 	return type_is_pkt_pointer(reg->type);
5661 }
5662 
5663 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5664 {
5665 	const struct bpf_reg_state *reg = reg_state(env, regno);
5666 
5667 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5668 	return reg->type == PTR_TO_FLOW_KEYS;
5669 }
5670 
5671 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5672 #ifdef CONFIG_NET
5673 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5674 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5675 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5676 #endif
5677 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5678 };
5679 
5680 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5681 {
5682 	/* A referenced register is always trusted. */
5683 	if (reg->ref_obj_id)
5684 		return true;
5685 
5686 	/* Types listed in the reg2btf_ids are always trusted */
5687 	if (reg2btf_ids[base_type(reg->type)])
5688 		return true;
5689 
5690 	/* If a register is not referenced, it is trusted if it has the
5691 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5692 	 * other type modifiers may be safe, but we elect to take an opt-in
5693 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5694 	 * not.
5695 	 *
5696 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5697 	 * for whether a register is trusted.
5698 	 */
5699 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5700 	       !bpf_type_has_unsafe_modifiers(reg->type);
5701 }
5702 
5703 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5704 {
5705 	return reg->type & MEM_RCU;
5706 }
5707 
5708 static void clear_trusted_flags(enum bpf_type_flag *flag)
5709 {
5710 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5711 }
5712 
5713 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5714 				   const struct bpf_reg_state *reg,
5715 				   int off, int size, bool strict)
5716 {
5717 	struct tnum reg_off;
5718 	int ip_align;
5719 
5720 	/* Byte size accesses are always allowed. */
5721 	if (!strict || size == 1)
5722 		return 0;
5723 
5724 	/* For platforms that do not have a Kconfig enabling
5725 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5726 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5727 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5728 	 * to this code only in strict mode where we want to emulate
5729 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5730 	 * unconditional IP align value of '2'.
5731 	 */
5732 	ip_align = 2;
5733 
5734 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5735 	if (!tnum_is_aligned(reg_off, size)) {
5736 		char tn_buf[48];
5737 
5738 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5739 		verbose(env,
5740 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5741 			ip_align, tn_buf, reg->off, off, size);
5742 		return -EACCES;
5743 	}
5744 
5745 	return 0;
5746 }
5747 
5748 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5749 				       const struct bpf_reg_state *reg,
5750 				       const char *pointer_desc,
5751 				       int off, int size, bool strict)
5752 {
5753 	struct tnum reg_off;
5754 
5755 	/* Byte size accesses are always allowed. */
5756 	if (!strict || size == 1)
5757 		return 0;
5758 
5759 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5760 	if (!tnum_is_aligned(reg_off, size)) {
5761 		char tn_buf[48];
5762 
5763 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5764 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5765 			pointer_desc, tn_buf, reg->off, off, size);
5766 		return -EACCES;
5767 	}
5768 
5769 	return 0;
5770 }
5771 
5772 static int check_ptr_alignment(struct bpf_verifier_env *env,
5773 			       const struct bpf_reg_state *reg, int off,
5774 			       int size, bool strict_alignment_once)
5775 {
5776 	bool strict = env->strict_alignment || strict_alignment_once;
5777 	const char *pointer_desc = "";
5778 
5779 	switch (reg->type) {
5780 	case PTR_TO_PACKET:
5781 	case PTR_TO_PACKET_META:
5782 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5783 		 * right in front, treat it the very same way.
5784 		 */
5785 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5786 	case PTR_TO_FLOW_KEYS:
5787 		pointer_desc = "flow keys ";
5788 		break;
5789 	case PTR_TO_MAP_KEY:
5790 		pointer_desc = "key ";
5791 		break;
5792 	case PTR_TO_MAP_VALUE:
5793 		pointer_desc = "value ";
5794 		break;
5795 	case PTR_TO_CTX:
5796 		pointer_desc = "context ";
5797 		break;
5798 	case PTR_TO_STACK:
5799 		pointer_desc = "stack ";
5800 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5801 		 * and check_stack_read_fixed_off() relies on stack accesses being
5802 		 * aligned.
5803 		 */
5804 		strict = true;
5805 		break;
5806 	case PTR_TO_SOCKET:
5807 		pointer_desc = "sock ";
5808 		break;
5809 	case PTR_TO_SOCK_COMMON:
5810 		pointer_desc = "sock_common ";
5811 		break;
5812 	case PTR_TO_TCP_SOCK:
5813 		pointer_desc = "tcp_sock ";
5814 		break;
5815 	case PTR_TO_XDP_SOCK:
5816 		pointer_desc = "xdp_sock ";
5817 		break;
5818 	default:
5819 		break;
5820 	}
5821 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5822 					   strict);
5823 }
5824 
5825 /* starting from main bpf function walk all instructions of the function
5826  * and recursively walk all callees that given function can call.
5827  * Ignore jump and exit insns.
5828  * Since recursion is prevented by check_cfg() this algorithm
5829  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5830  */
5831 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5832 {
5833 	struct bpf_subprog_info *subprog = env->subprog_info;
5834 	struct bpf_insn *insn = env->prog->insnsi;
5835 	int depth = 0, frame = 0, i, subprog_end;
5836 	bool tail_call_reachable = false;
5837 	int ret_insn[MAX_CALL_FRAMES];
5838 	int ret_prog[MAX_CALL_FRAMES];
5839 	int j;
5840 
5841 	i = subprog[idx].start;
5842 process_func:
5843 	/* protect against potential stack overflow that might happen when
5844 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5845 	 * depth for such case down to 256 so that the worst case scenario
5846 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5847 	 * 8k).
5848 	 *
5849 	 * To get the idea what might happen, see an example:
5850 	 * func1 -> sub rsp, 128
5851 	 *  subfunc1 -> sub rsp, 256
5852 	 *  tailcall1 -> add rsp, 256
5853 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5854 	 *   subfunc2 -> sub rsp, 64
5855 	 *   subfunc22 -> sub rsp, 128
5856 	 *   tailcall2 -> add rsp, 128
5857 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5858 	 *
5859 	 * tailcall will unwind the current stack frame but it will not get rid
5860 	 * of caller's stack as shown on the example above.
5861 	 */
5862 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5863 		verbose(env,
5864 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5865 			depth);
5866 		return -EACCES;
5867 	}
5868 	/* round up to 32-bytes, since this is granularity
5869 	 * of interpreter stack size
5870 	 */
5871 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5872 	if (depth > MAX_BPF_STACK) {
5873 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5874 			frame + 1, depth);
5875 		return -EACCES;
5876 	}
5877 continue_func:
5878 	subprog_end = subprog[idx + 1].start;
5879 	for (; i < subprog_end; i++) {
5880 		int next_insn, sidx;
5881 
5882 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5883 			continue;
5884 		/* remember insn and function to return to */
5885 		ret_insn[frame] = i + 1;
5886 		ret_prog[frame] = idx;
5887 
5888 		/* find the callee */
5889 		next_insn = i + insn[i].imm + 1;
5890 		sidx = find_subprog(env, next_insn);
5891 		if (sidx < 0) {
5892 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5893 				  next_insn);
5894 			return -EFAULT;
5895 		}
5896 		if (subprog[sidx].is_async_cb) {
5897 			if (subprog[sidx].has_tail_call) {
5898 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5899 				return -EFAULT;
5900 			}
5901 			/* async callbacks don't increase bpf prog stack size unless called directly */
5902 			if (!bpf_pseudo_call(insn + i))
5903 				continue;
5904 		}
5905 		i = next_insn;
5906 		idx = sidx;
5907 
5908 		if (subprog[idx].has_tail_call)
5909 			tail_call_reachable = true;
5910 
5911 		frame++;
5912 		if (frame >= MAX_CALL_FRAMES) {
5913 			verbose(env, "the call stack of %d frames is too deep !\n",
5914 				frame);
5915 			return -E2BIG;
5916 		}
5917 		goto process_func;
5918 	}
5919 	/* if tail call got detected across bpf2bpf calls then mark each of the
5920 	 * currently present subprog frames as tail call reachable subprogs;
5921 	 * this info will be utilized by JIT so that we will be preserving the
5922 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5923 	 */
5924 	if (tail_call_reachable)
5925 		for (j = 0; j < frame; j++)
5926 			subprog[ret_prog[j]].tail_call_reachable = true;
5927 	if (subprog[0].tail_call_reachable)
5928 		env->prog->aux->tail_call_reachable = true;
5929 
5930 	/* end of for() loop means the last insn of the 'subprog'
5931 	 * was reached. Doesn't matter whether it was JA or EXIT
5932 	 */
5933 	if (frame == 0)
5934 		return 0;
5935 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5936 	frame--;
5937 	i = ret_insn[frame];
5938 	idx = ret_prog[frame];
5939 	goto continue_func;
5940 }
5941 
5942 static int check_max_stack_depth(struct bpf_verifier_env *env)
5943 {
5944 	struct bpf_subprog_info *si = env->subprog_info;
5945 	int ret;
5946 
5947 	for (int i = 0; i < env->subprog_cnt; i++) {
5948 		if (!i || si[i].is_async_cb) {
5949 			ret = check_max_stack_depth_subprog(env, i);
5950 			if (ret < 0)
5951 				return ret;
5952 		}
5953 		continue;
5954 	}
5955 	return 0;
5956 }
5957 
5958 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5959 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5960 				  const struct bpf_insn *insn, int idx)
5961 {
5962 	int start = idx + insn->imm + 1, subprog;
5963 
5964 	subprog = find_subprog(env, start);
5965 	if (subprog < 0) {
5966 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5967 			  start);
5968 		return -EFAULT;
5969 	}
5970 	return env->subprog_info[subprog].stack_depth;
5971 }
5972 #endif
5973 
5974 static int __check_buffer_access(struct bpf_verifier_env *env,
5975 				 const char *buf_info,
5976 				 const struct bpf_reg_state *reg,
5977 				 int regno, int off, int size)
5978 {
5979 	if (off < 0) {
5980 		verbose(env,
5981 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5982 			regno, buf_info, off, size);
5983 		return -EACCES;
5984 	}
5985 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5986 		char tn_buf[48];
5987 
5988 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5989 		verbose(env,
5990 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5991 			regno, off, tn_buf);
5992 		return -EACCES;
5993 	}
5994 
5995 	return 0;
5996 }
5997 
5998 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5999 				  const struct bpf_reg_state *reg,
6000 				  int regno, int off, int size)
6001 {
6002 	int err;
6003 
6004 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6005 	if (err)
6006 		return err;
6007 
6008 	if (off + size > env->prog->aux->max_tp_access)
6009 		env->prog->aux->max_tp_access = off + size;
6010 
6011 	return 0;
6012 }
6013 
6014 static int check_buffer_access(struct bpf_verifier_env *env,
6015 			       const struct bpf_reg_state *reg,
6016 			       int regno, int off, int size,
6017 			       bool zero_size_allowed,
6018 			       u32 *max_access)
6019 {
6020 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6021 	int err;
6022 
6023 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6024 	if (err)
6025 		return err;
6026 
6027 	if (off + size > *max_access)
6028 		*max_access = off + size;
6029 
6030 	return 0;
6031 }
6032 
6033 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6034 static void zext_32_to_64(struct bpf_reg_state *reg)
6035 {
6036 	reg->var_off = tnum_subreg(reg->var_off);
6037 	__reg_assign_32_into_64(reg);
6038 }
6039 
6040 /* truncate register to smaller size (in bytes)
6041  * must be called with size < BPF_REG_SIZE
6042  */
6043 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6044 {
6045 	u64 mask;
6046 
6047 	/* clear high bits in bit representation */
6048 	reg->var_off = tnum_cast(reg->var_off, size);
6049 
6050 	/* fix arithmetic bounds */
6051 	mask = ((u64)1 << (size * 8)) - 1;
6052 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6053 		reg->umin_value &= mask;
6054 		reg->umax_value &= mask;
6055 	} else {
6056 		reg->umin_value = 0;
6057 		reg->umax_value = mask;
6058 	}
6059 	reg->smin_value = reg->umin_value;
6060 	reg->smax_value = reg->umax_value;
6061 
6062 	/* If size is smaller than 32bit register the 32bit register
6063 	 * values are also truncated so we push 64-bit bounds into
6064 	 * 32-bit bounds. Above were truncated < 32-bits already.
6065 	 */
6066 	if (size >= 4)
6067 		return;
6068 	__reg_combine_64_into_32(reg);
6069 }
6070 
6071 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6072 {
6073 	if (size == 1) {
6074 		reg->smin_value = reg->s32_min_value = S8_MIN;
6075 		reg->smax_value = reg->s32_max_value = S8_MAX;
6076 	} else if (size == 2) {
6077 		reg->smin_value = reg->s32_min_value = S16_MIN;
6078 		reg->smax_value = reg->s32_max_value = S16_MAX;
6079 	} else {
6080 		/* size == 4 */
6081 		reg->smin_value = reg->s32_min_value = S32_MIN;
6082 		reg->smax_value = reg->s32_max_value = S32_MAX;
6083 	}
6084 	reg->umin_value = reg->u32_min_value = 0;
6085 	reg->umax_value = U64_MAX;
6086 	reg->u32_max_value = U32_MAX;
6087 	reg->var_off = tnum_unknown;
6088 }
6089 
6090 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6091 {
6092 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6093 	u64 top_smax_value, top_smin_value;
6094 	u64 num_bits = size * 8;
6095 
6096 	if (tnum_is_const(reg->var_off)) {
6097 		u64_cval = reg->var_off.value;
6098 		if (size == 1)
6099 			reg->var_off = tnum_const((s8)u64_cval);
6100 		else if (size == 2)
6101 			reg->var_off = tnum_const((s16)u64_cval);
6102 		else
6103 			/* size == 4 */
6104 			reg->var_off = tnum_const((s32)u64_cval);
6105 
6106 		u64_cval = reg->var_off.value;
6107 		reg->smax_value = reg->smin_value = u64_cval;
6108 		reg->umax_value = reg->umin_value = u64_cval;
6109 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6110 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6111 		return;
6112 	}
6113 
6114 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6115 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6116 
6117 	if (top_smax_value != top_smin_value)
6118 		goto out;
6119 
6120 	/* find the s64_min and s64_min after sign extension */
6121 	if (size == 1) {
6122 		init_s64_max = (s8)reg->smax_value;
6123 		init_s64_min = (s8)reg->smin_value;
6124 	} else if (size == 2) {
6125 		init_s64_max = (s16)reg->smax_value;
6126 		init_s64_min = (s16)reg->smin_value;
6127 	} else {
6128 		init_s64_max = (s32)reg->smax_value;
6129 		init_s64_min = (s32)reg->smin_value;
6130 	}
6131 
6132 	s64_max = max(init_s64_max, init_s64_min);
6133 	s64_min = min(init_s64_max, init_s64_min);
6134 
6135 	/* both of s64_max/s64_min positive or negative */
6136 	if ((s64_max >= 0) == (s64_min >= 0)) {
6137 		reg->smin_value = reg->s32_min_value = s64_min;
6138 		reg->smax_value = reg->s32_max_value = s64_max;
6139 		reg->umin_value = reg->u32_min_value = s64_min;
6140 		reg->umax_value = reg->u32_max_value = s64_max;
6141 		reg->var_off = tnum_range(s64_min, s64_max);
6142 		return;
6143 	}
6144 
6145 out:
6146 	set_sext64_default_val(reg, size);
6147 }
6148 
6149 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6150 {
6151 	if (size == 1) {
6152 		reg->s32_min_value = S8_MIN;
6153 		reg->s32_max_value = S8_MAX;
6154 	} else {
6155 		/* size == 2 */
6156 		reg->s32_min_value = S16_MIN;
6157 		reg->s32_max_value = S16_MAX;
6158 	}
6159 	reg->u32_min_value = 0;
6160 	reg->u32_max_value = U32_MAX;
6161 }
6162 
6163 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6164 {
6165 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6166 	u32 top_smax_value, top_smin_value;
6167 	u32 num_bits = size * 8;
6168 
6169 	if (tnum_is_const(reg->var_off)) {
6170 		u32_val = reg->var_off.value;
6171 		if (size == 1)
6172 			reg->var_off = tnum_const((s8)u32_val);
6173 		else
6174 			reg->var_off = tnum_const((s16)u32_val);
6175 
6176 		u32_val = reg->var_off.value;
6177 		reg->s32_min_value = reg->s32_max_value = u32_val;
6178 		reg->u32_min_value = reg->u32_max_value = u32_val;
6179 		return;
6180 	}
6181 
6182 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6183 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6184 
6185 	if (top_smax_value != top_smin_value)
6186 		goto out;
6187 
6188 	/* find the s32_min and s32_min after sign extension */
6189 	if (size == 1) {
6190 		init_s32_max = (s8)reg->s32_max_value;
6191 		init_s32_min = (s8)reg->s32_min_value;
6192 	} else {
6193 		/* size == 2 */
6194 		init_s32_max = (s16)reg->s32_max_value;
6195 		init_s32_min = (s16)reg->s32_min_value;
6196 	}
6197 	s32_max = max(init_s32_max, init_s32_min);
6198 	s32_min = min(init_s32_max, init_s32_min);
6199 
6200 	if ((s32_min >= 0) == (s32_max >= 0)) {
6201 		reg->s32_min_value = s32_min;
6202 		reg->s32_max_value = s32_max;
6203 		reg->u32_min_value = (u32)s32_min;
6204 		reg->u32_max_value = (u32)s32_max;
6205 		return;
6206 	}
6207 
6208 out:
6209 	set_sext32_default_val(reg, size);
6210 }
6211 
6212 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6213 {
6214 	/* A map is considered read-only if the following condition are true:
6215 	 *
6216 	 * 1) BPF program side cannot change any of the map content. The
6217 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6218 	 *    and was set at map creation time.
6219 	 * 2) The map value(s) have been initialized from user space by a
6220 	 *    loader and then "frozen", such that no new map update/delete
6221 	 *    operations from syscall side are possible for the rest of
6222 	 *    the map's lifetime from that point onwards.
6223 	 * 3) Any parallel/pending map update/delete operations from syscall
6224 	 *    side have been completed. Only after that point, it's safe to
6225 	 *    assume that map value(s) are immutable.
6226 	 */
6227 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6228 	       READ_ONCE(map->frozen) &&
6229 	       !bpf_map_write_active(map);
6230 }
6231 
6232 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6233 			       bool is_ldsx)
6234 {
6235 	void *ptr;
6236 	u64 addr;
6237 	int err;
6238 
6239 	err = map->ops->map_direct_value_addr(map, &addr, off);
6240 	if (err)
6241 		return err;
6242 	ptr = (void *)(long)addr + off;
6243 
6244 	switch (size) {
6245 	case sizeof(u8):
6246 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6247 		break;
6248 	case sizeof(u16):
6249 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6250 		break;
6251 	case sizeof(u32):
6252 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6253 		break;
6254 	case sizeof(u64):
6255 		*val = *(u64 *)ptr;
6256 		break;
6257 	default:
6258 		return -EINVAL;
6259 	}
6260 	return 0;
6261 }
6262 
6263 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6264 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6265 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6266 
6267 /*
6268  * Allow list few fields as RCU trusted or full trusted.
6269  * This logic doesn't allow mix tagging and will be removed once GCC supports
6270  * btf_type_tag.
6271  */
6272 
6273 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6274 BTF_TYPE_SAFE_RCU(struct task_struct) {
6275 	const cpumask_t *cpus_ptr;
6276 	struct css_set __rcu *cgroups;
6277 	struct task_struct __rcu *real_parent;
6278 	struct task_struct *group_leader;
6279 };
6280 
6281 BTF_TYPE_SAFE_RCU(struct cgroup) {
6282 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6283 	struct kernfs_node *kn;
6284 };
6285 
6286 BTF_TYPE_SAFE_RCU(struct css_set) {
6287 	struct cgroup *dfl_cgrp;
6288 };
6289 
6290 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6291 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6292 	struct file __rcu *exe_file;
6293 };
6294 
6295 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6296  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6297  */
6298 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6299 	struct sock *sk;
6300 };
6301 
6302 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6303 	struct sock *sk;
6304 };
6305 
6306 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6307 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6308 	struct seq_file *seq;
6309 };
6310 
6311 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6312 	struct bpf_iter_meta *meta;
6313 	struct task_struct *task;
6314 };
6315 
6316 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6317 	struct file *file;
6318 };
6319 
6320 BTF_TYPE_SAFE_TRUSTED(struct file) {
6321 	struct inode *f_inode;
6322 };
6323 
6324 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6325 	/* no negative dentry-s in places where bpf can see it */
6326 	struct inode *d_inode;
6327 };
6328 
6329 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6330 	struct sock *sk;
6331 };
6332 
6333 static bool type_is_rcu(struct bpf_verifier_env *env,
6334 			struct bpf_reg_state *reg,
6335 			const char *field_name, u32 btf_id)
6336 {
6337 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6338 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6339 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6340 
6341 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6342 }
6343 
6344 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6345 				struct bpf_reg_state *reg,
6346 				const char *field_name, u32 btf_id)
6347 {
6348 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6349 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6350 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6351 
6352 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6353 }
6354 
6355 static bool type_is_trusted(struct bpf_verifier_env *env,
6356 			    struct bpf_reg_state *reg,
6357 			    const char *field_name, u32 btf_id)
6358 {
6359 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6360 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6361 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6362 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6363 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6364 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6365 
6366 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6367 }
6368 
6369 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6370 				   struct bpf_reg_state *regs,
6371 				   int regno, int off, int size,
6372 				   enum bpf_access_type atype,
6373 				   int value_regno)
6374 {
6375 	struct bpf_reg_state *reg = regs + regno;
6376 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6377 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6378 	const char *field_name = NULL;
6379 	enum bpf_type_flag flag = 0;
6380 	u32 btf_id = 0;
6381 	int ret;
6382 
6383 	if (!env->allow_ptr_leaks) {
6384 		verbose(env,
6385 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6386 			tname);
6387 		return -EPERM;
6388 	}
6389 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6390 		verbose(env,
6391 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6392 			tname);
6393 		return -EINVAL;
6394 	}
6395 	if (off < 0) {
6396 		verbose(env,
6397 			"R%d is ptr_%s invalid negative access: off=%d\n",
6398 			regno, tname, off);
6399 		return -EACCES;
6400 	}
6401 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6402 		char tn_buf[48];
6403 
6404 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6405 		verbose(env,
6406 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6407 			regno, tname, off, tn_buf);
6408 		return -EACCES;
6409 	}
6410 
6411 	if (reg->type & MEM_USER) {
6412 		verbose(env,
6413 			"R%d is ptr_%s access user memory: off=%d\n",
6414 			regno, tname, off);
6415 		return -EACCES;
6416 	}
6417 
6418 	if (reg->type & MEM_PERCPU) {
6419 		verbose(env,
6420 			"R%d is ptr_%s access percpu memory: off=%d\n",
6421 			regno, tname, off);
6422 		return -EACCES;
6423 	}
6424 
6425 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6426 		if (!btf_is_kernel(reg->btf)) {
6427 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6428 			return -EFAULT;
6429 		}
6430 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6431 	} else {
6432 		/* Writes are permitted with default btf_struct_access for
6433 		 * program allocated objects (which always have ref_obj_id > 0),
6434 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6435 		 */
6436 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6437 			verbose(env, "only read is supported\n");
6438 			return -EACCES;
6439 		}
6440 
6441 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6442 		    !reg->ref_obj_id) {
6443 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6444 			return -EFAULT;
6445 		}
6446 
6447 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6448 	}
6449 
6450 	if (ret < 0)
6451 		return ret;
6452 
6453 	if (ret != PTR_TO_BTF_ID) {
6454 		/* just mark; */
6455 
6456 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6457 		/* If this is an untrusted pointer, all pointers formed by walking it
6458 		 * also inherit the untrusted flag.
6459 		 */
6460 		flag = PTR_UNTRUSTED;
6461 
6462 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6463 		/* By default any pointer obtained from walking a trusted pointer is no
6464 		 * longer trusted, unless the field being accessed has explicitly been
6465 		 * marked as inheriting its parent's state of trust (either full or RCU).
6466 		 * For example:
6467 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6468 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6469 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6470 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6471 		 *
6472 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6473 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6474 		 */
6475 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6476 			flag |= PTR_TRUSTED;
6477 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6478 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6479 				/* ignore __rcu tag and mark it MEM_RCU */
6480 				flag |= MEM_RCU;
6481 			} else if (flag & MEM_RCU ||
6482 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6483 				/* __rcu tagged pointers can be NULL */
6484 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6485 
6486 				/* We always trust them */
6487 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6488 				    flag & PTR_UNTRUSTED)
6489 					flag &= ~PTR_UNTRUSTED;
6490 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6491 				/* keep as-is */
6492 			} else {
6493 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6494 				clear_trusted_flags(&flag);
6495 			}
6496 		} else {
6497 			/*
6498 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6499 			 * aggressively mark as untrusted otherwise such
6500 			 * pointers will be plain PTR_TO_BTF_ID without flags
6501 			 * and will be allowed to be passed into helpers for
6502 			 * compat reasons.
6503 			 */
6504 			flag = PTR_UNTRUSTED;
6505 		}
6506 	} else {
6507 		/* Old compat. Deprecated */
6508 		clear_trusted_flags(&flag);
6509 	}
6510 
6511 	if (atype == BPF_READ && value_regno >= 0)
6512 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6513 
6514 	return 0;
6515 }
6516 
6517 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6518 				   struct bpf_reg_state *regs,
6519 				   int regno, int off, int size,
6520 				   enum bpf_access_type atype,
6521 				   int value_regno)
6522 {
6523 	struct bpf_reg_state *reg = regs + regno;
6524 	struct bpf_map *map = reg->map_ptr;
6525 	struct bpf_reg_state map_reg;
6526 	enum bpf_type_flag flag = 0;
6527 	const struct btf_type *t;
6528 	const char *tname;
6529 	u32 btf_id;
6530 	int ret;
6531 
6532 	if (!btf_vmlinux) {
6533 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6534 		return -ENOTSUPP;
6535 	}
6536 
6537 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6538 		verbose(env, "map_ptr access not supported for map type %d\n",
6539 			map->map_type);
6540 		return -ENOTSUPP;
6541 	}
6542 
6543 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6544 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6545 
6546 	if (!env->allow_ptr_leaks) {
6547 		verbose(env,
6548 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6549 			tname);
6550 		return -EPERM;
6551 	}
6552 
6553 	if (off < 0) {
6554 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6555 			regno, tname, off);
6556 		return -EACCES;
6557 	}
6558 
6559 	if (atype != BPF_READ) {
6560 		verbose(env, "only read from %s is supported\n", tname);
6561 		return -EACCES;
6562 	}
6563 
6564 	/* Simulate access to a PTR_TO_BTF_ID */
6565 	memset(&map_reg, 0, sizeof(map_reg));
6566 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6567 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6568 	if (ret < 0)
6569 		return ret;
6570 
6571 	if (value_regno >= 0)
6572 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6573 
6574 	return 0;
6575 }
6576 
6577 /* Check that the stack access at the given offset is within bounds. The
6578  * maximum valid offset is -1.
6579  *
6580  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6581  * -state->allocated_stack for reads.
6582  */
6583 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6584                                           s64 off,
6585                                           struct bpf_func_state *state,
6586                                           enum bpf_access_type t)
6587 {
6588 	int min_valid_off;
6589 
6590 	if (t == BPF_WRITE || env->allow_uninit_stack)
6591 		min_valid_off = -MAX_BPF_STACK;
6592 	else
6593 		min_valid_off = -state->allocated_stack;
6594 
6595 	if (off < min_valid_off || off > -1)
6596 		return -EACCES;
6597 	return 0;
6598 }
6599 
6600 /* Check that the stack access at 'regno + off' falls within the maximum stack
6601  * bounds.
6602  *
6603  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6604  */
6605 static int check_stack_access_within_bounds(
6606 		struct bpf_verifier_env *env,
6607 		int regno, int off, int access_size,
6608 		enum bpf_access_src src, enum bpf_access_type type)
6609 {
6610 	struct bpf_reg_state *regs = cur_regs(env);
6611 	struct bpf_reg_state *reg = regs + regno;
6612 	struct bpf_func_state *state = func(env, reg);
6613 	s64 min_off, max_off;
6614 	int err;
6615 	char *err_extra;
6616 
6617 	if (src == ACCESS_HELPER)
6618 		/* We don't know if helpers are reading or writing (or both). */
6619 		err_extra = " indirect access to";
6620 	else if (type == BPF_READ)
6621 		err_extra = " read from";
6622 	else
6623 		err_extra = " write to";
6624 
6625 	if (tnum_is_const(reg->var_off)) {
6626 		min_off = (s64)reg->var_off.value + off;
6627 		max_off = min_off + access_size;
6628 	} else {
6629 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6630 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6631 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6632 				err_extra, regno);
6633 			return -EACCES;
6634 		}
6635 		min_off = reg->smin_value + off;
6636 		max_off = reg->smax_value + off + access_size;
6637 	}
6638 
6639 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6640 	if (!err && max_off > 0)
6641 		err = -EINVAL; /* out of stack access into non-negative offsets */
6642 	if (!err && access_size < 0)
6643 		/* access_size should not be negative (or overflow an int); others checks
6644 		 * along the way should have prevented such an access.
6645 		 */
6646 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6647 
6648 	if (err) {
6649 		if (tnum_is_const(reg->var_off)) {
6650 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6651 				err_extra, regno, off, access_size);
6652 		} else {
6653 			char tn_buf[48];
6654 
6655 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6656 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6657 				err_extra, regno, tn_buf, access_size);
6658 		}
6659 		return err;
6660 	}
6661 
6662 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6663 }
6664 
6665 /* check whether memory at (regno + off) is accessible for t = (read | write)
6666  * if t==write, value_regno is a register which value is stored into memory
6667  * if t==read, value_regno is a register which will receive the value from memory
6668  * if t==write && value_regno==-1, some unknown value is stored into memory
6669  * if t==read && value_regno==-1, don't care what we read from memory
6670  */
6671 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6672 			    int off, int bpf_size, enum bpf_access_type t,
6673 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6674 {
6675 	struct bpf_reg_state *regs = cur_regs(env);
6676 	struct bpf_reg_state *reg = regs + regno;
6677 	int size, err = 0;
6678 
6679 	size = bpf_size_to_bytes(bpf_size);
6680 	if (size < 0)
6681 		return size;
6682 
6683 	/* alignment checks will add in reg->off themselves */
6684 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6685 	if (err)
6686 		return err;
6687 
6688 	/* for access checks, reg->off is just part of off */
6689 	off += reg->off;
6690 
6691 	if (reg->type == PTR_TO_MAP_KEY) {
6692 		if (t == BPF_WRITE) {
6693 			verbose(env, "write to change key R%d not allowed\n", regno);
6694 			return -EACCES;
6695 		}
6696 
6697 		err = check_mem_region_access(env, regno, off, size,
6698 					      reg->map_ptr->key_size, false);
6699 		if (err)
6700 			return err;
6701 		if (value_regno >= 0)
6702 			mark_reg_unknown(env, regs, value_regno);
6703 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6704 		struct btf_field *kptr_field = NULL;
6705 
6706 		if (t == BPF_WRITE && value_regno >= 0 &&
6707 		    is_pointer_value(env, value_regno)) {
6708 			verbose(env, "R%d leaks addr into map\n", value_regno);
6709 			return -EACCES;
6710 		}
6711 		err = check_map_access_type(env, regno, off, size, t);
6712 		if (err)
6713 			return err;
6714 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6715 		if (err)
6716 			return err;
6717 		if (tnum_is_const(reg->var_off))
6718 			kptr_field = btf_record_find(reg->map_ptr->record,
6719 						     off + reg->var_off.value, BPF_KPTR);
6720 		if (kptr_field) {
6721 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6722 		} else if (t == BPF_READ && value_regno >= 0) {
6723 			struct bpf_map *map = reg->map_ptr;
6724 
6725 			/* if map is read-only, track its contents as scalars */
6726 			if (tnum_is_const(reg->var_off) &&
6727 			    bpf_map_is_rdonly(map) &&
6728 			    map->ops->map_direct_value_addr) {
6729 				int map_off = off + reg->var_off.value;
6730 				u64 val = 0;
6731 
6732 				err = bpf_map_direct_read(map, map_off, size,
6733 							  &val, is_ldsx);
6734 				if (err)
6735 					return err;
6736 
6737 				regs[value_regno].type = SCALAR_VALUE;
6738 				__mark_reg_known(&regs[value_regno], val);
6739 			} else {
6740 				mark_reg_unknown(env, regs, value_regno);
6741 			}
6742 		}
6743 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6744 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6745 
6746 		if (type_may_be_null(reg->type)) {
6747 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6748 				reg_type_str(env, reg->type));
6749 			return -EACCES;
6750 		}
6751 
6752 		if (t == BPF_WRITE && rdonly_mem) {
6753 			verbose(env, "R%d cannot write into %s\n",
6754 				regno, reg_type_str(env, reg->type));
6755 			return -EACCES;
6756 		}
6757 
6758 		if (t == BPF_WRITE && value_regno >= 0 &&
6759 		    is_pointer_value(env, value_regno)) {
6760 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6761 			return -EACCES;
6762 		}
6763 
6764 		err = check_mem_region_access(env, regno, off, size,
6765 					      reg->mem_size, false);
6766 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6767 			mark_reg_unknown(env, regs, value_regno);
6768 	} else if (reg->type == PTR_TO_CTX) {
6769 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6770 		struct btf *btf = NULL;
6771 		u32 btf_id = 0;
6772 
6773 		if (t == BPF_WRITE && value_regno >= 0 &&
6774 		    is_pointer_value(env, value_regno)) {
6775 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6776 			return -EACCES;
6777 		}
6778 
6779 		err = check_ptr_off_reg(env, reg, regno);
6780 		if (err < 0)
6781 			return err;
6782 
6783 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6784 				       &btf_id);
6785 		if (err)
6786 			verbose_linfo(env, insn_idx, "; ");
6787 		if (!err && t == BPF_READ && value_regno >= 0) {
6788 			/* ctx access returns either a scalar, or a
6789 			 * PTR_TO_PACKET[_META,_END]. In the latter
6790 			 * case, we know the offset is zero.
6791 			 */
6792 			if (reg_type == SCALAR_VALUE) {
6793 				mark_reg_unknown(env, regs, value_regno);
6794 			} else {
6795 				mark_reg_known_zero(env, regs,
6796 						    value_regno);
6797 				if (type_may_be_null(reg_type))
6798 					regs[value_regno].id = ++env->id_gen;
6799 				/* A load of ctx field could have different
6800 				 * actual load size with the one encoded in the
6801 				 * insn. When the dst is PTR, it is for sure not
6802 				 * a sub-register.
6803 				 */
6804 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6805 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6806 					regs[value_regno].btf = btf;
6807 					regs[value_regno].btf_id = btf_id;
6808 				}
6809 			}
6810 			regs[value_regno].type = reg_type;
6811 		}
6812 
6813 	} else if (reg->type == PTR_TO_STACK) {
6814 		/* Basic bounds checks. */
6815 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6816 		if (err)
6817 			return err;
6818 
6819 		if (t == BPF_READ)
6820 			err = check_stack_read(env, regno, off, size,
6821 					       value_regno);
6822 		else
6823 			err = check_stack_write(env, regno, off, size,
6824 						value_regno, insn_idx);
6825 	} else if (reg_is_pkt_pointer(reg)) {
6826 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6827 			verbose(env, "cannot write into packet\n");
6828 			return -EACCES;
6829 		}
6830 		if (t == BPF_WRITE && value_regno >= 0 &&
6831 		    is_pointer_value(env, value_regno)) {
6832 			verbose(env, "R%d leaks addr into packet\n",
6833 				value_regno);
6834 			return -EACCES;
6835 		}
6836 		err = check_packet_access(env, regno, off, size, false);
6837 		if (!err && t == BPF_READ && value_regno >= 0)
6838 			mark_reg_unknown(env, regs, value_regno);
6839 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6840 		if (t == BPF_WRITE && value_regno >= 0 &&
6841 		    is_pointer_value(env, value_regno)) {
6842 			verbose(env, "R%d leaks addr into flow keys\n",
6843 				value_regno);
6844 			return -EACCES;
6845 		}
6846 
6847 		err = check_flow_keys_access(env, off, size);
6848 		if (!err && t == BPF_READ && value_regno >= 0)
6849 			mark_reg_unknown(env, regs, value_regno);
6850 	} else if (type_is_sk_pointer(reg->type)) {
6851 		if (t == BPF_WRITE) {
6852 			verbose(env, "R%d cannot write into %s\n",
6853 				regno, reg_type_str(env, reg->type));
6854 			return -EACCES;
6855 		}
6856 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6857 		if (!err && value_regno >= 0)
6858 			mark_reg_unknown(env, regs, value_regno);
6859 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6860 		err = check_tp_buffer_access(env, reg, regno, off, size);
6861 		if (!err && t == BPF_READ && value_regno >= 0)
6862 			mark_reg_unknown(env, regs, value_regno);
6863 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6864 		   !type_may_be_null(reg->type)) {
6865 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6866 					      value_regno);
6867 	} else if (reg->type == CONST_PTR_TO_MAP) {
6868 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6869 					      value_regno);
6870 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6871 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6872 		u32 *max_access;
6873 
6874 		if (rdonly_mem) {
6875 			if (t == BPF_WRITE) {
6876 				verbose(env, "R%d cannot write into %s\n",
6877 					regno, reg_type_str(env, reg->type));
6878 				return -EACCES;
6879 			}
6880 			max_access = &env->prog->aux->max_rdonly_access;
6881 		} else {
6882 			max_access = &env->prog->aux->max_rdwr_access;
6883 		}
6884 
6885 		err = check_buffer_access(env, reg, regno, off, size, false,
6886 					  max_access);
6887 
6888 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6889 			mark_reg_unknown(env, regs, value_regno);
6890 	} else {
6891 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6892 			reg_type_str(env, reg->type));
6893 		return -EACCES;
6894 	}
6895 
6896 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6897 	    regs[value_regno].type == SCALAR_VALUE) {
6898 		if (!is_ldsx)
6899 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6900 			coerce_reg_to_size(&regs[value_regno], size);
6901 		else
6902 			coerce_reg_to_size_sx(&regs[value_regno], size);
6903 	}
6904 	return err;
6905 }
6906 
6907 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6908 {
6909 	int load_reg;
6910 	int err;
6911 
6912 	switch (insn->imm) {
6913 	case BPF_ADD:
6914 	case BPF_ADD | BPF_FETCH:
6915 	case BPF_AND:
6916 	case BPF_AND | BPF_FETCH:
6917 	case BPF_OR:
6918 	case BPF_OR | BPF_FETCH:
6919 	case BPF_XOR:
6920 	case BPF_XOR | BPF_FETCH:
6921 	case BPF_XCHG:
6922 	case BPF_CMPXCHG:
6923 		break;
6924 	default:
6925 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6926 		return -EINVAL;
6927 	}
6928 
6929 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6930 		verbose(env, "invalid atomic operand size\n");
6931 		return -EINVAL;
6932 	}
6933 
6934 	/* check src1 operand */
6935 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6936 	if (err)
6937 		return err;
6938 
6939 	/* check src2 operand */
6940 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6941 	if (err)
6942 		return err;
6943 
6944 	if (insn->imm == BPF_CMPXCHG) {
6945 		/* Check comparison of R0 with memory location */
6946 		const u32 aux_reg = BPF_REG_0;
6947 
6948 		err = check_reg_arg(env, aux_reg, SRC_OP);
6949 		if (err)
6950 			return err;
6951 
6952 		if (is_pointer_value(env, aux_reg)) {
6953 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6954 			return -EACCES;
6955 		}
6956 	}
6957 
6958 	if (is_pointer_value(env, insn->src_reg)) {
6959 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6960 		return -EACCES;
6961 	}
6962 
6963 	if (is_ctx_reg(env, insn->dst_reg) ||
6964 	    is_pkt_reg(env, insn->dst_reg) ||
6965 	    is_flow_key_reg(env, insn->dst_reg) ||
6966 	    is_sk_reg(env, insn->dst_reg)) {
6967 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6968 			insn->dst_reg,
6969 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6970 		return -EACCES;
6971 	}
6972 
6973 	if (insn->imm & BPF_FETCH) {
6974 		if (insn->imm == BPF_CMPXCHG)
6975 			load_reg = BPF_REG_0;
6976 		else
6977 			load_reg = insn->src_reg;
6978 
6979 		/* check and record load of old value */
6980 		err = check_reg_arg(env, load_reg, DST_OP);
6981 		if (err)
6982 			return err;
6983 	} else {
6984 		/* This instruction accesses a memory location but doesn't
6985 		 * actually load it into a register.
6986 		 */
6987 		load_reg = -1;
6988 	}
6989 
6990 	/* Check whether we can read the memory, with second call for fetch
6991 	 * case to simulate the register fill.
6992 	 */
6993 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6994 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6995 	if (!err && load_reg >= 0)
6996 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6997 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6998 				       true, false);
6999 	if (err)
7000 		return err;
7001 
7002 	/* Check whether we can write into the same memory. */
7003 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7004 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7005 	if (err)
7006 		return err;
7007 
7008 	return 0;
7009 }
7010 
7011 /* When register 'regno' is used to read the stack (either directly or through
7012  * a helper function) make sure that it's within stack boundary and, depending
7013  * on the access type and privileges, that all elements of the stack are
7014  * initialized.
7015  *
7016  * 'off' includes 'regno->off', but not its dynamic part (if any).
7017  *
7018  * All registers that have been spilled on the stack in the slots within the
7019  * read offsets are marked as read.
7020  */
7021 static int check_stack_range_initialized(
7022 		struct bpf_verifier_env *env, int regno, int off,
7023 		int access_size, bool zero_size_allowed,
7024 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7025 {
7026 	struct bpf_reg_state *reg = reg_state(env, regno);
7027 	struct bpf_func_state *state = func(env, reg);
7028 	int err, min_off, max_off, i, j, slot, spi;
7029 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7030 	enum bpf_access_type bounds_check_type;
7031 	/* Some accesses can write anything into the stack, others are
7032 	 * read-only.
7033 	 */
7034 	bool clobber = false;
7035 
7036 	if (access_size == 0 && !zero_size_allowed) {
7037 		verbose(env, "invalid zero-sized read\n");
7038 		return -EACCES;
7039 	}
7040 
7041 	if (type == ACCESS_HELPER) {
7042 		/* The bounds checks for writes are more permissive than for
7043 		 * reads. However, if raw_mode is not set, we'll do extra
7044 		 * checks below.
7045 		 */
7046 		bounds_check_type = BPF_WRITE;
7047 		clobber = true;
7048 	} else {
7049 		bounds_check_type = BPF_READ;
7050 	}
7051 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7052 					       type, bounds_check_type);
7053 	if (err)
7054 		return err;
7055 
7056 
7057 	if (tnum_is_const(reg->var_off)) {
7058 		min_off = max_off = reg->var_off.value + off;
7059 	} else {
7060 		/* Variable offset is prohibited for unprivileged mode for
7061 		 * simplicity since it requires corresponding support in
7062 		 * Spectre masking for stack ALU.
7063 		 * See also retrieve_ptr_limit().
7064 		 */
7065 		if (!env->bypass_spec_v1) {
7066 			char tn_buf[48];
7067 
7068 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7069 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7070 				regno, err_extra, tn_buf);
7071 			return -EACCES;
7072 		}
7073 		/* Only initialized buffer on stack is allowed to be accessed
7074 		 * with variable offset. With uninitialized buffer it's hard to
7075 		 * guarantee that whole memory is marked as initialized on
7076 		 * helper return since specific bounds are unknown what may
7077 		 * cause uninitialized stack leaking.
7078 		 */
7079 		if (meta && meta->raw_mode)
7080 			meta = NULL;
7081 
7082 		min_off = reg->smin_value + off;
7083 		max_off = reg->smax_value + off;
7084 	}
7085 
7086 	if (meta && meta->raw_mode) {
7087 		/* Ensure we won't be overwriting dynptrs when simulating byte
7088 		 * by byte access in check_helper_call using meta.access_size.
7089 		 * This would be a problem if we have a helper in the future
7090 		 * which takes:
7091 		 *
7092 		 *	helper(uninit_mem, len, dynptr)
7093 		 *
7094 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7095 		 * may end up writing to dynptr itself when touching memory from
7096 		 * arg 1. This can be relaxed on a case by case basis for known
7097 		 * safe cases, but reject due to the possibilitiy of aliasing by
7098 		 * default.
7099 		 */
7100 		for (i = min_off; i < max_off + access_size; i++) {
7101 			int stack_off = -i - 1;
7102 
7103 			spi = __get_spi(i);
7104 			/* raw_mode may write past allocated_stack */
7105 			if (state->allocated_stack <= stack_off)
7106 				continue;
7107 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7108 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7109 				return -EACCES;
7110 			}
7111 		}
7112 		meta->access_size = access_size;
7113 		meta->regno = regno;
7114 		return 0;
7115 	}
7116 
7117 	for (i = min_off; i < max_off + access_size; i++) {
7118 		u8 *stype;
7119 
7120 		slot = -i - 1;
7121 		spi = slot / BPF_REG_SIZE;
7122 		if (state->allocated_stack <= slot) {
7123 			verbose(env, "verifier bug: allocated_stack too small");
7124 			return -EFAULT;
7125 		}
7126 
7127 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7128 		if (*stype == STACK_MISC)
7129 			goto mark;
7130 		if ((*stype == STACK_ZERO) ||
7131 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7132 			if (clobber) {
7133 				/* helper can write anything into the stack */
7134 				*stype = STACK_MISC;
7135 			}
7136 			goto mark;
7137 		}
7138 
7139 		if (is_spilled_reg(&state->stack[spi]) &&
7140 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7141 		     env->allow_ptr_leaks)) {
7142 			if (clobber) {
7143 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7144 				for (j = 0; j < BPF_REG_SIZE; j++)
7145 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7146 			}
7147 			goto mark;
7148 		}
7149 
7150 		if (tnum_is_const(reg->var_off)) {
7151 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7152 				err_extra, regno, min_off, i - min_off, access_size);
7153 		} else {
7154 			char tn_buf[48];
7155 
7156 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7157 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7158 				err_extra, regno, tn_buf, i - min_off, access_size);
7159 		}
7160 		return -EACCES;
7161 mark:
7162 		/* reading any byte out of 8-byte 'spill_slot' will cause
7163 		 * the whole slot to be marked as 'read'
7164 		 */
7165 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7166 			      state->stack[spi].spilled_ptr.parent,
7167 			      REG_LIVE_READ64);
7168 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7169 		 * be sure that whether stack slot is written to or not. Hence,
7170 		 * we must still conservatively propagate reads upwards even if
7171 		 * helper may write to the entire memory range.
7172 		 */
7173 	}
7174 	return 0;
7175 }
7176 
7177 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7178 				   int access_size, bool zero_size_allowed,
7179 				   struct bpf_call_arg_meta *meta)
7180 {
7181 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7182 	u32 *max_access;
7183 
7184 	switch (base_type(reg->type)) {
7185 	case PTR_TO_PACKET:
7186 	case PTR_TO_PACKET_META:
7187 		return check_packet_access(env, regno, reg->off, access_size,
7188 					   zero_size_allowed);
7189 	case PTR_TO_MAP_KEY:
7190 		if (meta && meta->raw_mode) {
7191 			verbose(env, "R%d cannot write into %s\n", regno,
7192 				reg_type_str(env, reg->type));
7193 			return -EACCES;
7194 		}
7195 		return check_mem_region_access(env, regno, reg->off, access_size,
7196 					       reg->map_ptr->key_size, false);
7197 	case PTR_TO_MAP_VALUE:
7198 		if (check_map_access_type(env, regno, reg->off, access_size,
7199 					  meta && meta->raw_mode ? BPF_WRITE :
7200 					  BPF_READ))
7201 			return -EACCES;
7202 		return check_map_access(env, regno, reg->off, access_size,
7203 					zero_size_allowed, ACCESS_HELPER);
7204 	case PTR_TO_MEM:
7205 		if (type_is_rdonly_mem(reg->type)) {
7206 			if (meta && meta->raw_mode) {
7207 				verbose(env, "R%d cannot write into %s\n", regno,
7208 					reg_type_str(env, reg->type));
7209 				return -EACCES;
7210 			}
7211 		}
7212 		return check_mem_region_access(env, regno, reg->off,
7213 					       access_size, reg->mem_size,
7214 					       zero_size_allowed);
7215 	case PTR_TO_BUF:
7216 		if (type_is_rdonly_mem(reg->type)) {
7217 			if (meta && meta->raw_mode) {
7218 				verbose(env, "R%d cannot write into %s\n", regno,
7219 					reg_type_str(env, reg->type));
7220 				return -EACCES;
7221 			}
7222 
7223 			max_access = &env->prog->aux->max_rdonly_access;
7224 		} else {
7225 			max_access = &env->prog->aux->max_rdwr_access;
7226 		}
7227 		return check_buffer_access(env, reg, regno, reg->off,
7228 					   access_size, zero_size_allowed,
7229 					   max_access);
7230 	case PTR_TO_STACK:
7231 		return check_stack_range_initialized(
7232 				env,
7233 				regno, reg->off, access_size,
7234 				zero_size_allowed, ACCESS_HELPER, meta);
7235 	case PTR_TO_BTF_ID:
7236 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7237 					       access_size, BPF_READ, -1);
7238 	case PTR_TO_CTX:
7239 		/* in case the function doesn't know how to access the context,
7240 		 * (because we are in a program of type SYSCALL for example), we
7241 		 * can not statically check its size.
7242 		 * Dynamically check it now.
7243 		 */
7244 		if (!env->ops->convert_ctx_access) {
7245 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7246 			int offset = access_size - 1;
7247 
7248 			/* Allow zero-byte read from PTR_TO_CTX */
7249 			if (access_size == 0)
7250 				return zero_size_allowed ? 0 : -EACCES;
7251 
7252 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7253 						atype, -1, false, false);
7254 		}
7255 
7256 		fallthrough;
7257 	default: /* scalar_value or invalid ptr */
7258 		/* Allow zero-byte read from NULL, regardless of pointer type */
7259 		if (zero_size_allowed && access_size == 0 &&
7260 		    register_is_null(reg))
7261 			return 0;
7262 
7263 		verbose(env, "R%d type=%s ", regno,
7264 			reg_type_str(env, reg->type));
7265 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7266 		return -EACCES;
7267 	}
7268 }
7269 
7270 static int check_mem_size_reg(struct bpf_verifier_env *env,
7271 			      struct bpf_reg_state *reg, u32 regno,
7272 			      bool zero_size_allowed,
7273 			      struct bpf_call_arg_meta *meta)
7274 {
7275 	int err;
7276 
7277 	/* This is used to refine r0 return value bounds for helpers
7278 	 * that enforce this value as an upper bound on return values.
7279 	 * See do_refine_retval_range() for helpers that can refine
7280 	 * the return value. C type of helper is u32 so we pull register
7281 	 * bound from umax_value however, if negative verifier errors
7282 	 * out. Only upper bounds can be learned because retval is an
7283 	 * int type and negative retvals are allowed.
7284 	 */
7285 	meta->msize_max_value = reg->umax_value;
7286 
7287 	/* The register is SCALAR_VALUE; the access check
7288 	 * happens using its boundaries.
7289 	 */
7290 	if (!tnum_is_const(reg->var_off))
7291 		/* For unprivileged variable accesses, disable raw
7292 		 * mode so that the program is required to
7293 		 * initialize all the memory that the helper could
7294 		 * just partially fill up.
7295 		 */
7296 		meta = NULL;
7297 
7298 	if (reg->smin_value < 0) {
7299 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7300 			regno);
7301 		return -EACCES;
7302 	}
7303 
7304 	if (reg->umin_value == 0) {
7305 		err = check_helper_mem_access(env, regno - 1, 0,
7306 					      zero_size_allowed,
7307 					      meta);
7308 		if (err)
7309 			return err;
7310 	}
7311 
7312 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7313 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7314 			regno);
7315 		return -EACCES;
7316 	}
7317 	err = check_helper_mem_access(env, regno - 1,
7318 				      reg->umax_value,
7319 				      zero_size_allowed, meta);
7320 	if (!err)
7321 		err = mark_chain_precision(env, regno);
7322 	return err;
7323 }
7324 
7325 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7326 		   u32 regno, u32 mem_size)
7327 {
7328 	bool may_be_null = type_may_be_null(reg->type);
7329 	struct bpf_reg_state saved_reg;
7330 	struct bpf_call_arg_meta meta;
7331 	int err;
7332 
7333 	if (register_is_null(reg))
7334 		return 0;
7335 
7336 	memset(&meta, 0, sizeof(meta));
7337 	/* Assuming that the register contains a value check if the memory
7338 	 * access is safe. Temporarily save and restore the register's state as
7339 	 * the conversion shouldn't be visible to a caller.
7340 	 */
7341 	if (may_be_null) {
7342 		saved_reg = *reg;
7343 		mark_ptr_not_null_reg(reg);
7344 	}
7345 
7346 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7347 	/* Check access for BPF_WRITE */
7348 	meta.raw_mode = true;
7349 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7350 
7351 	if (may_be_null)
7352 		*reg = saved_reg;
7353 
7354 	return err;
7355 }
7356 
7357 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7358 				    u32 regno)
7359 {
7360 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7361 	bool may_be_null = type_may_be_null(mem_reg->type);
7362 	struct bpf_reg_state saved_reg;
7363 	struct bpf_call_arg_meta meta;
7364 	int err;
7365 
7366 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7367 
7368 	memset(&meta, 0, sizeof(meta));
7369 
7370 	if (may_be_null) {
7371 		saved_reg = *mem_reg;
7372 		mark_ptr_not_null_reg(mem_reg);
7373 	}
7374 
7375 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7376 	/* Check access for BPF_WRITE */
7377 	meta.raw_mode = true;
7378 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7379 
7380 	if (may_be_null)
7381 		*mem_reg = saved_reg;
7382 	return err;
7383 }
7384 
7385 /* Implementation details:
7386  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7387  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7388  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7389  * Two separate bpf_obj_new will also have different reg->id.
7390  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7391  * clears reg->id after value_or_null->value transition, since the verifier only
7392  * cares about the range of access to valid map value pointer and doesn't care
7393  * about actual address of the map element.
7394  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7395  * reg->id > 0 after value_or_null->value transition. By doing so
7396  * two bpf_map_lookups will be considered two different pointers that
7397  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7398  * returned from bpf_obj_new.
7399  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7400  * dead-locks.
7401  * Since only one bpf_spin_lock is allowed the checks are simpler than
7402  * reg_is_refcounted() logic. The verifier needs to remember only
7403  * one spin_lock instead of array of acquired_refs.
7404  * cur_state->active_lock remembers which map value element or allocated
7405  * object got locked and clears it after bpf_spin_unlock.
7406  */
7407 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7408 			     bool is_lock)
7409 {
7410 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7411 	struct bpf_verifier_state *cur = env->cur_state;
7412 	bool is_const = tnum_is_const(reg->var_off);
7413 	u64 val = reg->var_off.value;
7414 	struct bpf_map *map = NULL;
7415 	struct btf *btf = NULL;
7416 	struct btf_record *rec;
7417 
7418 	if (!is_const) {
7419 		verbose(env,
7420 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7421 			regno);
7422 		return -EINVAL;
7423 	}
7424 	if (reg->type == PTR_TO_MAP_VALUE) {
7425 		map = reg->map_ptr;
7426 		if (!map->btf) {
7427 			verbose(env,
7428 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7429 				map->name);
7430 			return -EINVAL;
7431 		}
7432 	} else {
7433 		btf = reg->btf;
7434 	}
7435 
7436 	rec = reg_btf_record(reg);
7437 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7438 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7439 			map ? map->name : "kptr");
7440 		return -EINVAL;
7441 	}
7442 	if (rec->spin_lock_off != val + reg->off) {
7443 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7444 			val + reg->off, rec->spin_lock_off);
7445 		return -EINVAL;
7446 	}
7447 	if (is_lock) {
7448 		if (cur->active_lock.ptr) {
7449 			verbose(env,
7450 				"Locking two bpf_spin_locks are not allowed\n");
7451 			return -EINVAL;
7452 		}
7453 		if (map)
7454 			cur->active_lock.ptr = map;
7455 		else
7456 			cur->active_lock.ptr = btf;
7457 		cur->active_lock.id = reg->id;
7458 	} else {
7459 		void *ptr;
7460 
7461 		if (map)
7462 			ptr = map;
7463 		else
7464 			ptr = btf;
7465 
7466 		if (!cur->active_lock.ptr) {
7467 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7468 			return -EINVAL;
7469 		}
7470 		if (cur->active_lock.ptr != ptr ||
7471 		    cur->active_lock.id != reg->id) {
7472 			verbose(env, "bpf_spin_unlock of different lock\n");
7473 			return -EINVAL;
7474 		}
7475 
7476 		invalidate_non_owning_refs(env);
7477 
7478 		cur->active_lock.ptr = NULL;
7479 		cur->active_lock.id = 0;
7480 	}
7481 	return 0;
7482 }
7483 
7484 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7485 			      struct bpf_call_arg_meta *meta)
7486 {
7487 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7488 	bool is_const = tnum_is_const(reg->var_off);
7489 	struct bpf_map *map = reg->map_ptr;
7490 	u64 val = reg->var_off.value;
7491 
7492 	if (!is_const) {
7493 		verbose(env,
7494 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7495 			regno);
7496 		return -EINVAL;
7497 	}
7498 	if (!map->btf) {
7499 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7500 			map->name);
7501 		return -EINVAL;
7502 	}
7503 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7504 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7505 		return -EINVAL;
7506 	}
7507 	if (map->record->timer_off != val + reg->off) {
7508 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7509 			val + reg->off, map->record->timer_off);
7510 		return -EINVAL;
7511 	}
7512 	if (meta->map_ptr) {
7513 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7514 		return -EFAULT;
7515 	}
7516 	meta->map_uid = reg->map_uid;
7517 	meta->map_ptr = map;
7518 	return 0;
7519 }
7520 
7521 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7522 			     struct bpf_call_arg_meta *meta)
7523 {
7524 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7525 	struct bpf_map *map_ptr = reg->map_ptr;
7526 	struct btf_field *kptr_field;
7527 	u32 kptr_off;
7528 
7529 	if (!tnum_is_const(reg->var_off)) {
7530 		verbose(env,
7531 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7532 			regno);
7533 		return -EINVAL;
7534 	}
7535 	if (!map_ptr->btf) {
7536 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7537 			map_ptr->name);
7538 		return -EINVAL;
7539 	}
7540 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7541 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7542 		return -EINVAL;
7543 	}
7544 
7545 	meta->map_ptr = map_ptr;
7546 	kptr_off = reg->off + reg->var_off.value;
7547 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7548 	if (!kptr_field) {
7549 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7550 		return -EACCES;
7551 	}
7552 	if (kptr_field->type != BPF_KPTR_REF) {
7553 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7554 		return -EACCES;
7555 	}
7556 	meta->kptr_field = kptr_field;
7557 	return 0;
7558 }
7559 
7560 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7561  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7562  *
7563  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7564  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7565  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7566  *
7567  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7568  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7569  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7570  * mutate the view of the dynptr and also possibly destroy it. In the latter
7571  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7572  * memory that dynptr points to.
7573  *
7574  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7575  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7576  * readonly dynptr view yet, hence only the first case is tracked and checked.
7577  *
7578  * This is consistent with how C applies the const modifier to a struct object,
7579  * where the pointer itself inside bpf_dynptr becomes const but not what it
7580  * points to.
7581  *
7582  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7583  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7584  */
7585 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7586 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7587 {
7588 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7589 	int err;
7590 
7591 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7592 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7593 	 */
7594 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7595 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7596 		return -EFAULT;
7597 	}
7598 
7599 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7600 	 *		 constructing a mutable bpf_dynptr object.
7601 	 *
7602 	 *		 Currently, this is only possible with PTR_TO_STACK
7603 	 *		 pointing to a region of at least 16 bytes which doesn't
7604 	 *		 contain an existing bpf_dynptr.
7605 	 *
7606 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7607 	 *		 mutated or destroyed. However, the memory it points to
7608 	 *		 may be mutated.
7609 	 *
7610 	 *  None       - Points to a initialized dynptr that can be mutated and
7611 	 *		 destroyed, including mutation of the memory it points
7612 	 *		 to.
7613 	 */
7614 	if (arg_type & MEM_UNINIT) {
7615 		int i;
7616 
7617 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7618 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7619 			return -EINVAL;
7620 		}
7621 
7622 		/* we write BPF_DW bits (8 bytes) at a time */
7623 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7624 			err = check_mem_access(env, insn_idx, regno,
7625 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7626 			if (err)
7627 				return err;
7628 		}
7629 
7630 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7631 	} else /* MEM_RDONLY and None case from above */ {
7632 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7633 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7634 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7635 			return -EINVAL;
7636 		}
7637 
7638 		if (!is_dynptr_reg_valid_init(env, reg)) {
7639 			verbose(env,
7640 				"Expected an initialized dynptr as arg #%d\n",
7641 				regno);
7642 			return -EINVAL;
7643 		}
7644 
7645 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7646 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7647 			verbose(env,
7648 				"Expected a dynptr of type %s as arg #%d\n",
7649 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7650 			return -EINVAL;
7651 		}
7652 
7653 		err = mark_dynptr_read(env, reg);
7654 	}
7655 	return err;
7656 }
7657 
7658 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7659 {
7660 	struct bpf_func_state *state = func(env, reg);
7661 
7662 	return state->stack[spi].spilled_ptr.ref_obj_id;
7663 }
7664 
7665 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7666 {
7667 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7668 }
7669 
7670 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7671 {
7672 	return meta->kfunc_flags & KF_ITER_NEW;
7673 }
7674 
7675 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7676 {
7677 	return meta->kfunc_flags & KF_ITER_NEXT;
7678 }
7679 
7680 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7681 {
7682 	return meta->kfunc_flags & KF_ITER_DESTROY;
7683 }
7684 
7685 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7686 {
7687 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7688 	 * kfunc is iter state pointer
7689 	 */
7690 	return arg == 0 && is_iter_kfunc(meta);
7691 }
7692 
7693 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7694 			    struct bpf_kfunc_call_arg_meta *meta)
7695 {
7696 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7697 	const struct btf_type *t;
7698 	const struct btf_param *arg;
7699 	int spi, err, i, nr_slots;
7700 	u32 btf_id;
7701 
7702 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7703 	arg = &btf_params(meta->func_proto)[0];
7704 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7705 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7706 	nr_slots = t->size / BPF_REG_SIZE;
7707 
7708 	if (is_iter_new_kfunc(meta)) {
7709 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7710 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7711 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7712 				iter_type_str(meta->btf, btf_id), regno);
7713 			return -EINVAL;
7714 		}
7715 
7716 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7717 			err = check_mem_access(env, insn_idx, regno,
7718 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7719 			if (err)
7720 				return err;
7721 		}
7722 
7723 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7724 		if (err)
7725 			return err;
7726 	} else {
7727 		/* iter_next() or iter_destroy() expect initialized iter state*/
7728 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7729 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7730 				iter_type_str(meta->btf, btf_id), regno);
7731 			return -EINVAL;
7732 		}
7733 
7734 		spi = iter_get_spi(env, reg, nr_slots);
7735 		if (spi < 0)
7736 			return spi;
7737 
7738 		err = mark_iter_read(env, reg, spi, nr_slots);
7739 		if (err)
7740 			return err;
7741 
7742 		/* remember meta->iter info for process_iter_next_call() */
7743 		meta->iter.spi = spi;
7744 		meta->iter.frameno = reg->frameno;
7745 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7746 
7747 		if (is_iter_destroy_kfunc(meta)) {
7748 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7749 			if (err)
7750 				return err;
7751 		}
7752 	}
7753 
7754 	return 0;
7755 }
7756 
7757 /* Look for a previous loop entry at insn_idx: nearest parent state
7758  * stopped at insn_idx with callsites matching those in cur->frame.
7759  */
7760 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7761 						  struct bpf_verifier_state *cur,
7762 						  int insn_idx)
7763 {
7764 	struct bpf_verifier_state_list *sl;
7765 	struct bpf_verifier_state *st;
7766 
7767 	/* Explored states are pushed in stack order, most recent states come first */
7768 	sl = *explored_state(env, insn_idx);
7769 	for (; sl; sl = sl->next) {
7770 		/* If st->branches != 0 state is a part of current DFS verification path,
7771 		 * hence cur & st for a loop.
7772 		 */
7773 		st = &sl->state;
7774 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7775 		    st->dfs_depth < cur->dfs_depth)
7776 			return st;
7777 	}
7778 
7779 	return NULL;
7780 }
7781 
7782 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7783 static bool regs_exact(const struct bpf_reg_state *rold,
7784 		       const struct bpf_reg_state *rcur,
7785 		       struct bpf_idmap *idmap);
7786 
7787 static void maybe_widen_reg(struct bpf_verifier_env *env,
7788 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7789 			    struct bpf_idmap *idmap)
7790 {
7791 	if (rold->type != SCALAR_VALUE)
7792 		return;
7793 	if (rold->type != rcur->type)
7794 		return;
7795 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7796 		return;
7797 	__mark_reg_unknown(env, rcur);
7798 }
7799 
7800 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7801 				   struct bpf_verifier_state *old,
7802 				   struct bpf_verifier_state *cur)
7803 {
7804 	struct bpf_func_state *fold, *fcur;
7805 	int i, fr;
7806 
7807 	reset_idmap_scratch(env);
7808 	for (fr = old->curframe; fr >= 0; fr--) {
7809 		fold = old->frame[fr];
7810 		fcur = cur->frame[fr];
7811 
7812 		for (i = 0; i < MAX_BPF_REG; i++)
7813 			maybe_widen_reg(env,
7814 					&fold->regs[i],
7815 					&fcur->regs[i],
7816 					&env->idmap_scratch);
7817 
7818 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7819 			if (!is_spilled_reg(&fold->stack[i]) ||
7820 			    !is_spilled_reg(&fcur->stack[i]))
7821 				continue;
7822 
7823 			maybe_widen_reg(env,
7824 					&fold->stack[i].spilled_ptr,
7825 					&fcur->stack[i].spilled_ptr,
7826 					&env->idmap_scratch);
7827 		}
7828 	}
7829 	return 0;
7830 }
7831 
7832 /* process_iter_next_call() is called when verifier gets to iterator's next
7833  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7834  * to it as just "iter_next()" in comments below.
7835  *
7836  * BPF verifier relies on a crucial contract for any iter_next()
7837  * implementation: it should *eventually* return NULL, and once that happens
7838  * it should keep returning NULL. That is, once iterator exhausts elements to
7839  * iterate, it should never reset or spuriously return new elements.
7840  *
7841  * With the assumption of such contract, process_iter_next_call() simulates
7842  * a fork in the verifier state to validate loop logic correctness and safety
7843  * without having to simulate infinite amount of iterations.
7844  *
7845  * In current state, we first assume that iter_next() returned NULL and
7846  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7847  * conditions we should not form an infinite loop and should eventually reach
7848  * exit.
7849  *
7850  * Besides that, we also fork current state and enqueue it for later
7851  * verification. In a forked state we keep iterator state as ACTIVE
7852  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7853  * also bump iteration depth to prevent erroneous infinite loop detection
7854  * later on (see iter_active_depths_differ() comment for details). In this
7855  * state we assume that we'll eventually loop back to another iter_next()
7856  * calls (it could be in exactly same location or in some other instruction,
7857  * it doesn't matter, we don't make any unnecessary assumptions about this,
7858  * everything revolves around iterator state in a stack slot, not which
7859  * instruction is calling iter_next()). When that happens, we either will come
7860  * to iter_next() with equivalent state and can conclude that next iteration
7861  * will proceed in exactly the same way as we just verified, so it's safe to
7862  * assume that loop converges. If not, we'll go on another iteration
7863  * simulation with a different input state, until all possible starting states
7864  * are validated or we reach maximum number of instructions limit.
7865  *
7866  * This way, we will either exhaustively discover all possible input states
7867  * that iterator loop can start with and eventually will converge, or we'll
7868  * effectively regress into bounded loop simulation logic and either reach
7869  * maximum number of instructions if loop is not provably convergent, or there
7870  * is some statically known limit on number of iterations (e.g., if there is
7871  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7872  *
7873  * Iteration convergence logic in is_state_visited() relies on exact
7874  * states comparison, which ignores read and precision marks.
7875  * This is necessary because read and precision marks are not finalized
7876  * while in the loop. Exact comparison might preclude convergence for
7877  * simple programs like below:
7878  *
7879  *     i = 0;
7880  *     while(iter_next(&it))
7881  *       i++;
7882  *
7883  * At each iteration step i++ would produce a new distinct state and
7884  * eventually instruction processing limit would be reached.
7885  *
7886  * To avoid such behavior speculatively forget (widen) range for
7887  * imprecise scalar registers, if those registers were not precise at the
7888  * end of the previous iteration and do not match exactly.
7889  *
7890  * This is a conservative heuristic that allows to verify wide range of programs,
7891  * however it precludes verification of programs that conjure an
7892  * imprecise value on the first loop iteration and use it as precise on a second.
7893  * For example, the following safe program would fail to verify:
7894  *
7895  *     struct bpf_num_iter it;
7896  *     int arr[10];
7897  *     int i = 0, a = 0;
7898  *     bpf_iter_num_new(&it, 0, 10);
7899  *     while (bpf_iter_num_next(&it)) {
7900  *       if (a == 0) {
7901  *         a = 1;
7902  *         i = 7; // Because i changed verifier would forget
7903  *                // it's range on second loop entry.
7904  *       } else {
7905  *         arr[i] = 42; // This would fail to verify.
7906  *       }
7907  *     }
7908  *     bpf_iter_num_destroy(&it);
7909  */
7910 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7911 				  struct bpf_kfunc_call_arg_meta *meta)
7912 {
7913 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7914 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7915 	struct bpf_reg_state *cur_iter, *queued_iter;
7916 	int iter_frameno = meta->iter.frameno;
7917 	int iter_spi = meta->iter.spi;
7918 
7919 	BTF_TYPE_EMIT(struct bpf_iter);
7920 
7921 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7922 
7923 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7924 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7925 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7926 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7927 		return -EFAULT;
7928 	}
7929 
7930 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7931 		/* Because iter_next() call is a checkpoint is_state_visitied()
7932 		 * should guarantee parent state with same call sites and insn_idx.
7933 		 */
7934 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7935 		    !same_callsites(cur_st->parent, cur_st)) {
7936 			verbose(env, "bug: bad parent state for iter next call");
7937 			return -EFAULT;
7938 		}
7939 		/* Note cur_st->parent in the call below, it is necessary to skip
7940 		 * checkpoint created for cur_st by is_state_visited()
7941 		 * right at this instruction.
7942 		 */
7943 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7944 		/* branch out active iter state */
7945 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7946 		if (!queued_st)
7947 			return -ENOMEM;
7948 
7949 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7950 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7951 		queued_iter->iter.depth++;
7952 		if (prev_st)
7953 			widen_imprecise_scalars(env, prev_st, queued_st);
7954 
7955 		queued_fr = queued_st->frame[queued_st->curframe];
7956 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7957 	}
7958 
7959 	/* switch to DRAINED state, but keep the depth unchanged */
7960 	/* mark current iter state as drained and assume returned NULL */
7961 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7962 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7963 
7964 	return 0;
7965 }
7966 
7967 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7968 {
7969 	return type == ARG_CONST_SIZE ||
7970 	       type == ARG_CONST_SIZE_OR_ZERO;
7971 }
7972 
7973 static bool arg_type_is_release(enum bpf_arg_type type)
7974 {
7975 	return type & OBJ_RELEASE;
7976 }
7977 
7978 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7979 {
7980 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7981 }
7982 
7983 static int int_ptr_type_to_size(enum bpf_arg_type type)
7984 {
7985 	if (type == ARG_PTR_TO_INT)
7986 		return sizeof(u32);
7987 	else if (type == ARG_PTR_TO_LONG)
7988 		return sizeof(u64);
7989 
7990 	return -EINVAL;
7991 }
7992 
7993 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7994 				 const struct bpf_call_arg_meta *meta,
7995 				 enum bpf_arg_type *arg_type)
7996 {
7997 	if (!meta->map_ptr) {
7998 		/* kernel subsystem misconfigured verifier */
7999 		verbose(env, "invalid map_ptr to access map->type\n");
8000 		return -EACCES;
8001 	}
8002 
8003 	switch (meta->map_ptr->map_type) {
8004 	case BPF_MAP_TYPE_SOCKMAP:
8005 	case BPF_MAP_TYPE_SOCKHASH:
8006 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8007 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8008 		} else {
8009 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8010 			return -EINVAL;
8011 		}
8012 		break;
8013 	case BPF_MAP_TYPE_BLOOM_FILTER:
8014 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8015 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8016 		break;
8017 	default:
8018 		break;
8019 	}
8020 	return 0;
8021 }
8022 
8023 struct bpf_reg_types {
8024 	const enum bpf_reg_type types[10];
8025 	u32 *btf_id;
8026 };
8027 
8028 static const struct bpf_reg_types sock_types = {
8029 	.types = {
8030 		PTR_TO_SOCK_COMMON,
8031 		PTR_TO_SOCKET,
8032 		PTR_TO_TCP_SOCK,
8033 		PTR_TO_XDP_SOCK,
8034 	},
8035 };
8036 
8037 #ifdef CONFIG_NET
8038 static const struct bpf_reg_types btf_id_sock_common_types = {
8039 	.types = {
8040 		PTR_TO_SOCK_COMMON,
8041 		PTR_TO_SOCKET,
8042 		PTR_TO_TCP_SOCK,
8043 		PTR_TO_XDP_SOCK,
8044 		PTR_TO_BTF_ID,
8045 		PTR_TO_BTF_ID | PTR_TRUSTED,
8046 	},
8047 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8048 };
8049 #endif
8050 
8051 static const struct bpf_reg_types mem_types = {
8052 	.types = {
8053 		PTR_TO_STACK,
8054 		PTR_TO_PACKET,
8055 		PTR_TO_PACKET_META,
8056 		PTR_TO_MAP_KEY,
8057 		PTR_TO_MAP_VALUE,
8058 		PTR_TO_MEM,
8059 		PTR_TO_MEM | MEM_RINGBUF,
8060 		PTR_TO_BUF,
8061 		PTR_TO_BTF_ID | PTR_TRUSTED,
8062 	},
8063 };
8064 
8065 static const struct bpf_reg_types int_ptr_types = {
8066 	.types = {
8067 		PTR_TO_STACK,
8068 		PTR_TO_PACKET,
8069 		PTR_TO_PACKET_META,
8070 		PTR_TO_MAP_KEY,
8071 		PTR_TO_MAP_VALUE,
8072 	},
8073 };
8074 
8075 static const struct bpf_reg_types spin_lock_types = {
8076 	.types = {
8077 		PTR_TO_MAP_VALUE,
8078 		PTR_TO_BTF_ID | MEM_ALLOC,
8079 	}
8080 };
8081 
8082 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8083 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8084 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8085 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8086 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8087 static const struct bpf_reg_types btf_ptr_types = {
8088 	.types = {
8089 		PTR_TO_BTF_ID,
8090 		PTR_TO_BTF_ID | PTR_TRUSTED,
8091 		PTR_TO_BTF_ID | MEM_RCU,
8092 	},
8093 };
8094 static const struct bpf_reg_types percpu_btf_ptr_types = {
8095 	.types = {
8096 		PTR_TO_BTF_ID | MEM_PERCPU,
8097 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8098 	}
8099 };
8100 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8101 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8102 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8103 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8104 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8105 static const struct bpf_reg_types dynptr_types = {
8106 	.types = {
8107 		PTR_TO_STACK,
8108 		CONST_PTR_TO_DYNPTR,
8109 	}
8110 };
8111 
8112 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8113 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8114 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8115 	[ARG_CONST_SIZE]		= &scalar_types,
8116 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8117 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8118 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8119 	[ARG_PTR_TO_CTX]		= &context_types,
8120 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8121 #ifdef CONFIG_NET
8122 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8123 #endif
8124 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8125 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8126 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8127 	[ARG_PTR_TO_MEM]		= &mem_types,
8128 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8129 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8130 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8131 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8132 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8133 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8134 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8135 	[ARG_PTR_TO_TIMER]		= &timer_types,
8136 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8137 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8138 };
8139 
8140 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8141 			  enum bpf_arg_type arg_type,
8142 			  const u32 *arg_btf_id,
8143 			  struct bpf_call_arg_meta *meta)
8144 {
8145 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8146 	enum bpf_reg_type expected, type = reg->type;
8147 	const struct bpf_reg_types *compatible;
8148 	int i, j;
8149 
8150 	compatible = compatible_reg_types[base_type(arg_type)];
8151 	if (!compatible) {
8152 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8153 		return -EFAULT;
8154 	}
8155 
8156 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8157 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8158 	 *
8159 	 * Same for MAYBE_NULL:
8160 	 *
8161 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8162 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8163 	 *
8164 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8165 	 *
8166 	 * Therefore we fold these flags depending on the arg_type before comparison.
8167 	 */
8168 	if (arg_type & MEM_RDONLY)
8169 		type &= ~MEM_RDONLY;
8170 	if (arg_type & PTR_MAYBE_NULL)
8171 		type &= ~PTR_MAYBE_NULL;
8172 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8173 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8174 
8175 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8176 		type &= ~MEM_ALLOC;
8177 
8178 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8179 		expected = compatible->types[i];
8180 		if (expected == NOT_INIT)
8181 			break;
8182 
8183 		if (type == expected)
8184 			goto found;
8185 	}
8186 
8187 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8188 	for (j = 0; j + 1 < i; j++)
8189 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8190 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8191 	return -EACCES;
8192 
8193 found:
8194 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8195 		return 0;
8196 
8197 	if (compatible == &mem_types) {
8198 		if (!(arg_type & MEM_RDONLY)) {
8199 			verbose(env,
8200 				"%s() may write into memory pointed by R%d type=%s\n",
8201 				func_id_name(meta->func_id),
8202 				regno, reg_type_str(env, reg->type));
8203 			return -EACCES;
8204 		}
8205 		return 0;
8206 	}
8207 
8208 	switch ((int)reg->type) {
8209 	case PTR_TO_BTF_ID:
8210 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8211 	case PTR_TO_BTF_ID | MEM_RCU:
8212 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8213 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8214 	{
8215 		/* For bpf_sk_release, it needs to match against first member
8216 		 * 'struct sock_common', hence make an exception for it. This
8217 		 * allows bpf_sk_release to work for multiple socket types.
8218 		 */
8219 		bool strict_type_match = arg_type_is_release(arg_type) &&
8220 					 meta->func_id != BPF_FUNC_sk_release;
8221 
8222 		if (type_may_be_null(reg->type) &&
8223 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8224 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8225 			return -EACCES;
8226 		}
8227 
8228 		if (!arg_btf_id) {
8229 			if (!compatible->btf_id) {
8230 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8231 				return -EFAULT;
8232 			}
8233 			arg_btf_id = compatible->btf_id;
8234 		}
8235 
8236 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8237 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8238 				return -EACCES;
8239 		} else {
8240 			if (arg_btf_id == BPF_PTR_POISON) {
8241 				verbose(env, "verifier internal error:");
8242 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8243 					regno);
8244 				return -EACCES;
8245 			}
8246 
8247 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8248 						  btf_vmlinux, *arg_btf_id,
8249 						  strict_type_match)) {
8250 				verbose(env, "R%d is of type %s but %s is expected\n",
8251 					regno, btf_type_name(reg->btf, reg->btf_id),
8252 					btf_type_name(btf_vmlinux, *arg_btf_id));
8253 				return -EACCES;
8254 			}
8255 		}
8256 		break;
8257 	}
8258 	case PTR_TO_BTF_ID | MEM_ALLOC:
8259 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8260 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8261 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8262 			return -EFAULT;
8263 		}
8264 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8265 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8266 				return -EACCES;
8267 		}
8268 		break;
8269 	case PTR_TO_BTF_ID | MEM_PERCPU:
8270 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8271 		/* Handled by helper specific checks */
8272 		break;
8273 	default:
8274 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8275 		return -EFAULT;
8276 	}
8277 	return 0;
8278 }
8279 
8280 static struct btf_field *
8281 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8282 {
8283 	struct btf_field *field;
8284 	struct btf_record *rec;
8285 
8286 	rec = reg_btf_record(reg);
8287 	if (!rec)
8288 		return NULL;
8289 
8290 	field = btf_record_find(rec, off, fields);
8291 	if (!field)
8292 		return NULL;
8293 
8294 	return field;
8295 }
8296 
8297 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8298 			   const struct bpf_reg_state *reg, int regno,
8299 			   enum bpf_arg_type arg_type)
8300 {
8301 	u32 type = reg->type;
8302 
8303 	/* When referenced register is passed to release function, its fixed
8304 	 * offset must be 0.
8305 	 *
8306 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8307 	 * meta->release_regno.
8308 	 */
8309 	if (arg_type_is_release(arg_type)) {
8310 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8311 		 * may not directly point to the object being released, but to
8312 		 * dynptr pointing to such object, which might be at some offset
8313 		 * on the stack. In that case, we simply to fallback to the
8314 		 * default handling.
8315 		 */
8316 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8317 			return 0;
8318 
8319 		/* Doing check_ptr_off_reg check for the offset will catch this
8320 		 * because fixed_off_ok is false, but checking here allows us
8321 		 * to give the user a better error message.
8322 		 */
8323 		if (reg->off) {
8324 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8325 				regno);
8326 			return -EINVAL;
8327 		}
8328 		return __check_ptr_off_reg(env, reg, regno, false);
8329 	}
8330 
8331 	switch (type) {
8332 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8333 	case PTR_TO_STACK:
8334 	case PTR_TO_PACKET:
8335 	case PTR_TO_PACKET_META:
8336 	case PTR_TO_MAP_KEY:
8337 	case PTR_TO_MAP_VALUE:
8338 	case PTR_TO_MEM:
8339 	case PTR_TO_MEM | MEM_RDONLY:
8340 	case PTR_TO_MEM | MEM_RINGBUF:
8341 	case PTR_TO_BUF:
8342 	case PTR_TO_BUF | MEM_RDONLY:
8343 	case SCALAR_VALUE:
8344 		return 0;
8345 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8346 	 * fixed offset.
8347 	 */
8348 	case PTR_TO_BTF_ID:
8349 	case PTR_TO_BTF_ID | MEM_ALLOC:
8350 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8351 	case PTR_TO_BTF_ID | MEM_RCU:
8352 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8353 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8354 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8355 		 * its fixed offset must be 0. In the other cases, fixed offset
8356 		 * can be non-zero. This was already checked above. So pass
8357 		 * fixed_off_ok as true to allow fixed offset for all other
8358 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8359 		 * still need to do checks instead of returning.
8360 		 */
8361 		return __check_ptr_off_reg(env, reg, regno, true);
8362 	default:
8363 		return __check_ptr_off_reg(env, reg, regno, false);
8364 	}
8365 }
8366 
8367 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8368 						const struct bpf_func_proto *fn,
8369 						struct bpf_reg_state *regs)
8370 {
8371 	struct bpf_reg_state *state = NULL;
8372 	int i;
8373 
8374 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8375 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8376 			if (state) {
8377 				verbose(env, "verifier internal error: multiple dynptr args\n");
8378 				return NULL;
8379 			}
8380 			state = &regs[BPF_REG_1 + i];
8381 		}
8382 
8383 	if (!state)
8384 		verbose(env, "verifier internal error: no dynptr arg found\n");
8385 
8386 	return state;
8387 }
8388 
8389 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8390 {
8391 	struct bpf_func_state *state = func(env, reg);
8392 	int spi;
8393 
8394 	if (reg->type == CONST_PTR_TO_DYNPTR)
8395 		return reg->id;
8396 	spi = dynptr_get_spi(env, reg);
8397 	if (spi < 0)
8398 		return spi;
8399 	return state->stack[spi].spilled_ptr.id;
8400 }
8401 
8402 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8403 {
8404 	struct bpf_func_state *state = func(env, reg);
8405 	int spi;
8406 
8407 	if (reg->type == CONST_PTR_TO_DYNPTR)
8408 		return reg->ref_obj_id;
8409 	spi = dynptr_get_spi(env, reg);
8410 	if (spi < 0)
8411 		return spi;
8412 	return state->stack[spi].spilled_ptr.ref_obj_id;
8413 }
8414 
8415 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8416 					    struct bpf_reg_state *reg)
8417 {
8418 	struct bpf_func_state *state = func(env, reg);
8419 	int spi;
8420 
8421 	if (reg->type == CONST_PTR_TO_DYNPTR)
8422 		return reg->dynptr.type;
8423 
8424 	spi = __get_spi(reg->off);
8425 	if (spi < 0) {
8426 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8427 		return BPF_DYNPTR_TYPE_INVALID;
8428 	}
8429 
8430 	return state->stack[spi].spilled_ptr.dynptr.type;
8431 }
8432 
8433 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8434 			  struct bpf_call_arg_meta *meta,
8435 			  const struct bpf_func_proto *fn,
8436 			  int insn_idx)
8437 {
8438 	u32 regno = BPF_REG_1 + arg;
8439 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8440 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8441 	enum bpf_reg_type type = reg->type;
8442 	u32 *arg_btf_id = NULL;
8443 	int err = 0;
8444 
8445 	if (arg_type == ARG_DONTCARE)
8446 		return 0;
8447 
8448 	err = check_reg_arg(env, regno, SRC_OP);
8449 	if (err)
8450 		return err;
8451 
8452 	if (arg_type == ARG_ANYTHING) {
8453 		if (is_pointer_value(env, regno)) {
8454 			verbose(env, "R%d leaks addr into helper function\n",
8455 				regno);
8456 			return -EACCES;
8457 		}
8458 		return 0;
8459 	}
8460 
8461 	if (type_is_pkt_pointer(type) &&
8462 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8463 		verbose(env, "helper access to the packet is not allowed\n");
8464 		return -EACCES;
8465 	}
8466 
8467 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8468 		err = resolve_map_arg_type(env, meta, &arg_type);
8469 		if (err)
8470 			return err;
8471 	}
8472 
8473 	if (register_is_null(reg) && type_may_be_null(arg_type))
8474 		/* A NULL register has a SCALAR_VALUE type, so skip
8475 		 * type checking.
8476 		 */
8477 		goto skip_type_check;
8478 
8479 	/* arg_btf_id and arg_size are in a union. */
8480 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8481 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8482 		arg_btf_id = fn->arg_btf_id[arg];
8483 
8484 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8485 	if (err)
8486 		return err;
8487 
8488 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8489 	if (err)
8490 		return err;
8491 
8492 skip_type_check:
8493 	if (arg_type_is_release(arg_type)) {
8494 		if (arg_type_is_dynptr(arg_type)) {
8495 			struct bpf_func_state *state = func(env, reg);
8496 			int spi;
8497 
8498 			/* Only dynptr created on stack can be released, thus
8499 			 * the get_spi and stack state checks for spilled_ptr
8500 			 * should only be done before process_dynptr_func for
8501 			 * PTR_TO_STACK.
8502 			 */
8503 			if (reg->type == PTR_TO_STACK) {
8504 				spi = dynptr_get_spi(env, reg);
8505 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8506 					verbose(env, "arg %d is an unacquired reference\n", regno);
8507 					return -EINVAL;
8508 				}
8509 			} else {
8510 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8511 				return -EINVAL;
8512 			}
8513 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8514 			verbose(env, "R%d must be referenced when passed to release function\n",
8515 				regno);
8516 			return -EINVAL;
8517 		}
8518 		if (meta->release_regno) {
8519 			verbose(env, "verifier internal error: more than one release argument\n");
8520 			return -EFAULT;
8521 		}
8522 		meta->release_regno = regno;
8523 	}
8524 
8525 	if (reg->ref_obj_id) {
8526 		if (meta->ref_obj_id) {
8527 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8528 				regno, reg->ref_obj_id,
8529 				meta->ref_obj_id);
8530 			return -EFAULT;
8531 		}
8532 		meta->ref_obj_id = reg->ref_obj_id;
8533 	}
8534 
8535 	switch (base_type(arg_type)) {
8536 	case ARG_CONST_MAP_PTR:
8537 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8538 		if (meta->map_ptr) {
8539 			/* Use map_uid (which is unique id of inner map) to reject:
8540 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8541 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8542 			 * if (inner_map1 && inner_map2) {
8543 			 *     timer = bpf_map_lookup_elem(inner_map1);
8544 			 *     if (timer)
8545 			 *         // mismatch would have been allowed
8546 			 *         bpf_timer_init(timer, inner_map2);
8547 			 * }
8548 			 *
8549 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8550 			 */
8551 			if (meta->map_ptr != reg->map_ptr ||
8552 			    meta->map_uid != reg->map_uid) {
8553 				verbose(env,
8554 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8555 					meta->map_uid, reg->map_uid);
8556 				return -EINVAL;
8557 			}
8558 		}
8559 		meta->map_ptr = reg->map_ptr;
8560 		meta->map_uid = reg->map_uid;
8561 		break;
8562 	case ARG_PTR_TO_MAP_KEY:
8563 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8564 		 * check that [key, key + map->key_size) are within
8565 		 * stack limits and initialized
8566 		 */
8567 		if (!meta->map_ptr) {
8568 			/* in function declaration map_ptr must come before
8569 			 * map_key, so that it's verified and known before
8570 			 * we have to check map_key here. Otherwise it means
8571 			 * that kernel subsystem misconfigured verifier
8572 			 */
8573 			verbose(env, "invalid map_ptr to access map->key\n");
8574 			return -EACCES;
8575 		}
8576 		err = check_helper_mem_access(env, regno,
8577 					      meta->map_ptr->key_size, false,
8578 					      NULL);
8579 		break;
8580 	case ARG_PTR_TO_MAP_VALUE:
8581 		if (type_may_be_null(arg_type) && register_is_null(reg))
8582 			return 0;
8583 
8584 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8585 		 * check [value, value + map->value_size) validity
8586 		 */
8587 		if (!meta->map_ptr) {
8588 			/* kernel subsystem misconfigured verifier */
8589 			verbose(env, "invalid map_ptr to access map->value\n");
8590 			return -EACCES;
8591 		}
8592 		meta->raw_mode = arg_type & MEM_UNINIT;
8593 		err = check_helper_mem_access(env, regno,
8594 					      meta->map_ptr->value_size, false,
8595 					      meta);
8596 		break;
8597 	case ARG_PTR_TO_PERCPU_BTF_ID:
8598 		if (!reg->btf_id) {
8599 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8600 			return -EACCES;
8601 		}
8602 		meta->ret_btf = reg->btf;
8603 		meta->ret_btf_id = reg->btf_id;
8604 		break;
8605 	case ARG_PTR_TO_SPIN_LOCK:
8606 		if (in_rbtree_lock_required_cb(env)) {
8607 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8608 			return -EACCES;
8609 		}
8610 		if (meta->func_id == BPF_FUNC_spin_lock) {
8611 			err = process_spin_lock(env, regno, true);
8612 			if (err)
8613 				return err;
8614 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8615 			err = process_spin_lock(env, regno, false);
8616 			if (err)
8617 				return err;
8618 		} else {
8619 			verbose(env, "verifier internal error\n");
8620 			return -EFAULT;
8621 		}
8622 		break;
8623 	case ARG_PTR_TO_TIMER:
8624 		err = process_timer_func(env, regno, meta);
8625 		if (err)
8626 			return err;
8627 		break;
8628 	case ARG_PTR_TO_FUNC:
8629 		meta->subprogno = reg->subprogno;
8630 		break;
8631 	case ARG_PTR_TO_MEM:
8632 		/* The access to this pointer is only checked when we hit the
8633 		 * next is_mem_size argument below.
8634 		 */
8635 		meta->raw_mode = arg_type & MEM_UNINIT;
8636 		if (arg_type & MEM_FIXED_SIZE) {
8637 			err = check_helper_mem_access(env, regno,
8638 						      fn->arg_size[arg], false,
8639 						      meta);
8640 		}
8641 		break;
8642 	case ARG_CONST_SIZE:
8643 		err = check_mem_size_reg(env, reg, regno, false, meta);
8644 		break;
8645 	case ARG_CONST_SIZE_OR_ZERO:
8646 		err = check_mem_size_reg(env, reg, regno, true, meta);
8647 		break;
8648 	case ARG_PTR_TO_DYNPTR:
8649 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8650 		if (err)
8651 			return err;
8652 		break;
8653 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8654 		if (!tnum_is_const(reg->var_off)) {
8655 			verbose(env, "R%d is not a known constant'\n",
8656 				regno);
8657 			return -EACCES;
8658 		}
8659 		meta->mem_size = reg->var_off.value;
8660 		err = mark_chain_precision(env, regno);
8661 		if (err)
8662 			return err;
8663 		break;
8664 	case ARG_PTR_TO_INT:
8665 	case ARG_PTR_TO_LONG:
8666 	{
8667 		int size = int_ptr_type_to_size(arg_type);
8668 
8669 		err = check_helper_mem_access(env, regno, size, false, meta);
8670 		if (err)
8671 			return err;
8672 		err = check_ptr_alignment(env, reg, 0, size, true);
8673 		break;
8674 	}
8675 	case ARG_PTR_TO_CONST_STR:
8676 	{
8677 		struct bpf_map *map = reg->map_ptr;
8678 		int map_off;
8679 		u64 map_addr;
8680 		char *str_ptr;
8681 
8682 		if (!bpf_map_is_rdonly(map)) {
8683 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8684 			return -EACCES;
8685 		}
8686 
8687 		if (!tnum_is_const(reg->var_off)) {
8688 			verbose(env, "R%d is not a constant address'\n", regno);
8689 			return -EACCES;
8690 		}
8691 
8692 		if (!map->ops->map_direct_value_addr) {
8693 			verbose(env, "no direct value access support for this map type\n");
8694 			return -EACCES;
8695 		}
8696 
8697 		err = check_map_access(env, regno, reg->off,
8698 				       map->value_size - reg->off, false,
8699 				       ACCESS_HELPER);
8700 		if (err)
8701 			return err;
8702 
8703 		map_off = reg->off + reg->var_off.value;
8704 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8705 		if (err) {
8706 			verbose(env, "direct value access on string failed\n");
8707 			return err;
8708 		}
8709 
8710 		str_ptr = (char *)(long)(map_addr);
8711 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8712 			verbose(env, "string is not zero-terminated\n");
8713 			return -EINVAL;
8714 		}
8715 		break;
8716 	}
8717 	case ARG_PTR_TO_KPTR:
8718 		err = process_kptr_func(env, regno, meta);
8719 		if (err)
8720 			return err;
8721 		break;
8722 	}
8723 
8724 	return err;
8725 }
8726 
8727 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8728 {
8729 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8730 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8731 
8732 	if (func_id != BPF_FUNC_map_update_elem)
8733 		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_SOCKET_FILTER:
8744 	case BPF_PROG_TYPE_SCHED_CLS:
8745 	case BPF_PROG_TYPE_SCHED_ACT:
8746 	case BPF_PROG_TYPE_XDP:
8747 	case BPF_PROG_TYPE_SK_REUSEPORT:
8748 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8749 	case BPF_PROG_TYPE_SK_LOOKUP:
8750 		return true;
8751 	default:
8752 		break;
8753 	}
8754 
8755 	verbose(env, "cannot update sockmap in this context\n");
8756 	return false;
8757 }
8758 
8759 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8760 {
8761 	return env->prog->jit_requested &&
8762 	       bpf_jit_supports_subprog_tailcalls();
8763 }
8764 
8765 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8766 					struct bpf_map *map, int func_id)
8767 {
8768 	if (!map)
8769 		return 0;
8770 
8771 	/* We need a two way check, first is from map perspective ... */
8772 	switch (map->map_type) {
8773 	case BPF_MAP_TYPE_PROG_ARRAY:
8774 		if (func_id != BPF_FUNC_tail_call)
8775 			goto error;
8776 		break;
8777 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8778 		if (func_id != BPF_FUNC_perf_event_read &&
8779 		    func_id != BPF_FUNC_perf_event_output &&
8780 		    func_id != BPF_FUNC_skb_output &&
8781 		    func_id != BPF_FUNC_perf_event_read_value &&
8782 		    func_id != BPF_FUNC_xdp_output)
8783 			goto error;
8784 		break;
8785 	case BPF_MAP_TYPE_RINGBUF:
8786 		if (func_id != BPF_FUNC_ringbuf_output &&
8787 		    func_id != BPF_FUNC_ringbuf_reserve &&
8788 		    func_id != BPF_FUNC_ringbuf_query &&
8789 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8790 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8791 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8792 			goto error;
8793 		break;
8794 	case BPF_MAP_TYPE_USER_RINGBUF:
8795 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8796 			goto error;
8797 		break;
8798 	case BPF_MAP_TYPE_STACK_TRACE:
8799 		if (func_id != BPF_FUNC_get_stackid)
8800 			goto error;
8801 		break;
8802 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8803 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8804 		    func_id != BPF_FUNC_current_task_under_cgroup)
8805 			goto error;
8806 		break;
8807 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8808 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8809 		if (func_id != BPF_FUNC_get_local_storage)
8810 			goto error;
8811 		break;
8812 	case BPF_MAP_TYPE_DEVMAP:
8813 	case BPF_MAP_TYPE_DEVMAP_HASH:
8814 		if (func_id != BPF_FUNC_redirect_map &&
8815 		    func_id != BPF_FUNC_map_lookup_elem)
8816 			goto error;
8817 		break;
8818 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8819 	 * appear.
8820 	 */
8821 	case BPF_MAP_TYPE_CPUMAP:
8822 		if (func_id != BPF_FUNC_redirect_map)
8823 			goto error;
8824 		break;
8825 	case BPF_MAP_TYPE_XSKMAP:
8826 		if (func_id != BPF_FUNC_redirect_map &&
8827 		    func_id != BPF_FUNC_map_lookup_elem)
8828 			goto error;
8829 		break;
8830 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8831 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8832 		if (func_id != BPF_FUNC_map_lookup_elem)
8833 			goto error;
8834 		break;
8835 	case BPF_MAP_TYPE_SOCKMAP:
8836 		if (func_id != BPF_FUNC_sk_redirect_map &&
8837 		    func_id != BPF_FUNC_sock_map_update &&
8838 		    func_id != BPF_FUNC_map_delete_elem &&
8839 		    func_id != BPF_FUNC_msg_redirect_map &&
8840 		    func_id != BPF_FUNC_sk_select_reuseport &&
8841 		    func_id != BPF_FUNC_map_lookup_elem &&
8842 		    !may_update_sockmap(env, func_id))
8843 			goto error;
8844 		break;
8845 	case BPF_MAP_TYPE_SOCKHASH:
8846 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8847 		    func_id != BPF_FUNC_sock_hash_update &&
8848 		    func_id != BPF_FUNC_map_delete_elem &&
8849 		    func_id != BPF_FUNC_msg_redirect_hash &&
8850 		    func_id != BPF_FUNC_sk_select_reuseport &&
8851 		    func_id != BPF_FUNC_map_lookup_elem &&
8852 		    !may_update_sockmap(env, func_id))
8853 			goto error;
8854 		break;
8855 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8856 		if (func_id != BPF_FUNC_sk_select_reuseport)
8857 			goto error;
8858 		break;
8859 	case BPF_MAP_TYPE_QUEUE:
8860 	case BPF_MAP_TYPE_STACK:
8861 		if (func_id != BPF_FUNC_map_peek_elem &&
8862 		    func_id != BPF_FUNC_map_pop_elem &&
8863 		    func_id != BPF_FUNC_map_push_elem)
8864 			goto error;
8865 		break;
8866 	case BPF_MAP_TYPE_SK_STORAGE:
8867 		if (func_id != BPF_FUNC_sk_storage_get &&
8868 		    func_id != BPF_FUNC_sk_storage_delete &&
8869 		    func_id != BPF_FUNC_kptr_xchg)
8870 			goto error;
8871 		break;
8872 	case BPF_MAP_TYPE_INODE_STORAGE:
8873 		if (func_id != BPF_FUNC_inode_storage_get &&
8874 		    func_id != BPF_FUNC_inode_storage_delete &&
8875 		    func_id != BPF_FUNC_kptr_xchg)
8876 			goto error;
8877 		break;
8878 	case BPF_MAP_TYPE_TASK_STORAGE:
8879 		if (func_id != BPF_FUNC_task_storage_get &&
8880 		    func_id != BPF_FUNC_task_storage_delete &&
8881 		    func_id != BPF_FUNC_kptr_xchg)
8882 			goto error;
8883 		break;
8884 	case BPF_MAP_TYPE_CGRP_STORAGE:
8885 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8886 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8887 		    func_id != BPF_FUNC_kptr_xchg)
8888 			goto error;
8889 		break;
8890 	case BPF_MAP_TYPE_BLOOM_FILTER:
8891 		if (func_id != BPF_FUNC_map_peek_elem &&
8892 		    func_id != BPF_FUNC_map_push_elem)
8893 			goto error;
8894 		break;
8895 	default:
8896 		break;
8897 	}
8898 
8899 	/* ... and second from the function itself. */
8900 	switch (func_id) {
8901 	case BPF_FUNC_tail_call:
8902 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8903 			goto error;
8904 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8905 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8906 			return -EINVAL;
8907 		}
8908 		break;
8909 	case BPF_FUNC_perf_event_read:
8910 	case BPF_FUNC_perf_event_output:
8911 	case BPF_FUNC_perf_event_read_value:
8912 	case BPF_FUNC_skb_output:
8913 	case BPF_FUNC_xdp_output:
8914 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8915 			goto error;
8916 		break;
8917 	case BPF_FUNC_ringbuf_output:
8918 	case BPF_FUNC_ringbuf_reserve:
8919 	case BPF_FUNC_ringbuf_query:
8920 	case BPF_FUNC_ringbuf_reserve_dynptr:
8921 	case BPF_FUNC_ringbuf_submit_dynptr:
8922 	case BPF_FUNC_ringbuf_discard_dynptr:
8923 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8924 			goto error;
8925 		break;
8926 	case BPF_FUNC_user_ringbuf_drain:
8927 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8928 			goto error;
8929 		break;
8930 	case BPF_FUNC_get_stackid:
8931 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8932 			goto error;
8933 		break;
8934 	case BPF_FUNC_current_task_under_cgroup:
8935 	case BPF_FUNC_skb_under_cgroup:
8936 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8937 			goto error;
8938 		break;
8939 	case BPF_FUNC_redirect_map:
8940 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8941 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8942 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8943 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8944 			goto error;
8945 		break;
8946 	case BPF_FUNC_sk_redirect_map:
8947 	case BPF_FUNC_msg_redirect_map:
8948 	case BPF_FUNC_sock_map_update:
8949 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8950 			goto error;
8951 		break;
8952 	case BPF_FUNC_sk_redirect_hash:
8953 	case BPF_FUNC_msg_redirect_hash:
8954 	case BPF_FUNC_sock_hash_update:
8955 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8956 			goto error;
8957 		break;
8958 	case BPF_FUNC_get_local_storage:
8959 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8960 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8961 			goto error;
8962 		break;
8963 	case BPF_FUNC_sk_select_reuseport:
8964 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8965 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8966 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8967 			goto error;
8968 		break;
8969 	case BPF_FUNC_map_pop_elem:
8970 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8971 		    map->map_type != BPF_MAP_TYPE_STACK)
8972 			goto error;
8973 		break;
8974 	case BPF_FUNC_map_peek_elem:
8975 	case BPF_FUNC_map_push_elem:
8976 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8977 		    map->map_type != BPF_MAP_TYPE_STACK &&
8978 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8979 			goto error;
8980 		break;
8981 	case BPF_FUNC_map_lookup_percpu_elem:
8982 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8983 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8984 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8985 			goto error;
8986 		break;
8987 	case BPF_FUNC_sk_storage_get:
8988 	case BPF_FUNC_sk_storage_delete:
8989 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8990 			goto error;
8991 		break;
8992 	case BPF_FUNC_inode_storage_get:
8993 	case BPF_FUNC_inode_storage_delete:
8994 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8995 			goto error;
8996 		break;
8997 	case BPF_FUNC_task_storage_get:
8998 	case BPF_FUNC_task_storage_delete:
8999 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9000 			goto error;
9001 		break;
9002 	case BPF_FUNC_cgrp_storage_get:
9003 	case BPF_FUNC_cgrp_storage_delete:
9004 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9005 			goto error;
9006 		break;
9007 	default:
9008 		break;
9009 	}
9010 
9011 	return 0;
9012 error:
9013 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9014 		map->map_type, func_id_name(func_id), func_id);
9015 	return -EINVAL;
9016 }
9017 
9018 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9019 {
9020 	int count = 0;
9021 
9022 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9023 		count++;
9024 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9025 		count++;
9026 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9027 		count++;
9028 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9029 		count++;
9030 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9031 		count++;
9032 
9033 	/* We only support one arg being in raw mode at the moment,
9034 	 * which is sufficient for the helper functions we have
9035 	 * right now.
9036 	 */
9037 	return count <= 1;
9038 }
9039 
9040 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9041 {
9042 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9043 	bool has_size = fn->arg_size[arg] != 0;
9044 	bool is_next_size = false;
9045 
9046 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9047 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9048 
9049 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9050 		return is_next_size;
9051 
9052 	return has_size == is_next_size || is_next_size == is_fixed;
9053 }
9054 
9055 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9056 {
9057 	/* bpf_xxx(..., buf, len) call will access 'len'
9058 	 * bytes from memory 'buf'. Both arg types need
9059 	 * to be paired, so make sure there's no buggy
9060 	 * helper function specification.
9061 	 */
9062 	if (arg_type_is_mem_size(fn->arg1_type) ||
9063 	    check_args_pair_invalid(fn, 0) ||
9064 	    check_args_pair_invalid(fn, 1) ||
9065 	    check_args_pair_invalid(fn, 2) ||
9066 	    check_args_pair_invalid(fn, 3) ||
9067 	    check_args_pair_invalid(fn, 4))
9068 		return false;
9069 
9070 	return true;
9071 }
9072 
9073 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9074 {
9075 	int i;
9076 
9077 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9078 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9079 			return !!fn->arg_btf_id[i];
9080 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9081 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9082 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9083 		    /* arg_btf_id and arg_size are in a union. */
9084 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9085 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9086 			return false;
9087 	}
9088 
9089 	return true;
9090 }
9091 
9092 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9093 {
9094 	return check_raw_mode_ok(fn) &&
9095 	       check_arg_pair_ok(fn) &&
9096 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9097 }
9098 
9099 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9100  * are now invalid, so turn them into unknown SCALAR_VALUE.
9101  *
9102  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9103  * since these slices point to packet data.
9104  */
9105 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9106 {
9107 	struct bpf_func_state *state;
9108 	struct bpf_reg_state *reg;
9109 
9110 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9111 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9112 			mark_reg_invalid(env, reg);
9113 	}));
9114 }
9115 
9116 enum {
9117 	AT_PKT_END = -1,
9118 	BEYOND_PKT_END = -2,
9119 };
9120 
9121 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9122 {
9123 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9124 	struct bpf_reg_state *reg = &state->regs[regn];
9125 
9126 	if (reg->type != PTR_TO_PACKET)
9127 		/* PTR_TO_PACKET_META is not supported yet */
9128 		return;
9129 
9130 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9131 	 * How far beyond pkt_end it goes is unknown.
9132 	 * if (!range_open) it's the case of pkt >= pkt_end
9133 	 * if (range_open) it's the case of pkt > pkt_end
9134 	 * hence this pointer is at least 1 byte bigger than pkt_end
9135 	 */
9136 	if (range_open)
9137 		reg->range = BEYOND_PKT_END;
9138 	else
9139 		reg->range = AT_PKT_END;
9140 }
9141 
9142 /* The pointer with the specified id has released its reference to kernel
9143  * resources. Identify all copies of the same pointer and clear the reference.
9144  */
9145 static int release_reference(struct bpf_verifier_env *env,
9146 			     int ref_obj_id)
9147 {
9148 	struct bpf_func_state *state;
9149 	struct bpf_reg_state *reg;
9150 	int err;
9151 
9152 	err = release_reference_state(cur_func(env), ref_obj_id);
9153 	if (err)
9154 		return err;
9155 
9156 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9157 		if (reg->ref_obj_id == ref_obj_id)
9158 			mark_reg_invalid(env, reg);
9159 	}));
9160 
9161 	return 0;
9162 }
9163 
9164 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9165 {
9166 	struct bpf_func_state *unused;
9167 	struct bpf_reg_state *reg;
9168 
9169 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9170 		if (type_is_non_owning_ref(reg->type))
9171 			mark_reg_invalid(env, reg);
9172 	}));
9173 }
9174 
9175 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9176 				    struct bpf_reg_state *regs)
9177 {
9178 	int i;
9179 
9180 	/* after the call registers r0 - r5 were scratched */
9181 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9182 		mark_reg_not_init(env, regs, caller_saved[i]);
9183 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9184 	}
9185 }
9186 
9187 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9188 				   struct bpf_func_state *caller,
9189 				   struct bpf_func_state *callee,
9190 				   int insn_idx);
9191 
9192 static int set_callee_state(struct bpf_verifier_env *env,
9193 			    struct bpf_func_state *caller,
9194 			    struct bpf_func_state *callee, int insn_idx);
9195 
9196 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9197 			    set_callee_state_fn set_callee_state_cb,
9198 			    struct bpf_verifier_state *state)
9199 {
9200 	struct bpf_func_state *caller, *callee;
9201 	int err;
9202 
9203 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9204 		verbose(env, "the call stack of %d frames is too deep\n",
9205 			state->curframe + 2);
9206 		return -E2BIG;
9207 	}
9208 
9209 	if (state->frame[state->curframe + 1]) {
9210 		verbose(env, "verifier bug. Frame %d already allocated\n",
9211 			state->curframe + 1);
9212 		return -EFAULT;
9213 	}
9214 
9215 	caller = state->frame[state->curframe];
9216 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9217 	if (!callee)
9218 		return -ENOMEM;
9219 	state->frame[state->curframe + 1] = callee;
9220 
9221 	/* callee cannot access r0, r6 - r9 for reading and has to write
9222 	 * into its own stack before reading from it.
9223 	 * callee can read/write into caller's stack
9224 	 */
9225 	init_func_state(env, callee,
9226 			/* remember the callsite, it will be used by bpf_exit */
9227 			callsite,
9228 			state->curframe + 1 /* frameno within this callchain */,
9229 			subprog /* subprog number within this prog */);
9230 	/* Transfer references to the callee */
9231 	err = copy_reference_state(callee, caller);
9232 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9233 	if (err)
9234 		goto err_out;
9235 
9236 	/* only increment it after check_reg_arg() finished */
9237 	state->curframe++;
9238 
9239 	return 0;
9240 
9241 err_out:
9242 	free_func_state(callee);
9243 	state->frame[state->curframe + 1] = NULL;
9244 	return err;
9245 }
9246 
9247 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9248 			      int insn_idx, int subprog,
9249 			      set_callee_state_fn set_callee_state_cb)
9250 {
9251 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9252 	struct bpf_func_state *caller, *callee;
9253 	int err;
9254 
9255 	caller = state->frame[state->curframe];
9256 	err = btf_check_subprog_call(env, subprog, caller->regs);
9257 	if (err == -EFAULT)
9258 		return err;
9259 
9260 	/* set_callee_state is used for direct subprog calls, but we are
9261 	 * interested in validating only BPF helpers that can call subprogs as
9262 	 * callbacks
9263 	 */
9264 	if (bpf_pseudo_kfunc_call(insn) &&
9265 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9266 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9267 			func_id_name(insn->imm), insn->imm);
9268 		return -EFAULT;
9269 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9270 		   !is_callback_calling_function(insn->imm)) { /* helper */
9271 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9272 			func_id_name(insn->imm), insn->imm);
9273 		return -EFAULT;
9274 	}
9275 
9276 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9277 	    insn->src_reg == 0 &&
9278 	    insn->imm == BPF_FUNC_timer_set_callback) {
9279 		struct bpf_verifier_state *async_cb;
9280 
9281 		/* there is no real recursion here. timer callbacks are async */
9282 		env->subprog_info[subprog].is_async_cb = true;
9283 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9284 					 insn_idx, subprog);
9285 		if (!async_cb)
9286 			return -EFAULT;
9287 		callee = async_cb->frame[0];
9288 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9289 
9290 		/* Convert bpf_timer_set_callback() args into timer callback args */
9291 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9292 		if (err)
9293 			return err;
9294 
9295 		return 0;
9296 	}
9297 
9298 	/* for callback functions enqueue entry to callback and
9299 	 * proceed with next instruction within current frame.
9300 	 */
9301 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9302 	if (!callback_state)
9303 		return -ENOMEM;
9304 
9305 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9306 			       callback_state);
9307 	if (err)
9308 		return err;
9309 
9310 	callback_state->callback_unroll_depth++;
9311 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9312 	caller->callback_depth = 0;
9313 	return 0;
9314 }
9315 
9316 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9317 			   int *insn_idx)
9318 {
9319 	struct bpf_verifier_state *state = env->cur_state;
9320 	struct bpf_func_state *caller;
9321 	int err, subprog, target_insn;
9322 
9323 	target_insn = *insn_idx + insn->imm + 1;
9324 	subprog = find_subprog(env, target_insn);
9325 	if (subprog < 0) {
9326 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9327 		return -EFAULT;
9328 	}
9329 
9330 	caller = state->frame[state->curframe];
9331 	err = btf_check_subprog_call(env, subprog, caller->regs);
9332 	if (err == -EFAULT)
9333 		return err;
9334 	if (subprog_is_global(env, subprog)) {
9335 		if (err) {
9336 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9337 			return err;
9338 		}
9339 
9340 		if (env->log.level & BPF_LOG_LEVEL)
9341 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9342 		clear_caller_saved_regs(env, caller->regs);
9343 
9344 		/* All global functions return a 64-bit SCALAR_VALUE */
9345 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9346 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9347 
9348 		/* continue with next insn after call */
9349 		return 0;
9350 	}
9351 
9352 	/* for regular function entry setup new frame and continue
9353 	 * from that frame.
9354 	 */
9355 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9356 	if (err)
9357 		return err;
9358 
9359 	clear_caller_saved_regs(env, caller->regs);
9360 
9361 	/* and go analyze first insn of the callee */
9362 	*insn_idx = env->subprog_info[subprog].start - 1;
9363 
9364 	if (env->log.level & BPF_LOG_LEVEL) {
9365 		verbose(env, "caller:\n");
9366 		print_verifier_state(env, caller, true);
9367 		verbose(env, "callee:\n");
9368 		print_verifier_state(env, state->frame[state->curframe], true);
9369 	}
9370 
9371 	return 0;
9372 }
9373 
9374 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9375 				   struct bpf_func_state *caller,
9376 				   struct bpf_func_state *callee)
9377 {
9378 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9379 	 *      void *callback_ctx, u64 flags);
9380 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9381 	 *      void *callback_ctx);
9382 	 */
9383 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9384 
9385 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9386 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9387 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9388 
9389 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9390 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9391 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9392 
9393 	/* pointer to stack or null */
9394 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9395 
9396 	/* unused */
9397 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9398 	return 0;
9399 }
9400 
9401 static int set_callee_state(struct bpf_verifier_env *env,
9402 			    struct bpf_func_state *caller,
9403 			    struct bpf_func_state *callee, int insn_idx)
9404 {
9405 	int i;
9406 
9407 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9408 	 * pointers, which connects us up to the liveness chain
9409 	 */
9410 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9411 		callee->regs[i] = caller->regs[i];
9412 	return 0;
9413 }
9414 
9415 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9416 				       struct bpf_func_state *caller,
9417 				       struct bpf_func_state *callee,
9418 				       int insn_idx)
9419 {
9420 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9421 	struct bpf_map *map;
9422 	int err;
9423 
9424 	if (bpf_map_ptr_poisoned(insn_aux)) {
9425 		verbose(env, "tail_call abusing map_ptr\n");
9426 		return -EINVAL;
9427 	}
9428 
9429 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9430 	if (!map->ops->map_set_for_each_callback_args ||
9431 	    !map->ops->map_for_each_callback) {
9432 		verbose(env, "callback function not allowed for map\n");
9433 		return -ENOTSUPP;
9434 	}
9435 
9436 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9437 	if (err)
9438 		return err;
9439 
9440 	callee->in_callback_fn = true;
9441 	callee->callback_ret_range = tnum_range(0, 1);
9442 	return 0;
9443 }
9444 
9445 static int set_loop_callback_state(struct bpf_verifier_env *env,
9446 				   struct bpf_func_state *caller,
9447 				   struct bpf_func_state *callee,
9448 				   int insn_idx)
9449 {
9450 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9451 	 *	    u64 flags);
9452 	 * callback_fn(u32 index, void *callback_ctx);
9453 	 */
9454 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9455 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9456 
9457 	/* unused */
9458 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9459 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9460 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9461 
9462 	callee->in_callback_fn = true;
9463 	callee->callback_ret_range = tnum_range(0, 1);
9464 	return 0;
9465 }
9466 
9467 static int set_timer_callback_state(struct bpf_verifier_env *env,
9468 				    struct bpf_func_state *caller,
9469 				    struct bpf_func_state *callee,
9470 				    int insn_idx)
9471 {
9472 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9473 
9474 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9475 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9476 	 */
9477 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9478 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9479 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9480 
9481 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9482 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9483 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9484 
9485 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9486 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9487 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9488 
9489 	/* unused */
9490 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9491 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9492 	callee->in_async_callback_fn = true;
9493 	callee->callback_ret_range = tnum_range(0, 1);
9494 	return 0;
9495 }
9496 
9497 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9498 				       struct bpf_func_state *caller,
9499 				       struct bpf_func_state *callee,
9500 				       int insn_idx)
9501 {
9502 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9503 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9504 	 * (callback_fn)(struct task_struct *task,
9505 	 *               struct vm_area_struct *vma, void *callback_ctx);
9506 	 */
9507 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9508 
9509 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9510 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9511 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9512 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9513 
9514 	/* pointer to stack or null */
9515 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9516 
9517 	/* unused */
9518 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9519 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9520 	callee->in_callback_fn = true;
9521 	callee->callback_ret_range = tnum_range(0, 1);
9522 	return 0;
9523 }
9524 
9525 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9526 					   struct bpf_func_state *caller,
9527 					   struct bpf_func_state *callee,
9528 					   int insn_idx)
9529 {
9530 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9531 	 *			  callback_ctx, u64 flags);
9532 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9533 	 */
9534 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9535 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9536 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9537 
9538 	/* unused */
9539 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9540 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9541 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9542 
9543 	callee->in_callback_fn = true;
9544 	callee->callback_ret_range = tnum_range(0, 1);
9545 	return 0;
9546 }
9547 
9548 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9549 					 struct bpf_func_state *caller,
9550 					 struct bpf_func_state *callee,
9551 					 int insn_idx)
9552 {
9553 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9554 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9555 	 *
9556 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9557 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9558 	 * by this point, so look at 'root'
9559 	 */
9560 	struct btf_field *field;
9561 
9562 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9563 				      BPF_RB_ROOT);
9564 	if (!field || !field->graph_root.value_btf_id)
9565 		return -EFAULT;
9566 
9567 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9568 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9569 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9570 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9571 
9572 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9573 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9574 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9575 	callee->in_callback_fn = true;
9576 	callee->callback_ret_range = tnum_range(0, 1);
9577 	return 0;
9578 }
9579 
9580 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9581 
9582 /* Are we currently verifying the callback for a rbtree helper that must
9583  * be called with lock held? If so, no need to complain about unreleased
9584  * lock
9585  */
9586 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9587 {
9588 	struct bpf_verifier_state *state = env->cur_state;
9589 	struct bpf_insn *insn = env->prog->insnsi;
9590 	struct bpf_func_state *callee;
9591 	int kfunc_btf_id;
9592 
9593 	if (!state->curframe)
9594 		return false;
9595 
9596 	callee = state->frame[state->curframe];
9597 
9598 	if (!callee->in_callback_fn)
9599 		return false;
9600 
9601 	kfunc_btf_id = insn[callee->callsite].imm;
9602 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9603 }
9604 
9605 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9606 {
9607 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9608 	struct bpf_func_state *caller, *callee;
9609 	struct bpf_reg_state *r0;
9610 	bool in_callback_fn;
9611 	int err;
9612 
9613 	callee = state->frame[state->curframe];
9614 	r0 = &callee->regs[BPF_REG_0];
9615 	if (r0->type == PTR_TO_STACK) {
9616 		/* technically it's ok to return caller's stack pointer
9617 		 * (or caller's caller's pointer) back to the caller,
9618 		 * since these pointers are valid. Only current stack
9619 		 * pointer will be invalid as soon as function exits,
9620 		 * but let's be conservative
9621 		 */
9622 		verbose(env, "cannot return stack pointer to the caller\n");
9623 		return -EINVAL;
9624 	}
9625 
9626 	caller = state->frame[state->curframe - 1];
9627 	if (callee->in_callback_fn) {
9628 		/* enforce R0 return value range [0, 1]. */
9629 		struct tnum range = callee->callback_ret_range;
9630 
9631 		if (r0->type != SCALAR_VALUE) {
9632 			verbose(env, "R0 not a scalar value\n");
9633 			return -EACCES;
9634 		}
9635 
9636 		/* we are going to rely on register's precise value */
9637 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9638 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9639 		if (err)
9640 			return err;
9641 
9642 		if (!tnum_in(range, r0->var_off)) {
9643 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9644 			return -EINVAL;
9645 		}
9646 		if (!calls_callback(env, callee->callsite)) {
9647 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9648 				*insn_idx, callee->callsite);
9649 			return -EFAULT;
9650 		}
9651 	} else {
9652 		/* return to the caller whatever r0 had in the callee */
9653 		caller->regs[BPF_REG_0] = *r0;
9654 	}
9655 
9656 	/* callback_fn frame should have released its own additions to parent's
9657 	 * reference state at this point, or check_reference_leak would
9658 	 * complain, hence it must be the same as the caller. There is no need
9659 	 * to copy it back.
9660 	 */
9661 	if (!callee->in_callback_fn) {
9662 		/* Transfer references to the caller */
9663 		err = copy_reference_state(caller, callee);
9664 		if (err)
9665 			return err;
9666 	}
9667 
9668 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9669 	 * there function call logic would reschedule callback visit. If iteration
9670 	 * converges is_state_visited() would prune that visit eventually.
9671 	 */
9672 	in_callback_fn = callee->in_callback_fn;
9673 	if (in_callback_fn)
9674 		*insn_idx = callee->callsite;
9675 	else
9676 		*insn_idx = callee->callsite + 1;
9677 
9678 	if (env->log.level & BPF_LOG_LEVEL) {
9679 		verbose(env, "returning from callee:\n");
9680 		print_verifier_state(env, callee, true);
9681 		verbose(env, "to caller at %d:\n", *insn_idx);
9682 		print_verifier_state(env, caller, true);
9683 	}
9684 	/* clear everything in the callee */
9685 	free_func_state(callee);
9686 	state->frame[state->curframe--] = NULL;
9687 
9688 	/* for callbacks widen imprecise scalars to make programs like below verify:
9689 	 *
9690 	 *   struct ctx { int i; }
9691 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9692 	 *   ...
9693 	 *   struct ctx = { .i = 0; }
9694 	 *   bpf_loop(100, cb, &ctx, 0);
9695 	 *
9696 	 * This is similar to what is done in process_iter_next_call() for open
9697 	 * coded iterators.
9698 	 */
9699 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9700 	if (prev_st) {
9701 		err = widen_imprecise_scalars(env, prev_st, state);
9702 		if (err)
9703 			return err;
9704 	}
9705 	return 0;
9706 }
9707 
9708 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9709 				   int func_id,
9710 				   struct bpf_call_arg_meta *meta)
9711 {
9712 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9713 
9714 	if (ret_type != RET_INTEGER)
9715 		return;
9716 
9717 	switch (func_id) {
9718 	case BPF_FUNC_get_stack:
9719 	case BPF_FUNC_get_task_stack:
9720 	case BPF_FUNC_probe_read_str:
9721 	case BPF_FUNC_probe_read_kernel_str:
9722 	case BPF_FUNC_probe_read_user_str:
9723 		ret_reg->smax_value = meta->msize_max_value;
9724 		ret_reg->s32_max_value = meta->msize_max_value;
9725 		ret_reg->smin_value = -MAX_ERRNO;
9726 		ret_reg->s32_min_value = -MAX_ERRNO;
9727 		reg_bounds_sync(ret_reg);
9728 		break;
9729 	case BPF_FUNC_get_smp_processor_id:
9730 		ret_reg->umax_value = nr_cpu_ids - 1;
9731 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9732 		ret_reg->smax_value = nr_cpu_ids - 1;
9733 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9734 		ret_reg->umin_value = 0;
9735 		ret_reg->u32_min_value = 0;
9736 		ret_reg->smin_value = 0;
9737 		ret_reg->s32_min_value = 0;
9738 		reg_bounds_sync(ret_reg);
9739 		break;
9740 	}
9741 }
9742 
9743 static int
9744 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9745 		int func_id, int insn_idx)
9746 {
9747 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9748 	struct bpf_map *map = meta->map_ptr;
9749 
9750 	if (func_id != BPF_FUNC_tail_call &&
9751 	    func_id != BPF_FUNC_map_lookup_elem &&
9752 	    func_id != BPF_FUNC_map_update_elem &&
9753 	    func_id != BPF_FUNC_map_delete_elem &&
9754 	    func_id != BPF_FUNC_map_push_elem &&
9755 	    func_id != BPF_FUNC_map_pop_elem &&
9756 	    func_id != BPF_FUNC_map_peek_elem &&
9757 	    func_id != BPF_FUNC_for_each_map_elem &&
9758 	    func_id != BPF_FUNC_redirect_map &&
9759 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9760 		return 0;
9761 
9762 	if (map == NULL) {
9763 		verbose(env, "kernel subsystem misconfigured verifier\n");
9764 		return -EINVAL;
9765 	}
9766 
9767 	/* In case of read-only, some additional restrictions
9768 	 * need to be applied in order to prevent altering the
9769 	 * state of the map from program side.
9770 	 */
9771 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9772 	    (func_id == BPF_FUNC_map_delete_elem ||
9773 	     func_id == BPF_FUNC_map_update_elem ||
9774 	     func_id == BPF_FUNC_map_push_elem ||
9775 	     func_id == BPF_FUNC_map_pop_elem)) {
9776 		verbose(env, "write into map forbidden\n");
9777 		return -EACCES;
9778 	}
9779 
9780 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9781 		bpf_map_ptr_store(aux, meta->map_ptr,
9782 				  !meta->map_ptr->bypass_spec_v1);
9783 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9784 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9785 				  !meta->map_ptr->bypass_spec_v1);
9786 	return 0;
9787 }
9788 
9789 static int
9790 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9791 		int func_id, int insn_idx)
9792 {
9793 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9794 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9795 	struct bpf_map *map = meta->map_ptr;
9796 	u64 val, max;
9797 	int err;
9798 
9799 	if (func_id != BPF_FUNC_tail_call)
9800 		return 0;
9801 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9802 		verbose(env, "kernel subsystem misconfigured verifier\n");
9803 		return -EINVAL;
9804 	}
9805 
9806 	reg = &regs[BPF_REG_3];
9807 	val = reg->var_off.value;
9808 	max = map->max_entries;
9809 
9810 	if (!(register_is_const(reg) && val < max)) {
9811 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9812 		return 0;
9813 	}
9814 
9815 	err = mark_chain_precision(env, BPF_REG_3);
9816 	if (err)
9817 		return err;
9818 	if (bpf_map_key_unseen(aux))
9819 		bpf_map_key_store(aux, val);
9820 	else if (!bpf_map_key_poisoned(aux) &&
9821 		  bpf_map_key_immediate(aux) != val)
9822 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9823 	return 0;
9824 }
9825 
9826 static int check_reference_leak(struct bpf_verifier_env *env)
9827 {
9828 	struct bpf_func_state *state = cur_func(env);
9829 	bool refs_lingering = false;
9830 	int i;
9831 
9832 	if (state->frameno && !state->in_callback_fn)
9833 		return 0;
9834 
9835 	for (i = 0; i < state->acquired_refs; i++) {
9836 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9837 			continue;
9838 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9839 			state->refs[i].id, state->refs[i].insn_idx);
9840 		refs_lingering = true;
9841 	}
9842 	return refs_lingering ? -EINVAL : 0;
9843 }
9844 
9845 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9846 				   struct bpf_reg_state *regs)
9847 {
9848 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9849 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9850 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9851 	struct bpf_bprintf_data data = {};
9852 	int err, fmt_map_off, num_args;
9853 	u64 fmt_addr;
9854 	char *fmt;
9855 
9856 	/* data must be an array of u64 */
9857 	if (data_len_reg->var_off.value % 8)
9858 		return -EINVAL;
9859 	num_args = data_len_reg->var_off.value / 8;
9860 
9861 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9862 	 * and map_direct_value_addr is set.
9863 	 */
9864 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9865 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9866 						  fmt_map_off);
9867 	if (err) {
9868 		verbose(env, "verifier bug\n");
9869 		return -EFAULT;
9870 	}
9871 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9872 
9873 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9874 	 * can focus on validating the format specifiers.
9875 	 */
9876 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9877 	if (err < 0)
9878 		verbose(env, "Invalid format string\n");
9879 
9880 	return err;
9881 }
9882 
9883 static int check_get_func_ip(struct bpf_verifier_env *env)
9884 {
9885 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9886 	int func_id = BPF_FUNC_get_func_ip;
9887 
9888 	if (type == BPF_PROG_TYPE_TRACING) {
9889 		if (!bpf_prog_has_trampoline(env->prog)) {
9890 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9891 				func_id_name(func_id), func_id);
9892 			return -ENOTSUPP;
9893 		}
9894 		return 0;
9895 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9896 		return 0;
9897 	}
9898 
9899 	verbose(env, "func %s#%d not supported for program type %d\n",
9900 		func_id_name(func_id), func_id, type);
9901 	return -ENOTSUPP;
9902 }
9903 
9904 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9905 {
9906 	return &env->insn_aux_data[env->insn_idx];
9907 }
9908 
9909 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9910 {
9911 	struct bpf_reg_state *regs = cur_regs(env);
9912 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9913 	bool reg_is_null = register_is_null(reg);
9914 
9915 	if (reg_is_null)
9916 		mark_chain_precision(env, BPF_REG_4);
9917 
9918 	return reg_is_null;
9919 }
9920 
9921 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9922 {
9923 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9924 
9925 	if (!state->initialized) {
9926 		state->initialized = 1;
9927 		state->fit_for_inline = loop_flag_is_zero(env);
9928 		state->callback_subprogno = subprogno;
9929 		return;
9930 	}
9931 
9932 	if (!state->fit_for_inline)
9933 		return;
9934 
9935 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9936 				 state->callback_subprogno == subprogno);
9937 }
9938 
9939 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9940 			     int *insn_idx_p)
9941 {
9942 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9943 	const struct bpf_func_proto *fn = NULL;
9944 	enum bpf_return_type ret_type;
9945 	enum bpf_type_flag ret_flag;
9946 	struct bpf_reg_state *regs;
9947 	struct bpf_call_arg_meta meta;
9948 	int insn_idx = *insn_idx_p;
9949 	bool changes_data;
9950 	int i, err, func_id;
9951 
9952 	/* find function prototype */
9953 	func_id = insn->imm;
9954 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9955 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9956 			func_id);
9957 		return -EINVAL;
9958 	}
9959 
9960 	if (env->ops->get_func_proto)
9961 		fn = env->ops->get_func_proto(func_id, env->prog);
9962 	if (!fn) {
9963 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9964 			func_id);
9965 		return -EINVAL;
9966 	}
9967 
9968 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9969 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9970 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9971 		return -EINVAL;
9972 	}
9973 
9974 	if (fn->allowed && !fn->allowed(env->prog)) {
9975 		verbose(env, "helper call is not allowed in probe\n");
9976 		return -EINVAL;
9977 	}
9978 
9979 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9980 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9981 		return -EINVAL;
9982 	}
9983 
9984 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9985 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9986 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9987 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9988 			func_id_name(func_id), func_id);
9989 		return -EINVAL;
9990 	}
9991 
9992 	memset(&meta, 0, sizeof(meta));
9993 	meta.pkt_access = fn->pkt_access;
9994 
9995 	err = check_func_proto(fn, func_id);
9996 	if (err) {
9997 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9998 			func_id_name(func_id), func_id);
9999 		return err;
10000 	}
10001 
10002 	if (env->cur_state->active_rcu_lock) {
10003 		if (fn->might_sleep) {
10004 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10005 				func_id_name(func_id), func_id);
10006 			return -EINVAL;
10007 		}
10008 
10009 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10010 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10011 	}
10012 
10013 	meta.func_id = func_id;
10014 	/* check args */
10015 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10016 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10017 		if (err)
10018 			return err;
10019 	}
10020 
10021 	err = record_func_map(env, &meta, func_id, insn_idx);
10022 	if (err)
10023 		return err;
10024 
10025 	err = record_func_key(env, &meta, func_id, insn_idx);
10026 	if (err)
10027 		return err;
10028 
10029 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10030 	 * is inferred from register state.
10031 	 */
10032 	for (i = 0; i < meta.access_size; i++) {
10033 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10034 				       BPF_WRITE, -1, false, false);
10035 		if (err)
10036 			return err;
10037 	}
10038 
10039 	regs = cur_regs(env);
10040 
10041 	if (meta.release_regno) {
10042 		err = -EINVAL;
10043 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10044 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10045 		 * is safe to do directly.
10046 		 */
10047 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10048 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10049 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10050 				return -EFAULT;
10051 			}
10052 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10053 		} else if (meta.ref_obj_id) {
10054 			err = release_reference(env, meta.ref_obj_id);
10055 		} else if (register_is_null(&regs[meta.release_regno])) {
10056 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10057 			 * released is NULL, which must be > R0.
10058 			 */
10059 			err = 0;
10060 		}
10061 		if (err) {
10062 			verbose(env, "func %s#%d reference has not been acquired before\n",
10063 				func_id_name(func_id), func_id);
10064 			return err;
10065 		}
10066 	}
10067 
10068 	switch (func_id) {
10069 	case BPF_FUNC_tail_call:
10070 		err = check_reference_leak(env);
10071 		if (err) {
10072 			verbose(env, "tail_call would lead to reference leak\n");
10073 			return err;
10074 		}
10075 		break;
10076 	case BPF_FUNC_get_local_storage:
10077 		/* check that flags argument in get_local_storage(map, flags) is 0,
10078 		 * this is required because get_local_storage() can't return an error.
10079 		 */
10080 		if (!register_is_null(&regs[BPF_REG_2])) {
10081 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10082 			return -EINVAL;
10083 		}
10084 		break;
10085 	case BPF_FUNC_for_each_map_elem:
10086 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10087 					 set_map_elem_callback_state);
10088 		break;
10089 	case BPF_FUNC_timer_set_callback:
10090 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10091 					 set_timer_callback_state);
10092 		break;
10093 	case BPF_FUNC_find_vma:
10094 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10095 					 set_find_vma_callback_state);
10096 		break;
10097 	case BPF_FUNC_snprintf:
10098 		err = check_bpf_snprintf_call(env, regs);
10099 		break;
10100 	case BPF_FUNC_loop:
10101 		update_loop_inline_state(env, meta.subprogno);
10102 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10103 		 * is finished, thus mark it precise.
10104 		 */
10105 		err = mark_chain_precision(env, BPF_REG_1);
10106 		if (err)
10107 			return err;
10108 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10109 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10110 						 set_loop_callback_state);
10111 		} else {
10112 			cur_func(env)->callback_depth = 0;
10113 			if (env->log.level & BPF_LOG_LEVEL2)
10114 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10115 					env->cur_state->curframe);
10116 		}
10117 		break;
10118 	case BPF_FUNC_dynptr_from_mem:
10119 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10120 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10121 				reg_type_str(env, regs[BPF_REG_1].type));
10122 			return -EACCES;
10123 		}
10124 		break;
10125 	case BPF_FUNC_set_retval:
10126 		if (prog_type == BPF_PROG_TYPE_LSM &&
10127 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10128 			if (!env->prog->aux->attach_func_proto->type) {
10129 				/* Make sure programs that attach to void
10130 				 * hooks don't try to modify return value.
10131 				 */
10132 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10133 				return -EINVAL;
10134 			}
10135 		}
10136 		break;
10137 	case BPF_FUNC_dynptr_data:
10138 	{
10139 		struct bpf_reg_state *reg;
10140 		int id, ref_obj_id;
10141 
10142 		reg = get_dynptr_arg_reg(env, fn, regs);
10143 		if (!reg)
10144 			return -EFAULT;
10145 
10146 
10147 		if (meta.dynptr_id) {
10148 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10149 			return -EFAULT;
10150 		}
10151 		if (meta.ref_obj_id) {
10152 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10153 			return -EFAULT;
10154 		}
10155 
10156 		id = dynptr_id(env, reg);
10157 		if (id < 0) {
10158 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10159 			return id;
10160 		}
10161 
10162 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10163 		if (ref_obj_id < 0) {
10164 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10165 			return ref_obj_id;
10166 		}
10167 
10168 		meta.dynptr_id = id;
10169 		meta.ref_obj_id = ref_obj_id;
10170 
10171 		break;
10172 	}
10173 	case BPF_FUNC_dynptr_write:
10174 	{
10175 		enum bpf_dynptr_type dynptr_type;
10176 		struct bpf_reg_state *reg;
10177 
10178 		reg = get_dynptr_arg_reg(env, fn, regs);
10179 		if (!reg)
10180 			return -EFAULT;
10181 
10182 		dynptr_type = dynptr_get_type(env, reg);
10183 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10184 			return -EFAULT;
10185 
10186 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10187 			/* this will trigger clear_all_pkt_pointers(), which will
10188 			 * invalidate all dynptr slices associated with the skb
10189 			 */
10190 			changes_data = true;
10191 
10192 		break;
10193 	}
10194 	case BPF_FUNC_user_ringbuf_drain:
10195 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10196 					 set_user_ringbuf_callback_state);
10197 		break;
10198 	}
10199 
10200 	if (err)
10201 		return err;
10202 
10203 	/* reset caller saved regs */
10204 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10205 		mark_reg_not_init(env, regs, caller_saved[i]);
10206 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10207 	}
10208 
10209 	/* helper call returns 64-bit value. */
10210 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10211 
10212 	/* update return register (already marked as written above) */
10213 	ret_type = fn->ret_type;
10214 	ret_flag = type_flag(ret_type);
10215 
10216 	switch (base_type(ret_type)) {
10217 	case RET_INTEGER:
10218 		/* sets type to SCALAR_VALUE */
10219 		mark_reg_unknown(env, regs, BPF_REG_0);
10220 		break;
10221 	case RET_VOID:
10222 		regs[BPF_REG_0].type = NOT_INIT;
10223 		break;
10224 	case RET_PTR_TO_MAP_VALUE:
10225 		/* There is no offset yet applied, variable or fixed */
10226 		mark_reg_known_zero(env, regs, BPF_REG_0);
10227 		/* remember map_ptr, so that check_map_access()
10228 		 * can check 'value_size' boundary of memory access
10229 		 * to map element returned from bpf_map_lookup_elem()
10230 		 */
10231 		if (meta.map_ptr == NULL) {
10232 			verbose(env,
10233 				"kernel subsystem misconfigured verifier\n");
10234 			return -EINVAL;
10235 		}
10236 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10237 		regs[BPF_REG_0].map_uid = meta.map_uid;
10238 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10239 		if (!type_may_be_null(ret_type) &&
10240 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10241 			regs[BPF_REG_0].id = ++env->id_gen;
10242 		}
10243 		break;
10244 	case RET_PTR_TO_SOCKET:
10245 		mark_reg_known_zero(env, regs, BPF_REG_0);
10246 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10247 		break;
10248 	case RET_PTR_TO_SOCK_COMMON:
10249 		mark_reg_known_zero(env, regs, BPF_REG_0);
10250 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10251 		break;
10252 	case RET_PTR_TO_TCP_SOCK:
10253 		mark_reg_known_zero(env, regs, BPF_REG_0);
10254 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10255 		break;
10256 	case RET_PTR_TO_MEM:
10257 		mark_reg_known_zero(env, regs, BPF_REG_0);
10258 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10259 		regs[BPF_REG_0].mem_size = meta.mem_size;
10260 		break;
10261 	case RET_PTR_TO_MEM_OR_BTF_ID:
10262 	{
10263 		const struct btf_type *t;
10264 
10265 		mark_reg_known_zero(env, regs, BPF_REG_0);
10266 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10267 		if (!btf_type_is_struct(t)) {
10268 			u32 tsize;
10269 			const struct btf_type *ret;
10270 			const char *tname;
10271 
10272 			/* resolve the type size of ksym. */
10273 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10274 			if (IS_ERR(ret)) {
10275 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10276 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10277 					tname, PTR_ERR(ret));
10278 				return -EINVAL;
10279 			}
10280 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10281 			regs[BPF_REG_0].mem_size = tsize;
10282 		} else {
10283 			/* MEM_RDONLY may be carried from ret_flag, but it
10284 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10285 			 * it will confuse the check of PTR_TO_BTF_ID in
10286 			 * check_mem_access().
10287 			 */
10288 			ret_flag &= ~MEM_RDONLY;
10289 
10290 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10291 			regs[BPF_REG_0].btf = meta.ret_btf;
10292 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10293 		}
10294 		break;
10295 	}
10296 	case RET_PTR_TO_BTF_ID:
10297 	{
10298 		struct btf *ret_btf;
10299 		int ret_btf_id;
10300 
10301 		mark_reg_known_zero(env, regs, BPF_REG_0);
10302 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10303 		if (func_id == BPF_FUNC_kptr_xchg) {
10304 			ret_btf = meta.kptr_field->kptr.btf;
10305 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10306 			if (!btf_is_kernel(ret_btf))
10307 				regs[BPF_REG_0].type |= MEM_ALLOC;
10308 		} else {
10309 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10310 				verbose(env, "verifier internal error:");
10311 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10312 					func_id_name(func_id));
10313 				return -EINVAL;
10314 			}
10315 			ret_btf = btf_vmlinux;
10316 			ret_btf_id = *fn->ret_btf_id;
10317 		}
10318 		if (ret_btf_id == 0) {
10319 			verbose(env, "invalid return type %u of func %s#%d\n",
10320 				base_type(ret_type), func_id_name(func_id),
10321 				func_id);
10322 			return -EINVAL;
10323 		}
10324 		regs[BPF_REG_0].btf = ret_btf;
10325 		regs[BPF_REG_0].btf_id = ret_btf_id;
10326 		break;
10327 	}
10328 	default:
10329 		verbose(env, "unknown return type %u of func %s#%d\n",
10330 			base_type(ret_type), func_id_name(func_id), func_id);
10331 		return -EINVAL;
10332 	}
10333 
10334 	if (type_may_be_null(regs[BPF_REG_0].type))
10335 		regs[BPF_REG_0].id = ++env->id_gen;
10336 
10337 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10338 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10339 			func_id_name(func_id), func_id);
10340 		return -EFAULT;
10341 	}
10342 
10343 	if (is_dynptr_ref_function(func_id))
10344 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10345 
10346 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10347 		/* For release_reference() */
10348 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10349 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10350 		int id = acquire_reference_state(env, insn_idx);
10351 
10352 		if (id < 0)
10353 			return id;
10354 		/* For mark_ptr_or_null_reg() */
10355 		regs[BPF_REG_0].id = id;
10356 		/* For release_reference() */
10357 		regs[BPF_REG_0].ref_obj_id = id;
10358 	}
10359 
10360 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10361 
10362 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10363 	if (err)
10364 		return err;
10365 
10366 	if ((func_id == BPF_FUNC_get_stack ||
10367 	     func_id == BPF_FUNC_get_task_stack) &&
10368 	    !env->prog->has_callchain_buf) {
10369 		const char *err_str;
10370 
10371 #ifdef CONFIG_PERF_EVENTS
10372 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10373 		err_str = "cannot get callchain buffer for func %s#%d\n";
10374 #else
10375 		err = -ENOTSUPP;
10376 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10377 #endif
10378 		if (err) {
10379 			verbose(env, err_str, func_id_name(func_id), func_id);
10380 			return err;
10381 		}
10382 
10383 		env->prog->has_callchain_buf = true;
10384 	}
10385 
10386 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10387 		env->prog->call_get_stack = true;
10388 
10389 	if (func_id == BPF_FUNC_get_func_ip) {
10390 		if (check_get_func_ip(env))
10391 			return -ENOTSUPP;
10392 		env->prog->call_get_func_ip = true;
10393 	}
10394 
10395 	if (changes_data)
10396 		clear_all_pkt_pointers(env);
10397 	return 0;
10398 }
10399 
10400 /* mark_btf_func_reg_size() is used when the reg size is determined by
10401  * the BTF func_proto's return value size and argument.
10402  */
10403 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10404 				   size_t reg_size)
10405 {
10406 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10407 
10408 	if (regno == BPF_REG_0) {
10409 		/* Function return value */
10410 		reg->live |= REG_LIVE_WRITTEN;
10411 		reg->subreg_def = reg_size == sizeof(u64) ?
10412 			DEF_NOT_SUBREG : env->insn_idx + 1;
10413 	} else {
10414 		/* Function argument */
10415 		if (reg_size == sizeof(u64)) {
10416 			mark_insn_zext(env, reg);
10417 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10418 		} else {
10419 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10420 		}
10421 	}
10422 }
10423 
10424 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10425 {
10426 	return meta->kfunc_flags & KF_ACQUIRE;
10427 }
10428 
10429 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10430 {
10431 	return meta->kfunc_flags & KF_RELEASE;
10432 }
10433 
10434 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10435 {
10436 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10437 }
10438 
10439 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10440 {
10441 	return meta->kfunc_flags & KF_SLEEPABLE;
10442 }
10443 
10444 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10445 {
10446 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10447 }
10448 
10449 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10450 {
10451 	return meta->kfunc_flags & KF_RCU;
10452 }
10453 
10454 static bool __kfunc_param_match_suffix(const struct btf *btf,
10455 				       const struct btf_param *arg,
10456 				       const char *suffix)
10457 {
10458 	int suffix_len = strlen(suffix), len;
10459 	const char *param_name;
10460 
10461 	/* In the future, this can be ported to use BTF tagging */
10462 	param_name = btf_name_by_offset(btf, arg->name_off);
10463 	if (str_is_empty(param_name))
10464 		return false;
10465 	len = strlen(param_name);
10466 	if (len < suffix_len)
10467 		return false;
10468 	param_name += len - suffix_len;
10469 	return !strncmp(param_name, suffix, suffix_len);
10470 }
10471 
10472 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10473 				  const struct btf_param *arg,
10474 				  const struct bpf_reg_state *reg)
10475 {
10476 	const struct btf_type *t;
10477 
10478 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10479 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10480 		return false;
10481 
10482 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10483 }
10484 
10485 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10486 					const struct btf_param *arg,
10487 					const struct bpf_reg_state *reg)
10488 {
10489 	const struct btf_type *t;
10490 
10491 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10492 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10493 		return false;
10494 
10495 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10496 }
10497 
10498 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10499 {
10500 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10501 }
10502 
10503 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10504 {
10505 	return __kfunc_param_match_suffix(btf, arg, "__k");
10506 }
10507 
10508 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10509 {
10510 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10511 }
10512 
10513 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10514 {
10515 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10516 }
10517 
10518 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10519 {
10520 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10521 }
10522 
10523 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10524 {
10525 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10526 }
10527 
10528 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10529 					  const struct btf_param *arg,
10530 					  const char *name)
10531 {
10532 	int len, target_len = strlen(name);
10533 	const char *param_name;
10534 
10535 	param_name = btf_name_by_offset(btf, arg->name_off);
10536 	if (str_is_empty(param_name))
10537 		return false;
10538 	len = strlen(param_name);
10539 	if (len != target_len)
10540 		return false;
10541 	if (strcmp(param_name, name))
10542 		return false;
10543 
10544 	return true;
10545 }
10546 
10547 enum {
10548 	KF_ARG_DYNPTR_ID,
10549 	KF_ARG_LIST_HEAD_ID,
10550 	KF_ARG_LIST_NODE_ID,
10551 	KF_ARG_RB_ROOT_ID,
10552 	KF_ARG_RB_NODE_ID,
10553 };
10554 
10555 BTF_ID_LIST(kf_arg_btf_ids)
10556 BTF_ID(struct, bpf_dynptr_kern)
10557 BTF_ID(struct, bpf_list_head)
10558 BTF_ID(struct, bpf_list_node)
10559 BTF_ID(struct, bpf_rb_root)
10560 BTF_ID(struct, bpf_rb_node)
10561 
10562 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10563 				    const struct btf_param *arg, int type)
10564 {
10565 	const struct btf_type *t;
10566 	u32 res_id;
10567 
10568 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10569 	if (!t)
10570 		return false;
10571 	if (!btf_type_is_ptr(t))
10572 		return false;
10573 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10574 	if (!t)
10575 		return false;
10576 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10577 }
10578 
10579 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10580 {
10581 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10582 }
10583 
10584 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10585 {
10586 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10587 }
10588 
10589 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10590 {
10591 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10592 }
10593 
10594 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10595 {
10596 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10597 }
10598 
10599 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10600 {
10601 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10602 }
10603 
10604 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10605 				  const struct btf_param *arg)
10606 {
10607 	const struct btf_type *t;
10608 
10609 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10610 	if (!t)
10611 		return false;
10612 
10613 	return true;
10614 }
10615 
10616 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10617 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10618 					const struct btf *btf,
10619 					const struct btf_type *t, int rec)
10620 {
10621 	const struct btf_type *member_type;
10622 	const struct btf_member *member;
10623 	u32 i;
10624 
10625 	if (!btf_type_is_struct(t))
10626 		return false;
10627 
10628 	for_each_member(i, t, member) {
10629 		const struct btf_array *array;
10630 
10631 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10632 		if (btf_type_is_struct(member_type)) {
10633 			if (rec >= 3) {
10634 				verbose(env, "max struct nesting depth exceeded\n");
10635 				return false;
10636 			}
10637 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10638 				return false;
10639 			continue;
10640 		}
10641 		if (btf_type_is_array(member_type)) {
10642 			array = btf_array(member_type);
10643 			if (!array->nelems)
10644 				return false;
10645 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10646 			if (!btf_type_is_scalar(member_type))
10647 				return false;
10648 			continue;
10649 		}
10650 		if (!btf_type_is_scalar(member_type))
10651 			return false;
10652 	}
10653 	return true;
10654 }
10655 
10656 enum kfunc_ptr_arg_type {
10657 	KF_ARG_PTR_TO_CTX,
10658 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10659 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10660 	KF_ARG_PTR_TO_DYNPTR,
10661 	KF_ARG_PTR_TO_ITER,
10662 	KF_ARG_PTR_TO_LIST_HEAD,
10663 	KF_ARG_PTR_TO_LIST_NODE,
10664 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10665 	KF_ARG_PTR_TO_MEM,
10666 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10667 	KF_ARG_PTR_TO_CALLBACK,
10668 	KF_ARG_PTR_TO_RB_ROOT,
10669 	KF_ARG_PTR_TO_RB_NODE,
10670 };
10671 
10672 enum special_kfunc_type {
10673 	KF_bpf_obj_new_impl,
10674 	KF_bpf_obj_drop_impl,
10675 	KF_bpf_refcount_acquire_impl,
10676 	KF_bpf_list_push_front_impl,
10677 	KF_bpf_list_push_back_impl,
10678 	KF_bpf_list_pop_front,
10679 	KF_bpf_list_pop_back,
10680 	KF_bpf_cast_to_kern_ctx,
10681 	KF_bpf_rdonly_cast,
10682 	KF_bpf_rcu_read_lock,
10683 	KF_bpf_rcu_read_unlock,
10684 	KF_bpf_rbtree_remove,
10685 	KF_bpf_rbtree_add_impl,
10686 	KF_bpf_rbtree_first,
10687 	KF_bpf_dynptr_from_skb,
10688 	KF_bpf_dynptr_from_xdp,
10689 	KF_bpf_dynptr_slice,
10690 	KF_bpf_dynptr_slice_rdwr,
10691 	KF_bpf_dynptr_clone,
10692 };
10693 
10694 BTF_SET_START(special_kfunc_set)
10695 BTF_ID(func, bpf_obj_new_impl)
10696 BTF_ID(func, bpf_obj_drop_impl)
10697 BTF_ID(func, bpf_refcount_acquire_impl)
10698 BTF_ID(func, bpf_list_push_front_impl)
10699 BTF_ID(func, bpf_list_push_back_impl)
10700 BTF_ID(func, bpf_list_pop_front)
10701 BTF_ID(func, bpf_list_pop_back)
10702 BTF_ID(func, bpf_cast_to_kern_ctx)
10703 BTF_ID(func, bpf_rdonly_cast)
10704 BTF_ID(func, bpf_rbtree_remove)
10705 BTF_ID(func, bpf_rbtree_add_impl)
10706 BTF_ID(func, bpf_rbtree_first)
10707 BTF_ID(func, bpf_dynptr_from_skb)
10708 BTF_ID(func, bpf_dynptr_from_xdp)
10709 BTF_ID(func, bpf_dynptr_slice)
10710 BTF_ID(func, bpf_dynptr_slice_rdwr)
10711 BTF_ID(func, bpf_dynptr_clone)
10712 BTF_SET_END(special_kfunc_set)
10713 
10714 BTF_ID_LIST(special_kfunc_list)
10715 BTF_ID(func, bpf_obj_new_impl)
10716 BTF_ID(func, bpf_obj_drop_impl)
10717 BTF_ID(func, bpf_refcount_acquire_impl)
10718 BTF_ID(func, bpf_list_push_front_impl)
10719 BTF_ID(func, bpf_list_push_back_impl)
10720 BTF_ID(func, bpf_list_pop_front)
10721 BTF_ID(func, bpf_list_pop_back)
10722 BTF_ID(func, bpf_cast_to_kern_ctx)
10723 BTF_ID(func, bpf_rdonly_cast)
10724 BTF_ID(func, bpf_rcu_read_lock)
10725 BTF_ID(func, bpf_rcu_read_unlock)
10726 BTF_ID(func, bpf_rbtree_remove)
10727 BTF_ID(func, bpf_rbtree_add_impl)
10728 BTF_ID(func, bpf_rbtree_first)
10729 BTF_ID(func, bpf_dynptr_from_skb)
10730 BTF_ID(func, bpf_dynptr_from_xdp)
10731 BTF_ID(func, bpf_dynptr_slice)
10732 BTF_ID(func, bpf_dynptr_slice_rdwr)
10733 BTF_ID(func, bpf_dynptr_clone)
10734 
10735 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10736 {
10737 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10738 	    meta->arg_owning_ref) {
10739 		return false;
10740 	}
10741 
10742 	return meta->kfunc_flags & KF_RET_NULL;
10743 }
10744 
10745 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10746 {
10747 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10748 }
10749 
10750 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10751 {
10752 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10753 }
10754 
10755 static enum kfunc_ptr_arg_type
10756 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10757 		       struct bpf_kfunc_call_arg_meta *meta,
10758 		       const struct btf_type *t, const struct btf_type *ref_t,
10759 		       const char *ref_tname, const struct btf_param *args,
10760 		       int argno, int nargs)
10761 {
10762 	u32 regno = argno + 1;
10763 	struct bpf_reg_state *regs = cur_regs(env);
10764 	struct bpf_reg_state *reg = &regs[regno];
10765 	bool arg_mem_size = false;
10766 
10767 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10768 		return KF_ARG_PTR_TO_CTX;
10769 
10770 	/* In this function, we verify the kfunc's BTF as per the argument type,
10771 	 * leaving the rest of the verification with respect to the register
10772 	 * type to our caller. When a set of conditions hold in the BTF type of
10773 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10774 	 */
10775 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10776 		return KF_ARG_PTR_TO_CTX;
10777 
10778 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10779 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10780 
10781 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10782 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10783 
10784 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10785 		return KF_ARG_PTR_TO_DYNPTR;
10786 
10787 	if (is_kfunc_arg_iter(meta, argno))
10788 		return KF_ARG_PTR_TO_ITER;
10789 
10790 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10791 		return KF_ARG_PTR_TO_LIST_HEAD;
10792 
10793 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10794 		return KF_ARG_PTR_TO_LIST_NODE;
10795 
10796 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10797 		return KF_ARG_PTR_TO_RB_ROOT;
10798 
10799 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10800 		return KF_ARG_PTR_TO_RB_NODE;
10801 
10802 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10803 		if (!btf_type_is_struct(ref_t)) {
10804 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10805 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10806 			return -EINVAL;
10807 		}
10808 		return KF_ARG_PTR_TO_BTF_ID;
10809 	}
10810 
10811 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10812 		return KF_ARG_PTR_TO_CALLBACK;
10813 
10814 
10815 	if (argno + 1 < nargs &&
10816 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10817 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10818 		arg_mem_size = true;
10819 
10820 	/* This is the catch all argument type of register types supported by
10821 	 * check_helper_mem_access. However, we only allow when argument type is
10822 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10823 	 * arg_mem_size is true, the pointer can be void *.
10824 	 */
10825 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10826 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10827 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10828 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10829 		return -EINVAL;
10830 	}
10831 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10832 }
10833 
10834 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10835 					struct bpf_reg_state *reg,
10836 					const struct btf_type *ref_t,
10837 					const char *ref_tname, u32 ref_id,
10838 					struct bpf_kfunc_call_arg_meta *meta,
10839 					int argno)
10840 {
10841 	const struct btf_type *reg_ref_t;
10842 	bool strict_type_match = false;
10843 	const struct btf *reg_btf;
10844 	const char *reg_ref_tname;
10845 	u32 reg_ref_id;
10846 
10847 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10848 		reg_btf = reg->btf;
10849 		reg_ref_id = reg->btf_id;
10850 	} else {
10851 		reg_btf = btf_vmlinux;
10852 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10853 	}
10854 
10855 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10856 	 * or releasing a reference, or are no-cast aliases. We do _not_
10857 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10858 	 * as we want to enable BPF programs to pass types that are bitwise
10859 	 * equivalent without forcing them to explicitly cast with something
10860 	 * like bpf_cast_to_kern_ctx().
10861 	 *
10862 	 * For example, say we had a type like the following:
10863 	 *
10864 	 * struct bpf_cpumask {
10865 	 *	cpumask_t cpumask;
10866 	 *	refcount_t usage;
10867 	 * };
10868 	 *
10869 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10870 	 * to a struct cpumask, so it would be safe to pass a struct
10871 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10872 	 *
10873 	 * The philosophy here is similar to how we allow scalars of different
10874 	 * types to be passed to kfuncs as long as the size is the same. The
10875 	 * only difference here is that we're simply allowing
10876 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10877 	 * resolve types.
10878 	 */
10879 	if (is_kfunc_acquire(meta) ||
10880 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10881 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10882 		strict_type_match = true;
10883 
10884 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10885 
10886 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10887 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10888 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10889 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10890 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10891 			btf_type_str(reg_ref_t), reg_ref_tname);
10892 		return -EINVAL;
10893 	}
10894 	return 0;
10895 }
10896 
10897 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10898 {
10899 	struct bpf_verifier_state *state = env->cur_state;
10900 	struct btf_record *rec = reg_btf_record(reg);
10901 
10902 	if (!state->active_lock.ptr) {
10903 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10904 		return -EFAULT;
10905 	}
10906 
10907 	if (type_flag(reg->type) & NON_OWN_REF) {
10908 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10909 		return -EFAULT;
10910 	}
10911 
10912 	reg->type |= NON_OWN_REF;
10913 	if (rec->refcount_off >= 0)
10914 		reg->type |= MEM_RCU;
10915 
10916 	return 0;
10917 }
10918 
10919 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10920 {
10921 	struct bpf_func_state *state, *unused;
10922 	struct bpf_reg_state *reg;
10923 	int i;
10924 
10925 	state = cur_func(env);
10926 
10927 	if (!ref_obj_id) {
10928 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10929 			     "owning -> non-owning conversion\n");
10930 		return -EFAULT;
10931 	}
10932 
10933 	for (i = 0; i < state->acquired_refs; i++) {
10934 		if (state->refs[i].id != ref_obj_id)
10935 			continue;
10936 
10937 		/* Clear ref_obj_id here so release_reference doesn't clobber
10938 		 * the whole reg
10939 		 */
10940 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10941 			if (reg->ref_obj_id == ref_obj_id) {
10942 				reg->ref_obj_id = 0;
10943 				ref_set_non_owning(env, reg);
10944 			}
10945 		}));
10946 		return 0;
10947 	}
10948 
10949 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10950 	return -EFAULT;
10951 }
10952 
10953 /* Implementation details:
10954  *
10955  * Each register points to some region of memory, which we define as an
10956  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10957  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10958  * allocation. The lock and the data it protects are colocated in the same
10959  * memory region.
10960  *
10961  * Hence, everytime a register holds a pointer value pointing to such
10962  * allocation, the verifier preserves a unique reg->id for it.
10963  *
10964  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10965  * bpf_spin_lock is called.
10966  *
10967  * To enable this, lock state in the verifier captures two values:
10968  *	active_lock.ptr = Register's type specific pointer
10969  *	active_lock.id  = A unique ID for each register pointer value
10970  *
10971  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10972  * supported register types.
10973  *
10974  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10975  * allocated objects is the reg->btf pointer.
10976  *
10977  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10978  * can establish the provenance of the map value statically for each distinct
10979  * lookup into such maps. They always contain a single map value hence unique
10980  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10981  *
10982  * So, in case of global variables, they use array maps with max_entries = 1,
10983  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10984  * into the same map value as max_entries is 1, as described above).
10985  *
10986  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10987  * outer map pointer (in verifier context), but each lookup into an inner map
10988  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10989  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10990  * will get different reg->id assigned to each lookup, hence different
10991  * active_lock.id.
10992  *
10993  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10994  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10995  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10996  */
10997 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10998 {
10999 	void *ptr;
11000 	u32 id;
11001 
11002 	switch ((int)reg->type) {
11003 	case PTR_TO_MAP_VALUE:
11004 		ptr = reg->map_ptr;
11005 		break;
11006 	case PTR_TO_BTF_ID | MEM_ALLOC:
11007 		ptr = reg->btf;
11008 		break;
11009 	default:
11010 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11011 		return -EFAULT;
11012 	}
11013 	id = reg->id;
11014 
11015 	if (!env->cur_state->active_lock.ptr)
11016 		return -EINVAL;
11017 	if (env->cur_state->active_lock.ptr != ptr ||
11018 	    env->cur_state->active_lock.id != id) {
11019 		verbose(env, "held lock and object are not in the same allocation\n");
11020 		return -EINVAL;
11021 	}
11022 	return 0;
11023 }
11024 
11025 static bool is_bpf_list_api_kfunc(u32 btf_id)
11026 {
11027 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11028 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11029 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11030 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11031 }
11032 
11033 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11034 {
11035 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11036 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11037 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11038 }
11039 
11040 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11041 {
11042 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11043 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11044 }
11045 
11046 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11047 {
11048 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11049 }
11050 
11051 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11052 {
11053 	return is_bpf_rbtree_api_kfunc(btf_id);
11054 }
11055 
11056 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11057 					  enum btf_field_type head_field_type,
11058 					  u32 kfunc_btf_id)
11059 {
11060 	bool ret;
11061 
11062 	switch (head_field_type) {
11063 	case BPF_LIST_HEAD:
11064 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11065 		break;
11066 	case BPF_RB_ROOT:
11067 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11068 		break;
11069 	default:
11070 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11071 			btf_field_type_name(head_field_type));
11072 		return false;
11073 	}
11074 
11075 	if (!ret)
11076 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11077 			btf_field_type_name(head_field_type));
11078 	return ret;
11079 }
11080 
11081 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11082 					  enum btf_field_type node_field_type,
11083 					  u32 kfunc_btf_id)
11084 {
11085 	bool ret;
11086 
11087 	switch (node_field_type) {
11088 	case BPF_LIST_NODE:
11089 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11090 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11091 		break;
11092 	case BPF_RB_NODE:
11093 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11094 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11095 		break;
11096 	default:
11097 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11098 			btf_field_type_name(node_field_type));
11099 		return false;
11100 	}
11101 
11102 	if (!ret)
11103 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11104 			btf_field_type_name(node_field_type));
11105 	return ret;
11106 }
11107 
11108 static int
11109 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11110 				   struct bpf_reg_state *reg, u32 regno,
11111 				   struct bpf_kfunc_call_arg_meta *meta,
11112 				   enum btf_field_type head_field_type,
11113 				   struct btf_field **head_field)
11114 {
11115 	const char *head_type_name;
11116 	struct btf_field *field;
11117 	struct btf_record *rec;
11118 	u32 head_off;
11119 
11120 	if (meta->btf != btf_vmlinux) {
11121 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11122 		return -EFAULT;
11123 	}
11124 
11125 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11126 		return -EFAULT;
11127 
11128 	head_type_name = btf_field_type_name(head_field_type);
11129 	if (!tnum_is_const(reg->var_off)) {
11130 		verbose(env,
11131 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11132 			regno, head_type_name);
11133 		return -EINVAL;
11134 	}
11135 
11136 	rec = reg_btf_record(reg);
11137 	head_off = reg->off + reg->var_off.value;
11138 	field = btf_record_find(rec, head_off, head_field_type);
11139 	if (!field) {
11140 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11141 		return -EINVAL;
11142 	}
11143 
11144 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11145 	if (check_reg_allocation_locked(env, reg)) {
11146 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11147 			rec->spin_lock_off, head_type_name);
11148 		return -EINVAL;
11149 	}
11150 
11151 	if (*head_field) {
11152 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11153 		return -EFAULT;
11154 	}
11155 	*head_field = field;
11156 	return 0;
11157 }
11158 
11159 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11160 					   struct bpf_reg_state *reg, u32 regno,
11161 					   struct bpf_kfunc_call_arg_meta *meta)
11162 {
11163 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11164 							  &meta->arg_list_head.field);
11165 }
11166 
11167 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11168 					     struct bpf_reg_state *reg, u32 regno,
11169 					     struct bpf_kfunc_call_arg_meta *meta)
11170 {
11171 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11172 							  &meta->arg_rbtree_root.field);
11173 }
11174 
11175 static int
11176 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11177 				   struct bpf_reg_state *reg, u32 regno,
11178 				   struct bpf_kfunc_call_arg_meta *meta,
11179 				   enum btf_field_type head_field_type,
11180 				   enum btf_field_type node_field_type,
11181 				   struct btf_field **node_field)
11182 {
11183 	const char *node_type_name;
11184 	const struct btf_type *et, *t;
11185 	struct btf_field *field;
11186 	u32 node_off;
11187 
11188 	if (meta->btf != btf_vmlinux) {
11189 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11190 		return -EFAULT;
11191 	}
11192 
11193 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11194 		return -EFAULT;
11195 
11196 	node_type_name = btf_field_type_name(node_field_type);
11197 	if (!tnum_is_const(reg->var_off)) {
11198 		verbose(env,
11199 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11200 			regno, node_type_name);
11201 		return -EINVAL;
11202 	}
11203 
11204 	node_off = reg->off + reg->var_off.value;
11205 	field = reg_find_field_offset(reg, node_off, node_field_type);
11206 	if (!field || field->offset != node_off) {
11207 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11208 		return -EINVAL;
11209 	}
11210 
11211 	field = *node_field;
11212 
11213 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11214 	t = btf_type_by_id(reg->btf, reg->btf_id);
11215 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11216 				  field->graph_root.value_btf_id, true)) {
11217 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11218 			"in struct %s, but arg is at offset=%d in struct %s\n",
11219 			btf_field_type_name(head_field_type),
11220 			btf_field_type_name(node_field_type),
11221 			field->graph_root.node_offset,
11222 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11223 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11224 		return -EINVAL;
11225 	}
11226 	meta->arg_btf = reg->btf;
11227 	meta->arg_btf_id = reg->btf_id;
11228 
11229 	if (node_off != field->graph_root.node_offset) {
11230 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11231 			node_off, btf_field_type_name(node_field_type),
11232 			field->graph_root.node_offset,
11233 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11234 		return -EINVAL;
11235 	}
11236 
11237 	return 0;
11238 }
11239 
11240 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11241 					   struct bpf_reg_state *reg, u32 regno,
11242 					   struct bpf_kfunc_call_arg_meta *meta)
11243 {
11244 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11245 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11246 						  &meta->arg_list_head.field);
11247 }
11248 
11249 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11250 					     struct bpf_reg_state *reg, u32 regno,
11251 					     struct bpf_kfunc_call_arg_meta *meta)
11252 {
11253 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11254 						  BPF_RB_ROOT, BPF_RB_NODE,
11255 						  &meta->arg_rbtree_root.field);
11256 }
11257 
11258 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11259 			    int insn_idx)
11260 {
11261 	const char *func_name = meta->func_name, *ref_tname;
11262 	const struct btf *btf = meta->btf;
11263 	const struct btf_param *args;
11264 	struct btf_record *rec;
11265 	u32 i, nargs;
11266 	int ret;
11267 
11268 	args = (const struct btf_param *)(meta->func_proto + 1);
11269 	nargs = btf_type_vlen(meta->func_proto);
11270 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11271 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11272 			MAX_BPF_FUNC_REG_ARGS);
11273 		return -EINVAL;
11274 	}
11275 
11276 	/* Check that BTF function arguments match actual types that the
11277 	 * verifier sees.
11278 	 */
11279 	for (i = 0; i < nargs; i++) {
11280 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11281 		const struct btf_type *t, *ref_t, *resolve_ret;
11282 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11283 		u32 regno = i + 1, ref_id, type_size;
11284 		bool is_ret_buf_sz = false;
11285 		int kf_arg_type;
11286 
11287 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11288 
11289 		if (is_kfunc_arg_ignore(btf, &args[i]))
11290 			continue;
11291 
11292 		if (btf_type_is_scalar(t)) {
11293 			if (reg->type != SCALAR_VALUE) {
11294 				verbose(env, "R%d is not a scalar\n", regno);
11295 				return -EINVAL;
11296 			}
11297 
11298 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11299 				if (meta->arg_constant.found) {
11300 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11301 					return -EFAULT;
11302 				}
11303 				if (!tnum_is_const(reg->var_off)) {
11304 					verbose(env, "R%d must be a known constant\n", regno);
11305 					return -EINVAL;
11306 				}
11307 				ret = mark_chain_precision(env, regno);
11308 				if (ret < 0)
11309 					return ret;
11310 				meta->arg_constant.found = true;
11311 				meta->arg_constant.value = reg->var_off.value;
11312 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11313 				meta->r0_rdonly = true;
11314 				is_ret_buf_sz = true;
11315 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11316 				is_ret_buf_sz = true;
11317 			}
11318 
11319 			if (is_ret_buf_sz) {
11320 				if (meta->r0_size) {
11321 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11322 					return -EINVAL;
11323 				}
11324 
11325 				if (!tnum_is_const(reg->var_off)) {
11326 					verbose(env, "R%d is not a const\n", regno);
11327 					return -EINVAL;
11328 				}
11329 
11330 				meta->r0_size = reg->var_off.value;
11331 				ret = mark_chain_precision(env, regno);
11332 				if (ret)
11333 					return ret;
11334 			}
11335 			continue;
11336 		}
11337 
11338 		if (!btf_type_is_ptr(t)) {
11339 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11340 			return -EINVAL;
11341 		}
11342 
11343 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11344 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11345 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11346 			return -EACCES;
11347 		}
11348 
11349 		if (reg->ref_obj_id) {
11350 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11351 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11352 					regno, reg->ref_obj_id,
11353 					meta->ref_obj_id);
11354 				return -EFAULT;
11355 			}
11356 			meta->ref_obj_id = reg->ref_obj_id;
11357 			if (is_kfunc_release(meta))
11358 				meta->release_regno = regno;
11359 		}
11360 
11361 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11362 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11363 
11364 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11365 		if (kf_arg_type < 0)
11366 			return kf_arg_type;
11367 
11368 		switch (kf_arg_type) {
11369 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11370 		case KF_ARG_PTR_TO_BTF_ID:
11371 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11372 				break;
11373 
11374 			if (!is_trusted_reg(reg)) {
11375 				if (!is_kfunc_rcu(meta)) {
11376 					verbose(env, "R%d must be referenced or trusted\n", regno);
11377 					return -EINVAL;
11378 				}
11379 				if (!is_rcu_reg(reg)) {
11380 					verbose(env, "R%d must be a rcu pointer\n", regno);
11381 					return -EINVAL;
11382 				}
11383 			}
11384 
11385 			fallthrough;
11386 		case KF_ARG_PTR_TO_CTX:
11387 			/* Trusted arguments have the same offset checks as release arguments */
11388 			arg_type |= OBJ_RELEASE;
11389 			break;
11390 		case KF_ARG_PTR_TO_DYNPTR:
11391 		case KF_ARG_PTR_TO_ITER:
11392 		case KF_ARG_PTR_TO_LIST_HEAD:
11393 		case KF_ARG_PTR_TO_LIST_NODE:
11394 		case KF_ARG_PTR_TO_RB_ROOT:
11395 		case KF_ARG_PTR_TO_RB_NODE:
11396 		case KF_ARG_PTR_TO_MEM:
11397 		case KF_ARG_PTR_TO_MEM_SIZE:
11398 		case KF_ARG_PTR_TO_CALLBACK:
11399 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11400 			/* Trusted by default */
11401 			break;
11402 		default:
11403 			WARN_ON_ONCE(1);
11404 			return -EFAULT;
11405 		}
11406 
11407 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11408 			arg_type |= OBJ_RELEASE;
11409 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11410 		if (ret < 0)
11411 			return ret;
11412 
11413 		switch (kf_arg_type) {
11414 		case KF_ARG_PTR_TO_CTX:
11415 			if (reg->type != PTR_TO_CTX) {
11416 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11417 				return -EINVAL;
11418 			}
11419 
11420 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11421 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11422 				if (ret < 0)
11423 					return -EINVAL;
11424 				meta->ret_btf_id  = ret;
11425 			}
11426 			break;
11427 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11428 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11429 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11430 				return -EINVAL;
11431 			}
11432 			if (!reg->ref_obj_id) {
11433 				verbose(env, "allocated object must be referenced\n");
11434 				return -EINVAL;
11435 			}
11436 			if (meta->btf == btf_vmlinux &&
11437 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11438 				meta->arg_btf = reg->btf;
11439 				meta->arg_btf_id = reg->btf_id;
11440 			}
11441 			break;
11442 		case KF_ARG_PTR_TO_DYNPTR:
11443 		{
11444 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11445 			int clone_ref_obj_id = 0;
11446 
11447 			if (reg->type != PTR_TO_STACK &&
11448 			    reg->type != CONST_PTR_TO_DYNPTR) {
11449 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11450 				return -EINVAL;
11451 			}
11452 
11453 			if (reg->type == CONST_PTR_TO_DYNPTR)
11454 				dynptr_arg_type |= MEM_RDONLY;
11455 
11456 			if (is_kfunc_arg_uninit(btf, &args[i]))
11457 				dynptr_arg_type |= MEM_UNINIT;
11458 
11459 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11460 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11461 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11462 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11463 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11464 				   (dynptr_arg_type & MEM_UNINIT)) {
11465 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11466 
11467 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11468 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11469 					return -EFAULT;
11470 				}
11471 
11472 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11473 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11474 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11475 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11476 					return -EFAULT;
11477 				}
11478 			}
11479 
11480 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11481 			if (ret < 0)
11482 				return ret;
11483 
11484 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11485 				int id = dynptr_id(env, reg);
11486 
11487 				if (id < 0) {
11488 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11489 					return id;
11490 				}
11491 				meta->initialized_dynptr.id = id;
11492 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11493 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11494 			}
11495 
11496 			break;
11497 		}
11498 		case KF_ARG_PTR_TO_ITER:
11499 			ret = process_iter_arg(env, regno, insn_idx, meta);
11500 			if (ret < 0)
11501 				return ret;
11502 			break;
11503 		case KF_ARG_PTR_TO_LIST_HEAD:
11504 			if (reg->type != PTR_TO_MAP_VALUE &&
11505 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11506 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11507 				return -EINVAL;
11508 			}
11509 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11510 				verbose(env, "allocated object must be referenced\n");
11511 				return -EINVAL;
11512 			}
11513 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11514 			if (ret < 0)
11515 				return ret;
11516 			break;
11517 		case KF_ARG_PTR_TO_RB_ROOT:
11518 			if (reg->type != PTR_TO_MAP_VALUE &&
11519 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11520 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11521 				return -EINVAL;
11522 			}
11523 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11524 				verbose(env, "allocated object must be referenced\n");
11525 				return -EINVAL;
11526 			}
11527 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11528 			if (ret < 0)
11529 				return ret;
11530 			break;
11531 		case KF_ARG_PTR_TO_LIST_NODE:
11532 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11533 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11534 				return -EINVAL;
11535 			}
11536 			if (!reg->ref_obj_id) {
11537 				verbose(env, "allocated object must be referenced\n");
11538 				return -EINVAL;
11539 			}
11540 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11541 			if (ret < 0)
11542 				return ret;
11543 			break;
11544 		case KF_ARG_PTR_TO_RB_NODE:
11545 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11546 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11547 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11548 					return -EINVAL;
11549 				}
11550 				if (in_rbtree_lock_required_cb(env)) {
11551 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11552 					return -EINVAL;
11553 				}
11554 			} else {
11555 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11556 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11557 					return -EINVAL;
11558 				}
11559 				if (!reg->ref_obj_id) {
11560 					verbose(env, "allocated object must be referenced\n");
11561 					return -EINVAL;
11562 				}
11563 			}
11564 
11565 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11566 			if (ret < 0)
11567 				return ret;
11568 			break;
11569 		case KF_ARG_PTR_TO_BTF_ID:
11570 			/* Only base_type is checked, further checks are done here */
11571 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11572 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11573 			    !reg2btf_ids[base_type(reg->type)]) {
11574 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11575 				verbose(env, "expected %s or socket\n",
11576 					reg_type_str(env, base_type(reg->type) |
11577 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11578 				return -EINVAL;
11579 			}
11580 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11581 			if (ret < 0)
11582 				return ret;
11583 			break;
11584 		case KF_ARG_PTR_TO_MEM:
11585 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11586 			if (IS_ERR(resolve_ret)) {
11587 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11588 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11589 				return -EINVAL;
11590 			}
11591 			ret = check_mem_reg(env, reg, regno, type_size);
11592 			if (ret < 0)
11593 				return ret;
11594 			break;
11595 		case KF_ARG_PTR_TO_MEM_SIZE:
11596 		{
11597 			struct bpf_reg_state *buff_reg = &regs[regno];
11598 			const struct btf_param *buff_arg = &args[i];
11599 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11600 			const struct btf_param *size_arg = &args[i + 1];
11601 
11602 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11603 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11604 				if (ret < 0) {
11605 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11606 					return ret;
11607 				}
11608 			}
11609 
11610 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11611 				if (meta->arg_constant.found) {
11612 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11613 					return -EFAULT;
11614 				}
11615 				if (!tnum_is_const(size_reg->var_off)) {
11616 					verbose(env, "R%d must be a known constant\n", regno + 1);
11617 					return -EINVAL;
11618 				}
11619 				meta->arg_constant.found = true;
11620 				meta->arg_constant.value = size_reg->var_off.value;
11621 			}
11622 
11623 			/* Skip next '__sz' or '__szk' argument */
11624 			i++;
11625 			break;
11626 		}
11627 		case KF_ARG_PTR_TO_CALLBACK:
11628 			if (reg->type != PTR_TO_FUNC) {
11629 				verbose(env, "arg%d expected pointer to func\n", i);
11630 				return -EINVAL;
11631 			}
11632 			meta->subprogno = reg->subprogno;
11633 			break;
11634 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11635 			if (!type_is_ptr_alloc_obj(reg->type)) {
11636 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11637 				return -EINVAL;
11638 			}
11639 			if (!type_is_non_owning_ref(reg->type))
11640 				meta->arg_owning_ref = true;
11641 
11642 			rec = reg_btf_record(reg);
11643 			if (!rec) {
11644 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11645 				return -EFAULT;
11646 			}
11647 
11648 			if (rec->refcount_off < 0) {
11649 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11650 				return -EINVAL;
11651 			}
11652 
11653 			meta->arg_btf = reg->btf;
11654 			meta->arg_btf_id = reg->btf_id;
11655 			break;
11656 		}
11657 	}
11658 
11659 	if (is_kfunc_release(meta) && !meta->release_regno) {
11660 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11661 			func_name);
11662 		return -EINVAL;
11663 	}
11664 
11665 	return 0;
11666 }
11667 
11668 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11669 			    struct bpf_insn *insn,
11670 			    struct bpf_kfunc_call_arg_meta *meta,
11671 			    const char **kfunc_name)
11672 {
11673 	const struct btf_type *func, *func_proto;
11674 	u32 func_id, *kfunc_flags;
11675 	const char *func_name;
11676 	struct btf *desc_btf;
11677 
11678 	if (kfunc_name)
11679 		*kfunc_name = NULL;
11680 
11681 	if (!insn->imm)
11682 		return -EINVAL;
11683 
11684 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11685 	if (IS_ERR(desc_btf))
11686 		return PTR_ERR(desc_btf);
11687 
11688 	func_id = insn->imm;
11689 	func = btf_type_by_id(desc_btf, func_id);
11690 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11691 	if (kfunc_name)
11692 		*kfunc_name = func_name;
11693 	func_proto = btf_type_by_id(desc_btf, func->type);
11694 
11695 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11696 	if (!kfunc_flags) {
11697 		return -EACCES;
11698 	}
11699 
11700 	memset(meta, 0, sizeof(*meta));
11701 	meta->btf = desc_btf;
11702 	meta->func_id = func_id;
11703 	meta->kfunc_flags = *kfunc_flags;
11704 	meta->func_proto = func_proto;
11705 	meta->func_name = func_name;
11706 
11707 	return 0;
11708 }
11709 
11710 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11711 			    int *insn_idx_p)
11712 {
11713 	const struct btf_type *t, *ptr_type;
11714 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11715 	struct bpf_reg_state *regs = cur_regs(env);
11716 	const char *func_name, *ptr_type_name;
11717 	bool sleepable, rcu_lock, rcu_unlock;
11718 	struct bpf_kfunc_call_arg_meta meta;
11719 	struct bpf_insn_aux_data *insn_aux;
11720 	int err, insn_idx = *insn_idx_p;
11721 	const struct btf_param *args;
11722 	const struct btf_type *ret_t;
11723 	struct btf *desc_btf;
11724 
11725 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11726 	if (!insn->imm)
11727 		return 0;
11728 
11729 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11730 	if (err == -EACCES && func_name)
11731 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11732 	if (err)
11733 		return err;
11734 	desc_btf = meta.btf;
11735 	insn_aux = &env->insn_aux_data[insn_idx];
11736 
11737 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11738 
11739 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11740 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11741 		return -EACCES;
11742 	}
11743 
11744 	sleepable = is_kfunc_sleepable(&meta);
11745 	if (sleepable && !env->prog->aux->sleepable) {
11746 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11747 		return -EACCES;
11748 	}
11749 
11750 	/* Check the arguments */
11751 	err = check_kfunc_args(env, &meta, insn_idx);
11752 	if (err < 0)
11753 		return err;
11754 
11755 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11756 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11757 					 set_rbtree_add_callback_state);
11758 		if (err) {
11759 			verbose(env, "kfunc %s#%d failed callback verification\n",
11760 				func_name, meta.func_id);
11761 			return err;
11762 		}
11763 	}
11764 
11765 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11766 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11767 
11768 	if (env->cur_state->active_rcu_lock) {
11769 		struct bpf_func_state *state;
11770 		struct bpf_reg_state *reg;
11771 
11772 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11773 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11774 			return -EACCES;
11775 		}
11776 
11777 		if (rcu_lock) {
11778 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11779 			return -EINVAL;
11780 		} else if (rcu_unlock) {
11781 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11782 				if (reg->type & MEM_RCU) {
11783 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11784 					reg->type |= PTR_UNTRUSTED;
11785 				}
11786 			}));
11787 			env->cur_state->active_rcu_lock = false;
11788 		} else if (sleepable) {
11789 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11790 			return -EACCES;
11791 		}
11792 	} else if (rcu_lock) {
11793 		env->cur_state->active_rcu_lock = true;
11794 	} else if (rcu_unlock) {
11795 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11796 		return -EINVAL;
11797 	}
11798 
11799 	/* In case of release function, we get register number of refcounted
11800 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11801 	 */
11802 	if (meta.release_regno) {
11803 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11804 		if (err) {
11805 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11806 				func_name, meta.func_id);
11807 			return err;
11808 		}
11809 	}
11810 
11811 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11812 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11813 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11814 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11815 		insn_aux->insert_off = regs[BPF_REG_2].off;
11816 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11817 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11818 		if (err) {
11819 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11820 				func_name, meta.func_id);
11821 			return err;
11822 		}
11823 
11824 		err = release_reference(env, release_ref_obj_id);
11825 		if (err) {
11826 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11827 				func_name, meta.func_id);
11828 			return err;
11829 		}
11830 	}
11831 
11832 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11833 		mark_reg_not_init(env, regs, caller_saved[i]);
11834 
11835 	/* Check return type */
11836 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11837 
11838 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11839 		/* Only exception is bpf_obj_new_impl */
11840 		if (meta.btf != btf_vmlinux ||
11841 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11842 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11843 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11844 			return -EINVAL;
11845 		}
11846 	}
11847 
11848 	if (btf_type_is_scalar(t)) {
11849 		mark_reg_unknown(env, regs, BPF_REG_0);
11850 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11851 	} else if (btf_type_is_ptr(t)) {
11852 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11853 
11854 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11855 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11856 				struct btf *ret_btf;
11857 				u32 ret_btf_id;
11858 
11859 				if (unlikely(!bpf_global_ma_set))
11860 					return -ENOMEM;
11861 
11862 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11863 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11864 					return -EINVAL;
11865 				}
11866 
11867 				ret_btf = env->prog->aux->btf;
11868 				ret_btf_id = meta.arg_constant.value;
11869 
11870 				/* This may be NULL due to user not supplying a BTF */
11871 				if (!ret_btf) {
11872 					verbose(env, "bpf_obj_new requires prog BTF\n");
11873 					return -EINVAL;
11874 				}
11875 
11876 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11877 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11878 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11879 					return -EINVAL;
11880 				}
11881 
11882 				mark_reg_known_zero(env, regs, BPF_REG_0);
11883 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11884 				regs[BPF_REG_0].btf = ret_btf;
11885 				regs[BPF_REG_0].btf_id = ret_btf_id;
11886 
11887 				insn_aux->obj_new_size = ret_t->size;
11888 				insn_aux->kptr_struct_meta =
11889 					btf_find_struct_meta(ret_btf, ret_btf_id);
11890 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11891 				mark_reg_known_zero(env, regs, BPF_REG_0);
11892 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11893 				regs[BPF_REG_0].btf = meta.arg_btf;
11894 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11895 
11896 				insn_aux->kptr_struct_meta =
11897 					btf_find_struct_meta(meta.arg_btf,
11898 							     meta.arg_btf_id);
11899 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11900 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11901 				struct btf_field *field = meta.arg_list_head.field;
11902 
11903 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11904 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11905 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11906 				struct btf_field *field = meta.arg_rbtree_root.field;
11907 
11908 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11909 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11910 				mark_reg_known_zero(env, regs, BPF_REG_0);
11911 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11912 				regs[BPF_REG_0].btf = desc_btf;
11913 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11914 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11915 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11916 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11917 					verbose(env,
11918 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11919 					return -EINVAL;
11920 				}
11921 
11922 				mark_reg_known_zero(env, regs, BPF_REG_0);
11923 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11924 				regs[BPF_REG_0].btf = desc_btf;
11925 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11926 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11927 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11928 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11929 
11930 				mark_reg_known_zero(env, regs, BPF_REG_0);
11931 
11932 				if (!meta.arg_constant.found) {
11933 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11934 					return -EFAULT;
11935 				}
11936 
11937 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11938 
11939 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11940 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11941 
11942 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11943 					regs[BPF_REG_0].type |= MEM_RDONLY;
11944 				} else {
11945 					/* this will set env->seen_direct_write to true */
11946 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11947 						verbose(env, "the prog does not allow writes to packet data\n");
11948 						return -EINVAL;
11949 					}
11950 				}
11951 
11952 				if (!meta.initialized_dynptr.id) {
11953 					verbose(env, "verifier internal error: no dynptr id\n");
11954 					return -EFAULT;
11955 				}
11956 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11957 
11958 				/* we don't need to set BPF_REG_0's ref obj id
11959 				 * because packet slices are not refcounted (see
11960 				 * dynptr_type_refcounted)
11961 				 */
11962 			} else {
11963 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11964 					meta.func_name);
11965 				return -EFAULT;
11966 			}
11967 		} else if (!__btf_type_is_struct(ptr_type)) {
11968 			if (!meta.r0_size) {
11969 				__u32 sz;
11970 
11971 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11972 					meta.r0_size = sz;
11973 					meta.r0_rdonly = true;
11974 				}
11975 			}
11976 			if (!meta.r0_size) {
11977 				ptr_type_name = btf_name_by_offset(desc_btf,
11978 								   ptr_type->name_off);
11979 				verbose(env,
11980 					"kernel function %s returns pointer type %s %s is not supported\n",
11981 					func_name,
11982 					btf_type_str(ptr_type),
11983 					ptr_type_name);
11984 				return -EINVAL;
11985 			}
11986 
11987 			mark_reg_known_zero(env, regs, BPF_REG_0);
11988 			regs[BPF_REG_0].type = PTR_TO_MEM;
11989 			regs[BPF_REG_0].mem_size = meta.r0_size;
11990 
11991 			if (meta.r0_rdonly)
11992 				regs[BPF_REG_0].type |= MEM_RDONLY;
11993 
11994 			/* Ensures we don't access the memory after a release_reference() */
11995 			if (meta.ref_obj_id)
11996 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11997 		} else {
11998 			mark_reg_known_zero(env, regs, BPF_REG_0);
11999 			regs[BPF_REG_0].btf = desc_btf;
12000 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12001 			regs[BPF_REG_0].btf_id = ptr_type_id;
12002 		}
12003 
12004 		if (is_kfunc_ret_null(&meta)) {
12005 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12006 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12007 			regs[BPF_REG_0].id = ++env->id_gen;
12008 		}
12009 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12010 		if (is_kfunc_acquire(&meta)) {
12011 			int id = acquire_reference_state(env, insn_idx);
12012 
12013 			if (id < 0)
12014 				return id;
12015 			if (is_kfunc_ret_null(&meta))
12016 				regs[BPF_REG_0].id = id;
12017 			regs[BPF_REG_0].ref_obj_id = id;
12018 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12019 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12020 		}
12021 
12022 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12023 			regs[BPF_REG_0].id = ++env->id_gen;
12024 	} else if (btf_type_is_void(t)) {
12025 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12026 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12027 				insn_aux->kptr_struct_meta =
12028 					btf_find_struct_meta(meta.arg_btf,
12029 							     meta.arg_btf_id);
12030 			}
12031 		}
12032 	}
12033 
12034 	nargs = btf_type_vlen(meta.func_proto);
12035 	args = (const struct btf_param *)(meta.func_proto + 1);
12036 	for (i = 0; i < nargs; i++) {
12037 		u32 regno = i + 1;
12038 
12039 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12040 		if (btf_type_is_ptr(t))
12041 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12042 		else
12043 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12044 			mark_btf_func_reg_size(env, regno, t->size);
12045 	}
12046 
12047 	if (is_iter_next_kfunc(&meta)) {
12048 		err = process_iter_next_call(env, insn_idx, &meta);
12049 		if (err)
12050 			return err;
12051 	}
12052 
12053 	return 0;
12054 }
12055 
12056 static bool signed_add_overflows(s64 a, s64 b)
12057 {
12058 	/* Do the add in u64, where overflow is well-defined */
12059 	s64 res = (s64)((u64)a + (u64)b);
12060 
12061 	if (b < 0)
12062 		return res > a;
12063 	return res < a;
12064 }
12065 
12066 static bool signed_add32_overflows(s32 a, s32 b)
12067 {
12068 	/* Do the add in u32, where overflow is well-defined */
12069 	s32 res = (s32)((u32)a + (u32)b);
12070 
12071 	if (b < 0)
12072 		return res > a;
12073 	return res < a;
12074 }
12075 
12076 static bool signed_sub_overflows(s64 a, s64 b)
12077 {
12078 	/* Do the sub in u64, where overflow is well-defined */
12079 	s64 res = (s64)((u64)a - (u64)b);
12080 
12081 	if (b < 0)
12082 		return res < a;
12083 	return res > a;
12084 }
12085 
12086 static bool signed_sub32_overflows(s32 a, s32 b)
12087 {
12088 	/* Do the sub in u32, where overflow is well-defined */
12089 	s32 res = (s32)((u32)a - (u32)b);
12090 
12091 	if (b < 0)
12092 		return res < a;
12093 	return res > a;
12094 }
12095 
12096 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12097 				  const struct bpf_reg_state *reg,
12098 				  enum bpf_reg_type type)
12099 {
12100 	bool known = tnum_is_const(reg->var_off);
12101 	s64 val = reg->var_off.value;
12102 	s64 smin = reg->smin_value;
12103 
12104 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12105 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12106 			reg_type_str(env, type), val);
12107 		return false;
12108 	}
12109 
12110 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12111 		verbose(env, "%s pointer offset %d is not allowed\n",
12112 			reg_type_str(env, type), reg->off);
12113 		return false;
12114 	}
12115 
12116 	if (smin == S64_MIN) {
12117 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12118 			reg_type_str(env, type));
12119 		return false;
12120 	}
12121 
12122 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12123 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12124 			smin, reg_type_str(env, type));
12125 		return false;
12126 	}
12127 
12128 	return true;
12129 }
12130 
12131 enum {
12132 	REASON_BOUNDS	= -1,
12133 	REASON_TYPE	= -2,
12134 	REASON_PATHS	= -3,
12135 	REASON_LIMIT	= -4,
12136 	REASON_STACK	= -5,
12137 };
12138 
12139 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12140 			      u32 *alu_limit, bool mask_to_left)
12141 {
12142 	u32 max = 0, ptr_limit = 0;
12143 
12144 	switch (ptr_reg->type) {
12145 	case PTR_TO_STACK:
12146 		/* Offset 0 is out-of-bounds, but acceptable start for the
12147 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12148 		 * offset where we would need to deal with min/max bounds is
12149 		 * currently prohibited for unprivileged.
12150 		 */
12151 		max = MAX_BPF_STACK + mask_to_left;
12152 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12153 		break;
12154 	case PTR_TO_MAP_VALUE:
12155 		max = ptr_reg->map_ptr->value_size;
12156 		ptr_limit = (mask_to_left ?
12157 			     ptr_reg->smin_value :
12158 			     ptr_reg->umax_value) + ptr_reg->off;
12159 		break;
12160 	default:
12161 		return REASON_TYPE;
12162 	}
12163 
12164 	if (ptr_limit >= max)
12165 		return REASON_LIMIT;
12166 	*alu_limit = ptr_limit;
12167 	return 0;
12168 }
12169 
12170 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12171 				    const struct bpf_insn *insn)
12172 {
12173 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12174 }
12175 
12176 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12177 				       u32 alu_state, u32 alu_limit)
12178 {
12179 	/* If we arrived here from different branches with different
12180 	 * state or limits to sanitize, then this won't work.
12181 	 */
12182 	if (aux->alu_state &&
12183 	    (aux->alu_state != alu_state ||
12184 	     aux->alu_limit != alu_limit))
12185 		return REASON_PATHS;
12186 
12187 	/* Corresponding fixup done in do_misc_fixups(). */
12188 	aux->alu_state = alu_state;
12189 	aux->alu_limit = alu_limit;
12190 	return 0;
12191 }
12192 
12193 static int sanitize_val_alu(struct bpf_verifier_env *env,
12194 			    struct bpf_insn *insn)
12195 {
12196 	struct bpf_insn_aux_data *aux = cur_aux(env);
12197 
12198 	if (can_skip_alu_sanitation(env, insn))
12199 		return 0;
12200 
12201 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12202 }
12203 
12204 static bool sanitize_needed(u8 opcode)
12205 {
12206 	return opcode == BPF_ADD || opcode == BPF_SUB;
12207 }
12208 
12209 struct bpf_sanitize_info {
12210 	struct bpf_insn_aux_data aux;
12211 	bool mask_to_left;
12212 };
12213 
12214 static struct bpf_verifier_state *
12215 sanitize_speculative_path(struct bpf_verifier_env *env,
12216 			  const struct bpf_insn *insn,
12217 			  u32 next_idx, u32 curr_idx)
12218 {
12219 	struct bpf_verifier_state *branch;
12220 	struct bpf_reg_state *regs;
12221 
12222 	branch = push_stack(env, next_idx, curr_idx, true);
12223 	if (branch && insn) {
12224 		regs = branch->frame[branch->curframe]->regs;
12225 		if (BPF_SRC(insn->code) == BPF_K) {
12226 			mark_reg_unknown(env, regs, insn->dst_reg);
12227 		} else if (BPF_SRC(insn->code) == BPF_X) {
12228 			mark_reg_unknown(env, regs, insn->dst_reg);
12229 			mark_reg_unknown(env, regs, insn->src_reg);
12230 		}
12231 	}
12232 	return branch;
12233 }
12234 
12235 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12236 			    struct bpf_insn *insn,
12237 			    const struct bpf_reg_state *ptr_reg,
12238 			    const struct bpf_reg_state *off_reg,
12239 			    struct bpf_reg_state *dst_reg,
12240 			    struct bpf_sanitize_info *info,
12241 			    const bool commit_window)
12242 {
12243 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12244 	struct bpf_verifier_state *vstate = env->cur_state;
12245 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12246 	bool off_is_neg = off_reg->smin_value < 0;
12247 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12248 	u8 opcode = BPF_OP(insn->code);
12249 	u32 alu_state, alu_limit;
12250 	struct bpf_reg_state tmp;
12251 	bool ret;
12252 	int err;
12253 
12254 	if (can_skip_alu_sanitation(env, insn))
12255 		return 0;
12256 
12257 	/* We already marked aux for masking from non-speculative
12258 	 * paths, thus we got here in the first place. We only care
12259 	 * to explore bad access from here.
12260 	 */
12261 	if (vstate->speculative)
12262 		goto do_sim;
12263 
12264 	if (!commit_window) {
12265 		if (!tnum_is_const(off_reg->var_off) &&
12266 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12267 			return REASON_BOUNDS;
12268 
12269 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12270 				     (opcode == BPF_SUB && !off_is_neg);
12271 	}
12272 
12273 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12274 	if (err < 0)
12275 		return err;
12276 
12277 	if (commit_window) {
12278 		/* In commit phase we narrow the masking window based on
12279 		 * the observed pointer move after the simulated operation.
12280 		 */
12281 		alu_state = info->aux.alu_state;
12282 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12283 	} else {
12284 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12285 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12286 		alu_state |= ptr_is_dst_reg ?
12287 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12288 
12289 		/* Limit pruning on unknown scalars to enable deep search for
12290 		 * potential masking differences from other program paths.
12291 		 */
12292 		if (!off_is_imm)
12293 			env->explore_alu_limits = true;
12294 	}
12295 
12296 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12297 	if (err < 0)
12298 		return err;
12299 do_sim:
12300 	/* If we're in commit phase, we're done here given we already
12301 	 * pushed the truncated dst_reg into the speculative verification
12302 	 * stack.
12303 	 *
12304 	 * Also, when register is a known constant, we rewrite register-based
12305 	 * operation to immediate-based, and thus do not need masking (and as
12306 	 * a consequence, do not need to simulate the zero-truncation either).
12307 	 */
12308 	if (commit_window || off_is_imm)
12309 		return 0;
12310 
12311 	/* Simulate and find potential out-of-bounds access under
12312 	 * speculative execution from truncation as a result of
12313 	 * masking when off was not within expected range. If off
12314 	 * sits in dst, then we temporarily need to move ptr there
12315 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12316 	 * for cases where we use K-based arithmetic in one direction
12317 	 * and truncated reg-based in the other in order to explore
12318 	 * bad access.
12319 	 */
12320 	if (!ptr_is_dst_reg) {
12321 		tmp = *dst_reg;
12322 		copy_register_state(dst_reg, ptr_reg);
12323 	}
12324 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12325 					env->insn_idx);
12326 	if (!ptr_is_dst_reg && ret)
12327 		*dst_reg = tmp;
12328 	return !ret ? REASON_STACK : 0;
12329 }
12330 
12331 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12332 {
12333 	struct bpf_verifier_state *vstate = env->cur_state;
12334 
12335 	/* If we simulate paths under speculation, we don't update the
12336 	 * insn as 'seen' such that when we verify unreachable paths in
12337 	 * the non-speculative domain, sanitize_dead_code() can still
12338 	 * rewrite/sanitize them.
12339 	 */
12340 	if (!vstate->speculative)
12341 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12342 }
12343 
12344 static int sanitize_err(struct bpf_verifier_env *env,
12345 			const struct bpf_insn *insn, int reason,
12346 			const struct bpf_reg_state *off_reg,
12347 			const struct bpf_reg_state *dst_reg)
12348 {
12349 	static const char *err = "pointer arithmetic with it prohibited for !root";
12350 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12351 	u32 dst = insn->dst_reg, src = insn->src_reg;
12352 
12353 	switch (reason) {
12354 	case REASON_BOUNDS:
12355 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12356 			off_reg == dst_reg ? dst : src, err);
12357 		break;
12358 	case REASON_TYPE:
12359 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12360 			off_reg == dst_reg ? src : dst, err);
12361 		break;
12362 	case REASON_PATHS:
12363 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12364 			dst, op, err);
12365 		break;
12366 	case REASON_LIMIT:
12367 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12368 			dst, op, err);
12369 		break;
12370 	case REASON_STACK:
12371 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12372 			dst, err);
12373 		break;
12374 	default:
12375 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12376 			reason);
12377 		break;
12378 	}
12379 
12380 	return -EACCES;
12381 }
12382 
12383 /* check that stack access falls within stack limits and that 'reg' doesn't
12384  * have a variable offset.
12385  *
12386  * Variable offset is prohibited for unprivileged mode for simplicity since it
12387  * requires corresponding support in Spectre masking for stack ALU.  See also
12388  * retrieve_ptr_limit().
12389  *
12390  *
12391  * 'off' includes 'reg->off'.
12392  */
12393 static int check_stack_access_for_ptr_arithmetic(
12394 				struct bpf_verifier_env *env,
12395 				int regno,
12396 				const struct bpf_reg_state *reg,
12397 				int off)
12398 {
12399 	if (!tnum_is_const(reg->var_off)) {
12400 		char tn_buf[48];
12401 
12402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12403 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12404 			regno, tn_buf, off);
12405 		return -EACCES;
12406 	}
12407 
12408 	if (off >= 0 || off < -MAX_BPF_STACK) {
12409 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12410 			"prohibited for !root; off=%d\n", regno, off);
12411 		return -EACCES;
12412 	}
12413 
12414 	return 0;
12415 }
12416 
12417 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12418 				 const struct bpf_insn *insn,
12419 				 const struct bpf_reg_state *dst_reg)
12420 {
12421 	u32 dst = insn->dst_reg;
12422 
12423 	/* For unprivileged we require that resulting offset must be in bounds
12424 	 * in order to be able to sanitize access later on.
12425 	 */
12426 	if (env->bypass_spec_v1)
12427 		return 0;
12428 
12429 	switch (dst_reg->type) {
12430 	case PTR_TO_STACK:
12431 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12432 					dst_reg->off + dst_reg->var_off.value))
12433 			return -EACCES;
12434 		break;
12435 	case PTR_TO_MAP_VALUE:
12436 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12437 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12438 				"prohibited for !root\n", dst);
12439 			return -EACCES;
12440 		}
12441 		break;
12442 	default:
12443 		break;
12444 	}
12445 
12446 	return 0;
12447 }
12448 
12449 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12450  * Caller should also handle BPF_MOV case separately.
12451  * If we return -EACCES, caller may want to try again treating pointer as a
12452  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12453  */
12454 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12455 				   struct bpf_insn *insn,
12456 				   const struct bpf_reg_state *ptr_reg,
12457 				   const struct bpf_reg_state *off_reg)
12458 {
12459 	struct bpf_verifier_state *vstate = env->cur_state;
12460 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12461 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12462 	bool known = tnum_is_const(off_reg->var_off);
12463 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12464 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12465 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12466 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12467 	struct bpf_sanitize_info info = {};
12468 	u8 opcode = BPF_OP(insn->code);
12469 	u32 dst = insn->dst_reg;
12470 	int ret;
12471 
12472 	dst_reg = &regs[dst];
12473 
12474 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12475 	    smin_val > smax_val || umin_val > umax_val) {
12476 		/* Taint dst register if offset had invalid bounds derived from
12477 		 * e.g. dead branches.
12478 		 */
12479 		__mark_reg_unknown(env, dst_reg);
12480 		return 0;
12481 	}
12482 
12483 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12484 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12485 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12486 			__mark_reg_unknown(env, dst_reg);
12487 			return 0;
12488 		}
12489 
12490 		verbose(env,
12491 			"R%d 32-bit pointer arithmetic prohibited\n",
12492 			dst);
12493 		return -EACCES;
12494 	}
12495 
12496 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12497 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12498 			dst, reg_type_str(env, ptr_reg->type));
12499 		return -EACCES;
12500 	}
12501 
12502 	switch (base_type(ptr_reg->type)) {
12503 	case PTR_TO_FLOW_KEYS:
12504 		if (known)
12505 			break;
12506 		fallthrough;
12507 	case CONST_PTR_TO_MAP:
12508 		/* smin_val represents the known value */
12509 		if (known && smin_val == 0 && opcode == BPF_ADD)
12510 			break;
12511 		fallthrough;
12512 	case PTR_TO_PACKET_END:
12513 	case PTR_TO_SOCKET:
12514 	case PTR_TO_SOCK_COMMON:
12515 	case PTR_TO_TCP_SOCK:
12516 	case PTR_TO_XDP_SOCK:
12517 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12518 			dst, reg_type_str(env, ptr_reg->type));
12519 		return -EACCES;
12520 	default:
12521 		break;
12522 	}
12523 
12524 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12525 	 * The id may be overwritten later if we create a new variable offset.
12526 	 */
12527 	dst_reg->type = ptr_reg->type;
12528 	dst_reg->id = ptr_reg->id;
12529 
12530 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12531 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12532 		return -EINVAL;
12533 
12534 	/* pointer types do not carry 32-bit bounds at the moment. */
12535 	__mark_reg32_unbounded(dst_reg);
12536 
12537 	if (sanitize_needed(opcode)) {
12538 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12539 				       &info, false);
12540 		if (ret < 0)
12541 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12542 	}
12543 
12544 	switch (opcode) {
12545 	case BPF_ADD:
12546 		/* We can take a fixed offset as long as it doesn't overflow
12547 		 * the s32 'off' field
12548 		 */
12549 		if (known && (ptr_reg->off + smin_val ==
12550 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12551 			/* pointer += K.  Accumulate it into fixed offset */
12552 			dst_reg->smin_value = smin_ptr;
12553 			dst_reg->smax_value = smax_ptr;
12554 			dst_reg->umin_value = umin_ptr;
12555 			dst_reg->umax_value = umax_ptr;
12556 			dst_reg->var_off = ptr_reg->var_off;
12557 			dst_reg->off = ptr_reg->off + smin_val;
12558 			dst_reg->raw = ptr_reg->raw;
12559 			break;
12560 		}
12561 		/* A new variable offset is created.  Note that off_reg->off
12562 		 * == 0, since it's a scalar.
12563 		 * dst_reg gets the pointer type and since some positive
12564 		 * integer value was added to the pointer, give it a new 'id'
12565 		 * if it's a PTR_TO_PACKET.
12566 		 * this creates a new 'base' pointer, off_reg (variable) gets
12567 		 * added into the variable offset, and we copy the fixed offset
12568 		 * from ptr_reg.
12569 		 */
12570 		if (signed_add_overflows(smin_ptr, smin_val) ||
12571 		    signed_add_overflows(smax_ptr, smax_val)) {
12572 			dst_reg->smin_value = S64_MIN;
12573 			dst_reg->smax_value = S64_MAX;
12574 		} else {
12575 			dst_reg->smin_value = smin_ptr + smin_val;
12576 			dst_reg->smax_value = smax_ptr + smax_val;
12577 		}
12578 		if (umin_ptr + umin_val < umin_ptr ||
12579 		    umax_ptr + umax_val < umax_ptr) {
12580 			dst_reg->umin_value = 0;
12581 			dst_reg->umax_value = U64_MAX;
12582 		} else {
12583 			dst_reg->umin_value = umin_ptr + umin_val;
12584 			dst_reg->umax_value = umax_ptr + umax_val;
12585 		}
12586 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12587 		dst_reg->off = ptr_reg->off;
12588 		dst_reg->raw = ptr_reg->raw;
12589 		if (reg_is_pkt_pointer(ptr_reg)) {
12590 			dst_reg->id = ++env->id_gen;
12591 			/* something was added to pkt_ptr, set range to zero */
12592 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12593 		}
12594 		break;
12595 	case BPF_SUB:
12596 		if (dst_reg == off_reg) {
12597 			/* scalar -= pointer.  Creates an unknown scalar */
12598 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12599 				dst);
12600 			return -EACCES;
12601 		}
12602 		/* We don't allow subtraction from FP, because (according to
12603 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12604 		 * be able to deal with it.
12605 		 */
12606 		if (ptr_reg->type == PTR_TO_STACK) {
12607 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12608 				dst);
12609 			return -EACCES;
12610 		}
12611 		if (known && (ptr_reg->off - smin_val ==
12612 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12613 			/* pointer -= K.  Subtract it from fixed offset */
12614 			dst_reg->smin_value = smin_ptr;
12615 			dst_reg->smax_value = smax_ptr;
12616 			dst_reg->umin_value = umin_ptr;
12617 			dst_reg->umax_value = umax_ptr;
12618 			dst_reg->var_off = ptr_reg->var_off;
12619 			dst_reg->id = ptr_reg->id;
12620 			dst_reg->off = ptr_reg->off - smin_val;
12621 			dst_reg->raw = ptr_reg->raw;
12622 			break;
12623 		}
12624 		/* A new variable offset is created.  If the subtrahend is known
12625 		 * nonnegative, then any reg->range we had before is still good.
12626 		 */
12627 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12628 		    signed_sub_overflows(smax_ptr, smin_val)) {
12629 			/* Overflow possible, we know nothing */
12630 			dst_reg->smin_value = S64_MIN;
12631 			dst_reg->smax_value = S64_MAX;
12632 		} else {
12633 			dst_reg->smin_value = smin_ptr - smax_val;
12634 			dst_reg->smax_value = smax_ptr - smin_val;
12635 		}
12636 		if (umin_ptr < umax_val) {
12637 			/* Overflow possible, we know nothing */
12638 			dst_reg->umin_value = 0;
12639 			dst_reg->umax_value = U64_MAX;
12640 		} else {
12641 			/* Cannot overflow (as long as bounds are consistent) */
12642 			dst_reg->umin_value = umin_ptr - umax_val;
12643 			dst_reg->umax_value = umax_ptr - umin_val;
12644 		}
12645 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12646 		dst_reg->off = ptr_reg->off;
12647 		dst_reg->raw = ptr_reg->raw;
12648 		if (reg_is_pkt_pointer(ptr_reg)) {
12649 			dst_reg->id = ++env->id_gen;
12650 			/* something was added to pkt_ptr, set range to zero */
12651 			if (smin_val < 0)
12652 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12653 		}
12654 		break;
12655 	case BPF_AND:
12656 	case BPF_OR:
12657 	case BPF_XOR:
12658 		/* bitwise ops on pointers are troublesome, prohibit. */
12659 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12660 			dst, bpf_alu_string[opcode >> 4]);
12661 		return -EACCES;
12662 	default:
12663 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12664 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12665 			dst, bpf_alu_string[opcode >> 4]);
12666 		return -EACCES;
12667 	}
12668 
12669 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12670 		return -EINVAL;
12671 	reg_bounds_sync(dst_reg);
12672 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12673 		return -EACCES;
12674 	if (sanitize_needed(opcode)) {
12675 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12676 				       &info, true);
12677 		if (ret < 0)
12678 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12679 	}
12680 
12681 	return 0;
12682 }
12683 
12684 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12685 				 struct bpf_reg_state *src_reg)
12686 {
12687 	s32 smin_val = src_reg->s32_min_value;
12688 	s32 smax_val = src_reg->s32_max_value;
12689 	u32 umin_val = src_reg->u32_min_value;
12690 	u32 umax_val = src_reg->u32_max_value;
12691 
12692 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12693 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12694 		dst_reg->s32_min_value = S32_MIN;
12695 		dst_reg->s32_max_value = S32_MAX;
12696 	} else {
12697 		dst_reg->s32_min_value += smin_val;
12698 		dst_reg->s32_max_value += smax_val;
12699 	}
12700 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12701 	    dst_reg->u32_max_value + umax_val < umax_val) {
12702 		dst_reg->u32_min_value = 0;
12703 		dst_reg->u32_max_value = U32_MAX;
12704 	} else {
12705 		dst_reg->u32_min_value += umin_val;
12706 		dst_reg->u32_max_value += umax_val;
12707 	}
12708 }
12709 
12710 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12711 			       struct bpf_reg_state *src_reg)
12712 {
12713 	s64 smin_val = src_reg->smin_value;
12714 	s64 smax_val = src_reg->smax_value;
12715 	u64 umin_val = src_reg->umin_value;
12716 	u64 umax_val = src_reg->umax_value;
12717 
12718 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12719 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12720 		dst_reg->smin_value = S64_MIN;
12721 		dst_reg->smax_value = S64_MAX;
12722 	} else {
12723 		dst_reg->smin_value += smin_val;
12724 		dst_reg->smax_value += smax_val;
12725 	}
12726 	if (dst_reg->umin_value + umin_val < umin_val ||
12727 	    dst_reg->umax_value + umax_val < umax_val) {
12728 		dst_reg->umin_value = 0;
12729 		dst_reg->umax_value = U64_MAX;
12730 	} else {
12731 		dst_reg->umin_value += umin_val;
12732 		dst_reg->umax_value += umax_val;
12733 	}
12734 }
12735 
12736 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12737 				 struct bpf_reg_state *src_reg)
12738 {
12739 	s32 smin_val = src_reg->s32_min_value;
12740 	s32 smax_val = src_reg->s32_max_value;
12741 	u32 umin_val = src_reg->u32_min_value;
12742 	u32 umax_val = src_reg->u32_max_value;
12743 
12744 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12745 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12746 		/* Overflow possible, we know nothing */
12747 		dst_reg->s32_min_value = S32_MIN;
12748 		dst_reg->s32_max_value = S32_MAX;
12749 	} else {
12750 		dst_reg->s32_min_value -= smax_val;
12751 		dst_reg->s32_max_value -= smin_val;
12752 	}
12753 	if (dst_reg->u32_min_value < umax_val) {
12754 		/* Overflow possible, we know nothing */
12755 		dst_reg->u32_min_value = 0;
12756 		dst_reg->u32_max_value = U32_MAX;
12757 	} else {
12758 		/* Cannot overflow (as long as bounds are consistent) */
12759 		dst_reg->u32_min_value -= umax_val;
12760 		dst_reg->u32_max_value -= umin_val;
12761 	}
12762 }
12763 
12764 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12765 			       struct bpf_reg_state *src_reg)
12766 {
12767 	s64 smin_val = src_reg->smin_value;
12768 	s64 smax_val = src_reg->smax_value;
12769 	u64 umin_val = src_reg->umin_value;
12770 	u64 umax_val = src_reg->umax_value;
12771 
12772 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12773 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12774 		/* Overflow possible, we know nothing */
12775 		dst_reg->smin_value = S64_MIN;
12776 		dst_reg->smax_value = S64_MAX;
12777 	} else {
12778 		dst_reg->smin_value -= smax_val;
12779 		dst_reg->smax_value -= smin_val;
12780 	}
12781 	if (dst_reg->umin_value < umax_val) {
12782 		/* Overflow possible, we know nothing */
12783 		dst_reg->umin_value = 0;
12784 		dst_reg->umax_value = U64_MAX;
12785 	} else {
12786 		/* Cannot overflow (as long as bounds are consistent) */
12787 		dst_reg->umin_value -= umax_val;
12788 		dst_reg->umax_value -= umin_val;
12789 	}
12790 }
12791 
12792 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12793 				 struct bpf_reg_state *src_reg)
12794 {
12795 	s32 smin_val = src_reg->s32_min_value;
12796 	u32 umin_val = src_reg->u32_min_value;
12797 	u32 umax_val = src_reg->u32_max_value;
12798 
12799 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12800 		/* Ain't nobody got time to multiply that sign */
12801 		__mark_reg32_unbounded(dst_reg);
12802 		return;
12803 	}
12804 	/* Both values are positive, so we can work with unsigned and
12805 	 * copy the result to signed (unless it exceeds S32_MAX).
12806 	 */
12807 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12808 		/* Potential overflow, we know nothing */
12809 		__mark_reg32_unbounded(dst_reg);
12810 		return;
12811 	}
12812 	dst_reg->u32_min_value *= umin_val;
12813 	dst_reg->u32_max_value *= umax_val;
12814 	if (dst_reg->u32_max_value > S32_MAX) {
12815 		/* Overflow possible, we know nothing */
12816 		dst_reg->s32_min_value = S32_MIN;
12817 		dst_reg->s32_max_value = S32_MAX;
12818 	} else {
12819 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12820 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12821 	}
12822 }
12823 
12824 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12825 			       struct bpf_reg_state *src_reg)
12826 {
12827 	s64 smin_val = src_reg->smin_value;
12828 	u64 umin_val = src_reg->umin_value;
12829 	u64 umax_val = src_reg->umax_value;
12830 
12831 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12832 		/* Ain't nobody got time to multiply that sign */
12833 		__mark_reg64_unbounded(dst_reg);
12834 		return;
12835 	}
12836 	/* Both values are positive, so we can work with unsigned and
12837 	 * copy the result to signed (unless it exceeds S64_MAX).
12838 	 */
12839 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12840 		/* Potential overflow, we know nothing */
12841 		__mark_reg64_unbounded(dst_reg);
12842 		return;
12843 	}
12844 	dst_reg->umin_value *= umin_val;
12845 	dst_reg->umax_value *= umax_val;
12846 	if (dst_reg->umax_value > S64_MAX) {
12847 		/* Overflow possible, we know nothing */
12848 		dst_reg->smin_value = S64_MIN;
12849 		dst_reg->smax_value = S64_MAX;
12850 	} else {
12851 		dst_reg->smin_value = dst_reg->umin_value;
12852 		dst_reg->smax_value = dst_reg->umax_value;
12853 	}
12854 }
12855 
12856 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12857 				 struct bpf_reg_state *src_reg)
12858 {
12859 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12860 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12861 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12862 	s32 smin_val = src_reg->s32_min_value;
12863 	u32 umax_val = src_reg->u32_max_value;
12864 
12865 	if (src_known && dst_known) {
12866 		__mark_reg32_known(dst_reg, var32_off.value);
12867 		return;
12868 	}
12869 
12870 	/* We get our minimum from the var_off, since that's inherently
12871 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12872 	 */
12873 	dst_reg->u32_min_value = var32_off.value;
12874 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12875 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12876 		/* Lose signed bounds when ANDing negative numbers,
12877 		 * ain't nobody got time for that.
12878 		 */
12879 		dst_reg->s32_min_value = S32_MIN;
12880 		dst_reg->s32_max_value = S32_MAX;
12881 	} else {
12882 		/* ANDing two positives gives a positive, so safe to
12883 		 * cast result into s64.
12884 		 */
12885 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12886 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12887 	}
12888 }
12889 
12890 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12891 			       struct bpf_reg_state *src_reg)
12892 {
12893 	bool src_known = tnum_is_const(src_reg->var_off);
12894 	bool dst_known = tnum_is_const(dst_reg->var_off);
12895 	s64 smin_val = src_reg->smin_value;
12896 	u64 umax_val = src_reg->umax_value;
12897 
12898 	if (src_known && dst_known) {
12899 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12900 		return;
12901 	}
12902 
12903 	/* We get our minimum from the var_off, since that's inherently
12904 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12905 	 */
12906 	dst_reg->umin_value = dst_reg->var_off.value;
12907 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12908 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12909 		/* Lose signed bounds when ANDing negative numbers,
12910 		 * ain't nobody got time for that.
12911 		 */
12912 		dst_reg->smin_value = S64_MIN;
12913 		dst_reg->smax_value = S64_MAX;
12914 	} else {
12915 		/* ANDing two positives gives a positive, so safe to
12916 		 * cast result into s64.
12917 		 */
12918 		dst_reg->smin_value = dst_reg->umin_value;
12919 		dst_reg->smax_value = dst_reg->umax_value;
12920 	}
12921 	/* We may learn something more from the var_off */
12922 	__update_reg_bounds(dst_reg);
12923 }
12924 
12925 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12926 				struct bpf_reg_state *src_reg)
12927 {
12928 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12929 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12930 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12931 	s32 smin_val = src_reg->s32_min_value;
12932 	u32 umin_val = src_reg->u32_min_value;
12933 
12934 	if (src_known && dst_known) {
12935 		__mark_reg32_known(dst_reg, var32_off.value);
12936 		return;
12937 	}
12938 
12939 	/* We get our maximum from the var_off, and our minimum is the
12940 	 * maximum of the operands' minima
12941 	 */
12942 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12943 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12944 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12945 		/* Lose signed bounds when ORing negative numbers,
12946 		 * ain't nobody got time for that.
12947 		 */
12948 		dst_reg->s32_min_value = S32_MIN;
12949 		dst_reg->s32_max_value = S32_MAX;
12950 	} else {
12951 		/* ORing two positives gives a positive, so safe to
12952 		 * cast result into s64.
12953 		 */
12954 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12955 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12956 	}
12957 }
12958 
12959 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12960 			      struct bpf_reg_state *src_reg)
12961 {
12962 	bool src_known = tnum_is_const(src_reg->var_off);
12963 	bool dst_known = tnum_is_const(dst_reg->var_off);
12964 	s64 smin_val = src_reg->smin_value;
12965 	u64 umin_val = src_reg->umin_value;
12966 
12967 	if (src_known && dst_known) {
12968 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12969 		return;
12970 	}
12971 
12972 	/* We get our maximum from the var_off, and our minimum is the
12973 	 * maximum of the operands' minima
12974 	 */
12975 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12976 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12977 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12978 		/* Lose signed bounds when ORing negative numbers,
12979 		 * ain't nobody got time for that.
12980 		 */
12981 		dst_reg->smin_value = S64_MIN;
12982 		dst_reg->smax_value = S64_MAX;
12983 	} else {
12984 		/* ORing two positives gives a positive, so safe to
12985 		 * cast result into s64.
12986 		 */
12987 		dst_reg->smin_value = dst_reg->umin_value;
12988 		dst_reg->smax_value = dst_reg->umax_value;
12989 	}
12990 	/* We may learn something more from the var_off */
12991 	__update_reg_bounds(dst_reg);
12992 }
12993 
12994 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12995 				 struct bpf_reg_state *src_reg)
12996 {
12997 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12998 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12999 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13000 	s32 smin_val = src_reg->s32_min_value;
13001 
13002 	if (src_known && dst_known) {
13003 		__mark_reg32_known(dst_reg, var32_off.value);
13004 		return;
13005 	}
13006 
13007 	/* We get both minimum and maximum from the var32_off. */
13008 	dst_reg->u32_min_value = var32_off.value;
13009 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13010 
13011 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13012 		/* XORing two positive sign numbers gives a positive,
13013 		 * so safe to cast u32 result into s32.
13014 		 */
13015 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13016 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13017 	} else {
13018 		dst_reg->s32_min_value = S32_MIN;
13019 		dst_reg->s32_max_value = S32_MAX;
13020 	}
13021 }
13022 
13023 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13024 			       struct bpf_reg_state *src_reg)
13025 {
13026 	bool src_known = tnum_is_const(src_reg->var_off);
13027 	bool dst_known = tnum_is_const(dst_reg->var_off);
13028 	s64 smin_val = src_reg->smin_value;
13029 
13030 	if (src_known && dst_known) {
13031 		/* dst_reg->var_off.value has been updated earlier */
13032 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13033 		return;
13034 	}
13035 
13036 	/* We get both minimum and maximum from the var_off. */
13037 	dst_reg->umin_value = dst_reg->var_off.value;
13038 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13039 
13040 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13041 		/* XORing two positive sign numbers gives a positive,
13042 		 * so safe to cast u64 result into s64.
13043 		 */
13044 		dst_reg->smin_value = dst_reg->umin_value;
13045 		dst_reg->smax_value = dst_reg->umax_value;
13046 	} else {
13047 		dst_reg->smin_value = S64_MIN;
13048 		dst_reg->smax_value = S64_MAX;
13049 	}
13050 
13051 	__update_reg_bounds(dst_reg);
13052 }
13053 
13054 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13055 				   u64 umin_val, u64 umax_val)
13056 {
13057 	/* We lose all sign bit information (except what we can pick
13058 	 * up from var_off)
13059 	 */
13060 	dst_reg->s32_min_value = S32_MIN;
13061 	dst_reg->s32_max_value = S32_MAX;
13062 	/* If we might shift our top bit out, then we know nothing */
13063 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13064 		dst_reg->u32_min_value = 0;
13065 		dst_reg->u32_max_value = U32_MAX;
13066 	} else {
13067 		dst_reg->u32_min_value <<= umin_val;
13068 		dst_reg->u32_max_value <<= umax_val;
13069 	}
13070 }
13071 
13072 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13073 				 struct bpf_reg_state *src_reg)
13074 {
13075 	u32 umax_val = src_reg->u32_max_value;
13076 	u32 umin_val = src_reg->u32_min_value;
13077 	/* u32 alu operation will zext upper bits */
13078 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13079 
13080 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13081 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13082 	/* Not required but being careful mark reg64 bounds as unknown so
13083 	 * that we are forced to pick them up from tnum and zext later and
13084 	 * if some path skips this step we are still safe.
13085 	 */
13086 	__mark_reg64_unbounded(dst_reg);
13087 	__update_reg32_bounds(dst_reg);
13088 }
13089 
13090 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13091 				   u64 umin_val, u64 umax_val)
13092 {
13093 	/* Special case <<32 because it is a common compiler pattern to sign
13094 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13095 	 * positive we know this shift will also be positive so we can track
13096 	 * bounds correctly. Otherwise we lose all sign bit information except
13097 	 * what we can pick up from var_off. Perhaps we can generalize this
13098 	 * later to shifts of any length.
13099 	 */
13100 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13101 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13102 	else
13103 		dst_reg->smax_value = S64_MAX;
13104 
13105 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13106 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13107 	else
13108 		dst_reg->smin_value = S64_MIN;
13109 
13110 	/* If we might shift our top bit out, then we know nothing */
13111 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13112 		dst_reg->umin_value = 0;
13113 		dst_reg->umax_value = U64_MAX;
13114 	} else {
13115 		dst_reg->umin_value <<= umin_val;
13116 		dst_reg->umax_value <<= umax_val;
13117 	}
13118 }
13119 
13120 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13121 			       struct bpf_reg_state *src_reg)
13122 {
13123 	u64 umax_val = src_reg->umax_value;
13124 	u64 umin_val = src_reg->umin_value;
13125 
13126 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13127 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13128 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13129 
13130 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13131 	/* We may learn something more from the var_off */
13132 	__update_reg_bounds(dst_reg);
13133 }
13134 
13135 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13136 				 struct bpf_reg_state *src_reg)
13137 {
13138 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13139 	u32 umax_val = src_reg->u32_max_value;
13140 	u32 umin_val = src_reg->u32_min_value;
13141 
13142 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13143 	 * be negative, then either:
13144 	 * 1) src_reg might be zero, so the sign bit of the result is
13145 	 *    unknown, so we lose our signed bounds
13146 	 * 2) it's known negative, thus the unsigned bounds capture the
13147 	 *    signed bounds
13148 	 * 3) the signed bounds cross zero, so they tell us nothing
13149 	 *    about the result
13150 	 * If the value in dst_reg is known nonnegative, then again the
13151 	 * unsigned bounds capture the signed bounds.
13152 	 * Thus, in all cases it suffices to blow away our signed bounds
13153 	 * and rely on inferring new ones from the unsigned bounds and
13154 	 * var_off of the result.
13155 	 */
13156 	dst_reg->s32_min_value = S32_MIN;
13157 	dst_reg->s32_max_value = S32_MAX;
13158 
13159 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13160 	dst_reg->u32_min_value >>= umax_val;
13161 	dst_reg->u32_max_value >>= umin_val;
13162 
13163 	__mark_reg64_unbounded(dst_reg);
13164 	__update_reg32_bounds(dst_reg);
13165 }
13166 
13167 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13168 			       struct bpf_reg_state *src_reg)
13169 {
13170 	u64 umax_val = src_reg->umax_value;
13171 	u64 umin_val = src_reg->umin_value;
13172 
13173 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13174 	 * be negative, then either:
13175 	 * 1) src_reg might be zero, so the sign bit of the result is
13176 	 *    unknown, so we lose our signed bounds
13177 	 * 2) it's known negative, thus the unsigned bounds capture the
13178 	 *    signed bounds
13179 	 * 3) the signed bounds cross zero, so they tell us nothing
13180 	 *    about the result
13181 	 * If the value in dst_reg is known nonnegative, then again the
13182 	 * unsigned bounds capture the signed bounds.
13183 	 * Thus, in all cases it suffices to blow away our signed bounds
13184 	 * and rely on inferring new ones from the unsigned bounds and
13185 	 * var_off of the result.
13186 	 */
13187 	dst_reg->smin_value = S64_MIN;
13188 	dst_reg->smax_value = S64_MAX;
13189 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13190 	dst_reg->umin_value >>= umax_val;
13191 	dst_reg->umax_value >>= umin_val;
13192 
13193 	/* Its not easy to operate on alu32 bounds here because it depends
13194 	 * on bits being shifted in. Take easy way out and mark unbounded
13195 	 * so we can recalculate later from tnum.
13196 	 */
13197 	__mark_reg32_unbounded(dst_reg);
13198 	__update_reg_bounds(dst_reg);
13199 }
13200 
13201 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13202 				  struct bpf_reg_state *src_reg)
13203 {
13204 	u64 umin_val = src_reg->u32_min_value;
13205 
13206 	/* Upon reaching here, src_known is true and
13207 	 * umax_val is equal to umin_val.
13208 	 */
13209 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13210 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13211 
13212 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13213 
13214 	/* blow away the dst_reg umin_value/umax_value and rely on
13215 	 * dst_reg var_off to refine the result.
13216 	 */
13217 	dst_reg->u32_min_value = 0;
13218 	dst_reg->u32_max_value = U32_MAX;
13219 
13220 	__mark_reg64_unbounded(dst_reg);
13221 	__update_reg32_bounds(dst_reg);
13222 }
13223 
13224 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13225 				struct bpf_reg_state *src_reg)
13226 {
13227 	u64 umin_val = src_reg->umin_value;
13228 
13229 	/* Upon reaching here, src_known is true and umax_val is equal
13230 	 * to umin_val.
13231 	 */
13232 	dst_reg->smin_value >>= umin_val;
13233 	dst_reg->smax_value >>= umin_val;
13234 
13235 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13236 
13237 	/* blow away the dst_reg umin_value/umax_value and rely on
13238 	 * dst_reg var_off to refine the result.
13239 	 */
13240 	dst_reg->umin_value = 0;
13241 	dst_reg->umax_value = U64_MAX;
13242 
13243 	/* Its not easy to operate on alu32 bounds here because it depends
13244 	 * on bits being shifted in from upper 32-bits. Take easy way out
13245 	 * and mark unbounded so we can recalculate later from tnum.
13246 	 */
13247 	__mark_reg32_unbounded(dst_reg);
13248 	__update_reg_bounds(dst_reg);
13249 }
13250 
13251 /* WARNING: This function does calculations on 64-bit values, but the actual
13252  * execution may occur on 32-bit values. Therefore, things like bitshifts
13253  * need extra checks in the 32-bit case.
13254  */
13255 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13256 				      struct bpf_insn *insn,
13257 				      struct bpf_reg_state *dst_reg,
13258 				      struct bpf_reg_state src_reg)
13259 {
13260 	struct bpf_reg_state *regs = cur_regs(env);
13261 	u8 opcode = BPF_OP(insn->code);
13262 	bool src_known;
13263 	s64 smin_val, smax_val;
13264 	u64 umin_val, umax_val;
13265 	s32 s32_min_val, s32_max_val;
13266 	u32 u32_min_val, u32_max_val;
13267 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13268 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13269 	int ret;
13270 
13271 	smin_val = src_reg.smin_value;
13272 	smax_val = src_reg.smax_value;
13273 	umin_val = src_reg.umin_value;
13274 	umax_val = src_reg.umax_value;
13275 
13276 	s32_min_val = src_reg.s32_min_value;
13277 	s32_max_val = src_reg.s32_max_value;
13278 	u32_min_val = src_reg.u32_min_value;
13279 	u32_max_val = src_reg.u32_max_value;
13280 
13281 	if (alu32) {
13282 		src_known = tnum_subreg_is_const(src_reg.var_off);
13283 		if ((src_known &&
13284 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13285 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13286 			/* Taint dst register if offset had invalid bounds
13287 			 * derived from e.g. dead branches.
13288 			 */
13289 			__mark_reg_unknown(env, dst_reg);
13290 			return 0;
13291 		}
13292 	} else {
13293 		src_known = tnum_is_const(src_reg.var_off);
13294 		if ((src_known &&
13295 		     (smin_val != smax_val || umin_val != umax_val)) ||
13296 		    smin_val > smax_val || umin_val > umax_val) {
13297 			/* Taint dst register if offset had invalid bounds
13298 			 * derived from e.g. dead branches.
13299 			 */
13300 			__mark_reg_unknown(env, dst_reg);
13301 			return 0;
13302 		}
13303 	}
13304 
13305 	if (!src_known &&
13306 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13307 		__mark_reg_unknown(env, dst_reg);
13308 		return 0;
13309 	}
13310 
13311 	if (sanitize_needed(opcode)) {
13312 		ret = sanitize_val_alu(env, insn);
13313 		if (ret < 0)
13314 			return sanitize_err(env, insn, ret, NULL, NULL);
13315 	}
13316 
13317 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13318 	 * There are two classes of instructions: The first class we track both
13319 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13320 	 * greatest amount of precision when alu operations are mixed with jmp32
13321 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13322 	 * and BPF_OR. This is possible because these ops have fairly easy to
13323 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13324 	 * See alu32 verifier tests for examples. The second class of
13325 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13326 	 * with regards to tracking sign/unsigned bounds because the bits may
13327 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13328 	 * the reg unbounded in the subreg bound space and use the resulting
13329 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13330 	 */
13331 	switch (opcode) {
13332 	case BPF_ADD:
13333 		scalar32_min_max_add(dst_reg, &src_reg);
13334 		scalar_min_max_add(dst_reg, &src_reg);
13335 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13336 		break;
13337 	case BPF_SUB:
13338 		scalar32_min_max_sub(dst_reg, &src_reg);
13339 		scalar_min_max_sub(dst_reg, &src_reg);
13340 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13341 		break;
13342 	case BPF_MUL:
13343 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13344 		scalar32_min_max_mul(dst_reg, &src_reg);
13345 		scalar_min_max_mul(dst_reg, &src_reg);
13346 		break;
13347 	case BPF_AND:
13348 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13349 		scalar32_min_max_and(dst_reg, &src_reg);
13350 		scalar_min_max_and(dst_reg, &src_reg);
13351 		break;
13352 	case BPF_OR:
13353 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13354 		scalar32_min_max_or(dst_reg, &src_reg);
13355 		scalar_min_max_or(dst_reg, &src_reg);
13356 		break;
13357 	case BPF_XOR:
13358 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13359 		scalar32_min_max_xor(dst_reg, &src_reg);
13360 		scalar_min_max_xor(dst_reg, &src_reg);
13361 		break;
13362 	case BPF_LSH:
13363 		if (umax_val >= insn_bitness) {
13364 			/* Shifts greater than 31 or 63 are undefined.
13365 			 * This includes shifts by a negative number.
13366 			 */
13367 			mark_reg_unknown(env, regs, insn->dst_reg);
13368 			break;
13369 		}
13370 		if (alu32)
13371 			scalar32_min_max_lsh(dst_reg, &src_reg);
13372 		else
13373 			scalar_min_max_lsh(dst_reg, &src_reg);
13374 		break;
13375 	case BPF_RSH:
13376 		if (umax_val >= insn_bitness) {
13377 			/* Shifts greater than 31 or 63 are undefined.
13378 			 * This includes shifts by a negative number.
13379 			 */
13380 			mark_reg_unknown(env, regs, insn->dst_reg);
13381 			break;
13382 		}
13383 		if (alu32)
13384 			scalar32_min_max_rsh(dst_reg, &src_reg);
13385 		else
13386 			scalar_min_max_rsh(dst_reg, &src_reg);
13387 		break;
13388 	case BPF_ARSH:
13389 		if (umax_val >= insn_bitness) {
13390 			/* Shifts greater than 31 or 63 are undefined.
13391 			 * This includes shifts by a negative number.
13392 			 */
13393 			mark_reg_unknown(env, regs, insn->dst_reg);
13394 			break;
13395 		}
13396 		if (alu32)
13397 			scalar32_min_max_arsh(dst_reg, &src_reg);
13398 		else
13399 			scalar_min_max_arsh(dst_reg, &src_reg);
13400 		break;
13401 	default:
13402 		mark_reg_unknown(env, regs, insn->dst_reg);
13403 		break;
13404 	}
13405 
13406 	/* ALU32 ops are zero extended into 64bit register */
13407 	if (alu32)
13408 		zext_32_to_64(dst_reg);
13409 	reg_bounds_sync(dst_reg);
13410 	return 0;
13411 }
13412 
13413 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13414  * and var_off.
13415  */
13416 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13417 				   struct bpf_insn *insn)
13418 {
13419 	struct bpf_verifier_state *vstate = env->cur_state;
13420 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13421 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13422 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13423 	u8 opcode = BPF_OP(insn->code);
13424 	int err;
13425 
13426 	dst_reg = &regs[insn->dst_reg];
13427 	src_reg = NULL;
13428 	if (dst_reg->type != SCALAR_VALUE)
13429 		ptr_reg = dst_reg;
13430 	else
13431 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13432 		 * incorrectly propagated into other registers by find_equal_scalars()
13433 		 */
13434 		dst_reg->id = 0;
13435 	if (BPF_SRC(insn->code) == BPF_X) {
13436 		src_reg = &regs[insn->src_reg];
13437 		if (src_reg->type != SCALAR_VALUE) {
13438 			if (dst_reg->type != SCALAR_VALUE) {
13439 				/* Combining two pointers by any ALU op yields
13440 				 * an arbitrary scalar. Disallow all math except
13441 				 * pointer subtraction
13442 				 */
13443 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13444 					mark_reg_unknown(env, regs, insn->dst_reg);
13445 					return 0;
13446 				}
13447 				verbose(env, "R%d pointer %s pointer prohibited\n",
13448 					insn->dst_reg,
13449 					bpf_alu_string[opcode >> 4]);
13450 				return -EACCES;
13451 			} else {
13452 				/* scalar += pointer
13453 				 * This is legal, but we have to reverse our
13454 				 * src/dest handling in computing the range
13455 				 */
13456 				err = mark_chain_precision(env, insn->dst_reg);
13457 				if (err)
13458 					return err;
13459 				return adjust_ptr_min_max_vals(env, insn,
13460 							       src_reg, dst_reg);
13461 			}
13462 		} else if (ptr_reg) {
13463 			/* pointer += scalar */
13464 			err = mark_chain_precision(env, insn->src_reg);
13465 			if (err)
13466 				return err;
13467 			return adjust_ptr_min_max_vals(env, insn,
13468 						       dst_reg, src_reg);
13469 		} else if (dst_reg->precise) {
13470 			/* if dst_reg is precise, src_reg should be precise as well */
13471 			err = mark_chain_precision(env, insn->src_reg);
13472 			if (err)
13473 				return err;
13474 		}
13475 	} else {
13476 		/* Pretend the src is a reg with a known value, since we only
13477 		 * need to be able to read from this state.
13478 		 */
13479 		off_reg.type = SCALAR_VALUE;
13480 		__mark_reg_known(&off_reg, insn->imm);
13481 		src_reg = &off_reg;
13482 		if (ptr_reg) /* pointer += K */
13483 			return adjust_ptr_min_max_vals(env, insn,
13484 						       ptr_reg, src_reg);
13485 	}
13486 
13487 	/* Got here implies adding two SCALAR_VALUEs */
13488 	if (WARN_ON_ONCE(ptr_reg)) {
13489 		print_verifier_state(env, state, true);
13490 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13491 		return -EINVAL;
13492 	}
13493 	if (WARN_ON(!src_reg)) {
13494 		print_verifier_state(env, state, true);
13495 		verbose(env, "verifier internal error: no src_reg\n");
13496 		return -EINVAL;
13497 	}
13498 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13499 }
13500 
13501 /* check validity of 32-bit and 64-bit arithmetic operations */
13502 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13503 {
13504 	struct bpf_reg_state *regs = cur_regs(env);
13505 	u8 opcode = BPF_OP(insn->code);
13506 	int err;
13507 
13508 	if (opcode == BPF_END || opcode == BPF_NEG) {
13509 		if (opcode == BPF_NEG) {
13510 			if (BPF_SRC(insn->code) != BPF_K ||
13511 			    insn->src_reg != BPF_REG_0 ||
13512 			    insn->off != 0 || insn->imm != 0) {
13513 				verbose(env, "BPF_NEG uses reserved fields\n");
13514 				return -EINVAL;
13515 			}
13516 		} else {
13517 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13518 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13519 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13520 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13521 				verbose(env, "BPF_END uses reserved fields\n");
13522 				return -EINVAL;
13523 			}
13524 		}
13525 
13526 		/* check src operand */
13527 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13528 		if (err)
13529 			return err;
13530 
13531 		if (is_pointer_value(env, insn->dst_reg)) {
13532 			verbose(env, "R%d pointer arithmetic prohibited\n",
13533 				insn->dst_reg);
13534 			return -EACCES;
13535 		}
13536 
13537 		/* check dest operand */
13538 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13539 		if (err)
13540 			return err;
13541 
13542 	} else if (opcode == BPF_MOV) {
13543 
13544 		if (BPF_SRC(insn->code) == BPF_X) {
13545 			if (insn->imm != 0) {
13546 				verbose(env, "BPF_MOV uses reserved fields\n");
13547 				return -EINVAL;
13548 			}
13549 
13550 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13551 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13552 					verbose(env, "BPF_MOV uses reserved fields\n");
13553 					return -EINVAL;
13554 				}
13555 			} else {
13556 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13557 				    insn->off != 32) {
13558 					verbose(env, "BPF_MOV uses reserved fields\n");
13559 					return -EINVAL;
13560 				}
13561 			}
13562 
13563 			/* check src operand */
13564 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13565 			if (err)
13566 				return err;
13567 		} else {
13568 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13569 				verbose(env, "BPF_MOV uses reserved fields\n");
13570 				return -EINVAL;
13571 			}
13572 		}
13573 
13574 		/* check dest operand, mark as required later */
13575 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13576 		if (err)
13577 			return err;
13578 
13579 		if (BPF_SRC(insn->code) == BPF_X) {
13580 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13581 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13582 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13583 				       !tnum_is_const(src_reg->var_off);
13584 
13585 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13586 				if (insn->off == 0) {
13587 					/* case: R1 = R2
13588 					 * copy register state to dest reg
13589 					 */
13590 					if (need_id)
13591 						/* Assign src and dst registers the same ID
13592 						 * that will be used by find_equal_scalars()
13593 						 * to propagate min/max range.
13594 						 */
13595 						src_reg->id = ++env->id_gen;
13596 					copy_register_state(dst_reg, src_reg);
13597 					dst_reg->live |= REG_LIVE_WRITTEN;
13598 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13599 				} else {
13600 					/* case: R1 = (s8, s16 s32)R2 */
13601 					if (is_pointer_value(env, insn->src_reg)) {
13602 						verbose(env,
13603 							"R%d sign-extension part of pointer\n",
13604 							insn->src_reg);
13605 						return -EACCES;
13606 					} else if (src_reg->type == SCALAR_VALUE) {
13607 						bool no_sext;
13608 
13609 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13610 						if (no_sext && need_id)
13611 							src_reg->id = ++env->id_gen;
13612 						copy_register_state(dst_reg, src_reg);
13613 						if (!no_sext)
13614 							dst_reg->id = 0;
13615 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13616 						dst_reg->live |= REG_LIVE_WRITTEN;
13617 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13618 					} else {
13619 						mark_reg_unknown(env, regs, insn->dst_reg);
13620 					}
13621 				}
13622 			} else {
13623 				/* R1 = (u32) R2 */
13624 				if (is_pointer_value(env, insn->src_reg)) {
13625 					verbose(env,
13626 						"R%d partial copy of pointer\n",
13627 						insn->src_reg);
13628 					return -EACCES;
13629 				} else if (src_reg->type == SCALAR_VALUE) {
13630 					if (insn->off == 0) {
13631 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13632 
13633 						if (is_src_reg_u32 && need_id)
13634 							src_reg->id = ++env->id_gen;
13635 						copy_register_state(dst_reg, src_reg);
13636 						/* Make sure ID is cleared if src_reg is not in u32
13637 						 * range otherwise dst_reg min/max could be incorrectly
13638 						 * propagated into src_reg by find_equal_scalars()
13639 						 */
13640 						if (!is_src_reg_u32)
13641 							dst_reg->id = 0;
13642 						dst_reg->live |= REG_LIVE_WRITTEN;
13643 						dst_reg->subreg_def = env->insn_idx + 1;
13644 					} else {
13645 						/* case: W1 = (s8, s16)W2 */
13646 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13647 
13648 						if (no_sext && need_id)
13649 							src_reg->id = ++env->id_gen;
13650 						copy_register_state(dst_reg, src_reg);
13651 						if (!no_sext)
13652 							dst_reg->id = 0;
13653 						dst_reg->live |= REG_LIVE_WRITTEN;
13654 						dst_reg->subreg_def = env->insn_idx + 1;
13655 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13656 					}
13657 				} else {
13658 					mark_reg_unknown(env, regs,
13659 							 insn->dst_reg);
13660 				}
13661 				zext_32_to_64(dst_reg);
13662 				reg_bounds_sync(dst_reg);
13663 			}
13664 		} else {
13665 			/* case: R = imm
13666 			 * remember the value we stored into this reg
13667 			 */
13668 			/* clear any state __mark_reg_known doesn't set */
13669 			mark_reg_unknown(env, regs, insn->dst_reg);
13670 			regs[insn->dst_reg].type = SCALAR_VALUE;
13671 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13672 				__mark_reg_known(regs + insn->dst_reg,
13673 						 insn->imm);
13674 			} else {
13675 				__mark_reg_known(regs + insn->dst_reg,
13676 						 (u32)insn->imm);
13677 			}
13678 		}
13679 
13680 	} else if (opcode > BPF_END) {
13681 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13682 		return -EINVAL;
13683 
13684 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13685 
13686 		if (BPF_SRC(insn->code) == BPF_X) {
13687 			if (insn->imm != 0 || insn->off > 1 ||
13688 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13689 				verbose(env, "BPF_ALU uses reserved fields\n");
13690 				return -EINVAL;
13691 			}
13692 			/* check src1 operand */
13693 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13694 			if (err)
13695 				return err;
13696 		} else {
13697 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13698 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13699 				verbose(env, "BPF_ALU uses reserved fields\n");
13700 				return -EINVAL;
13701 			}
13702 		}
13703 
13704 		/* check src2 operand */
13705 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13706 		if (err)
13707 			return err;
13708 
13709 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13710 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13711 			verbose(env, "div by zero\n");
13712 			return -EINVAL;
13713 		}
13714 
13715 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13716 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13717 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13718 
13719 			if (insn->imm < 0 || insn->imm >= size) {
13720 				verbose(env, "invalid shift %d\n", insn->imm);
13721 				return -EINVAL;
13722 			}
13723 		}
13724 
13725 		/* check dest operand */
13726 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13727 		if (err)
13728 			return err;
13729 
13730 		return adjust_reg_min_max_vals(env, insn);
13731 	}
13732 
13733 	return 0;
13734 }
13735 
13736 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13737 				   struct bpf_reg_state *dst_reg,
13738 				   enum bpf_reg_type type,
13739 				   bool range_right_open)
13740 {
13741 	struct bpf_func_state *state;
13742 	struct bpf_reg_state *reg;
13743 	int new_range;
13744 
13745 	if (dst_reg->off < 0 ||
13746 	    (dst_reg->off == 0 && range_right_open))
13747 		/* This doesn't give us any range */
13748 		return;
13749 
13750 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13751 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13752 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13753 		 * than pkt_end, but that's because it's also less than pkt.
13754 		 */
13755 		return;
13756 
13757 	new_range = dst_reg->off;
13758 	if (range_right_open)
13759 		new_range++;
13760 
13761 	/* Examples for register markings:
13762 	 *
13763 	 * pkt_data in dst register:
13764 	 *
13765 	 *   r2 = r3;
13766 	 *   r2 += 8;
13767 	 *   if (r2 > pkt_end) goto <handle exception>
13768 	 *   <access okay>
13769 	 *
13770 	 *   r2 = r3;
13771 	 *   r2 += 8;
13772 	 *   if (r2 < pkt_end) goto <access okay>
13773 	 *   <handle exception>
13774 	 *
13775 	 *   Where:
13776 	 *     r2 == dst_reg, pkt_end == src_reg
13777 	 *     r2=pkt(id=n,off=8,r=0)
13778 	 *     r3=pkt(id=n,off=0,r=0)
13779 	 *
13780 	 * pkt_data in src register:
13781 	 *
13782 	 *   r2 = r3;
13783 	 *   r2 += 8;
13784 	 *   if (pkt_end >= r2) goto <access okay>
13785 	 *   <handle exception>
13786 	 *
13787 	 *   r2 = r3;
13788 	 *   r2 += 8;
13789 	 *   if (pkt_end <= r2) goto <handle exception>
13790 	 *   <access okay>
13791 	 *
13792 	 *   Where:
13793 	 *     pkt_end == dst_reg, r2 == src_reg
13794 	 *     r2=pkt(id=n,off=8,r=0)
13795 	 *     r3=pkt(id=n,off=0,r=0)
13796 	 *
13797 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13798 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13799 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13800 	 * the check.
13801 	 */
13802 
13803 	/* If our ids match, then we must have the same max_value.  And we
13804 	 * don't care about the other reg's fixed offset, since if it's too big
13805 	 * the range won't allow anything.
13806 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13807 	 */
13808 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13809 		if (reg->type == type && reg->id == dst_reg->id)
13810 			/* keep the maximum range already checked */
13811 			reg->range = max(reg->range, new_range);
13812 	}));
13813 }
13814 
13815 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13816 {
13817 	struct tnum subreg = tnum_subreg(reg->var_off);
13818 	s32 sval = (s32)val;
13819 
13820 	switch (opcode) {
13821 	case BPF_JEQ:
13822 		if (tnum_is_const(subreg))
13823 			return !!tnum_equals_const(subreg, val);
13824 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13825 			return 0;
13826 		break;
13827 	case BPF_JNE:
13828 		if (tnum_is_const(subreg))
13829 			return !tnum_equals_const(subreg, val);
13830 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13831 			return 1;
13832 		break;
13833 	case BPF_JSET:
13834 		if ((~subreg.mask & subreg.value) & val)
13835 			return 1;
13836 		if (!((subreg.mask | subreg.value) & val))
13837 			return 0;
13838 		break;
13839 	case BPF_JGT:
13840 		if (reg->u32_min_value > val)
13841 			return 1;
13842 		else if (reg->u32_max_value <= val)
13843 			return 0;
13844 		break;
13845 	case BPF_JSGT:
13846 		if (reg->s32_min_value > sval)
13847 			return 1;
13848 		else if (reg->s32_max_value <= sval)
13849 			return 0;
13850 		break;
13851 	case BPF_JLT:
13852 		if (reg->u32_max_value < val)
13853 			return 1;
13854 		else if (reg->u32_min_value >= val)
13855 			return 0;
13856 		break;
13857 	case BPF_JSLT:
13858 		if (reg->s32_max_value < sval)
13859 			return 1;
13860 		else if (reg->s32_min_value >= sval)
13861 			return 0;
13862 		break;
13863 	case BPF_JGE:
13864 		if (reg->u32_min_value >= val)
13865 			return 1;
13866 		else if (reg->u32_max_value < val)
13867 			return 0;
13868 		break;
13869 	case BPF_JSGE:
13870 		if (reg->s32_min_value >= sval)
13871 			return 1;
13872 		else if (reg->s32_max_value < sval)
13873 			return 0;
13874 		break;
13875 	case BPF_JLE:
13876 		if (reg->u32_max_value <= val)
13877 			return 1;
13878 		else if (reg->u32_min_value > val)
13879 			return 0;
13880 		break;
13881 	case BPF_JSLE:
13882 		if (reg->s32_max_value <= sval)
13883 			return 1;
13884 		else if (reg->s32_min_value > sval)
13885 			return 0;
13886 		break;
13887 	}
13888 
13889 	return -1;
13890 }
13891 
13892 
13893 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13894 {
13895 	s64 sval = (s64)val;
13896 
13897 	switch (opcode) {
13898 	case BPF_JEQ:
13899 		if (tnum_is_const(reg->var_off))
13900 			return !!tnum_equals_const(reg->var_off, val);
13901 		else if (val < reg->umin_value || val > reg->umax_value)
13902 			return 0;
13903 		break;
13904 	case BPF_JNE:
13905 		if (tnum_is_const(reg->var_off))
13906 			return !tnum_equals_const(reg->var_off, val);
13907 		else if (val < reg->umin_value || val > reg->umax_value)
13908 			return 1;
13909 		break;
13910 	case BPF_JSET:
13911 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13912 			return 1;
13913 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13914 			return 0;
13915 		break;
13916 	case BPF_JGT:
13917 		if (reg->umin_value > val)
13918 			return 1;
13919 		else if (reg->umax_value <= val)
13920 			return 0;
13921 		break;
13922 	case BPF_JSGT:
13923 		if (reg->smin_value > sval)
13924 			return 1;
13925 		else if (reg->smax_value <= sval)
13926 			return 0;
13927 		break;
13928 	case BPF_JLT:
13929 		if (reg->umax_value < val)
13930 			return 1;
13931 		else if (reg->umin_value >= val)
13932 			return 0;
13933 		break;
13934 	case BPF_JSLT:
13935 		if (reg->smax_value < sval)
13936 			return 1;
13937 		else if (reg->smin_value >= sval)
13938 			return 0;
13939 		break;
13940 	case BPF_JGE:
13941 		if (reg->umin_value >= val)
13942 			return 1;
13943 		else if (reg->umax_value < val)
13944 			return 0;
13945 		break;
13946 	case BPF_JSGE:
13947 		if (reg->smin_value >= sval)
13948 			return 1;
13949 		else if (reg->smax_value < sval)
13950 			return 0;
13951 		break;
13952 	case BPF_JLE:
13953 		if (reg->umax_value <= val)
13954 			return 1;
13955 		else if (reg->umin_value > val)
13956 			return 0;
13957 		break;
13958 	case BPF_JSLE:
13959 		if (reg->smax_value <= sval)
13960 			return 1;
13961 		else if (reg->smin_value > sval)
13962 			return 0;
13963 		break;
13964 	}
13965 
13966 	return -1;
13967 }
13968 
13969 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13970  * and return:
13971  *  1 - branch will be taken and "goto target" will be executed
13972  *  0 - branch will not be taken and fall-through to next insn
13973  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13974  *      range [0,10]
13975  */
13976 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13977 			   bool is_jmp32)
13978 {
13979 	if (__is_pointer_value(false, reg)) {
13980 		if (!reg_not_null(reg))
13981 			return -1;
13982 
13983 		/* If pointer is valid tests against zero will fail so we can
13984 		 * use this to direct branch taken.
13985 		 */
13986 		if (val != 0)
13987 			return -1;
13988 
13989 		switch (opcode) {
13990 		case BPF_JEQ:
13991 			return 0;
13992 		case BPF_JNE:
13993 			return 1;
13994 		default:
13995 			return -1;
13996 		}
13997 	}
13998 
13999 	if (is_jmp32)
14000 		return is_branch32_taken(reg, val, opcode);
14001 	return is_branch64_taken(reg, val, opcode);
14002 }
14003 
14004 static int flip_opcode(u32 opcode)
14005 {
14006 	/* How can we transform "a <op> b" into "b <op> a"? */
14007 	static const u8 opcode_flip[16] = {
14008 		/* these stay the same */
14009 		[BPF_JEQ  >> 4] = BPF_JEQ,
14010 		[BPF_JNE  >> 4] = BPF_JNE,
14011 		[BPF_JSET >> 4] = BPF_JSET,
14012 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14013 		[BPF_JGE  >> 4] = BPF_JLE,
14014 		[BPF_JGT  >> 4] = BPF_JLT,
14015 		[BPF_JLE  >> 4] = BPF_JGE,
14016 		[BPF_JLT  >> 4] = BPF_JGT,
14017 		[BPF_JSGE >> 4] = BPF_JSLE,
14018 		[BPF_JSGT >> 4] = BPF_JSLT,
14019 		[BPF_JSLE >> 4] = BPF_JSGE,
14020 		[BPF_JSLT >> 4] = BPF_JSGT
14021 	};
14022 	return opcode_flip[opcode >> 4];
14023 }
14024 
14025 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14026 				   struct bpf_reg_state *src_reg,
14027 				   u8 opcode)
14028 {
14029 	struct bpf_reg_state *pkt;
14030 
14031 	if (src_reg->type == PTR_TO_PACKET_END) {
14032 		pkt = dst_reg;
14033 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14034 		pkt = src_reg;
14035 		opcode = flip_opcode(opcode);
14036 	} else {
14037 		return -1;
14038 	}
14039 
14040 	if (pkt->range >= 0)
14041 		return -1;
14042 
14043 	switch (opcode) {
14044 	case BPF_JLE:
14045 		/* pkt <= pkt_end */
14046 		fallthrough;
14047 	case BPF_JGT:
14048 		/* pkt > pkt_end */
14049 		if (pkt->range == BEYOND_PKT_END)
14050 			/* pkt has at last one extra byte beyond pkt_end */
14051 			return opcode == BPF_JGT;
14052 		break;
14053 	case BPF_JLT:
14054 		/* pkt < pkt_end */
14055 		fallthrough;
14056 	case BPF_JGE:
14057 		/* pkt >= pkt_end */
14058 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14059 			return opcode == BPF_JGE;
14060 		break;
14061 	}
14062 	return -1;
14063 }
14064 
14065 /* Adjusts the register min/max values in the case that the dst_reg is the
14066  * variable register that we are working on, and src_reg is a constant or we're
14067  * simply doing a BPF_K check.
14068  * In JEQ/JNE cases we also adjust the var_off values.
14069  */
14070 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14071 			    struct bpf_reg_state *false_reg,
14072 			    u64 val, u32 val32,
14073 			    u8 opcode, bool is_jmp32)
14074 {
14075 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14076 	struct tnum false_64off = false_reg->var_off;
14077 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14078 	struct tnum true_64off = true_reg->var_off;
14079 	s64 sval = (s64)val;
14080 	s32 sval32 = (s32)val32;
14081 
14082 	/* If the dst_reg is a pointer, we can't learn anything about its
14083 	 * variable offset from the compare (unless src_reg were a pointer into
14084 	 * the same object, but we don't bother with that.
14085 	 * Since false_reg and true_reg have the same type by construction, we
14086 	 * only need to check one of them for pointerness.
14087 	 */
14088 	if (__is_pointer_value(false, false_reg))
14089 		return;
14090 
14091 	switch (opcode) {
14092 	/* JEQ/JNE comparison doesn't change the register equivalence.
14093 	 *
14094 	 * r1 = r2;
14095 	 * if (r1 == 42) goto label;
14096 	 * ...
14097 	 * label: // here both r1 and r2 are known to be 42.
14098 	 *
14099 	 * Hence when marking register as known preserve it's ID.
14100 	 */
14101 	case BPF_JEQ:
14102 		if (is_jmp32) {
14103 			__mark_reg32_known(true_reg, val32);
14104 			true_32off = tnum_subreg(true_reg->var_off);
14105 		} else {
14106 			___mark_reg_known(true_reg, val);
14107 			true_64off = true_reg->var_off;
14108 		}
14109 		break;
14110 	case BPF_JNE:
14111 		if (is_jmp32) {
14112 			__mark_reg32_known(false_reg, val32);
14113 			false_32off = tnum_subreg(false_reg->var_off);
14114 		} else {
14115 			___mark_reg_known(false_reg, val);
14116 			false_64off = false_reg->var_off;
14117 		}
14118 		break;
14119 	case BPF_JSET:
14120 		if (is_jmp32) {
14121 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14122 			if (is_power_of_2(val32))
14123 				true_32off = tnum_or(true_32off,
14124 						     tnum_const(val32));
14125 		} else {
14126 			false_64off = tnum_and(false_64off, tnum_const(~val));
14127 			if (is_power_of_2(val))
14128 				true_64off = tnum_or(true_64off,
14129 						     tnum_const(val));
14130 		}
14131 		break;
14132 	case BPF_JGE:
14133 	case BPF_JGT:
14134 	{
14135 		if (is_jmp32) {
14136 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14137 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14138 
14139 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14140 						       false_umax);
14141 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14142 						      true_umin);
14143 		} else {
14144 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14145 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14146 
14147 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14148 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14149 		}
14150 		break;
14151 	}
14152 	case BPF_JSGE:
14153 	case BPF_JSGT:
14154 	{
14155 		if (is_jmp32) {
14156 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14157 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14158 
14159 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14160 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14161 		} else {
14162 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14163 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14164 
14165 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14166 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14167 		}
14168 		break;
14169 	}
14170 	case BPF_JLE:
14171 	case BPF_JLT:
14172 	{
14173 		if (is_jmp32) {
14174 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14175 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14176 
14177 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14178 						       false_umin);
14179 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14180 						      true_umax);
14181 		} else {
14182 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14183 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14184 
14185 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14186 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14187 		}
14188 		break;
14189 	}
14190 	case BPF_JSLE:
14191 	case BPF_JSLT:
14192 	{
14193 		if (is_jmp32) {
14194 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14195 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14196 
14197 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14198 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14199 		} else {
14200 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14201 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14202 
14203 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14204 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14205 		}
14206 		break;
14207 	}
14208 	default:
14209 		return;
14210 	}
14211 
14212 	if (is_jmp32) {
14213 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14214 					     tnum_subreg(false_32off));
14215 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14216 					    tnum_subreg(true_32off));
14217 		__reg_combine_32_into_64(false_reg);
14218 		__reg_combine_32_into_64(true_reg);
14219 	} else {
14220 		false_reg->var_off = false_64off;
14221 		true_reg->var_off = true_64off;
14222 		__reg_combine_64_into_32(false_reg);
14223 		__reg_combine_64_into_32(true_reg);
14224 	}
14225 }
14226 
14227 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14228  * the variable reg.
14229  */
14230 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14231 				struct bpf_reg_state *false_reg,
14232 				u64 val, u32 val32,
14233 				u8 opcode, bool is_jmp32)
14234 {
14235 	opcode = flip_opcode(opcode);
14236 	/* This uses zero as "not present in table"; luckily the zero opcode,
14237 	 * BPF_JA, can't get here.
14238 	 */
14239 	if (opcode)
14240 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14241 }
14242 
14243 /* Regs are known to be equal, so intersect their min/max/var_off */
14244 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14245 				  struct bpf_reg_state *dst_reg)
14246 {
14247 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14248 							dst_reg->umin_value);
14249 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14250 							dst_reg->umax_value);
14251 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14252 							dst_reg->smin_value);
14253 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14254 							dst_reg->smax_value);
14255 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14256 							     dst_reg->var_off);
14257 	reg_bounds_sync(src_reg);
14258 	reg_bounds_sync(dst_reg);
14259 }
14260 
14261 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14262 				struct bpf_reg_state *true_dst,
14263 				struct bpf_reg_state *false_src,
14264 				struct bpf_reg_state *false_dst,
14265 				u8 opcode)
14266 {
14267 	switch (opcode) {
14268 	case BPF_JEQ:
14269 		__reg_combine_min_max(true_src, true_dst);
14270 		break;
14271 	case BPF_JNE:
14272 		__reg_combine_min_max(false_src, false_dst);
14273 		break;
14274 	}
14275 }
14276 
14277 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14278 				 struct bpf_reg_state *reg, u32 id,
14279 				 bool is_null)
14280 {
14281 	if (type_may_be_null(reg->type) && reg->id == id &&
14282 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14283 		/* Old offset (both fixed and variable parts) should have been
14284 		 * known-zero, because we don't allow pointer arithmetic on
14285 		 * pointers that might be NULL. If we see this happening, don't
14286 		 * convert the register.
14287 		 *
14288 		 * But in some cases, some helpers that return local kptrs
14289 		 * advance offset for the returned pointer. In those cases, it
14290 		 * is fine to expect to see reg->off.
14291 		 */
14292 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14293 			return;
14294 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14295 		    WARN_ON_ONCE(reg->off))
14296 			return;
14297 
14298 		if (is_null) {
14299 			reg->type = SCALAR_VALUE;
14300 			/* We don't need id and ref_obj_id from this point
14301 			 * onwards anymore, thus we should better reset it,
14302 			 * so that state pruning has chances to take effect.
14303 			 */
14304 			reg->id = 0;
14305 			reg->ref_obj_id = 0;
14306 
14307 			return;
14308 		}
14309 
14310 		mark_ptr_not_null_reg(reg);
14311 
14312 		if (!reg_may_point_to_spin_lock(reg)) {
14313 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14314 			 * in release_reference().
14315 			 *
14316 			 * reg->id is still used by spin_lock ptr. Other
14317 			 * than spin_lock ptr type, reg->id can be reset.
14318 			 */
14319 			reg->id = 0;
14320 		}
14321 	}
14322 }
14323 
14324 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14325  * be folded together at some point.
14326  */
14327 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14328 				  bool is_null)
14329 {
14330 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14331 	struct bpf_reg_state *regs = state->regs, *reg;
14332 	u32 ref_obj_id = regs[regno].ref_obj_id;
14333 	u32 id = regs[regno].id;
14334 
14335 	if (ref_obj_id && ref_obj_id == id && is_null)
14336 		/* regs[regno] is in the " == NULL" branch.
14337 		 * No one could have freed the reference state before
14338 		 * doing the NULL check.
14339 		 */
14340 		WARN_ON_ONCE(release_reference_state(state, id));
14341 
14342 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14343 		mark_ptr_or_null_reg(state, reg, id, is_null);
14344 	}));
14345 }
14346 
14347 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14348 				   struct bpf_reg_state *dst_reg,
14349 				   struct bpf_reg_state *src_reg,
14350 				   struct bpf_verifier_state *this_branch,
14351 				   struct bpf_verifier_state *other_branch)
14352 {
14353 	if (BPF_SRC(insn->code) != BPF_X)
14354 		return false;
14355 
14356 	/* Pointers are always 64-bit. */
14357 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14358 		return false;
14359 
14360 	switch (BPF_OP(insn->code)) {
14361 	case BPF_JGT:
14362 		if ((dst_reg->type == PTR_TO_PACKET &&
14363 		     src_reg->type == PTR_TO_PACKET_END) ||
14364 		    (dst_reg->type == PTR_TO_PACKET_META &&
14365 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14366 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14367 			find_good_pkt_pointers(this_branch, dst_reg,
14368 					       dst_reg->type, false);
14369 			mark_pkt_end(other_branch, insn->dst_reg, true);
14370 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14371 			    src_reg->type == PTR_TO_PACKET) ||
14372 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14373 			    src_reg->type == PTR_TO_PACKET_META)) {
14374 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14375 			find_good_pkt_pointers(other_branch, src_reg,
14376 					       src_reg->type, true);
14377 			mark_pkt_end(this_branch, insn->src_reg, false);
14378 		} else {
14379 			return false;
14380 		}
14381 		break;
14382 	case BPF_JLT:
14383 		if ((dst_reg->type == PTR_TO_PACKET &&
14384 		     src_reg->type == PTR_TO_PACKET_END) ||
14385 		    (dst_reg->type == PTR_TO_PACKET_META &&
14386 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14387 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14388 			find_good_pkt_pointers(other_branch, dst_reg,
14389 					       dst_reg->type, true);
14390 			mark_pkt_end(this_branch, insn->dst_reg, false);
14391 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14392 			    src_reg->type == PTR_TO_PACKET) ||
14393 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14394 			    src_reg->type == PTR_TO_PACKET_META)) {
14395 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14396 			find_good_pkt_pointers(this_branch, src_reg,
14397 					       src_reg->type, false);
14398 			mark_pkt_end(other_branch, insn->src_reg, true);
14399 		} else {
14400 			return false;
14401 		}
14402 		break;
14403 	case BPF_JGE:
14404 		if ((dst_reg->type == PTR_TO_PACKET &&
14405 		     src_reg->type == PTR_TO_PACKET_END) ||
14406 		    (dst_reg->type == PTR_TO_PACKET_META &&
14407 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14408 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14409 			find_good_pkt_pointers(this_branch, dst_reg,
14410 					       dst_reg->type, true);
14411 			mark_pkt_end(other_branch, insn->dst_reg, false);
14412 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14413 			    src_reg->type == PTR_TO_PACKET) ||
14414 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14415 			    src_reg->type == PTR_TO_PACKET_META)) {
14416 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14417 			find_good_pkt_pointers(other_branch, src_reg,
14418 					       src_reg->type, false);
14419 			mark_pkt_end(this_branch, insn->src_reg, true);
14420 		} else {
14421 			return false;
14422 		}
14423 		break;
14424 	case BPF_JLE:
14425 		if ((dst_reg->type == PTR_TO_PACKET &&
14426 		     src_reg->type == PTR_TO_PACKET_END) ||
14427 		    (dst_reg->type == PTR_TO_PACKET_META &&
14428 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14429 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14430 			find_good_pkt_pointers(other_branch, dst_reg,
14431 					       dst_reg->type, false);
14432 			mark_pkt_end(this_branch, insn->dst_reg, true);
14433 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14434 			    src_reg->type == PTR_TO_PACKET) ||
14435 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14436 			    src_reg->type == PTR_TO_PACKET_META)) {
14437 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14438 			find_good_pkt_pointers(this_branch, src_reg,
14439 					       src_reg->type, true);
14440 			mark_pkt_end(other_branch, insn->src_reg, false);
14441 		} else {
14442 			return false;
14443 		}
14444 		break;
14445 	default:
14446 		return false;
14447 	}
14448 
14449 	return true;
14450 }
14451 
14452 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14453 			       struct bpf_reg_state *known_reg)
14454 {
14455 	struct bpf_func_state *state;
14456 	struct bpf_reg_state *reg;
14457 
14458 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14459 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14460 			copy_register_state(reg, known_reg);
14461 	}));
14462 }
14463 
14464 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14465 			     struct bpf_insn *insn, int *insn_idx)
14466 {
14467 	struct bpf_verifier_state *this_branch = env->cur_state;
14468 	struct bpf_verifier_state *other_branch;
14469 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14470 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14471 	struct bpf_reg_state *eq_branch_regs;
14472 	u8 opcode = BPF_OP(insn->code);
14473 	bool is_jmp32;
14474 	int pred = -1;
14475 	int err;
14476 
14477 	/* Only conditional jumps are expected to reach here. */
14478 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14479 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14480 		return -EINVAL;
14481 	}
14482 
14483 	/* check src2 operand */
14484 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14485 	if (err)
14486 		return err;
14487 
14488 	dst_reg = &regs[insn->dst_reg];
14489 	if (BPF_SRC(insn->code) == BPF_X) {
14490 		if (insn->imm != 0) {
14491 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14492 			return -EINVAL;
14493 		}
14494 
14495 		/* check src1 operand */
14496 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14497 		if (err)
14498 			return err;
14499 
14500 		src_reg = &regs[insn->src_reg];
14501 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14502 		    is_pointer_value(env, insn->src_reg)) {
14503 			verbose(env, "R%d pointer comparison prohibited\n",
14504 				insn->src_reg);
14505 			return -EACCES;
14506 		}
14507 	} else {
14508 		if (insn->src_reg != BPF_REG_0) {
14509 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14510 			return -EINVAL;
14511 		}
14512 	}
14513 
14514 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14515 
14516 	if (BPF_SRC(insn->code) == BPF_K) {
14517 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14518 	} else if (src_reg->type == SCALAR_VALUE &&
14519 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14520 		pred = is_branch_taken(dst_reg,
14521 				       tnum_subreg(src_reg->var_off).value,
14522 				       opcode,
14523 				       is_jmp32);
14524 	} else if (src_reg->type == SCALAR_VALUE &&
14525 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14526 		pred = is_branch_taken(dst_reg,
14527 				       src_reg->var_off.value,
14528 				       opcode,
14529 				       is_jmp32);
14530 	} else if (dst_reg->type == SCALAR_VALUE &&
14531 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14532 		pred = is_branch_taken(src_reg,
14533 				       tnum_subreg(dst_reg->var_off).value,
14534 				       flip_opcode(opcode),
14535 				       is_jmp32);
14536 	} else if (dst_reg->type == SCALAR_VALUE &&
14537 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14538 		pred = is_branch_taken(src_reg,
14539 				       dst_reg->var_off.value,
14540 				       flip_opcode(opcode),
14541 				       is_jmp32);
14542 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14543 		   reg_is_pkt_pointer_any(src_reg) &&
14544 		   !is_jmp32) {
14545 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14546 	}
14547 
14548 	if (pred >= 0) {
14549 		/* If we get here with a dst_reg pointer type it is because
14550 		 * above is_branch_taken() special cased the 0 comparison.
14551 		 */
14552 		if (!__is_pointer_value(false, dst_reg))
14553 			err = mark_chain_precision(env, insn->dst_reg);
14554 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14555 		    !__is_pointer_value(false, src_reg))
14556 			err = mark_chain_precision(env, insn->src_reg);
14557 		if (err)
14558 			return err;
14559 	}
14560 
14561 	if (pred == 1) {
14562 		/* Only follow the goto, ignore fall-through. If needed, push
14563 		 * the fall-through branch for simulation under speculative
14564 		 * execution.
14565 		 */
14566 		if (!env->bypass_spec_v1 &&
14567 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14568 					       *insn_idx))
14569 			return -EFAULT;
14570 		if (env->log.level & BPF_LOG_LEVEL)
14571 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14572 		*insn_idx += insn->off;
14573 		return 0;
14574 	} else if (pred == 0) {
14575 		/* Only follow the fall-through branch, since that's where the
14576 		 * program will go. If needed, push the goto branch for
14577 		 * simulation under speculative execution.
14578 		 */
14579 		if (!env->bypass_spec_v1 &&
14580 		    !sanitize_speculative_path(env, insn,
14581 					       *insn_idx + insn->off + 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 		return 0;
14587 	}
14588 
14589 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14590 				  false);
14591 	if (!other_branch)
14592 		return -EFAULT;
14593 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14594 
14595 	/* detect if we are comparing against a constant value so we can adjust
14596 	 * our min/max values for our dst register.
14597 	 * this is only legit if both are scalars (or pointers to the same
14598 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14599 	 * because otherwise the different base pointers mean the offsets aren't
14600 	 * comparable.
14601 	 */
14602 	if (BPF_SRC(insn->code) == BPF_X) {
14603 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14604 
14605 		if (dst_reg->type == SCALAR_VALUE &&
14606 		    src_reg->type == SCALAR_VALUE) {
14607 			if (tnum_is_const(src_reg->var_off) ||
14608 			    (is_jmp32 &&
14609 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14610 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14611 						dst_reg,
14612 						src_reg->var_off.value,
14613 						tnum_subreg(src_reg->var_off).value,
14614 						opcode, is_jmp32);
14615 			else if (tnum_is_const(dst_reg->var_off) ||
14616 				 (is_jmp32 &&
14617 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14618 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14619 						    src_reg,
14620 						    dst_reg->var_off.value,
14621 						    tnum_subreg(dst_reg->var_off).value,
14622 						    opcode, is_jmp32);
14623 			else if (!is_jmp32 &&
14624 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14625 				/* Comparing for equality, we can combine knowledge */
14626 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14627 						    &other_branch_regs[insn->dst_reg],
14628 						    src_reg, dst_reg, opcode);
14629 			if (src_reg->id &&
14630 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14631 				find_equal_scalars(this_branch, src_reg);
14632 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14633 			}
14634 
14635 		}
14636 	} else if (dst_reg->type == SCALAR_VALUE) {
14637 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14638 					dst_reg, insn->imm, (u32)insn->imm,
14639 					opcode, is_jmp32);
14640 	}
14641 
14642 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14643 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14644 		find_equal_scalars(this_branch, dst_reg);
14645 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14646 	}
14647 
14648 	/* if one pointer register is compared to another pointer
14649 	 * register check if PTR_MAYBE_NULL could be lifted.
14650 	 * E.g. register A - maybe null
14651 	 *      register B - not null
14652 	 * for JNE A, B, ... - A is not null in the false branch;
14653 	 * for JEQ A, B, ... - A is not null in the true branch.
14654 	 *
14655 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14656 	 * not need to be null checked by the BPF program, i.e.,
14657 	 * could be null even without PTR_MAYBE_NULL marking, so
14658 	 * only propagate nullness when neither reg is that type.
14659 	 */
14660 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14661 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14662 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14663 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14664 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14665 		eq_branch_regs = NULL;
14666 		switch (opcode) {
14667 		case BPF_JEQ:
14668 			eq_branch_regs = other_branch_regs;
14669 			break;
14670 		case BPF_JNE:
14671 			eq_branch_regs = regs;
14672 			break;
14673 		default:
14674 			/* do nothing */
14675 			break;
14676 		}
14677 		if (eq_branch_regs) {
14678 			if (type_may_be_null(src_reg->type))
14679 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14680 			else
14681 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14682 		}
14683 	}
14684 
14685 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14686 	 * NOTE: these optimizations below are related with pointer comparison
14687 	 *       which will never be JMP32.
14688 	 */
14689 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14690 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14691 	    type_may_be_null(dst_reg->type)) {
14692 		/* Mark all identical registers in each branch as either
14693 		 * safe or unknown depending R == 0 or R != 0 conditional.
14694 		 */
14695 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14696 				      opcode == BPF_JNE);
14697 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14698 				      opcode == BPF_JEQ);
14699 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14700 					   this_branch, other_branch) &&
14701 		   is_pointer_value(env, insn->dst_reg)) {
14702 		verbose(env, "R%d pointer comparison prohibited\n",
14703 			insn->dst_reg);
14704 		return -EACCES;
14705 	}
14706 	if (env->log.level & BPF_LOG_LEVEL)
14707 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14708 	return 0;
14709 }
14710 
14711 /* verify BPF_LD_IMM64 instruction */
14712 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14713 {
14714 	struct bpf_insn_aux_data *aux = cur_aux(env);
14715 	struct bpf_reg_state *regs = cur_regs(env);
14716 	struct bpf_reg_state *dst_reg;
14717 	struct bpf_map *map;
14718 	int err;
14719 
14720 	if (BPF_SIZE(insn->code) != BPF_DW) {
14721 		verbose(env, "invalid BPF_LD_IMM insn\n");
14722 		return -EINVAL;
14723 	}
14724 	if (insn->off != 0) {
14725 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14726 		return -EINVAL;
14727 	}
14728 
14729 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14730 	if (err)
14731 		return err;
14732 
14733 	dst_reg = &regs[insn->dst_reg];
14734 	if (insn->src_reg == 0) {
14735 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14736 
14737 		dst_reg->type = SCALAR_VALUE;
14738 		__mark_reg_known(&regs[insn->dst_reg], imm);
14739 		return 0;
14740 	}
14741 
14742 	/* All special src_reg cases are listed below. From this point onwards
14743 	 * we either succeed and assign a corresponding dst_reg->type after
14744 	 * zeroing the offset, or fail and reject the program.
14745 	 */
14746 	mark_reg_known_zero(env, regs, insn->dst_reg);
14747 
14748 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14749 		dst_reg->type = aux->btf_var.reg_type;
14750 		switch (base_type(dst_reg->type)) {
14751 		case PTR_TO_MEM:
14752 			dst_reg->mem_size = aux->btf_var.mem_size;
14753 			break;
14754 		case PTR_TO_BTF_ID:
14755 			dst_reg->btf = aux->btf_var.btf;
14756 			dst_reg->btf_id = aux->btf_var.btf_id;
14757 			break;
14758 		default:
14759 			verbose(env, "bpf verifier is misconfigured\n");
14760 			return -EFAULT;
14761 		}
14762 		return 0;
14763 	}
14764 
14765 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14766 		struct bpf_prog_aux *aux = env->prog->aux;
14767 		u32 subprogno = find_subprog(env,
14768 					     env->insn_idx + insn->imm + 1);
14769 
14770 		if (!aux->func_info) {
14771 			verbose(env, "missing btf func_info\n");
14772 			return -EINVAL;
14773 		}
14774 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14775 			verbose(env, "callback function not static\n");
14776 			return -EINVAL;
14777 		}
14778 
14779 		dst_reg->type = PTR_TO_FUNC;
14780 		dst_reg->subprogno = subprogno;
14781 		return 0;
14782 	}
14783 
14784 	map = env->used_maps[aux->map_index];
14785 	dst_reg->map_ptr = map;
14786 
14787 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14788 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14789 		dst_reg->type = PTR_TO_MAP_VALUE;
14790 		dst_reg->off = aux->map_off;
14791 		WARN_ON_ONCE(map->max_entries != 1);
14792 		/* We want reg->id to be same (0) as map_value is not distinct */
14793 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14794 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14795 		dst_reg->type = CONST_PTR_TO_MAP;
14796 	} else {
14797 		verbose(env, "bpf verifier is misconfigured\n");
14798 		return -EINVAL;
14799 	}
14800 
14801 	return 0;
14802 }
14803 
14804 static bool may_access_skb(enum bpf_prog_type type)
14805 {
14806 	switch (type) {
14807 	case BPF_PROG_TYPE_SOCKET_FILTER:
14808 	case BPF_PROG_TYPE_SCHED_CLS:
14809 	case BPF_PROG_TYPE_SCHED_ACT:
14810 		return true;
14811 	default:
14812 		return false;
14813 	}
14814 }
14815 
14816 /* verify safety of LD_ABS|LD_IND instructions:
14817  * - they can only appear in the programs where ctx == skb
14818  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14819  *   preserve R6-R9, and store return value into R0
14820  *
14821  * Implicit input:
14822  *   ctx == skb == R6 == CTX
14823  *
14824  * Explicit input:
14825  *   SRC == any register
14826  *   IMM == 32-bit immediate
14827  *
14828  * Output:
14829  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14830  */
14831 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14832 {
14833 	struct bpf_reg_state *regs = cur_regs(env);
14834 	static const int ctx_reg = BPF_REG_6;
14835 	u8 mode = BPF_MODE(insn->code);
14836 	int i, err;
14837 
14838 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14839 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14840 		return -EINVAL;
14841 	}
14842 
14843 	if (!env->ops->gen_ld_abs) {
14844 		verbose(env, "bpf verifier is misconfigured\n");
14845 		return -EINVAL;
14846 	}
14847 
14848 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14849 	    BPF_SIZE(insn->code) == BPF_DW ||
14850 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14851 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14852 		return -EINVAL;
14853 	}
14854 
14855 	/* check whether implicit source operand (register R6) is readable */
14856 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14857 	if (err)
14858 		return err;
14859 
14860 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14861 	 * gen_ld_abs() may terminate the program at runtime, leading to
14862 	 * reference leak.
14863 	 */
14864 	err = check_reference_leak(env);
14865 	if (err) {
14866 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14867 		return err;
14868 	}
14869 
14870 	if (env->cur_state->active_lock.ptr) {
14871 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14872 		return -EINVAL;
14873 	}
14874 
14875 	if (env->cur_state->active_rcu_lock) {
14876 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14877 		return -EINVAL;
14878 	}
14879 
14880 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14881 		verbose(env,
14882 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14883 		return -EINVAL;
14884 	}
14885 
14886 	if (mode == BPF_IND) {
14887 		/* check explicit source operand */
14888 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14889 		if (err)
14890 			return err;
14891 	}
14892 
14893 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14894 	if (err < 0)
14895 		return err;
14896 
14897 	/* reset caller saved regs to unreadable */
14898 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14899 		mark_reg_not_init(env, regs, caller_saved[i]);
14900 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14901 	}
14902 
14903 	/* mark destination R0 register as readable, since it contains
14904 	 * the value fetched from the packet.
14905 	 * Already marked as written above.
14906 	 */
14907 	mark_reg_unknown(env, regs, BPF_REG_0);
14908 	/* ld_abs load up to 32-bit skb data. */
14909 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14910 	return 0;
14911 }
14912 
14913 static int check_return_code(struct bpf_verifier_env *env)
14914 {
14915 	struct tnum enforce_attach_type_range = tnum_unknown;
14916 	const struct bpf_prog *prog = env->prog;
14917 	struct bpf_reg_state *reg;
14918 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14919 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14920 	int err;
14921 	struct bpf_func_state *frame = env->cur_state->frame[0];
14922 	const bool is_subprog = frame->subprogno;
14923 
14924 	/* LSM and struct_ops func-ptr's return type could be "void" */
14925 	if (!is_subprog) {
14926 		switch (prog_type) {
14927 		case BPF_PROG_TYPE_LSM:
14928 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14929 				/* See below, can be 0 or 0-1 depending on hook. */
14930 				break;
14931 			fallthrough;
14932 		case BPF_PROG_TYPE_STRUCT_OPS:
14933 			if (!prog->aux->attach_func_proto->type)
14934 				return 0;
14935 			break;
14936 		default:
14937 			break;
14938 		}
14939 	}
14940 
14941 	/* eBPF calling convention is such that R0 is used
14942 	 * to return the value from eBPF program.
14943 	 * Make sure that it's readable at this time
14944 	 * of bpf_exit, which means that program wrote
14945 	 * something into it earlier
14946 	 */
14947 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14948 	if (err)
14949 		return err;
14950 
14951 	if (is_pointer_value(env, BPF_REG_0)) {
14952 		verbose(env, "R0 leaks addr as return value\n");
14953 		return -EACCES;
14954 	}
14955 
14956 	reg = cur_regs(env) + BPF_REG_0;
14957 
14958 	if (frame->in_async_callback_fn) {
14959 		/* enforce return zero from async callbacks like timer */
14960 		if (reg->type != SCALAR_VALUE) {
14961 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14962 				reg_type_str(env, reg->type));
14963 			return -EINVAL;
14964 		}
14965 
14966 		if (!tnum_in(const_0, reg->var_off)) {
14967 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14968 			return -EINVAL;
14969 		}
14970 		return 0;
14971 	}
14972 
14973 	if (is_subprog) {
14974 		if (reg->type != SCALAR_VALUE) {
14975 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14976 				reg_type_str(env, reg->type));
14977 			return -EINVAL;
14978 		}
14979 		return 0;
14980 	}
14981 
14982 	switch (prog_type) {
14983 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14984 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14985 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14986 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14987 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14988 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14989 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14990 			range = tnum_range(1, 1);
14991 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14992 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14993 			range = tnum_range(0, 3);
14994 		break;
14995 	case BPF_PROG_TYPE_CGROUP_SKB:
14996 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14997 			range = tnum_range(0, 3);
14998 			enforce_attach_type_range = tnum_range(2, 3);
14999 		}
15000 		break;
15001 	case BPF_PROG_TYPE_CGROUP_SOCK:
15002 	case BPF_PROG_TYPE_SOCK_OPS:
15003 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15004 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15005 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15006 		break;
15007 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15008 		if (!env->prog->aux->attach_btf_id)
15009 			return 0;
15010 		range = tnum_const(0);
15011 		break;
15012 	case BPF_PROG_TYPE_TRACING:
15013 		switch (env->prog->expected_attach_type) {
15014 		case BPF_TRACE_FENTRY:
15015 		case BPF_TRACE_FEXIT:
15016 			range = tnum_const(0);
15017 			break;
15018 		case BPF_TRACE_RAW_TP:
15019 		case BPF_MODIFY_RETURN:
15020 			return 0;
15021 		case BPF_TRACE_ITER:
15022 			break;
15023 		default:
15024 			return -ENOTSUPP;
15025 		}
15026 		break;
15027 	case BPF_PROG_TYPE_SK_LOOKUP:
15028 		range = tnum_range(SK_DROP, SK_PASS);
15029 		break;
15030 
15031 	case BPF_PROG_TYPE_LSM:
15032 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15033 			/* Regular BPF_PROG_TYPE_LSM programs can return
15034 			 * any value.
15035 			 */
15036 			return 0;
15037 		}
15038 		if (!env->prog->aux->attach_func_proto->type) {
15039 			/* Make sure programs that attach to void
15040 			 * hooks don't try to modify return value.
15041 			 */
15042 			range = tnum_range(1, 1);
15043 		}
15044 		break;
15045 
15046 	case BPF_PROG_TYPE_NETFILTER:
15047 		range = tnum_range(NF_DROP, NF_ACCEPT);
15048 		break;
15049 	case BPF_PROG_TYPE_EXT:
15050 		/* freplace program can return anything as its return value
15051 		 * depends on the to-be-replaced kernel func or bpf program.
15052 		 */
15053 	default:
15054 		return 0;
15055 	}
15056 
15057 	if (reg->type != SCALAR_VALUE) {
15058 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15059 			reg_type_str(env, reg->type));
15060 		return -EINVAL;
15061 	}
15062 
15063 	if (!tnum_in(range, reg->var_off)) {
15064 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15065 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15066 		    prog_type == BPF_PROG_TYPE_LSM &&
15067 		    !prog->aux->attach_func_proto->type)
15068 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15069 		return -EINVAL;
15070 	}
15071 
15072 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15073 	    tnum_in(enforce_attach_type_range, reg->var_off))
15074 		env->prog->enforce_expected_attach_type = 1;
15075 	return 0;
15076 }
15077 
15078 /* non-recursive DFS pseudo code
15079  * 1  procedure DFS-iterative(G,v):
15080  * 2      label v as discovered
15081  * 3      let S be a stack
15082  * 4      S.push(v)
15083  * 5      while S is not empty
15084  * 6            t <- S.peek()
15085  * 7            if t is what we're looking for:
15086  * 8                return t
15087  * 9            for all edges e in G.adjacentEdges(t) do
15088  * 10               if edge e is already labelled
15089  * 11                   continue with the next edge
15090  * 12               w <- G.adjacentVertex(t,e)
15091  * 13               if vertex w is not discovered and not explored
15092  * 14                   label e as tree-edge
15093  * 15                   label w as discovered
15094  * 16                   S.push(w)
15095  * 17                   continue at 5
15096  * 18               else if vertex w is discovered
15097  * 19                   label e as back-edge
15098  * 20               else
15099  * 21                   // vertex w is explored
15100  * 22                   label e as forward- or cross-edge
15101  * 23           label t as explored
15102  * 24           S.pop()
15103  *
15104  * convention:
15105  * 0x10 - discovered
15106  * 0x11 - discovered and fall-through edge labelled
15107  * 0x12 - discovered and fall-through and branch edges labelled
15108  * 0x20 - explored
15109  */
15110 
15111 enum {
15112 	DISCOVERED = 0x10,
15113 	EXPLORED = 0x20,
15114 	FALLTHROUGH = 1,
15115 	BRANCH = 2,
15116 };
15117 
15118 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15119 {
15120 	env->insn_aux_data[idx].prune_point = true;
15121 }
15122 
15123 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15124 {
15125 	return env->insn_aux_data[insn_idx].prune_point;
15126 }
15127 
15128 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15129 {
15130 	env->insn_aux_data[idx].force_checkpoint = true;
15131 }
15132 
15133 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15134 {
15135 	return env->insn_aux_data[insn_idx].force_checkpoint;
15136 }
15137 
15138 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15139 {
15140 	env->insn_aux_data[idx].calls_callback = true;
15141 }
15142 
15143 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15144 {
15145 	return env->insn_aux_data[insn_idx].calls_callback;
15146 }
15147 
15148 enum {
15149 	DONE_EXPLORING = 0,
15150 	KEEP_EXPLORING = 1,
15151 };
15152 
15153 /* t, w, e - match pseudo-code above:
15154  * t - index of current instruction
15155  * w - next instruction
15156  * e - edge
15157  */
15158 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15159 {
15160 	int *insn_stack = env->cfg.insn_stack;
15161 	int *insn_state = env->cfg.insn_state;
15162 
15163 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15164 		return DONE_EXPLORING;
15165 
15166 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15167 		return DONE_EXPLORING;
15168 
15169 	if (w < 0 || w >= env->prog->len) {
15170 		verbose_linfo(env, t, "%d: ", t);
15171 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15172 		return -EINVAL;
15173 	}
15174 
15175 	if (e == BRANCH) {
15176 		/* mark branch target for state pruning */
15177 		mark_prune_point(env, w);
15178 		mark_jmp_point(env, w);
15179 	}
15180 
15181 	if (insn_state[w] == 0) {
15182 		/* tree-edge */
15183 		insn_state[t] = DISCOVERED | e;
15184 		insn_state[w] = DISCOVERED;
15185 		if (env->cfg.cur_stack >= env->prog->len)
15186 			return -E2BIG;
15187 		insn_stack[env->cfg.cur_stack++] = w;
15188 		return KEEP_EXPLORING;
15189 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15190 		if (env->bpf_capable)
15191 			return DONE_EXPLORING;
15192 		verbose_linfo(env, t, "%d: ", t);
15193 		verbose_linfo(env, w, "%d: ", w);
15194 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15195 		return -EINVAL;
15196 	} else if (insn_state[w] == EXPLORED) {
15197 		/* forward- or cross-edge */
15198 		insn_state[t] = DISCOVERED | e;
15199 	} else {
15200 		verbose(env, "insn state internal bug\n");
15201 		return -EFAULT;
15202 	}
15203 	return DONE_EXPLORING;
15204 }
15205 
15206 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15207 				struct bpf_verifier_env *env,
15208 				bool visit_callee)
15209 {
15210 	int ret, insn_sz;
15211 
15212 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15213 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15214 	if (ret)
15215 		return ret;
15216 
15217 	mark_prune_point(env, t + insn_sz);
15218 	/* when we exit from subprog, we need to record non-linear history */
15219 	mark_jmp_point(env, t + insn_sz);
15220 
15221 	if (visit_callee) {
15222 		mark_prune_point(env, t);
15223 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15224 	}
15225 	return ret;
15226 }
15227 
15228 /* Visits the instruction at index t and returns one of the following:
15229  *  < 0 - an error occurred
15230  *  DONE_EXPLORING - the instruction was fully explored
15231  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15232  */
15233 static int visit_insn(int t, struct bpf_verifier_env *env)
15234 {
15235 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15236 	int ret, off, insn_sz;
15237 
15238 	if (bpf_pseudo_func(insn))
15239 		return visit_func_call_insn(t, insns, env, true);
15240 
15241 	/* All non-branch instructions have a single fall-through edge. */
15242 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15243 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15244 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15245 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15246 	}
15247 
15248 	switch (BPF_OP(insn->code)) {
15249 	case BPF_EXIT:
15250 		return DONE_EXPLORING;
15251 
15252 	case BPF_CALL:
15253 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15254 			/* Mark this call insn as a prune point to trigger
15255 			 * is_state_visited() check before call itself is
15256 			 * processed by __check_func_call(). Otherwise new
15257 			 * async state will be pushed for further exploration.
15258 			 */
15259 			mark_prune_point(env, t);
15260 		/* For functions that invoke callbacks it is not known how many times
15261 		 * callback would be called. Verifier models callback calling functions
15262 		 * by repeatedly visiting callback bodies and returning to origin call
15263 		 * instruction.
15264 		 * In order to stop such iteration verifier needs to identify when a
15265 		 * state identical some state from a previous iteration is reached.
15266 		 * Check below forces creation of checkpoint before callback calling
15267 		 * instruction to allow search for such identical states.
15268 		 */
15269 		if (is_sync_callback_calling_insn(insn)) {
15270 			mark_calls_callback(env, t);
15271 			mark_force_checkpoint(env, t);
15272 			mark_prune_point(env, t);
15273 			mark_jmp_point(env, t);
15274 		}
15275 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15276 			struct bpf_kfunc_call_arg_meta meta;
15277 
15278 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15279 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15280 				mark_prune_point(env, t);
15281 				/* Checking and saving state checkpoints at iter_next() call
15282 				 * is crucial for fast convergence of open-coded iterator loop
15283 				 * logic, so we need to force it. If we don't do that,
15284 				 * is_state_visited() might skip saving a checkpoint, causing
15285 				 * unnecessarily long sequence of not checkpointed
15286 				 * instructions and jumps, leading to exhaustion of jump
15287 				 * history buffer, and potentially other undesired outcomes.
15288 				 * It is expected that with correct open-coded iterators
15289 				 * convergence will happen quickly, so we don't run a risk of
15290 				 * exhausting memory.
15291 				 */
15292 				mark_force_checkpoint(env, t);
15293 			}
15294 		}
15295 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15296 
15297 	case BPF_JA:
15298 		if (BPF_SRC(insn->code) != BPF_K)
15299 			return -EINVAL;
15300 
15301 		if (BPF_CLASS(insn->code) == BPF_JMP)
15302 			off = insn->off;
15303 		else
15304 			off = insn->imm;
15305 
15306 		/* unconditional jump with single edge */
15307 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15308 		if (ret)
15309 			return ret;
15310 
15311 		mark_prune_point(env, t + off + 1);
15312 		mark_jmp_point(env, t + off + 1);
15313 
15314 		return ret;
15315 
15316 	default:
15317 		/* conditional jump with two edges */
15318 		mark_prune_point(env, t);
15319 
15320 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15321 		if (ret)
15322 			return ret;
15323 
15324 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15325 	}
15326 }
15327 
15328 /* non-recursive depth-first-search to detect loops in BPF program
15329  * loop == back-edge in directed graph
15330  */
15331 static int check_cfg(struct bpf_verifier_env *env)
15332 {
15333 	int insn_cnt = env->prog->len;
15334 	int *insn_stack, *insn_state;
15335 	int ret = 0;
15336 	int i;
15337 
15338 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15339 	if (!insn_state)
15340 		return -ENOMEM;
15341 
15342 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15343 	if (!insn_stack) {
15344 		kvfree(insn_state);
15345 		return -ENOMEM;
15346 	}
15347 
15348 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15349 	insn_stack[0] = 0; /* 0 is the first instruction */
15350 	env->cfg.cur_stack = 1;
15351 
15352 	while (env->cfg.cur_stack > 0) {
15353 		int t = insn_stack[env->cfg.cur_stack - 1];
15354 
15355 		ret = visit_insn(t, env);
15356 		switch (ret) {
15357 		case DONE_EXPLORING:
15358 			insn_state[t] = EXPLORED;
15359 			env->cfg.cur_stack--;
15360 			break;
15361 		case KEEP_EXPLORING:
15362 			break;
15363 		default:
15364 			if (ret > 0) {
15365 				verbose(env, "visit_insn internal bug\n");
15366 				ret = -EFAULT;
15367 			}
15368 			goto err_free;
15369 		}
15370 	}
15371 
15372 	if (env->cfg.cur_stack < 0) {
15373 		verbose(env, "pop stack internal bug\n");
15374 		ret = -EFAULT;
15375 		goto err_free;
15376 	}
15377 
15378 	for (i = 0; i < insn_cnt; i++) {
15379 		struct bpf_insn *insn = &env->prog->insnsi[i];
15380 
15381 		if (insn_state[i] != EXPLORED) {
15382 			verbose(env, "unreachable insn %d\n", i);
15383 			ret = -EINVAL;
15384 			goto err_free;
15385 		}
15386 		if (bpf_is_ldimm64(insn)) {
15387 			if (insn_state[i + 1] != 0) {
15388 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15389 				ret = -EINVAL;
15390 				goto err_free;
15391 			}
15392 			i++; /* skip second half of ldimm64 */
15393 		}
15394 	}
15395 	ret = 0; /* cfg looks good */
15396 
15397 err_free:
15398 	kvfree(insn_state);
15399 	kvfree(insn_stack);
15400 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15401 	return ret;
15402 }
15403 
15404 static int check_abnormal_return(struct bpf_verifier_env *env)
15405 {
15406 	int i;
15407 
15408 	for (i = 1; i < env->subprog_cnt; i++) {
15409 		if (env->subprog_info[i].has_ld_abs) {
15410 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15411 			return -EINVAL;
15412 		}
15413 		if (env->subprog_info[i].has_tail_call) {
15414 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15415 			return -EINVAL;
15416 		}
15417 	}
15418 	return 0;
15419 }
15420 
15421 /* The minimum supported BTF func info size */
15422 #define MIN_BPF_FUNCINFO_SIZE	8
15423 #define MAX_FUNCINFO_REC_SIZE	252
15424 
15425 static int check_btf_func(struct bpf_verifier_env *env,
15426 			  const union bpf_attr *attr,
15427 			  bpfptr_t uattr)
15428 {
15429 	const struct btf_type *type, *func_proto, *ret_type;
15430 	u32 i, nfuncs, urec_size, min_size;
15431 	u32 krec_size = sizeof(struct bpf_func_info);
15432 	struct bpf_func_info *krecord;
15433 	struct bpf_func_info_aux *info_aux = NULL;
15434 	struct bpf_prog *prog;
15435 	const struct btf *btf;
15436 	bpfptr_t urecord;
15437 	u32 prev_offset = 0;
15438 	bool scalar_return;
15439 	int ret = -ENOMEM;
15440 
15441 	nfuncs = attr->func_info_cnt;
15442 	if (!nfuncs) {
15443 		if (check_abnormal_return(env))
15444 			return -EINVAL;
15445 		return 0;
15446 	}
15447 
15448 	if (nfuncs != env->subprog_cnt) {
15449 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15450 		return -EINVAL;
15451 	}
15452 
15453 	urec_size = attr->func_info_rec_size;
15454 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15455 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15456 	    urec_size % sizeof(u32)) {
15457 		verbose(env, "invalid func info rec size %u\n", urec_size);
15458 		return -EINVAL;
15459 	}
15460 
15461 	prog = env->prog;
15462 	btf = prog->aux->btf;
15463 
15464 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15465 	min_size = min_t(u32, krec_size, urec_size);
15466 
15467 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15468 	if (!krecord)
15469 		return -ENOMEM;
15470 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15471 	if (!info_aux)
15472 		goto err_free;
15473 
15474 	for (i = 0; i < nfuncs; i++) {
15475 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15476 		if (ret) {
15477 			if (ret == -E2BIG) {
15478 				verbose(env, "nonzero tailing record in func info");
15479 				/* set the size kernel expects so loader can zero
15480 				 * out the rest of the record.
15481 				 */
15482 				if (copy_to_bpfptr_offset(uattr,
15483 							  offsetof(union bpf_attr, func_info_rec_size),
15484 							  &min_size, sizeof(min_size)))
15485 					ret = -EFAULT;
15486 			}
15487 			goto err_free;
15488 		}
15489 
15490 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15491 			ret = -EFAULT;
15492 			goto err_free;
15493 		}
15494 
15495 		/* check insn_off */
15496 		ret = -EINVAL;
15497 		if (i == 0) {
15498 			if (krecord[i].insn_off) {
15499 				verbose(env,
15500 					"nonzero insn_off %u for the first func info record",
15501 					krecord[i].insn_off);
15502 				goto err_free;
15503 			}
15504 		} else if (krecord[i].insn_off <= prev_offset) {
15505 			verbose(env,
15506 				"same or smaller insn offset (%u) than previous func info record (%u)",
15507 				krecord[i].insn_off, prev_offset);
15508 			goto err_free;
15509 		}
15510 
15511 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15512 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15513 			goto err_free;
15514 		}
15515 
15516 		/* check type_id */
15517 		type = btf_type_by_id(btf, krecord[i].type_id);
15518 		if (!type || !btf_type_is_func(type)) {
15519 			verbose(env, "invalid type id %d in func info",
15520 				krecord[i].type_id);
15521 			goto err_free;
15522 		}
15523 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15524 
15525 		func_proto = btf_type_by_id(btf, type->type);
15526 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15527 			/* btf_func_check() already verified it during BTF load */
15528 			goto err_free;
15529 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15530 		scalar_return =
15531 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15532 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15533 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15534 			goto err_free;
15535 		}
15536 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15537 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15538 			goto err_free;
15539 		}
15540 
15541 		prev_offset = krecord[i].insn_off;
15542 		bpfptr_add(&urecord, urec_size);
15543 	}
15544 
15545 	prog->aux->func_info = krecord;
15546 	prog->aux->func_info_cnt = nfuncs;
15547 	prog->aux->func_info_aux = info_aux;
15548 	return 0;
15549 
15550 err_free:
15551 	kvfree(krecord);
15552 	kfree(info_aux);
15553 	return ret;
15554 }
15555 
15556 static void adjust_btf_func(struct bpf_verifier_env *env)
15557 {
15558 	struct bpf_prog_aux *aux = env->prog->aux;
15559 	int i;
15560 
15561 	if (!aux->func_info)
15562 		return;
15563 
15564 	for (i = 0; i < env->subprog_cnt; i++)
15565 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15566 }
15567 
15568 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15569 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15570 
15571 static int check_btf_line(struct bpf_verifier_env *env,
15572 			  const union bpf_attr *attr,
15573 			  bpfptr_t uattr)
15574 {
15575 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15576 	struct bpf_subprog_info *sub;
15577 	struct bpf_line_info *linfo;
15578 	struct bpf_prog *prog;
15579 	const struct btf *btf;
15580 	bpfptr_t ulinfo;
15581 	int err;
15582 
15583 	nr_linfo = attr->line_info_cnt;
15584 	if (!nr_linfo)
15585 		return 0;
15586 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15587 		return -EINVAL;
15588 
15589 	rec_size = attr->line_info_rec_size;
15590 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15591 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15592 	    rec_size & (sizeof(u32) - 1))
15593 		return -EINVAL;
15594 
15595 	/* Need to zero it in case the userspace may
15596 	 * pass in a smaller bpf_line_info object.
15597 	 */
15598 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15599 			 GFP_KERNEL | __GFP_NOWARN);
15600 	if (!linfo)
15601 		return -ENOMEM;
15602 
15603 	prog = env->prog;
15604 	btf = prog->aux->btf;
15605 
15606 	s = 0;
15607 	sub = env->subprog_info;
15608 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15609 	expected_size = sizeof(struct bpf_line_info);
15610 	ncopy = min_t(u32, expected_size, rec_size);
15611 	for (i = 0; i < nr_linfo; i++) {
15612 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15613 		if (err) {
15614 			if (err == -E2BIG) {
15615 				verbose(env, "nonzero tailing record in line_info");
15616 				if (copy_to_bpfptr_offset(uattr,
15617 							  offsetof(union bpf_attr, line_info_rec_size),
15618 							  &expected_size, sizeof(expected_size)))
15619 					err = -EFAULT;
15620 			}
15621 			goto err_free;
15622 		}
15623 
15624 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15625 			err = -EFAULT;
15626 			goto err_free;
15627 		}
15628 
15629 		/*
15630 		 * Check insn_off to ensure
15631 		 * 1) strictly increasing AND
15632 		 * 2) bounded by prog->len
15633 		 *
15634 		 * The linfo[0].insn_off == 0 check logically falls into
15635 		 * the later "missing bpf_line_info for func..." case
15636 		 * because the first linfo[0].insn_off must be the
15637 		 * first sub also and the first sub must have
15638 		 * subprog_info[0].start == 0.
15639 		 */
15640 		if ((i && linfo[i].insn_off <= prev_offset) ||
15641 		    linfo[i].insn_off >= prog->len) {
15642 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15643 				i, linfo[i].insn_off, prev_offset,
15644 				prog->len);
15645 			err = -EINVAL;
15646 			goto err_free;
15647 		}
15648 
15649 		if (!prog->insnsi[linfo[i].insn_off].code) {
15650 			verbose(env,
15651 				"Invalid insn code at line_info[%u].insn_off\n",
15652 				i);
15653 			err = -EINVAL;
15654 			goto err_free;
15655 		}
15656 
15657 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15658 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15659 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15660 			err = -EINVAL;
15661 			goto err_free;
15662 		}
15663 
15664 		if (s != env->subprog_cnt) {
15665 			if (linfo[i].insn_off == sub[s].start) {
15666 				sub[s].linfo_idx = i;
15667 				s++;
15668 			} else if (sub[s].start < linfo[i].insn_off) {
15669 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15670 				err = -EINVAL;
15671 				goto err_free;
15672 			}
15673 		}
15674 
15675 		prev_offset = linfo[i].insn_off;
15676 		bpfptr_add(&ulinfo, rec_size);
15677 	}
15678 
15679 	if (s != env->subprog_cnt) {
15680 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15681 			env->subprog_cnt - s, s);
15682 		err = -EINVAL;
15683 		goto err_free;
15684 	}
15685 
15686 	prog->aux->linfo = linfo;
15687 	prog->aux->nr_linfo = nr_linfo;
15688 
15689 	return 0;
15690 
15691 err_free:
15692 	kvfree(linfo);
15693 	return err;
15694 }
15695 
15696 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15697 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15698 
15699 static int check_core_relo(struct bpf_verifier_env *env,
15700 			   const union bpf_attr *attr,
15701 			   bpfptr_t uattr)
15702 {
15703 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15704 	struct bpf_core_relo core_relo = {};
15705 	struct bpf_prog *prog = env->prog;
15706 	const struct btf *btf = prog->aux->btf;
15707 	struct bpf_core_ctx ctx = {
15708 		.log = &env->log,
15709 		.btf = btf,
15710 	};
15711 	bpfptr_t u_core_relo;
15712 	int err;
15713 
15714 	nr_core_relo = attr->core_relo_cnt;
15715 	if (!nr_core_relo)
15716 		return 0;
15717 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15718 		return -EINVAL;
15719 
15720 	rec_size = attr->core_relo_rec_size;
15721 	if (rec_size < MIN_CORE_RELO_SIZE ||
15722 	    rec_size > MAX_CORE_RELO_SIZE ||
15723 	    rec_size % sizeof(u32))
15724 		return -EINVAL;
15725 
15726 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15727 	expected_size = sizeof(struct bpf_core_relo);
15728 	ncopy = min_t(u32, expected_size, rec_size);
15729 
15730 	/* Unlike func_info and line_info, copy and apply each CO-RE
15731 	 * relocation record one at a time.
15732 	 */
15733 	for (i = 0; i < nr_core_relo; i++) {
15734 		/* future proofing when sizeof(bpf_core_relo) changes */
15735 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15736 		if (err) {
15737 			if (err == -E2BIG) {
15738 				verbose(env, "nonzero tailing record in core_relo");
15739 				if (copy_to_bpfptr_offset(uattr,
15740 							  offsetof(union bpf_attr, core_relo_rec_size),
15741 							  &expected_size, sizeof(expected_size)))
15742 					err = -EFAULT;
15743 			}
15744 			break;
15745 		}
15746 
15747 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15748 			err = -EFAULT;
15749 			break;
15750 		}
15751 
15752 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15753 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15754 				i, core_relo.insn_off, prog->len);
15755 			err = -EINVAL;
15756 			break;
15757 		}
15758 
15759 		err = bpf_core_apply(&ctx, &core_relo, i,
15760 				     &prog->insnsi[core_relo.insn_off / 8]);
15761 		if (err)
15762 			break;
15763 		bpfptr_add(&u_core_relo, rec_size);
15764 	}
15765 	return err;
15766 }
15767 
15768 static int check_btf_info(struct bpf_verifier_env *env,
15769 			  const union bpf_attr *attr,
15770 			  bpfptr_t uattr)
15771 {
15772 	struct btf *btf;
15773 	int err;
15774 
15775 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15776 		if (check_abnormal_return(env))
15777 			return -EINVAL;
15778 		return 0;
15779 	}
15780 
15781 	btf = btf_get_by_fd(attr->prog_btf_fd);
15782 	if (IS_ERR(btf))
15783 		return PTR_ERR(btf);
15784 	if (btf_is_kernel(btf)) {
15785 		btf_put(btf);
15786 		return -EACCES;
15787 	}
15788 	env->prog->aux->btf = btf;
15789 
15790 	err = check_btf_func(env, attr, uattr);
15791 	if (err)
15792 		return err;
15793 
15794 	err = check_btf_line(env, attr, uattr);
15795 	if (err)
15796 		return err;
15797 
15798 	err = check_core_relo(env, attr, uattr);
15799 	if (err)
15800 		return err;
15801 
15802 	return 0;
15803 }
15804 
15805 /* check %cur's range satisfies %old's */
15806 static bool range_within(struct bpf_reg_state *old,
15807 			 struct bpf_reg_state *cur)
15808 {
15809 	return old->umin_value <= cur->umin_value &&
15810 	       old->umax_value >= cur->umax_value &&
15811 	       old->smin_value <= cur->smin_value &&
15812 	       old->smax_value >= cur->smax_value &&
15813 	       old->u32_min_value <= cur->u32_min_value &&
15814 	       old->u32_max_value >= cur->u32_max_value &&
15815 	       old->s32_min_value <= cur->s32_min_value &&
15816 	       old->s32_max_value >= cur->s32_max_value;
15817 }
15818 
15819 /* If in the old state two registers had the same id, then they need to have
15820  * the same id in the new state as well.  But that id could be different from
15821  * the old state, so we need to track the mapping from old to new ids.
15822  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15823  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15824  * regs with a different old id could still have new id 9, we don't care about
15825  * that.
15826  * So we look through our idmap to see if this old id has been seen before.  If
15827  * so, we require the new id to match; otherwise, we add the id pair to the map.
15828  */
15829 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15830 {
15831 	struct bpf_id_pair *map = idmap->map;
15832 	unsigned int i;
15833 
15834 	/* either both IDs should be set or both should be zero */
15835 	if (!!old_id != !!cur_id)
15836 		return false;
15837 
15838 	if (old_id == 0) /* cur_id == 0 as well */
15839 		return true;
15840 
15841 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15842 		if (!map[i].old) {
15843 			/* Reached an empty slot; haven't seen this id before */
15844 			map[i].old = old_id;
15845 			map[i].cur = cur_id;
15846 			return true;
15847 		}
15848 		if (map[i].old == old_id)
15849 			return map[i].cur == cur_id;
15850 		if (map[i].cur == cur_id)
15851 			return false;
15852 	}
15853 	/* We ran out of idmap slots, which should be impossible */
15854 	WARN_ON_ONCE(1);
15855 	return false;
15856 }
15857 
15858 /* Similar to check_ids(), but allocate a unique temporary ID
15859  * for 'old_id' or 'cur_id' of zero.
15860  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15861  */
15862 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15863 {
15864 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15865 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15866 
15867 	return check_ids(old_id, cur_id, idmap);
15868 }
15869 
15870 static void clean_func_state(struct bpf_verifier_env *env,
15871 			     struct bpf_func_state *st)
15872 {
15873 	enum bpf_reg_liveness live;
15874 	int i, j;
15875 
15876 	for (i = 0; i < BPF_REG_FP; i++) {
15877 		live = st->regs[i].live;
15878 		/* liveness must not touch this register anymore */
15879 		st->regs[i].live |= REG_LIVE_DONE;
15880 		if (!(live & REG_LIVE_READ))
15881 			/* since the register is unused, clear its state
15882 			 * to make further comparison simpler
15883 			 */
15884 			__mark_reg_not_init(env, &st->regs[i]);
15885 	}
15886 
15887 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15888 		live = st->stack[i].spilled_ptr.live;
15889 		/* liveness must not touch this stack slot anymore */
15890 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15891 		if (!(live & REG_LIVE_READ)) {
15892 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15893 			for (j = 0; j < BPF_REG_SIZE; j++)
15894 				st->stack[i].slot_type[j] = STACK_INVALID;
15895 		}
15896 	}
15897 }
15898 
15899 static void clean_verifier_state(struct bpf_verifier_env *env,
15900 				 struct bpf_verifier_state *st)
15901 {
15902 	int i;
15903 
15904 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15905 		/* all regs in this state in all frames were already marked */
15906 		return;
15907 
15908 	for (i = 0; i <= st->curframe; i++)
15909 		clean_func_state(env, st->frame[i]);
15910 }
15911 
15912 /* the parentage chains form a tree.
15913  * the verifier states are added to state lists at given insn and
15914  * pushed into state stack for future exploration.
15915  * when the verifier reaches bpf_exit insn some of the verifer states
15916  * stored in the state lists have their final liveness state already,
15917  * but a lot of states will get revised from liveness point of view when
15918  * the verifier explores other branches.
15919  * Example:
15920  * 1: r0 = 1
15921  * 2: if r1 == 100 goto pc+1
15922  * 3: r0 = 2
15923  * 4: exit
15924  * when the verifier reaches exit insn the register r0 in the state list of
15925  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15926  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15927  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15928  *
15929  * Since the verifier pushes the branch states as it sees them while exploring
15930  * the program the condition of walking the branch instruction for the second
15931  * time means that all states below this branch were already explored and
15932  * their final liveness marks are already propagated.
15933  * Hence when the verifier completes the search of state list in is_state_visited()
15934  * we can call this clean_live_states() function to mark all liveness states
15935  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15936  * will not be used.
15937  * This function also clears the registers and stack for states that !READ
15938  * to simplify state merging.
15939  *
15940  * Important note here that walking the same branch instruction in the callee
15941  * doesn't meant that the states are DONE. The verifier has to compare
15942  * the callsites
15943  */
15944 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15945 			      struct bpf_verifier_state *cur)
15946 {
15947 	struct bpf_verifier_state_list *sl;
15948 
15949 	sl = *explored_state(env, insn);
15950 	while (sl) {
15951 		if (sl->state.branches)
15952 			goto next;
15953 		if (sl->state.insn_idx != insn ||
15954 		    !same_callsites(&sl->state, cur))
15955 			goto next;
15956 		clean_verifier_state(env, &sl->state);
15957 next:
15958 		sl = sl->next;
15959 	}
15960 }
15961 
15962 static bool regs_exact(const struct bpf_reg_state *rold,
15963 		       const struct bpf_reg_state *rcur,
15964 		       struct bpf_idmap *idmap)
15965 {
15966 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15967 	       check_ids(rold->id, rcur->id, idmap) &&
15968 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15969 }
15970 
15971 /* Returns true if (rold safe implies rcur safe) */
15972 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15973 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15974 {
15975 	if (exact)
15976 		return regs_exact(rold, rcur, idmap);
15977 
15978 	if (!(rold->live & REG_LIVE_READ))
15979 		/* explored state didn't use this */
15980 		return true;
15981 	if (rold->type == NOT_INIT)
15982 		/* explored state can't have used this */
15983 		return true;
15984 	if (rcur->type == NOT_INIT)
15985 		return false;
15986 
15987 	/* Enforce that register types have to match exactly, including their
15988 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15989 	 * rule.
15990 	 *
15991 	 * One can make a point that using a pointer register as unbounded
15992 	 * SCALAR would be technically acceptable, but this could lead to
15993 	 * pointer leaks because scalars are allowed to leak while pointers
15994 	 * are not. We could make this safe in special cases if root is
15995 	 * calling us, but it's probably not worth the hassle.
15996 	 *
15997 	 * Also, register types that are *not* MAYBE_NULL could technically be
15998 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15999 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16000 	 * to the same map).
16001 	 * However, if the old MAYBE_NULL register then got NULL checked,
16002 	 * doing so could have affected others with the same id, and we can't
16003 	 * check for that because we lost the id when we converted to
16004 	 * a non-MAYBE_NULL variant.
16005 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16006 	 * non-MAYBE_NULL registers as well.
16007 	 */
16008 	if (rold->type != rcur->type)
16009 		return false;
16010 
16011 	switch (base_type(rold->type)) {
16012 	case SCALAR_VALUE:
16013 		if (env->explore_alu_limits) {
16014 			/* explore_alu_limits disables tnum_in() and range_within()
16015 			 * logic and requires everything to be strict
16016 			 */
16017 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16018 			       check_scalar_ids(rold->id, rcur->id, idmap);
16019 		}
16020 		if (!rold->precise)
16021 			return true;
16022 		/* Why check_ids() for scalar registers?
16023 		 *
16024 		 * Consider the following BPF code:
16025 		 *   1: r6 = ... unbound scalar, ID=a ...
16026 		 *   2: r7 = ... unbound scalar, ID=b ...
16027 		 *   3: if (r6 > r7) goto +1
16028 		 *   4: r6 = r7
16029 		 *   5: if (r6 > X) goto ...
16030 		 *   6: ... memory operation using r7 ...
16031 		 *
16032 		 * First verification path is [1-6]:
16033 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16034 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16035 		 *   r7 <= X, because r6 and r7 share same id.
16036 		 * Next verification path is [1-4, 6].
16037 		 *
16038 		 * Instruction (6) would be reached in two states:
16039 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16040 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16041 		 *
16042 		 * Use check_ids() to distinguish these states.
16043 		 * ---
16044 		 * Also verify that new value satisfies old value range knowledge.
16045 		 */
16046 		return range_within(rold, rcur) &&
16047 		       tnum_in(rold->var_off, rcur->var_off) &&
16048 		       check_scalar_ids(rold->id, rcur->id, idmap);
16049 	case PTR_TO_MAP_KEY:
16050 	case PTR_TO_MAP_VALUE:
16051 	case PTR_TO_MEM:
16052 	case PTR_TO_BUF:
16053 	case PTR_TO_TP_BUFFER:
16054 		/* If the new min/max/var_off satisfy the old ones and
16055 		 * everything else matches, we are OK.
16056 		 */
16057 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16058 		       range_within(rold, rcur) &&
16059 		       tnum_in(rold->var_off, rcur->var_off) &&
16060 		       check_ids(rold->id, rcur->id, idmap) &&
16061 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16062 	case PTR_TO_PACKET_META:
16063 	case PTR_TO_PACKET:
16064 		/* We must have at least as much range as the old ptr
16065 		 * did, so that any accesses which were safe before are
16066 		 * still safe.  This is true even if old range < old off,
16067 		 * since someone could have accessed through (ptr - k), or
16068 		 * even done ptr -= k in a register, to get a safe access.
16069 		 */
16070 		if (rold->range > rcur->range)
16071 			return false;
16072 		/* If the offsets don't match, we can't trust our alignment;
16073 		 * nor can we be sure that we won't fall out of range.
16074 		 */
16075 		if (rold->off != rcur->off)
16076 			return false;
16077 		/* id relations must be preserved */
16078 		if (!check_ids(rold->id, rcur->id, idmap))
16079 			return false;
16080 		/* new val must satisfy old val knowledge */
16081 		return range_within(rold, rcur) &&
16082 		       tnum_in(rold->var_off, rcur->var_off);
16083 	case PTR_TO_STACK:
16084 		/* two stack pointers are equal only if they're pointing to
16085 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16086 		 */
16087 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16088 	default:
16089 		return regs_exact(rold, rcur, idmap);
16090 	}
16091 }
16092 
16093 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16094 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16095 {
16096 	int i, spi;
16097 
16098 	/* walk slots of the explored stack and ignore any additional
16099 	 * slots in the current stack, since explored(safe) state
16100 	 * didn't use them
16101 	 */
16102 	for (i = 0; i < old->allocated_stack; i++) {
16103 		struct bpf_reg_state *old_reg, *cur_reg;
16104 
16105 		spi = i / BPF_REG_SIZE;
16106 
16107 		if (exact &&
16108 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16109 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16110 			return false;
16111 
16112 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16113 			i += BPF_REG_SIZE - 1;
16114 			/* explored state didn't use this */
16115 			continue;
16116 		}
16117 
16118 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16119 			continue;
16120 
16121 		if (env->allow_uninit_stack &&
16122 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16123 			continue;
16124 
16125 		/* explored stack has more populated slots than current stack
16126 		 * and these slots were used
16127 		 */
16128 		if (i >= cur->allocated_stack)
16129 			return false;
16130 
16131 		/* if old state was safe with misc data in the stack
16132 		 * it will be safe with zero-initialized stack.
16133 		 * The opposite is not true
16134 		 */
16135 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16136 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16137 			continue;
16138 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16139 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16140 			/* Ex: old explored (safe) state has STACK_SPILL in
16141 			 * this stack slot, but current has STACK_MISC ->
16142 			 * this verifier states are not equivalent,
16143 			 * return false to continue verification of this path
16144 			 */
16145 			return false;
16146 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16147 			continue;
16148 		/* Both old and cur are having same slot_type */
16149 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16150 		case STACK_SPILL:
16151 			/* when explored and current stack slot are both storing
16152 			 * spilled registers, check that stored pointers types
16153 			 * are the same as well.
16154 			 * Ex: explored safe path could have stored
16155 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16156 			 * but current path has stored:
16157 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16158 			 * such verifier states are not equivalent.
16159 			 * return false to continue verification of this path
16160 			 */
16161 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16162 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16163 				return false;
16164 			break;
16165 		case STACK_DYNPTR:
16166 			old_reg = &old->stack[spi].spilled_ptr;
16167 			cur_reg = &cur->stack[spi].spilled_ptr;
16168 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16169 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16170 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16171 				return false;
16172 			break;
16173 		case STACK_ITER:
16174 			old_reg = &old->stack[spi].spilled_ptr;
16175 			cur_reg = &cur->stack[spi].spilled_ptr;
16176 			/* iter.depth is not compared between states as it
16177 			 * doesn't matter for correctness and would otherwise
16178 			 * prevent convergence; we maintain it only to prevent
16179 			 * infinite loop check triggering, see
16180 			 * iter_active_depths_differ()
16181 			 */
16182 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16183 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16184 			    old_reg->iter.state != cur_reg->iter.state ||
16185 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16186 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16187 				return false;
16188 			break;
16189 		case STACK_MISC:
16190 		case STACK_ZERO:
16191 		case STACK_INVALID:
16192 			continue;
16193 		/* Ensure that new unhandled slot types return false by default */
16194 		default:
16195 			return false;
16196 		}
16197 	}
16198 	return true;
16199 }
16200 
16201 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16202 		    struct bpf_idmap *idmap)
16203 {
16204 	int i;
16205 
16206 	if (old->acquired_refs != cur->acquired_refs)
16207 		return false;
16208 
16209 	for (i = 0; i < old->acquired_refs; i++) {
16210 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16211 			return false;
16212 	}
16213 
16214 	return true;
16215 }
16216 
16217 /* compare two verifier states
16218  *
16219  * all states stored in state_list are known to be valid, since
16220  * verifier reached 'bpf_exit' instruction through them
16221  *
16222  * this function is called when verifier exploring different branches of
16223  * execution popped from the state stack. If it sees an old state that has
16224  * more strict register state and more strict stack state then this execution
16225  * branch doesn't need to be explored further, since verifier already
16226  * concluded that more strict state leads to valid finish.
16227  *
16228  * Therefore two states are equivalent if register state is more conservative
16229  * and explored stack state is more conservative than the current one.
16230  * Example:
16231  *       explored                   current
16232  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16233  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16234  *
16235  * In other words if current stack state (one being explored) has more
16236  * valid slots than old one that already passed validation, it means
16237  * the verifier can stop exploring and conclude that current state is valid too
16238  *
16239  * Similarly with registers. If explored state has register type as invalid
16240  * whereas register type in current state is meaningful, it means that
16241  * the current state will reach 'bpf_exit' instruction safely
16242  */
16243 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16244 			      struct bpf_func_state *cur, bool exact)
16245 {
16246 	int i;
16247 
16248 	if (old->callback_depth > cur->callback_depth)
16249 		return false;
16250 
16251 	for (i = 0; i < MAX_BPF_REG; i++)
16252 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16253 			     &env->idmap_scratch, exact))
16254 			return false;
16255 
16256 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16257 		return false;
16258 
16259 	if (!refsafe(old, cur, &env->idmap_scratch))
16260 		return false;
16261 
16262 	return true;
16263 }
16264 
16265 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16266 {
16267 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16268 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16269 }
16270 
16271 static bool states_equal(struct bpf_verifier_env *env,
16272 			 struct bpf_verifier_state *old,
16273 			 struct bpf_verifier_state *cur,
16274 			 bool exact)
16275 {
16276 	int i;
16277 
16278 	if (old->curframe != cur->curframe)
16279 		return false;
16280 
16281 	reset_idmap_scratch(env);
16282 
16283 	/* Verification state from speculative execution simulation
16284 	 * must never prune a non-speculative execution one.
16285 	 */
16286 	if (old->speculative && !cur->speculative)
16287 		return false;
16288 
16289 	if (old->active_lock.ptr != cur->active_lock.ptr)
16290 		return false;
16291 
16292 	/* Old and cur active_lock's have to be either both present
16293 	 * or both absent.
16294 	 */
16295 	if (!!old->active_lock.id != !!cur->active_lock.id)
16296 		return false;
16297 
16298 	if (old->active_lock.id &&
16299 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16300 		return false;
16301 
16302 	if (old->active_rcu_lock != cur->active_rcu_lock)
16303 		return false;
16304 
16305 	/* for states to be equal callsites have to be the same
16306 	 * and all frame states need to be equivalent
16307 	 */
16308 	for (i = 0; i <= old->curframe; i++) {
16309 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16310 			return false;
16311 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16312 			return false;
16313 	}
16314 	return true;
16315 }
16316 
16317 /* Return 0 if no propagation happened. Return negative error code if error
16318  * happened. Otherwise, return the propagated bit.
16319  */
16320 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16321 				  struct bpf_reg_state *reg,
16322 				  struct bpf_reg_state *parent_reg)
16323 {
16324 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16325 	u8 flag = reg->live & REG_LIVE_READ;
16326 	int err;
16327 
16328 	/* When comes here, read flags of PARENT_REG or REG could be any of
16329 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16330 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16331 	 */
16332 	if (parent_flag == REG_LIVE_READ64 ||
16333 	    /* Or if there is no read flag from REG. */
16334 	    !flag ||
16335 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16336 	    parent_flag == flag)
16337 		return 0;
16338 
16339 	err = mark_reg_read(env, reg, parent_reg, flag);
16340 	if (err)
16341 		return err;
16342 
16343 	return flag;
16344 }
16345 
16346 /* A write screens off any subsequent reads; but write marks come from the
16347  * straight-line code between a state and its parent.  When we arrive at an
16348  * equivalent state (jump target or such) we didn't arrive by the straight-line
16349  * code, so read marks in the state must propagate to the parent regardless
16350  * of the state's write marks. That's what 'parent == state->parent' comparison
16351  * in mark_reg_read() is for.
16352  */
16353 static int propagate_liveness(struct bpf_verifier_env *env,
16354 			      const struct bpf_verifier_state *vstate,
16355 			      struct bpf_verifier_state *vparent)
16356 {
16357 	struct bpf_reg_state *state_reg, *parent_reg;
16358 	struct bpf_func_state *state, *parent;
16359 	int i, frame, err = 0;
16360 
16361 	if (vparent->curframe != vstate->curframe) {
16362 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16363 		     vparent->curframe, vstate->curframe);
16364 		return -EFAULT;
16365 	}
16366 	/* Propagate read liveness of registers... */
16367 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16368 	for (frame = 0; frame <= vstate->curframe; frame++) {
16369 		parent = vparent->frame[frame];
16370 		state = vstate->frame[frame];
16371 		parent_reg = parent->regs;
16372 		state_reg = state->regs;
16373 		/* We don't need to worry about FP liveness, it's read-only */
16374 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16375 			err = propagate_liveness_reg(env, &state_reg[i],
16376 						     &parent_reg[i]);
16377 			if (err < 0)
16378 				return err;
16379 			if (err == REG_LIVE_READ64)
16380 				mark_insn_zext(env, &parent_reg[i]);
16381 		}
16382 
16383 		/* Propagate stack slots. */
16384 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16385 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16386 			parent_reg = &parent->stack[i].spilled_ptr;
16387 			state_reg = &state->stack[i].spilled_ptr;
16388 			err = propagate_liveness_reg(env, state_reg,
16389 						     parent_reg);
16390 			if (err < 0)
16391 				return err;
16392 		}
16393 	}
16394 	return 0;
16395 }
16396 
16397 /* find precise scalars in the previous equivalent state and
16398  * propagate them into the current state
16399  */
16400 static int propagate_precision(struct bpf_verifier_env *env,
16401 			       const struct bpf_verifier_state *old)
16402 {
16403 	struct bpf_reg_state *state_reg;
16404 	struct bpf_func_state *state;
16405 	int i, err = 0, fr;
16406 	bool first;
16407 
16408 	for (fr = old->curframe; fr >= 0; fr--) {
16409 		state = old->frame[fr];
16410 		state_reg = state->regs;
16411 		first = true;
16412 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16413 			if (state_reg->type != SCALAR_VALUE ||
16414 			    !state_reg->precise ||
16415 			    !(state_reg->live & REG_LIVE_READ))
16416 				continue;
16417 			if (env->log.level & BPF_LOG_LEVEL2) {
16418 				if (first)
16419 					verbose(env, "frame %d: propagating r%d", fr, i);
16420 				else
16421 					verbose(env, ",r%d", i);
16422 			}
16423 			bt_set_frame_reg(&env->bt, fr, i);
16424 			first = false;
16425 		}
16426 
16427 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16428 			if (!is_spilled_reg(&state->stack[i]))
16429 				continue;
16430 			state_reg = &state->stack[i].spilled_ptr;
16431 			if (state_reg->type != SCALAR_VALUE ||
16432 			    !state_reg->precise ||
16433 			    !(state_reg->live & REG_LIVE_READ))
16434 				continue;
16435 			if (env->log.level & BPF_LOG_LEVEL2) {
16436 				if (first)
16437 					verbose(env, "frame %d: propagating fp%d",
16438 						fr, (-i - 1) * BPF_REG_SIZE);
16439 				else
16440 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16441 			}
16442 			bt_set_frame_slot(&env->bt, fr, i);
16443 			first = false;
16444 		}
16445 		if (!first)
16446 			verbose(env, "\n");
16447 	}
16448 
16449 	err = mark_chain_precision_batch(env);
16450 	if (err < 0)
16451 		return err;
16452 
16453 	return 0;
16454 }
16455 
16456 static bool states_maybe_looping(struct bpf_verifier_state *old,
16457 				 struct bpf_verifier_state *cur)
16458 {
16459 	struct bpf_func_state *fold, *fcur;
16460 	int i, fr = cur->curframe;
16461 
16462 	if (old->curframe != fr)
16463 		return false;
16464 
16465 	fold = old->frame[fr];
16466 	fcur = cur->frame[fr];
16467 	for (i = 0; i < MAX_BPF_REG; i++)
16468 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16469 			   offsetof(struct bpf_reg_state, parent)))
16470 			return false;
16471 	return true;
16472 }
16473 
16474 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16475 {
16476 	return env->insn_aux_data[insn_idx].is_iter_next;
16477 }
16478 
16479 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16480  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16481  * states to match, which otherwise would look like an infinite loop. So while
16482  * iter_next() calls are taken care of, we still need to be careful and
16483  * prevent erroneous and too eager declaration of "ininite loop", when
16484  * iterators are involved.
16485  *
16486  * Here's a situation in pseudo-BPF assembly form:
16487  *
16488  *   0: again:                          ; set up iter_next() call args
16489  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16490  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16491  *   3:   if r0 == 0 goto done
16492  *   4:   ... something useful here ...
16493  *   5:   goto again                    ; another iteration
16494  *   6: done:
16495  *   7:   r1 = &it
16496  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16497  *   9:   exit
16498  *
16499  * This is a typical loop. Let's assume that we have a prune point at 1:,
16500  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16501  * again`, assuming other heuristics don't get in a way).
16502  *
16503  * When we first time come to 1:, let's say we have some state X. We proceed
16504  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16505  * Now we come back to validate that forked ACTIVE state. We proceed through
16506  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16507  * are converging. But the problem is that we don't know that yet, as this
16508  * convergence has to happen at iter_next() call site only. So if nothing is
16509  * done, at 1: verifier will use bounded loop logic and declare infinite
16510  * looping (and would be *technically* correct, if not for iterator's
16511  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16512  * don't want that. So what we do in process_iter_next_call() when we go on
16513  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16514  * a different iteration. So when we suspect an infinite loop, we additionally
16515  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16516  * pretend we are not looping and wait for next iter_next() call.
16517  *
16518  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16519  * loop, because that would actually mean infinite loop, as DRAINED state is
16520  * "sticky", and so we'll keep returning into the same instruction with the
16521  * same state (at least in one of possible code paths).
16522  *
16523  * This approach allows to keep infinite loop heuristic even in the face of
16524  * active iterator. E.g., C snippet below is and will be detected as
16525  * inifintely looping:
16526  *
16527  *   struct bpf_iter_num it;
16528  *   int *p, x;
16529  *
16530  *   bpf_iter_num_new(&it, 0, 10);
16531  *   while ((p = bpf_iter_num_next(&t))) {
16532  *       x = p;
16533  *       while (x--) {} // <<-- infinite loop here
16534  *   }
16535  *
16536  */
16537 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16538 {
16539 	struct bpf_reg_state *slot, *cur_slot;
16540 	struct bpf_func_state *state;
16541 	int i, fr;
16542 
16543 	for (fr = old->curframe; fr >= 0; fr--) {
16544 		state = old->frame[fr];
16545 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16546 			if (state->stack[i].slot_type[0] != STACK_ITER)
16547 				continue;
16548 
16549 			slot = &state->stack[i].spilled_ptr;
16550 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16551 				continue;
16552 
16553 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16554 			if (cur_slot->iter.depth != slot->iter.depth)
16555 				return true;
16556 		}
16557 	}
16558 	return false;
16559 }
16560 
16561 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16562 {
16563 	struct bpf_verifier_state_list *new_sl;
16564 	struct bpf_verifier_state_list *sl, **pprev;
16565 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16566 	int i, j, n, err, states_cnt = 0;
16567 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16568 	bool add_new_state = force_new_state;
16569 	bool force_exact;
16570 
16571 	/* bpf progs typically have pruning point every 4 instructions
16572 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16573 	 * Do not add new state for future pruning if the verifier hasn't seen
16574 	 * at least 2 jumps and at least 8 instructions.
16575 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16576 	 * In tests that amounts to up to 50% reduction into total verifier
16577 	 * memory consumption and 20% verifier time speedup.
16578 	 */
16579 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16580 	    env->insn_processed - env->prev_insn_processed >= 8)
16581 		add_new_state = true;
16582 
16583 	pprev = explored_state(env, insn_idx);
16584 	sl = *pprev;
16585 
16586 	clean_live_states(env, insn_idx, cur);
16587 
16588 	while (sl) {
16589 		states_cnt++;
16590 		if (sl->state.insn_idx != insn_idx)
16591 			goto next;
16592 
16593 		if (sl->state.branches) {
16594 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16595 
16596 			if (frame->in_async_callback_fn &&
16597 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16598 				/* Different async_entry_cnt means that the verifier is
16599 				 * processing another entry into async callback.
16600 				 * Seeing the same state is not an indication of infinite
16601 				 * loop or infinite recursion.
16602 				 * But finding the same state doesn't mean that it's safe
16603 				 * to stop processing the current state. The previous state
16604 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16605 				 * Checking in_async_callback_fn alone is not enough either.
16606 				 * Since the verifier still needs to catch infinite loops
16607 				 * inside async callbacks.
16608 				 */
16609 				goto skip_inf_loop_check;
16610 			}
16611 			/* BPF open-coded iterators loop detection is special.
16612 			 * states_maybe_looping() logic is too simplistic in detecting
16613 			 * states that *might* be equivalent, because it doesn't know
16614 			 * about ID remapping, so don't even perform it.
16615 			 * See process_iter_next_call() and iter_active_depths_differ()
16616 			 * for overview of the logic. When current and one of parent
16617 			 * states are detected as equivalent, it's a good thing: we prove
16618 			 * convergence and can stop simulating further iterations.
16619 			 * It's safe to assume that iterator loop will finish, taking into
16620 			 * account iter_next() contract of eventually returning
16621 			 * sticky NULL result.
16622 			 *
16623 			 * Note, that states have to be compared exactly in this case because
16624 			 * read and precision marks might not be finalized inside the loop.
16625 			 * E.g. as in the program below:
16626 			 *
16627 			 *     1. r7 = -16
16628 			 *     2. r6 = bpf_get_prandom_u32()
16629 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16630 			 *     4.   if (r6 != 42) {
16631 			 *     5.     r7 = -32
16632 			 *     6.     r6 = bpf_get_prandom_u32()
16633 			 *     7.     continue
16634 			 *     8.   }
16635 			 *     9.   r0 = r10
16636 			 *    10.   r0 += r7
16637 			 *    11.   r8 = *(u64 *)(r0 + 0)
16638 			 *    12.   r6 = bpf_get_prandom_u32()
16639 			 *    13. }
16640 			 *
16641 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16642 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16643 			 * not have read or precision mark for r7 yet, thus inexact states
16644 			 * comparison would discard current state with r7=-32
16645 			 * => unsafe memory access at 11 would not be caught.
16646 			 */
16647 			if (is_iter_next_insn(env, insn_idx)) {
16648 				if (states_equal(env, &sl->state, cur, true)) {
16649 					struct bpf_func_state *cur_frame;
16650 					struct bpf_reg_state *iter_state, *iter_reg;
16651 					int spi;
16652 
16653 					cur_frame = cur->frame[cur->curframe];
16654 					/* btf_check_iter_kfuncs() enforces that
16655 					 * iter state pointer is always the first arg
16656 					 */
16657 					iter_reg = &cur_frame->regs[BPF_REG_1];
16658 					/* current state is valid due to states_equal(),
16659 					 * so we can assume valid iter and reg state,
16660 					 * no need for extra (re-)validations
16661 					 */
16662 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16663 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16664 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16665 						update_loop_entry(cur, &sl->state);
16666 						goto hit;
16667 					}
16668 				}
16669 				goto skip_inf_loop_check;
16670 			}
16671 			if (calls_callback(env, insn_idx)) {
16672 				if (states_equal(env, &sl->state, cur, true))
16673 					goto hit;
16674 				goto skip_inf_loop_check;
16675 			}
16676 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16677 			if (states_maybe_looping(&sl->state, cur) &&
16678 			    states_equal(env, &sl->state, cur, false) &&
16679 			    !iter_active_depths_differ(&sl->state, cur) &&
16680 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16681 				verbose_linfo(env, insn_idx, "; ");
16682 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16683 				verbose(env, "cur state:");
16684 				print_verifier_state(env, cur->frame[cur->curframe], true);
16685 				verbose(env, "old state:");
16686 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16687 				return -EINVAL;
16688 			}
16689 			/* if the verifier is processing a loop, avoid adding new state
16690 			 * too often, since different loop iterations have distinct
16691 			 * states and may not help future pruning.
16692 			 * This threshold shouldn't be too low to make sure that
16693 			 * a loop with large bound will be rejected quickly.
16694 			 * The most abusive loop will be:
16695 			 * r1 += 1
16696 			 * if r1 < 1000000 goto pc-2
16697 			 * 1M insn_procssed limit / 100 == 10k peak states.
16698 			 * This threshold shouldn't be too high either, since states
16699 			 * at the end of the loop are likely to be useful in pruning.
16700 			 */
16701 skip_inf_loop_check:
16702 			if (!force_new_state &&
16703 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16704 			    env->insn_processed - env->prev_insn_processed < 100)
16705 				add_new_state = false;
16706 			goto miss;
16707 		}
16708 		/* If sl->state is a part of a loop and this loop's entry is a part of
16709 		 * current verification path then states have to be compared exactly.
16710 		 * 'force_exact' is needed to catch the following case:
16711 		 *
16712 		 *                initial     Here state 'succ' was processed first,
16713 		 *                  |         it was eventually tracked to produce a
16714 		 *                  V         state identical to 'hdr'.
16715 		 *     .---------> hdr        All branches from 'succ' had been explored
16716 		 *     |            |         and thus 'succ' has its .branches == 0.
16717 		 *     |            V
16718 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16719 		 *     |    |       |         to the same instruction + callsites.
16720 		 *     |    V       V         In such case it is necessary to check
16721 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16722 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16723 		 *     |    V       V         same loop exact flag has to be set.
16724 		 *     |   succ <- cur        To check if that is the case, verify
16725 		 *     |    |                 if loop entry of 'succ' is in current
16726 		 *     |    V                 DFS path.
16727 		 *     |   ...
16728 		 *     |    |
16729 		 *     '----'
16730 		 *
16731 		 * Additional details are in the comment before get_loop_entry().
16732 		 */
16733 		loop_entry = get_loop_entry(&sl->state);
16734 		force_exact = loop_entry && loop_entry->branches > 0;
16735 		if (states_equal(env, &sl->state, cur, force_exact)) {
16736 			if (force_exact)
16737 				update_loop_entry(cur, loop_entry);
16738 hit:
16739 			sl->hit_cnt++;
16740 			/* reached equivalent register/stack state,
16741 			 * prune the search.
16742 			 * Registers read by the continuation are read by us.
16743 			 * If we have any write marks in env->cur_state, they
16744 			 * will prevent corresponding reads in the continuation
16745 			 * from reaching our parent (an explored_state).  Our
16746 			 * own state will get the read marks recorded, but
16747 			 * they'll be immediately forgotten as we're pruning
16748 			 * this state and will pop a new one.
16749 			 */
16750 			err = propagate_liveness(env, &sl->state, cur);
16751 
16752 			/* if previous state reached the exit with precision and
16753 			 * current state is equivalent to it (except precsion marks)
16754 			 * the precision needs to be propagated back in
16755 			 * the current state.
16756 			 */
16757 			err = err ? : push_jmp_history(env, cur);
16758 			err = err ? : propagate_precision(env, &sl->state);
16759 			if (err)
16760 				return err;
16761 			return 1;
16762 		}
16763 miss:
16764 		/* when new state is not going to be added do not increase miss count.
16765 		 * Otherwise several loop iterations will remove the state
16766 		 * recorded earlier. The goal of these heuristics is to have
16767 		 * states from some iterations of the loop (some in the beginning
16768 		 * and some at the end) to help pruning.
16769 		 */
16770 		if (add_new_state)
16771 			sl->miss_cnt++;
16772 		/* heuristic to determine whether this state is beneficial
16773 		 * to keep checking from state equivalence point of view.
16774 		 * Higher numbers increase max_states_per_insn and verification time,
16775 		 * but do not meaningfully decrease insn_processed.
16776 		 * 'n' controls how many times state could miss before eviction.
16777 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16778 		 * too early would hinder iterator convergence.
16779 		 */
16780 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16781 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16782 			/* the state is unlikely to be useful. Remove it to
16783 			 * speed up verification
16784 			 */
16785 			*pprev = sl->next;
16786 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16787 			    !sl->state.used_as_loop_entry) {
16788 				u32 br = sl->state.branches;
16789 
16790 				WARN_ONCE(br,
16791 					  "BUG live_done but branches_to_explore %d\n",
16792 					  br);
16793 				free_verifier_state(&sl->state, false);
16794 				kfree(sl);
16795 				env->peak_states--;
16796 			} else {
16797 				/* cannot free this state, since parentage chain may
16798 				 * walk it later. Add it for free_list instead to
16799 				 * be freed at the end of verification
16800 				 */
16801 				sl->next = env->free_list;
16802 				env->free_list = sl;
16803 			}
16804 			sl = *pprev;
16805 			continue;
16806 		}
16807 next:
16808 		pprev = &sl->next;
16809 		sl = *pprev;
16810 	}
16811 
16812 	if (env->max_states_per_insn < states_cnt)
16813 		env->max_states_per_insn = states_cnt;
16814 
16815 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16816 		return 0;
16817 
16818 	if (!add_new_state)
16819 		return 0;
16820 
16821 	/* There were no equivalent states, remember the current one.
16822 	 * Technically the current state is not proven to be safe yet,
16823 	 * but it will either reach outer most bpf_exit (which means it's safe)
16824 	 * or it will be rejected. When there are no loops the verifier won't be
16825 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16826 	 * again on the way to bpf_exit.
16827 	 * When looping the sl->state.branches will be > 0 and this state
16828 	 * will not be considered for equivalence until branches == 0.
16829 	 */
16830 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16831 	if (!new_sl)
16832 		return -ENOMEM;
16833 	env->total_states++;
16834 	env->peak_states++;
16835 	env->prev_jmps_processed = env->jmps_processed;
16836 	env->prev_insn_processed = env->insn_processed;
16837 
16838 	/* forget precise markings we inherited, see __mark_chain_precision */
16839 	if (env->bpf_capable)
16840 		mark_all_scalars_imprecise(env, cur);
16841 
16842 	/* add new state to the head of linked list */
16843 	new = &new_sl->state;
16844 	err = copy_verifier_state(new, cur);
16845 	if (err) {
16846 		free_verifier_state(new, false);
16847 		kfree(new_sl);
16848 		return err;
16849 	}
16850 	new->insn_idx = insn_idx;
16851 	WARN_ONCE(new->branches != 1,
16852 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16853 
16854 	cur->parent = new;
16855 	cur->first_insn_idx = insn_idx;
16856 	cur->dfs_depth = new->dfs_depth + 1;
16857 	clear_jmp_history(cur);
16858 	new_sl->next = *explored_state(env, insn_idx);
16859 	*explored_state(env, insn_idx) = new_sl;
16860 	/* connect new state to parentage chain. Current frame needs all
16861 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16862 	 * to the stack implicitly by JITs) so in callers' frames connect just
16863 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16864 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16865 	 * from callee with its full parentage chain, anyway.
16866 	 */
16867 	/* clear write marks in current state: the writes we did are not writes
16868 	 * our child did, so they don't screen off its reads from us.
16869 	 * (There are no read marks in current state, because reads always mark
16870 	 * their parent and current state never has children yet.  Only
16871 	 * explored_states can get read marks.)
16872 	 */
16873 	for (j = 0; j <= cur->curframe; j++) {
16874 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16875 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16876 		for (i = 0; i < BPF_REG_FP; i++)
16877 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16878 	}
16879 
16880 	/* all stack frames are accessible from callee, clear them all */
16881 	for (j = 0; j <= cur->curframe; j++) {
16882 		struct bpf_func_state *frame = cur->frame[j];
16883 		struct bpf_func_state *newframe = new->frame[j];
16884 
16885 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16886 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16887 			frame->stack[i].spilled_ptr.parent =
16888 						&newframe->stack[i].spilled_ptr;
16889 		}
16890 	}
16891 	return 0;
16892 }
16893 
16894 /* Return true if it's OK to have the same insn return a different type. */
16895 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16896 {
16897 	switch (base_type(type)) {
16898 	case PTR_TO_CTX:
16899 	case PTR_TO_SOCKET:
16900 	case PTR_TO_SOCK_COMMON:
16901 	case PTR_TO_TCP_SOCK:
16902 	case PTR_TO_XDP_SOCK:
16903 	case PTR_TO_BTF_ID:
16904 		return false;
16905 	default:
16906 		return true;
16907 	}
16908 }
16909 
16910 /* If an instruction was previously used with particular pointer types, then we
16911  * need to be careful to avoid cases such as the below, where it may be ok
16912  * for one branch accessing the pointer, but not ok for the other branch:
16913  *
16914  * R1 = sock_ptr
16915  * goto X;
16916  * ...
16917  * R1 = some_other_valid_ptr;
16918  * goto X;
16919  * ...
16920  * R2 = *(u32 *)(R1 + 0);
16921  */
16922 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16923 {
16924 	return src != prev && (!reg_type_mismatch_ok(src) ||
16925 			       !reg_type_mismatch_ok(prev));
16926 }
16927 
16928 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16929 			     bool allow_trust_missmatch)
16930 {
16931 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16932 
16933 	if (*prev_type == NOT_INIT) {
16934 		/* Saw a valid insn
16935 		 * dst_reg = *(u32 *)(src_reg + off)
16936 		 * save type to validate intersecting paths
16937 		 */
16938 		*prev_type = type;
16939 	} else if (reg_type_mismatch(type, *prev_type)) {
16940 		/* Abuser program is trying to use the same insn
16941 		 * dst_reg = *(u32*) (src_reg + off)
16942 		 * with different pointer types:
16943 		 * src_reg == ctx in one branch and
16944 		 * src_reg == stack|map in some other branch.
16945 		 * Reject it.
16946 		 */
16947 		if (allow_trust_missmatch &&
16948 		    base_type(type) == PTR_TO_BTF_ID &&
16949 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16950 			/*
16951 			 * Have to support a use case when one path through
16952 			 * the program yields TRUSTED pointer while another
16953 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16954 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16955 			 */
16956 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16957 		} else {
16958 			verbose(env, "same insn cannot be used with different pointers\n");
16959 			return -EINVAL;
16960 		}
16961 	}
16962 
16963 	return 0;
16964 }
16965 
16966 static int do_check(struct bpf_verifier_env *env)
16967 {
16968 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16969 	struct bpf_verifier_state *state = env->cur_state;
16970 	struct bpf_insn *insns = env->prog->insnsi;
16971 	struct bpf_reg_state *regs;
16972 	int insn_cnt = env->prog->len;
16973 	bool do_print_state = false;
16974 	int prev_insn_idx = -1;
16975 
16976 	for (;;) {
16977 		struct bpf_insn *insn;
16978 		u8 class;
16979 		int err;
16980 
16981 		env->prev_insn_idx = prev_insn_idx;
16982 		if (env->insn_idx >= insn_cnt) {
16983 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16984 				env->insn_idx, insn_cnt);
16985 			return -EFAULT;
16986 		}
16987 
16988 		insn = &insns[env->insn_idx];
16989 		class = BPF_CLASS(insn->code);
16990 
16991 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16992 			verbose(env,
16993 				"BPF program is too large. Processed %d insn\n",
16994 				env->insn_processed);
16995 			return -E2BIG;
16996 		}
16997 
16998 		state->last_insn_idx = env->prev_insn_idx;
16999 
17000 		if (is_prune_point(env, env->insn_idx)) {
17001 			err = is_state_visited(env, env->insn_idx);
17002 			if (err < 0)
17003 				return err;
17004 			if (err == 1) {
17005 				/* found equivalent state, can prune the search */
17006 				if (env->log.level & BPF_LOG_LEVEL) {
17007 					if (do_print_state)
17008 						verbose(env, "\nfrom %d to %d%s: safe\n",
17009 							env->prev_insn_idx, env->insn_idx,
17010 							env->cur_state->speculative ?
17011 							" (speculative execution)" : "");
17012 					else
17013 						verbose(env, "%d: safe\n", env->insn_idx);
17014 				}
17015 				goto process_bpf_exit;
17016 			}
17017 		}
17018 
17019 		if (is_jmp_point(env, env->insn_idx)) {
17020 			err = push_jmp_history(env, state);
17021 			if (err)
17022 				return err;
17023 		}
17024 
17025 		if (signal_pending(current))
17026 			return -EAGAIN;
17027 
17028 		if (need_resched())
17029 			cond_resched();
17030 
17031 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17032 			verbose(env, "\nfrom %d to %d%s:",
17033 				env->prev_insn_idx, env->insn_idx,
17034 				env->cur_state->speculative ?
17035 				" (speculative execution)" : "");
17036 			print_verifier_state(env, state->frame[state->curframe], true);
17037 			do_print_state = false;
17038 		}
17039 
17040 		if (env->log.level & BPF_LOG_LEVEL) {
17041 			const struct bpf_insn_cbs cbs = {
17042 				.cb_call	= disasm_kfunc_name,
17043 				.cb_print	= verbose,
17044 				.private_data	= env,
17045 			};
17046 
17047 			if (verifier_state_scratched(env))
17048 				print_insn_state(env, state->frame[state->curframe]);
17049 
17050 			verbose_linfo(env, env->insn_idx, "; ");
17051 			env->prev_log_pos = env->log.end_pos;
17052 			verbose(env, "%d: ", env->insn_idx);
17053 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17054 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17055 			env->prev_log_pos = env->log.end_pos;
17056 		}
17057 
17058 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17059 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17060 							   env->prev_insn_idx);
17061 			if (err)
17062 				return err;
17063 		}
17064 
17065 		regs = cur_regs(env);
17066 		sanitize_mark_insn_seen(env);
17067 		prev_insn_idx = env->insn_idx;
17068 
17069 		if (class == BPF_ALU || class == BPF_ALU64) {
17070 			err = check_alu_op(env, insn);
17071 			if (err)
17072 				return err;
17073 
17074 		} else if (class == BPF_LDX) {
17075 			enum bpf_reg_type src_reg_type;
17076 
17077 			/* check for reserved fields is already done */
17078 
17079 			/* check src operand */
17080 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17081 			if (err)
17082 				return err;
17083 
17084 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17085 			if (err)
17086 				return err;
17087 
17088 			src_reg_type = regs[insn->src_reg].type;
17089 
17090 			/* check that memory (src_reg + off) is readable,
17091 			 * the state of dst_reg will be updated by this func
17092 			 */
17093 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17094 					       insn->off, BPF_SIZE(insn->code),
17095 					       BPF_READ, insn->dst_reg, false,
17096 					       BPF_MODE(insn->code) == BPF_MEMSX);
17097 			if (err)
17098 				return err;
17099 
17100 			err = save_aux_ptr_type(env, src_reg_type, true);
17101 			if (err)
17102 				return err;
17103 		} else if (class == BPF_STX) {
17104 			enum bpf_reg_type dst_reg_type;
17105 
17106 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17107 				err = check_atomic(env, env->insn_idx, insn);
17108 				if (err)
17109 					return err;
17110 				env->insn_idx++;
17111 				continue;
17112 			}
17113 
17114 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17115 				verbose(env, "BPF_STX uses reserved fields\n");
17116 				return -EINVAL;
17117 			}
17118 
17119 			/* check src1 operand */
17120 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17121 			if (err)
17122 				return err;
17123 			/* check src2 operand */
17124 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17125 			if (err)
17126 				return err;
17127 
17128 			dst_reg_type = regs[insn->dst_reg].type;
17129 
17130 			/* check that memory (dst_reg + off) is writeable */
17131 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17132 					       insn->off, BPF_SIZE(insn->code),
17133 					       BPF_WRITE, insn->src_reg, false, false);
17134 			if (err)
17135 				return err;
17136 
17137 			err = save_aux_ptr_type(env, dst_reg_type, false);
17138 			if (err)
17139 				return err;
17140 		} else if (class == BPF_ST) {
17141 			enum bpf_reg_type dst_reg_type;
17142 
17143 			if (BPF_MODE(insn->code) != BPF_MEM ||
17144 			    insn->src_reg != BPF_REG_0) {
17145 				verbose(env, "BPF_ST uses reserved fields\n");
17146 				return -EINVAL;
17147 			}
17148 			/* check src operand */
17149 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17150 			if (err)
17151 				return err;
17152 
17153 			dst_reg_type = regs[insn->dst_reg].type;
17154 
17155 			/* check that memory (dst_reg + off) is writeable */
17156 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17157 					       insn->off, BPF_SIZE(insn->code),
17158 					       BPF_WRITE, -1, false, false);
17159 			if (err)
17160 				return err;
17161 
17162 			err = save_aux_ptr_type(env, dst_reg_type, false);
17163 			if (err)
17164 				return err;
17165 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17166 			u8 opcode = BPF_OP(insn->code);
17167 
17168 			env->jmps_processed++;
17169 			if (opcode == BPF_CALL) {
17170 				if (BPF_SRC(insn->code) != BPF_K ||
17171 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17172 				     && insn->off != 0) ||
17173 				    (insn->src_reg != BPF_REG_0 &&
17174 				     insn->src_reg != BPF_PSEUDO_CALL &&
17175 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17176 				    insn->dst_reg != BPF_REG_0 ||
17177 				    class == BPF_JMP32) {
17178 					verbose(env, "BPF_CALL uses reserved fields\n");
17179 					return -EINVAL;
17180 				}
17181 
17182 				if (env->cur_state->active_lock.ptr) {
17183 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17184 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17185 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17186 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17187 						verbose(env, "function calls are not allowed while holding a lock\n");
17188 						return -EINVAL;
17189 					}
17190 				}
17191 				if (insn->src_reg == BPF_PSEUDO_CALL)
17192 					err = check_func_call(env, insn, &env->insn_idx);
17193 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17194 					err = check_kfunc_call(env, insn, &env->insn_idx);
17195 				else
17196 					err = check_helper_call(env, insn, &env->insn_idx);
17197 				if (err)
17198 					return err;
17199 
17200 				mark_reg_scratched(env, BPF_REG_0);
17201 			} else if (opcode == BPF_JA) {
17202 				if (BPF_SRC(insn->code) != BPF_K ||
17203 				    insn->src_reg != BPF_REG_0 ||
17204 				    insn->dst_reg != BPF_REG_0 ||
17205 				    (class == BPF_JMP && insn->imm != 0) ||
17206 				    (class == BPF_JMP32 && insn->off != 0)) {
17207 					verbose(env, "BPF_JA uses reserved fields\n");
17208 					return -EINVAL;
17209 				}
17210 
17211 				if (class == BPF_JMP)
17212 					env->insn_idx += insn->off + 1;
17213 				else
17214 					env->insn_idx += insn->imm + 1;
17215 				continue;
17216 
17217 			} else if (opcode == BPF_EXIT) {
17218 				if (BPF_SRC(insn->code) != BPF_K ||
17219 				    insn->imm != 0 ||
17220 				    insn->src_reg != BPF_REG_0 ||
17221 				    insn->dst_reg != BPF_REG_0 ||
17222 				    class == BPF_JMP32) {
17223 					verbose(env, "BPF_EXIT uses reserved fields\n");
17224 					return -EINVAL;
17225 				}
17226 
17227 				if (env->cur_state->active_lock.ptr &&
17228 				    !in_rbtree_lock_required_cb(env)) {
17229 					verbose(env, "bpf_spin_unlock is missing\n");
17230 					return -EINVAL;
17231 				}
17232 
17233 				if (env->cur_state->active_rcu_lock &&
17234 				    !in_rbtree_lock_required_cb(env)) {
17235 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17236 					return -EINVAL;
17237 				}
17238 
17239 				/* We must do check_reference_leak here before
17240 				 * prepare_func_exit to handle the case when
17241 				 * state->curframe > 0, it may be a callback
17242 				 * function, for which reference_state must
17243 				 * match caller reference state when it exits.
17244 				 */
17245 				err = check_reference_leak(env);
17246 				if (err)
17247 					return err;
17248 
17249 				if (state->curframe) {
17250 					/* exit from nested function */
17251 					err = prepare_func_exit(env, &env->insn_idx);
17252 					if (err)
17253 						return err;
17254 					do_print_state = true;
17255 					continue;
17256 				}
17257 
17258 				err = check_return_code(env);
17259 				if (err)
17260 					return err;
17261 process_bpf_exit:
17262 				mark_verifier_state_scratched(env);
17263 				update_branch_counts(env, env->cur_state);
17264 				err = pop_stack(env, &prev_insn_idx,
17265 						&env->insn_idx, pop_log);
17266 				if (err < 0) {
17267 					if (err != -ENOENT)
17268 						return err;
17269 					break;
17270 				} else {
17271 					do_print_state = true;
17272 					continue;
17273 				}
17274 			} else {
17275 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17276 				if (err)
17277 					return err;
17278 			}
17279 		} else if (class == BPF_LD) {
17280 			u8 mode = BPF_MODE(insn->code);
17281 
17282 			if (mode == BPF_ABS || mode == BPF_IND) {
17283 				err = check_ld_abs(env, insn);
17284 				if (err)
17285 					return err;
17286 
17287 			} else if (mode == BPF_IMM) {
17288 				err = check_ld_imm(env, insn);
17289 				if (err)
17290 					return err;
17291 
17292 				env->insn_idx++;
17293 				sanitize_mark_insn_seen(env);
17294 			} else {
17295 				verbose(env, "invalid BPF_LD mode\n");
17296 				return -EINVAL;
17297 			}
17298 		} else {
17299 			verbose(env, "unknown insn class %d\n", class);
17300 			return -EINVAL;
17301 		}
17302 
17303 		env->insn_idx++;
17304 	}
17305 
17306 	return 0;
17307 }
17308 
17309 static int find_btf_percpu_datasec(struct btf *btf)
17310 {
17311 	const struct btf_type *t;
17312 	const char *tname;
17313 	int i, n;
17314 
17315 	/*
17316 	 * Both vmlinux and module each have their own ".data..percpu"
17317 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17318 	 * types to look at only module's own BTF types.
17319 	 */
17320 	n = btf_nr_types(btf);
17321 	if (btf_is_module(btf))
17322 		i = btf_nr_types(btf_vmlinux);
17323 	else
17324 		i = 1;
17325 
17326 	for(; i < n; i++) {
17327 		t = btf_type_by_id(btf, i);
17328 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17329 			continue;
17330 
17331 		tname = btf_name_by_offset(btf, t->name_off);
17332 		if (!strcmp(tname, ".data..percpu"))
17333 			return i;
17334 	}
17335 
17336 	return -ENOENT;
17337 }
17338 
17339 /* replace pseudo btf_id with kernel symbol address */
17340 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17341 			       struct bpf_insn *insn,
17342 			       struct bpf_insn_aux_data *aux)
17343 {
17344 	const struct btf_var_secinfo *vsi;
17345 	const struct btf_type *datasec;
17346 	struct btf_mod_pair *btf_mod;
17347 	const struct btf_type *t;
17348 	const char *sym_name;
17349 	bool percpu = false;
17350 	u32 type, id = insn->imm;
17351 	struct btf *btf;
17352 	s32 datasec_id;
17353 	u64 addr;
17354 	int i, btf_fd, err;
17355 
17356 	btf_fd = insn[1].imm;
17357 	if (btf_fd) {
17358 		btf = btf_get_by_fd(btf_fd);
17359 		if (IS_ERR(btf)) {
17360 			verbose(env, "invalid module BTF object FD specified.\n");
17361 			return -EINVAL;
17362 		}
17363 	} else {
17364 		if (!btf_vmlinux) {
17365 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17366 			return -EINVAL;
17367 		}
17368 		btf = btf_vmlinux;
17369 		btf_get(btf);
17370 	}
17371 
17372 	t = btf_type_by_id(btf, id);
17373 	if (!t) {
17374 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17375 		err = -ENOENT;
17376 		goto err_put;
17377 	}
17378 
17379 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17380 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17381 		err = -EINVAL;
17382 		goto err_put;
17383 	}
17384 
17385 	sym_name = btf_name_by_offset(btf, t->name_off);
17386 	addr = kallsyms_lookup_name(sym_name);
17387 	if (!addr) {
17388 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17389 			sym_name);
17390 		err = -ENOENT;
17391 		goto err_put;
17392 	}
17393 	insn[0].imm = (u32)addr;
17394 	insn[1].imm = addr >> 32;
17395 
17396 	if (btf_type_is_func(t)) {
17397 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17398 		aux->btf_var.mem_size = 0;
17399 		goto check_btf;
17400 	}
17401 
17402 	datasec_id = find_btf_percpu_datasec(btf);
17403 	if (datasec_id > 0) {
17404 		datasec = btf_type_by_id(btf, datasec_id);
17405 		for_each_vsi(i, datasec, vsi) {
17406 			if (vsi->type == id) {
17407 				percpu = true;
17408 				break;
17409 			}
17410 		}
17411 	}
17412 
17413 	type = t->type;
17414 	t = btf_type_skip_modifiers(btf, type, NULL);
17415 	if (percpu) {
17416 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17417 		aux->btf_var.btf = btf;
17418 		aux->btf_var.btf_id = type;
17419 	} else if (!btf_type_is_struct(t)) {
17420 		const struct btf_type *ret;
17421 		const char *tname;
17422 		u32 tsize;
17423 
17424 		/* resolve the type size of ksym. */
17425 		ret = btf_resolve_size(btf, t, &tsize);
17426 		if (IS_ERR(ret)) {
17427 			tname = btf_name_by_offset(btf, t->name_off);
17428 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17429 				tname, PTR_ERR(ret));
17430 			err = -EINVAL;
17431 			goto err_put;
17432 		}
17433 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17434 		aux->btf_var.mem_size = tsize;
17435 	} else {
17436 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17437 		aux->btf_var.btf = btf;
17438 		aux->btf_var.btf_id = type;
17439 	}
17440 check_btf:
17441 	/* check whether we recorded this BTF (and maybe module) already */
17442 	for (i = 0; i < env->used_btf_cnt; i++) {
17443 		if (env->used_btfs[i].btf == btf) {
17444 			btf_put(btf);
17445 			return 0;
17446 		}
17447 	}
17448 
17449 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17450 		err = -E2BIG;
17451 		goto err_put;
17452 	}
17453 
17454 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17455 	btf_mod->btf = btf;
17456 	btf_mod->module = NULL;
17457 
17458 	/* if we reference variables from kernel module, bump its refcount */
17459 	if (btf_is_module(btf)) {
17460 		btf_mod->module = btf_try_get_module(btf);
17461 		if (!btf_mod->module) {
17462 			err = -ENXIO;
17463 			goto err_put;
17464 		}
17465 	}
17466 
17467 	env->used_btf_cnt++;
17468 
17469 	return 0;
17470 err_put:
17471 	btf_put(btf);
17472 	return err;
17473 }
17474 
17475 static bool is_tracing_prog_type(enum bpf_prog_type type)
17476 {
17477 	switch (type) {
17478 	case BPF_PROG_TYPE_KPROBE:
17479 	case BPF_PROG_TYPE_TRACEPOINT:
17480 	case BPF_PROG_TYPE_PERF_EVENT:
17481 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17482 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17483 		return true;
17484 	default:
17485 		return false;
17486 	}
17487 }
17488 
17489 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17490 					struct bpf_map *map,
17491 					struct bpf_prog *prog)
17492 
17493 {
17494 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17495 
17496 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17497 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17498 		if (is_tracing_prog_type(prog_type)) {
17499 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17500 			return -EINVAL;
17501 		}
17502 	}
17503 
17504 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17505 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17506 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17507 			return -EINVAL;
17508 		}
17509 
17510 		if (is_tracing_prog_type(prog_type)) {
17511 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17512 			return -EINVAL;
17513 		}
17514 	}
17515 
17516 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17517 		if (is_tracing_prog_type(prog_type)) {
17518 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17519 			return -EINVAL;
17520 		}
17521 	}
17522 
17523 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17524 	    !bpf_offload_prog_map_match(prog, map)) {
17525 		verbose(env, "offload device mismatch between prog and map\n");
17526 		return -EINVAL;
17527 	}
17528 
17529 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17530 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17531 		return -EINVAL;
17532 	}
17533 
17534 	if (prog->aux->sleepable)
17535 		switch (map->map_type) {
17536 		case BPF_MAP_TYPE_HASH:
17537 		case BPF_MAP_TYPE_LRU_HASH:
17538 		case BPF_MAP_TYPE_ARRAY:
17539 		case BPF_MAP_TYPE_PERCPU_HASH:
17540 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17541 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17542 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17543 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17544 		case BPF_MAP_TYPE_RINGBUF:
17545 		case BPF_MAP_TYPE_USER_RINGBUF:
17546 		case BPF_MAP_TYPE_INODE_STORAGE:
17547 		case BPF_MAP_TYPE_SK_STORAGE:
17548 		case BPF_MAP_TYPE_TASK_STORAGE:
17549 		case BPF_MAP_TYPE_CGRP_STORAGE:
17550 			break;
17551 		default:
17552 			verbose(env,
17553 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17554 			return -EINVAL;
17555 		}
17556 
17557 	return 0;
17558 }
17559 
17560 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17561 {
17562 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17563 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17564 }
17565 
17566 /* find and rewrite pseudo imm in ld_imm64 instructions:
17567  *
17568  * 1. if it accesses map FD, replace it with actual map pointer.
17569  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17570  *
17571  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17572  */
17573 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17574 {
17575 	struct bpf_insn *insn = env->prog->insnsi;
17576 	int insn_cnt = env->prog->len;
17577 	int i, j, err;
17578 
17579 	err = bpf_prog_calc_tag(env->prog);
17580 	if (err)
17581 		return err;
17582 
17583 	for (i = 0; i < insn_cnt; i++, insn++) {
17584 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17585 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17586 		    insn->imm != 0)) {
17587 			verbose(env, "BPF_LDX uses reserved fields\n");
17588 			return -EINVAL;
17589 		}
17590 
17591 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17592 			struct bpf_insn_aux_data *aux;
17593 			struct bpf_map *map;
17594 			struct fd f;
17595 			u64 addr;
17596 			u32 fd;
17597 
17598 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17599 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17600 			    insn[1].off != 0) {
17601 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17602 				return -EINVAL;
17603 			}
17604 
17605 			if (insn[0].src_reg == 0)
17606 				/* valid generic load 64-bit imm */
17607 				goto next_insn;
17608 
17609 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17610 				aux = &env->insn_aux_data[i];
17611 				err = check_pseudo_btf_id(env, insn, aux);
17612 				if (err)
17613 					return err;
17614 				goto next_insn;
17615 			}
17616 
17617 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17618 				aux = &env->insn_aux_data[i];
17619 				aux->ptr_type = PTR_TO_FUNC;
17620 				goto next_insn;
17621 			}
17622 
17623 			/* In final convert_pseudo_ld_imm64() step, this is
17624 			 * converted into regular 64-bit imm load insn.
17625 			 */
17626 			switch (insn[0].src_reg) {
17627 			case BPF_PSEUDO_MAP_VALUE:
17628 			case BPF_PSEUDO_MAP_IDX_VALUE:
17629 				break;
17630 			case BPF_PSEUDO_MAP_FD:
17631 			case BPF_PSEUDO_MAP_IDX:
17632 				if (insn[1].imm == 0)
17633 					break;
17634 				fallthrough;
17635 			default:
17636 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17637 				return -EINVAL;
17638 			}
17639 
17640 			switch (insn[0].src_reg) {
17641 			case BPF_PSEUDO_MAP_IDX_VALUE:
17642 			case BPF_PSEUDO_MAP_IDX:
17643 				if (bpfptr_is_null(env->fd_array)) {
17644 					verbose(env, "fd_idx without fd_array is invalid\n");
17645 					return -EPROTO;
17646 				}
17647 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17648 							    insn[0].imm * sizeof(fd),
17649 							    sizeof(fd)))
17650 					return -EFAULT;
17651 				break;
17652 			default:
17653 				fd = insn[0].imm;
17654 				break;
17655 			}
17656 
17657 			f = fdget(fd);
17658 			map = __bpf_map_get(f);
17659 			if (IS_ERR(map)) {
17660 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17661 				return PTR_ERR(map);
17662 			}
17663 
17664 			err = check_map_prog_compatibility(env, map, env->prog);
17665 			if (err) {
17666 				fdput(f);
17667 				return err;
17668 			}
17669 
17670 			aux = &env->insn_aux_data[i];
17671 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17672 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17673 				addr = (unsigned long)map;
17674 			} else {
17675 				u32 off = insn[1].imm;
17676 
17677 				if (off >= BPF_MAX_VAR_OFF) {
17678 					verbose(env, "direct value offset of %u is not allowed\n", off);
17679 					fdput(f);
17680 					return -EINVAL;
17681 				}
17682 
17683 				if (!map->ops->map_direct_value_addr) {
17684 					verbose(env, "no direct value access support for this map type\n");
17685 					fdput(f);
17686 					return -EINVAL;
17687 				}
17688 
17689 				err = map->ops->map_direct_value_addr(map, &addr, off);
17690 				if (err) {
17691 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17692 						map->value_size, off);
17693 					fdput(f);
17694 					return err;
17695 				}
17696 
17697 				aux->map_off = off;
17698 				addr += off;
17699 			}
17700 
17701 			insn[0].imm = (u32)addr;
17702 			insn[1].imm = addr >> 32;
17703 
17704 			/* check whether we recorded this map already */
17705 			for (j = 0; j < env->used_map_cnt; j++) {
17706 				if (env->used_maps[j] == map) {
17707 					aux->map_index = j;
17708 					fdput(f);
17709 					goto next_insn;
17710 				}
17711 			}
17712 
17713 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17714 				fdput(f);
17715 				return -E2BIG;
17716 			}
17717 
17718 			/* hold the map. If the program is rejected by verifier,
17719 			 * the map will be released by release_maps() or it
17720 			 * will be used by the valid program until it's unloaded
17721 			 * and all maps are released in free_used_maps()
17722 			 */
17723 			bpf_map_inc(map);
17724 
17725 			aux->map_index = env->used_map_cnt;
17726 			env->used_maps[env->used_map_cnt++] = map;
17727 
17728 			if (bpf_map_is_cgroup_storage(map) &&
17729 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17730 				verbose(env, "only one cgroup storage of each type is allowed\n");
17731 				fdput(f);
17732 				return -EBUSY;
17733 			}
17734 
17735 			fdput(f);
17736 next_insn:
17737 			insn++;
17738 			i++;
17739 			continue;
17740 		}
17741 
17742 		/* Basic sanity check before we invest more work here. */
17743 		if (!bpf_opcode_in_insntable(insn->code)) {
17744 			verbose(env, "unknown opcode %02x\n", insn->code);
17745 			return -EINVAL;
17746 		}
17747 	}
17748 
17749 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17750 	 * 'struct bpf_map *' into a register instead of user map_fd.
17751 	 * These pointers will be used later by verifier to validate map access.
17752 	 */
17753 	return 0;
17754 }
17755 
17756 /* drop refcnt of maps used by the rejected program */
17757 static void release_maps(struct bpf_verifier_env *env)
17758 {
17759 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17760 			     env->used_map_cnt);
17761 }
17762 
17763 /* drop refcnt of maps used by the rejected program */
17764 static void release_btfs(struct bpf_verifier_env *env)
17765 {
17766 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17767 			     env->used_btf_cnt);
17768 }
17769 
17770 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17771 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17772 {
17773 	struct bpf_insn *insn = env->prog->insnsi;
17774 	int insn_cnt = env->prog->len;
17775 	int i;
17776 
17777 	for (i = 0; i < insn_cnt; i++, insn++) {
17778 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17779 			continue;
17780 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17781 			continue;
17782 		insn->src_reg = 0;
17783 	}
17784 }
17785 
17786 /* single env->prog->insni[off] instruction was replaced with the range
17787  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17788  * [0, off) and [off, end) to new locations, so the patched range stays zero
17789  */
17790 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17791 				 struct bpf_insn_aux_data *new_data,
17792 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17793 {
17794 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17795 	struct bpf_insn *insn = new_prog->insnsi;
17796 	u32 old_seen = old_data[off].seen;
17797 	u32 prog_len;
17798 	int i;
17799 
17800 	/* aux info at OFF always needs adjustment, no matter fast path
17801 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17802 	 * original insn at old prog.
17803 	 */
17804 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17805 
17806 	if (cnt == 1)
17807 		return;
17808 	prog_len = new_prog->len;
17809 
17810 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17811 	memcpy(new_data + off + cnt - 1, old_data + off,
17812 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17813 	for (i = off; i < off + cnt - 1; i++) {
17814 		/* Expand insni[off]'s seen count to the patched range. */
17815 		new_data[i].seen = old_seen;
17816 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17817 	}
17818 	env->insn_aux_data = new_data;
17819 	vfree(old_data);
17820 }
17821 
17822 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17823 {
17824 	int i;
17825 
17826 	if (len == 1)
17827 		return;
17828 	/* NOTE: fake 'exit' subprog should be updated as well. */
17829 	for (i = 0; i <= env->subprog_cnt; i++) {
17830 		if (env->subprog_info[i].start <= off)
17831 			continue;
17832 		env->subprog_info[i].start += len - 1;
17833 	}
17834 }
17835 
17836 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17837 {
17838 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17839 	int i, sz = prog->aux->size_poke_tab;
17840 	struct bpf_jit_poke_descriptor *desc;
17841 
17842 	for (i = 0; i < sz; i++) {
17843 		desc = &tab[i];
17844 		if (desc->insn_idx <= off)
17845 			continue;
17846 		desc->insn_idx += len - 1;
17847 	}
17848 }
17849 
17850 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17851 					    const struct bpf_insn *patch, u32 len)
17852 {
17853 	struct bpf_prog *new_prog;
17854 	struct bpf_insn_aux_data *new_data = NULL;
17855 
17856 	if (len > 1) {
17857 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17858 					      sizeof(struct bpf_insn_aux_data)));
17859 		if (!new_data)
17860 			return NULL;
17861 	}
17862 
17863 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17864 	if (IS_ERR(new_prog)) {
17865 		if (PTR_ERR(new_prog) == -ERANGE)
17866 			verbose(env,
17867 				"insn %d cannot be patched due to 16-bit range\n",
17868 				env->insn_aux_data[off].orig_idx);
17869 		vfree(new_data);
17870 		return NULL;
17871 	}
17872 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17873 	adjust_subprog_starts(env, off, len);
17874 	adjust_poke_descs(new_prog, off, len);
17875 	return new_prog;
17876 }
17877 
17878 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17879 					      u32 off, u32 cnt)
17880 {
17881 	int i, j;
17882 
17883 	/* find first prog starting at or after off (first to remove) */
17884 	for (i = 0; i < env->subprog_cnt; i++)
17885 		if (env->subprog_info[i].start >= off)
17886 			break;
17887 	/* find first prog starting at or after off + cnt (first to stay) */
17888 	for (j = i; j < env->subprog_cnt; j++)
17889 		if (env->subprog_info[j].start >= off + cnt)
17890 			break;
17891 	/* if j doesn't start exactly at off + cnt, we are just removing
17892 	 * the front of previous prog
17893 	 */
17894 	if (env->subprog_info[j].start != off + cnt)
17895 		j--;
17896 
17897 	if (j > i) {
17898 		struct bpf_prog_aux *aux = env->prog->aux;
17899 		int move;
17900 
17901 		/* move fake 'exit' subprog as well */
17902 		move = env->subprog_cnt + 1 - j;
17903 
17904 		memmove(env->subprog_info + i,
17905 			env->subprog_info + j,
17906 			sizeof(*env->subprog_info) * move);
17907 		env->subprog_cnt -= j - i;
17908 
17909 		/* remove func_info */
17910 		if (aux->func_info) {
17911 			move = aux->func_info_cnt - j;
17912 
17913 			memmove(aux->func_info + i,
17914 				aux->func_info + j,
17915 				sizeof(*aux->func_info) * move);
17916 			aux->func_info_cnt -= j - i;
17917 			/* func_info->insn_off is set after all code rewrites,
17918 			 * in adjust_btf_func() - no need to adjust
17919 			 */
17920 		}
17921 	} else {
17922 		/* convert i from "first prog to remove" to "first to adjust" */
17923 		if (env->subprog_info[i].start == off)
17924 			i++;
17925 	}
17926 
17927 	/* update fake 'exit' subprog as well */
17928 	for (; i <= env->subprog_cnt; i++)
17929 		env->subprog_info[i].start -= cnt;
17930 
17931 	return 0;
17932 }
17933 
17934 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17935 				      u32 cnt)
17936 {
17937 	struct bpf_prog *prog = env->prog;
17938 	u32 i, l_off, l_cnt, nr_linfo;
17939 	struct bpf_line_info *linfo;
17940 
17941 	nr_linfo = prog->aux->nr_linfo;
17942 	if (!nr_linfo)
17943 		return 0;
17944 
17945 	linfo = prog->aux->linfo;
17946 
17947 	/* find first line info to remove, count lines to be removed */
17948 	for (i = 0; i < nr_linfo; i++)
17949 		if (linfo[i].insn_off >= off)
17950 			break;
17951 
17952 	l_off = i;
17953 	l_cnt = 0;
17954 	for (; i < nr_linfo; i++)
17955 		if (linfo[i].insn_off < off + cnt)
17956 			l_cnt++;
17957 		else
17958 			break;
17959 
17960 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17961 	 * last removed linfo.  prog is already modified, so prog->len == off
17962 	 * means no live instructions after (tail of the program was removed).
17963 	 */
17964 	if (prog->len != off && l_cnt &&
17965 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17966 		l_cnt--;
17967 		linfo[--i].insn_off = off + cnt;
17968 	}
17969 
17970 	/* remove the line info which refer to the removed instructions */
17971 	if (l_cnt) {
17972 		memmove(linfo + l_off, linfo + i,
17973 			sizeof(*linfo) * (nr_linfo - i));
17974 
17975 		prog->aux->nr_linfo -= l_cnt;
17976 		nr_linfo = prog->aux->nr_linfo;
17977 	}
17978 
17979 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17980 	for (i = l_off; i < nr_linfo; i++)
17981 		linfo[i].insn_off -= cnt;
17982 
17983 	/* fix up all subprogs (incl. 'exit') which start >= off */
17984 	for (i = 0; i <= env->subprog_cnt; i++)
17985 		if (env->subprog_info[i].linfo_idx > l_off) {
17986 			/* program may have started in the removed region but
17987 			 * may not be fully removed
17988 			 */
17989 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17990 				env->subprog_info[i].linfo_idx -= l_cnt;
17991 			else
17992 				env->subprog_info[i].linfo_idx = l_off;
17993 		}
17994 
17995 	return 0;
17996 }
17997 
17998 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17999 {
18000 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18001 	unsigned int orig_prog_len = env->prog->len;
18002 	int err;
18003 
18004 	if (bpf_prog_is_offloaded(env->prog->aux))
18005 		bpf_prog_offload_remove_insns(env, off, cnt);
18006 
18007 	err = bpf_remove_insns(env->prog, off, cnt);
18008 	if (err)
18009 		return err;
18010 
18011 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18012 	if (err)
18013 		return err;
18014 
18015 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18016 	if (err)
18017 		return err;
18018 
18019 	memmove(aux_data + off,	aux_data + off + cnt,
18020 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18021 
18022 	return 0;
18023 }
18024 
18025 /* The verifier does more data flow analysis than llvm and will not
18026  * explore branches that are dead at run time. Malicious programs can
18027  * have dead code too. Therefore replace all dead at-run-time code
18028  * with 'ja -1'.
18029  *
18030  * Just nops are not optimal, e.g. if they would sit at the end of the
18031  * program and through another bug we would manage to jump there, then
18032  * we'd execute beyond program memory otherwise. Returning exception
18033  * code also wouldn't work since we can have subprogs where the dead
18034  * code could be located.
18035  */
18036 static void sanitize_dead_code(struct bpf_verifier_env *env)
18037 {
18038 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18039 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18040 	struct bpf_insn *insn = env->prog->insnsi;
18041 	const int insn_cnt = env->prog->len;
18042 	int i;
18043 
18044 	for (i = 0; i < insn_cnt; i++) {
18045 		if (aux_data[i].seen)
18046 			continue;
18047 		memcpy(insn + i, &trap, sizeof(trap));
18048 		aux_data[i].zext_dst = false;
18049 	}
18050 }
18051 
18052 static bool insn_is_cond_jump(u8 code)
18053 {
18054 	u8 op;
18055 
18056 	op = BPF_OP(code);
18057 	if (BPF_CLASS(code) == BPF_JMP32)
18058 		return op != BPF_JA;
18059 
18060 	if (BPF_CLASS(code) != BPF_JMP)
18061 		return false;
18062 
18063 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18064 }
18065 
18066 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18067 {
18068 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18069 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18070 	struct bpf_insn *insn = env->prog->insnsi;
18071 	const int insn_cnt = env->prog->len;
18072 	int i;
18073 
18074 	for (i = 0; i < insn_cnt; i++, insn++) {
18075 		if (!insn_is_cond_jump(insn->code))
18076 			continue;
18077 
18078 		if (!aux_data[i + 1].seen)
18079 			ja.off = insn->off;
18080 		else if (!aux_data[i + 1 + insn->off].seen)
18081 			ja.off = 0;
18082 		else
18083 			continue;
18084 
18085 		if (bpf_prog_is_offloaded(env->prog->aux))
18086 			bpf_prog_offload_replace_insn(env, i, &ja);
18087 
18088 		memcpy(insn, &ja, sizeof(ja));
18089 	}
18090 }
18091 
18092 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18093 {
18094 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18095 	int insn_cnt = env->prog->len;
18096 	int i, err;
18097 
18098 	for (i = 0; i < insn_cnt; i++) {
18099 		int j;
18100 
18101 		j = 0;
18102 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18103 			j++;
18104 		if (!j)
18105 			continue;
18106 
18107 		err = verifier_remove_insns(env, i, j);
18108 		if (err)
18109 			return err;
18110 		insn_cnt = env->prog->len;
18111 	}
18112 
18113 	return 0;
18114 }
18115 
18116 static int opt_remove_nops(struct bpf_verifier_env *env)
18117 {
18118 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18119 	struct bpf_insn *insn = env->prog->insnsi;
18120 	int insn_cnt = env->prog->len;
18121 	int i, err;
18122 
18123 	for (i = 0; i < insn_cnt; i++) {
18124 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18125 			continue;
18126 
18127 		err = verifier_remove_insns(env, i, 1);
18128 		if (err)
18129 			return err;
18130 		insn_cnt--;
18131 		i--;
18132 	}
18133 
18134 	return 0;
18135 }
18136 
18137 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18138 					 const union bpf_attr *attr)
18139 {
18140 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18141 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18142 	int i, patch_len, delta = 0, len = env->prog->len;
18143 	struct bpf_insn *insns = env->prog->insnsi;
18144 	struct bpf_prog *new_prog;
18145 	bool rnd_hi32;
18146 
18147 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18148 	zext_patch[1] = BPF_ZEXT_REG(0);
18149 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18150 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18151 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18152 	for (i = 0; i < len; i++) {
18153 		int adj_idx = i + delta;
18154 		struct bpf_insn insn;
18155 		int load_reg;
18156 
18157 		insn = insns[adj_idx];
18158 		load_reg = insn_def_regno(&insn);
18159 		if (!aux[adj_idx].zext_dst) {
18160 			u8 code, class;
18161 			u32 imm_rnd;
18162 
18163 			if (!rnd_hi32)
18164 				continue;
18165 
18166 			code = insn.code;
18167 			class = BPF_CLASS(code);
18168 			if (load_reg == -1)
18169 				continue;
18170 
18171 			/* NOTE: arg "reg" (the fourth one) is only used for
18172 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18173 			 *       here.
18174 			 */
18175 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18176 				if (class == BPF_LD &&
18177 				    BPF_MODE(code) == BPF_IMM)
18178 					i++;
18179 				continue;
18180 			}
18181 
18182 			/* ctx load could be transformed into wider load. */
18183 			if (class == BPF_LDX &&
18184 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18185 				continue;
18186 
18187 			imm_rnd = get_random_u32();
18188 			rnd_hi32_patch[0] = insn;
18189 			rnd_hi32_patch[1].imm = imm_rnd;
18190 			rnd_hi32_patch[3].dst_reg = load_reg;
18191 			patch = rnd_hi32_patch;
18192 			patch_len = 4;
18193 			goto apply_patch_buffer;
18194 		}
18195 
18196 		/* Add in an zero-extend instruction if a) the JIT has requested
18197 		 * it or b) it's a CMPXCHG.
18198 		 *
18199 		 * The latter is because: BPF_CMPXCHG always loads a value into
18200 		 * R0, therefore always zero-extends. However some archs'
18201 		 * equivalent instruction only does this load when the
18202 		 * comparison is successful. This detail of CMPXCHG is
18203 		 * orthogonal to the general zero-extension behaviour of the
18204 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18205 		 */
18206 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18207 			continue;
18208 
18209 		/* Zero-extension is done by the caller. */
18210 		if (bpf_pseudo_kfunc_call(&insn))
18211 			continue;
18212 
18213 		if (WARN_ON(load_reg == -1)) {
18214 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18215 			return -EFAULT;
18216 		}
18217 
18218 		zext_patch[0] = insn;
18219 		zext_patch[1].dst_reg = load_reg;
18220 		zext_patch[1].src_reg = load_reg;
18221 		patch = zext_patch;
18222 		patch_len = 2;
18223 apply_patch_buffer:
18224 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18225 		if (!new_prog)
18226 			return -ENOMEM;
18227 		env->prog = new_prog;
18228 		insns = new_prog->insnsi;
18229 		aux = env->insn_aux_data;
18230 		delta += patch_len - 1;
18231 	}
18232 
18233 	return 0;
18234 }
18235 
18236 /* convert load instructions that access fields of a context type into a
18237  * sequence of instructions that access fields of the underlying structure:
18238  *     struct __sk_buff    -> struct sk_buff
18239  *     struct bpf_sock_ops -> struct sock
18240  */
18241 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18242 {
18243 	const struct bpf_verifier_ops *ops = env->ops;
18244 	int i, cnt, size, ctx_field_size, delta = 0;
18245 	const int insn_cnt = env->prog->len;
18246 	struct bpf_insn insn_buf[16], *insn;
18247 	u32 target_size, size_default, off;
18248 	struct bpf_prog *new_prog;
18249 	enum bpf_access_type type;
18250 	bool is_narrower_load;
18251 
18252 	if (ops->gen_prologue || env->seen_direct_write) {
18253 		if (!ops->gen_prologue) {
18254 			verbose(env, "bpf verifier is misconfigured\n");
18255 			return -EINVAL;
18256 		}
18257 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18258 					env->prog);
18259 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18260 			verbose(env, "bpf verifier is misconfigured\n");
18261 			return -EINVAL;
18262 		} else if (cnt) {
18263 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18264 			if (!new_prog)
18265 				return -ENOMEM;
18266 
18267 			env->prog = new_prog;
18268 			delta += cnt - 1;
18269 		}
18270 	}
18271 
18272 	if (bpf_prog_is_offloaded(env->prog->aux))
18273 		return 0;
18274 
18275 	insn = env->prog->insnsi + delta;
18276 
18277 	for (i = 0; i < insn_cnt; i++, insn++) {
18278 		bpf_convert_ctx_access_t convert_ctx_access;
18279 		u8 mode;
18280 
18281 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18282 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18283 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18284 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18285 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18286 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18287 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18288 			type = BPF_READ;
18289 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18290 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18291 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18292 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18293 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18294 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18295 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18296 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18297 			type = BPF_WRITE;
18298 		} else {
18299 			continue;
18300 		}
18301 
18302 		if (type == BPF_WRITE &&
18303 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18304 			struct bpf_insn patch[] = {
18305 				*insn,
18306 				BPF_ST_NOSPEC(),
18307 			};
18308 
18309 			cnt = ARRAY_SIZE(patch);
18310 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18311 			if (!new_prog)
18312 				return -ENOMEM;
18313 
18314 			delta    += cnt - 1;
18315 			env->prog = new_prog;
18316 			insn      = new_prog->insnsi + i + delta;
18317 			continue;
18318 		}
18319 
18320 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18321 		case PTR_TO_CTX:
18322 			if (!ops->convert_ctx_access)
18323 				continue;
18324 			convert_ctx_access = ops->convert_ctx_access;
18325 			break;
18326 		case PTR_TO_SOCKET:
18327 		case PTR_TO_SOCK_COMMON:
18328 			convert_ctx_access = bpf_sock_convert_ctx_access;
18329 			break;
18330 		case PTR_TO_TCP_SOCK:
18331 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18332 			break;
18333 		case PTR_TO_XDP_SOCK:
18334 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18335 			break;
18336 		case PTR_TO_BTF_ID:
18337 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18338 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18339 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18340 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18341 		 * any faults for loads into such types. BPF_WRITE is disallowed
18342 		 * for this case.
18343 		 */
18344 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18345 			if (type == BPF_READ) {
18346 				if (BPF_MODE(insn->code) == BPF_MEM)
18347 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18348 						     BPF_SIZE((insn)->code);
18349 				else
18350 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18351 						     BPF_SIZE((insn)->code);
18352 				env->prog->aux->num_exentries++;
18353 			}
18354 			continue;
18355 		default:
18356 			continue;
18357 		}
18358 
18359 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18360 		size = BPF_LDST_BYTES(insn);
18361 		mode = BPF_MODE(insn->code);
18362 
18363 		/* If the read access is a narrower load of the field,
18364 		 * convert to a 4/8-byte load, to minimum program type specific
18365 		 * convert_ctx_access changes. If conversion is successful,
18366 		 * we will apply proper mask to the result.
18367 		 */
18368 		is_narrower_load = size < ctx_field_size;
18369 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18370 		off = insn->off;
18371 		if (is_narrower_load) {
18372 			u8 size_code;
18373 
18374 			if (type == BPF_WRITE) {
18375 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18376 				return -EINVAL;
18377 			}
18378 
18379 			size_code = BPF_H;
18380 			if (ctx_field_size == 4)
18381 				size_code = BPF_W;
18382 			else if (ctx_field_size == 8)
18383 				size_code = BPF_DW;
18384 
18385 			insn->off = off & ~(size_default - 1);
18386 			insn->code = BPF_LDX | BPF_MEM | size_code;
18387 		}
18388 
18389 		target_size = 0;
18390 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18391 					 &target_size);
18392 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18393 		    (ctx_field_size && !target_size)) {
18394 			verbose(env, "bpf verifier is misconfigured\n");
18395 			return -EINVAL;
18396 		}
18397 
18398 		if (is_narrower_load && size < target_size) {
18399 			u8 shift = bpf_ctx_narrow_access_offset(
18400 				off, size, size_default) * 8;
18401 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18402 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18403 				return -EINVAL;
18404 			}
18405 			if (ctx_field_size <= 4) {
18406 				if (shift)
18407 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18408 									insn->dst_reg,
18409 									shift);
18410 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18411 								(1 << size * 8) - 1);
18412 			} else {
18413 				if (shift)
18414 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18415 									insn->dst_reg,
18416 									shift);
18417 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18418 								(1ULL << size * 8) - 1);
18419 			}
18420 		}
18421 		if (mode == BPF_MEMSX)
18422 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18423 						       insn->dst_reg, insn->dst_reg,
18424 						       size * 8, 0);
18425 
18426 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18427 		if (!new_prog)
18428 			return -ENOMEM;
18429 
18430 		delta += cnt - 1;
18431 
18432 		/* keep walking new program and skip insns we just inserted */
18433 		env->prog = new_prog;
18434 		insn      = new_prog->insnsi + i + delta;
18435 	}
18436 
18437 	return 0;
18438 }
18439 
18440 static int jit_subprogs(struct bpf_verifier_env *env)
18441 {
18442 	struct bpf_prog *prog = env->prog, **func, *tmp;
18443 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18444 	struct bpf_map *map_ptr;
18445 	struct bpf_insn *insn;
18446 	void *old_bpf_func;
18447 	int err, num_exentries;
18448 
18449 	if (env->subprog_cnt <= 1)
18450 		return 0;
18451 
18452 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18453 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18454 			continue;
18455 
18456 		/* Upon error here we cannot fall back to interpreter but
18457 		 * need a hard reject of the program. Thus -EFAULT is
18458 		 * propagated in any case.
18459 		 */
18460 		subprog = find_subprog(env, i + insn->imm + 1);
18461 		if (subprog < 0) {
18462 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18463 				  i + insn->imm + 1);
18464 			return -EFAULT;
18465 		}
18466 		/* temporarily remember subprog id inside insn instead of
18467 		 * aux_data, since next loop will split up all insns into funcs
18468 		 */
18469 		insn->off = subprog;
18470 		/* remember original imm in case JIT fails and fallback
18471 		 * to interpreter will be needed
18472 		 */
18473 		env->insn_aux_data[i].call_imm = insn->imm;
18474 		/* point imm to __bpf_call_base+1 from JITs point of view */
18475 		insn->imm = 1;
18476 		if (bpf_pseudo_func(insn))
18477 			/* jit (e.g. x86_64) may emit fewer instructions
18478 			 * if it learns a u32 imm is the same as a u64 imm.
18479 			 * Force a non zero here.
18480 			 */
18481 			insn[1].imm = 1;
18482 	}
18483 
18484 	err = bpf_prog_alloc_jited_linfo(prog);
18485 	if (err)
18486 		goto out_undo_insn;
18487 
18488 	err = -ENOMEM;
18489 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18490 	if (!func)
18491 		goto out_undo_insn;
18492 
18493 	for (i = 0; i < env->subprog_cnt; i++) {
18494 		subprog_start = subprog_end;
18495 		subprog_end = env->subprog_info[i + 1].start;
18496 
18497 		len = subprog_end - subprog_start;
18498 		/* bpf_prog_run() doesn't call subprogs directly,
18499 		 * hence main prog stats include the runtime of subprogs.
18500 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18501 		 * func[i]->stats will never be accessed and stays NULL
18502 		 */
18503 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18504 		if (!func[i])
18505 			goto out_free;
18506 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18507 		       len * sizeof(struct bpf_insn));
18508 		func[i]->type = prog->type;
18509 		func[i]->len = len;
18510 		if (bpf_prog_calc_tag(func[i]))
18511 			goto out_free;
18512 		func[i]->is_func = 1;
18513 		func[i]->aux->func_idx = i;
18514 		/* Below members will be freed only at prog->aux */
18515 		func[i]->aux->btf = prog->aux->btf;
18516 		func[i]->aux->func_info = prog->aux->func_info;
18517 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18518 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18519 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18520 
18521 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18522 			struct bpf_jit_poke_descriptor *poke;
18523 
18524 			poke = &prog->aux->poke_tab[j];
18525 			if (poke->insn_idx < subprog_end &&
18526 			    poke->insn_idx >= subprog_start)
18527 				poke->aux = func[i]->aux;
18528 		}
18529 
18530 		func[i]->aux->name[0] = 'F';
18531 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18532 		func[i]->jit_requested = 1;
18533 		func[i]->blinding_requested = prog->blinding_requested;
18534 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18535 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18536 		func[i]->aux->linfo = prog->aux->linfo;
18537 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18538 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18539 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18540 		num_exentries = 0;
18541 		insn = func[i]->insnsi;
18542 		for (j = 0; j < func[i]->len; j++, insn++) {
18543 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18544 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18545 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18546 				num_exentries++;
18547 		}
18548 		func[i]->aux->num_exentries = num_exentries;
18549 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18550 		func[i] = bpf_int_jit_compile(func[i]);
18551 		if (!func[i]->jited) {
18552 			err = -ENOTSUPP;
18553 			goto out_free;
18554 		}
18555 		cond_resched();
18556 	}
18557 
18558 	/* at this point all bpf functions were successfully JITed
18559 	 * now populate all bpf_calls with correct addresses and
18560 	 * run last pass of JIT
18561 	 */
18562 	for (i = 0; i < env->subprog_cnt; i++) {
18563 		insn = func[i]->insnsi;
18564 		for (j = 0; j < func[i]->len; j++, insn++) {
18565 			if (bpf_pseudo_func(insn)) {
18566 				subprog = insn->off;
18567 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18568 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18569 				continue;
18570 			}
18571 			if (!bpf_pseudo_call(insn))
18572 				continue;
18573 			subprog = insn->off;
18574 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18575 		}
18576 
18577 		/* we use the aux data to keep a list of the start addresses
18578 		 * of the JITed images for each function in the program
18579 		 *
18580 		 * for some architectures, such as powerpc64, the imm field
18581 		 * might not be large enough to hold the offset of the start
18582 		 * address of the callee's JITed image from __bpf_call_base
18583 		 *
18584 		 * in such cases, we can lookup the start address of a callee
18585 		 * by using its subprog id, available from the off field of
18586 		 * the call instruction, as an index for this list
18587 		 */
18588 		func[i]->aux->func = func;
18589 		func[i]->aux->func_cnt = env->subprog_cnt;
18590 	}
18591 	for (i = 0; i < env->subprog_cnt; i++) {
18592 		old_bpf_func = func[i]->bpf_func;
18593 		tmp = bpf_int_jit_compile(func[i]);
18594 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18595 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18596 			err = -ENOTSUPP;
18597 			goto out_free;
18598 		}
18599 		cond_resched();
18600 	}
18601 
18602 	/* finally lock prog and jit images for all functions and
18603 	 * populate kallsysm. Begin at the first subprogram, since
18604 	 * bpf_prog_load will add the kallsyms for the main program.
18605 	 */
18606 	for (i = 1; i < env->subprog_cnt; i++) {
18607 		bpf_prog_lock_ro(func[i]);
18608 		bpf_prog_kallsyms_add(func[i]);
18609 	}
18610 
18611 	/* Last step: make now unused interpreter insns from main
18612 	 * prog consistent for later dump requests, so they can
18613 	 * later look the same as if they were interpreted only.
18614 	 */
18615 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18616 		if (bpf_pseudo_func(insn)) {
18617 			insn[0].imm = env->insn_aux_data[i].call_imm;
18618 			insn[1].imm = insn->off;
18619 			insn->off = 0;
18620 			continue;
18621 		}
18622 		if (!bpf_pseudo_call(insn))
18623 			continue;
18624 		insn->off = env->insn_aux_data[i].call_imm;
18625 		subprog = find_subprog(env, i + insn->off + 1);
18626 		insn->imm = subprog;
18627 	}
18628 
18629 	prog->jited = 1;
18630 	prog->bpf_func = func[0]->bpf_func;
18631 	prog->jited_len = func[0]->jited_len;
18632 	prog->aux->extable = func[0]->aux->extable;
18633 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18634 	prog->aux->func = func;
18635 	prog->aux->func_cnt = env->subprog_cnt;
18636 	bpf_prog_jit_attempt_done(prog);
18637 	return 0;
18638 out_free:
18639 	/* We failed JIT'ing, so at this point we need to unregister poke
18640 	 * descriptors from subprogs, so that kernel is not attempting to
18641 	 * patch it anymore as we're freeing the subprog JIT memory.
18642 	 */
18643 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18644 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18645 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18646 	}
18647 	/* At this point we're guaranteed that poke descriptors are not
18648 	 * live anymore. We can just unlink its descriptor table as it's
18649 	 * released with the main prog.
18650 	 */
18651 	for (i = 0; i < env->subprog_cnt; i++) {
18652 		if (!func[i])
18653 			continue;
18654 		func[i]->aux->poke_tab = NULL;
18655 		bpf_jit_free(func[i]);
18656 	}
18657 	kfree(func);
18658 out_undo_insn:
18659 	/* cleanup main prog to be interpreted */
18660 	prog->jit_requested = 0;
18661 	prog->blinding_requested = 0;
18662 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18663 		if (!bpf_pseudo_call(insn))
18664 			continue;
18665 		insn->off = 0;
18666 		insn->imm = env->insn_aux_data[i].call_imm;
18667 	}
18668 	bpf_prog_jit_attempt_done(prog);
18669 	return err;
18670 }
18671 
18672 static int fixup_call_args(struct bpf_verifier_env *env)
18673 {
18674 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18675 	struct bpf_prog *prog = env->prog;
18676 	struct bpf_insn *insn = prog->insnsi;
18677 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18678 	int i, depth;
18679 #endif
18680 	int err = 0;
18681 
18682 	if (env->prog->jit_requested &&
18683 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18684 		err = jit_subprogs(env);
18685 		if (err == 0)
18686 			return 0;
18687 		if (err == -EFAULT)
18688 			return err;
18689 	}
18690 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18691 	if (has_kfunc_call) {
18692 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18693 		return -EINVAL;
18694 	}
18695 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18696 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18697 		 * have to be rejected, since interpreter doesn't support them yet.
18698 		 */
18699 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18700 		return -EINVAL;
18701 	}
18702 	for (i = 0; i < prog->len; i++, insn++) {
18703 		if (bpf_pseudo_func(insn)) {
18704 			/* When JIT fails the progs with callback calls
18705 			 * have to be rejected, since interpreter doesn't support them yet.
18706 			 */
18707 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18708 			return -EINVAL;
18709 		}
18710 
18711 		if (!bpf_pseudo_call(insn))
18712 			continue;
18713 		depth = get_callee_stack_depth(env, insn, i);
18714 		if (depth < 0)
18715 			return depth;
18716 		bpf_patch_call_args(insn, depth);
18717 	}
18718 	err = 0;
18719 #endif
18720 	return err;
18721 }
18722 
18723 /* replace a generic kfunc with a specialized version if necessary */
18724 static void specialize_kfunc(struct bpf_verifier_env *env,
18725 			     u32 func_id, u16 offset, unsigned long *addr)
18726 {
18727 	struct bpf_prog *prog = env->prog;
18728 	bool seen_direct_write;
18729 	void *xdp_kfunc;
18730 	bool is_rdonly;
18731 
18732 	if (bpf_dev_bound_kfunc_id(func_id)) {
18733 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18734 		if (xdp_kfunc) {
18735 			*addr = (unsigned long)xdp_kfunc;
18736 			return;
18737 		}
18738 		/* fallback to default kfunc when not supported by netdev */
18739 	}
18740 
18741 	if (offset)
18742 		return;
18743 
18744 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18745 		seen_direct_write = env->seen_direct_write;
18746 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18747 
18748 		if (is_rdonly)
18749 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18750 
18751 		/* restore env->seen_direct_write to its original value, since
18752 		 * may_access_direct_pkt_data mutates it
18753 		 */
18754 		env->seen_direct_write = seen_direct_write;
18755 	}
18756 }
18757 
18758 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18759 					    u16 struct_meta_reg,
18760 					    u16 node_offset_reg,
18761 					    struct bpf_insn *insn,
18762 					    struct bpf_insn *insn_buf,
18763 					    int *cnt)
18764 {
18765 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18766 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18767 
18768 	insn_buf[0] = addr[0];
18769 	insn_buf[1] = addr[1];
18770 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18771 	insn_buf[3] = *insn;
18772 	*cnt = 4;
18773 }
18774 
18775 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18776 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18777 {
18778 	const struct bpf_kfunc_desc *desc;
18779 
18780 	if (!insn->imm) {
18781 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18782 		return -EINVAL;
18783 	}
18784 
18785 	*cnt = 0;
18786 
18787 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18788 	 * __bpf_call_base, unless the JIT needs to call functions that are
18789 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18790 	 */
18791 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18792 	if (!desc) {
18793 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18794 			insn->imm);
18795 		return -EFAULT;
18796 	}
18797 
18798 	if (!bpf_jit_supports_far_kfunc_call())
18799 		insn->imm = BPF_CALL_IMM(desc->addr);
18800 	if (insn->off)
18801 		return 0;
18802 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18803 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18804 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18805 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18806 
18807 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18808 		insn_buf[1] = addr[0];
18809 		insn_buf[2] = addr[1];
18810 		insn_buf[3] = *insn;
18811 		*cnt = 4;
18812 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18813 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18814 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18815 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18816 
18817 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18818 		    !kptr_struct_meta) {
18819 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18820 				insn_idx);
18821 			return -EFAULT;
18822 		}
18823 
18824 		insn_buf[0] = addr[0];
18825 		insn_buf[1] = addr[1];
18826 		insn_buf[2] = *insn;
18827 		*cnt = 3;
18828 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18829 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18830 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18831 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18832 		int struct_meta_reg = BPF_REG_3;
18833 		int node_offset_reg = BPF_REG_4;
18834 
18835 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18836 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18837 			struct_meta_reg = BPF_REG_4;
18838 			node_offset_reg = BPF_REG_5;
18839 		}
18840 
18841 		if (!kptr_struct_meta) {
18842 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18843 				insn_idx);
18844 			return -EFAULT;
18845 		}
18846 
18847 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18848 						node_offset_reg, insn, insn_buf, cnt);
18849 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18850 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18851 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18852 		*cnt = 1;
18853 	}
18854 	return 0;
18855 }
18856 
18857 /* Do various post-verification rewrites in a single program pass.
18858  * These rewrites simplify JIT and interpreter implementations.
18859  */
18860 static int do_misc_fixups(struct bpf_verifier_env *env)
18861 {
18862 	struct bpf_prog *prog = env->prog;
18863 	enum bpf_attach_type eatype = prog->expected_attach_type;
18864 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18865 	struct bpf_insn *insn = prog->insnsi;
18866 	const struct bpf_func_proto *fn;
18867 	const int insn_cnt = prog->len;
18868 	const struct bpf_map_ops *ops;
18869 	struct bpf_insn_aux_data *aux;
18870 	struct bpf_insn insn_buf[16];
18871 	struct bpf_prog *new_prog;
18872 	struct bpf_map *map_ptr;
18873 	int i, ret, cnt, delta = 0;
18874 
18875 	for (i = 0; i < insn_cnt; i++, insn++) {
18876 		/* Make divide-by-zero exceptions impossible. */
18877 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18878 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18879 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18880 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18881 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18882 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18883 			struct bpf_insn *patchlet;
18884 			struct bpf_insn chk_and_div[] = {
18885 				/* [R,W]x div 0 -> 0 */
18886 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18887 					     BPF_JNE | BPF_K, insn->src_reg,
18888 					     0, 2, 0),
18889 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18890 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18891 				*insn,
18892 			};
18893 			struct bpf_insn chk_and_mod[] = {
18894 				/* [R,W]x mod 0 -> [R,W]x */
18895 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18896 					     BPF_JEQ | BPF_K, insn->src_reg,
18897 					     0, 1 + (is64 ? 0 : 1), 0),
18898 				*insn,
18899 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18900 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18901 			};
18902 
18903 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18904 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18905 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18906 
18907 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18908 			if (!new_prog)
18909 				return -ENOMEM;
18910 
18911 			delta    += cnt - 1;
18912 			env->prog = prog = new_prog;
18913 			insn      = new_prog->insnsi + i + delta;
18914 			continue;
18915 		}
18916 
18917 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18918 		if (BPF_CLASS(insn->code) == BPF_LD &&
18919 		    (BPF_MODE(insn->code) == BPF_ABS ||
18920 		     BPF_MODE(insn->code) == BPF_IND)) {
18921 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18922 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18923 				verbose(env, "bpf verifier is misconfigured\n");
18924 				return -EINVAL;
18925 			}
18926 
18927 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18928 			if (!new_prog)
18929 				return -ENOMEM;
18930 
18931 			delta    += cnt - 1;
18932 			env->prog = prog = new_prog;
18933 			insn      = new_prog->insnsi + i + delta;
18934 			continue;
18935 		}
18936 
18937 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18938 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18939 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18940 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18941 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18942 			struct bpf_insn *patch = &insn_buf[0];
18943 			bool issrc, isneg, isimm;
18944 			u32 off_reg;
18945 
18946 			aux = &env->insn_aux_data[i + delta];
18947 			if (!aux->alu_state ||
18948 			    aux->alu_state == BPF_ALU_NON_POINTER)
18949 				continue;
18950 
18951 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18952 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18953 				BPF_ALU_SANITIZE_SRC;
18954 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18955 
18956 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18957 			if (isimm) {
18958 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18959 			} else {
18960 				if (isneg)
18961 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18962 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18963 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18964 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18965 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18966 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18967 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18968 			}
18969 			if (!issrc)
18970 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18971 			insn->src_reg = BPF_REG_AX;
18972 			if (isneg)
18973 				insn->code = insn->code == code_add ?
18974 					     code_sub : code_add;
18975 			*patch++ = *insn;
18976 			if (issrc && isneg && !isimm)
18977 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18978 			cnt = patch - insn_buf;
18979 
18980 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18981 			if (!new_prog)
18982 				return -ENOMEM;
18983 
18984 			delta    += cnt - 1;
18985 			env->prog = prog = new_prog;
18986 			insn      = new_prog->insnsi + i + delta;
18987 			continue;
18988 		}
18989 
18990 		if (insn->code != (BPF_JMP | BPF_CALL))
18991 			continue;
18992 		if (insn->src_reg == BPF_PSEUDO_CALL)
18993 			continue;
18994 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18995 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18996 			if (ret)
18997 				return ret;
18998 			if (cnt == 0)
18999 				continue;
19000 
19001 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19002 			if (!new_prog)
19003 				return -ENOMEM;
19004 
19005 			delta	 += cnt - 1;
19006 			env->prog = prog = new_prog;
19007 			insn	  = new_prog->insnsi + i + delta;
19008 			continue;
19009 		}
19010 
19011 		if (insn->imm == BPF_FUNC_get_route_realm)
19012 			prog->dst_needed = 1;
19013 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19014 			bpf_user_rnd_init_once();
19015 		if (insn->imm == BPF_FUNC_override_return)
19016 			prog->kprobe_override = 1;
19017 		if (insn->imm == BPF_FUNC_tail_call) {
19018 			/* If we tail call into other programs, we
19019 			 * cannot make any assumptions since they can
19020 			 * be replaced dynamically during runtime in
19021 			 * the program array.
19022 			 */
19023 			prog->cb_access = 1;
19024 			if (!allow_tail_call_in_subprogs(env))
19025 				prog->aux->stack_depth = MAX_BPF_STACK;
19026 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19027 
19028 			/* mark bpf_tail_call as different opcode to avoid
19029 			 * conditional branch in the interpreter for every normal
19030 			 * call and to prevent accidental JITing by JIT compiler
19031 			 * that doesn't support bpf_tail_call yet
19032 			 */
19033 			insn->imm = 0;
19034 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19035 
19036 			aux = &env->insn_aux_data[i + delta];
19037 			if (env->bpf_capable && !prog->blinding_requested &&
19038 			    prog->jit_requested &&
19039 			    !bpf_map_key_poisoned(aux) &&
19040 			    !bpf_map_ptr_poisoned(aux) &&
19041 			    !bpf_map_ptr_unpriv(aux)) {
19042 				struct bpf_jit_poke_descriptor desc = {
19043 					.reason = BPF_POKE_REASON_TAIL_CALL,
19044 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19045 					.tail_call.key = bpf_map_key_immediate(aux),
19046 					.insn_idx = i + delta,
19047 				};
19048 
19049 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19050 				if (ret < 0) {
19051 					verbose(env, "adding tail call poke descriptor failed\n");
19052 					return ret;
19053 				}
19054 
19055 				insn->imm = ret + 1;
19056 				continue;
19057 			}
19058 
19059 			if (!bpf_map_ptr_unpriv(aux))
19060 				continue;
19061 
19062 			/* instead of changing every JIT dealing with tail_call
19063 			 * emit two extra insns:
19064 			 * if (index >= max_entries) goto out;
19065 			 * index &= array->index_mask;
19066 			 * to avoid out-of-bounds cpu speculation
19067 			 */
19068 			if (bpf_map_ptr_poisoned(aux)) {
19069 				verbose(env, "tail_call abusing map_ptr\n");
19070 				return -EINVAL;
19071 			}
19072 
19073 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19074 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19075 						  map_ptr->max_entries, 2);
19076 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19077 						    container_of(map_ptr,
19078 								 struct bpf_array,
19079 								 map)->index_mask);
19080 			insn_buf[2] = *insn;
19081 			cnt = 3;
19082 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19083 			if (!new_prog)
19084 				return -ENOMEM;
19085 
19086 			delta    += cnt - 1;
19087 			env->prog = prog = new_prog;
19088 			insn      = new_prog->insnsi + i + delta;
19089 			continue;
19090 		}
19091 
19092 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19093 			/* The verifier will process callback_fn as many times as necessary
19094 			 * with different maps and the register states prepared by
19095 			 * set_timer_callback_state will be accurate.
19096 			 *
19097 			 * The following use case is valid:
19098 			 *   map1 is shared by prog1, prog2, prog3.
19099 			 *   prog1 calls bpf_timer_init for some map1 elements
19100 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19101 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19102 			 *   prog3 calls bpf_timer_start for some map1 elements.
19103 			 *     Those that were not both bpf_timer_init-ed and
19104 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19105 			 */
19106 			struct bpf_insn ld_addrs[2] = {
19107 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19108 			};
19109 
19110 			insn_buf[0] = ld_addrs[0];
19111 			insn_buf[1] = ld_addrs[1];
19112 			insn_buf[2] = *insn;
19113 			cnt = 3;
19114 
19115 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19116 			if (!new_prog)
19117 				return -ENOMEM;
19118 
19119 			delta    += cnt - 1;
19120 			env->prog = prog = new_prog;
19121 			insn      = new_prog->insnsi + i + delta;
19122 			goto patch_call_imm;
19123 		}
19124 
19125 		if (is_storage_get_function(insn->imm)) {
19126 			if (!env->prog->aux->sleepable ||
19127 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19128 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19129 			else
19130 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19131 			insn_buf[1] = *insn;
19132 			cnt = 2;
19133 
19134 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19135 			if (!new_prog)
19136 				return -ENOMEM;
19137 
19138 			delta += cnt - 1;
19139 			env->prog = prog = new_prog;
19140 			insn = new_prog->insnsi + i + delta;
19141 			goto patch_call_imm;
19142 		}
19143 
19144 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19145 		 * and other inlining handlers are currently limited to 64 bit
19146 		 * only.
19147 		 */
19148 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19149 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19150 		     insn->imm == BPF_FUNC_map_update_elem ||
19151 		     insn->imm == BPF_FUNC_map_delete_elem ||
19152 		     insn->imm == BPF_FUNC_map_push_elem   ||
19153 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19154 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19155 		     insn->imm == BPF_FUNC_redirect_map    ||
19156 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19157 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19158 			aux = &env->insn_aux_data[i + delta];
19159 			if (bpf_map_ptr_poisoned(aux))
19160 				goto patch_call_imm;
19161 
19162 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19163 			ops = map_ptr->ops;
19164 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19165 			    ops->map_gen_lookup) {
19166 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19167 				if (cnt == -EOPNOTSUPP)
19168 					goto patch_map_ops_generic;
19169 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19170 					verbose(env, "bpf verifier is misconfigured\n");
19171 					return -EINVAL;
19172 				}
19173 
19174 				new_prog = bpf_patch_insn_data(env, i + delta,
19175 							       insn_buf, cnt);
19176 				if (!new_prog)
19177 					return -ENOMEM;
19178 
19179 				delta    += cnt - 1;
19180 				env->prog = prog = new_prog;
19181 				insn      = new_prog->insnsi + i + delta;
19182 				continue;
19183 			}
19184 
19185 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19186 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19187 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19188 				     (long (*)(struct bpf_map *map, void *key))NULL));
19189 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19190 				     (long (*)(struct bpf_map *map, void *key, void *value,
19191 					      u64 flags))NULL));
19192 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19193 				     (long (*)(struct bpf_map *map, void *value,
19194 					      u64 flags))NULL));
19195 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19196 				     (long (*)(struct bpf_map *map, void *value))NULL));
19197 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19198 				     (long (*)(struct bpf_map *map, void *value))NULL));
19199 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19200 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19201 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19202 				     (long (*)(struct bpf_map *map,
19203 					      bpf_callback_t callback_fn,
19204 					      void *callback_ctx,
19205 					      u64 flags))NULL));
19206 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19207 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19208 
19209 patch_map_ops_generic:
19210 			switch (insn->imm) {
19211 			case BPF_FUNC_map_lookup_elem:
19212 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19213 				continue;
19214 			case BPF_FUNC_map_update_elem:
19215 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19216 				continue;
19217 			case BPF_FUNC_map_delete_elem:
19218 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19219 				continue;
19220 			case BPF_FUNC_map_push_elem:
19221 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19222 				continue;
19223 			case BPF_FUNC_map_pop_elem:
19224 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19225 				continue;
19226 			case BPF_FUNC_map_peek_elem:
19227 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19228 				continue;
19229 			case BPF_FUNC_redirect_map:
19230 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19231 				continue;
19232 			case BPF_FUNC_for_each_map_elem:
19233 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19234 				continue;
19235 			case BPF_FUNC_map_lookup_percpu_elem:
19236 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19237 				continue;
19238 			}
19239 
19240 			goto patch_call_imm;
19241 		}
19242 
19243 		/* Implement bpf_jiffies64 inline. */
19244 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19245 		    insn->imm == BPF_FUNC_jiffies64) {
19246 			struct bpf_insn ld_jiffies_addr[2] = {
19247 				BPF_LD_IMM64(BPF_REG_0,
19248 					     (unsigned long)&jiffies),
19249 			};
19250 
19251 			insn_buf[0] = ld_jiffies_addr[0];
19252 			insn_buf[1] = ld_jiffies_addr[1];
19253 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19254 						  BPF_REG_0, 0);
19255 			cnt = 3;
19256 
19257 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19258 						       cnt);
19259 			if (!new_prog)
19260 				return -ENOMEM;
19261 
19262 			delta    += cnt - 1;
19263 			env->prog = prog = new_prog;
19264 			insn      = new_prog->insnsi + i + delta;
19265 			continue;
19266 		}
19267 
19268 		/* Implement bpf_get_func_arg inline. */
19269 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19270 		    insn->imm == BPF_FUNC_get_func_arg) {
19271 			/* Load nr_args from ctx - 8 */
19272 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19273 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19274 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19275 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19276 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19277 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19278 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19279 			insn_buf[7] = BPF_JMP_A(1);
19280 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19281 			cnt = 9;
19282 
19283 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19284 			if (!new_prog)
19285 				return -ENOMEM;
19286 
19287 			delta    += cnt - 1;
19288 			env->prog = prog = new_prog;
19289 			insn      = new_prog->insnsi + i + delta;
19290 			continue;
19291 		}
19292 
19293 		/* Implement bpf_get_func_ret inline. */
19294 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19295 		    insn->imm == BPF_FUNC_get_func_ret) {
19296 			if (eatype == BPF_TRACE_FEXIT ||
19297 			    eatype == BPF_MODIFY_RETURN) {
19298 				/* Load nr_args from ctx - 8 */
19299 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19300 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19301 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19302 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19303 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19304 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19305 				cnt = 6;
19306 			} else {
19307 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19308 				cnt = 1;
19309 			}
19310 
19311 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19312 			if (!new_prog)
19313 				return -ENOMEM;
19314 
19315 			delta    += cnt - 1;
19316 			env->prog = prog = new_prog;
19317 			insn      = new_prog->insnsi + i + delta;
19318 			continue;
19319 		}
19320 
19321 		/* Implement get_func_arg_cnt inline. */
19322 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19323 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19324 			/* Load nr_args from ctx - 8 */
19325 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19326 
19327 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19328 			if (!new_prog)
19329 				return -ENOMEM;
19330 
19331 			env->prog = prog = new_prog;
19332 			insn      = new_prog->insnsi + i + delta;
19333 			continue;
19334 		}
19335 
19336 		/* Implement bpf_get_func_ip inline. */
19337 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19338 		    insn->imm == BPF_FUNC_get_func_ip) {
19339 			/* Load IP address from ctx - 16 */
19340 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19341 
19342 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19343 			if (!new_prog)
19344 				return -ENOMEM;
19345 
19346 			env->prog = prog = new_prog;
19347 			insn      = new_prog->insnsi + i + delta;
19348 			continue;
19349 		}
19350 
19351 patch_call_imm:
19352 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19353 		/* all functions that have prototype and verifier allowed
19354 		 * programs to call them, must be real in-kernel functions
19355 		 */
19356 		if (!fn->func) {
19357 			verbose(env,
19358 				"kernel subsystem misconfigured func %s#%d\n",
19359 				func_id_name(insn->imm), insn->imm);
19360 			return -EFAULT;
19361 		}
19362 		insn->imm = fn->func - __bpf_call_base;
19363 	}
19364 
19365 	/* Since poke tab is now finalized, publish aux to tracker. */
19366 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19367 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19368 		if (!map_ptr->ops->map_poke_track ||
19369 		    !map_ptr->ops->map_poke_untrack ||
19370 		    !map_ptr->ops->map_poke_run) {
19371 			verbose(env, "bpf verifier is misconfigured\n");
19372 			return -EINVAL;
19373 		}
19374 
19375 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19376 		if (ret < 0) {
19377 			verbose(env, "tracking tail call prog failed\n");
19378 			return ret;
19379 		}
19380 	}
19381 
19382 	sort_kfunc_descs_by_imm_off(env->prog);
19383 
19384 	return 0;
19385 }
19386 
19387 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19388 					int position,
19389 					s32 stack_base,
19390 					u32 callback_subprogno,
19391 					u32 *cnt)
19392 {
19393 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19394 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19395 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19396 	int reg_loop_max = BPF_REG_6;
19397 	int reg_loop_cnt = BPF_REG_7;
19398 	int reg_loop_ctx = BPF_REG_8;
19399 
19400 	struct bpf_prog *new_prog;
19401 	u32 callback_start;
19402 	u32 call_insn_offset;
19403 	s32 callback_offset;
19404 
19405 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19406 	 * be careful to modify this code in sync.
19407 	 */
19408 	struct bpf_insn insn_buf[] = {
19409 		/* Return error and jump to the end of the patch if
19410 		 * expected number of iterations is too big.
19411 		 */
19412 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19413 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19414 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19415 		/* spill R6, R7, R8 to use these as loop vars */
19416 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19417 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19418 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19419 		/* initialize loop vars */
19420 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19421 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19422 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19423 		/* loop header,
19424 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19425 		 */
19426 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19427 		/* callback call,
19428 		 * correct callback offset would be set after patching
19429 		 */
19430 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19431 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19432 		BPF_CALL_REL(0),
19433 		/* increment loop counter */
19434 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19435 		/* jump to loop header if callback returned 0 */
19436 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19437 		/* return value of bpf_loop,
19438 		 * set R0 to the number of iterations
19439 		 */
19440 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19441 		/* restore original values of R6, R7, R8 */
19442 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19443 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19444 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19445 	};
19446 
19447 	*cnt = ARRAY_SIZE(insn_buf);
19448 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19449 	if (!new_prog)
19450 		return new_prog;
19451 
19452 	/* callback start is known only after patching */
19453 	callback_start = env->subprog_info[callback_subprogno].start;
19454 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19455 	call_insn_offset = position + 12;
19456 	callback_offset = callback_start - call_insn_offset - 1;
19457 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19458 
19459 	return new_prog;
19460 }
19461 
19462 static bool is_bpf_loop_call(struct bpf_insn *insn)
19463 {
19464 	return insn->code == (BPF_JMP | BPF_CALL) &&
19465 		insn->src_reg == 0 &&
19466 		insn->imm == BPF_FUNC_loop;
19467 }
19468 
19469 /* For all sub-programs in the program (including main) check
19470  * insn_aux_data to see if there are bpf_loop calls that require
19471  * inlining. If such calls are found the calls are replaced with a
19472  * sequence of instructions produced by `inline_bpf_loop` function and
19473  * subprog stack_depth is increased by the size of 3 registers.
19474  * This stack space is used to spill values of the R6, R7, R8.  These
19475  * registers are used to store the loop bound, counter and context
19476  * variables.
19477  */
19478 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19479 {
19480 	struct bpf_subprog_info *subprogs = env->subprog_info;
19481 	int i, cur_subprog = 0, cnt, delta = 0;
19482 	struct bpf_insn *insn = env->prog->insnsi;
19483 	int insn_cnt = env->prog->len;
19484 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19485 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19486 	u16 stack_depth_extra = 0;
19487 
19488 	for (i = 0; i < insn_cnt; i++, insn++) {
19489 		struct bpf_loop_inline_state *inline_state =
19490 			&env->insn_aux_data[i + delta].loop_inline_state;
19491 
19492 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19493 			struct bpf_prog *new_prog;
19494 
19495 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19496 			new_prog = inline_bpf_loop(env,
19497 						   i + delta,
19498 						   -(stack_depth + stack_depth_extra),
19499 						   inline_state->callback_subprogno,
19500 						   &cnt);
19501 			if (!new_prog)
19502 				return -ENOMEM;
19503 
19504 			delta     += cnt - 1;
19505 			env->prog  = new_prog;
19506 			insn       = new_prog->insnsi + i + delta;
19507 		}
19508 
19509 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19510 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19511 			cur_subprog++;
19512 			stack_depth = subprogs[cur_subprog].stack_depth;
19513 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19514 			stack_depth_extra = 0;
19515 		}
19516 	}
19517 
19518 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19519 
19520 	return 0;
19521 }
19522 
19523 static void free_states(struct bpf_verifier_env *env)
19524 {
19525 	struct bpf_verifier_state_list *sl, *sln;
19526 	int i;
19527 
19528 	sl = env->free_list;
19529 	while (sl) {
19530 		sln = sl->next;
19531 		free_verifier_state(&sl->state, false);
19532 		kfree(sl);
19533 		sl = sln;
19534 	}
19535 	env->free_list = NULL;
19536 
19537 	if (!env->explored_states)
19538 		return;
19539 
19540 	for (i = 0; i < state_htab_size(env); i++) {
19541 		sl = env->explored_states[i];
19542 
19543 		while (sl) {
19544 			sln = sl->next;
19545 			free_verifier_state(&sl->state, false);
19546 			kfree(sl);
19547 			sl = sln;
19548 		}
19549 		env->explored_states[i] = NULL;
19550 	}
19551 }
19552 
19553 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19554 {
19555 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19556 	struct bpf_verifier_state *state;
19557 	struct bpf_reg_state *regs;
19558 	int ret, i;
19559 
19560 	env->prev_linfo = NULL;
19561 	env->pass_cnt++;
19562 
19563 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19564 	if (!state)
19565 		return -ENOMEM;
19566 	state->curframe = 0;
19567 	state->speculative = false;
19568 	state->branches = 1;
19569 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19570 	if (!state->frame[0]) {
19571 		kfree(state);
19572 		return -ENOMEM;
19573 	}
19574 	env->cur_state = state;
19575 	init_func_state(env, state->frame[0],
19576 			BPF_MAIN_FUNC /* callsite */,
19577 			0 /* frameno */,
19578 			subprog);
19579 	state->first_insn_idx = env->subprog_info[subprog].start;
19580 	state->last_insn_idx = -1;
19581 
19582 	regs = state->frame[state->curframe]->regs;
19583 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19584 		ret = btf_prepare_func_args(env, subprog, regs);
19585 		if (ret)
19586 			goto out;
19587 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19588 			if (regs[i].type == PTR_TO_CTX)
19589 				mark_reg_known_zero(env, regs, i);
19590 			else if (regs[i].type == SCALAR_VALUE)
19591 				mark_reg_unknown(env, regs, i);
19592 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19593 				const u32 mem_size = regs[i].mem_size;
19594 
19595 				mark_reg_known_zero(env, regs, i);
19596 				regs[i].mem_size = mem_size;
19597 				regs[i].id = ++env->id_gen;
19598 			}
19599 		}
19600 	} else {
19601 		/* 1st arg to a function */
19602 		regs[BPF_REG_1].type = PTR_TO_CTX;
19603 		mark_reg_known_zero(env, regs, BPF_REG_1);
19604 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19605 		if (ret == -EFAULT)
19606 			/* unlikely verifier bug. abort.
19607 			 * ret == 0 and ret < 0 are sadly acceptable for
19608 			 * main() function due to backward compatibility.
19609 			 * Like socket filter program may be written as:
19610 			 * int bpf_prog(struct pt_regs *ctx)
19611 			 * and never dereference that ctx in the program.
19612 			 * 'struct pt_regs' is a type mismatch for socket
19613 			 * filter that should be using 'struct __sk_buff'.
19614 			 */
19615 			goto out;
19616 	}
19617 
19618 	ret = do_check(env);
19619 out:
19620 	/* check for NULL is necessary, since cur_state can be freed inside
19621 	 * do_check() under memory pressure.
19622 	 */
19623 	if (env->cur_state) {
19624 		free_verifier_state(env->cur_state, true);
19625 		env->cur_state = NULL;
19626 	}
19627 	while (!pop_stack(env, NULL, NULL, false));
19628 	if (!ret && pop_log)
19629 		bpf_vlog_reset(&env->log, 0);
19630 	free_states(env);
19631 	return ret;
19632 }
19633 
19634 /* Verify all global functions in a BPF program one by one based on their BTF.
19635  * All global functions must pass verification. Otherwise the whole program is rejected.
19636  * Consider:
19637  * int bar(int);
19638  * int foo(int f)
19639  * {
19640  *    return bar(f);
19641  * }
19642  * int bar(int b)
19643  * {
19644  *    ...
19645  * }
19646  * foo() will be verified first for R1=any_scalar_value. During verification it
19647  * will be assumed that bar() already verified successfully and call to bar()
19648  * from foo() will be checked for type match only. Later bar() will be verified
19649  * independently to check that it's safe for R1=any_scalar_value.
19650  */
19651 static int do_check_subprogs(struct bpf_verifier_env *env)
19652 {
19653 	struct bpf_prog_aux *aux = env->prog->aux;
19654 	int i, ret;
19655 
19656 	if (!aux->func_info)
19657 		return 0;
19658 
19659 	for (i = 1; i < env->subprog_cnt; i++) {
19660 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19661 			continue;
19662 		env->insn_idx = env->subprog_info[i].start;
19663 		WARN_ON_ONCE(env->insn_idx == 0);
19664 		ret = do_check_common(env, i);
19665 		if (ret) {
19666 			return ret;
19667 		} else if (env->log.level & BPF_LOG_LEVEL) {
19668 			verbose(env,
19669 				"Func#%d is safe for any args that match its prototype\n",
19670 				i);
19671 		}
19672 	}
19673 	return 0;
19674 }
19675 
19676 static int do_check_main(struct bpf_verifier_env *env)
19677 {
19678 	int ret;
19679 
19680 	env->insn_idx = 0;
19681 	ret = do_check_common(env, 0);
19682 	if (!ret)
19683 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19684 	return ret;
19685 }
19686 
19687 
19688 static void print_verification_stats(struct bpf_verifier_env *env)
19689 {
19690 	int i;
19691 
19692 	if (env->log.level & BPF_LOG_STATS) {
19693 		verbose(env, "verification time %lld usec\n",
19694 			div_u64(env->verification_time, 1000));
19695 		verbose(env, "stack depth ");
19696 		for (i = 0; i < env->subprog_cnt; i++) {
19697 			u32 depth = env->subprog_info[i].stack_depth;
19698 
19699 			verbose(env, "%d", depth);
19700 			if (i + 1 < env->subprog_cnt)
19701 				verbose(env, "+");
19702 		}
19703 		verbose(env, "\n");
19704 	}
19705 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19706 		"total_states %d peak_states %d mark_read %d\n",
19707 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19708 		env->max_states_per_insn, env->total_states,
19709 		env->peak_states, env->longest_mark_read_walk);
19710 }
19711 
19712 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19713 {
19714 	const struct btf_type *t, *func_proto;
19715 	const struct bpf_struct_ops *st_ops;
19716 	const struct btf_member *member;
19717 	struct bpf_prog *prog = env->prog;
19718 	u32 btf_id, member_idx;
19719 	const char *mname;
19720 
19721 	if (!prog->gpl_compatible) {
19722 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19723 		return -EINVAL;
19724 	}
19725 
19726 	btf_id = prog->aux->attach_btf_id;
19727 	st_ops = bpf_struct_ops_find(btf_id);
19728 	if (!st_ops) {
19729 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19730 			btf_id);
19731 		return -ENOTSUPP;
19732 	}
19733 
19734 	t = st_ops->type;
19735 	member_idx = prog->expected_attach_type;
19736 	if (member_idx >= btf_type_vlen(t)) {
19737 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19738 			member_idx, st_ops->name);
19739 		return -EINVAL;
19740 	}
19741 
19742 	member = &btf_type_member(t)[member_idx];
19743 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19744 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19745 					       NULL);
19746 	if (!func_proto) {
19747 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19748 			mname, member_idx, st_ops->name);
19749 		return -EINVAL;
19750 	}
19751 
19752 	if (st_ops->check_member) {
19753 		int err = st_ops->check_member(t, member, prog);
19754 
19755 		if (err) {
19756 			verbose(env, "attach to unsupported member %s of struct %s\n",
19757 				mname, st_ops->name);
19758 			return err;
19759 		}
19760 	}
19761 
19762 	prog->aux->attach_func_proto = func_proto;
19763 	prog->aux->attach_func_name = mname;
19764 	env->ops = st_ops->verifier_ops;
19765 
19766 	return 0;
19767 }
19768 #define SECURITY_PREFIX "security_"
19769 
19770 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19771 {
19772 	if (within_error_injection_list(addr) ||
19773 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19774 		return 0;
19775 
19776 	return -EINVAL;
19777 }
19778 
19779 /* list of non-sleepable functions that are otherwise on
19780  * ALLOW_ERROR_INJECTION list
19781  */
19782 BTF_SET_START(btf_non_sleepable_error_inject)
19783 /* Three functions below can be called from sleepable and non-sleepable context.
19784  * Assume non-sleepable from bpf safety point of view.
19785  */
19786 BTF_ID(func, __filemap_add_folio)
19787 BTF_ID(func, should_fail_alloc_page)
19788 BTF_ID(func, should_failslab)
19789 BTF_SET_END(btf_non_sleepable_error_inject)
19790 
19791 static int check_non_sleepable_error_inject(u32 btf_id)
19792 {
19793 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19794 }
19795 
19796 int bpf_check_attach_target(struct bpf_verifier_log *log,
19797 			    const struct bpf_prog *prog,
19798 			    const struct bpf_prog *tgt_prog,
19799 			    u32 btf_id,
19800 			    struct bpf_attach_target_info *tgt_info)
19801 {
19802 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19803 	const char prefix[] = "btf_trace_";
19804 	int ret = 0, subprog = -1, i;
19805 	const struct btf_type *t;
19806 	bool conservative = true;
19807 	const char *tname;
19808 	struct btf *btf;
19809 	long addr = 0;
19810 	struct module *mod = NULL;
19811 
19812 	if (!btf_id) {
19813 		bpf_log(log, "Tracing programs must provide btf_id\n");
19814 		return -EINVAL;
19815 	}
19816 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19817 	if (!btf) {
19818 		bpf_log(log,
19819 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19820 		return -EINVAL;
19821 	}
19822 	t = btf_type_by_id(btf, btf_id);
19823 	if (!t) {
19824 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19825 		return -EINVAL;
19826 	}
19827 	tname = btf_name_by_offset(btf, t->name_off);
19828 	if (!tname) {
19829 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19830 		return -EINVAL;
19831 	}
19832 	if (tgt_prog) {
19833 		struct bpf_prog_aux *aux = tgt_prog->aux;
19834 
19835 		if (bpf_prog_is_dev_bound(prog->aux) &&
19836 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19837 			bpf_log(log, "Target program bound device mismatch");
19838 			return -EINVAL;
19839 		}
19840 
19841 		for (i = 0; i < aux->func_info_cnt; i++)
19842 			if (aux->func_info[i].type_id == btf_id) {
19843 				subprog = i;
19844 				break;
19845 			}
19846 		if (subprog == -1) {
19847 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19848 			return -EINVAL;
19849 		}
19850 		conservative = aux->func_info_aux[subprog].unreliable;
19851 		if (prog_extension) {
19852 			if (conservative) {
19853 				bpf_log(log,
19854 					"Cannot replace static functions\n");
19855 				return -EINVAL;
19856 			}
19857 			if (!prog->jit_requested) {
19858 				bpf_log(log,
19859 					"Extension programs should be JITed\n");
19860 				return -EINVAL;
19861 			}
19862 		}
19863 		if (!tgt_prog->jited) {
19864 			bpf_log(log, "Can attach to only JITed progs\n");
19865 			return -EINVAL;
19866 		}
19867 		if (tgt_prog->type == prog->type) {
19868 			/* Cannot fentry/fexit another fentry/fexit program.
19869 			 * Cannot attach program extension to another extension.
19870 			 * It's ok to attach fentry/fexit to extension program.
19871 			 */
19872 			bpf_log(log, "Cannot recursively attach\n");
19873 			return -EINVAL;
19874 		}
19875 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19876 		    prog_extension &&
19877 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19878 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19879 			/* Program extensions can extend all program types
19880 			 * except fentry/fexit. The reason is the following.
19881 			 * The fentry/fexit programs are used for performance
19882 			 * analysis, stats and can be attached to any program
19883 			 * type except themselves. When extension program is
19884 			 * replacing XDP function it is necessary to allow
19885 			 * performance analysis of all functions. Both original
19886 			 * XDP program and its program extension. Hence
19887 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19888 			 * allowed. If extending of fentry/fexit was allowed it
19889 			 * would be possible to create long call chain
19890 			 * fentry->extension->fentry->extension beyond
19891 			 * reasonable stack size. Hence extending fentry is not
19892 			 * allowed.
19893 			 */
19894 			bpf_log(log, "Cannot extend fentry/fexit\n");
19895 			return -EINVAL;
19896 		}
19897 	} else {
19898 		if (prog_extension) {
19899 			bpf_log(log, "Cannot replace kernel functions\n");
19900 			return -EINVAL;
19901 		}
19902 	}
19903 
19904 	switch (prog->expected_attach_type) {
19905 	case BPF_TRACE_RAW_TP:
19906 		if (tgt_prog) {
19907 			bpf_log(log,
19908 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19909 			return -EINVAL;
19910 		}
19911 		if (!btf_type_is_typedef(t)) {
19912 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19913 				btf_id);
19914 			return -EINVAL;
19915 		}
19916 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19917 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19918 				btf_id, tname);
19919 			return -EINVAL;
19920 		}
19921 		tname += sizeof(prefix) - 1;
19922 		t = btf_type_by_id(btf, t->type);
19923 		if (!btf_type_is_ptr(t))
19924 			/* should never happen in valid vmlinux build */
19925 			return -EINVAL;
19926 		t = btf_type_by_id(btf, t->type);
19927 		if (!btf_type_is_func_proto(t))
19928 			/* should never happen in valid vmlinux build */
19929 			return -EINVAL;
19930 
19931 		break;
19932 	case BPF_TRACE_ITER:
19933 		if (!btf_type_is_func(t)) {
19934 			bpf_log(log, "attach_btf_id %u is not a function\n",
19935 				btf_id);
19936 			return -EINVAL;
19937 		}
19938 		t = btf_type_by_id(btf, t->type);
19939 		if (!btf_type_is_func_proto(t))
19940 			return -EINVAL;
19941 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19942 		if (ret)
19943 			return ret;
19944 		break;
19945 	default:
19946 		if (!prog_extension)
19947 			return -EINVAL;
19948 		fallthrough;
19949 	case BPF_MODIFY_RETURN:
19950 	case BPF_LSM_MAC:
19951 	case BPF_LSM_CGROUP:
19952 	case BPF_TRACE_FENTRY:
19953 	case BPF_TRACE_FEXIT:
19954 		if (!btf_type_is_func(t)) {
19955 			bpf_log(log, "attach_btf_id %u is not a function\n",
19956 				btf_id);
19957 			return -EINVAL;
19958 		}
19959 		if (prog_extension &&
19960 		    btf_check_type_match(log, prog, btf, t))
19961 			return -EINVAL;
19962 		t = btf_type_by_id(btf, t->type);
19963 		if (!btf_type_is_func_proto(t))
19964 			return -EINVAL;
19965 
19966 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19967 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19968 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19969 			return -EINVAL;
19970 
19971 		if (tgt_prog && conservative)
19972 			t = NULL;
19973 
19974 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19975 		if (ret < 0)
19976 			return ret;
19977 
19978 		if (tgt_prog) {
19979 			if (subprog == 0)
19980 				addr = (long) tgt_prog->bpf_func;
19981 			else
19982 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19983 		} else {
19984 			if (btf_is_module(btf)) {
19985 				mod = btf_try_get_module(btf);
19986 				if (mod)
19987 					addr = find_kallsyms_symbol_value(mod, tname);
19988 				else
19989 					addr = 0;
19990 			} else {
19991 				addr = kallsyms_lookup_name(tname);
19992 			}
19993 			if (!addr) {
19994 				module_put(mod);
19995 				bpf_log(log,
19996 					"The address of function %s cannot be found\n",
19997 					tname);
19998 				return -ENOENT;
19999 			}
20000 		}
20001 
20002 		if (prog->aux->sleepable) {
20003 			ret = -EINVAL;
20004 			switch (prog->type) {
20005 			case BPF_PROG_TYPE_TRACING:
20006 
20007 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20008 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20009 				 */
20010 				if (!check_non_sleepable_error_inject(btf_id) &&
20011 				    within_error_injection_list(addr))
20012 					ret = 0;
20013 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20014 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20015 				 */
20016 				else {
20017 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20018 										prog);
20019 
20020 					if (flags && (*flags & KF_SLEEPABLE))
20021 						ret = 0;
20022 				}
20023 				break;
20024 			case BPF_PROG_TYPE_LSM:
20025 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20026 				 * Only some of them are sleepable.
20027 				 */
20028 				if (bpf_lsm_is_sleepable_hook(btf_id))
20029 					ret = 0;
20030 				break;
20031 			default:
20032 				break;
20033 			}
20034 			if (ret) {
20035 				module_put(mod);
20036 				bpf_log(log, "%s is not sleepable\n", tname);
20037 				return ret;
20038 			}
20039 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20040 			if (tgt_prog) {
20041 				module_put(mod);
20042 				bpf_log(log, "can't modify return codes of BPF programs\n");
20043 				return -EINVAL;
20044 			}
20045 			ret = -EINVAL;
20046 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20047 			    !check_attach_modify_return(addr, tname))
20048 				ret = 0;
20049 			if (ret) {
20050 				module_put(mod);
20051 				bpf_log(log, "%s() is not modifiable\n", tname);
20052 				return ret;
20053 			}
20054 		}
20055 
20056 		break;
20057 	}
20058 	tgt_info->tgt_addr = addr;
20059 	tgt_info->tgt_name = tname;
20060 	tgt_info->tgt_type = t;
20061 	tgt_info->tgt_mod = mod;
20062 	return 0;
20063 }
20064 
20065 BTF_SET_START(btf_id_deny)
20066 BTF_ID_UNUSED
20067 #ifdef CONFIG_SMP
20068 BTF_ID(func, migrate_disable)
20069 BTF_ID(func, migrate_enable)
20070 #endif
20071 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20072 BTF_ID(func, rcu_read_unlock_strict)
20073 #endif
20074 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20075 BTF_ID(func, preempt_count_add)
20076 BTF_ID(func, preempt_count_sub)
20077 #endif
20078 #ifdef CONFIG_PREEMPT_RCU
20079 BTF_ID(func, __rcu_read_lock)
20080 BTF_ID(func, __rcu_read_unlock)
20081 #endif
20082 BTF_SET_END(btf_id_deny)
20083 
20084 static bool can_be_sleepable(struct bpf_prog *prog)
20085 {
20086 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20087 		switch (prog->expected_attach_type) {
20088 		case BPF_TRACE_FENTRY:
20089 		case BPF_TRACE_FEXIT:
20090 		case BPF_MODIFY_RETURN:
20091 		case BPF_TRACE_ITER:
20092 			return true;
20093 		default:
20094 			return false;
20095 		}
20096 	}
20097 	return prog->type == BPF_PROG_TYPE_LSM ||
20098 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20099 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20100 }
20101 
20102 static int check_attach_btf_id(struct bpf_verifier_env *env)
20103 {
20104 	struct bpf_prog *prog = env->prog;
20105 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20106 	struct bpf_attach_target_info tgt_info = {};
20107 	u32 btf_id = prog->aux->attach_btf_id;
20108 	struct bpf_trampoline *tr;
20109 	int ret;
20110 	u64 key;
20111 
20112 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20113 		if (prog->aux->sleepable)
20114 			/* attach_btf_id checked to be zero already */
20115 			return 0;
20116 		verbose(env, "Syscall programs can only be sleepable\n");
20117 		return -EINVAL;
20118 	}
20119 
20120 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20121 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20122 		return -EINVAL;
20123 	}
20124 
20125 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20126 		return check_struct_ops_btf_id(env);
20127 
20128 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20129 	    prog->type != BPF_PROG_TYPE_LSM &&
20130 	    prog->type != BPF_PROG_TYPE_EXT)
20131 		return 0;
20132 
20133 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20134 	if (ret)
20135 		return ret;
20136 
20137 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20138 		/* to make freplace equivalent to their targets, they need to
20139 		 * inherit env->ops and expected_attach_type for the rest of the
20140 		 * verification
20141 		 */
20142 		env->ops = bpf_verifier_ops[tgt_prog->type];
20143 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20144 	}
20145 
20146 	/* store info about the attachment target that will be used later */
20147 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20148 	prog->aux->attach_func_name = tgt_info.tgt_name;
20149 	prog->aux->mod = tgt_info.tgt_mod;
20150 
20151 	if (tgt_prog) {
20152 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20153 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20154 	}
20155 
20156 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20157 		prog->aux->attach_btf_trace = true;
20158 		return 0;
20159 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20160 		if (!bpf_iter_prog_supported(prog))
20161 			return -EINVAL;
20162 		return 0;
20163 	}
20164 
20165 	if (prog->type == BPF_PROG_TYPE_LSM) {
20166 		ret = bpf_lsm_verify_prog(&env->log, prog);
20167 		if (ret < 0)
20168 			return ret;
20169 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20170 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20171 		return -EINVAL;
20172 	}
20173 
20174 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20175 	tr = bpf_trampoline_get(key, &tgt_info);
20176 	if (!tr)
20177 		return -ENOMEM;
20178 
20179 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20180 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20181 
20182 	prog->aux->dst_trampoline = tr;
20183 	return 0;
20184 }
20185 
20186 struct btf *bpf_get_btf_vmlinux(void)
20187 {
20188 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20189 		mutex_lock(&bpf_verifier_lock);
20190 		if (!btf_vmlinux)
20191 			btf_vmlinux = btf_parse_vmlinux();
20192 		mutex_unlock(&bpf_verifier_lock);
20193 	}
20194 	return btf_vmlinux;
20195 }
20196 
20197 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20198 {
20199 	u64 start_time = ktime_get_ns();
20200 	struct bpf_verifier_env *env;
20201 	int i, len, ret = -EINVAL, err;
20202 	u32 log_true_size;
20203 	bool is_priv;
20204 
20205 	/* no program is valid */
20206 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20207 		return -EINVAL;
20208 
20209 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20210 	 * allocate/free it every time bpf_check() is called
20211 	 */
20212 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20213 	if (!env)
20214 		return -ENOMEM;
20215 
20216 	env->bt.env = env;
20217 
20218 	len = (*prog)->len;
20219 	env->insn_aux_data =
20220 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20221 	ret = -ENOMEM;
20222 	if (!env->insn_aux_data)
20223 		goto err_free_env;
20224 	for (i = 0; i < len; i++)
20225 		env->insn_aux_data[i].orig_idx = i;
20226 	env->prog = *prog;
20227 	env->ops = bpf_verifier_ops[env->prog->type];
20228 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20229 	is_priv = bpf_capable();
20230 
20231 	bpf_get_btf_vmlinux();
20232 
20233 	/* grab the mutex to protect few globals used by verifier */
20234 	if (!is_priv)
20235 		mutex_lock(&bpf_verifier_lock);
20236 
20237 	/* user could have requested verbose verifier output
20238 	 * and supplied buffer to store the verification trace
20239 	 */
20240 	ret = bpf_vlog_init(&env->log, attr->log_level,
20241 			    (char __user *) (unsigned long) attr->log_buf,
20242 			    attr->log_size);
20243 	if (ret)
20244 		goto err_unlock;
20245 
20246 	mark_verifier_state_clean(env);
20247 
20248 	if (IS_ERR(btf_vmlinux)) {
20249 		/* Either gcc or pahole or kernel are broken. */
20250 		verbose(env, "in-kernel BTF is malformed\n");
20251 		ret = PTR_ERR(btf_vmlinux);
20252 		goto skip_full_check;
20253 	}
20254 
20255 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20256 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20257 		env->strict_alignment = true;
20258 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20259 		env->strict_alignment = false;
20260 
20261 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20262 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20263 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20264 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20265 	env->bpf_capable = bpf_capable();
20266 
20267 	if (is_priv)
20268 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20269 
20270 	env->explored_states = kvcalloc(state_htab_size(env),
20271 				       sizeof(struct bpf_verifier_state_list *),
20272 				       GFP_USER);
20273 	ret = -ENOMEM;
20274 	if (!env->explored_states)
20275 		goto skip_full_check;
20276 
20277 	ret = add_subprog_and_kfunc(env);
20278 	if (ret < 0)
20279 		goto skip_full_check;
20280 
20281 	ret = check_subprogs(env);
20282 	if (ret < 0)
20283 		goto skip_full_check;
20284 
20285 	ret = check_btf_info(env, attr, uattr);
20286 	if (ret < 0)
20287 		goto skip_full_check;
20288 
20289 	ret = check_attach_btf_id(env);
20290 	if (ret)
20291 		goto skip_full_check;
20292 
20293 	ret = resolve_pseudo_ldimm64(env);
20294 	if (ret < 0)
20295 		goto skip_full_check;
20296 
20297 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20298 		ret = bpf_prog_offload_verifier_prep(env->prog);
20299 		if (ret)
20300 			goto skip_full_check;
20301 	}
20302 
20303 	ret = check_cfg(env);
20304 	if (ret < 0)
20305 		goto skip_full_check;
20306 
20307 	ret = do_check_subprogs(env);
20308 	ret = ret ?: do_check_main(env);
20309 
20310 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20311 		ret = bpf_prog_offload_finalize(env);
20312 
20313 skip_full_check:
20314 	kvfree(env->explored_states);
20315 
20316 	if (ret == 0)
20317 		ret = check_max_stack_depth(env);
20318 
20319 	/* instruction rewrites happen after this point */
20320 	if (ret == 0)
20321 		ret = optimize_bpf_loop(env);
20322 
20323 	if (is_priv) {
20324 		if (ret == 0)
20325 			opt_hard_wire_dead_code_branches(env);
20326 		if (ret == 0)
20327 			ret = opt_remove_dead_code(env);
20328 		if (ret == 0)
20329 			ret = opt_remove_nops(env);
20330 	} else {
20331 		if (ret == 0)
20332 			sanitize_dead_code(env);
20333 	}
20334 
20335 	if (ret == 0)
20336 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20337 		ret = convert_ctx_accesses(env);
20338 
20339 	if (ret == 0)
20340 		ret = do_misc_fixups(env);
20341 
20342 	/* do 32-bit optimization after insn patching has done so those patched
20343 	 * insns could be handled correctly.
20344 	 */
20345 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20346 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20347 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20348 								     : false;
20349 	}
20350 
20351 	if (ret == 0)
20352 		ret = fixup_call_args(env);
20353 
20354 	env->verification_time = ktime_get_ns() - start_time;
20355 	print_verification_stats(env);
20356 	env->prog->aux->verified_insns = env->insn_processed;
20357 
20358 	/* preserve original error even if log finalization is successful */
20359 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20360 	if (err)
20361 		ret = err;
20362 
20363 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20364 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20365 				  &log_true_size, sizeof(log_true_size))) {
20366 		ret = -EFAULT;
20367 		goto err_release_maps;
20368 	}
20369 
20370 	if (ret)
20371 		goto err_release_maps;
20372 
20373 	if (env->used_map_cnt) {
20374 		/* if program passed verifier, update used_maps in bpf_prog_info */
20375 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20376 							  sizeof(env->used_maps[0]),
20377 							  GFP_KERNEL);
20378 
20379 		if (!env->prog->aux->used_maps) {
20380 			ret = -ENOMEM;
20381 			goto err_release_maps;
20382 		}
20383 
20384 		memcpy(env->prog->aux->used_maps, env->used_maps,
20385 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20386 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20387 	}
20388 	if (env->used_btf_cnt) {
20389 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20390 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20391 							  sizeof(env->used_btfs[0]),
20392 							  GFP_KERNEL);
20393 		if (!env->prog->aux->used_btfs) {
20394 			ret = -ENOMEM;
20395 			goto err_release_maps;
20396 		}
20397 
20398 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20399 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20400 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20401 	}
20402 	if (env->used_map_cnt || env->used_btf_cnt) {
20403 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20404 		 * bpf_ld_imm64 instructions
20405 		 */
20406 		convert_pseudo_ld_imm64(env);
20407 	}
20408 
20409 	adjust_btf_func(env);
20410 
20411 err_release_maps:
20412 	if (!env->prog->aux->used_maps)
20413 		/* if we didn't copy map pointers into bpf_prog_info, release
20414 		 * them now. Otherwise free_used_maps() will release them.
20415 		 */
20416 		release_maps(env);
20417 	if (!env->prog->aux->used_btfs)
20418 		release_btfs(env);
20419 
20420 	/* extension progs temporarily inherit the attach_type of their targets
20421 	   for verification purposes, so set it back to zero before returning
20422 	 */
20423 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20424 		env->prog->expected_attach_type = 0;
20425 
20426 	*prog = env->prog;
20427 err_unlock:
20428 	if (!is_priv)
20429 		mutex_unlock(&bpf_verifier_lock);
20430 	vfree(env->insn_aux_data);
20431 err_free_env:
20432 	kfree(env);
20433 	return ret;
20434 }
20435