xref: /openbmc/linux/kernel/bpf/verifier.c (revision 2c733bb7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 }
2543 
2544 #define DEF_NOT_SUBREG	(0)
2545 static void init_reg_state(struct bpf_verifier_env *env,
2546 			   struct bpf_func_state *state)
2547 {
2548 	struct bpf_reg_state *regs = state->regs;
2549 	int i;
2550 
2551 	for (i = 0; i < MAX_BPF_REG; i++) {
2552 		mark_reg_not_init(env, regs, i);
2553 		regs[i].live = REG_LIVE_NONE;
2554 		regs[i].parent = NULL;
2555 		regs[i].subreg_def = DEF_NOT_SUBREG;
2556 	}
2557 
2558 	/* frame pointer */
2559 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2560 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2561 	regs[BPF_REG_FP].frameno = state->frameno;
2562 }
2563 
2564 #define BPF_MAIN_FUNC (-1)
2565 static void init_func_state(struct bpf_verifier_env *env,
2566 			    struct bpf_func_state *state,
2567 			    int callsite, int frameno, int subprogno)
2568 {
2569 	state->callsite = callsite;
2570 	state->frameno = frameno;
2571 	state->subprogno = subprogno;
2572 	state->callback_ret_range = tnum_range(0, 0);
2573 	init_reg_state(env, state);
2574 	mark_verifier_state_scratched(env);
2575 }
2576 
2577 /* Similar to push_stack(), but for async callbacks */
2578 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2579 						int insn_idx, int prev_insn_idx,
2580 						int subprog)
2581 {
2582 	struct bpf_verifier_stack_elem *elem;
2583 	struct bpf_func_state *frame;
2584 
2585 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2586 	if (!elem)
2587 		goto err;
2588 
2589 	elem->insn_idx = insn_idx;
2590 	elem->prev_insn_idx = prev_insn_idx;
2591 	elem->next = env->head;
2592 	elem->log_pos = env->log.end_pos;
2593 	env->head = elem;
2594 	env->stack_size++;
2595 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2596 		verbose(env,
2597 			"The sequence of %d jumps is too complex for async cb.\n",
2598 			env->stack_size);
2599 		goto err;
2600 	}
2601 	/* Unlike push_stack() do not copy_verifier_state().
2602 	 * The caller state doesn't matter.
2603 	 * This is async callback. It starts in a fresh stack.
2604 	 * Initialize it similar to do_check_common().
2605 	 */
2606 	elem->st.branches = 1;
2607 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2608 	if (!frame)
2609 		goto err;
2610 	init_func_state(env, frame,
2611 			BPF_MAIN_FUNC /* callsite */,
2612 			0 /* frameno within this callchain */,
2613 			subprog /* subprog number within this prog */);
2614 	elem->st.frame[0] = frame;
2615 	return &elem->st;
2616 err:
2617 	free_verifier_state(env->cur_state, true);
2618 	env->cur_state = NULL;
2619 	/* pop all elements and return */
2620 	while (!pop_stack(env, NULL, NULL, false));
2621 	return NULL;
2622 }
2623 
2624 
2625 enum reg_arg_type {
2626 	SRC_OP,		/* register is used as source operand */
2627 	DST_OP,		/* register is used as destination operand */
2628 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2629 };
2630 
2631 static int cmp_subprogs(const void *a, const void *b)
2632 {
2633 	return ((struct bpf_subprog_info *)a)->start -
2634 	       ((struct bpf_subprog_info *)b)->start;
2635 }
2636 
2637 static int find_subprog(struct bpf_verifier_env *env, int off)
2638 {
2639 	struct bpf_subprog_info *p;
2640 
2641 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2642 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2643 	if (!p)
2644 		return -ENOENT;
2645 	return p - env->subprog_info;
2646 
2647 }
2648 
2649 static int add_subprog(struct bpf_verifier_env *env, int off)
2650 {
2651 	int insn_cnt = env->prog->len;
2652 	int ret;
2653 
2654 	if (off >= insn_cnt || off < 0) {
2655 		verbose(env, "call to invalid destination\n");
2656 		return -EINVAL;
2657 	}
2658 	ret = find_subprog(env, off);
2659 	if (ret >= 0)
2660 		return ret;
2661 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2662 		verbose(env, "too many subprograms\n");
2663 		return -E2BIG;
2664 	}
2665 	/* determine subprog starts. The end is one before the next starts */
2666 	env->subprog_info[env->subprog_cnt++].start = off;
2667 	sort(env->subprog_info, env->subprog_cnt,
2668 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2669 	return env->subprog_cnt - 1;
2670 }
2671 
2672 #define MAX_KFUNC_DESCS 256
2673 #define MAX_KFUNC_BTFS	256
2674 
2675 struct bpf_kfunc_desc {
2676 	struct btf_func_model func_model;
2677 	u32 func_id;
2678 	s32 imm;
2679 	u16 offset;
2680 	unsigned long addr;
2681 };
2682 
2683 struct bpf_kfunc_btf {
2684 	struct btf *btf;
2685 	struct module *module;
2686 	u16 offset;
2687 };
2688 
2689 struct bpf_kfunc_desc_tab {
2690 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2691 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2692 	 * available, therefore at the end of verification do_misc_fixups()
2693 	 * sorts this by imm and offset.
2694 	 */
2695 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2696 	u32 nr_descs;
2697 };
2698 
2699 struct bpf_kfunc_btf_tab {
2700 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2701 	u32 nr_descs;
2702 };
2703 
2704 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2705 {
2706 	const struct bpf_kfunc_desc *d0 = a;
2707 	const struct bpf_kfunc_desc *d1 = b;
2708 
2709 	/* func_id is not greater than BTF_MAX_TYPE */
2710 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2711 }
2712 
2713 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2714 {
2715 	const struct bpf_kfunc_btf *d0 = a;
2716 	const struct bpf_kfunc_btf *d1 = b;
2717 
2718 	return d0->offset - d1->offset;
2719 }
2720 
2721 static const struct bpf_kfunc_desc *
2722 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2723 {
2724 	struct bpf_kfunc_desc desc = {
2725 		.func_id = func_id,
2726 		.offset = offset,
2727 	};
2728 	struct bpf_kfunc_desc_tab *tab;
2729 
2730 	tab = prog->aux->kfunc_tab;
2731 	return bsearch(&desc, tab->descs, tab->nr_descs,
2732 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2733 }
2734 
2735 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2736 		       u16 btf_fd_idx, u8 **func_addr)
2737 {
2738 	const struct bpf_kfunc_desc *desc;
2739 
2740 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2741 	if (!desc)
2742 		return -EFAULT;
2743 
2744 	*func_addr = (u8 *)desc->addr;
2745 	return 0;
2746 }
2747 
2748 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2749 					 s16 offset)
2750 {
2751 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2752 	struct bpf_kfunc_btf_tab *tab;
2753 	struct bpf_kfunc_btf *b;
2754 	struct module *mod;
2755 	struct btf *btf;
2756 	int btf_fd;
2757 
2758 	tab = env->prog->aux->kfunc_btf_tab;
2759 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2760 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2761 	if (!b) {
2762 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2763 			verbose(env, "too many different module BTFs\n");
2764 			return ERR_PTR(-E2BIG);
2765 		}
2766 
2767 		if (bpfptr_is_null(env->fd_array)) {
2768 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2769 			return ERR_PTR(-EPROTO);
2770 		}
2771 
2772 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2773 					    offset * sizeof(btf_fd),
2774 					    sizeof(btf_fd)))
2775 			return ERR_PTR(-EFAULT);
2776 
2777 		btf = btf_get_by_fd(btf_fd);
2778 		if (IS_ERR(btf)) {
2779 			verbose(env, "invalid module BTF fd specified\n");
2780 			return btf;
2781 		}
2782 
2783 		if (!btf_is_module(btf)) {
2784 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2785 			btf_put(btf);
2786 			return ERR_PTR(-EINVAL);
2787 		}
2788 
2789 		mod = btf_try_get_module(btf);
2790 		if (!mod) {
2791 			btf_put(btf);
2792 			return ERR_PTR(-ENXIO);
2793 		}
2794 
2795 		b = &tab->descs[tab->nr_descs++];
2796 		b->btf = btf;
2797 		b->module = mod;
2798 		b->offset = offset;
2799 
2800 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2801 		     kfunc_btf_cmp_by_off, NULL);
2802 	}
2803 	return b->btf;
2804 }
2805 
2806 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2807 {
2808 	if (!tab)
2809 		return;
2810 
2811 	while (tab->nr_descs--) {
2812 		module_put(tab->descs[tab->nr_descs].module);
2813 		btf_put(tab->descs[tab->nr_descs].btf);
2814 	}
2815 	kfree(tab);
2816 }
2817 
2818 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2819 {
2820 	if (offset) {
2821 		if (offset < 0) {
2822 			/* In the future, this can be allowed to increase limit
2823 			 * of fd index into fd_array, interpreted as u16.
2824 			 */
2825 			verbose(env, "negative offset disallowed for kernel module function call\n");
2826 			return ERR_PTR(-EINVAL);
2827 		}
2828 
2829 		return __find_kfunc_desc_btf(env, offset);
2830 	}
2831 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2832 }
2833 
2834 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2835 {
2836 	const struct btf_type *func, *func_proto;
2837 	struct bpf_kfunc_btf_tab *btf_tab;
2838 	struct bpf_kfunc_desc_tab *tab;
2839 	struct bpf_prog_aux *prog_aux;
2840 	struct bpf_kfunc_desc *desc;
2841 	const char *func_name;
2842 	struct btf *desc_btf;
2843 	unsigned long call_imm;
2844 	unsigned long addr;
2845 	int err;
2846 
2847 	prog_aux = env->prog->aux;
2848 	tab = prog_aux->kfunc_tab;
2849 	btf_tab = prog_aux->kfunc_btf_tab;
2850 	if (!tab) {
2851 		if (!btf_vmlinux) {
2852 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2853 			return -ENOTSUPP;
2854 		}
2855 
2856 		if (!env->prog->jit_requested) {
2857 			verbose(env, "JIT is required for calling kernel function\n");
2858 			return -ENOTSUPP;
2859 		}
2860 
2861 		if (!bpf_jit_supports_kfunc_call()) {
2862 			verbose(env, "JIT does not support calling kernel function\n");
2863 			return -ENOTSUPP;
2864 		}
2865 
2866 		if (!env->prog->gpl_compatible) {
2867 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2868 			return -EINVAL;
2869 		}
2870 
2871 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2872 		if (!tab)
2873 			return -ENOMEM;
2874 		prog_aux->kfunc_tab = tab;
2875 	}
2876 
2877 	/* func_id == 0 is always invalid, but instead of returning an error, be
2878 	 * conservative and wait until the code elimination pass before returning
2879 	 * error, so that invalid calls that get pruned out can be in BPF programs
2880 	 * loaded from userspace.  It is also required that offset be untouched
2881 	 * for such calls.
2882 	 */
2883 	if (!func_id && !offset)
2884 		return 0;
2885 
2886 	if (!btf_tab && offset) {
2887 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2888 		if (!btf_tab)
2889 			return -ENOMEM;
2890 		prog_aux->kfunc_btf_tab = btf_tab;
2891 	}
2892 
2893 	desc_btf = find_kfunc_desc_btf(env, offset);
2894 	if (IS_ERR(desc_btf)) {
2895 		verbose(env, "failed to find BTF for kernel function\n");
2896 		return PTR_ERR(desc_btf);
2897 	}
2898 
2899 	if (find_kfunc_desc(env->prog, func_id, offset))
2900 		return 0;
2901 
2902 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2903 		verbose(env, "too many different kernel function calls\n");
2904 		return -E2BIG;
2905 	}
2906 
2907 	func = btf_type_by_id(desc_btf, func_id);
2908 	if (!func || !btf_type_is_func(func)) {
2909 		verbose(env, "kernel btf_id %u is not a function\n",
2910 			func_id);
2911 		return -EINVAL;
2912 	}
2913 	func_proto = btf_type_by_id(desc_btf, func->type);
2914 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2915 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2916 			func_id);
2917 		return -EINVAL;
2918 	}
2919 
2920 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2921 	addr = kallsyms_lookup_name(func_name);
2922 	if (!addr) {
2923 		verbose(env, "cannot find address for kernel function %s\n",
2924 			func_name);
2925 		return -EINVAL;
2926 	}
2927 	specialize_kfunc(env, func_id, offset, &addr);
2928 
2929 	if (bpf_jit_supports_far_kfunc_call()) {
2930 		call_imm = func_id;
2931 	} else {
2932 		call_imm = BPF_CALL_IMM(addr);
2933 		/* Check whether the relative offset overflows desc->imm */
2934 		if ((unsigned long)(s32)call_imm != call_imm) {
2935 			verbose(env, "address of kernel function %s is out of range\n",
2936 				func_name);
2937 			return -EINVAL;
2938 		}
2939 	}
2940 
2941 	if (bpf_dev_bound_kfunc_id(func_id)) {
2942 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2943 		if (err)
2944 			return err;
2945 	}
2946 
2947 	desc = &tab->descs[tab->nr_descs++];
2948 	desc->func_id = func_id;
2949 	desc->imm = call_imm;
2950 	desc->offset = offset;
2951 	desc->addr = addr;
2952 	err = btf_distill_func_proto(&env->log, desc_btf,
2953 				     func_proto, func_name,
2954 				     &desc->func_model);
2955 	if (!err)
2956 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2957 		     kfunc_desc_cmp_by_id_off, NULL);
2958 	return err;
2959 }
2960 
2961 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2962 {
2963 	const struct bpf_kfunc_desc *d0 = a;
2964 	const struct bpf_kfunc_desc *d1 = b;
2965 
2966 	if (d0->imm != d1->imm)
2967 		return d0->imm < d1->imm ? -1 : 1;
2968 	if (d0->offset != d1->offset)
2969 		return d0->offset < d1->offset ? -1 : 1;
2970 	return 0;
2971 }
2972 
2973 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2974 {
2975 	struct bpf_kfunc_desc_tab *tab;
2976 
2977 	tab = prog->aux->kfunc_tab;
2978 	if (!tab)
2979 		return;
2980 
2981 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2982 	     kfunc_desc_cmp_by_imm_off, NULL);
2983 }
2984 
2985 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2986 {
2987 	return !!prog->aux->kfunc_tab;
2988 }
2989 
2990 const struct btf_func_model *
2991 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2992 			 const struct bpf_insn *insn)
2993 {
2994 	const struct bpf_kfunc_desc desc = {
2995 		.imm = insn->imm,
2996 		.offset = insn->off,
2997 	};
2998 	const struct bpf_kfunc_desc *res;
2999 	struct bpf_kfunc_desc_tab *tab;
3000 
3001 	tab = prog->aux->kfunc_tab;
3002 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3003 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3004 
3005 	return res ? &res->func_model : NULL;
3006 }
3007 
3008 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3009 {
3010 	struct bpf_subprog_info *subprog = env->subprog_info;
3011 	struct bpf_insn *insn = env->prog->insnsi;
3012 	int i, ret, insn_cnt = env->prog->len;
3013 
3014 	/* Add entry function. */
3015 	ret = add_subprog(env, 0);
3016 	if (ret)
3017 		return ret;
3018 
3019 	for (i = 0; i < insn_cnt; i++, insn++) {
3020 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3021 		    !bpf_pseudo_kfunc_call(insn))
3022 			continue;
3023 
3024 		if (!env->bpf_capable) {
3025 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3026 			return -EPERM;
3027 		}
3028 
3029 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3030 			ret = add_subprog(env, i + insn->imm + 1);
3031 		else
3032 			ret = add_kfunc_call(env, insn->imm, insn->off);
3033 
3034 		if (ret < 0)
3035 			return ret;
3036 	}
3037 
3038 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3039 	 * logic. 'subprog_cnt' should not be increased.
3040 	 */
3041 	subprog[env->subprog_cnt].start = insn_cnt;
3042 
3043 	if (env->log.level & BPF_LOG_LEVEL2)
3044 		for (i = 0; i < env->subprog_cnt; i++)
3045 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3046 
3047 	return 0;
3048 }
3049 
3050 static int check_subprogs(struct bpf_verifier_env *env)
3051 {
3052 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3053 	struct bpf_subprog_info *subprog = env->subprog_info;
3054 	struct bpf_insn *insn = env->prog->insnsi;
3055 	int insn_cnt = env->prog->len;
3056 
3057 	/* now check that all jumps are within the same subprog */
3058 	subprog_start = subprog[cur_subprog].start;
3059 	subprog_end = subprog[cur_subprog + 1].start;
3060 	for (i = 0; i < insn_cnt; i++) {
3061 		u8 code = insn[i].code;
3062 
3063 		if (code == (BPF_JMP | BPF_CALL) &&
3064 		    insn[i].src_reg == 0 &&
3065 		    insn[i].imm == BPF_FUNC_tail_call)
3066 			subprog[cur_subprog].has_tail_call = true;
3067 		if (BPF_CLASS(code) == BPF_LD &&
3068 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3069 			subprog[cur_subprog].has_ld_abs = true;
3070 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3071 			goto next;
3072 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3073 			goto next;
3074 		if (code == (BPF_JMP32 | BPF_JA))
3075 			off = i + insn[i].imm + 1;
3076 		else
3077 			off = i + insn[i].off + 1;
3078 		if (off < subprog_start || off >= subprog_end) {
3079 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3080 			return -EINVAL;
3081 		}
3082 next:
3083 		if (i == subprog_end - 1) {
3084 			/* to avoid fall-through from one subprog into another
3085 			 * the last insn of the subprog should be either exit
3086 			 * or unconditional jump back
3087 			 */
3088 			if (code != (BPF_JMP | BPF_EXIT) &&
3089 			    code != (BPF_JMP32 | BPF_JA) &&
3090 			    code != (BPF_JMP | BPF_JA)) {
3091 				verbose(env, "last insn is not an exit or jmp\n");
3092 				return -EINVAL;
3093 			}
3094 			subprog_start = subprog_end;
3095 			cur_subprog++;
3096 			if (cur_subprog < env->subprog_cnt)
3097 				subprog_end = subprog[cur_subprog + 1].start;
3098 		}
3099 	}
3100 	return 0;
3101 }
3102 
3103 /* Parentage chain of this register (or stack slot) should take care of all
3104  * issues like callee-saved registers, stack slot allocation time, etc.
3105  */
3106 static int mark_reg_read(struct bpf_verifier_env *env,
3107 			 const struct bpf_reg_state *state,
3108 			 struct bpf_reg_state *parent, u8 flag)
3109 {
3110 	bool writes = parent == state->parent; /* Observe write marks */
3111 	int cnt = 0;
3112 
3113 	while (parent) {
3114 		/* if read wasn't screened by an earlier write ... */
3115 		if (writes && state->live & REG_LIVE_WRITTEN)
3116 			break;
3117 		if (parent->live & REG_LIVE_DONE) {
3118 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3119 				reg_type_str(env, parent->type),
3120 				parent->var_off.value, parent->off);
3121 			return -EFAULT;
3122 		}
3123 		/* The first condition is more likely to be true than the
3124 		 * second, checked it first.
3125 		 */
3126 		if ((parent->live & REG_LIVE_READ) == flag ||
3127 		    parent->live & REG_LIVE_READ64)
3128 			/* The parentage chain never changes and
3129 			 * this parent was already marked as LIVE_READ.
3130 			 * There is no need to keep walking the chain again and
3131 			 * keep re-marking all parents as LIVE_READ.
3132 			 * This case happens when the same register is read
3133 			 * multiple times without writes into it in-between.
3134 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3135 			 * then no need to set the weak REG_LIVE_READ32.
3136 			 */
3137 			break;
3138 		/* ... then we depend on parent's value */
3139 		parent->live |= flag;
3140 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3141 		if (flag == REG_LIVE_READ64)
3142 			parent->live &= ~REG_LIVE_READ32;
3143 		state = parent;
3144 		parent = state->parent;
3145 		writes = true;
3146 		cnt++;
3147 	}
3148 
3149 	if (env->longest_mark_read_walk < cnt)
3150 		env->longest_mark_read_walk = cnt;
3151 	return 0;
3152 }
3153 
3154 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3155 {
3156 	struct bpf_func_state *state = func(env, reg);
3157 	int spi, ret;
3158 
3159 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3160 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3161 	 * check_kfunc_call.
3162 	 */
3163 	if (reg->type == CONST_PTR_TO_DYNPTR)
3164 		return 0;
3165 	spi = dynptr_get_spi(env, reg);
3166 	if (spi < 0)
3167 		return spi;
3168 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3169 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3170 	 * read.
3171 	 */
3172 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3173 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3174 	if (ret)
3175 		return ret;
3176 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3177 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3178 }
3179 
3180 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3181 			  int spi, int nr_slots)
3182 {
3183 	struct bpf_func_state *state = func(env, reg);
3184 	int err, i;
3185 
3186 	for (i = 0; i < nr_slots; i++) {
3187 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3188 
3189 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3190 		if (err)
3191 			return err;
3192 
3193 		mark_stack_slot_scratched(env, spi - i);
3194 	}
3195 
3196 	return 0;
3197 }
3198 
3199 /* This function is supposed to be used by the following 32-bit optimization
3200  * code only. It returns TRUE if the source or destination register operates
3201  * on 64-bit, otherwise return FALSE.
3202  */
3203 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3204 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3205 {
3206 	u8 code, class, op;
3207 
3208 	code = insn->code;
3209 	class = BPF_CLASS(code);
3210 	op = BPF_OP(code);
3211 	if (class == BPF_JMP) {
3212 		/* BPF_EXIT for "main" will reach here. Return TRUE
3213 		 * conservatively.
3214 		 */
3215 		if (op == BPF_EXIT)
3216 			return true;
3217 		if (op == BPF_CALL) {
3218 			/* BPF to BPF call will reach here because of marking
3219 			 * caller saved clobber with DST_OP_NO_MARK for which we
3220 			 * don't care the register def because they are anyway
3221 			 * marked as NOT_INIT already.
3222 			 */
3223 			if (insn->src_reg == BPF_PSEUDO_CALL)
3224 				return false;
3225 			/* Helper call will reach here because of arg type
3226 			 * check, conservatively return TRUE.
3227 			 */
3228 			if (t == SRC_OP)
3229 				return true;
3230 
3231 			return false;
3232 		}
3233 	}
3234 
3235 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3236 		return false;
3237 
3238 	if (class == BPF_ALU64 || class == BPF_JMP ||
3239 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3240 		return true;
3241 
3242 	if (class == BPF_ALU || class == BPF_JMP32)
3243 		return false;
3244 
3245 	if (class == BPF_LDX) {
3246 		if (t != SRC_OP)
3247 			return BPF_SIZE(code) == BPF_DW;
3248 		/* LDX source must be ptr. */
3249 		return true;
3250 	}
3251 
3252 	if (class == BPF_STX) {
3253 		/* BPF_STX (including atomic variants) has multiple source
3254 		 * operands, one of which is a ptr. Check whether the caller is
3255 		 * asking about it.
3256 		 */
3257 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3258 			return true;
3259 		return BPF_SIZE(code) == BPF_DW;
3260 	}
3261 
3262 	if (class == BPF_LD) {
3263 		u8 mode = BPF_MODE(code);
3264 
3265 		/* LD_IMM64 */
3266 		if (mode == BPF_IMM)
3267 			return true;
3268 
3269 		/* Both LD_IND and LD_ABS return 32-bit data. */
3270 		if (t != SRC_OP)
3271 			return  false;
3272 
3273 		/* Implicit ctx ptr. */
3274 		if (regno == BPF_REG_6)
3275 			return true;
3276 
3277 		/* Explicit source could be any width. */
3278 		return true;
3279 	}
3280 
3281 	if (class == BPF_ST)
3282 		/* The only source register for BPF_ST is a ptr. */
3283 		return true;
3284 
3285 	/* Conservatively return true at default. */
3286 	return true;
3287 }
3288 
3289 /* Return the regno defined by the insn, or -1. */
3290 static int insn_def_regno(const struct bpf_insn *insn)
3291 {
3292 	switch (BPF_CLASS(insn->code)) {
3293 	case BPF_JMP:
3294 	case BPF_JMP32:
3295 	case BPF_ST:
3296 		return -1;
3297 	case BPF_STX:
3298 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3299 		    (insn->imm & BPF_FETCH)) {
3300 			if (insn->imm == BPF_CMPXCHG)
3301 				return BPF_REG_0;
3302 			else
3303 				return insn->src_reg;
3304 		} else {
3305 			return -1;
3306 		}
3307 	default:
3308 		return insn->dst_reg;
3309 	}
3310 }
3311 
3312 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3313 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3314 {
3315 	int dst_reg = insn_def_regno(insn);
3316 
3317 	if (dst_reg == -1)
3318 		return false;
3319 
3320 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3321 }
3322 
3323 static void mark_insn_zext(struct bpf_verifier_env *env,
3324 			   struct bpf_reg_state *reg)
3325 {
3326 	s32 def_idx = reg->subreg_def;
3327 
3328 	if (def_idx == DEF_NOT_SUBREG)
3329 		return;
3330 
3331 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3332 	/* The dst will be zero extended, so won't be sub-register anymore. */
3333 	reg->subreg_def = DEF_NOT_SUBREG;
3334 }
3335 
3336 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3337 			   enum reg_arg_type t)
3338 {
3339 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3340 	struct bpf_reg_state *reg;
3341 	bool rw64;
3342 
3343 	if (regno >= MAX_BPF_REG) {
3344 		verbose(env, "R%d is invalid\n", regno);
3345 		return -EINVAL;
3346 	}
3347 
3348 	mark_reg_scratched(env, regno);
3349 
3350 	reg = &regs[regno];
3351 	rw64 = is_reg64(env, insn, regno, reg, t);
3352 	if (t == SRC_OP) {
3353 		/* check whether register used as source operand can be read */
3354 		if (reg->type == NOT_INIT) {
3355 			verbose(env, "R%d !read_ok\n", regno);
3356 			return -EACCES;
3357 		}
3358 		/* We don't need to worry about FP liveness because it's read-only */
3359 		if (regno == BPF_REG_FP)
3360 			return 0;
3361 
3362 		if (rw64)
3363 			mark_insn_zext(env, reg);
3364 
3365 		return mark_reg_read(env, reg, reg->parent,
3366 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3367 	} else {
3368 		/* check whether register used as dest operand can be written to */
3369 		if (regno == BPF_REG_FP) {
3370 			verbose(env, "frame pointer is read only\n");
3371 			return -EACCES;
3372 		}
3373 		reg->live |= REG_LIVE_WRITTEN;
3374 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3375 		if (t == DST_OP)
3376 			mark_reg_unknown(env, regs, regno);
3377 	}
3378 	return 0;
3379 }
3380 
3381 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3382 			 enum reg_arg_type t)
3383 {
3384 	struct bpf_verifier_state *vstate = env->cur_state;
3385 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3386 
3387 	return __check_reg_arg(env, state->regs, regno, t);
3388 }
3389 
3390 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3391 {
3392 	env->insn_aux_data[idx].jmp_point = true;
3393 }
3394 
3395 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3396 {
3397 	return env->insn_aux_data[insn_idx].jmp_point;
3398 }
3399 
3400 /* for any branch, call, exit record the history of jmps in the given state */
3401 static int push_jmp_history(struct bpf_verifier_env *env,
3402 			    struct bpf_verifier_state *cur)
3403 {
3404 	u32 cnt = cur->jmp_history_cnt;
3405 	struct bpf_idx_pair *p;
3406 	size_t alloc_size;
3407 
3408 	if (!is_jmp_point(env, env->insn_idx))
3409 		return 0;
3410 
3411 	cnt++;
3412 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3413 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3414 	if (!p)
3415 		return -ENOMEM;
3416 	p[cnt - 1].idx = env->insn_idx;
3417 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3418 	cur->jmp_history = p;
3419 	cur->jmp_history_cnt = cnt;
3420 	return 0;
3421 }
3422 
3423 /* Backtrack one insn at a time. If idx is not at the top of recorded
3424  * history then previous instruction came from straight line execution.
3425  * Return -ENOENT if we exhausted all instructions within given state.
3426  *
3427  * It's legal to have a bit of a looping with the same starting and ending
3428  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3429  * instruction index is the same as state's first_idx doesn't mean we are
3430  * done. If there is still some jump history left, we should keep going. We
3431  * need to take into account that we might have a jump history between given
3432  * state's parent and itself, due to checkpointing. In this case, we'll have
3433  * history entry recording a jump from last instruction of parent state and
3434  * first instruction of given state.
3435  */
3436 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3437 			     u32 *history)
3438 {
3439 	u32 cnt = *history;
3440 
3441 	if (i == st->first_insn_idx) {
3442 		if (cnt == 0)
3443 			return -ENOENT;
3444 		if (cnt == 1 && st->jmp_history[0].idx == i)
3445 			return -ENOENT;
3446 	}
3447 
3448 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3449 		i = st->jmp_history[cnt - 1].prev_idx;
3450 		(*history)--;
3451 	} else {
3452 		i--;
3453 	}
3454 	return i;
3455 }
3456 
3457 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3458 {
3459 	const struct btf_type *func;
3460 	struct btf *desc_btf;
3461 
3462 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3463 		return NULL;
3464 
3465 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3466 	if (IS_ERR(desc_btf))
3467 		return "<error>";
3468 
3469 	func = btf_type_by_id(desc_btf, insn->imm);
3470 	return btf_name_by_offset(desc_btf, func->name_off);
3471 }
3472 
3473 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3474 {
3475 	bt->frame = frame;
3476 }
3477 
3478 static inline void bt_reset(struct backtrack_state *bt)
3479 {
3480 	struct bpf_verifier_env *env = bt->env;
3481 
3482 	memset(bt, 0, sizeof(*bt));
3483 	bt->env = env;
3484 }
3485 
3486 static inline u32 bt_empty(struct backtrack_state *bt)
3487 {
3488 	u64 mask = 0;
3489 	int i;
3490 
3491 	for (i = 0; i <= bt->frame; i++)
3492 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3493 
3494 	return mask == 0;
3495 }
3496 
3497 static inline int bt_subprog_enter(struct backtrack_state *bt)
3498 {
3499 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3500 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3501 		WARN_ONCE(1, "verifier backtracking bug");
3502 		return -EFAULT;
3503 	}
3504 	bt->frame++;
3505 	return 0;
3506 }
3507 
3508 static inline int bt_subprog_exit(struct backtrack_state *bt)
3509 {
3510 	if (bt->frame == 0) {
3511 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3512 		WARN_ONCE(1, "verifier backtracking bug");
3513 		return -EFAULT;
3514 	}
3515 	bt->frame--;
3516 	return 0;
3517 }
3518 
3519 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3520 {
3521 	bt->reg_masks[frame] |= 1 << reg;
3522 }
3523 
3524 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3525 {
3526 	bt->reg_masks[frame] &= ~(1 << reg);
3527 }
3528 
3529 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3530 {
3531 	bt_set_frame_reg(bt, bt->frame, reg);
3532 }
3533 
3534 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3535 {
3536 	bt_clear_frame_reg(bt, bt->frame, reg);
3537 }
3538 
3539 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3540 {
3541 	bt->stack_masks[frame] |= 1ull << slot;
3542 }
3543 
3544 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3545 {
3546 	bt->stack_masks[frame] &= ~(1ull << slot);
3547 }
3548 
3549 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3550 {
3551 	bt_set_frame_slot(bt, bt->frame, slot);
3552 }
3553 
3554 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3555 {
3556 	bt_clear_frame_slot(bt, bt->frame, slot);
3557 }
3558 
3559 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3560 {
3561 	return bt->reg_masks[frame];
3562 }
3563 
3564 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3565 {
3566 	return bt->reg_masks[bt->frame];
3567 }
3568 
3569 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3570 {
3571 	return bt->stack_masks[frame];
3572 }
3573 
3574 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3575 {
3576 	return bt->stack_masks[bt->frame];
3577 }
3578 
3579 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3580 {
3581 	return bt->reg_masks[bt->frame] & (1 << reg);
3582 }
3583 
3584 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3585 {
3586 	return bt->stack_masks[bt->frame] & (1ull << slot);
3587 }
3588 
3589 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3590 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3591 {
3592 	DECLARE_BITMAP(mask, 64);
3593 	bool first = true;
3594 	int i, n;
3595 
3596 	buf[0] = '\0';
3597 
3598 	bitmap_from_u64(mask, reg_mask);
3599 	for_each_set_bit(i, mask, 32) {
3600 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3601 		first = false;
3602 		buf += n;
3603 		buf_sz -= n;
3604 		if (buf_sz < 0)
3605 			break;
3606 	}
3607 }
3608 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3609 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3610 {
3611 	DECLARE_BITMAP(mask, 64);
3612 	bool first = true;
3613 	int i, n;
3614 
3615 	buf[0] = '\0';
3616 
3617 	bitmap_from_u64(mask, stack_mask);
3618 	for_each_set_bit(i, mask, 64) {
3619 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3620 		first = false;
3621 		buf += n;
3622 		buf_sz -= n;
3623 		if (buf_sz < 0)
3624 			break;
3625 	}
3626 }
3627 
3628 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3629 
3630 /* For given verifier state backtrack_insn() is called from the last insn to
3631  * the first insn. Its purpose is to compute a bitmask of registers and
3632  * stack slots that needs precision in the parent verifier state.
3633  *
3634  * @idx is an index of the instruction we are currently processing;
3635  * @subseq_idx is an index of the subsequent instruction that:
3636  *   - *would be* executed next, if jump history is viewed in forward order;
3637  *   - *was* processed previously during backtracking.
3638  */
3639 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3640 			  struct backtrack_state *bt)
3641 {
3642 	const struct bpf_insn_cbs cbs = {
3643 		.cb_call	= disasm_kfunc_name,
3644 		.cb_print	= verbose,
3645 		.private_data	= env,
3646 	};
3647 	struct bpf_insn *insn = env->prog->insnsi + idx;
3648 	u8 class = BPF_CLASS(insn->code);
3649 	u8 opcode = BPF_OP(insn->code);
3650 	u8 mode = BPF_MODE(insn->code);
3651 	u32 dreg = insn->dst_reg;
3652 	u32 sreg = insn->src_reg;
3653 	u32 spi, i;
3654 
3655 	if (insn->code == 0)
3656 		return 0;
3657 	if (env->log.level & BPF_LOG_LEVEL2) {
3658 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3659 		verbose(env, "mark_precise: frame%d: regs=%s ",
3660 			bt->frame, env->tmp_str_buf);
3661 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3662 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3663 		verbose(env, "%d: ", idx);
3664 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3665 	}
3666 
3667 	if (class == BPF_ALU || class == BPF_ALU64) {
3668 		if (!bt_is_reg_set(bt, dreg))
3669 			return 0;
3670 		if (opcode == BPF_END || opcode == BPF_NEG) {
3671 			/* sreg is reserved and unused
3672 			 * dreg still need precision before this insn
3673 			 */
3674 			return 0;
3675 		} else if (opcode == BPF_MOV) {
3676 			if (BPF_SRC(insn->code) == BPF_X) {
3677 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3678 				 * dreg needs precision after this insn
3679 				 * sreg needs precision before this insn
3680 				 */
3681 				bt_clear_reg(bt, dreg);
3682 				bt_set_reg(bt, sreg);
3683 			} else {
3684 				/* dreg = K
3685 				 * dreg needs precision after this insn.
3686 				 * Corresponding register is already marked
3687 				 * as precise=true in this verifier state.
3688 				 * No further markings in parent are necessary
3689 				 */
3690 				bt_clear_reg(bt, dreg);
3691 			}
3692 		} else {
3693 			if (BPF_SRC(insn->code) == BPF_X) {
3694 				/* dreg += sreg
3695 				 * both dreg and sreg need precision
3696 				 * before this insn
3697 				 */
3698 				bt_set_reg(bt, sreg);
3699 			} /* else dreg += K
3700 			   * dreg still needs precision before this insn
3701 			   */
3702 		}
3703 	} else if (class == BPF_LDX) {
3704 		if (!bt_is_reg_set(bt, dreg))
3705 			return 0;
3706 		bt_clear_reg(bt, dreg);
3707 
3708 		/* scalars can only be spilled into stack w/o losing precision.
3709 		 * Load from any other memory can be zero extended.
3710 		 * The desire to keep that precision is already indicated
3711 		 * by 'precise' mark in corresponding register of this state.
3712 		 * No further tracking necessary.
3713 		 */
3714 		if (insn->src_reg != BPF_REG_FP)
3715 			return 0;
3716 
3717 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3718 		 * that [fp - off] slot contains scalar that needs to be
3719 		 * tracked with precision
3720 		 */
3721 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3722 		if (spi >= 64) {
3723 			verbose(env, "BUG spi %d\n", spi);
3724 			WARN_ONCE(1, "verifier backtracking bug");
3725 			return -EFAULT;
3726 		}
3727 		bt_set_slot(bt, spi);
3728 	} else if (class == BPF_STX || class == BPF_ST) {
3729 		if (bt_is_reg_set(bt, dreg))
3730 			/* stx & st shouldn't be using _scalar_ dst_reg
3731 			 * to access memory. It means backtracking
3732 			 * encountered a case of pointer subtraction.
3733 			 */
3734 			return -ENOTSUPP;
3735 		/* scalars can only be spilled into stack */
3736 		if (insn->dst_reg != BPF_REG_FP)
3737 			return 0;
3738 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3739 		if (spi >= 64) {
3740 			verbose(env, "BUG spi %d\n", spi);
3741 			WARN_ONCE(1, "verifier backtracking bug");
3742 			return -EFAULT;
3743 		}
3744 		if (!bt_is_slot_set(bt, spi))
3745 			return 0;
3746 		bt_clear_slot(bt, spi);
3747 		if (class == BPF_STX)
3748 			bt_set_reg(bt, sreg);
3749 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3750 		if (bpf_pseudo_call(insn)) {
3751 			int subprog_insn_idx, subprog;
3752 
3753 			subprog_insn_idx = idx + insn->imm + 1;
3754 			subprog = find_subprog(env, subprog_insn_idx);
3755 			if (subprog < 0)
3756 				return -EFAULT;
3757 
3758 			if (subprog_is_global(env, subprog)) {
3759 				/* check that jump history doesn't have any
3760 				 * extra instructions from subprog; the next
3761 				 * instruction after call to global subprog
3762 				 * should be literally next instruction in
3763 				 * caller program
3764 				 */
3765 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3766 				/* r1-r5 are invalidated after subprog call,
3767 				 * so for global func call it shouldn't be set
3768 				 * anymore
3769 				 */
3770 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3771 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3772 					WARN_ONCE(1, "verifier backtracking bug");
3773 					return -EFAULT;
3774 				}
3775 				/* global subprog always sets R0 */
3776 				bt_clear_reg(bt, BPF_REG_0);
3777 				return 0;
3778 			} else {
3779 				/* static subprog call instruction, which
3780 				 * means that we are exiting current subprog,
3781 				 * so only r1-r5 could be still requested as
3782 				 * precise, r0 and r6-r10 or any stack slot in
3783 				 * the current frame should be zero by now
3784 				 */
3785 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3786 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3787 					WARN_ONCE(1, "verifier backtracking bug");
3788 					return -EFAULT;
3789 				}
3790 				/* we don't track register spills perfectly,
3791 				 * so fallback to force-precise instead of failing */
3792 				if (bt_stack_mask(bt) != 0)
3793 					return -ENOTSUPP;
3794 				/* propagate r1-r5 to the caller */
3795 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3796 					if (bt_is_reg_set(bt, i)) {
3797 						bt_clear_reg(bt, i);
3798 						bt_set_frame_reg(bt, bt->frame - 1, i);
3799 					}
3800 				}
3801 				if (bt_subprog_exit(bt))
3802 					return -EFAULT;
3803 				return 0;
3804 			}
3805 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3806 			/* exit from callback subprog to callback-calling helper or
3807 			 * kfunc call. Use idx/subseq_idx check to discern it from
3808 			 * straight line code backtracking.
3809 			 * Unlike the subprog call handling above, we shouldn't
3810 			 * propagate precision of r1-r5 (if any requested), as they are
3811 			 * not actually arguments passed directly to callback subprogs
3812 			 */
3813 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3814 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3815 				WARN_ONCE(1, "verifier backtracking bug");
3816 				return -EFAULT;
3817 			}
3818 			if (bt_stack_mask(bt) != 0)
3819 				return -ENOTSUPP;
3820 			/* clear r1-r5 in callback subprog's mask */
3821 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3822 				bt_clear_reg(bt, i);
3823 			if (bt_subprog_exit(bt))
3824 				return -EFAULT;
3825 			return 0;
3826 		} else if (opcode == BPF_CALL) {
3827 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3828 			 * catch this error later. Make backtracking conservative
3829 			 * with ENOTSUPP.
3830 			 */
3831 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3832 				return -ENOTSUPP;
3833 			/* regular helper call sets R0 */
3834 			bt_clear_reg(bt, BPF_REG_0);
3835 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3836 				/* if backtracing was looking for registers R1-R5
3837 				 * they should have been found already.
3838 				 */
3839 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3840 				WARN_ONCE(1, "verifier backtracking bug");
3841 				return -EFAULT;
3842 			}
3843 		} else if (opcode == BPF_EXIT) {
3844 			bool r0_precise;
3845 
3846 			/* Backtracking to a nested function call, 'idx' is a part of
3847 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3848 			 * In case of a regular function call, instructions giving
3849 			 * precision to registers R1-R5 should have been found already.
3850 			 * In case of a callback, it is ok to have R1-R5 marked for
3851 			 * backtracking, as these registers are set by the function
3852 			 * invoking callback.
3853 			 */
3854 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3855 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3856 					bt_clear_reg(bt, i);
3857 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3858 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3859 				WARN_ONCE(1, "verifier backtracking bug");
3860 				return -EFAULT;
3861 			}
3862 
3863 			/* BPF_EXIT in subprog or callback always returns
3864 			 * right after the call instruction, so by checking
3865 			 * whether the instruction at subseq_idx-1 is subprog
3866 			 * call or not we can distinguish actual exit from
3867 			 * *subprog* from exit from *callback*. In the former
3868 			 * case, we need to propagate r0 precision, if
3869 			 * necessary. In the former we never do that.
3870 			 */
3871 			r0_precise = subseq_idx - 1 >= 0 &&
3872 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3873 				     bt_is_reg_set(bt, BPF_REG_0);
3874 
3875 			bt_clear_reg(bt, BPF_REG_0);
3876 			if (bt_subprog_enter(bt))
3877 				return -EFAULT;
3878 
3879 			if (r0_precise)
3880 				bt_set_reg(bt, BPF_REG_0);
3881 			/* r6-r9 and stack slots will stay set in caller frame
3882 			 * bitmasks until we return back from callee(s)
3883 			 */
3884 			return 0;
3885 		} else if (BPF_SRC(insn->code) == BPF_X) {
3886 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3887 				return 0;
3888 			/* dreg <cond> sreg
3889 			 * Both dreg and sreg need precision before
3890 			 * this insn. If only sreg was marked precise
3891 			 * before it would be equally necessary to
3892 			 * propagate it to dreg.
3893 			 */
3894 			bt_set_reg(bt, dreg);
3895 			bt_set_reg(bt, sreg);
3896 			 /* else dreg <cond> K
3897 			  * Only dreg still needs precision before
3898 			  * this insn, so for the K-based conditional
3899 			  * there is nothing new to be marked.
3900 			  */
3901 		}
3902 	} else if (class == BPF_LD) {
3903 		if (!bt_is_reg_set(bt, dreg))
3904 			return 0;
3905 		bt_clear_reg(bt, dreg);
3906 		/* It's ld_imm64 or ld_abs or ld_ind.
3907 		 * For ld_imm64 no further tracking of precision
3908 		 * into parent is necessary
3909 		 */
3910 		if (mode == BPF_IND || mode == BPF_ABS)
3911 			/* to be analyzed */
3912 			return -ENOTSUPP;
3913 	}
3914 	return 0;
3915 }
3916 
3917 /* the scalar precision tracking algorithm:
3918  * . at the start all registers have precise=false.
3919  * . scalar ranges are tracked as normal through alu and jmp insns.
3920  * . once precise value of the scalar register is used in:
3921  *   .  ptr + scalar alu
3922  *   . if (scalar cond K|scalar)
3923  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3924  *   backtrack through the verifier states and mark all registers and
3925  *   stack slots with spilled constants that these scalar regisers
3926  *   should be precise.
3927  * . during state pruning two registers (or spilled stack slots)
3928  *   are equivalent if both are not precise.
3929  *
3930  * Note the verifier cannot simply walk register parentage chain,
3931  * since many different registers and stack slots could have been
3932  * used to compute single precise scalar.
3933  *
3934  * The approach of starting with precise=true for all registers and then
3935  * backtrack to mark a register as not precise when the verifier detects
3936  * that program doesn't care about specific value (e.g., when helper
3937  * takes register as ARG_ANYTHING parameter) is not safe.
3938  *
3939  * It's ok to walk single parentage chain of the verifier states.
3940  * It's possible that this backtracking will go all the way till 1st insn.
3941  * All other branches will be explored for needing precision later.
3942  *
3943  * The backtracking needs to deal with cases like:
3944  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3945  * r9 -= r8
3946  * r5 = r9
3947  * if r5 > 0x79f goto pc+7
3948  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3949  * r5 += 1
3950  * ...
3951  * call bpf_perf_event_output#25
3952  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3953  *
3954  * and this case:
3955  * r6 = 1
3956  * call foo // uses callee's r6 inside to compute r0
3957  * r0 += r6
3958  * if r0 == 0 goto
3959  *
3960  * to track above reg_mask/stack_mask needs to be independent for each frame.
3961  *
3962  * Also if parent's curframe > frame where backtracking started,
3963  * the verifier need to mark registers in both frames, otherwise callees
3964  * may incorrectly prune callers. This is similar to
3965  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3966  *
3967  * For now backtracking falls back into conservative marking.
3968  */
3969 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3970 				     struct bpf_verifier_state *st)
3971 {
3972 	struct bpf_func_state *func;
3973 	struct bpf_reg_state *reg;
3974 	int i, j;
3975 
3976 	if (env->log.level & BPF_LOG_LEVEL2) {
3977 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3978 			st->curframe);
3979 	}
3980 
3981 	/* big hammer: mark all scalars precise in this path.
3982 	 * pop_stack may still get !precise scalars.
3983 	 * We also skip current state and go straight to first parent state,
3984 	 * because precision markings in current non-checkpointed state are
3985 	 * not needed. See why in the comment in __mark_chain_precision below.
3986 	 */
3987 	for (st = st->parent; st; st = st->parent) {
3988 		for (i = 0; i <= st->curframe; i++) {
3989 			func = st->frame[i];
3990 			for (j = 0; j < BPF_REG_FP; j++) {
3991 				reg = &func->regs[j];
3992 				if (reg->type != SCALAR_VALUE || reg->precise)
3993 					continue;
3994 				reg->precise = true;
3995 				if (env->log.level & BPF_LOG_LEVEL2) {
3996 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3997 						i, j);
3998 				}
3999 			}
4000 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4001 				if (!is_spilled_reg(&func->stack[j]))
4002 					continue;
4003 				reg = &func->stack[j].spilled_ptr;
4004 				if (reg->type != SCALAR_VALUE || reg->precise)
4005 					continue;
4006 				reg->precise = true;
4007 				if (env->log.level & BPF_LOG_LEVEL2) {
4008 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4009 						i, -(j + 1) * 8);
4010 				}
4011 			}
4012 		}
4013 	}
4014 }
4015 
4016 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4017 {
4018 	struct bpf_func_state *func;
4019 	struct bpf_reg_state *reg;
4020 	int i, j;
4021 
4022 	for (i = 0; i <= st->curframe; i++) {
4023 		func = st->frame[i];
4024 		for (j = 0; j < BPF_REG_FP; j++) {
4025 			reg = &func->regs[j];
4026 			if (reg->type != SCALAR_VALUE)
4027 				continue;
4028 			reg->precise = false;
4029 		}
4030 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4031 			if (!is_spilled_reg(&func->stack[j]))
4032 				continue;
4033 			reg = &func->stack[j].spilled_ptr;
4034 			if (reg->type != SCALAR_VALUE)
4035 				continue;
4036 			reg->precise = false;
4037 		}
4038 	}
4039 }
4040 
4041 static bool idset_contains(struct bpf_idset *s, u32 id)
4042 {
4043 	u32 i;
4044 
4045 	for (i = 0; i < s->count; ++i)
4046 		if (s->ids[i] == id)
4047 			return true;
4048 
4049 	return false;
4050 }
4051 
4052 static int idset_push(struct bpf_idset *s, u32 id)
4053 {
4054 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4055 		return -EFAULT;
4056 	s->ids[s->count++] = id;
4057 	return 0;
4058 }
4059 
4060 static void idset_reset(struct bpf_idset *s)
4061 {
4062 	s->count = 0;
4063 }
4064 
4065 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4066  * Mark all registers with these IDs as precise.
4067  */
4068 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4069 {
4070 	struct bpf_idset *precise_ids = &env->idset_scratch;
4071 	struct backtrack_state *bt = &env->bt;
4072 	struct bpf_func_state *func;
4073 	struct bpf_reg_state *reg;
4074 	DECLARE_BITMAP(mask, 64);
4075 	int i, fr;
4076 
4077 	idset_reset(precise_ids);
4078 
4079 	for (fr = bt->frame; fr >= 0; fr--) {
4080 		func = st->frame[fr];
4081 
4082 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4083 		for_each_set_bit(i, mask, 32) {
4084 			reg = &func->regs[i];
4085 			if (!reg->id || reg->type != SCALAR_VALUE)
4086 				continue;
4087 			if (idset_push(precise_ids, reg->id))
4088 				return -EFAULT;
4089 		}
4090 
4091 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4092 		for_each_set_bit(i, mask, 64) {
4093 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4094 				break;
4095 			if (!is_spilled_scalar_reg(&func->stack[i]))
4096 				continue;
4097 			reg = &func->stack[i].spilled_ptr;
4098 			if (!reg->id)
4099 				continue;
4100 			if (idset_push(precise_ids, reg->id))
4101 				return -EFAULT;
4102 		}
4103 	}
4104 
4105 	for (fr = 0; fr <= st->curframe; ++fr) {
4106 		func = st->frame[fr];
4107 
4108 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4109 			reg = &func->regs[i];
4110 			if (!reg->id)
4111 				continue;
4112 			if (!idset_contains(precise_ids, reg->id))
4113 				continue;
4114 			bt_set_frame_reg(bt, fr, i);
4115 		}
4116 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4117 			if (!is_spilled_scalar_reg(&func->stack[i]))
4118 				continue;
4119 			reg = &func->stack[i].spilled_ptr;
4120 			if (!reg->id)
4121 				continue;
4122 			if (!idset_contains(precise_ids, reg->id))
4123 				continue;
4124 			bt_set_frame_slot(bt, fr, i);
4125 		}
4126 	}
4127 
4128 	return 0;
4129 }
4130 
4131 /*
4132  * __mark_chain_precision() backtracks BPF program instruction sequence and
4133  * chain of verifier states making sure that register *regno* (if regno >= 0)
4134  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4135  * SCALARS, as well as any other registers and slots that contribute to
4136  * a tracked state of given registers/stack slots, depending on specific BPF
4137  * assembly instructions (see backtrack_insns() for exact instruction handling
4138  * logic). This backtracking relies on recorded jmp_history and is able to
4139  * traverse entire chain of parent states. This process ends only when all the
4140  * necessary registers/slots and their transitive dependencies are marked as
4141  * precise.
4142  *
4143  * One important and subtle aspect is that precise marks *do not matter* in
4144  * the currently verified state (current state). It is important to understand
4145  * why this is the case.
4146  *
4147  * First, note that current state is the state that is not yet "checkpointed",
4148  * i.e., it is not yet put into env->explored_states, and it has no children
4149  * states as well. It's ephemeral, and can end up either a) being discarded if
4150  * compatible explored state is found at some point or BPF_EXIT instruction is
4151  * reached or b) checkpointed and put into env->explored_states, branching out
4152  * into one or more children states.
4153  *
4154  * In the former case, precise markings in current state are completely
4155  * ignored by state comparison code (see regsafe() for details). Only
4156  * checkpointed ("old") state precise markings are important, and if old
4157  * state's register/slot is precise, regsafe() assumes current state's
4158  * register/slot as precise and checks value ranges exactly and precisely. If
4159  * states turn out to be compatible, current state's necessary precise
4160  * markings and any required parent states' precise markings are enforced
4161  * after the fact with propagate_precision() logic, after the fact. But it's
4162  * important to realize that in this case, even after marking current state
4163  * registers/slots as precise, we immediately discard current state. So what
4164  * actually matters is any of the precise markings propagated into current
4165  * state's parent states, which are always checkpointed (due to b) case above).
4166  * As such, for scenario a) it doesn't matter if current state has precise
4167  * markings set or not.
4168  *
4169  * Now, for the scenario b), checkpointing and forking into child(ren)
4170  * state(s). Note that before current state gets to checkpointing step, any
4171  * processed instruction always assumes precise SCALAR register/slot
4172  * knowledge: if precise value or range is useful to prune jump branch, BPF
4173  * verifier takes this opportunity enthusiastically. Similarly, when
4174  * register's value is used to calculate offset or memory address, exact
4175  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4176  * what we mentioned above about state comparison ignoring precise markings
4177  * during state comparison, BPF verifier ignores and also assumes precise
4178  * markings *at will* during instruction verification process. But as verifier
4179  * assumes precision, it also propagates any precision dependencies across
4180  * parent states, which are not yet finalized, so can be further restricted
4181  * based on new knowledge gained from restrictions enforced by their children
4182  * states. This is so that once those parent states are finalized, i.e., when
4183  * they have no more active children state, state comparison logic in
4184  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4185  * required for correctness.
4186  *
4187  * To build a bit more intuition, note also that once a state is checkpointed,
4188  * the path we took to get to that state is not important. This is crucial
4189  * property for state pruning. When state is checkpointed and finalized at
4190  * some instruction index, it can be correctly and safely used to "short
4191  * circuit" any *compatible* state that reaches exactly the same instruction
4192  * index. I.e., if we jumped to that instruction from a completely different
4193  * code path than original finalized state was derived from, it doesn't
4194  * matter, current state can be discarded because from that instruction
4195  * forward having a compatible state will ensure we will safely reach the
4196  * exit. States describe preconditions for further exploration, but completely
4197  * forget the history of how we got here.
4198  *
4199  * This also means that even if we needed precise SCALAR range to get to
4200  * finalized state, but from that point forward *that same* SCALAR register is
4201  * never used in a precise context (i.e., it's precise value is not needed for
4202  * correctness), it's correct and safe to mark such register as "imprecise"
4203  * (i.e., precise marking set to false). This is what we rely on when we do
4204  * not set precise marking in current state. If no child state requires
4205  * precision for any given SCALAR register, it's safe to dictate that it can
4206  * be imprecise. If any child state does require this register to be precise,
4207  * we'll mark it precise later retroactively during precise markings
4208  * propagation from child state to parent states.
4209  *
4210  * Skipping precise marking setting in current state is a mild version of
4211  * relying on the above observation. But we can utilize this property even
4212  * more aggressively by proactively forgetting any precise marking in the
4213  * current state (which we inherited from the parent state), right before we
4214  * checkpoint it and branch off into new child state. This is done by
4215  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4216  * finalized states which help in short circuiting more future states.
4217  */
4218 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4219 {
4220 	struct backtrack_state *bt = &env->bt;
4221 	struct bpf_verifier_state *st = env->cur_state;
4222 	int first_idx = st->first_insn_idx;
4223 	int last_idx = env->insn_idx;
4224 	int subseq_idx = -1;
4225 	struct bpf_func_state *func;
4226 	struct bpf_reg_state *reg;
4227 	bool skip_first = true;
4228 	int i, fr, err;
4229 
4230 	if (!env->bpf_capable)
4231 		return 0;
4232 
4233 	/* set frame number from which we are starting to backtrack */
4234 	bt_init(bt, env->cur_state->curframe);
4235 
4236 	/* Do sanity checks against current state of register and/or stack
4237 	 * slot, but don't set precise flag in current state, as precision
4238 	 * tracking in the current state is unnecessary.
4239 	 */
4240 	func = st->frame[bt->frame];
4241 	if (regno >= 0) {
4242 		reg = &func->regs[regno];
4243 		if (reg->type != SCALAR_VALUE) {
4244 			WARN_ONCE(1, "backtracing misuse");
4245 			return -EFAULT;
4246 		}
4247 		bt_set_reg(bt, regno);
4248 	}
4249 
4250 	if (bt_empty(bt))
4251 		return 0;
4252 
4253 	for (;;) {
4254 		DECLARE_BITMAP(mask, 64);
4255 		u32 history = st->jmp_history_cnt;
4256 
4257 		if (env->log.level & BPF_LOG_LEVEL2) {
4258 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4259 				bt->frame, last_idx, first_idx, subseq_idx);
4260 		}
4261 
4262 		/* If some register with scalar ID is marked as precise,
4263 		 * make sure that all registers sharing this ID are also precise.
4264 		 * This is needed to estimate effect of find_equal_scalars().
4265 		 * Do this at the last instruction of each state,
4266 		 * bpf_reg_state::id fields are valid for these instructions.
4267 		 *
4268 		 * Allows to track precision in situation like below:
4269 		 *
4270 		 *     r2 = unknown value
4271 		 *     ...
4272 		 *   --- state #0 ---
4273 		 *     ...
4274 		 *     r1 = r2                 // r1 and r2 now share the same ID
4275 		 *     ...
4276 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4277 		 *     ...
4278 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4279 		 *     ...
4280 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4281 		 *     r3 = r10
4282 		 *     r3 += r1                // need to mark both r1 and r2
4283 		 */
4284 		if (mark_precise_scalar_ids(env, st))
4285 			return -EFAULT;
4286 
4287 		if (last_idx < 0) {
4288 			/* we are at the entry into subprog, which
4289 			 * is expected for global funcs, but only if
4290 			 * requested precise registers are R1-R5
4291 			 * (which are global func's input arguments)
4292 			 */
4293 			if (st->curframe == 0 &&
4294 			    st->frame[0]->subprogno > 0 &&
4295 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4296 			    bt_stack_mask(bt) == 0 &&
4297 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4298 				bitmap_from_u64(mask, bt_reg_mask(bt));
4299 				for_each_set_bit(i, mask, 32) {
4300 					reg = &st->frame[0]->regs[i];
4301 					bt_clear_reg(bt, i);
4302 					if (reg->type == SCALAR_VALUE)
4303 						reg->precise = true;
4304 				}
4305 				return 0;
4306 			}
4307 
4308 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4309 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4310 			WARN_ONCE(1, "verifier backtracking bug");
4311 			return -EFAULT;
4312 		}
4313 
4314 		for (i = last_idx;;) {
4315 			if (skip_first) {
4316 				err = 0;
4317 				skip_first = false;
4318 			} else {
4319 				err = backtrack_insn(env, i, subseq_idx, bt);
4320 			}
4321 			if (err == -ENOTSUPP) {
4322 				mark_all_scalars_precise(env, env->cur_state);
4323 				bt_reset(bt);
4324 				return 0;
4325 			} else if (err) {
4326 				return err;
4327 			}
4328 			if (bt_empty(bt))
4329 				/* Found assignment(s) into tracked register in this state.
4330 				 * Since this state is already marked, just return.
4331 				 * Nothing to be tracked further in the parent state.
4332 				 */
4333 				return 0;
4334 			subseq_idx = i;
4335 			i = get_prev_insn_idx(st, i, &history);
4336 			if (i == -ENOENT)
4337 				break;
4338 			if (i >= env->prog->len) {
4339 				/* This can happen if backtracking reached insn 0
4340 				 * and there are still reg_mask or stack_mask
4341 				 * to backtrack.
4342 				 * It means the backtracking missed the spot where
4343 				 * particular register was initialized with a constant.
4344 				 */
4345 				verbose(env, "BUG backtracking idx %d\n", i);
4346 				WARN_ONCE(1, "verifier backtracking bug");
4347 				return -EFAULT;
4348 			}
4349 		}
4350 		st = st->parent;
4351 		if (!st)
4352 			break;
4353 
4354 		for (fr = bt->frame; fr >= 0; fr--) {
4355 			func = st->frame[fr];
4356 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4357 			for_each_set_bit(i, mask, 32) {
4358 				reg = &func->regs[i];
4359 				if (reg->type != SCALAR_VALUE) {
4360 					bt_clear_frame_reg(bt, fr, i);
4361 					continue;
4362 				}
4363 				if (reg->precise)
4364 					bt_clear_frame_reg(bt, fr, i);
4365 				else
4366 					reg->precise = true;
4367 			}
4368 
4369 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4370 			for_each_set_bit(i, mask, 64) {
4371 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4372 					/* the sequence of instructions:
4373 					 * 2: (bf) r3 = r10
4374 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4375 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4376 					 * doesn't contain jmps. It's backtracked
4377 					 * as a single block.
4378 					 * During backtracking insn 3 is not recognized as
4379 					 * stack access, so at the end of backtracking
4380 					 * stack slot fp-8 is still marked in stack_mask.
4381 					 * However the parent state may not have accessed
4382 					 * fp-8 and it's "unallocated" stack space.
4383 					 * In such case fallback to conservative.
4384 					 */
4385 					mark_all_scalars_precise(env, env->cur_state);
4386 					bt_reset(bt);
4387 					return 0;
4388 				}
4389 
4390 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4391 					bt_clear_frame_slot(bt, fr, i);
4392 					continue;
4393 				}
4394 				reg = &func->stack[i].spilled_ptr;
4395 				if (reg->precise)
4396 					bt_clear_frame_slot(bt, fr, i);
4397 				else
4398 					reg->precise = true;
4399 			}
4400 			if (env->log.level & BPF_LOG_LEVEL2) {
4401 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4402 					     bt_frame_reg_mask(bt, fr));
4403 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4404 					fr, env->tmp_str_buf);
4405 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4406 					       bt_frame_stack_mask(bt, fr));
4407 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4408 				print_verifier_state(env, func, true);
4409 			}
4410 		}
4411 
4412 		if (bt_empty(bt))
4413 			return 0;
4414 
4415 		subseq_idx = first_idx;
4416 		last_idx = st->last_insn_idx;
4417 		first_idx = st->first_insn_idx;
4418 	}
4419 
4420 	/* if we still have requested precise regs or slots, we missed
4421 	 * something (e.g., stack access through non-r10 register), so
4422 	 * fallback to marking all precise
4423 	 */
4424 	if (!bt_empty(bt)) {
4425 		mark_all_scalars_precise(env, env->cur_state);
4426 		bt_reset(bt);
4427 	}
4428 
4429 	return 0;
4430 }
4431 
4432 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4433 {
4434 	return __mark_chain_precision(env, regno);
4435 }
4436 
4437 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4438  * desired reg and stack masks across all relevant frames
4439  */
4440 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4441 {
4442 	return __mark_chain_precision(env, -1);
4443 }
4444 
4445 static bool is_spillable_regtype(enum bpf_reg_type type)
4446 {
4447 	switch (base_type(type)) {
4448 	case PTR_TO_MAP_VALUE:
4449 	case PTR_TO_STACK:
4450 	case PTR_TO_CTX:
4451 	case PTR_TO_PACKET:
4452 	case PTR_TO_PACKET_META:
4453 	case PTR_TO_PACKET_END:
4454 	case PTR_TO_FLOW_KEYS:
4455 	case CONST_PTR_TO_MAP:
4456 	case PTR_TO_SOCKET:
4457 	case PTR_TO_SOCK_COMMON:
4458 	case PTR_TO_TCP_SOCK:
4459 	case PTR_TO_XDP_SOCK:
4460 	case PTR_TO_BTF_ID:
4461 	case PTR_TO_BUF:
4462 	case PTR_TO_MEM:
4463 	case PTR_TO_FUNC:
4464 	case PTR_TO_MAP_KEY:
4465 		return true;
4466 	default:
4467 		return false;
4468 	}
4469 }
4470 
4471 /* Does this register contain a constant zero? */
4472 static bool register_is_null(struct bpf_reg_state *reg)
4473 {
4474 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4475 }
4476 
4477 static bool register_is_const(struct bpf_reg_state *reg)
4478 {
4479 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4480 }
4481 
4482 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4483 {
4484 	return tnum_is_unknown(reg->var_off) &&
4485 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4486 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4487 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4488 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4489 }
4490 
4491 static bool register_is_bounded(struct bpf_reg_state *reg)
4492 {
4493 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4494 }
4495 
4496 static bool __is_pointer_value(bool allow_ptr_leaks,
4497 			       const struct bpf_reg_state *reg)
4498 {
4499 	if (allow_ptr_leaks)
4500 		return false;
4501 
4502 	return reg->type != SCALAR_VALUE;
4503 }
4504 
4505 /* Copy src state preserving dst->parent and dst->live fields */
4506 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4507 {
4508 	struct bpf_reg_state *parent = dst->parent;
4509 	enum bpf_reg_liveness live = dst->live;
4510 
4511 	*dst = *src;
4512 	dst->parent = parent;
4513 	dst->live = live;
4514 }
4515 
4516 static void save_register_state(struct bpf_func_state *state,
4517 				int spi, struct bpf_reg_state *reg,
4518 				int size)
4519 {
4520 	int i;
4521 
4522 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4523 	if (size == BPF_REG_SIZE)
4524 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4525 
4526 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4527 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4528 
4529 	/* size < 8 bytes spill */
4530 	for (; i; i--)
4531 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4532 }
4533 
4534 static bool is_bpf_st_mem(struct bpf_insn *insn)
4535 {
4536 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4537 }
4538 
4539 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4540  * stack boundary and alignment are checked in check_mem_access()
4541  */
4542 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4543 				       /* stack frame we're writing to */
4544 				       struct bpf_func_state *state,
4545 				       int off, int size, int value_regno,
4546 				       int insn_idx)
4547 {
4548 	struct bpf_func_state *cur; /* state of the current function */
4549 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4550 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4551 	struct bpf_reg_state *reg = NULL;
4552 	u32 dst_reg = insn->dst_reg;
4553 
4554 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4555 	 * so it's aligned access and [off, off + size) are within stack limits
4556 	 */
4557 	if (!env->allow_ptr_leaks &&
4558 	    is_spilled_reg(&state->stack[spi]) &&
4559 	    size != BPF_REG_SIZE) {
4560 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4561 		return -EACCES;
4562 	}
4563 
4564 	cur = env->cur_state->frame[env->cur_state->curframe];
4565 	if (value_regno >= 0)
4566 		reg = &cur->regs[value_regno];
4567 	if (!env->bypass_spec_v4) {
4568 		bool sanitize = reg && is_spillable_regtype(reg->type);
4569 
4570 		for (i = 0; i < size; i++) {
4571 			u8 type = state->stack[spi].slot_type[i];
4572 
4573 			if (type != STACK_MISC && type != STACK_ZERO) {
4574 				sanitize = true;
4575 				break;
4576 			}
4577 		}
4578 
4579 		if (sanitize)
4580 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4581 	}
4582 
4583 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4584 	if (err)
4585 		return err;
4586 
4587 	mark_stack_slot_scratched(env, spi);
4588 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4589 	    !register_is_null(reg) && env->bpf_capable) {
4590 		if (dst_reg != BPF_REG_FP) {
4591 			/* The backtracking logic can only recognize explicit
4592 			 * stack slot address like [fp - 8]. Other spill of
4593 			 * scalar via different register has to be conservative.
4594 			 * Backtrack from here and mark all registers as precise
4595 			 * that contributed into 'reg' being a constant.
4596 			 */
4597 			err = mark_chain_precision(env, value_regno);
4598 			if (err)
4599 				return err;
4600 		}
4601 		save_register_state(state, spi, reg, size);
4602 		/* Break the relation on a narrowing spill. */
4603 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4604 			state->stack[spi].spilled_ptr.id = 0;
4605 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4606 		   insn->imm != 0 && env->bpf_capable) {
4607 		struct bpf_reg_state fake_reg = {};
4608 
4609 		__mark_reg_known(&fake_reg, insn->imm);
4610 		fake_reg.type = SCALAR_VALUE;
4611 		save_register_state(state, spi, &fake_reg, size);
4612 	} else if (reg && is_spillable_regtype(reg->type)) {
4613 		/* register containing pointer is being spilled into stack */
4614 		if (size != BPF_REG_SIZE) {
4615 			verbose_linfo(env, insn_idx, "; ");
4616 			verbose(env, "invalid size of register spill\n");
4617 			return -EACCES;
4618 		}
4619 		if (state != cur && reg->type == PTR_TO_STACK) {
4620 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4621 			return -EINVAL;
4622 		}
4623 		save_register_state(state, spi, reg, size);
4624 	} else {
4625 		u8 type = STACK_MISC;
4626 
4627 		/* regular write of data into stack destroys any spilled ptr */
4628 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4629 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4630 		if (is_stack_slot_special(&state->stack[spi]))
4631 			for (i = 0; i < BPF_REG_SIZE; i++)
4632 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4633 
4634 		/* only mark the slot as written if all 8 bytes were written
4635 		 * otherwise read propagation may incorrectly stop too soon
4636 		 * when stack slots are partially written.
4637 		 * This heuristic means that read propagation will be
4638 		 * conservative, since it will add reg_live_read marks
4639 		 * to stack slots all the way to first state when programs
4640 		 * writes+reads less than 8 bytes
4641 		 */
4642 		if (size == BPF_REG_SIZE)
4643 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4644 
4645 		/* when we zero initialize stack slots mark them as such */
4646 		if ((reg && register_is_null(reg)) ||
4647 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4648 			/* backtracking doesn't work for STACK_ZERO yet. */
4649 			err = mark_chain_precision(env, value_regno);
4650 			if (err)
4651 				return err;
4652 			type = STACK_ZERO;
4653 		}
4654 
4655 		/* Mark slots affected by this stack write. */
4656 		for (i = 0; i < size; i++)
4657 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4658 				type;
4659 	}
4660 	return 0;
4661 }
4662 
4663 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4664  * known to contain a variable offset.
4665  * This function checks whether the write is permitted and conservatively
4666  * tracks the effects of the write, considering that each stack slot in the
4667  * dynamic range is potentially written to.
4668  *
4669  * 'off' includes 'regno->off'.
4670  * 'value_regno' can be -1, meaning that an unknown value is being written to
4671  * the stack.
4672  *
4673  * Spilled pointers in range are not marked as written because we don't know
4674  * what's going to be actually written. This means that read propagation for
4675  * future reads cannot be terminated by this write.
4676  *
4677  * For privileged programs, uninitialized stack slots are considered
4678  * initialized by this write (even though we don't know exactly what offsets
4679  * are going to be written to). The idea is that we don't want the verifier to
4680  * reject future reads that access slots written to through variable offsets.
4681  */
4682 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4683 				     /* func where register points to */
4684 				     struct bpf_func_state *state,
4685 				     int ptr_regno, int off, int size,
4686 				     int value_regno, int insn_idx)
4687 {
4688 	struct bpf_func_state *cur; /* state of the current function */
4689 	int min_off, max_off;
4690 	int i, err;
4691 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4692 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4693 	bool writing_zero = false;
4694 	/* set if the fact that we're writing a zero is used to let any
4695 	 * stack slots remain STACK_ZERO
4696 	 */
4697 	bool zero_used = false;
4698 
4699 	cur = env->cur_state->frame[env->cur_state->curframe];
4700 	ptr_reg = &cur->regs[ptr_regno];
4701 	min_off = ptr_reg->smin_value + off;
4702 	max_off = ptr_reg->smax_value + off + size;
4703 	if (value_regno >= 0)
4704 		value_reg = &cur->regs[value_regno];
4705 	if ((value_reg && register_is_null(value_reg)) ||
4706 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4707 		writing_zero = true;
4708 
4709 	for (i = min_off; i < max_off; i++) {
4710 		int spi;
4711 
4712 		spi = __get_spi(i);
4713 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4714 		if (err)
4715 			return err;
4716 	}
4717 
4718 	/* Variable offset writes destroy any spilled pointers in range. */
4719 	for (i = min_off; i < max_off; i++) {
4720 		u8 new_type, *stype;
4721 		int slot, spi;
4722 
4723 		slot = -i - 1;
4724 		spi = slot / BPF_REG_SIZE;
4725 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4726 		mark_stack_slot_scratched(env, spi);
4727 
4728 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4729 			/* Reject the write if range we may write to has not
4730 			 * been initialized beforehand. If we didn't reject
4731 			 * here, the ptr status would be erased below (even
4732 			 * though not all slots are actually overwritten),
4733 			 * possibly opening the door to leaks.
4734 			 *
4735 			 * We do however catch STACK_INVALID case below, and
4736 			 * only allow reading possibly uninitialized memory
4737 			 * later for CAP_PERFMON, as the write may not happen to
4738 			 * that slot.
4739 			 */
4740 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4741 				insn_idx, i);
4742 			return -EINVAL;
4743 		}
4744 
4745 		/* Erase all spilled pointers. */
4746 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4747 
4748 		/* Update the slot type. */
4749 		new_type = STACK_MISC;
4750 		if (writing_zero && *stype == STACK_ZERO) {
4751 			new_type = STACK_ZERO;
4752 			zero_used = true;
4753 		}
4754 		/* If the slot is STACK_INVALID, we check whether it's OK to
4755 		 * pretend that it will be initialized by this write. The slot
4756 		 * might not actually be written to, and so if we mark it as
4757 		 * initialized future reads might leak uninitialized memory.
4758 		 * For privileged programs, we will accept such reads to slots
4759 		 * that may or may not be written because, if we're reject
4760 		 * them, the error would be too confusing.
4761 		 */
4762 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4763 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4764 					insn_idx, i);
4765 			return -EINVAL;
4766 		}
4767 		*stype = new_type;
4768 	}
4769 	if (zero_used) {
4770 		/* backtracking doesn't work for STACK_ZERO yet. */
4771 		err = mark_chain_precision(env, value_regno);
4772 		if (err)
4773 			return err;
4774 	}
4775 	return 0;
4776 }
4777 
4778 /* When register 'dst_regno' is assigned some values from stack[min_off,
4779  * max_off), we set the register's type according to the types of the
4780  * respective stack slots. If all the stack values are known to be zeros, then
4781  * so is the destination reg. Otherwise, the register is considered to be
4782  * SCALAR. This function does not deal with register filling; the caller must
4783  * ensure that all spilled registers in the stack range have been marked as
4784  * read.
4785  */
4786 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4787 				/* func where src register points to */
4788 				struct bpf_func_state *ptr_state,
4789 				int min_off, int max_off, int dst_regno)
4790 {
4791 	struct bpf_verifier_state *vstate = env->cur_state;
4792 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4793 	int i, slot, spi;
4794 	u8 *stype;
4795 	int zeros = 0;
4796 
4797 	for (i = min_off; i < max_off; i++) {
4798 		slot = -i - 1;
4799 		spi = slot / BPF_REG_SIZE;
4800 		mark_stack_slot_scratched(env, spi);
4801 		stype = ptr_state->stack[spi].slot_type;
4802 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4803 			break;
4804 		zeros++;
4805 	}
4806 	if (zeros == max_off - min_off) {
4807 		/* any access_size read into register is zero extended,
4808 		 * so the whole register == const_zero
4809 		 */
4810 		__mark_reg_const_zero(&state->regs[dst_regno]);
4811 		/* backtracking doesn't support STACK_ZERO yet,
4812 		 * so mark it precise here, so that later
4813 		 * backtracking can stop here.
4814 		 * Backtracking may not need this if this register
4815 		 * doesn't participate in pointer adjustment.
4816 		 * Forward propagation of precise flag is not
4817 		 * necessary either. This mark is only to stop
4818 		 * backtracking. Any register that contributed
4819 		 * to const 0 was marked precise before spill.
4820 		 */
4821 		state->regs[dst_regno].precise = true;
4822 	} else {
4823 		/* have read misc data from the stack */
4824 		mark_reg_unknown(env, state->regs, dst_regno);
4825 	}
4826 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4827 }
4828 
4829 /* Read the stack at 'off' and put the results into the register indicated by
4830  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4831  * spilled reg.
4832  *
4833  * 'dst_regno' can be -1, meaning that the read value is not going to a
4834  * register.
4835  *
4836  * The access is assumed to be within the current stack bounds.
4837  */
4838 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4839 				      /* func where src register points to */
4840 				      struct bpf_func_state *reg_state,
4841 				      int off, int size, int dst_regno)
4842 {
4843 	struct bpf_verifier_state *vstate = env->cur_state;
4844 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4845 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4846 	struct bpf_reg_state *reg;
4847 	u8 *stype, type;
4848 
4849 	stype = reg_state->stack[spi].slot_type;
4850 	reg = &reg_state->stack[spi].spilled_ptr;
4851 
4852 	mark_stack_slot_scratched(env, spi);
4853 
4854 	if (is_spilled_reg(&reg_state->stack[spi])) {
4855 		u8 spill_size = 1;
4856 
4857 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4858 			spill_size++;
4859 
4860 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4861 			if (reg->type != SCALAR_VALUE) {
4862 				verbose_linfo(env, env->insn_idx, "; ");
4863 				verbose(env, "invalid size of register fill\n");
4864 				return -EACCES;
4865 			}
4866 
4867 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4868 			if (dst_regno < 0)
4869 				return 0;
4870 
4871 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4872 				/* The earlier check_reg_arg() has decided the
4873 				 * subreg_def for this insn.  Save it first.
4874 				 */
4875 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4876 
4877 				copy_register_state(&state->regs[dst_regno], reg);
4878 				state->regs[dst_regno].subreg_def = subreg_def;
4879 			} else {
4880 				for (i = 0; i < size; i++) {
4881 					type = stype[(slot - i) % BPF_REG_SIZE];
4882 					if (type == STACK_SPILL)
4883 						continue;
4884 					if (type == STACK_MISC)
4885 						continue;
4886 					if (type == STACK_INVALID && env->allow_uninit_stack)
4887 						continue;
4888 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4889 						off, i, size);
4890 					return -EACCES;
4891 				}
4892 				mark_reg_unknown(env, state->regs, dst_regno);
4893 			}
4894 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4895 			return 0;
4896 		}
4897 
4898 		if (dst_regno >= 0) {
4899 			/* restore register state from stack */
4900 			copy_register_state(&state->regs[dst_regno], reg);
4901 			/* mark reg as written since spilled pointer state likely
4902 			 * has its liveness marks cleared by is_state_visited()
4903 			 * which resets stack/reg liveness for state transitions
4904 			 */
4905 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4906 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4907 			/* If dst_regno==-1, the caller is asking us whether
4908 			 * it is acceptable to use this value as a SCALAR_VALUE
4909 			 * (e.g. for XADD).
4910 			 * We must not allow unprivileged callers to do that
4911 			 * with spilled pointers.
4912 			 */
4913 			verbose(env, "leaking pointer from stack off %d\n",
4914 				off);
4915 			return -EACCES;
4916 		}
4917 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4918 	} else {
4919 		for (i = 0; i < size; i++) {
4920 			type = stype[(slot - i) % BPF_REG_SIZE];
4921 			if (type == STACK_MISC)
4922 				continue;
4923 			if (type == STACK_ZERO)
4924 				continue;
4925 			if (type == STACK_INVALID && env->allow_uninit_stack)
4926 				continue;
4927 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4928 				off, i, size);
4929 			return -EACCES;
4930 		}
4931 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4932 		if (dst_regno >= 0)
4933 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4934 	}
4935 	return 0;
4936 }
4937 
4938 enum bpf_access_src {
4939 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4940 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4941 };
4942 
4943 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4944 					 int regno, int off, int access_size,
4945 					 bool zero_size_allowed,
4946 					 enum bpf_access_src type,
4947 					 struct bpf_call_arg_meta *meta);
4948 
4949 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4950 {
4951 	return cur_regs(env) + regno;
4952 }
4953 
4954 /* Read the stack at 'ptr_regno + off' and put the result into the register
4955  * 'dst_regno'.
4956  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4957  * but not its variable offset.
4958  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4959  *
4960  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4961  * filling registers (i.e. reads of spilled register cannot be detected when
4962  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4963  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4964  * offset; for a fixed offset check_stack_read_fixed_off should be used
4965  * instead.
4966  */
4967 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4968 				    int ptr_regno, int off, int size, int dst_regno)
4969 {
4970 	/* The state of the source register. */
4971 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4972 	struct bpf_func_state *ptr_state = func(env, reg);
4973 	int err;
4974 	int min_off, max_off;
4975 
4976 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4977 	 */
4978 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4979 					    false, ACCESS_DIRECT, NULL);
4980 	if (err)
4981 		return err;
4982 
4983 	min_off = reg->smin_value + off;
4984 	max_off = reg->smax_value + off;
4985 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4986 	return 0;
4987 }
4988 
4989 /* check_stack_read dispatches to check_stack_read_fixed_off or
4990  * check_stack_read_var_off.
4991  *
4992  * The caller must ensure that the offset falls within the allocated stack
4993  * bounds.
4994  *
4995  * 'dst_regno' is a register which will receive the value from the stack. It
4996  * can be -1, meaning that the read value is not going to a register.
4997  */
4998 static int check_stack_read(struct bpf_verifier_env *env,
4999 			    int ptr_regno, int off, int size,
5000 			    int dst_regno)
5001 {
5002 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5003 	struct bpf_func_state *state = func(env, reg);
5004 	int err;
5005 	/* Some accesses are only permitted with a static offset. */
5006 	bool var_off = !tnum_is_const(reg->var_off);
5007 
5008 	/* The offset is required to be static when reads don't go to a
5009 	 * register, in order to not leak pointers (see
5010 	 * check_stack_read_fixed_off).
5011 	 */
5012 	if (dst_regno < 0 && var_off) {
5013 		char tn_buf[48];
5014 
5015 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5016 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5017 			tn_buf, off, size);
5018 		return -EACCES;
5019 	}
5020 	/* Variable offset is prohibited for unprivileged mode for simplicity
5021 	 * since it requires corresponding support in Spectre masking for stack
5022 	 * ALU. See also retrieve_ptr_limit(). The check in
5023 	 * check_stack_access_for_ptr_arithmetic() called by
5024 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5025 	 * with variable offsets, therefore no check is required here. Further,
5026 	 * just checking it here would be insufficient as speculative stack
5027 	 * writes could still lead to unsafe speculative behaviour.
5028 	 */
5029 	if (!var_off) {
5030 		off += reg->var_off.value;
5031 		err = check_stack_read_fixed_off(env, state, off, size,
5032 						 dst_regno);
5033 	} else {
5034 		/* Variable offset stack reads need more conservative handling
5035 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5036 		 * branch.
5037 		 */
5038 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5039 					       dst_regno);
5040 	}
5041 	return err;
5042 }
5043 
5044 
5045 /* check_stack_write dispatches to check_stack_write_fixed_off or
5046  * check_stack_write_var_off.
5047  *
5048  * 'ptr_regno' is the register used as a pointer into the stack.
5049  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5050  * 'value_regno' is the register whose value we're writing to the stack. It can
5051  * be -1, meaning that we're not writing from a register.
5052  *
5053  * The caller must ensure that the offset falls within the maximum stack size.
5054  */
5055 static int check_stack_write(struct bpf_verifier_env *env,
5056 			     int ptr_regno, int off, int size,
5057 			     int value_regno, int insn_idx)
5058 {
5059 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5060 	struct bpf_func_state *state = func(env, reg);
5061 	int err;
5062 
5063 	if (tnum_is_const(reg->var_off)) {
5064 		off += reg->var_off.value;
5065 		err = check_stack_write_fixed_off(env, state, off, size,
5066 						  value_regno, insn_idx);
5067 	} else {
5068 		/* Variable offset stack reads need more conservative handling
5069 		 * than fixed offset ones.
5070 		 */
5071 		err = check_stack_write_var_off(env, state,
5072 						ptr_regno, off, size,
5073 						value_regno, insn_idx);
5074 	}
5075 	return err;
5076 }
5077 
5078 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5079 				 int off, int size, enum bpf_access_type type)
5080 {
5081 	struct bpf_reg_state *regs = cur_regs(env);
5082 	struct bpf_map *map = regs[regno].map_ptr;
5083 	u32 cap = bpf_map_flags_to_cap(map);
5084 
5085 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5086 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5087 			map->value_size, off, size);
5088 		return -EACCES;
5089 	}
5090 
5091 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5092 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5093 			map->value_size, off, size);
5094 		return -EACCES;
5095 	}
5096 
5097 	return 0;
5098 }
5099 
5100 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5101 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5102 			      int off, int size, u32 mem_size,
5103 			      bool zero_size_allowed)
5104 {
5105 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5106 	struct bpf_reg_state *reg;
5107 
5108 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5109 		return 0;
5110 
5111 	reg = &cur_regs(env)[regno];
5112 	switch (reg->type) {
5113 	case PTR_TO_MAP_KEY:
5114 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5115 			mem_size, off, size);
5116 		break;
5117 	case PTR_TO_MAP_VALUE:
5118 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5119 			mem_size, off, size);
5120 		break;
5121 	case PTR_TO_PACKET:
5122 	case PTR_TO_PACKET_META:
5123 	case PTR_TO_PACKET_END:
5124 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5125 			off, size, regno, reg->id, off, mem_size);
5126 		break;
5127 	case PTR_TO_MEM:
5128 	default:
5129 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5130 			mem_size, off, size);
5131 	}
5132 
5133 	return -EACCES;
5134 }
5135 
5136 /* check read/write into a memory region with possible variable offset */
5137 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5138 				   int off, int size, u32 mem_size,
5139 				   bool zero_size_allowed)
5140 {
5141 	struct bpf_verifier_state *vstate = env->cur_state;
5142 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5143 	struct bpf_reg_state *reg = &state->regs[regno];
5144 	int err;
5145 
5146 	/* We may have adjusted the register pointing to memory region, so we
5147 	 * need to try adding each of min_value and max_value to off
5148 	 * to make sure our theoretical access will be safe.
5149 	 *
5150 	 * The minimum value is only important with signed
5151 	 * comparisons where we can't assume the floor of a
5152 	 * value is 0.  If we are using signed variables for our
5153 	 * index'es we need to make sure that whatever we use
5154 	 * will have a set floor within our range.
5155 	 */
5156 	if (reg->smin_value < 0 &&
5157 	    (reg->smin_value == S64_MIN ||
5158 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5159 	      reg->smin_value + off < 0)) {
5160 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5161 			regno);
5162 		return -EACCES;
5163 	}
5164 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5165 				 mem_size, zero_size_allowed);
5166 	if (err) {
5167 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5168 			regno);
5169 		return err;
5170 	}
5171 
5172 	/* If we haven't set a max value then we need to bail since we can't be
5173 	 * sure we won't do bad things.
5174 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5175 	 */
5176 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5177 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5178 			regno);
5179 		return -EACCES;
5180 	}
5181 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5182 				 mem_size, zero_size_allowed);
5183 	if (err) {
5184 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5185 			regno);
5186 		return err;
5187 	}
5188 
5189 	return 0;
5190 }
5191 
5192 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5193 			       const struct bpf_reg_state *reg, int regno,
5194 			       bool fixed_off_ok)
5195 {
5196 	/* Access to this pointer-typed register or passing it to a helper
5197 	 * is only allowed in its original, unmodified form.
5198 	 */
5199 
5200 	if (reg->off < 0) {
5201 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5202 			reg_type_str(env, reg->type), regno, reg->off);
5203 		return -EACCES;
5204 	}
5205 
5206 	if (!fixed_off_ok && reg->off) {
5207 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5208 			reg_type_str(env, reg->type), regno, reg->off);
5209 		return -EACCES;
5210 	}
5211 
5212 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5213 		char tn_buf[48];
5214 
5215 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5216 		verbose(env, "variable %s access var_off=%s disallowed\n",
5217 			reg_type_str(env, reg->type), tn_buf);
5218 		return -EACCES;
5219 	}
5220 
5221 	return 0;
5222 }
5223 
5224 int check_ptr_off_reg(struct bpf_verifier_env *env,
5225 		      const struct bpf_reg_state *reg, int regno)
5226 {
5227 	return __check_ptr_off_reg(env, reg, regno, false);
5228 }
5229 
5230 static int map_kptr_match_type(struct bpf_verifier_env *env,
5231 			       struct btf_field *kptr_field,
5232 			       struct bpf_reg_state *reg, u32 regno)
5233 {
5234 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5235 	int perm_flags;
5236 	const char *reg_name = "";
5237 
5238 	if (btf_is_kernel(reg->btf)) {
5239 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5240 
5241 		/* Only unreferenced case accepts untrusted pointers */
5242 		if (kptr_field->type == BPF_KPTR_UNREF)
5243 			perm_flags |= PTR_UNTRUSTED;
5244 	} else {
5245 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5246 	}
5247 
5248 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5249 		goto bad_type;
5250 
5251 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5252 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5253 
5254 	/* For ref_ptr case, release function check should ensure we get one
5255 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5256 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5257 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5258 	 * reg->off and reg->ref_obj_id are not needed here.
5259 	 */
5260 	if (__check_ptr_off_reg(env, reg, regno, true))
5261 		return -EACCES;
5262 
5263 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5264 	 * we also need to take into account the reg->off.
5265 	 *
5266 	 * We want to support cases like:
5267 	 *
5268 	 * struct foo {
5269 	 *         struct bar br;
5270 	 *         struct baz bz;
5271 	 * };
5272 	 *
5273 	 * struct foo *v;
5274 	 * v = func();	      // PTR_TO_BTF_ID
5275 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5276 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5277 	 *                    // first member type of struct after comparison fails
5278 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5279 	 *                    // to match type
5280 	 *
5281 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5282 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5283 	 * the struct to match type against first member of struct, i.e. reject
5284 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5285 	 * strict mode to true for type match.
5286 	 */
5287 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5288 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5289 				  kptr_field->type == BPF_KPTR_REF))
5290 		goto bad_type;
5291 	return 0;
5292 bad_type:
5293 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5294 		reg_type_str(env, reg->type), reg_name);
5295 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5296 	if (kptr_field->type == BPF_KPTR_UNREF)
5297 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5298 			targ_name);
5299 	else
5300 		verbose(env, "\n");
5301 	return -EINVAL;
5302 }
5303 
5304 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5305  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5306  */
5307 static bool in_rcu_cs(struct bpf_verifier_env *env)
5308 {
5309 	return env->cur_state->active_rcu_lock ||
5310 	       env->cur_state->active_lock.ptr ||
5311 	       !env->prog->aux->sleepable;
5312 }
5313 
5314 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5315 BTF_SET_START(rcu_protected_types)
5316 BTF_ID(struct, prog_test_ref_kfunc)
5317 BTF_ID(struct, cgroup)
5318 BTF_ID(struct, bpf_cpumask)
5319 BTF_ID(struct, task_struct)
5320 BTF_SET_END(rcu_protected_types)
5321 
5322 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5323 {
5324 	if (!btf_is_kernel(btf))
5325 		return false;
5326 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5327 }
5328 
5329 static bool rcu_safe_kptr(const struct btf_field *field)
5330 {
5331 	const struct btf_field_kptr *kptr = &field->kptr;
5332 
5333 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5334 }
5335 
5336 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5337 				 int value_regno, int insn_idx,
5338 				 struct btf_field *kptr_field)
5339 {
5340 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5341 	int class = BPF_CLASS(insn->code);
5342 	struct bpf_reg_state *val_reg;
5343 
5344 	/* Things we already checked for in check_map_access and caller:
5345 	 *  - Reject cases where variable offset may touch kptr
5346 	 *  - size of access (must be BPF_DW)
5347 	 *  - tnum_is_const(reg->var_off)
5348 	 *  - kptr_field->offset == off + reg->var_off.value
5349 	 */
5350 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5351 	if (BPF_MODE(insn->code) != BPF_MEM) {
5352 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5353 		return -EACCES;
5354 	}
5355 
5356 	/* We only allow loading referenced kptr, since it will be marked as
5357 	 * untrusted, similar to unreferenced kptr.
5358 	 */
5359 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5360 		verbose(env, "store to referenced kptr disallowed\n");
5361 		return -EACCES;
5362 	}
5363 
5364 	if (class == BPF_LDX) {
5365 		val_reg = reg_state(env, value_regno);
5366 		/* We can simply mark the value_regno receiving the pointer
5367 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5368 		 */
5369 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5370 				kptr_field->kptr.btf_id,
5371 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5372 				PTR_MAYBE_NULL | MEM_RCU :
5373 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5374 		/* For mark_ptr_or_null_reg */
5375 		val_reg->id = ++env->id_gen;
5376 	} else if (class == BPF_STX) {
5377 		val_reg = reg_state(env, value_regno);
5378 		if (!register_is_null(val_reg) &&
5379 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5380 			return -EACCES;
5381 	} else if (class == BPF_ST) {
5382 		if (insn->imm) {
5383 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5384 				kptr_field->offset);
5385 			return -EACCES;
5386 		}
5387 	} else {
5388 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5389 		return -EACCES;
5390 	}
5391 	return 0;
5392 }
5393 
5394 /* check read/write into a map element with possible variable offset */
5395 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5396 			    int off, int size, bool zero_size_allowed,
5397 			    enum bpf_access_src src)
5398 {
5399 	struct bpf_verifier_state *vstate = env->cur_state;
5400 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5401 	struct bpf_reg_state *reg = &state->regs[regno];
5402 	struct bpf_map *map = reg->map_ptr;
5403 	struct btf_record *rec;
5404 	int err, i;
5405 
5406 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5407 				      zero_size_allowed);
5408 	if (err)
5409 		return err;
5410 
5411 	if (IS_ERR_OR_NULL(map->record))
5412 		return 0;
5413 	rec = map->record;
5414 	for (i = 0; i < rec->cnt; i++) {
5415 		struct btf_field *field = &rec->fields[i];
5416 		u32 p = field->offset;
5417 
5418 		/* If any part of a field  can be touched by load/store, reject
5419 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5420 		 * it is sufficient to check x1 < y2 && y1 < x2.
5421 		 */
5422 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5423 		    p < reg->umax_value + off + size) {
5424 			switch (field->type) {
5425 			case BPF_KPTR_UNREF:
5426 			case BPF_KPTR_REF:
5427 				if (src != ACCESS_DIRECT) {
5428 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5429 					return -EACCES;
5430 				}
5431 				if (!tnum_is_const(reg->var_off)) {
5432 					verbose(env, "kptr access cannot have variable offset\n");
5433 					return -EACCES;
5434 				}
5435 				if (p != off + reg->var_off.value) {
5436 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5437 						p, off + reg->var_off.value);
5438 					return -EACCES;
5439 				}
5440 				if (size != bpf_size_to_bytes(BPF_DW)) {
5441 					verbose(env, "kptr access size must be BPF_DW\n");
5442 					return -EACCES;
5443 				}
5444 				break;
5445 			default:
5446 				verbose(env, "%s cannot be accessed directly by load/store\n",
5447 					btf_field_type_name(field->type));
5448 				return -EACCES;
5449 			}
5450 		}
5451 	}
5452 	return 0;
5453 }
5454 
5455 #define MAX_PACKET_OFF 0xffff
5456 
5457 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5458 				       const struct bpf_call_arg_meta *meta,
5459 				       enum bpf_access_type t)
5460 {
5461 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5462 
5463 	switch (prog_type) {
5464 	/* Program types only with direct read access go here! */
5465 	case BPF_PROG_TYPE_LWT_IN:
5466 	case BPF_PROG_TYPE_LWT_OUT:
5467 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5468 	case BPF_PROG_TYPE_SK_REUSEPORT:
5469 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5470 	case BPF_PROG_TYPE_CGROUP_SKB:
5471 		if (t == BPF_WRITE)
5472 			return false;
5473 		fallthrough;
5474 
5475 	/* Program types with direct read + write access go here! */
5476 	case BPF_PROG_TYPE_SCHED_CLS:
5477 	case BPF_PROG_TYPE_SCHED_ACT:
5478 	case BPF_PROG_TYPE_XDP:
5479 	case BPF_PROG_TYPE_LWT_XMIT:
5480 	case BPF_PROG_TYPE_SK_SKB:
5481 	case BPF_PROG_TYPE_SK_MSG:
5482 		if (meta)
5483 			return meta->pkt_access;
5484 
5485 		env->seen_direct_write = true;
5486 		return true;
5487 
5488 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5489 		if (t == BPF_WRITE)
5490 			env->seen_direct_write = true;
5491 
5492 		return true;
5493 
5494 	default:
5495 		return false;
5496 	}
5497 }
5498 
5499 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5500 			       int size, bool zero_size_allowed)
5501 {
5502 	struct bpf_reg_state *regs = cur_regs(env);
5503 	struct bpf_reg_state *reg = &regs[regno];
5504 	int err;
5505 
5506 	/* We may have added a variable offset to the packet pointer; but any
5507 	 * reg->range we have comes after that.  We are only checking the fixed
5508 	 * offset.
5509 	 */
5510 
5511 	/* We don't allow negative numbers, because we aren't tracking enough
5512 	 * detail to prove they're safe.
5513 	 */
5514 	if (reg->smin_value < 0) {
5515 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5516 			regno);
5517 		return -EACCES;
5518 	}
5519 
5520 	err = reg->range < 0 ? -EINVAL :
5521 	      __check_mem_access(env, regno, off, size, reg->range,
5522 				 zero_size_allowed);
5523 	if (err) {
5524 		verbose(env, "R%d offset is outside of the packet\n", regno);
5525 		return err;
5526 	}
5527 
5528 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5529 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5530 	 * otherwise find_good_pkt_pointers would have refused to set range info
5531 	 * that __check_mem_access would have rejected this pkt access.
5532 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5533 	 */
5534 	env->prog->aux->max_pkt_offset =
5535 		max_t(u32, env->prog->aux->max_pkt_offset,
5536 		      off + reg->umax_value + size - 1);
5537 
5538 	return err;
5539 }
5540 
5541 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5542 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5543 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5544 			    struct btf **btf, u32 *btf_id)
5545 {
5546 	struct bpf_insn_access_aux info = {
5547 		.reg_type = *reg_type,
5548 		.log = &env->log,
5549 	};
5550 
5551 	if (env->ops->is_valid_access &&
5552 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5553 		/* A non zero info.ctx_field_size indicates that this field is a
5554 		 * candidate for later verifier transformation to load the whole
5555 		 * field and then apply a mask when accessed with a narrower
5556 		 * access than actual ctx access size. A zero info.ctx_field_size
5557 		 * will only allow for whole field access and rejects any other
5558 		 * type of narrower access.
5559 		 */
5560 		*reg_type = info.reg_type;
5561 
5562 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5563 			*btf = info.btf;
5564 			*btf_id = info.btf_id;
5565 		} else {
5566 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5567 		}
5568 		/* remember the offset of last byte accessed in ctx */
5569 		if (env->prog->aux->max_ctx_offset < off + size)
5570 			env->prog->aux->max_ctx_offset = off + size;
5571 		return 0;
5572 	}
5573 
5574 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5575 	return -EACCES;
5576 }
5577 
5578 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5579 				  int size)
5580 {
5581 	if (size < 0 || off < 0 ||
5582 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5583 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5584 			off, size);
5585 		return -EACCES;
5586 	}
5587 	return 0;
5588 }
5589 
5590 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5591 			     u32 regno, int off, int size,
5592 			     enum bpf_access_type t)
5593 {
5594 	struct bpf_reg_state *regs = cur_regs(env);
5595 	struct bpf_reg_state *reg = &regs[regno];
5596 	struct bpf_insn_access_aux info = {};
5597 	bool valid;
5598 
5599 	if (reg->smin_value < 0) {
5600 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5601 			regno);
5602 		return -EACCES;
5603 	}
5604 
5605 	switch (reg->type) {
5606 	case PTR_TO_SOCK_COMMON:
5607 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5608 		break;
5609 	case PTR_TO_SOCKET:
5610 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5611 		break;
5612 	case PTR_TO_TCP_SOCK:
5613 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5614 		break;
5615 	case PTR_TO_XDP_SOCK:
5616 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5617 		break;
5618 	default:
5619 		valid = false;
5620 	}
5621 
5622 
5623 	if (valid) {
5624 		env->insn_aux_data[insn_idx].ctx_field_size =
5625 			info.ctx_field_size;
5626 		return 0;
5627 	}
5628 
5629 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5630 		regno, reg_type_str(env, reg->type), off, size);
5631 
5632 	return -EACCES;
5633 }
5634 
5635 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5636 {
5637 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5638 }
5639 
5640 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5641 {
5642 	const struct bpf_reg_state *reg = reg_state(env, regno);
5643 
5644 	return reg->type == PTR_TO_CTX;
5645 }
5646 
5647 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5648 {
5649 	const struct bpf_reg_state *reg = reg_state(env, regno);
5650 
5651 	return type_is_sk_pointer(reg->type);
5652 }
5653 
5654 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5655 {
5656 	const struct bpf_reg_state *reg = reg_state(env, regno);
5657 
5658 	return type_is_pkt_pointer(reg->type);
5659 }
5660 
5661 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5662 {
5663 	const struct bpf_reg_state *reg = reg_state(env, regno);
5664 
5665 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5666 	return reg->type == PTR_TO_FLOW_KEYS;
5667 }
5668 
5669 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5670 #ifdef CONFIG_NET
5671 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5672 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5673 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5674 #endif
5675 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5676 };
5677 
5678 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5679 {
5680 	/* A referenced register is always trusted. */
5681 	if (reg->ref_obj_id)
5682 		return true;
5683 
5684 	/* Types listed in the reg2btf_ids are always trusted */
5685 	if (reg2btf_ids[base_type(reg->type)])
5686 		return true;
5687 
5688 	/* If a register is not referenced, it is trusted if it has the
5689 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5690 	 * other type modifiers may be safe, but we elect to take an opt-in
5691 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5692 	 * not.
5693 	 *
5694 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5695 	 * for whether a register is trusted.
5696 	 */
5697 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5698 	       !bpf_type_has_unsafe_modifiers(reg->type);
5699 }
5700 
5701 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5702 {
5703 	return reg->type & MEM_RCU;
5704 }
5705 
5706 static void clear_trusted_flags(enum bpf_type_flag *flag)
5707 {
5708 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5709 }
5710 
5711 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5712 				   const struct bpf_reg_state *reg,
5713 				   int off, int size, bool strict)
5714 {
5715 	struct tnum reg_off;
5716 	int ip_align;
5717 
5718 	/* Byte size accesses are always allowed. */
5719 	if (!strict || size == 1)
5720 		return 0;
5721 
5722 	/* For platforms that do not have a Kconfig enabling
5723 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5724 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5725 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5726 	 * to this code only in strict mode where we want to emulate
5727 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5728 	 * unconditional IP align value of '2'.
5729 	 */
5730 	ip_align = 2;
5731 
5732 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5733 	if (!tnum_is_aligned(reg_off, size)) {
5734 		char tn_buf[48];
5735 
5736 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5737 		verbose(env,
5738 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5739 			ip_align, tn_buf, reg->off, off, size);
5740 		return -EACCES;
5741 	}
5742 
5743 	return 0;
5744 }
5745 
5746 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5747 				       const struct bpf_reg_state *reg,
5748 				       const char *pointer_desc,
5749 				       int off, int size, bool strict)
5750 {
5751 	struct tnum reg_off;
5752 
5753 	/* Byte size accesses are always allowed. */
5754 	if (!strict || size == 1)
5755 		return 0;
5756 
5757 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5758 	if (!tnum_is_aligned(reg_off, size)) {
5759 		char tn_buf[48];
5760 
5761 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5762 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5763 			pointer_desc, tn_buf, reg->off, off, size);
5764 		return -EACCES;
5765 	}
5766 
5767 	return 0;
5768 }
5769 
5770 static int check_ptr_alignment(struct bpf_verifier_env *env,
5771 			       const struct bpf_reg_state *reg, int off,
5772 			       int size, bool strict_alignment_once)
5773 {
5774 	bool strict = env->strict_alignment || strict_alignment_once;
5775 	const char *pointer_desc = "";
5776 
5777 	switch (reg->type) {
5778 	case PTR_TO_PACKET:
5779 	case PTR_TO_PACKET_META:
5780 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5781 		 * right in front, treat it the very same way.
5782 		 */
5783 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5784 	case PTR_TO_FLOW_KEYS:
5785 		pointer_desc = "flow keys ";
5786 		break;
5787 	case PTR_TO_MAP_KEY:
5788 		pointer_desc = "key ";
5789 		break;
5790 	case PTR_TO_MAP_VALUE:
5791 		pointer_desc = "value ";
5792 		break;
5793 	case PTR_TO_CTX:
5794 		pointer_desc = "context ";
5795 		break;
5796 	case PTR_TO_STACK:
5797 		pointer_desc = "stack ";
5798 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5799 		 * and check_stack_read_fixed_off() relies on stack accesses being
5800 		 * aligned.
5801 		 */
5802 		strict = true;
5803 		break;
5804 	case PTR_TO_SOCKET:
5805 		pointer_desc = "sock ";
5806 		break;
5807 	case PTR_TO_SOCK_COMMON:
5808 		pointer_desc = "sock_common ";
5809 		break;
5810 	case PTR_TO_TCP_SOCK:
5811 		pointer_desc = "tcp_sock ";
5812 		break;
5813 	case PTR_TO_XDP_SOCK:
5814 		pointer_desc = "xdp_sock ";
5815 		break;
5816 	default:
5817 		break;
5818 	}
5819 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5820 					   strict);
5821 }
5822 
5823 /* starting from main bpf function walk all instructions of the function
5824  * and recursively walk all callees that given function can call.
5825  * Ignore jump and exit insns.
5826  * Since recursion is prevented by check_cfg() this algorithm
5827  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5828  */
5829 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5830 {
5831 	struct bpf_subprog_info *subprog = env->subprog_info;
5832 	struct bpf_insn *insn = env->prog->insnsi;
5833 	int depth = 0, frame = 0, i, subprog_end;
5834 	bool tail_call_reachable = false;
5835 	int ret_insn[MAX_CALL_FRAMES];
5836 	int ret_prog[MAX_CALL_FRAMES];
5837 	int j;
5838 
5839 	i = subprog[idx].start;
5840 process_func:
5841 	/* protect against potential stack overflow that might happen when
5842 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5843 	 * depth for such case down to 256 so that the worst case scenario
5844 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5845 	 * 8k).
5846 	 *
5847 	 * To get the idea what might happen, see an example:
5848 	 * func1 -> sub rsp, 128
5849 	 *  subfunc1 -> sub rsp, 256
5850 	 *  tailcall1 -> add rsp, 256
5851 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5852 	 *   subfunc2 -> sub rsp, 64
5853 	 *   subfunc22 -> sub rsp, 128
5854 	 *   tailcall2 -> add rsp, 128
5855 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5856 	 *
5857 	 * tailcall will unwind the current stack frame but it will not get rid
5858 	 * of caller's stack as shown on the example above.
5859 	 */
5860 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5861 		verbose(env,
5862 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5863 			depth);
5864 		return -EACCES;
5865 	}
5866 	/* round up to 32-bytes, since this is granularity
5867 	 * of interpreter stack size
5868 	 */
5869 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5870 	if (depth > MAX_BPF_STACK) {
5871 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5872 			frame + 1, depth);
5873 		return -EACCES;
5874 	}
5875 continue_func:
5876 	subprog_end = subprog[idx + 1].start;
5877 	for (; i < subprog_end; i++) {
5878 		int next_insn, sidx;
5879 
5880 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5881 			continue;
5882 		/* remember insn and function to return to */
5883 		ret_insn[frame] = i + 1;
5884 		ret_prog[frame] = idx;
5885 
5886 		/* find the callee */
5887 		next_insn = i + insn[i].imm + 1;
5888 		sidx = find_subprog(env, next_insn);
5889 		if (sidx < 0) {
5890 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5891 				  next_insn);
5892 			return -EFAULT;
5893 		}
5894 		if (subprog[sidx].is_async_cb) {
5895 			if (subprog[sidx].has_tail_call) {
5896 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5897 				return -EFAULT;
5898 			}
5899 			/* async callbacks don't increase bpf prog stack size unless called directly */
5900 			if (!bpf_pseudo_call(insn + i))
5901 				continue;
5902 		}
5903 		i = next_insn;
5904 		idx = sidx;
5905 
5906 		if (subprog[idx].has_tail_call)
5907 			tail_call_reachable = true;
5908 
5909 		frame++;
5910 		if (frame >= MAX_CALL_FRAMES) {
5911 			verbose(env, "the call stack of %d frames is too deep !\n",
5912 				frame);
5913 			return -E2BIG;
5914 		}
5915 		goto process_func;
5916 	}
5917 	/* if tail call got detected across bpf2bpf calls then mark each of the
5918 	 * currently present subprog frames as tail call reachable subprogs;
5919 	 * this info will be utilized by JIT so that we will be preserving the
5920 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5921 	 */
5922 	if (tail_call_reachable)
5923 		for (j = 0; j < frame; j++)
5924 			subprog[ret_prog[j]].tail_call_reachable = true;
5925 	if (subprog[0].tail_call_reachable)
5926 		env->prog->aux->tail_call_reachable = true;
5927 
5928 	/* end of for() loop means the last insn of the 'subprog'
5929 	 * was reached. Doesn't matter whether it was JA or EXIT
5930 	 */
5931 	if (frame == 0)
5932 		return 0;
5933 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5934 	frame--;
5935 	i = ret_insn[frame];
5936 	idx = ret_prog[frame];
5937 	goto continue_func;
5938 }
5939 
5940 static int check_max_stack_depth(struct bpf_verifier_env *env)
5941 {
5942 	struct bpf_subprog_info *si = env->subprog_info;
5943 	int ret;
5944 
5945 	for (int i = 0; i < env->subprog_cnt; i++) {
5946 		if (!i || si[i].is_async_cb) {
5947 			ret = check_max_stack_depth_subprog(env, i);
5948 			if (ret < 0)
5949 				return ret;
5950 		}
5951 		continue;
5952 	}
5953 	return 0;
5954 }
5955 
5956 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5957 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5958 				  const struct bpf_insn *insn, int idx)
5959 {
5960 	int start = idx + insn->imm + 1, subprog;
5961 
5962 	subprog = find_subprog(env, start);
5963 	if (subprog < 0) {
5964 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5965 			  start);
5966 		return -EFAULT;
5967 	}
5968 	return env->subprog_info[subprog].stack_depth;
5969 }
5970 #endif
5971 
5972 static int __check_buffer_access(struct bpf_verifier_env *env,
5973 				 const char *buf_info,
5974 				 const struct bpf_reg_state *reg,
5975 				 int regno, int off, int size)
5976 {
5977 	if (off < 0) {
5978 		verbose(env,
5979 			"R%d invalid %s buffer access: off=%d, size=%d\n",
5980 			regno, buf_info, off, size);
5981 		return -EACCES;
5982 	}
5983 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5984 		char tn_buf[48];
5985 
5986 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5987 		verbose(env,
5988 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5989 			regno, off, tn_buf);
5990 		return -EACCES;
5991 	}
5992 
5993 	return 0;
5994 }
5995 
5996 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5997 				  const struct bpf_reg_state *reg,
5998 				  int regno, int off, int size)
5999 {
6000 	int err;
6001 
6002 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6003 	if (err)
6004 		return err;
6005 
6006 	if (off + size > env->prog->aux->max_tp_access)
6007 		env->prog->aux->max_tp_access = off + size;
6008 
6009 	return 0;
6010 }
6011 
6012 static int check_buffer_access(struct bpf_verifier_env *env,
6013 			       const struct bpf_reg_state *reg,
6014 			       int regno, int off, int size,
6015 			       bool zero_size_allowed,
6016 			       u32 *max_access)
6017 {
6018 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6019 	int err;
6020 
6021 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6022 	if (err)
6023 		return err;
6024 
6025 	if (off + size > *max_access)
6026 		*max_access = off + size;
6027 
6028 	return 0;
6029 }
6030 
6031 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6032 static void zext_32_to_64(struct bpf_reg_state *reg)
6033 {
6034 	reg->var_off = tnum_subreg(reg->var_off);
6035 	__reg_assign_32_into_64(reg);
6036 }
6037 
6038 /* truncate register to smaller size (in bytes)
6039  * must be called with size < BPF_REG_SIZE
6040  */
6041 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6042 {
6043 	u64 mask;
6044 
6045 	/* clear high bits in bit representation */
6046 	reg->var_off = tnum_cast(reg->var_off, size);
6047 
6048 	/* fix arithmetic bounds */
6049 	mask = ((u64)1 << (size * 8)) - 1;
6050 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6051 		reg->umin_value &= mask;
6052 		reg->umax_value &= mask;
6053 	} else {
6054 		reg->umin_value = 0;
6055 		reg->umax_value = mask;
6056 	}
6057 	reg->smin_value = reg->umin_value;
6058 	reg->smax_value = reg->umax_value;
6059 
6060 	/* If size is smaller than 32bit register the 32bit register
6061 	 * values are also truncated so we push 64-bit bounds into
6062 	 * 32-bit bounds. Above were truncated < 32-bits already.
6063 	 */
6064 	if (size >= 4)
6065 		return;
6066 	__reg_combine_64_into_32(reg);
6067 }
6068 
6069 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6070 {
6071 	if (size == 1) {
6072 		reg->smin_value = reg->s32_min_value = S8_MIN;
6073 		reg->smax_value = reg->s32_max_value = S8_MAX;
6074 	} else if (size == 2) {
6075 		reg->smin_value = reg->s32_min_value = S16_MIN;
6076 		reg->smax_value = reg->s32_max_value = S16_MAX;
6077 	} else {
6078 		/* size == 4 */
6079 		reg->smin_value = reg->s32_min_value = S32_MIN;
6080 		reg->smax_value = reg->s32_max_value = S32_MAX;
6081 	}
6082 	reg->umin_value = reg->u32_min_value = 0;
6083 	reg->umax_value = U64_MAX;
6084 	reg->u32_max_value = U32_MAX;
6085 	reg->var_off = tnum_unknown;
6086 }
6087 
6088 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6089 {
6090 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6091 	u64 top_smax_value, top_smin_value;
6092 	u64 num_bits = size * 8;
6093 
6094 	if (tnum_is_const(reg->var_off)) {
6095 		u64_cval = reg->var_off.value;
6096 		if (size == 1)
6097 			reg->var_off = tnum_const((s8)u64_cval);
6098 		else if (size == 2)
6099 			reg->var_off = tnum_const((s16)u64_cval);
6100 		else
6101 			/* size == 4 */
6102 			reg->var_off = tnum_const((s32)u64_cval);
6103 
6104 		u64_cval = reg->var_off.value;
6105 		reg->smax_value = reg->smin_value = u64_cval;
6106 		reg->umax_value = reg->umin_value = u64_cval;
6107 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6108 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6109 		return;
6110 	}
6111 
6112 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6113 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6114 
6115 	if (top_smax_value != top_smin_value)
6116 		goto out;
6117 
6118 	/* find the s64_min and s64_min after sign extension */
6119 	if (size == 1) {
6120 		init_s64_max = (s8)reg->smax_value;
6121 		init_s64_min = (s8)reg->smin_value;
6122 	} else if (size == 2) {
6123 		init_s64_max = (s16)reg->smax_value;
6124 		init_s64_min = (s16)reg->smin_value;
6125 	} else {
6126 		init_s64_max = (s32)reg->smax_value;
6127 		init_s64_min = (s32)reg->smin_value;
6128 	}
6129 
6130 	s64_max = max(init_s64_max, init_s64_min);
6131 	s64_min = min(init_s64_max, init_s64_min);
6132 
6133 	/* both of s64_max/s64_min positive or negative */
6134 	if ((s64_max >= 0) == (s64_min >= 0)) {
6135 		reg->smin_value = reg->s32_min_value = s64_min;
6136 		reg->smax_value = reg->s32_max_value = s64_max;
6137 		reg->umin_value = reg->u32_min_value = s64_min;
6138 		reg->umax_value = reg->u32_max_value = s64_max;
6139 		reg->var_off = tnum_range(s64_min, s64_max);
6140 		return;
6141 	}
6142 
6143 out:
6144 	set_sext64_default_val(reg, size);
6145 }
6146 
6147 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6148 {
6149 	if (size == 1) {
6150 		reg->s32_min_value = S8_MIN;
6151 		reg->s32_max_value = S8_MAX;
6152 	} else {
6153 		/* size == 2 */
6154 		reg->s32_min_value = S16_MIN;
6155 		reg->s32_max_value = S16_MAX;
6156 	}
6157 	reg->u32_min_value = 0;
6158 	reg->u32_max_value = U32_MAX;
6159 }
6160 
6161 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6162 {
6163 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6164 	u32 top_smax_value, top_smin_value;
6165 	u32 num_bits = size * 8;
6166 
6167 	if (tnum_is_const(reg->var_off)) {
6168 		u32_val = reg->var_off.value;
6169 		if (size == 1)
6170 			reg->var_off = tnum_const((s8)u32_val);
6171 		else
6172 			reg->var_off = tnum_const((s16)u32_val);
6173 
6174 		u32_val = reg->var_off.value;
6175 		reg->s32_min_value = reg->s32_max_value = u32_val;
6176 		reg->u32_min_value = reg->u32_max_value = u32_val;
6177 		return;
6178 	}
6179 
6180 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6181 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6182 
6183 	if (top_smax_value != top_smin_value)
6184 		goto out;
6185 
6186 	/* find the s32_min and s32_min after sign extension */
6187 	if (size == 1) {
6188 		init_s32_max = (s8)reg->s32_max_value;
6189 		init_s32_min = (s8)reg->s32_min_value;
6190 	} else {
6191 		/* size == 2 */
6192 		init_s32_max = (s16)reg->s32_max_value;
6193 		init_s32_min = (s16)reg->s32_min_value;
6194 	}
6195 	s32_max = max(init_s32_max, init_s32_min);
6196 	s32_min = min(init_s32_max, init_s32_min);
6197 
6198 	if ((s32_min >= 0) == (s32_max >= 0)) {
6199 		reg->s32_min_value = s32_min;
6200 		reg->s32_max_value = s32_max;
6201 		reg->u32_min_value = (u32)s32_min;
6202 		reg->u32_max_value = (u32)s32_max;
6203 		return;
6204 	}
6205 
6206 out:
6207 	set_sext32_default_val(reg, size);
6208 }
6209 
6210 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6211 {
6212 	/* A map is considered read-only if the following condition are true:
6213 	 *
6214 	 * 1) BPF program side cannot change any of the map content. The
6215 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6216 	 *    and was set at map creation time.
6217 	 * 2) The map value(s) have been initialized from user space by a
6218 	 *    loader and then "frozen", such that no new map update/delete
6219 	 *    operations from syscall side are possible for the rest of
6220 	 *    the map's lifetime from that point onwards.
6221 	 * 3) Any parallel/pending map update/delete operations from syscall
6222 	 *    side have been completed. Only after that point, it's safe to
6223 	 *    assume that map value(s) are immutable.
6224 	 */
6225 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6226 	       READ_ONCE(map->frozen) &&
6227 	       !bpf_map_write_active(map);
6228 }
6229 
6230 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6231 			       bool is_ldsx)
6232 {
6233 	void *ptr;
6234 	u64 addr;
6235 	int err;
6236 
6237 	err = map->ops->map_direct_value_addr(map, &addr, off);
6238 	if (err)
6239 		return err;
6240 	ptr = (void *)(long)addr + off;
6241 
6242 	switch (size) {
6243 	case sizeof(u8):
6244 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6245 		break;
6246 	case sizeof(u16):
6247 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6248 		break;
6249 	case sizeof(u32):
6250 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6251 		break;
6252 	case sizeof(u64):
6253 		*val = *(u64 *)ptr;
6254 		break;
6255 	default:
6256 		return -EINVAL;
6257 	}
6258 	return 0;
6259 }
6260 
6261 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6262 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6263 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6264 
6265 /*
6266  * Allow list few fields as RCU trusted or full trusted.
6267  * This logic doesn't allow mix tagging and will be removed once GCC supports
6268  * btf_type_tag.
6269  */
6270 
6271 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6272 BTF_TYPE_SAFE_RCU(struct task_struct) {
6273 	const cpumask_t *cpus_ptr;
6274 	struct css_set __rcu *cgroups;
6275 	struct task_struct __rcu *real_parent;
6276 	struct task_struct *group_leader;
6277 };
6278 
6279 BTF_TYPE_SAFE_RCU(struct cgroup) {
6280 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6281 	struct kernfs_node *kn;
6282 };
6283 
6284 BTF_TYPE_SAFE_RCU(struct css_set) {
6285 	struct cgroup *dfl_cgrp;
6286 };
6287 
6288 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6289 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6290 	struct file __rcu *exe_file;
6291 };
6292 
6293 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6294  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6295  */
6296 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6297 	struct sock *sk;
6298 };
6299 
6300 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6301 	struct sock *sk;
6302 };
6303 
6304 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6305 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6306 	struct seq_file *seq;
6307 };
6308 
6309 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6310 	struct bpf_iter_meta *meta;
6311 	struct task_struct *task;
6312 };
6313 
6314 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6315 	struct file *file;
6316 };
6317 
6318 BTF_TYPE_SAFE_TRUSTED(struct file) {
6319 	struct inode *f_inode;
6320 };
6321 
6322 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6323 	/* no negative dentry-s in places where bpf can see it */
6324 	struct inode *d_inode;
6325 };
6326 
6327 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6328 	struct sock *sk;
6329 };
6330 
6331 static bool type_is_rcu(struct bpf_verifier_env *env,
6332 			struct bpf_reg_state *reg,
6333 			const char *field_name, u32 btf_id)
6334 {
6335 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6336 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6337 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6338 
6339 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6340 }
6341 
6342 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6343 				struct bpf_reg_state *reg,
6344 				const char *field_name, u32 btf_id)
6345 {
6346 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6347 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6348 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6349 
6350 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6351 }
6352 
6353 static bool type_is_trusted(struct bpf_verifier_env *env,
6354 			    struct bpf_reg_state *reg,
6355 			    const char *field_name, u32 btf_id)
6356 {
6357 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6358 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6359 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6360 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6361 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6362 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6363 
6364 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6365 }
6366 
6367 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6368 				   struct bpf_reg_state *regs,
6369 				   int regno, int off, int size,
6370 				   enum bpf_access_type atype,
6371 				   int value_regno)
6372 {
6373 	struct bpf_reg_state *reg = regs + regno;
6374 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6375 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6376 	const char *field_name = NULL;
6377 	enum bpf_type_flag flag = 0;
6378 	u32 btf_id = 0;
6379 	int ret;
6380 
6381 	if (!env->allow_ptr_leaks) {
6382 		verbose(env,
6383 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6384 			tname);
6385 		return -EPERM;
6386 	}
6387 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6388 		verbose(env,
6389 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6390 			tname);
6391 		return -EINVAL;
6392 	}
6393 	if (off < 0) {
6394 		verbose(env,
6395 			"R%d is ptr_%s invalid negative access: off=%d\n",
6396 			regno, tname, off);
6397 		return -EACCES;
6398 	}
6399 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6400 		char tn_buf[48];
6401 
6402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6403 		verbose(env,
6404 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6405 			regno, tname, off, tn_buf);
6406 		return -EACCES;
6407 	}
6408 
6409 	if (reg->type & MEM_USER) {
6410 		verbose(env,
6411 			"R%d is ptr_%s access user memory: off=%d\n",
6412 			regno, tname, off);
6413 		return -EACCES;
6414 	}
6415 
6416 	if (reg->type & MEM_PERCPU) {
6417 		verbose(env,
6418 			"R%d is ptr_%s access percpu memory: off=%d\n",
6419 			regno, tname, off);
6420 		return -EACCES;
6421 	}
6422 
6423 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6424 		if (!btf_is_kernel(reg->btf)) {
6425 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6426 			return -EFAULT;
6427 		}
6428 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6429 	} else {
6430 		/* Writes are permitted with default btf_struct_access for
6431 		 * program allocated objects (which always have ref_obj_id > 0),
6432 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6433 		 */
6434 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6435 			verbose(env, "only read is supported\n");
6436 			return -EACCES;
6437 		}
6438 
6439 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6440 		    !reg->ref_obj_id) {
6441 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6442 			return -EFAULT;
6443 		}
6444 
6445 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6446 	}
6447 
6448 	if (ret < 0)
6449 		return ret;
6450 
6451 	if (ret != PTR_TO_BTF_ID) {
6452 		/* just mark; */
6453 
6454 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6455 		/* If this is an untrusted pointer, all pointers formed by walking it
6456 		 * also inherit the untrusted flag.
6457 		 */
6458 		flag = PTR_UNTRUSTED;
6459 
6460 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6461 		/* By default any pointer obtained from walking a trusted pointer is no
6462 		 * longer trusted, unless the field being accessed has explicitly been
6463 		 * marked as inheriting its parent's state of trust (either full or RCU).
6464 		 * For example:
6465 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6466 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6467 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6468 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6469 		 *
6470 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6471 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6472 		 */
6473 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6474 			flag |= PTR_TRUSTED;
6475 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6476 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6477 				/* ignore __rcu tag and mark it MEM_RCU */
6478 				flag |= MEM_RCU;
6479 			} else if (flag & MEM_RCU ||
6480 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6481 				/* __rcu tagged pointers can be NULL */
6482 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6483 
6484 				/* We always trust them */
6485 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6486 				    flag & PTR_UNTRUSTED)
6487 					flag &= ~PTR_UNTRUSTED;
6488 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6489 				/* keep as-is */
6490 			} else {
6491 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6492 				clear_trusted_flags(&flag);
6493 			}
6494 		} else {
6495 			/*
6496 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6497 			 * aggressively mark as untrusted otherwise such
6498 			 * pointers will be plain PTR_TO_BTF_ID without flags
6499 			 * and will be allowed to be passed into helpers for
6500 			 * compat reasons.
6501 			 */
6502 			flag = PTR_UNTRUSTED;
6503 		}
6504 	} else {
6505 		/* Old compat. Deprecated */
6506 		clear_trusted_flags(&flag);
6507 	}
6508 
6509 	if (atype == BPF_READ && value_regno >= 0)
6510 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6511 
6512 	return 0;
6513 }
6514 
6515 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6516 				   struct bpf_reg_state *regs,
6517 				   int regno, int off, int size,
6518 				   enum bpf_access_type atype,
6519 				   int value_regno)
6520 {
6521 	struct bpf_reg_state *reg = regs + regno;
6522 	struct bpf_map *map = reg->map_ptr;
6523 	struct bpf_reg_state map_reg;
6524 	enum bpf_type_flag flag = 0;
6525 	const struct btf_type *t;
6526 	const char *tname;
6527 	u32 btf_id;
6528 	int ret;
6529 
6530 	if (!btf_vmlinux) {
6531 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6532 		return -ENOTSUPP;
6533 	}
6534 
6535 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6536 		verbose(env, "map_ptr access not supported for map type %d\n",
6537 			map->map_type);
6538 		return -ENOTSUPP;
6539 	}
6540 
6541 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6542 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6543 
6544 	if (!env->allow_ptr_leaks) {
6545 		verbose(env,
6546 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6547 			tname);
6548 		return -EPERM;
6549 	}
6550 
6551 	if (off < 0) {
6552 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6553 			regno, tname, off);
6554 		return -EACCES;
6555 	}
6556 
6557 	if (atype != BPF_READ) {
6558 		verbose(env, "only read from %s is supported\n", tname);
6559 		return -EACCES;
6560 	}
6561 
6562 	/* Simulate access to a PTR_TO_BTF_ID */
6563 	memset(&map_reg, 0, sizeof(map_reg));
6564 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6565 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6566 	if (ret < 0)
6567 		return ret;
6568 
6569 	if (value_regno >= 0)
6570 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6571 
6572 	return 0;
6573 }
6574 
6575 /* Check that the stack access at the given offset is within bounds. The
6576  * maximum valid offset is -1.
6577  *
6578  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6579  * -state->allocated_stack for reads.
6580  */
6581 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6582                                           s64 off,
6583                                           struct bpf_func_state *state,
6584                                           enum bpf_access_type t)
6585 {
6586 	int min_valid_off;
6587 
6588 	if (t == BPF_WRITE || env->allow_uninit_stack)
6589 		min_valid_off = -MAX_BPF_STACK;
6590 	else
6591 		min_valid_off = -state->allocated_stack;
6592 
6593 	if (off < min_valid_off || off > -1)
6594 		return -EACCES;
6595 	return 0;
6596 }
6597 
6598 /* Check that the stack access at 'regno + off' falls within the maximum stack
6599  * bounds.
6600  *
6601  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6602  */
6603 static int check_stack_access_within_bounds(
6604 		struct bpf_verifier_env *env,
6605 		int regno, int off, int access_size,
6606 		enum bpf_access_src src, enum bpf_access_type type)
6607 {
6608 	struct bpf_reg_state *regs = cur_regs(env);
6609 	struct bpf_reg_state *reg = regs + regno;
6610 	struct bpf_func_state *state = func(env, reg);
6611 	s64 min_off, max_off;
6612 	int err;
6613 	char *err_extra;
6614 
6615 	if (src == ACCESS_HELPER)
6616 		/* We don't know if helpers are reading or writing (or both). */
6617 		err_extra = " indirect access to";
6618 	else if (type == BPF_READ)
6619 		err_extra = " read from";
6620 	else
6621 		err_extra = " write to";
6622 
6623 	if (tnum_is_const(reg->var_off)) {
6624 		min_off = (s64)reg->var_off.value + off;
6625 		max_off = min_off + access_size;
6626 	} else {
6627 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6628 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6629 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6630 				err_extra, regno);
6631 			return -EACCES;
6632 		}
6633 		min_off = reg->smin_value + off;
6634 		max_off = reg->smax_value + off + access_size;
6635 	}
6636 
6637 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6638 	if (!err && max_off > 0)
6639 		err = -EINVAL; /* out of stack access into non-negative offsets */
6640 	if (!err && access_size < 0)
6641 		/* access_size should not be negative (or overflow an int); others checks
6642 		 * along the way should have prevented such an access.
6643 		 */
6644 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6645 
6646 	if (err) {
6647 		if (tnum_is_const(reg->var_off)) {
6648 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6649 				err_extra, regno, off, access_size);
6650 		} else {
6651 			char tn_buf[48];
6652 
6653 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6654 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6655 				err_extra, regno, tn_buf, access_size);
6656 		}
6657 		return err;
6658 	}
6659 
6660 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6661 }
6662 
6663 /* check whether memory at (regno + off) is accessible for t = (read | write)
6664  * if t==write, value_regno is a register which value is stored into memory
6665  * if t==read, value_regno is a register which will receive the value from memory
6666  * if t==write && value_regno==-1, some unknown value is stored into memory
6667  * if t==read && value_regno==-1, don't care what we read from memory
6668  */
6669 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6670 			    int off, int bpf_size, enum bpf_access_type t,
6671 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6672 {
6673 	struct bpf_reg_state *regs = cur_regs(env);
6674 	struct bpf_reg_state *reg = regs + regno;
6675 	int size, err = 0;
6676 
6677 	size = bpf_size_to_bytes(bpf_size);
6678 	if (size < 0)
6679 		return size;
6680 
6681 	/* alignment checks will add in reg->off themselves */
6682 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6683 	if (err)
6684 		return err;
6685 
6686 	/* for access checks, reg->off is just part of off */
6687 	off += reg->off;
6688 
6689 	if (reg->type == PTR_TO_MAP_KEY) {
6690 		if (t == BPF_WRITE) {
6691 			verbose(env, "write to change key R%d not allowed\n", regno);
6692 			return -EACCES;
6693 		}
6694 
6695 		err = check_mem_region_access(env, regno, off, size,
6696 					      reg->map_ptr->key_size, false);
6697 		if (err)
6698 			return err;
6699 		if (value_regno >= 0)
6700 			mark_reg_unknown(env, regs, value_regno);
6701 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6702 		struct btf_field *kptr_field = NULL;
6703 
6704 		if (t == BPF_WRITE && value_regno >= 0 &&
6705 		    is_pointer_value(env, value_regno)) {
6706 			verbose(env, "R%d leaks addr into map\n", value_regno);
6707 			return -EACCES;
6708 		}
6709 		err = check_map_access_type(env, regno, off, size, t);
6710 		if (err)
6711 			return err;
6712 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6713 		if (err)
6714 			return err;
6715 		if (tnum_is_const(reg->var_off))
6716 			kptr_field = btf_record_find(reg->map_ptr->record,
6717 						     off + reg->var_off.value, BPF_KPTR);
6718 		if (kptr_field) {
6719 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6720 		} else if (t == BPF_READ && value_regno >= 0) {
6721 			struct bpf_map *map = reg->map_ptr;
6722 
6723 			/* if map is read-only, track its contents as scalars */
6724 			if (tnum_is_const(reg->var_off) &&
6725 			    bpf_map_is_rdonly(map) &&
6726 			    map->ops->map_direct_value_addr) {
6727 				int map_off = off + reg->var_off.value;
6728 				u64 val = 0;
6729 
6730 				err = bpf_map_direct_read(map, map_off, size,
6731 							  &val, is_ldsx);
6732 				if (err)
6733 					return err;
6734 
6735 				regs[value_regno].type = SCALAR_VALUE;
6736 				__mark_reg_known(&regs[value_regno], val);
6737 			} else {
6738 				mark_reg_unknown(env, regs, value_regno);
6739 			}
6740 		}
6741 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6742 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6743 
6744 		if (type_may_be_null(reg->type)) {
6745 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6746 				reg_type_str(env, reg->type));
6747 			return -EACCES;
6748 		}
6749 
6750 		if (t == BPF_WRITE && rdonly_mem) {
6751 			verbose(env, "R%d cannot write into %s\n",
6752 				regno, reg_type_str(env, reg->type));
6753 			return -EACCES;
6754 		}
6755 
6756 		if (t == BPF_WRITE && value_regno >= 0 &&
6757 		    is_pointer_value(env, value_regno)) {
6758 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6759 			return -EACCES;
6760 		}
6761 
6762 		err = check_mem_region_access(env, regno, off, size,
6763 					      reg->mem_size, false);
6764 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6765 			mark_reg_unknown(env, regs, value_regno);
6766 	} else if (reg->type == PTR_TO_CTX) {
6767 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6768 		struct btf *btf = NULL;
6769 		u32 btf_id = 0;
6770 
6771 		if (t == BPF_WRITE && value_regno >= 0 &&
6772 		    is_pointer_value(env, value_regno)) {
6773 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6774 			return -EACCES;
6775 		}
6776 
6777 		err = check_ptr_off_reg(env, reg, regno);
6778 		if (err < 0)
6779 			return err;
6780 
6781 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6782 				       &btf_id);
6783 		if (err)
6784 			verbose_linfo(env, insn_idx, "; ");
6785 		if (!err && t == BPF_READ && value_regno >= 0) {
6786 			/* ctx access returns either a scalar, or a
6787 			 * PTR_TO_PACKET[_META,_END]. In the latter
6788 			 * case, we know the offset is zero.
6789 			 */
6790 			if (reg_type == SCALAR_VALUE) {
6791 				mark_reg_unknown(env, regs, value_regno);
6792 			} else {
6793 				mark_reg_known_zero(env, regs,
6794 						    value_regno);
6795 				if (type_may_be_null(reg_type))
6796 					regs[value_regno].id = ++env->id_gen;
6797 				/* A load of ctx field could have different
6798 				 * actual load size with the one encoded in the
6799 				 * insn. When the dst is PTR, it is for sure not
6800 				 * a sub-register.
6801 				 */
6802 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6803 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6804 					regs[value_regno].btf = btf;
6805 					regs[value_regno].btf_id = btf_id;
6806 				}
6807 			}
6808 			regs[value_regno].type = reg_type;
6809 		}
6810 
6811 	} else if (reg->type == PTR_TO_STACK) {
6812 		/* Basic bounds checks. */
6813 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6814 		if (err)
6815 			return err;
6816 
6817 		if (t == BPF_READ)
6818 			err = check_stack_read(env, regno, off, size,
6819 					       value_regno);
6820 		else
6821 			err = check_stack_write(env, regno, off, size,
6822 						value_regno, insn_idx);
6823 	} else if (reg_is_pkt_pointer(reg)) {
6824 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6825 			verbose(env, "cannot write into packet\n");
6826 			return -EACCES;
6827 		}
6828 		if (t == BPF_WRITE && value_regno >= 0 &&
6829 		    is_pointer_value(env, value_regno)) {
6830 			verbose(env, "R%d leaks addr into packet\n",
6831 				value_regno);
6832 			return -EACCES;
6833 		}
6834 		err = check_packet_access(env, regno, off, size, false);
6835 		if (!err && t == BPF_READ && value_regno >= 0)
6836 			mark_reg_unknown(env, regs, value_regno);
6837 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6838 		if (t == BPF_WRITE && value_regno >= 0 &&
6839 		    is_pointer_value(env, value_regno)) {
6840 			verbose(env, "R%d leaks addr into flow keys\n",
6841 				value_regno);
6842 			return -EACCES;
6843 		}
6844 
6845 		err = check_flow_keys_access(env, off, size);
6846 		if (!err && t == BPF_READ && value_regno >= 0)
6847 			mark_reg_unknown(env, regs, value_regno);
6848 	} else if (type_is_sk_pointer(reg->type)) {
6849 		if (t == BPF_WRITE) {
6850 			verbose(env, "R%d cannot write into %s\n",
6851 				regno, reg_type_str(env, reg->type));
6852 			return -EACCES;
6853 		}
6854 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6855 		if (!err && value_regno >= 0)
6856 			mark_reg_unknown(env, regs, value_regno);
6857 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6858 		err = check_tp_buffer_access(env, reg, regno, off, size);
6859 		if (!err && t == BPF_READ && value_regno >= 0)
6860 			mark_reg_unknown(env, regs, value_regno);
6861 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6862 		   !type_may_be_null(reg->type)) {
6863 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6864 					      value_regno);
6865 	} else if (reg->type == CONST_PTR_TO_MAP) {
6866 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6867 					      value_regno);
6868 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6869 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6870 		u32 *max_access;
6871 
6872 		if (rdonly_mem) {
6873 			if (t == BPF_WRITE) {
6874 				verbose(env, "R%d cannot write into %s\n",
6875 					regno, reg_type_str(env, reg->type));
6876 				return -EACCES;
6877 			}
6878 			max_access = &env->prog->aux->max_rdonly_access;
6879 		} else {
6880 			max_access = &env->prog->aux->max_rdwr_access;
6881 		}
6882 
6883 		err = check_buffer_access(env, reg, regno, off, size, false,
6884 					  max_access);
6885 
6886 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6887 			mark_reg_unknown(env, regs, value_regno);
6888 	} else {
6889 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6890 			reg_type_str(env, reg->type));
6891 		return -EACCES;
6892 	}
6893 
6894 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6895 	    regs[value_regno].type == SCALAR_VALUE) {
6896 		if (!is_ldsx)
6897 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6898 			coerce_reg_to_size(&regs[value_regno], size);
6899 		else
6900 			coerce_reg_to_size_sx(&regs[value_regno], size);
6901 	}
6902 	return err;
6903 }
6904 
6905 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6906 {
6907 	int load_reg;
6908 	int err;
6909 
6910 	switch (insn->imm) {
6911 	case BPF_ADD:
6912 	case BPF_ADD | BPF_FETCH:
6913 	case BPF_AND:
6914 	case BPF_AND | BPF_FETCH:
6915 	case BPF_OR:
6916 	case BPF_OR | BPF_FETCH:
6917 	case BPF_XOR:
6918 	case BPF_XOR | BPF_FETCH:
6919 	case BPF_XCHG:
6920 	case BPF_CMPXCHG:
6921 		break;
6922 	default:
6923 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6924 		return -EINVAL;
6925 	}
6926 
6927 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6928 		verbose(env, "invalid atomic operand size\n");
6929 		return -EINVAL;
6930 	}
6931 
6932 	/* check src1 operand */
6933 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6934 	if (err)
6935 		return err;
6936 
6937 	/* check src2 operand */
6938 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6939 	if (err)
6940 		return err;
6941 
6942 	if (insn->imm == BPF_CMPXCHG) {
6943 		/* Check comparison of R0 with memory location */
6944 		const u32 aux_reg = BPF_REG_0;
6945 
6946 		err = check_reg_arg(env, aux_reg, SRC_OP);
6947 		if (err)
6948 			return err;
6949 
6950 		if (is_pointer_value(env, aux_reg)) {
6951 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6952 			return -EACCES;
6953 		}
6954 	}
6955 
6956 	if (is_pointer_value(env, insn->src_reg)) {
6957 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6958 		return -EACCES;
6959 	}
6960 
6961 	if (is_ctx_reg(env, insn->dst_reg) ||
6962 	    is_pkt_reg(env, insn->dst_reg) ||
6963 	    is_flow_key_reg(env, insn->dst_reg) ||
6964 	    is_sk_reg(env, insn->dst_reg)) {
6965 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6966 			insn->dst_reg,
6967 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6968 		return -EACCES;
6969 	}
6970 
6971 	if (insn->imm & BPF_FETCH) {
6972 		if (insn->imm == BPF_CMPXCHG)
6973 			load_reg = BPF_REG_0;
6974 		else
6975 			load_reg = insn->src_reg;
6976 
6977 		/* check and record load of old value */
6978 		err = check_reg_arg(env, load_reg, DST_OP);
6979 		if (err)
6980 			return err;
6981 	} else {
6982 		/* This instruction accesses a memory location but doesn't
6983 		 * actually load it into a register.
6984 		 */
6985 		load_reg = -1;
6986 	}
6987 
6988 	/* Check whether we can read the memory, with second call for fetch
6989 	 * case to simulate the register fill.
6990 	 */
6991 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6992 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6993 	if (!err && load_reg >= 0)
6994 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6995 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
6996 				       true, false);
6997 	if (err)
6998 		return err;
6999 
7000 	/* Check whether we can write into the same memory. */
7001 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7002 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7003 	if (err)
7004 		return err;
7005 
7006 	return 0;
7007 }
7008 
7009 /* When register 'regno' is used to read the stack (either directly or through
7010  * a helper function) make sure that it's within stack boundary and, depending
7011  * on the access type and privileges, that all elements of the stack are
7012  * initialized.
7013  *
7014  * 'off' includes 'regno->off', but not its dynamic part (if any).
7015  *
7016  * All registers that have been spilled on the stack in the slots within the
7017  * read offsets are marked as read.
7018  */
7019 static int check_stack_range_initialized(
7020 		struct bpf_verifier_env *env, int regno, int off,
7021 		int access_size, bool zero_size_allowed,
7022 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7023 {
7024 	struct bpf_reg_state *reg = reg_state(env, regno);
7025 	struct bpf_func_state *state = func(env, reg);
7026 	int err, min_off, max_off, i, j, slot, spi;
7027 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7028 	enum bpf_access_type bounds_check_type;
7029 	/* Some accesses can write anything into the stack, others are
7030 	 * read-only.
7031 	 */
7032 	bool clobber = false;
7033 
7034 	if (access_size == 0 && !zero_size_allowed) {
7035 		verbose(env, "invalid zero-sized read\n");
7036 		return -EACCES;
7037 	}
7038 
7039 	if (type == ACCESS_HELPER) {
7040 		/* The bounds checks for writes are more permissive than for
7041 		 * reads. However, if raw_mode is not set, we'll do extra
7042 		 * checks below.
7043 		 */
7044 		bounds_check_type = BPF_WRITE;
7045 		clobber = true;
7046 	} else {
7047 		bounds_check_type = BPF_READ;
7048 	}
7049 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7050 					       type, bounds_check_type);
7051 	if (err)
7052 		return err;
7053 
7054 
7055 	if (tnum_is_const(reg->var_off)) {
7056 		min_off = max_off = reg->var_off.value + off;
7057 	} else {
7058 		/* Variable offset is prohibited for unprivileged mode for
7059 		 * simplicity since it requires corresponding support in
7060 		 * Spectre masking for stack ALU.
7061 		 * See also retrieve_ptr_limit().
7062 		 */
7063 		if (!env->bypass_spec_v1) {
7064 			char tn_buf[48];
7065 
7066 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7067 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7068 				regno, err_extra, tn_buf);
7069 			return -EACCES;
7070 		}
7071 		/* Only initialized buffer on stack is allowed to be accessed
7072 		 * with variable offset. With uninitialized buffer it's hard to
7073 		 * guarantee that whole memory is marked as initialized on
7074 		 * helper return since specific bounds are unknown what may
7075 		 * cause uninitialized stack leaking.
7076 		 */
7077 		if (meta && meta->raw_mode)
7078 			meta = NULL;
7079 
7080 		min_off = reg->smin_value + off;
7081 		max_off = reg->smax_value + off;
7082 	}
7083 
7084 	if (meta && meta->raw_mode) {
7085 		/* Ensure we won't be overwriting dynptrs when simulating byte
7086 		 * by byte access in check_helper_call using meta.access_size.
7087 		 * This would be a problem if we have a helper in the future
7088 		 * which takes:
7089 		 *
7090 		 *	helper(uninit_mem, len, dynptr)
7091 		 *
7092 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7093 		 * may end up writing to dynptr itself when touching memory from
7094 		 * arg 1. This can be relaxed on a case by case basis for known
7095 		 * safe cases, but reject due to the possibilitiy of aliasing by
7096 		 * default.
7097 		 */
7098 		for (i = min_off; i < max_off + access_size; i++) {
7099 			int stack_off = -i - 1;
7100 
7101 			spi = __get_spi(i);
7102 			/* raw_mode may write past allocated_stack */
7103 			if (state->allocated_stack <= stack_off)
7104 				continue;
7105 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7106 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7107 				return -EACCES;
7108 			}
7109 		}
7110 		meta->access_size = access_size;
7111 		meta->regno = regno;
7112 		return 0;
7113 	}
7114 
7115 	for (i = min_off; i < max_off + access_size; i++) {
7116 		u8 *stype;
7117 
7118 		slot = -i - 1;
7119 		spi = slot / BPF_REG_SIZE;
7120 		if (state->allocated_stack <= slot) {
7121 			verbose(env, "verifier bug: allocated_stack too small");
7122 			return -EFAULT;
7123 		}
7124 
7125 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7126 		if (*stype == STACK_MISC)
7127 			goto mark;
7128 		if ((*stype == STACK_ZERO) ||
7129 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7130 			if (clobber) {
7131 				/* helper can write anything into the stack */
7132 				*stype = STACK_MISC;
7133 			}
7134 			goto mark;
7135 		}
7136 
7137 		if (is_spilled_reg(&state->stack[spi]) &&
7138 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7139 		     env->allow_ptr_leaks)) {
7140 			if (clobber) {
7141 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7142 				for (j = 0; j < BPF_REG_SIZE; j++)
7143 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7144 			}
7145 			goto mark;
7146 		}
7147 
7148 		if (tnum_is_const(reg->var_off)) {
7149 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7150 				err_extra, regno, min_off, i - min_off, access_size);
7151 		} else {
7152 			char tn_buf[48];
7153 
7154 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7155 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7156 				err_extra, regno, tn_buf, i - min_off, access_size);
7157 		}
7158 		return -EACCES;
7159 mark:
7160 		/* reading any byte out of 8-byte 'spill_slot' will cause
7161 		 * the whole slot to be marked as 'read'
7162 		 */
7163 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7164 			      state->stack[spi].spilled_ptr.parent,
7165 			      REG_LIVE_READ64);
7166 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7167 		 * be sure that whether stack slot is written to or not. Hence,
7168 		 * we must still conservatively propagate reads upwards even if
7169 		 * helper may write to the entire memory range.
7170 		 */
7171 	}
7172 	return 0;
7173 }
7174 
7175 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7176 				   int access_size, bool zero_size_allowed,
7177 				   struct bpf_call_arg_meta *meta)
7178 {
7179 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7180 	u32 *max_access;
7181 
7182 	switch (base_type(reg->type)) {
7183 	case PTR_TO_PACKET:
7184 	case PTR_TO_PACKET_META:
7185 		return check_packet_access(env, regno, reg->off, access_size,
7186 					   zero_size_allowed);
7187 	case PTR_TO_MAP_KEY:
7188 		if (meta && meta->raw_mode) {
7189 			verbose(env, "R%d cannot write into %s\n", regno,
7190 				reg_type_str(env, reg->type));
7191 			return -EACCES;
7192 		}
7193 		return check_mem_region_access(env, regno, reg->off, access_size,
7194 					       reg->map_ptr->key_size, false);
7195 	case PTR_TO_MAP_VALUE:
7196 		if (check_map_access_type(env, regno, reg->off, access_size,
7197 					  meta && meta->raw_mode ? BPF_WRITE :
7198 					  BPF_READ))
7199 			return -EACCES;
7200 		return check_map_access(env, regno, reg->off, access_size,
7201 					zero_size_allowed, ACCESS_HELPER);
7202 	case PTR_TO_MEM:
7203 		if (type_is_rdonly_mem(reg->type)) {
7204 			if (meta && meta->raw_mode) {
7205 				verbose(env, "R%d cannot write into %s\n", regno,
7206 					reg_type_str(env, reg->type));
7207 				return -EACCES;
7208 			}
7209 		}
7210 		return check_mem_region_access(env, regno, reg->off,
7211 					       access_size, reg->mem_size,
7212 					       zero_size_allowed);
7213 	case PTR_TO_BUF:
7214 		if (type_is_rdonly_mem(reg->type)) {
7215 			if (meta && meta->raw_mode) {
7216 				verbose(env, "R%d cannot write into %s\n", regno,
7217 					reg_type_str(env, reg->type));
7218 				return -EACCES;
7219 			}
7220 
7221 			max_access = &env->prog->aux->max_rdonly_access;
7222 		} else {
7223 			max_access = &env->prog->aux->max_rdwr_access;
7224 		}
7225 		return check_buffer_access(env, reg, regno, reg->off,
7226 					   access_size, zero_size_allowed,
7227 					   max_access);
7228 	case PTR_TO_STACK:
7229 		return check_stack_range_initialized(
7230 				env,
7231 				regno, reg->off, access_size,
7232 				zero_size_allowed, ACCESS_HELPER, meta);
7233 	case PTR_TO_BTF_ID:
7234 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7235 					       access_size, BPF_READ, -1);
7236 	case PTR_TO_CTX:
7237 		/* in case the function doesn't know how to access the context,
7238 		 * (because we are in a program of type SYSCALL for example), we
7239 		 * can not statically check its size.
7240 		 * Dynamically check it now.
7241 		 */
7242 		if (!env->ops->convert_ctx_access) {
7243 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7244 			int offset = access_size - 1;
7245 
7246 			/* Allow zero-byte read from PTR_TO_CTX */
7247 			if (access_size == 0)
7248 				return zero_size_allowed ? 0 : -EACCES;
7249 
7250 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7251 						atype, -1, false, false);
7252 		}
7253 
7254 		fallthrough;
7255 	default: /* scalar_value or invalid ptr */
7256 		/* Allow zero-byte read from NULL, regardless of pointer type */
7257 		if (zero_size_allowed && access_size == 0 &&
7258 		    register_is_null(reg))
7259 			return 0;
7260 
7261 		verbose(env, "R%d type=%s ", regno,
7262 			reg_type_str(env, reg->type));
7263 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7264 		return -EACCES;
7265 	}
7266 }
7267 
7268 static int check_mem_size_reg(struct bpf_verifier_env *env,
7269 			      struct bpf_reg_state *reg, u32 regno,
7270 			      bool zero_size_allowed,
7271 			      struct bpf_call_arg_meta *meta)
7272 {
7273 	int err;
7274 
7275 	/* This is used to refine r0 return value bounds for helpers
7276 	 * that enforce this value as an upper bound on return values.
7277 	 * See do_refine_retval_range() for helpers that can refine
7278 	 * the return value. C type of helper is u32 so we pull register
7279 	 * bound from umax_value however, if negative verifier errors
7280 	 * out. Only upper bounds can be learned because retval is an
7281 	 * int type and negative retvals are allowed.
7282 	 */
7283 	meta->msize_max_value = reg->umax_value;
7284 
7285 	/* The register is SCALAR_VALUE; the access check
7286 	 * happens using its boundaries.
7287 	 */
7288 	if (!tnum_is_const(reg->var_off))
7289 		/* For unprivileged variable accesses, disable raw
7290 		 * mode so that the program is required to
7291 		 * initialize all the memory that the helper could
7292 		 * just partially fill up.
7293 		 */
7294 		meta = NULL;
7295 
7296 	if (reg->smin_value < 0) {
7297 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7298 			regno);
7299 		return -EACCES;
7300 	}
7301 
7302 	if (reg->umin_value == 0) {
7303 		err = check_helper_mem_access(env, regno - 1, 0,
7304 					      zero_size_allowed,
7305 					      meta);
7306 		if (err)
7307 			return err;
7308 	}
7309 
7310 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7311 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7312 			regno);
7313 		return -EACCES;
7314 	}
7315 	err = check_helper_mem_access(env, regno - 1,
7316 				      reg->umax_value,
7317 				      zero_size_allowed, meta);
7318 	if (!err)
7319 		err = mark_chain_precision(env, regno);
7320 	return err;
7321 }
7322 
7323 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7324 		   u32 regno, u32 mem_size)
7325 {
7326 	bool may_be_null = type_may_be_null(reg->type);
7327 	struct bpf_reg_state saved_reg;
7328 	struct bpf_call_arg_meta meta;
7329 	int err;
7330 
7331 	if (register_is_null(reg))
7332 		return 0;
7333 
7334 	memset(&meta, 0, sizeof(meta));
7335 	/* Assuming that the register contains a value check if the memory
7336 	 * access is safe. Temporarily save and restore the register's state as
7337 	 * the conversion shouldn't be visible to a caller.
7338 	 */
7339 	if (may_be_null) {
7340 		saved_reg = *reg;
7341 		mark_ptr_not_null_reg(reg);
7342 	}
7343 
7344 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7345 	/* Check access for BPF_WRITE */
7346 	meta.raw_mode = true;
7347 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7348 
7349 	if (may_be_null)
7350 		*reg = saved_reg;
7351 
7352 	return err;
7353 }
7354 
7355 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7356 				    u32 regno)
7357 {
7358 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7359 	bool may_be_null = type_may_be_null(mem_reg->type);
7360 	struct bpf_reg_state saved_reg;
7361 	struct bpf_call_arg_meta meta;
7362 	int err;
7363 
7364 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7365 
7366 	memset(&meta, 0, sizeof(meta));
7367 
7368 	if (may_be_null) {
7369 		saved_reg = *mem_reg;
7370 		mark_ptr_not_null_reg(mem_reg);
7371 	}
7372 
7373 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7374 	/* Check access for BPF_WRITE */
7375 	meta.raw_mode = true;
7376 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7377 
7378 	if (may_be_null)
7379 		*mem_reg = saved_reg;
7380 	return err;
7381 }
7382 
7383 /* Implementation details:
7384  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7385  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7386  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7387  * Two separate bpf_obj_new will also have different reg->id.
7388  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7389  * clears reg->id after value_or_null->value transition, since the verifier only
7390  * cares about the range of access to valid map value pointer and doesn't care
7391  * about actual address of the map element.
7392  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7393  * reg->id > 0 after value_or_null->value transition. By doing so
7394  * two bpf_map_lookups will be considered two different pointers that
7395  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7396  * returned from bpf_obj_new.
7397  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7398  * dead-locks.
7399  * Since only one bpf_spin_lock is allowed the checks are simpler than
7400  * reg_is_refcounted() logic. The verifier needs to remember only
7401  * one spin_lock instead of array of acquired_refs.
7402  * cur_state->active_lock remembers which map value element or allocated
7403  * object got locked and clears it after bpf_spin_unlock.
7404  */
7405 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7406 			     bool is_lock)
7407 {
7408 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7409 	struct bpf_verifier_state *cur = env->cur_state;
7410 	bool is_const = tnum_is_const(reg->var_off);
7411 	u64 val = reg->var_off.value;
7412 	struct bpf_map *map = NULL;
7413 	struct btf *btf = NULL;
7414 	struct btf_record *rec;
7415 
7416 	if (!is_const) {
7417 		verbose(env,
7418 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7419 			regno);
7420 		return -EINVAL;
7421 	}
7422 	if (reg->type == PTR_TO_MAP_VALUE) {
7423 		map = reg->map_ptr;
7424 		if (!map->btf) {
7425 			verbose(env,
7426 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7427 				map->name);
7428 			return -EINVAL;
7429 		}
7430 	} else {
7431 		btf = reg->btf;
7432 	}
7433 
7434 	rec = reg_btf_record(reg);
7435 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7436 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7437 			map ? map->name : "kptr");
7438 		return -EINVAL;
7439 	}
7440 	if (rec->spin_lock_off != val + reg->off) {
7441 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7442 			val + reg->off, rec->spin_lock_off);
7443 		return -EINVAL;
7444 	}
7445 	if (is_lock) {
7446 		if (cur->active_lock.ptr) {
7447 			verbose(env,
7448 				"Locking two bpf_spin_locks are not allowed\n");
7449 			return -EINVAL;
7450 		}
7451 		if (map)
7452 			cur->active_lock.ptr = map;
7453 		else
7454 			cur->active_lock.ptr = btf;
7455 		cur->active_lock.id = reg->id;
7456 	} else {
7457 		void *ptr;
7458 
7459 		if (map)
7460 			ptr = map;
7461 		else
7462 			ptr = btf;
7463 
7464 		if (!cur->active_lock.ptr) {
7465 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7466 			return -EINVAL;
7467 		}
7468 		if (cur->active_lock.ptr != ptr ||
7469 		    cur->active_lock.id != reg->id) {
7470 			verbose(env, "bpf_spin_unlock of different lock\n");
7471 			return -EINVAL;
7472 		}
7473 
7474 		invalidate_non_owning_refs(env);
7475 
7476 		cur->active_lock.ptr = NULL;
7477 		cur->active_lock.id = 0;
7478 	}
7479 	return 0;
7480 }
7481 
7482 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7483 			      struct bpf_call_arg_meta *meta)
7484 {
7485 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7486 	bool is_const = tnum_is_const(reg->var_off);
7487 	struct bpf_map *map = reg->map_ptr;
7488 	u64 val = reg->var_off.value;
7489 
7490 	if (!is_const) {
7491 		verbose(env,
7492 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7493 			regno);
7494 		return -EINVAL;
7495 	}
7496 	if (!map->btf) {
7497 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7498 			map->name);
7499 		return -EINVAL;
7500 	}
7501 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7502 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7503 		return -EINVAL;
7504 	}
7505 	if (map->record->timer_off != val + reg->off) {
7506 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7507 			val + reg->off, map->record->timer_off);
7508 		return -EINVAL;
7509 	}
7510 	if (meta->map_ptr) {
7511 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7512 		return -EFAULT;
7513 	}
7514 	meta->map_uid = reg->map_uid;
7515 	meta->map_ptr = map;
7516 	return 0;
7517 }
7518 
7519 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7520 			     struct bpf_call_arg_meta *meta)
7521 {
7522 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7523 	struct bpf_map *map_ptr = reg->map_ptr;
7524 	struct btf_field *kptr_field;
7525 	u32 kptr_off;
7526 
7527 	if (!tnum_is_const(reg->var_off)) {
7528 		verbose(env,
7529 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7530 			regno);
7531 		return -EINVAL;
7532 	}
7533 	if (!map_ptr->btf) {
7534 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7535 			map_ptr->name);
7536 		return -EINVAL;
7537 	}
7538 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7539 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7540 		return -EINVAL;
7541 	}
7542 
7543 	meta->map_ptr = map_ptr;
7544 	kptr_off = reg->off + reg->var_off.value;
7545 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7546 	if (!kptr_field) {
7547 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7548 		return -EACCES;
7549 	}
7550 	if (kptr_field->type != BPF_KPTR_REF) {
7551 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7552 		return -EACCES;
7553 	}
7554 	meta->kptr_field = kptr_field;
7555 	return 0;
7556 }
7557 
7558 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7559  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7560  *
7561  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7562  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7563  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7564  *
7565  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7566  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7567  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7568  * mutate the view of the dynptr and also possibly destroy it. In the latter
7569  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7570  * memory that dynptr points to.
7571  *
7572  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7573  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7574  * readonly dynptr view yet, hence only the first case is tracked and checked.
7575  *
7576  * This is consistent with how C applies the const modifier to a struct object,
7577  * where the pointer itself inside bpf_dynptr becomes const but not what it
7578  * points to.
7579  *
7580  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7581  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7582  */
7583 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7584 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7585 {
7586 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7587 	int err;
7588 
7589 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7590 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7591 	 */
7592 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7593 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7594 		return -EFAULT;
7595 	}
7596 
7597 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7598 	 *		 constructing a mutable bpf_dynptr object.
7599 	 *
7600 	 *		 Currently, this is only possible with PTR_TO_STACK
7601 	 *		 pointing to a region of at least 16 bytes which doesn't
7602 	 *		 contain an existing bpf_dynptr.
7603 	 *
7604 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7605 	 *		 mutated or destroyed. However, the memory it points to
7606 	 *		 may be mutated.
7607 	 *
7608 	 *  None       - Points to a initialized dynptr that can be mutated and
7609 	 *		 destroyed, including mutation of the memory it points
7610 	 *		 to.
7611 	 */
7612 	if (arg_type & MEM_UNINIT) {
7613 		int i;
7614 
7615 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7616 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7617 			return -EINVAL;
7618 		}
7619 
7620 		/* we write BPF_DW bits (8 bytes) at a time */
7621 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7622 			err = check_mem_access(env, insn_idx, regno,
7623 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7624 			if (err)
7625 				return err;
7626 		}
7627 
7628 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7629 	} else /* MEM_RDONLY and None case from above */ {
7630 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7631 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7632 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7633 			return -EINVAL;
7634 		}
7635 
7636 		if (!is_dynptr_reg_valid_init(env, reg)) {
7637 			verbose(env,
7638 				"Expected an initialized dynptr as arg #%d\n",
7639 				regno);
7640 			return -EINVAL;
7641 		}
7642 
7643 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7644 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7645 			verbose(env,
7646 				"Expected a dynptr of type %s as arg #%d\n",
7647 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7648 			return -EINVAL;
7649 		}
7650 
7651 		err = mark_dynptr_read(env, reg);
7652 	}
7653 	return err;
7654 }
7655 
7656 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7657 {
7658 	struct bpf_func_state *state = func(env, reg);
7659 
7660 	return state->stack[spi].spilled_ptr.ref_obj_id;
7661 }
7662 
7663 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7664 {
7665 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7666 }
7667 
7668 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7669 {
7670 	return meta->kfunc_flags & KF_ITER_NEW;
7671 }
7672 
7673 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7674 {
7675 	return meta->kfunc_flags & KF_ITER_NEXT;
7676 }
7677 
7678 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7679 {
7680 	return meta->kfunc_flags & KF_ITER_DESTROY;
7681 }
7682 
7683 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7684 {
7685 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7686 	 * kfunc is iter state pointer
7687 	 */
7688 	return arg == 0 && is_iter_kfunc(meta);
7689 }
7690 
7691 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7692 			    struct bpf_kfunc_call_arg_meta *meta)
7693 {
7694 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7695 	const struct btf_type *t;
7696 	const struct btf_param *arg;
7697 	int spi, err, i, nr_slots;
7698 	u32 btf_id;
7699 
7700 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7701 	arg = &btf_params(meta->func_proto)[0];
7702 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7703 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7704 	nr_slots = t->size / BPF_REG_SIZE;
7705 
7706 	if (is_iter_new_kfunc(meta)) {
7707 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7708 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7709 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7710 				iter_type_str(meta->btf, btf_id), regno);
7711 			return -EINVAL;
7712 		}
7713 
7714 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7715 			err = check_mem_access(env, insn_idx, regno,
7716 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7717 			if (err)
7718 				return err;
7719 		}
7720 
7721 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7722 		if (err)
7723 			return err;
7724 	} else {
7725 		/* iter_next() or iter_destroy() expect initialized iter state*/
7726 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7727 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7728 				iter_type_str(meta->btf, btf_id), regno);
7729 			return -EINVAL;
7730 		}
7731 
7732 		spi = iter_get_spi(env, reg, nr_slots);
7733 		if (spi < 0)
7734 			return spi;
7735 
7736 		err = mark_iter_read(env, reg, spi, nr_slots);
7737 		if (err)
7738 			return err;
7739 
7740 		/* remember meta->iter info for process_iter_next_call() */
7741 		meta->iter.spi = spi;
7742 		meta->iter.frameno = reg->frameno;
7743 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7744 
7745 		if (is_iter_destroy_kfunc(meta)) {
7746 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7747 			if (err)
7748 				return err;
7749 		}
7750 	}
7751 
7752 	return 0;
7753 }
7754 
7755 /* Look for a previous loop entry at insn_idx: nearest parent state
7756  * stopped at insn_idx with callsites matching those in cur->frame.
7757  */
7758 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7759 						  struct bpf_verifier_state *cur,
7760 						  int insn_idx)
7761 {
7762 	struct bpf_verifier_state_list *sl;
7763 	struct bpf_verifier_state *st;
7764 
7765 	/* Explored states are pushed in stack order, most recent states come first */
7766 	sl = *explored_state(env, insn_idx);
7767 	for (; sl; sl = sl->next) {
7768 		/* If st->branches != 0 state is a part of current DFS verification path,
7769 		 * hence cur & st for a loop.
7770 		 */
7771 		st = &sl->state;
7772 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7773 		    st->dfs_depth < cur->dfs_depth)
7774 			return st;
7775 	}
7776 
7777 	return NULL;
7778 }
7779 
7780 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7781 static bool regs_exact(const struct bpf_reg_state *rold,
7782 		       const struct bpf_reg_state *rcur,
7783 		       struct bpf_idmap *idmap);
7784 
7785 static void maybe_widen_reg(struct bpf_verifier_env *env,
7786 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7787 			    struct bpf_idmap *idmap)
7788 {
7789 	if (rold->type != SCALAR_VALUE)
7790 		return;
7791 	if (rold->type != rcur->type)
7792 		return;
7793 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7794 		return;
7795 	__mark_reg_unknown(env, rcur);
7796 }
7797 
7798 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7799 				   struct bpf_verifier_state *old,
7800 				   struct bpf_verifier_state *cur)
7801 {
7802 	struct bpf_func_state *fold, *fcur;
7803 	int i, fr;
7804 
7805 	reset_idmap_scratch(env);
7806 	for (fr = old->curframe; fr >= 0; fr--) {
7807 		fold = old->frame[fr];
7808 		fcur = cur->frame[fr];
7809 
7810 		for (i = 0; i < MAX_BPF_REG; i++)
7811 			maybe_widen_reg(env,
7812 					&fold->regs[i],
7813 					&fcur->regs[i],
7814 					&env->idmap_scratch);
7815 
7816 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7817 			if (!is_spilled_reg(&fold->stack[i]) ||
7818 			    !is_spilled_reg(&fcur->stack[i]))
7819 				continue;
7820 
7821 			maybe_widen_reg(env,
7822 					&fold->stack[i].spilled_ptr,
7823 					&fcur->stack[i].spilled_ptr,
7824 					&env->idmap_scratch);
7825 		}
7826 	}
7827 	return 0;
7828 }
7829 
7830 /* process_iter_next_call() is called when verifier gets to iterator's next
7831  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7832  * to it as just "iter_next()" in comments below.
7833  *
7834  * BPF verifier relies on a crucial contract for any iter_next()
7835  * implementation: it should *eventually* return NULL, and once that happens
7836  * it should keep returning NULL. That is, once iterator exhausts elements to
7837  * iterate, it should never reset or spuriously return new elements.
7838  *
7839  * With the assumption of such contract, process_iter_next_call() simulates
7840  * a fork in the verifier state to validate loop logic correctness and safety
7841  * without having to simulate infinite amount of iterations.
7842  *
7843  * In current state, we first assume that iter_next() returned NULL and
7844  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7845  * conditions we should not form an infinite loop and should eventually reach
7846  * exit.
7847  *
7848  * Besides that, we also fork current state and enqueue it for later
7849  * verification. In a forked state we keep iterator state as ACTIVE
7850  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7851  * also bump iteration depth to prevent erroneous infinite loop detection
7852  * later on (see iter_active_depths_differ() comment for details). In this
7853  * state we assume that we'll eventually loop back to another iter_next()
7854  * calls (it could be in exactly same location or in some other instruction,
7855  * it doesn't matter, we don't make any unnecessary assumptions about this,
7856  * everything revolves around iterator state in a stack slot, not which
7857  * instruction is calling iter_next()). When that happens, we either will come
7858  * to iter_next() with equivalent state and can conclude that next iteration
7859  * will proceed in exactly the same way as we just verified, so it's safe to
7860  * assume that loop converges. If not, we'll go on another iteration
7861  * simulation with a different input state, until all possible starting states
7862  * are validated or we reach maximum number of instructions limit.
7863  *
7864  * This way, we will either exhaustively discover all possible input states
7865  * that iterator loop can start with and eventually will converge, or we'll
7866  * effectively regress into bounded loop simulation logic and either reach
7867  * maximum number of instructions if loop is not provably convergent, or there
7868  * is some statically known limit on number of iterations (e.g., if there is
7869  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7870  *
7871  * Iteration convergence logic in is_state_visited() relies on exact
7872  * states comparison, which ignores read and precision marks.
7873  * This is necessary because read and precision marks are not finalized
7874  * while in the loop. Exact comparison might preclude convergence for
7875  * simple programs like below:
7876  *
7877  *     i = 0;
7878  *     while(iter_next(&it))
7879  *       i++;
7880  *
7881  * At each iteration step i++ would produce a new distinct state and
7882  * eventually instruction processing limit would be reached.
7883  *
7884  * To avoid such behavior speculatively forget (widen) range for
7885  * imprecise scalar registers, if those registers were not precise at the
7886  * end of the previous iteration and do not match exactly.
7887  *
7888  * This is a conservative heuristic that allows to verify wide range of programs,
7889  * however it precludes verification of programs that conjure an
7890  * imprecise value on the first loop iteration and use it as precise on a second.
7891  * For example, the following safe program would fail to verify:
7892  *
7893  *     struct bpf_num_iter it;
7894  *     int arr[10];
7895  *     int i = 0, a = 0;
7896  *     bpf_iter_num_new(&it, 0, 10);
7897  *     while (bpf_iter_num_next(&it)) {
7898  *       if (a == 0) {
7899  *         a = 1;
7900  *         i = 7; // Because i changed verifier would forget
7901  *                // it's range on second loop entry.
7902  *       } else {
7903  *         arr[i] = 42; // This would fail to verify.
7904  *       }
7905  *     }
7906  *     bpf_iter_num_destroy(&it);
7907  */
7908 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7909 				  struct bpf_kfunc_call_arg_meta *meta)
7910 {
7911 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7912 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7913 	struct bpf_reg_state *cur_iter, *queued_iter;
7914 	int iter_frameno = meta->iter.frameno;
7915 	int iter_spi = meta->iter.spi;
7916 
7917 	BTF_TYPE_EMIT(struct bpf_iter);
7918 
7919 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7920 
7921 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7922 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7923 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7924 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7925 		return -EFAULT;
7926 	}
7927 
7928 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7929 		/* Because iter_next() call is a checkpoint is_state_visitied()
7930 		 * should guarantee parent state with same call sites and insn_idx.
7931 		 */
7932 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7933 		    !same_callsites(cur_st->parent, cur_st)) {
7934 			verbose(env, "bug: bad parent state for iter next call");
7935 			return -EFAULT;
7936 		}
7937 		/* Note cur_st->parent in the call below, it is necessary to skip
7938 		 * checkpoint created for cur_st by is_state_visited()
7939 		 * right at this instruction.
7940 		 */
7941 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7942 		/* branch out active iter state */
7943 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7944 		if (!queued_st)
7945 			return -ENOMEM;
7946 
7947 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7948 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7949 		queued_iter->iter.depth++;
7950 		if (prev_st)
7951 			widen_imprecise_scalars(env, prev_st, queued_st);
7952 
7953 		queued_fr = queued_st->frame[queued_st->curframe];
7954 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7955 	}
7956 
7957 	/* switch to DRAINED state, but keep the depth unchanged */
7958 	/* mark current iter state as drained and assume returned NULL */
7959 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7960 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7961 
7962 	return 0;
7963 }
7964 
7965 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7966 {
7967 	return type == ARG_CONST_SIZE ||
7968 	       type == ARG_CONST_SIZE_OR_ZERO;
7969 }
7970 
7971 static bool arg_type_is_release(enum bpf_arg_type type)
7972 {
7973 	return type & OBJ_RELEASE;
7974 }
7975 
7976 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7977 {
7978 	return base_type(type) == ARG_PTR_TO_DYNPTR;
7979 }
7980 
7981 static int int_ptr_type_to_size(enum bpf_arg_type type)
7982 {
7983 	if (type == ARG_PTR_TO_INT)
7984 		return sizeof(u32);
7985 	else if (type == ARG_PTR_TO_LONG)
7986 		return sizeof(u64);
7987 
7988 	return -EINVAL;
7989 }
7990 
7991 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7992 				 const struct bpf_call_arg_meta *meta,
7993 				 enum bpf_arg_type *arg_type)
7994 {
7995 	if (!meta->map_ptr) {
7996 		/* kernel subsystem misconfigured verifier */
7997 		verbose(env, "invalid map_ptr to access map->type\n");
7998 		return -EACCES;
7999 	}
8000 
8001 	switch (meta->map_ptr->map_type) {
8002 	case BPF_MAP_TYPE_SOCKMAP:
8003 	case BPF_MAP_TYPE_SOCKHASH:
8004 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8005 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8006 		} else {
8007 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8008 			return -EINVAL;
8009 		}
8010 		break;
8011 	case BPF_MAP_TYPE_BLOOM_FILTER:
8012 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8013 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8014 		break;
8015 	default:
8016 		break;
8017 	}
8018 	return 0;
8019 }
8020 
8021 struct bpf_reg_types {
8022 	const enum bpf_reg_type types[10];
8023 	u32 *btf_id;
8024 };
8025 
8026 static const struct bpf_reg_types sock_types = {
8027 	.types = {
8028 		PTR_TO_SOCK_COMMON,
8029 		PTR_TO_SOCKET,
8030 		PTR_TO_TCP_SOCK,
8031 		PTR_TO_XDP_SOCK,
8032 	},
8033 };
8034 
8035 #ifdef CONFIG_NET
8036 static const struct bpf_reg_types btf_id_sock_common_types = {
8037 	.types = {
8038 		PTR_TO_SOCK_COMMON,
8039 		PTR_TO_SOCKET,
8040 		PTR_TO_TCP_SOCK,
8041 		PTR_TO_XDP_SOCK,
8042 		PTR_TO_BTF_ID,
8043 		PTR_TO_BTF_ID | PTR_TRUSTED,
8044 	},
8045 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8046 };
8047 #endif
8048 
8049 static const struct bpf_reg_types mem_types = {
8050 	.types = {
8051 		PTR_TO_STACK,
8052 		PTR_TO_PACKET,
8053 		PTR_TO_PACKET_META,
8054 		PTR_TO_MAP_KEY,
8055 		PTR_TO_MAP_VALUE,
8056 		PTR_TO_MEM,
8057 		PTR_TO_MEM | MEM_RINGBUF,
8058 		PTR_TO_BUF,
8059 		PTR_TO_BTF_ID | PTR_TRUSTED,
8060 	},
8061 };
8062 
8063 static const struct bpf_reg_types int_ptr_types = {
8064 	.types = {
8065 		PTR_TO_STACK,
8066 		PTR_TO_PACKET,
8067 		PTR_TO_PACKET_META,
8068 		PTR_TO_MAP_KEY,
8069 		PTR_TO_MAP_VALUE,
8070 	},
8071 };
8072 
8073 static const struct bpf_reg_types spin_lock_types = {
8074 	.types = {
8075 		PTR_TO_MAP_VALUE,
8076 		PTR_TO_BTF_ID | MEM_ALLOC,
8077 	}
8078 };
8079 
8080 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8081 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8082 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8083 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8084 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8085 static const struct bpf_reg_types btf_ptr_types = {
8086 	.types = {
8087 		PTR_TO_BTF_ID,
8088 		PTR_TO_BTF_ID | PTR_TRUSTED,
8089 		PTR_TO_BTF_ID | MEM_RCU,
8090 	},
8091 };
8092 static const struct bpf_reg_types percpu_btf_ptr_types = {
8093 	.types = {
8094 		PTR_TO_BTF_ID | MEM_PERCPU,
8095 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8096 	}
8097 };
8098 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8099 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8100 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8101 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8102 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8103 static const struct bpf_reg_types dynptr_types = {
8104 	.types = {
8105 		PTR_TO_STACK,
8106 		CONST_PTR_TO_DYNPTR,
8107 	}
8108 };
8109 
8110 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8111 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8112 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8113 	[ARG_CONST_SIZE]		= &scalar_types,
8114 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8115 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8116 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8117 	[ARG_PTR_TO_CTX]		= &context_types,
8118 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8119 #ifdef CONFIG_NET
8120 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8121 #endif
8122 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8123 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8124 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8125 	[ARG_PTR_TO_MEM]		= &mem_types,
8126 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8127 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8128 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8129 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8130 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8131 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8132 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8133 	[ARG_PTR_TO_TIMER]		= &timer_types,
8134 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8135 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8136 };
8137 
8138 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8139 			  enum bpf_arg_type arg_type,
8140 			  const u32 *arg_btf_id,
8141 			  struct bpf_call_arg_meta *meta)
8142 {
8143 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8144 	enum bpf_reg_type expected, type = reg->type;
8145 	const struct bpf_reg_types *compatible;
8146 	int i, j;
8147 
8148 	compatible = compatible_reg_types[base_type(arg_type)];
8149 	if (!compatible) {
8150 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8151 		return -EFAULT;
8152 	}
8153 
8154 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8155 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8156 	 *
8157 	 * Same for MAYBE_NULL:
8158 	 *
8159 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8160 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8161 	 *
8162 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8163 	 *
8164 	 * Therefore we fold these flags depending on the arg_type before comparison.
8165 	 */
8166 	if (arg_type & MEM_RDONLY)
8167 		type &= ~MEM_RDONLY;
8168 	if (arg_type & PTR_MAYBE_NULL)
8169 		type &= ~PTR_MAYBE_NULL;
8170 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8171 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8172 
8173 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8174 		type &= ~MEM_ALLOC;
8175 
8176 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8177 		expected = compatible->types[i];
8178 		if (expected == NOT_INIT)
8179 			break;
8180 
8181 		if (type == expected)
8182 			goto found;
8183 	}
8184 
8185 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8186 	for (j = 0; j + 1 < i; j++)
8187 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8188 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8189 	return -EACCES;
8190 
8191 found:
8192 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8193 		return 0;
8194 
8195 	if (compatible == &mem_types) {
8196 		if (!(arg_type & MEM_RDONLY)) {
8197 			verbose(env,
8198 				"%s() may write into memory pointed by R%d type=%s\n",
8199 				func_id_name(meta->func_id),
8200 				regno, reg_type_str(env, reg->type));
8201 			return -EACCES;
8202 		}
8203 		return 0;
8204 	}
8205 
8206 	switch ((int)reg->type) {
8207 	case PTR_TO_BTF_ID:
8208 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8209 	case PTR_TO_BTF_ID | MEM_RCU:
8210 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8211 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8212 	{
8213 		/* For bpf_sk_release, it needs to match against first member
8214 		 * 'struct sock_common', hence make an exception for it. This
8215 		 * allows bpf_sk_release to work for multiple socket types.
8216 		 */
8217 		bool strict_type_match = arg_type_is_release(arg_type) &&
8218 					 meta->func_id != BPF_FUNC_sk_release;
8219 
8220 		if (type_may_be_null(reg->type) &&
8221 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8222 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8223 			return -EACCES;
8224 		}
8225 
8226 		if (!arg_btf_id) {
8227 			if (!compatible->btf_id) {
8228 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8229 				return -EFAULT;
8230 			}
8231 			arg_btf_id = compatible->btf_id;
8232 		}
8233 
8234 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8235 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8236 				return -EACCES;
8237 		} else {
8238 			if (arg_btf_id == BPF_PTR_POISON) {
8239 				verbose(env, "verifier internal error:");
8240 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8241 					regno);
8242 				return -EACCES;
8243 			}
8244 
8245 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8246 						  btf_vmlinux, *arg_btf_id,
8247 						  strict_type_match)) {
8248 				verbose(env, "R%d is of type %s but %s is expected\n",
8249 					regno, btf_type_name(reg->btf, reg->btf_id),
8250 					btf_type_name(btf_vmlinux, *arg_btf_id));
8251 				return -EACCES;
8252 			}
8253 		}
8254 		break;
8255 	}
8256 	case PTR_TO_BTF_ID | MEM_ALLOC:
8257 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8258 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8259 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8260 			return -EFAULT;
8261 		}
8262 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8263 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8264 				return -EACCES;
8265 		}
8266 		break;
8267 	case PTR_TO_BTF_ID | MEM_PERCPU:
8268 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8269 		/* Handled by helper specific checks */
8270 		break;
8271 	default:
8272 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8273 		return -EFAULT;
8274 	}
8275 	return 0;
8276 }
8277 
8278 static struct btf_field *
8279 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8280 {
8281 	struct btf_field *field;
8282 	struct btf_record *rec;
8283 
8284 	rec = reg_btf_record(reg);
8285 	if (!rec)
8286 		return NULL;
8287 
8288 	field = btf_record_find(rec, off, fields);
8289 	if (!field)
8290 		return NULL;
8291 
8292 	return field;
8293 }
8294 
8295 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8296 			   const struct bpf_reg_state *reg, int regno,
8297 			   enum bpf_arg_type arg_type)
8298 {
8299 	u32 type = reg->type;
8300 
8301 	/* When referenced register is passed to release function, its fixed
8302 	 * offset must be 0.
8303 	 *
8304 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8305 	 * meta->release_regno.
8306 	 */
8307 	if (arg_type_is_release(arg_type)) {
8308 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8309 		 * may not directly point to the object being released, but to
8310 		 * dynptr pointing to such object, which might be at some offset
8311 		 * on the stack. In that case, we simply to fallback to the
8312 		 * default handling.
8313 		 */
8314 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8315 			return 0;
8316 
8317 		/* Doing check_ptr_off_reg check for the offset will catch this
8318 		 * because fixed_off_ok is false, but checking here allows us
8319 		 * to give the user a better error message.
8320 		 */
8321 		if (reg->off) {
8322 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8323 				regno);
8324 			return -EINVAL;
8325 		}
8326 		return __check_ptr_off_reg(env, reg, regno, false);
8327 	}
8328 
8329 	switch (type) {
8330 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8331 	case PTR_TO_STACK:
8332 	case PTR_TO_PACKET:
8333 	case PTR_TO_PACKET_META:
8334 	case PTR_TO_MAP_KEY:
8335 	case PTR_TO_MAP_VALUE:
8336 	case PTR_TO_MEM:
8337 	case PTR_TO_MEM | MEM_RDONLY:
8338 	case PTR_TO_MEM | MEM_RINGBUF:
8339 	case PTR_TO_BUF:
8340 	case PTR_TO_BUF | MEM_RDONLY:
8341 	case SCALAR_VALUE:
8342 		return 0;
8343 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8344 	 * fixed offset.
8345 	 */
8346 	case PTR_TO_BTF_ID:
8347 	case PTR_TO_BTF_ID | MEM_ALLOC:
8348 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8349 	case PTR_TO_BTF_ID | MEM_RCU:
8350 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8351 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8352 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8353 		 * its fixed offset must be 0. In the other cases, fixed offset
8354 		 * can be non-zero. This was already checked above. So pass
8355 		 * fixed_off_ok as true to allow fixed offset for all other
8356 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8357 		 * still need to do checks instead of returning.
8358 		 */
8359 		return __check_ptr_off_reg(env, reg, regno, true);
8360 	default:
8361 		return __check_ptr_off_reg(env, reg, regno, false);
8362 	}
8363 }
8364 
8365 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8366 						const struct bpf_func_proto *fn,
8367 						struct bpf_reg_state *regs)
8368 {
8369 	struct bpf_reg_state *state = NULL;
8370 	int i;
8371 
8372 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8373 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8374 			if (state) {
8375 				verbose(env, "verifier internal error: multiple dynptr args\n");
8376 				return NULL;
8377 			}
8378 			state = &regs[BPF_REG_1 + i];
8379 		}
8380 
8381 	if (!state)
8382 		verbose(env, "verifier internal error: no dynptr arg found\n");
8383 
8384 	return state;
8385 }
8386 
8387 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8388 {
8389 	struct bpf_func_state *state = func(env, reg);
8390 	int spi;
8391 
8392 	if (reg->type == CONST_PTR_TO_DYNPTR)
8393 		return reg->id;
8394 	spi = dynptr_get_spi(env, reg);
8395 	if (spi < 0)
8396 		return spi;
8397 	return state->stack[spi].spilled_ptr.id;
8398 }
8399 
8400 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8401 {
8402 	struct bpf_func_state *state = func(env, reg);
8403 	int spi;
8404 
8405 	if (reg->type == CONST_PTR_TO_DYNPTR)
8406 		return reg->ref_obj_id;
8407 	spi = dynptr_get_spi(env, reg);
8408 	if (spi < 0)
8409 		return spi;
8410 	return state->stack[spi].spilled_ptr.ref_obj_id;
8411 }
8412 
8413 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8414 					    struct bpf_reg_state *reg)
8415 {
8416 	struct bpf_func_state *state = func(env, reg);
8417 	int spi;
8418 
8419 	if (reg->type == CONST_PTR_TO_DYNPTR)
8420 		return reg->dynptr.type;
8421 
8422 	spi = __get_spi(reg->off);
8423 	if (spi < 0) {
8424 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8425 		return BPF_DYNPTR_TYPE_INVALID;
8426 	}
8427 
8428 	return state->stack[spi].spilled_ptr.dynptr.type;
8429 }
8430 
8431 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8432 			  struct bpf_call_arg_meta *meta,
8433 			  const struct bpf_func_proto *fn,
8434 			  int insn_idx)
8435 {
8436 	u32 regno = BPF_REG_1 + arg;
8437 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8438 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8439 	enum bpf_reg_type type = reg->type;
8440 	u32 *arg_btf_id = NULL;
8441 	int err = 0;
8442 
8443 	if (arg_type == ARG_DONTCARE)
8444 		return 0;
8445 
8446 	err = check_reg_arg(env, regno, SRC_OP);
8447 	if (err)
8448 		return err;
8449 
8450 	if (arg_type == ARG_ANYTHING) {
8451 		if (is_pointer_value(env, regno)) {
8452 			verbose(env, "R%d leaks addr into helper function\n",
8453 				regno);
8454 			return -EACCES;
8455 		}
8456 		return 0;
8457 	}
8458 
8459 	if (type_is_pkt_pointer(type) &&
8460 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8461 		verbose(env, "helper access to the packet is not allowed\n");
8462 		return -EACCES;
8463 	}
8464 
8465 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8466 		err = resolve_map_arg_type(env, meta, &arg_type);
8467 		if (err)
8468 			return err;
8469 	}
8470 
8471 	if (register_is_null(reg) && type_may_be_null(arg_type))
8472 		/* A NULL register has a SCALAR_VALUE type, so skip
8473 		 * type checking.
8474 		 */
8475 		goto skip_type_check;
8476 
8477 	/* arg_btf_id and arg_size are in a union. */
8478 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8479 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8480 		arg_btf_id = fn->arg_btf_id[arg];
8481 
8482 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8483 	if (err)
8484 		return err;
8485 
8486 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8487 	if (err)
8488 		return err;
8489 
8490 skip_type_check:
8491 	if (arg_type_is_release(arg_type)) {
8492 		if (arg_type_is_dynptr(arg_type)) {
8493 			struct bpf_func_state *state = func(env, reg);
8494 			int spi;
8495 
8496 			/* Only dynptr created on stack can be released, thus
8497 			 * the get_spi and stack state checks for spilled_ptr
8498 			 * should only be done before process_dynptr_func for
8499 			 * PTR_TO_STACK.
8500 			 */
8501 			if (reg->type == PTR_TO_STACK) {
8502 				spi = dynptr_get_spi(env, reg);
8503 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8504 					verbose(env, "arg %d is an unacquired reference\n", regno);
8505 					return -EINVAL;
8506 				}
8507 			} else {
8508 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8509 				return -EINVAL;
8510 			}
8511 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8512 			verbose(env, "R%d must be referenced when passed to release function\n",
8513 				regno);
8514 			return -EINVAL;
8515 		}
8516 		if (meta->release_regno) {
8517 			verbose(env, "verifier internal error: more than one release argument\n");
8518 			return -EFAULT;
8519 		}
8520 		meta->release_regno = regno;
8521 	}
8522 
8523 	if (reg->ref_obj_id) {
8524 		if (meta->ref_obj_id) {
8525 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8526 				regno, reg->ref_obj_id,
8527 				meta->ref_obj_id);
8528 			return -EFAULT;
8529 		}
8530 		meta->ref_obj_id = reg->ref_obj_id;
8531 	}
8532 
8533 	switch (base_type(arg_type)) {
8534 	case ARG_CONST_MAP_PTR:
8535 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8536 		if (meta->map_ptr) {
8537 			/* Use map_uid (which is unique id of inner map) to reject:
8538 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8539 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8540 			 * if (inner_map1 && inner_map2) {
8541 			 *     timer = bpf_map_lookup_elem(inner_map1);
8542 			 *     if (timer)
8543 			 *         // mismatch would have been allowed
8544 			 *         bpf_timer_init(timer, inner_map2);
8545 			 * }
8546 			 *
8547 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8548 			 */
8549 			if (meta->map_ptr != reg->map_ptr ||
8550 			    meta->map_uid != reg->map_uid) {
8551 				verbose(env,
8552 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8553 					meta->map_uid, reg->map_uid);
8554 				return -EINVAL;
8555 			}
8556 		}
8557 		meta->map_ptr = reg->map_ptr;
8558 		meta->map_uid = reg->map_uid;
8559 		break;
8560 	case ARG_PTR_TO_MAP_KEY:
8561 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8562 		 * check that [key, key + map->key_size) are within
8563 		 * stack limits and initialized
8564 		 */
8565 		if (!meta->map_ptr) {
8566 			/* in function declaration map_ptr must come before
8567 			 * map_key, so that it's verified and known before
8568 			 * we have to check map_key here. Otherwise it means
8569 			 * that kernel subsystem misconfigured verifier
8570 			 */
8571 			verbose(env, "invalid map_ptr to access map->key\n");
8572 			return -EACCES;
8573 		}
8574 		err = check_helper_mem_access(env, regno,
8575 					      meta->map_ptr->key_size, false,
8576 					      NULL);
8577 		break;
8578 	case ARG_PTR_TO_MAP_VALUE:
8579 		if (type_may_be_null(arg_type) && register_is_null(reg))
8580 			return 0;
8581 
8582 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8583 		 * check [value, value + map->value_size) validity
8584 		 */
8585 		if (!meta->map_ptr) {
8586 			/* kernel subsystem misconfigured verifier */
8587 			verbose(env, "invalid map_ptr to access map->value\n");
8588 			return -EACCES;
8589 		}
8590 		meta->raw_mode = arg_type & MEM_UNINIT;
8591 		err = check_helper_mem_access(env, regno,
8592 					      meta->map_ptr->value_size, false,
8593 					      meta);
8594 		break;
8595 	case ARG_PTR_TO_PERCPU_BTF_ID:
8596 		if (!reg->btf_id) {
8597 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8598 			return -EACCES;
8599 		}
8600 		meta->ret_btf = reg->btf;
8601 		meta->ret_btf_id = reg->btf_id;
8602 		break;
8603 	case ARG_PTR_TO_SPIN_LOCK:
8604 		if (in_rbtree_lock_required_cb(env)) {
8605 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8606 			return -EACCES;
8607 		}
8608 		if (meta->func_id == BPF_FUNC_spin_lock) {
8609 			err = process_spin_lock(env, regno, true);
8610 			if (err)
8611 				return err;
8612 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8613 			err = process_spin_lock(env, regno, false);
8614 			if (err)
8615 				return err;
8616 		} else {
8617 			verbose(env, "verifier internal error\n");
8618 			return -EFAULT;
8619 		}
8620 		break;
8621 	case ARG_PTR_TO_TIMER:
8622 		err = process_timer_func(env, regno, meta);
8623 		if (err)
8624 			return err;
8625 		break;
8626 	case ARG_PTR_TO_FUNC:
8627 		meta->subprogno = reg->subprogno;
8628 		break;
8629 	case ARG_PTR_TO_MEM:
8630 		/* The access to this pointer is only checked when we hit the
8631 		 * next is_mem_size argument below.
8632 		 */
8633 		meta->raw_mode = arg_type & MEM_UNINIT;
8634 		if (arg_type & MEM_FIXED_SIZE) {
8635 			err = check_helper_mem_access(env, regno,
8636 						      fn->arg_size[arg], false,
8637 						      meta);
8638 		}
8639 		break;
8640 	case ARG_CONST_SIZE:
8641 		err = check_mem_size_reg(env, reg, regno, false, meta);
8642 		break;
8643 	case ARG_CONST_SIZE_OR_ZERO:
8644 		err = check_mem_size_reg(env, reg, regno, true, meta);
8645 		break;
8646 	case ARG_PTR_TO_DYNPTR:
8647 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8648 		if (err)
8649 			return err;
8650 		break;
8651 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8652 		if (!tnum_is_const(reg->var_off)) {
8653 			verbose(env, "R%d is not a known constant'\n",
8654 				regno);
8655 			return -EACCES;
8656 		}
8657 		meta->mem_size = reg->var_off.value;
8658 		err = mark_chain_precision(env, regno);
8659 		if (err)
8660 			return err;
8661 		break;
8662 	case ARG_PTR_TO_INT:
8663 	case ARG_PTR_TO_LONG:
8664 	{
8665 		int size = int_ptr_type_to_size(arg_type);
8666 
8667 		err = check_helper_mem_access(env, regno, size, false, meta);
8668 		if (err)
8669 			return err;
8670 		err = check_ptr_alignment(env, reg, 0, size, true);
8671 		break;
8672 	}
8673 	case ARG_PTR_TO_CONST_STR:
8674 	{
8675 		struct bpf_map *map = reg->map_ptr;
8676 		int map_off;
8677 		u64 map_addr;
8678 		char *str_ptr;
8679 
8680 		if (!bpf_map_is_rdonly(map)) {
8681 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8682 			return -EACCES;
8683 		}
8684 
8685 		if (!tnum_is_const(reg->var_off)) {
8686 			verbose(env, "R%d is not a constant address'\n", regno);
8687 			return -EACCES;
8688 		}
8689 
8690 		if (!map->ops->map_direct_value_addr) {
8691 			verbose(env, "no direct value access support for this map type\n");
8692 			return -EACCES;
8693 		}
8694 
8695 		err = check_map_access(env, regno, reg->off,
8696 				       map->value_size - reg->off, false,
8697 				       ACCESS_HELPER);
8698 		if (err)
8699 			return err;
8700 
8701 		map_off = reg->off + reg->var_off.value;
8702 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8703 		if (err) {
8704 			verbose(env, "direct value access on string failed\n");
8705 			return err;
8706 		}
8707 
8708 		str_ptr = (char *)(long)(map_addr);
8709 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8710 			verbose(env, "string is not zero-terminated\n");
8711 			return -EINVAL;
8712 		}
8713 		break;
8714 	}
8715 	case ARG_PTR_TO_KPTR:
8716 		err = process_kptr_func(env, regno, meta);
8717 		if (err)
8718 			return err;
8719 		break;
8720 	}
8721 
8722 	return err;
8723 }
8724 
8725 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8726 {
8727 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8728 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8729 
8730 	if (func_id != BPF_FUNC_map_update_elem)
8731 		return false;
8732 
8733 	/* It's not possible to get access to a locked struct sock in these
8734 	 * contexts, so updating is safe.
8735 	 */
8736 	switch (type) {
8737 	case BPF_PROG_TYPE_TRACING:
8738 		if (eatype == BPF_TRACE_ITER)
8739 			return true;
8740 		break;
8741 	case BPF_PROG_TYPE_SOCKET_FILTER:
8742 	case BPF_PROG_TYPE_SCHED_CLS:
8743 	case BPF_PROG_TYPE_SCHED_ACT:
8744 	case BPF_PROG_TYPE_XDP:
8745 	case BPF_PROG_TYPE_SK_REUSEPORT:
8746 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8747 	case BPF_PROG_TYPE_SK_LOOKUP:
8748 		return true;
8749 	default:
8750 		break;
8751 	}
8752 
8753 	verbose(env, "cannot update sockmap in this context\n");
8754 	return false;
8755 }
8756 
8757 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8758 {
8759 	return env->prog->jit_requested &&
8760 	       bpf_jit_supports_subprog_tailcalls();
8761 }
8762 
8763 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8764 					struct bpf_map *map, int func_id)
8765 {
8766 	if (!map)
8767 		return 0;
8768 
8769 	/* We need a two way check, first is from map perspective ... */
8770 	switch (map->map_type) {
8771 	case BPF_MAP_TYPE_PROG_ARRAY:
8772 		if (func_id != BPF_FUNC_tail_call)
8773 			goto error;
8774 		break;
8775 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8776 		if (func_id != BPF_FUNC_perf_event_read &&
8777 		    func_id != BPF_FUNC_perf_event_output &&
8778 		    func_id != BPF_FUNC_skb_output &&
8779 		    func_id != BPF_FUNC_perf_event_read_value &&
8780 		    func_id != BPF_FUNC_xdp_output)
8781 			goto error;
8782 		break;
8783 	case BPF_MAP_TYPE_RINGBUF:
8784 		if (func_id != BPF_FUNC_ringbuf_output &&
8785 		    func_id != BPF_FUNC_ringbuf_reserve &&
8786 		    func_id != BPF_FUNC_ringbuf_query &&
8787 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8788 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8789 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8790 			goto error;
8791 		break;
8792 	case BPF_MAP_TYPE_USER_RINGBUF:
8793 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8794 			goto error;
8795 		break;
8796 	case BPF_MAP_TYPE_STACK_TRACE:
8797 		if (func_id != BPF_FUNC_get_stackid)
8798 			goto error;
8799 		break;
8800 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8801 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8802 		    func_id != BPF_FUNC_current_task_under_cgroup)
8803 			goto error;
8804 		break;
8805 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8806 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8807 		if (func_id != BPF_FUNC_get_local_storage)
8808 			goto error;
8809 		break;
8810 	case BPF_MAP_TYPE_DEVMAP:
8811 	case BPF_MAP_TYPE_DEVMAP_HASH:
8812 		if (func_id != BPF_FUNC_redirect_map &&
8813 		    func_id != BPF_FUNC_map_lookup_elem)
8814 			goto error;
8815 		break;
8816 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8817 	 * appear.
8818 	 */
8819 	case BPF_MAP_TYPE_CPUMAP:
8820 		if (func_id != BPF_FUNC_redirect_map)
8821 			goto error;
8822 		break;
8823 	case BPF_MAP_TYPE_XSKMAP:
8824 		if (func_id != BPF_FUNC_redirect_map &&
8825 		    func_id != BPF_FUNC_map_lookup_elem)
8826 			goto error;
8827 		break;
8828 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8829 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8830 		if (func_id != BPF_FUNC_map_lookup_elem)
8831 			goto error;
8832 		break;
8833 	case BPF_MAP_TYPE_SOCKMAP:
8834 		if (func_id != BPF_FUNC_sk_redirect_map &&
8835 		    func_id != BPF_FUNC_sock_map_update &&
8836 		    func_id != BPF_FUNC_map_delete_elem &&
8837 		    func_id != BPF_FUNC_msg_redirect_map &&
8838 		    func_id != BPF_FUNC_sk_select_reuseport &&
8839 		    func_id != BPF_FUNC_map_lookup_elem &&
8840 		    !may_update_sockmap(env, func_id))
8841 			goto error;
8842 		break;
8843 	case BPF_MAP_TYPE_SOCKHASH:
8844 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8845 		    func_id != BPF_FUNC_sock_hash_update &&
8846 		    func_id != BPF_FUNC_map_delete_elem &&
8847 		    func_id != BPF_FUNC_msg_redirect_hash &&
8848 		    func_id != BPF_FUNC_sk_select_reuseport &&
8849 		    func_id != BPF_FUNC_map_lookup_elem &&
8850 		    !may_update_sockmap(env, func_id))
8851 			goto error;
8852 		break;
8853 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8854 		if (func_id != BPF_FUNC_sk_select_reuseport)
8855 			goto error;
8856 		break;
8857 	case BPF_MAP_TYPE_QUEUE:
8858 	case BPF_MAP_TYPE_STACK:
8859 		if (func_id != BPF_FUNC_map_peek_elem &&
8860 		    func_id != BPF_FUNC_map_pop_elem &&
8861 		    func_id != BPF_FUNC_map_push_elem)
8862 			goto error;
8863 		break;
8864 	case BPF_MAP_TYPE_SK_STORAGE:
8865 		if (func_id != BPF_FUNC_sk_storage_get &&
8866 		    func_id != BPF_FUNC_sk_storage_delete &&
8867 		    func_id != BPF_FUNC_kptr_xchg)
8868 			goto error;
8869 		break;
8870 	case BPF_MAP_TYPE_INODE_STORAGE:
8871 		if (func_id != BPF_FUNC_inode_storage_get &&
8872 		    func_id != BPF_FUNC_inode_storage_delete &&
8873 		    func_id != BPF_FUNC_kptr_xchg)
8874 			goto error;
8875 		break;
8876 	case BPF_MAP_TYPE_TASK_STORAGE:
8877 		if (func_id != BPF_FUNC_task_storage_get &&
8878 		    func_id != BPF_FUNC_task_storage_delete &&
8879 		    func_id != BPF_FUNC_kptr_xchg)
8880 			goto error;
8881 		break;
8882 	case BPF_MAP_TYPE_CGRP_STORAGE:
8883 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8884 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8885 		    func_id != BPF_FUNC_kptr_xchg)
8886 			goto error;
8887 		break;
8888 	case BPF_MAP_TYPE_BLOOM_FILTER:
8889 		if (func_id != BPF_FUNC_map_peek_elem &&
8890 		    func_id != BPF_FUNC_map_push_elem)
8891 			goto error;
8892 		break;
8893 	default:
8894 		break;
8895 	}
8896 
8897 	/* ... and second from the function itself. */
8898 	switch (func_id) {
8899 	case BPF_FUNC_tail_call:
8900 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8901 			goto error;
8902 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8903 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8904 			return -EINVAL;
8905 		}
8906 		break;
8907 	case BPF_FUNC_perf_event_read:
8908 	case BPF_FUNC_perf_event_output:
8909 	case BPF_FUNC_perf_event_read_value:
8910 	case BPF_FUNC_skb_output:
8911 	case BPF_FUNC_xdp_output:
8912 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8913 			goto error;
8914 		break;
8915 	case BPF_FUNC_ringbuf_output:
8916 	case BPF_FUNC_ringbuf_reserve:
8917 	case BPF_FUNC_ringbuf_query:
8918 	case BPF_FUNC_ringbuf_reserve_dynptr:
8919 	case BPF_FUNC_ringbuf_submit_dynptr:
8920 	case BPF_FUNC_ringbuf_discard_dynptr:
8921 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8922 			goto error;
8923 		break;
8924 	case BPF_FUNC_user_ringbuf_drain:
8925 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8926 			goto error;
8927 		break;
8928 	case BPF_FUNC_get_stackid:
8929 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8930 			goto error;
8931 		break;
8932 	case BPF_FUNC_current_task_under_cgroup:
8933 	case BPF_FUNC_skb_under_cgroup:
8934 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8935 			goto error;
8936 		break;
8937 	case BPF_FUNC_redirect_map:
8938 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8939 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8940 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8941 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8942 			goto error;
8943 		break;
8944 	case BPF_FUNC_sk_redirect_map:
8945 	case BPF_FUNC_msg_redirect_map:
8946 	case BPF_FUNC_sock_map_update:
8947 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8948 			goto error;
8949 		break;
8950 	case BPF_FUNC_sk_redirect_hash:
8951 	case BPF_FUNC_msg_redirect_hash:
8952 	case BPF_FUNC_sock_hash_update:
8953 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8954 			goto error;
8955 		break;
8956 	case BPF_FUNC_get_local_storage:
8957 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8958 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8959 			goto error;
8960 		break;
8961 	case BPF_FUNC_sk_select_reuseport:
8962 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8963 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8964 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8965 			goto error;
8966 		break;
8967 	case BPF_FUNC_map_pop_elem:
8968 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8969 		    map->map_type != BPF_MAP_TYPE_STACK)
8970 			goto error;
8971 		break;
8972 	case BPF_FUNC_map_peek_elem:
8973 	case BPF_FUNC_map_push_elem:
8974 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8975 		    map->map_type != BPF_MAP_TYPE_STACK &&
8976 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8977 			goto error;
8978 		break;
8979 	case BPF_FUNC_map_lookup_percpu_elem:
8980 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8981 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8982 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8983 			goto error;
8984 		break;
8985 	case BPF_FUNC_sk_storage_get:
8986 	case BPF_FUNC_sk_storage_delete:
8987 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8988 			goto error;
8989 		break;
8990 	case BPF_FUNC_inode_storage_get:
8991 	case BPF_FUNC_inode_storage_delete:
8992 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8993 			goto error;
8994 		break;
8995 	case BPF_FUNC_task_storage_get:
8996 	case BPF_FUNC_task_storage_delete:
8997 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8998 			goto error;
8999 		break;
9000 	case BPF_FUNC_cgrp_storage_get:
9001 	case BPF_FUNC_cgrp_storage_delete:
9002 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9003 			goto error;
9004 		break;
9005 	default:
9006 		break;
9007 	}
9008 
9009 	return 0;
9010 error:
9011 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9012 		map->map_type, func_id_name(func_id), func_id);
9013 	return -EINVAL;
9014 }
9015 
9016 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9017 {
9018 	int count = 0;
9019 
9020 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9021 		count++;
9022 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9023 		count++;
9024 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9025 		count++;
9026 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9027 		count++;
9028 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9029 		count++;
9030 
9031 	/* We only support one arg being in raw mode at the moment,
9032 	 * which is sufficient for the helper functions we have
9033 	 * right now.
9034 	 */
9035 	return count <= 1;
9036 }
9037 
9038 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9039 {
9040 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9041 	bool has_size = fn->arg_size[arg] != 0;
9042 	bool is_next_size = false;
9043 
9044 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9045 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9046 
9047 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9048 		return is_next_size;
9049 
9050 	return has_size == is_next_size || is_next_size == is_fixed;
9051 }
9052 
9053 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9054 {
9055 	/* bpf_xxx(..., buf, len) call will access 'len'
9056 	 * bytes from memory 'buf'. Both arg types need
9057 	 * to be paired, so make sure there's no buggy
9058 	 * helper function specification.
9059 	 */
9060 	if (arg_type_is_mem_size(fn->arg1_type) ||
9061 	    check_args_pair_invalid(fn, 0) ||
9062 	    check_args_pair_invalid(fn, 1) ||
9063 	    check_args_pair_invalid(fn, 2) ||
9064 	    check_args_pair_invalid(fn, 3) ||
9065 	    check_args_pair_invalid(fn, 4))
9066 		return false;
9067 
9068 	return true;
9069 }
9070 
9071 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9072 {
9073 	int i;
9074 
9075 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9076 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9077 			return !!fn->arg_btf_id[i];
9078 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9079 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9080 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9081 		    /* arg_btf_id and arg_size are in a union. */
9082 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9083 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9084 			return false;
9085 	}
9086 
9087 	return true;
9088 }
9089 
9090 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9091 {
9092 	return check_raw_mode_ok(fn) &&
9093 	       check_arg_pair_ok(fn) &&
9094 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9095 }
9096 
9097 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9098  * are now invalid, so turn them into unknown SCALAR_VALUE.
9099  *
9100  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9101  * since these slices point to packet data.
9102  */
9103 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9104 {
9105 	struct bpf_func_state *state;
9106 	struct bpf_reg_state *reg;
9107 
9108 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9109 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9110 			mark_reg_invalid(env, reg);
9111 	}));
9112 }
9113 
9114 enum {
9115 	AT_PKT_END = -1,
9116 	BEYOND_PKT_END = -2,
9117 };
9118 
9119 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9120 {
9121 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9122 	struct bpf_reg_state *reg = &state->regs[regn];
9123 
9124 	if (reg->type != PTR_TO_PACKET)
9125 		/* PTR_TO_PACKET_META is not supported yet */
9126 		return;
9127 
9128 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9129 	 * How far beyond pkt_end it goes is unknown.
9130 	 * if (!range_open) it's the case of pkt >= pkt_end
9131 	 * if (range_open) it's the case of pkt > pkt_end
9132 	 * hence this pointer is at least 1 byte bigger than pkt_end
9133 	 */
9134 	if (range_open)
9135 		reg->range = BEYOND_PKT_END;
9136 	else
9137 		reg->range = AT_PKT_END;
9138 }
9139 
9140 /* The pointer with the specified id has released its reference to kernel
9141  * resources. Identify all copies of the same pointer and clear the reference.
9142  */
9143 static int release_reference(struct bpf_verifier_env *env,
9144 			     int ref_obj_id)
9145 {
9146 	struct bpf_func_state *state;
9147 	struct bpf_reg_state *reg;
9148 	int err;
9149 
9150 	err = release_reference_state(cur_func(env), ref_obj_id);
9151 	if (err)
9152 		return err;
9153 
9154 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9155 		if (reg->ref_obj_id == ref_obj_id)
9156 			mark_reg_invalid(env, reg);
9157 	}));
9158 
9159 	return 0;
9160 }
9161 
9162 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9163 {
9164 	struct bpf_func_state *unused;
9165 	struct bpf_reg_state *reg;
9166 
9167 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9168 		if (type_is_non_owning_ref(reg->type))
9169 			mark_reg_invalid(env, reg);
9170 	}));
9171 }
9172 
9173 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9174 				    struct bpf_reg_state *regs)
9175 {
9176 	int i;
9177 
9178 	/* after the call registers r0 - r5 were scratched */
9179 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9180 		mark_reg_not_init(env, regs, caller_saved[i]);
9181 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9182 	}
9183 }
9184 
9185 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9186 				   struct bpf_func_state *caller,
9187 				   struct bpf_func_state *callee,
9188 				   int insn_idx);
9189 
9190 static int set_callee_state(struct bpf_verifier_env *env,
9191 			    struct bpf_func_state *caller,
9192 			    struct bpf_func_state *callee, int insn_idx);
9193 
9194 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9195 			    set_callee_state_fn set_callee_state_cb,
9196 			    struct bpf_verifier_state *state)
9197 {
9198 	struct bpf_func_state *caller, *callee;
9199 	int err;
9200 
9201 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9202 		verbose(env, "the call stack of %d frames is too deep\n",
9203 			state->curframe + 2);
9204 		return -E2BIG;
9205 	}
9206 
9207 	if (state->frame[state->curframe + 1]) {
9208 		verbose(env, "verifier bug. Frame %d already allocated\n",
9209 			state->curframe + 1);
9210 		return -EFAULT;
9211 	}
9212 
9213 	caller = state->frame[state->curframe];
9214 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9215 	if (!callee)
9216 		return -ENOMEM;
9217 	state->frame[state->curframe + 1] = callee;
9218 
9219 	/* callee cannot access r0, r6 - r9 for reading and has to write
9220 	 * into its own stack before reading from it.
9221 	 * callee can read/write into caller's stack
9222 	 */
9223 	init_func_state(env, callee,
9224 			/* remember the callsite, it will be used by bpf_exit */
9225 			callsite,
9226 			state->curframe + 1 /* frameno within this callchain */,
9227 			subprog /* subprog number within this prog */);
9228 	/* Transfer references to the callee */
9229 	err = copy_reference_state(callee, caller);
9230 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9231 	if (err)
9232 		goto err_out;
9233 
9234 	/* only increment it after check_reg_arg() finished */
9235 	state->curframe++;
9236 
9237 	return 0;
9238 
9239 err_out:
9240 	free_func_state(callee);
9241 	state->frame[state->curframe + 1] = NULL;
9242 	return err;
9243 }
9244 
9245 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9246 			      int insn_idx, int subprog,
9247 			      set_callee_state_fn set_callee_state_cb)
9248 {
9249 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9250 	struct bpf_func_state *caller, *callee;
9251 	int err;
9252 
9253 	caller = state->frame[state->curframe];
9254 	err = btf_check_subprog_call(env, subprog, caller->regs);
9255 	if (err == -EFAULT)
9256 		return err;
9257 
9258 	/* set_callee_state is used for direct subprog calls, but we are
9259 	 * interested in validating only BPF helpers that can call subprogs as
9260 	 * callbacks
9261 	 */
9262 	if (bpf_pseudo_kfunc_call(insn) &&
9263 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9264 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9265 			func_id_name(insn->imm), insn->imm);
9266 		return -EFAULT;
9267 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9268 		   !is_callback_calling_function(insn->imm)) { /* helper */
9269 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9270 			func_id_name(insn->imm), insn->imm);
9271 		return -EFAULT;
9272 	}
9273 
9274 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9275 	    insn->src_reg == 0 &&
9276 	    insn->imm == BPF_FUNC_timer_set_callback) {
9277 		struct bpf_verifier_state *async_cb;
9278 
9279 		/* there is no real recursion here. timer callbacks are async */
9280 		env->subprog_info[subprog].is_async_cb = true;
9281 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9282 					 insn_idx, subprog);
9283 		if (!async_cb)
9284 			return -EFAULT;
9285 		callee = async_cb->frame[0];
9286 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9287 
9288 		/* Convert bpf_timer_set_callback() args into timer callback args */
9289 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9290 		if (err)
9291 			return err;
9292 
9293 		return 0;
9294 	}
9295 
9296 	/* for callback functions enqueue entry to callback and
9297 	 * proceed with next instruction within current frame.
9298 	 */
9299 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9300 	if (!callback_state)
9301 		return -ENOMEM;
9302 
9303 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9304 			       callback_state);
9305 	if (err)
9306 		return err;
9307 
9308 	callback_state->callback_unroll_depth++;
9309 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9310 	caller->callback_depth = 0;
9311 	return 0;
9312 }
9313 
9314 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9315 			   int *insn_idx)
9316 {
9317 	struct bpf_verifier_state *state = env->cur_state;
9318 	struct bpf_func_state *caller;
9319 	int err, subprog, target_insn;
9320 
9321 	target_insn = *insn_idx + insn->imm + 1;
9322 	subprog = find_subprog(env, target_insn);
9323 	if (subprog < 0) {
9324 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9325 		return -EFAULT;
9326 	}
9327 
9328 	caller = state->frame[state->curframe];
9329 	err = btf_check_subprog_call(env, subprog, caller->regs);
9330 	if (err == -EFAULT)
9331 		return err;
9332 	if (subprog_is_global(env, subprog)) {
9333 		if (err) {
9334 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9335 			return err;
9336 		}
9337 
9338 		if (env->log.level & BPF_LOG_LEVEL)
9339 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9340 		clear_caller_saved_regs(env, caller->regs);
9341 
9342 		/* All global functions return a 64-bit SCALAR_VALUE */
9343 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9344 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9345 
9346 		/* continue with next insn after call */
9347 		return 0;
9348 	}
9349 
9350 	/* for regular function entry setup new frame and continue
9351 	 * from that frame.
9352 	 */
9353 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9354 	if (err)
9355 		return err;
9356 
9357 	clear_caller_saved_regs(env, caller->regs);
9358 
9359 	/* and go analyze first insn of the callee */
9360 	*insn_idx = env->subprog_info[subprog].start - 1;
9361 
9362 	if (env->log.level & BPF_LOG_LEVEL) {
9363 		verbose(env, "caller:\n");
9364 		print_verifier_state(env, caller, true);
9365 		verbose(env, "callee:\n");
9366 		print_verifier_state(env, state->frame[state->curframe], true);
9367 	}
9368 
9369 	return 0;
9370 }
9371 
9372 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9373 				   struct bpf_func_state *caller,
9374 				   struct bpf_func_state *callee)
9375 {
9376 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9377 	 *      void *callback_ctx, u64 flags);
9378 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9379 	 *      void *callback_ctx);
9380 	 */
9381 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9382 
9383 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9384 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9385 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9386 
9387 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9388 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9389 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9390 
9391 	/* pointer to stack or null */
9392 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9393 
9394 	/* unused */
9395 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9396 	return 0;
9397 }
9398 
9399 static int set_callee_state(struct bpf_verifier_env *env,
9400 			    struct bpf_func_state *caller,
9401 			    struct bpf_func_state *callee, int insn_idx)
9402 {
9403 	int i;
9404 
9405 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9406 	 * pointers, which connects us up to the liveness chain
9407 	 */
9408 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9409 		callee->regs[i] = caller->regs[i];
9410 	return 0;
9411 }
9412 
9413 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9414 				       struct bpf_func_state *caller,
9415 				       struct bpf_func_state *callee,
9416 				       int insn_idx)
9417 {
9418 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9419 	struct bpf_map *map;
9420 	int err;
9421 
9422 	if (bpf_map_ptr_poisoned(insn_aux)) {
9423 		verbose(env, "tail_call abusing map_ptr\n");
9424 		return -EINVAL;
9425 	}
9426 
9427 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9428 	if (!map->ops->map_set_for_each_callback_args ||
9429 	    !map->ops->map_for_each_callback) {
9430 		verbose(env, "callback function not allowed for map\n");
9431 		return -ENOTSUPP;
9432 	}
9433 
9434 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9435 	if (err)
9436 		return err;
9437 
9438 	callee->in_callback_fn = true;
9439 	callee->callback_ret_range = tnum_range(0, 1);
9440 	return 0;
9441 }
9442 
9443 static int set_loop_callback_state(struct bpf_verifier_env *env,
9444 				   struct bpf_func_state *caller,
9445 				   struct bpf_func_state *callee,
9446 				   int insn_idx)
9447 {
9448 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9449 	 *	    u64 flags);
9450 	 * callback_fn(u32 index, void *callback_ctx);
9451 	 */
9452 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9453 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9454 
9455 	/* unused */
9456 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9457 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9458 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9459 
9460 	callee->in_callback_fn = true;
9461 	callee->callback_ret_range = tnum_range(0, 1);
9462 	return 0;
9463 }
9464 
9465 static int set_timer_callback_state(struct bpf_verifier_env *env,
9466 				    struct bpf_func_state *caller,
9467 				    struct bpf_func_state *callee,
9468 				    int insn_idx)
9469 {
9470 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9471 
9472 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9473 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9474 	 */
9475 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9476 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9477 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9478 
9479 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9480 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9481 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9482 
9483 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9484 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9485 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9486 
9487 	/* unused */
9488 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9489 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9490 	callee->in_async_callback_fn = true;
9491 	callee->callback_ret_range = tnum_range(0, 1);
9492 	return 0;
9493 }
9494 
9495 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9496 				       struct bpf_func_state *caller,
9497 				       struct bpf_func_state *callee,
9498 				       int insn_idx)
9499 {
9500 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9501 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9502 	 * (callback_fn)(struct task_struct *task,
9503 	 *               struct vm_area_struct *vma, void *callback_ctx);
9504 	 */
9505 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9506 
9507 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9508 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9509 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9510 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9511 
9512 	/* pointer to stack or null */
9513 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9514 
9515 	/* unused */
9516 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9517 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9518 	callee->in_callback_fn = true;
9519 	callee->callback_ret_range = tnum_range(0, 1);
9520 	return 0;
9521 }
9522 
9523 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9524 					   struct bpf_func_state *caller,
9525 					   struct bpf_func_state *callee,
9526 					   int insn_idx)
9527 {
9528 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9529 	 *			  callback_ctx, u64 flags);
9530 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9531 	 */
9532 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9533 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9534 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9535 
9536 	/* unused */
9537 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9538 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9539 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9540 
9541 	callee->in_callback_fn = true;
9542 	callee->callback_ret_range = tnum_range(0, 1);
9543 	return 0;
9544 }
9545 
9546 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9547 					 struct bpf_func_state *caller,
9548 					 struct bpf_func_state *callee,
9549 					 int insn_idx)
9550 {
9551 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9552 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9553 	 *
9554 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9555 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9556 	 * by this point, so look at 'root'
9557 	 */
9558 	struct btf_field *field;
9559 
9560 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9561 				      BPF_RB_ROOT);
9562 	if (!field || !field->graph_root.value_btf_id)
9563 		return -EFAULT;
9564 
9565 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9566 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9567 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9568 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9569 
9570 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9571 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9572 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9573 	callee->in_callback_fn = true;
9574 	callee->callback_ret_range = tnum_range(0, 1);
9575 	return 0;
9576 }
9577 
9578 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9579 
9580 /* Are we currently verifying the callback for a rbtree helper that must
9581  * be called with lock held? If so, no need to complain about unreleased
9582  * lock
9583  */
9584 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9585 {
9586 	struct bpf_verifier_state *state = env->cur_state;
9587 	struct bpf_insn *insn = env->prog->insnsi;
9588 	struct bpf_func_state *callee;
9589 	int kfunc_btf_id;
9590 
9591 	if (!state->curframe)
9592 		return false;
9593 
9594 	callee = state->frame[state->curframe];
9595 
9596 	if (!callee->in_callback_fn)
9597 		return false;
9598 
9599 	kfunc_btf_id = insn[callee->callsite].imm;
9600 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9601 }
9602 
9603 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9604 {
9605 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9606 	struct bpf_func_state *caller, *callee;
9607 	struct bpf_reg_state *r0;
9608 	bool in_callback_fn;
9609 	int err;
9610 
9611 	callee = state->frame[state->curframe];
9612 	r0 = &callee->regs[BPF_REG_0];
9613 	if (r0->type == PTR_TO_STACK) {
9614 		/* technically it's ok to return caller's stack pointer
9615 		 * (or caller's caller's pointer) back to the caller,
9616 		 * since these pointers are valid. Only current stack
9617 		 * pointer will be invalid as soon as function exits,
9618 		 * but let's be conservative
9619 		 */
9620 		verbose(env, "cannot return stack pointer to the caller\n");
9621 		return -EINVAL;
9622 	}
9623 
9624 	caller = state->frame[state->curframe - 1];
9625 	if (callee->in_callback_fn) {
9626 		/* enforce R0 return value range [0, 1]. */
9627 		struct tnum range = callee->callback_ret_range;
9628 
9629 		if (r0->type != SCALAR_VALUE) {
9630 			verbose(env, "R0 not a scalar value\n");
9631 			return -EACCES;
9632 		}
9633 
9634 		/* we are going to rely on register's precise value */
9635 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9636 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9637 		if (err)
9638 			return err;
9639 
9640 		if (!tnum_in(range, r0->var_off)) {
9641 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9642 			return -EINVAL;
9643 		}
9644 		if (!calls_callback(env, callee->callsite)) {
9645 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9646 				*insn_idx, callee->callsite);
9647 			return -EFAULT;
9648 		}
9649 	} else {
9650 		/* return to the caller whatever r0 had in the callee */
9651 		caller->regs[BPF_REG_0] = *r0;
9652 	}
9653 
9654 	/* callback_fn frame should have released its own additions to parent's
9655 	 * reference state at this point, or check_reference_leak would
9656 	 * complain, hence it must be the same as the caller. There is no need
9657 	 * to copy it back.
9658 	 */
9659 	if (!callee->in_callback_fn) {
9660 		/* Transfer references to the caller */
9661 		err = copy_reference_state(caller, callee);
9662 		if (err)
9663 			return err;
9664 	}
9665 
9666 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9667 	 * there function call logic would reschedule callback visit. If iteration
9668 	 * converges is_state_visited() would prune that visit eventually.
9669 	 */
9670 	in_callback_fn = callee->in_callback_fn;
9671 	if (in_callback_fn)
9672 		*insn_idx = callee->callsite;
9673 	else
9674 		*insn_idx = callee->callsite + 1;
9675 
9676 	if (env->log.level & BPF_LOG_LEVEL) {
9677 		verbose(env, "returning from callee:\n");
9678 		print_verifier_state(env, callee, true);
9679 		verbose(env, "to caller at %d:\n", *insn_idx);
9680 		print_verifier_state(env, caller, true);
9681 	}
9682 	/* clear everything in the callee */
9683 	free_func_state(callee);
9684 	state->frame[state->curframe--] = NULL;
9685 
9686 	/* for callbacks widen imprecise scalars to make programs like below verify:
9687 	 *
9688 	 *   struct ctx { int i; }
9689 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9690 	 *   ...
9691 	 *   struct ctx = { .i = 0; }
9692 	 *   bpf_loop(100, cb, &ctx, 0);
9693 	 *
9694 	 * This is similar to what is done in process_iter_next_call() for open
9695 	 * coded iterators.
9696 	 */
9697 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9698 	if (prev_st) {
9699 		err = widen_imprecise_scalars(env, prev_st, state);
9700 		if (err)
9701 			return err;
9702 	}
9703 	return 0;
9704 }
9705 
9706 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9707 				   int func_id,
9708 				   struct bpf_call_arg_meta *meta)
9709 {
9710 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9711 
9712 	if (ret_type != RET_INTEGER)
9713 		return;
9714 
9715 	switch (func_id) {
9716 	case BPF_FUNC_get_stack:
9717 	case BPF_FUNC_get_task_stack:
9718 	case BPF_FUNC_probe_read_str:
9719 	case BPF_FUNC_probe_read_kernel_str:
9720 	case BPF_FUNC_probe_read_user_str:
9721 		ret_reg->smax_value = meta->msize_max_value;
9722 		ret_reg->s32_max_value = meta->msize_max_value;
9723 		ret_reg->smin_value = -MAX_ERRNO;
9724 		ret_reg->s32_min_value = -MAX_ERRNO;
9725 		reg_bounds_sync(ret_reg);
9726 		break;
9727 	case BPF_FUNC_get_smp_processor_id:
9728 		ret_reg->umax_value = nr_cpu_ids - 1;
9729 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9730 		ret_reg->smax_value = nr_cpu_ids - 1;
9731 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9732 		ret_reg->umin_value = 0;
9733 		ret_reg->u32_min_value = 0;
9734 		ret_reg->smin_value = 0;
9735 		ret_reg->s32_min_value = 0;
9736 		reg_bounds_sync(ret_reg);
9737 		break;
9738 	}
9739 }
9740 
9741 static int
9742 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9743 		int func_id, int insn_idx)
9744 {
9745 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9746 	struct bpf_map *map = meta->map_ptr;
9747 
9748 	if (func_id != BPF_FUNC_tail_call &&
9749 	    func_id != BPF_FUNC_map_lookup_elem &&
9750 	    func_id != BPF_FUNC_map_update_elem &&
9751 	    func_id != BPF_FUNC_map_delete_elem &&
9752 	    func_id != BPF_FUNC_map_push_elem &&
9753 	    func_id != BPF_FUNC_map_pop_elem &&
9754 	    func_id != BPF_FUNC_map_peek_elem &&
9755 	    func_id != BPF_FUNC_for_each_map_elem &&
9756 	    func_id != BPF_FUNC_redirect_map &&
9757 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9758 		return 0;
9759 
9760 	if (map == NULL) {
9761 		verbose(env, "kernel subsystem misconfigured verifier\n");
9762 		return -EINVAL;
9763 	}
9764 
9765 	/* In case of read-only, some additional restrictions
9766 	 * need to be applied in order to prevent altering the
9767 	 * state of the map from program side.
9768 	 */
9769 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9770 	    (func_id == BPF_FUNC_map_delete_elem ||
9771 	     func_id == BPF_FUNC_map_update_elem ||
9772 	     func_id == BPF_FUNC_map_push_elem ||
9773 	     func_id == BPF_FUNC_map_pop_elem)) {
9774 		verbose(env, "write into map forbidden\n");
9775 		return -EACCES;
9776 	}
9777 
9778 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9779 		bpf_map_ptr_store(aux, meta->map_ptr,
9780 				  !meta->map_ptr->bypass_spec_v1);
9781 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9782 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9783 				  !meta->map_ptr->bypass_spec_v1);
9784 	return 0;
9785 }
9786 
9787 static int
9788 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9789 		int func_id, int insn_idx)
9790 {
9791 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9792 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9793 	struct bpf_map *map = meta->map_ptr;
9794 	u64 val, max;
9795 	int err;
9796 
9797 	if (func_id != BPF_FUNC_tail_call)
9798 		return 0;
9799 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9800 		verbose(env, "kernel subsystem misconfigured verifier\n");
9801 		return -EINVAL;
9802 	}
9803 
9804 	reg = &regs[BPF_REG_3];
9805 	val = reg->var_off.value;
9806 	max = map->max_entries;
9807 
9808 	if (!(register_is_const(reg) && val < max)) {
9809 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9810 		return 0;
9811 	}
9812 
9813 	err = mark_chain_precision(env, BPF_REG_3);
9814 	if (err)
9815 		return err;
9816 	if (bpf_map_key_unseen(aux))
9817 		bpf_map_key_store(aux, val);
9818 	else if (!bpf_map_key_poisoned(aux) &&
9819 		  bpf_map_key_immediate(aux) != val)
9820 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9821 	return 0;
9822 }
9823 
9824 static int check_reference_leak(struct bpf_verifier_env *env)
9825 {
9826 	struct bpf_func_state *state = cur_func(env);
9827 	bool refs_lingering = false;
9828 	int i;
9829 
9830 	if (state->frameno && !state->in_callback_fn)
9831 		return 0;
9832 
9833 	for (i = 0; i < state->acquired_refs; i++) {
9834 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9835 			continue;
9836 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9837 			state->refs[i].id, state->refs[i].insn_idx);
9838 		refs_lingering = true;
9839 	}
9840 	return refs_lingering ? -EINVAL : 0;
9841 }
9842 
9843 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9844 				   struct bpf_reg_state *regs)
9845 {
9846 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9847 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9848 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9849 	struct bpf_bprintf_data data = {};
9850 	int err, fmt_map_off, num_args;
9851 	u64 fmt_addr;
9852 	char *fmt;
9853 
9854 	/* data must be an array of u64 */
9855 	if (data_len_reg->var_off.value % 8)
9856 		return -EINVAL;
9857 	num_args = data_len_reg->var_off.value / 8;
9858 
9859 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9860 	 * and map_direct_value_addr is set.
9861 	 */
9862 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9863 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9864 						  fmt_map_off);
9865 	if (err) {
9866 		verbose(env, "verifier bug\n");
9867 		return -EFAULT;
9868 	}
9869 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9870 
9871 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9872 	 * can focus on validating the format specifiers.
9873 	 */
9874 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9875 	if (err < 0)
9876 		verbose(env, "Invalid format string\n");
9877 
9878 	return err;
9879 }
9880 
9881 static int check_get_func_ip(struct bpf_verifier_env *env)
9882 {
9883 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9884 	int func_id = BPF_FUNC_get_func_ip;
9885 
9886 	if (type == BPF_PROG_TYPE_TRACING) {
9887 		if (!bpf_prog_has_trampoline(env->prog)) {
9888 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9889 				func_id_name(func_id), func_id);
9890 			return -ENOTSUPP;
9891 		}
9892 		return 0;
9893 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9894 		return 0;
9895 	}
9896 
9897 	verbose(env, "func %s#%d not supported for program type %d\n",
9898 		func_id_name(func_id), func_id, type);
9899 	return -ENOTSUPP;
9900 }
9901 
9902 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9903 {
9904 	return &env->insn_aux_data[env->insn_idx];
9905 }
9906 
9907 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9908 {
9909 	struct bpf_reg_state *regs = cur_regs(env);
9910 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9911 	bool reg_is_null = register_is_null(reg);
9912 
9913 	if (reg_is_null)
9914 		mark_chain_precision(env, BPF_REG_4);
9915 
9916 	return reg_is_null;
9917 }
9918 
9919 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9920 {
9921 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9922 
9923 	if (!state->initialized) {
9924 		state->initialized = 1;
9925 		state->fit_for_inline = loop_flag_is_zero(env);
9926 		state->callback_subprogno = subprogno;
9927 		return;
9928 	}
9929 
9930 	if (!state->fit_for_inline)
9931 		return;
9932 
9933 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9934 				 state->callback_subprogno == subprogno);
9935 }
9936 
9937 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9938 			     int *insn_idx_p)
9939 {
9940 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9941 	const struct bpf_func_proto *fn = NULL;
9942 	enum bpf_return_type ret_type;
9943 	enum bpf_type_flag ret_flag;
9944 	struct bpf_reg_state *regs;
9945 	struct bpf_call_arg_meta meta;
9946 	int insn_idx = *insn_idx_p;
9947 	bool changes_data;
9948 	int i, err, func_id;
9949 
9950 	/* find function prototype */
9951 	func_id = insn->imm;
9952 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9953 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9954 			func_id);
9955 		return -EINVAL;
9956 	}
9957 
9958 	if (env->ops->get_func_proto)
9959 		fn = env->ops->get_func_proto(func_id, env->prog);
9960 	if (!fn) {
9961 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9962 			func_id);
9963 		return -EINVAL;
9964 	}
9965 
9966 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9967 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9968 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9969 		return -EINVAL;
9970 	}
9971 
9972 	if (fn->allowed && !fn->allowed(env->prog)) {
9973 		verbose(env, "helper call is not allowed in probe\n");
9974 		return -EINVAL;
9975 	}
9976 
9977 	if (!env->prog->aux->sleepable && fn->might_sleep) {
9978 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9979 		return -EINVAL;
9980 	}
9981 
9982 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9983 	changes_data = bpf_helper_changes_pkt_data(fn->func);
9984 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9985 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9986 			func_id_name(func_id), func_id);
9987 		return -EINVAL;
9988 	}
9989 
9990 	memset(&meta, 0, sizeof(meta));
9991 	meta.pkt_access = fn->pkt_access;
9992 
9993 	err = check_func_proto(fn, func_id);
9994 	if (err) {
9995 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9996 			func_id_name(func_id), func_id);
9997 		return err;
9998 	}
9999 
10000 	if (env->cur_state->active_rcu_lock) {
10001 		if (fn->might_sleep) {
10002 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10003 				func_id_name(func_id), func_id);
10004 			return -EINVAL;
10005 		}
10006 
10007 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10008 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10009 	}
10010 
10011 	meta.func_id = func_id;
10012 	/* check args */
10013 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10014 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10015 		if (err)
10016 			return err;
10017 	}
10018 
10019 	err = record_func_map(env, &meta, func_id, insn_idx);
10020 	if (err)
10021 		return err;
10022 
10023 	err = record_func_key(env, &meta, func_id, insn_idx);
10024 	if (err)
10025 		return err;
10026 
10027 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10028 	 * is inferred from register state.
10029 	 */
10030 	for (i = 0; i < meta.access_size; i++) {
10031 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10032 				       BPF_WRITE, -1, false, false);
10033 		if (err)
10034 			return err;
10035 	}
10036 
10037 	regs = cur_regs(env);
10038 
10039 	if (meta.release_regno) {
10040 		err = -EINVAL;
10041 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10042 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10043 		 * is safe to do directly.
10044 		 */
10045 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10046 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10047 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10048 				return -EFAULT;
10049 			}
10050 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10051 		} else if (meta.ref_obj_id) {
10052 			err = release_reference(env, meta.ref_obj_id);
10053 		} else if (register_is_null(&regs[meta.release_regno])) {
10054 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10055 			 * released is NULL, which must be > R0.
10056 			 */
10057 			err = 0;
10058 		}
10059 		if (err) {
10060 			verbose(env, "func %s#%d reference has not been acquired before\n",
10061 				func_id_name(func_id), func_id);
10062 			return err;
10063 		}
10064 	}
10065 
10066 	switch (func_id) {
10067 	case BPF_FUNC_tail_call:
10068 		err = check_reference_leak(env);
10069 		if (err) {
10070 			verbose(env, "tail_call would lead to reference leak\n");
10071 			return err;
10072 		}
10073 		break;
10074 	case BPF_FUNC_get_local_storage:
10075 		/* check that flags argument in get_local_storage(map, flags) is 0,
10076 		 * this is required because get_local_storage() can't return an error.
10077 		 */
10078 		if (!register_is_null(&regs[BPF_REG_2])) {
10079 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10080 			return -EINVAL;
10081 		}
10082 		break;
10083 	case BPF_FUNC_for_each_map_elem:
10084 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10085 					 set_map_elem_callback_state);
10086 		break;
10087 	case BPF_FUNC_timer_set_callback:
10088 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10089 					 set_timer_callback_state);
10090 		break;
10091 	case BPF_FUNC_find_vma:
10092 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10093 					 set_find_vma_callback_state);
10094 		break;
10095 	case BPF_FUNC_snprintf:
10096 		err = check_bpf_snprintf_call(env, regs);
10097 		break;
10098 	case BPF_FUNC_loop:
10099 		update_loop_inline_state(env, meta.subprogno);
10100 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10101 		 * is finished, thus mark it precise.
10102 		 */
10103 		err = mark_chain_precision(env, BPF_REG_1);
10104 		if (err)
10105 			return err;
10106 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10107 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10108 						 set_loop_callback_state);
10109 		} else {
10110 			cur_func(env)->callback_depth = 0;
10111 			if (env->log.level & BPF_LOG_LEVEL2)
10112 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10113 					env->cur_state->curframe);
10114 		}
10115 		break;
10116 	case BPF_FUNC_dynptr_from_mem:
10117 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10118 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10119 				reg_type_str(env, regs[BPF_REG_1].type));
10120 			return -EACCES;
10121 		}
10122 		break;
10123 	case BPF_FUNC_set_retval:
10124 		if (prog_type == BPF_PROG_TYPE_LSM &&
10125 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10126 			if (!env->prog->aux->attach_func_proto->type) {
10127 				/* Make sure programs that attach to void
10128 				 * hooks don't try to modify return value.
10129 				 */
10130 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10131 				return -EINVAL;
10132 			}
10133 		}
10134 		break;
10135 	case BPF_FUNC_dynptr_data:
10136 	{
10137 		struct bpf_reg_state *reg;
10138 		int id, ref_obj_id;
10139 
10140 		reg = get_dynptr_arg_reg(env, fn, regs);
10141 		if (!reg)
10142 			return -EFAULT;
10143 
10144 
10145 		if (meta.dynptr_id) {
10146 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10147 			return -EFAULT;
10148 		}
10149 		if (meta.ref_obj_id) {
10150 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10151 			return -EFAULT;
10152 		}
10153 
10154 		id = dynptr_id(env, reg);
10155 		if (id < 0) {
10156 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10157 			return id;
10158 		}
10159 
10160 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10161 		if (ref_obj_id < 0) {
10162 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10163 			return ref_obj_id;
10164 		}
10165 
10166 		meta.dynptr_id = id;
10167 		meta.ref_obj_id = ref_obj_id;
10168 
10169 		break;
10170 	}
10171 	case BPF_FUNC_dynptr_write:
10172 	{
10173 		enum bpf_dynptr_type dynptr_type;
10174 		struct bpf_reg_state *reg;
10175 
10176 		reg = get_dynptr_arg_reg(env, fn, regs);
10177 		if (!reg)
10178 			return -EFAULT;
10179 
10180 		dynptr_type = dynptr_get_type(env, reg);
10181 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10182 			return -EFAULT;
10183 
10184 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10185 			/* this will trigger clear_all_pkt_pointers(), which will
10186 			 * invalidate all dynptr slices associated with the skb
10187 			 */
10188 			changes_data = true;
10189 
10190 		break;
10191 	}
10192 	case BPF_FUNC_user_ringbuf_drain:
10193 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10194 					 set_user_ringbuf_callback_state);
10195 		break;
10196 	}
10197 
10198 	if (err)
10199 		return err;
10200 
10201 	/* reset caller saved regs */
10202 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10203 		mark_reg_not_init(env, regs, caller_saved[i]);
10204 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10205 	}
10206 
10207 	/* helper call returns 64-bit value. */
10208 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10209 
10210 	/* update return register (already marked as written above) */
10211 	ret_type = fn->ret_type;
10212 	ret_flag = type_flag(ret_type);
10213 
10214 	switch (base_type(ret_type)) {
10215 	case RET_INTEGER:
10216 		/* sets type to SCALAR_VALUE */
10217 		mark_reg_unknown(env, regs, BPF_REG_0);
10218 		break;
10219 	case RET_VOID:
10220 		regs[BPF_REG_0].type = NOT_INIT;
10221 		break;
10222 	case RET_PTR_TO_MAP_VALUE:
10223 		/* There is no offset yet applied, variable or fixed */
10224 		mark_reg_known_zero(env, regs, BPF_REG_0);
10225 		/* remember map_ptr, so that check_map_access()
10226 		 * can check 'value_size' boundary of memory access
10227 		 * to map element returned from bpf_map_lookup_elem()
10228 		 */
10229 		if (meta.map_ptr == NULL) {
10230 			verbose(env,
10231 				"kernel subsystem misconfigured verifier\n");
10232 			return -EINVAL;
10233 		}
10234 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10235 		regs[BPF_REG_0].map_uid = meta.map_uid;
10236 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10237 		if (!type_may_be_null(ret_type) &&
10238 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10239 			regs[BPF_REG_0].id = ++env->id_gen;
10240 		}
10241 		break;
10242 	case RET_PTR_TO_SOCKET:
10243 		mark_reg_known_zero(env, regs, BPF_REG_0);
10244 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10245 		break;
10246 	case RET_PTR_TO_SOCK_COMMON:
10247 		mark_reg_known_zero(env, regs, BPF_REG_0);
10248 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10249 		break;
10250 	case RET_PTR_TO_TCP_SOCK:
10251 		mark_reg_known_zero(env, regs, BPF_REG_0);
10252 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10253 		break;
10254 	case RET_PTR_TO_MEM:
10255 		mark_reg_known_zero(env, regs, BPF_REG_0);
10256 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10257 		regs[BPF_REG_0].mem_size = meta.mem_size;
10258 		break;
10259 	case RET_PTR_TO_MEM_OR_BTF_ID:
10260 	{
10261 		const struct btf_type *t;
10262 
10263 		mark_reg_known_zero(env, regs, BPF_REG_0);
10264 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10265 		if (!btf_type_is_struct(t)) {
10266 			u32 tsize;
10267 			const struct btf_type *ret;
10268 			const char *tname;
10269 
10270 			/* resolve the type size of ksym. */
10271 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10272 			if (IS_ERR(ret)) {
10273 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10274 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10275 					tname, PTR_ERR(ret));
10276 				return -EINVAL;
10277 			}
10278 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10279 			regs[BPF_REG_0].mem_size = tsize;
10280 		} else {
10281 			/* MEM_RDONLY may be carried from ret_flag, but it
10282 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10283 			 * it will confuse the check of PTR_TO_BTF_ID in
10284 			 * check_mem_access().
10285 			 */
10286 			ret_flag &= ~MEM_RDONLY;
10287 
10288 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10289 			regs[BPF_REG_0].btf = meta.ret_btf;
10290 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10291 		}
10292 		break;
10293 	}
10294 	case RET_PTR_TO_BTF_ID:
10295 	{
10296 		struct btf *ret_btf;
10297 		int ret_btf_id;
10298 
10299 		mark_reg_known_zero(env, regs, BPF_REG_0);
10300 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10301 		if (func_id == BPF_FUNC_kptr_xchg) {
10302 			ret_btf = meta.kptr_field->kptr.btf;
10303 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10304 			if (!btf_is_kernel(ret_btf))
10305 				regs[BPF_REG_0].type |= MEM_ALLOC;
10306 		} else {
10307 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10308 				verbose(env, "verifier internal error:");
10309 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10310 					func_id_name(func_id));
10311 				return -EINVAL;
10312 			}
10313 			ret_btf = btf_vmlinux;
10314 			ret_btf_id = *fn->ret_btf_id;
10315 		}
10316 		if (ret_btf_id == 0) {
10317 			verbose(env, "invalid return type %u of func %s#%d\n",
10318 				base_type(ret_type), func_id_name(func_id),
10319 				func_id);
10320 			return -EINVAL;
10321 		}
10322 		regs[BPF_REG_0].btf = ret_btf;
10323 		regs[BPF_REG_0].btf_id = ret_btf_id;
10324 		break;
10325 	}
10326 	default:
10327 		verbose(env, "unknown return type %u of func %s#%d\n",
10328 			base_type(ret_type), func_id_name(func_id), func_id);
10329 		return -EINVAL;
10330 	}
10331 
10332 	if (type_may_be_null(regs[BPF_REG_0].type))
10333 		regs[BPF_REG_0].id = ++env->id_gen;
10334 
10335 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10336 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10337 			func_id_name(func_id), func_id);
10338 		return -EFAULT;
10339 	}
10340 
10341 	if (is_dynptr_ref_function(func_id))
10342 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10343 
10344 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10345 		/* For release_reference() */
10346 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10347 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10348 		int id = acquire_reference_state(env, insn_idx);
10349 
10350 		if (id < 0)
10351 			return id;
10352 		/* For mark_ptr_or_null_reg() */
10353 		regs[BPF_REG_0].id = id;
10354 		/* For release_reference() */
10355 		regs[BPF_REG_0].ref_obj_id = id;
10356 	}
10357 
10358 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10359 
10360 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10361 	if (err)
10362 		return err;
10363 
10364 	if ((func_id == BPF_FUNC_get_stack ||
10365 	     func_id == BPF_FUNC_get_task_stack) &&
10366 	    !env->prog->has_callchain_buf) {
10367 		const char *err_str;
10368 
10369 #ifdef CONFIG_PERF_EVENTS
10370 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10371 		err_str = "cannot get callchain buffer for func %s#%d\n";
10372 #else
10373 		err = -ENOTSUPP;
10374 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10375 #endif
10376 		if (err) {
10377 			verbose(env, err_str, func_id_name(func_id), func_id);
10378 			return err;
10379 		}
10380 
10381 		env->prog->has_callchain_buf = true;
10382 	}
10383 
10384 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10385 		env->prog->call_get_stack = true;
10386 
10387 	if (func_id == BPF_FUNC_get_func_ip) {
10388 		if (check_get_func_ip(env))
10389 			return -ENOTSUPP;
10390 		env->prog->call_get_func_ip = true;
10391 	}
10392 
10393 	if (changes_data)
10394 		clear_all_pkt_pointers(env);
10395 	return 0;
10396 }
10397 
10398 /* mark_btf_func_reg_size() is used when the reg size is determined by
10399  * the BTF func_proto's return value size and argument.
10400  */
10401 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10402 				   size_t reg_size)
10403 {
10404 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10405 
10406 	if (regno == BPF_REG_0) {
10407 		/* Function return value */
10408 		reg->live |= REG_LIVE_WRITTEN;
10409 		reg->subreg_def = reg_size == sizeof(u64) ?
10410 			DEF_NOT_SUBREG : env->insn_idx + 1;
10411 	} else {
10412 		/* Function argument */
10413 		if (reg_size == sizeof(u64)) {
10414 			mark_insn_zext(env, reg);
10415 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10416 		} else {
10417 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10418 		}
10419 	}
10420 }
10421 
10422 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10423 {
10424 	return meta->kfunc_flags & KF_ACQUIRE;
10425 }
10426 
10427 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10428 {
10429 	return meta->kfunc_flags & KF_RELEASE;
10430 }
10431 
10432 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10433 {
10434 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10435 }
10436 
10437 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10438 {
10439 	return meta->kfunc_flags & KF_SLEEPABLE;
10440 }
10441 
10442 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10443 {
10444 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10445 }
10446 
10447 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10448 {
10449 	return meta->kfunc_flags & KF_RCU;
10450 }
10451 
10452 static bool __kfunc_param_match_suffix(const struct btf *btf,
10453 				       const struct btf_param *arg,
10454 				       const char *suffix)
10455 {
10456 	int suffix_len = strlen(suffix), len;
10457 	const char *param_name;
10458 
10459 	/* In the future, this can be ported to use BTF tagging */
10460 	param_name = btf_name_by_offset(btf, arg->name_off);
10461 	if (str_is_empty(param_name))
10462 		return false;
10463 	len = strlen(param_name);
10464 	if (len < suffix_len)
10465 		return false;
10466 	param_name += len - suffix_len;
10467 	return !strncmp(param_name, suffix, suffix_len);
10468 }
10469 
10470 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10471 				  const struct btf_param *arg,
10472 				  const struct bpf_reg_state *reg)
10473 {
10474 	const struct btf_type *t;
10475 
10476 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10477 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10478 		return false;
10479 
10480 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10481 }
10482 
10483 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10484 					const struct btf_param *arg,
10485 					const struct bpf_reg_state *reg)
10486 {
10487 	const struct btf_type *t;
10488 
10489 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10490 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10491 		return false;
10492 
10493 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10494 }
10495 
10496 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10497 {
10498 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10499 }
10500 
10501 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10502 {
10503 	return __kfunc_param_match_suffix(btf, arg, "__k");
10504 }
10505 
10506 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10507 {
10508 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10509 }
10510 
10511 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10512 {
10513 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10514 }
10515 
10516 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10517 {
10518 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10519 }
10520 
10521 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10522 {
10523 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10524 }
10525 
10526 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10527 					  const struct btf_param *arg,
10528 					  const char *name)
10529 {
10530 	int len, target_len = strlen(name);
10531 	const char *param_name;
10532 
10533 	param_name = btf_name_by_offset(btf, arg->name_off);
10534 	if (str_is_empty(param_name))
10535 		return false;
10536 	len = strlen(param_name);
10537 	if (len != target_len)
10538 		return false;
10539 	if (strcmp(param_name, name))
10540 		return false;
10541 
10542 	return true;
10543 }
10544 
10545 enum {
10546 	KF_ARG_DYNPTR_ID,
10547 	KF_ARG_LIST_HEAD_ID,
10548 	KF_ARG_LIST_NODE_ID,
10549 	KF_ARG_RB_ROOT_ID,
10550 	KF_ARG_RB_NODE_ID,
10551 };
10552 
10553 BTF_ID_LIST(kf_arg_btf_ids)
10554 BTF_ID(struct, bpf_dynptr_kern)
10555 BTF_ID(struct, bpf_list_head)
10556 BTF_ID(struct, bpf_list_node)
10557 BTF_ID(struct, bpf_rb_root)
10558 BTF_ID(struct, bpf_rb_node)
10559 
10560 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10561 				    const struct btf_param *arg, int type)
10562 {
10563 	const struct btf_type *t;
10564 	u32 res_id;
10565 
10566 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10567 	if (!t)
10568 		return false;
10569 	if (!btf_type_is_ptr(t))
10570 		return false;
10571 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10572 	if (!t)
10573 		return false;
10574 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10575 }
10576 
10577 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10578 {
10579 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10580 }
10581 
10582 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10583 {
10584 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10585 }
10586 
10587 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10588 {
10589 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10590 }
10591 
10592 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10593 {
10594 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10595 }
10596 
10597 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10598 {
10599 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10600 }
10601 
10602 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10603 				  const struct btf_param *arg)
10604 {
10605 	const struct btf_type *t;
10606 
10607 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10608 	if (!t)
10609 		return false;
10610 
10611 	return true;
10612 }
10613 
10614 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10615 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10616 					const struct btf *btf,
10617 					const struct btf_type *t, int rec)
10618 {
10619 	const struct btf_type *member_type;
10620 	const struct btf_member *member;
10621 	u32 i;
10622 
10623 	if (!btf_type_is_struct(t))
10624 		return false;
10625 
10626 	for_each_member(i, t, member) {
10627 		const struct btf_array *array;
10628 
10629 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10630 		if (btf_type_is_struct(member_type)) {
10631 			if (rec >= 3) {
10632 				verbose(env, "max struct nesting depth exceeded\n");
10633 				return false;
10634 			}
10635 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10636 				return false;
10637 			continue;
10638 		}
10639 		if (btf_type_is_array(member_type)) {
10640 			array = btf_array(member_type);
10641 			if (!array->nelems)
10642 				return false;
10643 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10644 			if (!btf_type_is_scalar(member_type))
10645 				return false;
10646 			continue;
10647 		}
10648 		if (!btf_type_is_scalar(member_type))
10649 			return false;
10650 	}
10651 	return true;
10652 }
10653 
10654 enum kfunc_ptr_arg_type {
10655 	KF_ARG_PTR_TO_CTX,
10656 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10657 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10658 	KF_ARG_PTR_TO_DYNPTR,
10659 	KF_ARG_PTR_TO_ITER,
10660 	KF_ARG_PTR_TO_LIST_HEAD,
10661 	KF_ARG_PTR_TO_LIST_NODE,
10662 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10663 	KF_ARG_PTR_TO_MEM,
10664 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10665 	KF_ARG_PTR_TO_CALLBACK,
10666 	KF_ARG_PTR_TO_RB_ROOT,
10667 	KF_ARG_PTR_TO_RB_NODE,
10668 };
10669 
10670 enum special_kfunc_type {
10671 	KF_bpf_obj_new_impl,
10672 	KF_bpf_obj_drop_impl,
10673 	KF_bpf_refcount_acquire_impl,
10674 	KF_bpf_list_push_front_impl,
10675 	KF_bpf_list_push_back_impl,
10676 	KF_bpf_list_pop_front,
10677 	KF_bpf_list_pop_back,
10678 	KF_bpf_cast_to_kern_ctx,
10679 	KF_bpf_rdonly_cast,
10680 	KF_bpf_rcu_read_lock,
10681 	KF_bpf_rcu_read_unlock,
10682 	KF_bpf_rbtree_remove,
10683 	KF_bpf_rbtree_add_impl,
10684 	KF_bpf_rbtree_first,
10685 	KF_bpf_dynptr_from_skb,
10686 	KF_bpf_dynptr_from_xdp,
10687 	KF_bpf_dynptr_slice,
10688 	KF_bpf_dynptr_slice_rdwr,
10689 	KF_bpf_dynptr_clone,
10690 };
10691 
10692 BTF_SET_START(special_kfunc_set)
10693 BTF_ID(func, bpf_obj_new_impl)
10694 BTF_ID(func, bpf_obj_drop_impl)
10695 BTF_ID(func, bpf_refcount_acquire_impl)
10696 BTF_ID(func, bpf_list_push_front_impl)
10697 BTF_ID(func, bpf_list_push_back_impl)
10698 BTF_ID(func, bpf_list_pop_front)
10699 BTF_ID(func, bpf_list_pop_back)
10700 BTF_ID(func, bpf_cast_to_kern_ctx)
10701 BTF_ID(func, bpf_rdonly_cast)
10702 BTF_ID(func, bpf_rbtree_remove)
10703 BTF_ID(func, bpf_rbtree_add_impl)
10704 BTF_ID(func, bpf_rbtree_first)
10705 BTF_ID(func, bpf_dynptr_from_skb)
10706 BTF_ID(func, bpf_dynptr_from_xdp)
10707 BTF_ID(func, bpf_dynptr_slice)
10708 BTF_ID(func, bpf_dynptr_slice_rdwr)
10709 BTF_ID(func, bpf_dynptr_clone)
10710 BTF_SET_END(special_kfunc_set)
10711 
10712 BTF_ID_LIST(special_kfunc_list)
10713 BTF_ID(func, bpf_obj_new_impl)
10714 BTF_ID(func, bpf_obj_drop_impl)
10715 BTF_ID(func, bpf_refcount_acquire_impl)
10716 BTF_ID(func, bpf_list_push_front_impl)
10717 BTF_ID(func, bpf_list_push_back_impl)
10718 BTF_ID(func, bpf_list_pop_front)
10719 BTF_ID(func, bpf_list_pop_back)
10720 BTF_ID(func, bpf_cast_to_kern_ctx)
10721 BTF_ID(func, bpf_rdonly_cast)
10722 BTF_ID(func, bpf_rcu_read_lock)
10723 BTF_ID(func, bpf_rcu_read_unlock)
10724 BTF_ID(func, bpf_rbtree_remove)
10725 BTF_ID(func, bpf_rbtree_add_impl)
10726 BTF_ID(func, bpf_rbtree_first)
10727 BTF_ID(func, bpf_dynptr_from_skb)
10728 BTF_ID(func, bpf_dynptr_from_xdp)
10729 BTF_ID(func, bpf_dynptr_slice)
10730 BTF_ID(func, bpf_dynptr_slice_rdwr)
10731 BTF_ID(func, bpf_dynptr_clone)
10732 
10733 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10734 {
10735 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10736 	    meta->arg_owning_ref) {
10737 		return false;
10738 	}
10739 
10740 	return meta->kfunc_flags & KF_RET_NULL;
10741 }
10742 
10743 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10744 {
10745 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10746 }
10747 
10748 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10749 {
10750 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10751 }
10752 
10753 static enum kfunc_ptr_arg_type
10754 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10755 		       struct bpf_kfunc_call_arg_meta *meta,
10756 		       const struct btf_type *t, const struct btf_type *ref_t,
10757 		       const char *ref_tname, const struct btf_param *args,
10758 		       int argno, int nargs)
10759 {
10760 	u32 regno = argno + 1;
10761 	struct bpf_reg_state *regs = cur_regs(env);
10762 	struct bpf_reg_state *reg = &regs[regno];
10763 	bool arg_mem_size = false;
10764 
10765 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10766 		return KF_ARG_PTR_TO_CTX;
10767 
10768 	/* In this function, we verify the kfunc's BTF as per the argument type,
10769 	 * leaving the rest of the verification with respect to the register
10770 	 * type to our caller. When a set of conditions hold in the BTF type of
10771 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10772 	 */
10773 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10774 		return KF_ARG_PTR_TO_CTX;
10775 
10776 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10777 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10778 
10779 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10780 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10781 
10782 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10783 		return KF_ARG_PTR_TO_DYNPTR;
10784 
10785 	if (is_kfunc_arg_iter(meta, argno))
10786 		return KF_ARG_PTR_TO_ITER;
10787 
10788 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10789 		return KF_ARG_PTR_TO_LIST_HEAD;
10790 
10791 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10792 		return KF_ARG_PTR_TO_LIST_NODE;
10793 
10794 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10795 		return KF_ARG_PTR_TO_RB_ROOT;
10796 
10797 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10798 		return KF_ARG_PTR_TO_RB_NODE;
10799 
10800 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10801 		if (!btf_type_is_struct(ref_t)) {
10802 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10803 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10804 			return -EINVAL;
10805 		}
10806 		return KF_ARG_PTR_TO_BTF_ID;
10807 	}
10808 
10809 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10810 		return KF_ARG_PTR_TO_CALLBACK;
10811 
10812 
10813 	if (argno + 1 < nargs &&
10814 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10815 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10816 		arg_mem_size = true;
10817 
10818 	/* This is the catch all argument type of register types supported by
10819 	 * check_helper_mem_access. However, we only allow when argument type is
10820 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10821 	 * arg_mem_size is true, the pointer can be void *.
10822 	 */
10823 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10824 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10825 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10826 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10827 		return -EINVAL;
10828 	}
10829 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10830 }
10831 
10832 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10833 					struct bpf_reg_state *reg,
10834 					const struct btf_type *ref_t,
10835 					const char *ref_tname, u32 ref_id,
10836 					struct bpf_kfunc_call_arg_meta *meta,
10837 					int argno)
10838 {
10839 	const struct btf_type *reg_ref_t;
10840 	bool strict_type_match = false;
10841 	const struct btf *reg_btf;
10842 	const char *reg_ref_tname;
10843 	u32 reg_ref_id;
10844 
10845 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10846 		reg_btf = reg->btf;
10847 		reg_ref_id = reg->btf_id;
10848 	} else {
10849 		reg_btf = btf_vmlinux;
10850 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10851 	}
10852 
10853 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10854 	 * or releasing a reference, or are no-cast aliases. We do _not_
10855 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10856 	 * as we want to enable BPF programs to pass types that are bitwise
10857 	 * equivalent without forcing them to explicitly cast with something
10858 	 * like bpf_cast_to_kern_ctx().
10859 	 *
10860 	 * For example, say we had a type like the following:
10861 	 *
10862 	 * struct bpf_cpumask {
10863 	 *	cpumask_t cpumask;
10864 	 *	refcount_t usage;
10865 	 * };
10866 	 *
10867 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10868 	 * to a struct cpumask, so it would be safe to pass a struct
10869 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10870 	 *
10871 	 * The philosophy here is similar to how we allow scalars of different
10872 	 * types to be passed to kfuncs as long as the size is the same. The
10873 	 * only difference here is that we're simply allowing
10874 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10875 	 * resolve types.
10876 	 */
10877 	if (is_kfunc_acquire(meta) ||
10878 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10879 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10880 		strict_type_match = true;
10881 
10882 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10883 
10884 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10885 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10886 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10887 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10888 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10889 			btf_type_str(reg_ref_t), reg_ref_tname);
10890 		return -EINVAL;
10891 	}
10892 	return 0;
10893 }
10894 
10895 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10896 {
10897 	struct bpf_verifier_state *state = env->cur_state;
10898 	struct btf_record *rec = reg_btf_record(reg);
10899 
10900 	if (!state->active_lock.ptr) {
10901 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10902 		return -EFAULT;
10903 	}
10904 
10905 	if (type_flag(reg->type) & NON_OWN_REF) {
10906 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10907 		return -EFAULT;
10908 	}
10909 
10910 	reg->type |= NON_OWN_REF;
10911 	if (rec->refcount_off >= 0)
10912 		reg->type |= MEM_RCU;
10913 
10914 	return 0;
10915 }
10916 
10917 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10918 {
10919 	struct bpf_func_state *state, *unused;
10920 	struct bpf_reg_state *reg;
10921 	int i;
10922 
10923 	state = cur_func(env);
10924 
10925 	if (!ref_obj_id) {
10926 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10927 			     "owning -> non-owning conversion\n");
10928 		return -EFAULT;
10929 	}
10930 
10931 	for (i = 0; i < state->acquired_refs; i++) {
10932 		if (state->refs[i].id != ref_obj_id)
10933 			continue;
10934 
10935 		/* Clear ref_obj_id here so release_reference doesn't clobber
10936 		 * the whole reg
10937 		 */
10938 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10939 			if (reg->ref_obj_id == ref_obj_id) {
10940 				reg->ref_obj_id = 0;
10941 				ref_set_non_owning(env, reg);
10942 			}
10943 		}));
10944 		return 0;
10945 	}
10946 
10947 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10948 	return -EFAULT;
10949 }
10950 
10951 /* Implementation details:
10952  *
10953  * Each register points to some region of memory, which we define as an
10954  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10955  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10956  * allocation. The lock and the data it protects are colocated in the same
10957  * memory region.
10958  *
10959  * Hence, everytime a register holds a pointer value pointing to such
10960  * allocation, the verifier preserves a unique reg->id for it.
10961  *
10962  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10963  * bpf_spin_lock is called.
10964  *
10965  * To enable this, lock state in the verifier captures two values:
10966  *	active_lock.ptr = Register's type specific pointer
10967  *	active_lock.id  = A unique ID for each register pointer value
10968  *
10969  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10970  * supported register types.
10971  *
10972  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10973  * allocated objects is the reg->btf pointer.
10974  *
10975  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10976  * can establish the provenance of the map value statically for each distinct
10977  * lookup into such maps. They always contain a single map value hence unique
10978  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10979  *
10980  * So, in case of global variables, they use array maps with max_entries = 1,
10981  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10982  * into the same map value as max_entries is 1, as described above).
10983  *
10984  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10985  * outer map pointer (in verifier context), but each lookup into an inner map
10986  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10987  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10988  * will get different reg->id assigned to each lookup, hence different
10989  * active_lock.id.
10990  *
10991  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10992  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10993  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10994  */
10995 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10996 {
10997 	void *ptr;
10998 	u32 id;
10999 
11000 	switch ((int)reg->type) {
11001 	case PTR_TO_MAP_VALUE:
11002 		ptr = reg->map_ptr;
11003 		break;
11004 	case PTR_TO_BTF_ID | MEM_ALLOC:
11005 		ptr = reg->btf;
11006 		break;
11007 	default:
11008 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11009 		return -EFAULT;
11010 	}
11011 	id = reg->id;
11012 
11013 	if (!env->cur_state->active_lock.ptr)
11014 		return -EINVAL;
11015 	if (env->cur_state->active_lock.ptr != ptr ||
11016 	    env->cur_state->active_lock.id != id) {
11017 		verbose(env, "held lock and object are not in the same allocation\n");
11018 		return -EINVAL;
11019 	}
11020 	return 0;
11021 }
11022 
11023 static bool is_bpf_list_api_kfunc(u32 btf_id)
11024 {
11025 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11026 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11027 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11028 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11029 }
11030 
11031 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11032 {
11033 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11034 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11035 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11036 }
11037 
11038 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11039 {
11040 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11041 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11042 }
11043 
11044 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11045 {
11046 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11047 }
11048 
11049 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11050 {
11051 	return is_bpf_rbtree_api_kfunc(btf_id);
11052 }
11053 
11054 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11055 					  enum btf_field_type head_field_type,
11056 					  u32 kfunc_btf_id)
11057 {
11058 	bool ret;
11059 
11060 	switch (head_field_type) {
11061 	case BPF_LIST_HEAD:
11062 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11063 		break;
11064 	case BPF_RB_ROOT:
11065 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11066 		break;
11067 	default:
11068 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11069 			btf_field_type_name(head_field_type));
11070 		return false;
11071 	}
11072 
11073 	if (!ret)
11074 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11075 			btf_field_type_name(head_field_type));
11076 	return ret;
11077 }
11078 
11079 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11080 					  enum btf_field_type node_field_type,
11081 					  u32 kfunc_btf_id)
11082 {
11083 	bool ret;
11084 
11085 	switch (node_field_type) {
11086 	case BPF_LIST_NODE:
11087 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11088 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11089 		break;
11090 	case BPF_RB_NODE:
11091 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11092 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11093 		break;
11094 	default:
11095 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11096 			btf_field_type_name(node_field_type));
11097 		return false;
11098 	}
11099 
11100 	if (!ret)
11101 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11102 			btf_field_type_name(node_field_type));
11103 	return ret;
11104 }
11105 
11106 static int
11107 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11108 				   struct bpf_reg_state *reg, u32 regno,
11109 				   struct bpf_kfunc_call_arg_meta *meta,
11110 				   enum btf_field_type head_field_type,
11111 				   struct btf_field **head_field)
11112 {
11113 	const char *head_type_name;
11114 	struct btf_field *field;
11115 	struct btf_record *rec;
11116 	u32 head_off;
11117 
11118 	if (meta->btf != btf_vmlinux) {
11119 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11120 		return -EFAULT;
11121 	}
11122 
11123 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11124 		return -EFAULT;
11125 
11126 	head_type_name = btf_field_type_name(head_field_type);
11127 	if (!tnum_is_const(reg->var_off)) {
11128 		verbose(env,
11129 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11130 			regno, head_type_name);
11131 		return -EINVAL;
11132 	}
11133 
11134 	rec = reg_btf_record(reg);
11135 	head_off = reg->off + reg->var_off.value;
11136 	field = btf_record_find(rec, head_off, head_field_type);
11137 	if (!field) {
11138 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11139 		return -EINVAL;
11140 	}
11141 
11142 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11143 	if (check_reg_allocation_locked(env, reg)) {
11144 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11145 			rec->spin_lock_off, head_type_name);
11146 		return -EINVAL;
11147 	}
11148 
11149 	if (*head_field) {
11150 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11151 		return -EFAULT;
11152 	}
11153 	*head_field = field;
11154 	return 0;
11155 }
11156 
11157 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11158 					   struct bpf_reg_state *reg, u32 regno,
11159 					   struct bpf_kfunc_call_arg_meta *meta)
11160 {
11161 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11162 							  &meta->arg_list_head.field);
11163 }
11164 
11165 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11166 					     struct bpf_reg_state *reg, u32 regno,
11167 					     struct bpf_kfunc_call_arg_meta *meta)
11168 {
11169 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11170 							  &meta->arg_rbtree_root.field);
11171 }
11172 
11173 static int
11174 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11175 				   struct bpf_reg_state *reg, u32 regno,
11176 				   struct bpf_kfunc_call_arg_meta *meta,
11177 				   enum btf_field_type head_field_type,
11178 				   enum btf_field_type node_field_type,
11179 				   struct btf_field **node_field)
11180 {
11181 	const char *node_type_name;
11182 	const struct btf_type *et, *t;
11183 	struct btf_field *field;
11184 	u32 node_off;
11185 
11186 	if (meta->btf != btf_vmlinux) {
11187 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11188 		return -EFAULT;
11189 	}
11190 
11191 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11192 		return -EFAULT;
11193 
11194 	node_type_name = btf_field_type_name(node_field_type);
11195 	if (!tnum_is_const(reg->var_off)) {
11196 		verbose(env,
11197 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11198 			regno, node_type_name);
11199 		return -EINVAL;
11200 	}
11201 
11202 	node_off = reg->off + reg->var_off.value;
11203 	field = reg_find_field_offset(reg, node_off, node_field_type);
11204 	if (!field || field->offset != node_off) {
11205 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11206 		return -EINVAL;
11207 	}
11208 
11209 	field = *node_field;
11210 
11211 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11212 	t = btf_type_by_id(reg->btf, reg->btf_id);
11213 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11214 				  field->graph_root.value_btf_id, true)) {
11215 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11216 			"in struct %s, but arg is at offset=%d in struct %s\n",
11217 			btf_field_type_name(head_field_type),
11218 			btf_field_type_name(node_field_type),
11219 			field->graph_root.node_offset,
11220 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11221 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11222 		return -EINVAL;
11223 	}
11224 	meta->arg_btf = reg->btf;
11225 	meta->arg_btf_id = reg->btf_id;
11226 
11227 	if (node_off != field->graph_root.node_offset) {
11228 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11229 			node_off, btf_field_type_name(node_field_type),
11230 			field->graph_root.node_offset,
11231 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11232 		return -EINVAL;
11233 	}
11234 
11235 	return 0;
11236 }
11237 
11238 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11239 					   struct bpf_reg_state *reg, u32 regno,
11240 					   struct bpf_kfunc_call_arg_meta *meta)
11241 {
11242 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11243 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11244 						  &meta->arg_list_head.field);
11245 }
11246 
11247 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11248 					     struct bpf_reg_state *reg, u32 regno,
11249 					     struct bpf_kfunc_call_arg_meta *meta)
11250 {
11251 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11252 						  BPF_RB_ROOT, BPF_RB_NODE,
11253 						  &meta->arg_rbtree_root.field);
11254 }
11255 
11256 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11257 			    int insn_idx)
11258 {
11259 	const char *func_name = meta->func_name, *ref_tname;
11260 	const struct btf *btf = meta->btf;
11261 	const struct btf_param *args;
11262 	struct btf_record *rec;
11263 	u32 i, nargs;
11264 	int ret;
11265 
11266 	args = (const struct btf_param *)(meta->func_proto + 1);
11267 	nargs = btf_type_vlen(meta->func_proto);
11268 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11269 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11270 			MAX_BPF_FUNC_REG_ARGS);
11271 		return -EINVAL;
11272 	}
11273 
11274 	/* Check that BTF function arguments match actual types that the
11275 	 * verifier sees.
11276 	 */
11277 	for (i = 0; i < nargs; i++) {
11278 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11279 		const struct btf_type *t, *ref_t, *resolve_ret;
11280 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11281 		u32 regno = i + 1, ref_id, type_size;
11282 		bool is_ret_buf_sz = false;
11283 		int kf_arg_type;
11284 
11285 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11286 
11287 		if (is_kfunc_arg_ignore(btf, &args[i]))
11288 			continue;
11289 
11290 		if (btf_type_is_scalar(t)) {
11291 			if (reg->type != SCALAR_VALUE) {
11292 				verbose(env, "R%d is not a scalar\n", regno);
11293 				return -EINVAL;
11294 			}
11295 
11296 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11297 				if (meta->arg_constant.found) {
11298 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11299 					return -EFAULT;
11300 				}
11301 				if (!tnum_is_const(reg->var_off)) {
11302 					verbose(env, "R%d must be a known constant\n", regno);
11303 					return -EINVAL;
11304 				}
11305 				ret = mark_chain_precision(env, regno);
11306 				if (ret < 0)
11307 					return ret;
11308 				meta->arg_constant.found = true;
11309 				meta->arg_constant.value = reg->var_off.value;
11310 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11311 				meta->r0_rdonly = true;
11312 				is_ret_buf_sz = true;
11313 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11314 				is_ret_buf_sz = true;
11315 			}
11316 
11317 			if (is_ret_buf_sz) {
11318 				if (meta->r0_size) {
11319 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11320 					return -EINVAL;
11321 				}
11322 
11323 				if (!tnum_is_const(reg->var_off)) {
11324 					verbose(env, "R%d is not a const\n", regno);
11325 					return -EINVAL;
11326 				}
11327 
11328 				meta->r0_size = reg->var_off.value;
11329 				ret = mark_chain_precision(env, regno);
11330 				if (ret)
11331 					return ret;
11332 			}
11333 			continue;
11334 		}
11335 
11336 		if (!btf_type_is_ptr(t)) {
11337 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11338 			return -EINVAL;
11339 		}
11340 
11341 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11342 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11343 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11344 			return -EACCES;
11345 		}
11346 
11347 		if (reg->ref_obj_id) {
11348 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11349 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11350 					regno, reg->ref_obj_id,
11351 					meta->ref_obj_id);
11352 				return -EFAULT;
11353 			}
11354 			meta->ref_obj_id = reg->ref_obj_id;
11355 			if (is_kfunc_release(meta))
11356 				meta->release_regno = regno;
11357 		}
11358 
11359 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11360 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11361 
11362 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11363 		if (kf_arg_type < 0)
11364 			return kf_arg_type;
11365 
11366 		switch (kf_arg_type) {
11367 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11368 		case KF_ARG_PTR_TO_BTF_ID:
11369 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11370 				break;
11371 
11372 			if (!is_trusted_reg(reg)) {
11373 				if (!is_kfunc_rcu(meta)) {
11374 					verbose(env, "R%d must be referenced or trusted\n", regno);
11375 					return -EINVAL;
11376 				}
11377 				if (!is_rcu_reg(reg)) {
11378 					verbose(env, "R%d must be a rcu pointer\n", regno);
11379 					return -EINVAL;
11380 				}
11381 			}
11382 
11383 			fallthrough;
11384 		case KF_ARG_PTR_TO_CTX:
11385 			/* Trusted arguments have the same offset checks as release arguments */
11386 			arg_type |= OBJ_RELEASE;
11387 			break;
11388 		case KF_ARG_PTR_TO_DYNPTR:
11389 		case KF_ARG_PTR_TO_ITER:
11390 		case KF_ARG_PTR_TO_LIST_HEAD:
11391 		case KF_ARG_PTR_TO_LIST_NODE:
11392 		case KF_ARG_PTR_TO_RB_ROOT:
11393 		case KF_ARG_PTR_TO_RB_NODE:
11394 		case KF_ARG_PTR_TO_MEM:
11395 		case KF_ARG_PTR_TO_MEM_SIZE:
11396 		case KF_ARG_PTR_TO_CALLBACK:
11397 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11398 			/* Trusted by default */
11399 			break;
11400 		default:
11401 			WARN_ON_ONCE(1);
11402 			return -EFAULT;
11403 		}
11404 
11405 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11406 			arg_type |= OBJ_RELEASE;
11407 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11408 		if (ret < 0)
11409 			return ret;
11410 
11411 		switch (kf_arg_type) {
11412 		case KF_ARG_PTR_TO_CTX:
11413 			if (reg->type != PTR_TO_CTX) {
11414 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11415 				return -EINVAL;
11416 			}
11417 
11418 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11419 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11420 				if (ret < 0)
11421 					return -EINVAL;
11422 				meta->ret_btf_id  = ret;
11423 			}
11424 			break;
11425 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11426 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11427 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11428 				return -EINVAL;
11429 			}
11430 			if (!reg->ref_obj_id) {
11431 				verbose(env, "allocated object must be referenced\n");
11432 				return -EINVAL;
11433 			}
11434 			if (meta->btf == btf_vmlinux &&
11435 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11436 				meta->arg_btf = reg->btf;
11437 				meta->arg_btf_id = reg->btf_id;
11438 			}
11439 			break;
11440 		case KF_ARG_PTR_TO_DYNPTR:
11441 		{
11442 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11443 			int clone_ref_obj_id = 0;
11444 
11445 			if (reg->type != PTR_TO_STACK &&
11446 			    reg->type != CONST_PTR_TO_DYNPTR) {
11447 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11448 				return -EINVAL;
11449 			}
11450 
11451 			if (reg->type == CONST_PTR_TO_DYNPTR)
11452 				dynptr_arg_type |= MEM_RDONLY;
11453 
11454 			if (is_kfunc_arg_uninit(btf, &args[i]))
11455 				dynptr_arg_type |= MEM_UNINIT;
11456 
11457 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11458 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11459 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11460 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11461 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11462 				   (dynptr_arg_type & MEM_UNINIT)) {
11463 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11464 
11465 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11466 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11467 					return -EFAULT;
11468 				}
11469 
11470 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11471 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11472 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11473 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11474 					return -EFAULT;
11475 				}
11476 			}
11477 
11478 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11479 			if (ret < 0)
11480 				return ret;
11481 
11482 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11483 				int id = dynptr_id(env, reg);
11484 
11485 				if (id < 0) {
11486 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11487 					return id;
11488 				}
11489 				meta->initialized_dynptr.id = id;
11490 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11491 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11492 			}
11493 
11494 			break;
11495 		}
11496 		case KF_ARG_PTR_TO_ITER:
11497 			ret = process_iter_arg(env, regno, insn_idx, meta);
11498 			if (ret < 0)
11499 				return ret;
11500 			break;
11501 		case KF_ARG_PTR_TO_LIST_HEAD:
11502 			if (reg->type != PTR_TO_MAP_VALUE &&
11503 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11504 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11505 				return -EINVAL;
11506 			}
11507 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11508 				verbose(env, "allocated object must be referenced\n");
11509 				return -EINVAL;
11510 			}
11511 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11512 			if (ret < 0)
11513 				return ret;
11514 			break;
11515 		case KF_ARG_PTR_TO_RB_ROOT:
11516 			if (reg->type != PTR_TO_MAP_VALUE &&
11517 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11518 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11519 				return -EINVAL;
11520 			}
11521 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11522 				verbose(env, "allocated object must be referenced\n");
11523 				return -EINVAL;
11524 			}
11525 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11526 			if (ret < 0)
11527 				return ret;
11528 			break;
11529 		case KF_ARG_PTR_TO_LIST_NODE:
11530 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11531 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11532 				return -EINVAL;
11533 			}
11534 			if (!reg->ref_obj_id) {
11535 				verbose(env, "allocated object must be referenced\n");
11536 				return -EINVAL;
11537 			}
11538 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11539 			if (ret < 0)
11540 				return ret;
11541 			break;
11542 		case KF_ARG_PTR_TO_RB_NODE:
11543 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11544 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11545 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11546 					return -EINVAL;
11547 				}
11548 				if (in_rbtree_lock_required_cb(env)) {
11549 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11550 					return -EINVAL;
11551 				}
11552 			} else {
11553 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11554 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11555 					return -EINVAL;
11556 				}
11557 				if (!reg->ref_obj_id) {
11558 					verbose(env, "allocated object must be referenced\n");
11559 					return -EINVAL;
11560 				}
11561 			}
11562 
11563 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11564 			if (ret < 0)
11565 				return ret;
11566 			break;
11567 		case KF_ARG_PTR_TO_BTF_ID:
11568 			/* Only base_type is checked, further checks are done here */
11569 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11570 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11571 			    !reg2btf_ids[base_type(reg->type)]) {
11572 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11573 				verbose(env, "expected %s or socket\n",
11574 					reg_type_str(env, base_type(reg->type) |
11575 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11576 				return -EINVAL;
11577 			}
11578 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11579 			if (ret < 0)
11580 				return ret;
11581 			break;
11582 		case KF_ARG_PTR_TO_MEM:
11583 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11584 			if (IS_ERR(resolve_ret)) {
11585 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11586 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11587 				return -EINVAL;
11588 			}
11589 			ret = check_mem_reg(env, reg, regno, type_size);
11590 			if (ret < 0)
11591 				return ret;
11592 			break;
11593 		case KF_ARG_PTR_TO_MEM_SIZE:
11594 		{
11595 			struct bpf_reg_state *buff_reg = &regs[regno];
11596 			const struct btf_param *buff_arg = &args[i];
11597 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11598 			const struct btf_param *size_arg = &args[i + 1];
11599 
11600 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11601 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11602 				if (ret < 0) {
11603 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11604 					return ret;
11605 				}
11606 			}
11607 
11608 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11609 				if (meta->arg_constant.found) {
11610 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11611 					return -EFAULT;
11612 				}
11613 				if (!tnum_is_const(size_reg->var_off)) {
11614 					verbose(env, "R%d must be a known constant\n", regno + 1);
11615 					return -EINVAL;
11616 				}
11617 				meta->arg_constant.found = true;
11618 				meta->arg_constant.value = size_reg->var_off.value;
11619 			}
11620 
11621 			/* Skip next '__sz' or '__szk' argument */
11622 			i++;
11623 			break;
11624 		}
11625 		case KF_ARG_PTR_TO_CALLBACK:
11626 			if (reg->type != PTR_TO_FUNC) {
11627 				verbose(env, "arg%d expected pointer to func\n", i);
11628 				return -EINVAL;
11629 			}
11630 			meta->subprogno = reg->subprogno;
11631 			break;
11632 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11633 			if (!type_is_ptr_alloc_obj(reg->type)) {
11634 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11635 				return -EINVAL;
11636 			}
11637 			if (!type_is_non_owning_ref(reg->type))
11638 				meta->arg_owning_ref = true;
11639 
11640 			rec = reg_btf_record(reg);
11641 			if (!rec) {
11642 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11643 				return -EFAULT;
11644 			}
11645 
11646 			if (rec->refcount_off < 0) {
11647 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11648 				return -EINVAL;
11649 			}
11650 
11651 			meta->arg_btf = reg->btf;
11652 			meta->arg_btf_id = reg->btf_id;
11653 			break;
11654 		}
11655 	}
11656 
11657 	if (is_kfunc_release(meta) && !meta->release_regno) {
11658 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11659 			func_name);
11660 		return -EINVAL;
11661 	}
11662 
11663 	return 0;
11664 }
11665 
11666 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11667 			    struct bpf_insn *insn,
11668 			    struct bpf_kfunc_call_arg_meta *meta,
11669 			    const char **kfunc_name)
11670 {
11671 	const struct btf_type *func, *func_proto;
11672 	u32 func_id, *kfunc_flags;
11673 	const char *func_name;
11674 	struct btf *desc_btf;
11675 
11676 	if (kfunc_name)
11677 		*kfunc_name = NULL;
11678 
11679 	if (!insn->imm)
11680 		return -EINVAL;
11681 
11682 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11683 	if (IS_ERR(desc_btf))
11684 		return PTR_ERR(desc_btf);
11685 
11686 	func_id = insn->imm;
11687 	func = btf_type_by_id(desc_btf, func_id);
11688 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11689 	if (kfunc_name)
11690 		*kfunc_name = func_name;
11691 	func_proto = btf_type_by_id(desc_btf, func->type);
11692 
11693 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11694 	if (!kfunc_flags) {
11695 		return -EACCES;
11696 	}
11697 
11698 	memset(meta, 0, sizeof(*meta));
11699 	meta->btf = desc_btf;
11700 	meta->func_id = func_id;
11701 	meta->kfunc_flags = *kfunc_flags;
11702 	meta->func_proto = func_proto;
11703 	meta->func_name = func_name;
11704 
11705 	return 0;
11706 }
11707 
11708 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11709 			    int *insn_idx_p)
11710 {
11711 	const struct btf_type *t, *ptr_type;
11712 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11713 	struct bpf_reg_state *regs = cur_regs(env);
11714 	const char *func_name, *ptr_type_name;
11715 	bool sleepable, rcu_lock, rcu_unlock;
11716 	struct bpf_kfunc_call_arg_meta meta;
11717 	struct bpf_insn_aux_data *insn_aux;
11718 	int err, insn_idx = *insn_idx_p;
11719 	const struct btf_param *args;
11720 	const struct btf_type *ret_t;
11721 	struct btf *desc_btf;
11722 
11723 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11724 	if (!insn->imm)
11725 		return 0;
11726 
11727 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11728 	if (err == -EACCES && func_name)
11729 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11730 	if (err)
11731 		return err;
11732 	desc_btf = meta.btf;
11733 	insn_aux = &env->insn_aux_data[insn_idx];
11734 
11735 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11736 
11737 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11738 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11739 		return -EACCES;
11740 	}
11741 
11742 	sleepable = is_kfunc_sleepable(&meta);
11743 	if (sleepable && !env->prog->aux->sleepable) {
11744 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11745 		return -EACCES;
11746 	}
11747 
11748 	/* Check the arguments */
11749 	err = check_kfunc_args(env, &meta, insn_idx);
11750 	if (err < 0)
11751 		return err;
11752 
11753 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11754 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11755 					 set_rbtree_add_callback_state);
11756 		if (err) {
11757 			verbose(env, "kfunc %s#%d failed callback verification\n",
11758 				func_name, meta.func_id);
11759 			return err;
11760 		}
11761 	}
11762 
11763 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11764 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11765 
11766 	if (env->cur_state->active_rcu_lock) {
11767 		struct bpf_func_state *state;
11768 		struct bpf_reg_state *reg;
11769 
11770 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11771 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11772 			return -EACCES;
11773 		}
11774 
11775 		if (rcu_lock) {
11776 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11777 			return -EINVAL;
11778 		} else if (rcu_unlock) {
11779 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11780 				if (reg->type & MEM_RCU) {
11781 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11782 					reg->type |= PTR_UNTRUSTED;
11783 				}
11784 			}));
11785 			env->cur_state->active_rcu_lock = false;
11786 		} else if (sleepable) {
11787 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11788 			return -EACCES;
11789 		}
11790 	} else if (rcu_lock) {
11791 		env->cur_state->active_rcu_lock = true;
11792 	} else if (rcu_unlock) {
11793 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11794 		return -EINVAL;
11795 	}
11796 
11797 	/* In case of release function, we get register number of refcounted
11798 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11799 	 */
11800 	if (meta.release_regno) {
11801 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11802 		if (err) {
11803 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11804 				func_name, meta.func_id);
11805 			return err;
11806 		}
11807 	}
11808 
11809 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11810 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11811 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11812 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11813 		insn_aux->insert_off = regs[BPF_REG_2].off;
11814 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11815 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11816 		if (err) {
11817 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11818 				func_name, meta.func_id);
11819 			return err;
11820 		}
11821 
11822 		err = release_reference(env, release_ref_obj_id);
11823 		if (err) {
11824 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11825 				func_name, meta.func_id);
11826 			return err;
11827 		}
11828 	}
11829 
11830 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11831 		mark_reg_not_init(env, regs, caller_saved[i]);
11832 
11833 	/* Check return type */
11834 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11835 
11836 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11837 		/* Only exception is bpf_obj_new_impl */
11838 		if (meta.btf != btf_vmlinux ||
11839 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11840 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11841 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11842 			return -EINVAL;
11843 		}
11844 	}
11845 
11846 	if (btf_type_is_scalar(t)) {
11847 		mark_reg_unknown(env, regs, BPF_REG_0);
11848 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11849 	} else if (btf_type_is_ptr(t)) {
11850 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11851 
11852 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11853 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11854 				struct btf *ret_btf;
11855 				u32 ret_btf_id;
11856 
11857 				if (unlikely(!bpf_global_ma_set))
11858 					return -ENOMEM;
11859 
11860 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11861 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11862 					return -EINVAL;
11863 				}
11864 
11865 				ret_btf = env->prog->aux->btf;
11866 				ret_btf_id = meta.arg_constant.value;
11867 
11868 				/* This may be NULL due to user not supplying a BTF */
11869 				if (!ret_btf) {
11870 					verbose(env, "bpf_obj_new requires prog BTF\n");
11871 					return -EINVAL;
11872 				}
11873 
11874 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11875 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11876 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11877 					return -EINVAL;
11878 				}
11879 
11880 				mark_reg_known_zero(env, regs, BPF_REG_0);
11881 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11882 				regs[BPF_REG_0].btf = ret_btf;
11883 				regs[BPF_REG_0].btf_id = ret_btf_id;
11884 
11885 				insn_aux->obj_new_size = ret_t->size;
11886 				insn_aux->kptr_struct_meta =
11887 					btf_find_struct_meta(ret_btf, ret_btf_id);
11888 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11889 				mark_reg_known_zero(env, regs, BPF_REG_0);
11890 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11891 				regs[BPF_REG_0].btf = meta.arg_btf;
11892 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11893 
11894 				insn_aux->kptr_struct_meta =
11895 					btf_find_struct_meta(meta.arg_btf,
11896 							     meta.arg_btf_id);
11897 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11898 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11899 				struct btf_field *field = meta.arg_list_head.field;
11900 
11901 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11902 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11903 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11904 				struct btf_field *field = meta.arg_rbtree_root.field;
11905 
11906 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11907 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11908 				mark_reg_known_zero(env, regs, BPF_REG_0);
11909 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11910 				regs[BPF_REG_0].btf = desc_btf;
11911 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11912 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11913 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11914 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11915 					verbose(env,
11916 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11917 					return -EINVAL;
11918 				}
11919 
11920 				mark_reg_known_zero(env, regs, BPF_REG_0);
11921 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11922 				regs[BPF_REG_0].btf = desc_btf;
11923 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11924 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11925 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11926 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11927 
11928 				mark_reg_known_zero(env, regs, BPF_REG_0);
11929 
11930 				if (!meta.arg_constant.found) {
11931 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11932 					return -EFAULT;
11933 				}
11934 
11935 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11936 
11937 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11938 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11939 
11940 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11941 					regs[BPF_REG_0].type |= MEM_RDONLY;
11942 				} else {
11943 					/* this will set env->seen_direct_write to true */
11944 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11945 						verbose(env, "the prog does not allow writes to packet data\n");
11946 						return -EINVAL;
11947 					}
11948 				}
11949 
11950 				if (!meta.initialized_dynptr.id) {
11951 					verbose(env, "verifier internal error: no dynptr id\n");
11952 					return -EFAULT;
11953 				}
11954 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11955 
11956 				/* we don't need to set BPF_REG_0's ref obj id
11957 				 * because packet slices are not refcounted (see
11958 				 * dynptr_type_refcounted)
11959 				 */
11960 			} else {
11961 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11962 					meta.func_name);
11963 				return -EFAULT;
11964 			}
11965 		} else if (!__btf_type_is_struct(ptr_type)) {
11966 			if (!meta.r0_size) {
11967 				__u32 sz;
11968 
11969 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11970 					meta.r0_size = sz;
11971 					meta.r0_rdonly = true;
11972 				}
11973 			}
11974 			if (!meta.r0_size) {
11975 				ptr_type_name = btf_name_by_offset(desc_btf,
11976 								   ptr_type->name_off);
11977 				verbose(env,
11978 					"kernel function %s returns pointer type %s %s is not supported\n",
11979 					func_name,
11980 					btf_type_str(ptr_type),
11981 					ptr_type_name);
11982 				return -EINVAL;
11983 			}
11984 
11985 			mark_reg_known_zero(env, regs, BPF_REG_0);
11986 			regs[BPF_REG_0].type = PTR_TO_MEM;
11987 			regs[BPF_REG_0].mem_size = meta.r0_size;
11988 
11989 			if (meta.r0_rdonly)
11990 				regs[BPF_REG_0].type |= MEM_RDONLY;
11991 
11992 			/* Ensures we don't access the memory after a release_reference() */
11993 			if (meta.ref_obj_id)
11994 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11995 		} else {
11996 			mark_reg_known_zero(env, regs, BPF_REG_0);
11997 			regs[BPF_REG_0].btf = desc_btf;
11998 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11999 			regs[BPF_REG_0].btf_id = ptr_type_id;
12000 		}
12001 
12002 		if (is_kfunc_ret_null(&meta)) {
12003 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12004 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12005 			regs[BPF_REG_0].id = ++env->id_gen;
12006 		}
12007 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12008 		if (is_kfunc_acquire(&meta)) {
12009 			int id = acquire_reference_state(env, insn_idx);
12010 
12011 			if (id < 0)
12012 				return id;
12013 			if (is_kfunc_ret_null(&meta))
12014 				regs[BPF_REG_0].id = id;
12015 			regs[BPF_REG_0].ref_obj_id = id;
12016 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12017 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12018 		}
12019 
12020 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12021 			regs[BPF_REG_0].id = ++env->id_gen;
12022 	} else if (btf_type_is_void(t)) {
12023 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12024 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12025 				insn_aux->kptr_struct_meta =
12026 					btf_find_struct_meta(meta.arg_btf,
12027 							     meta.arg_btf_id);
12028 			}
12029 		}
12030 	}
12031 
12032 	nargs = btf_type_vlen(meta.func_proto);
12033 	args = (const struct btf_param *)(meta.func_proto + 1);
12034 	for (i = 0; i < nargs; i++) {
12035 		u32 regno = i + 1;
12036 
12037 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12038 		if (btf_type_is_ptr(t))
12039 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12040 		else
12041 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12042 			mark_btf_func_reg_size(env, regno, t->size);
12043 	}
12044 
12045 	if (is_iter_next_kfunc(&meta)) {
12046 		err = process_iter_next_call(env, insn_idx, &meta);
12047 		if (err)
12048 			return err;
12049 	}
12050 
12051 	return 0;
12052 }
12053 
12054 static bool signed_add_overflows(s64 a, s64 b)
12055 {
12056 	/* Do the add in u64, where overflow is well-defined */
12057 	s64 res = (s64)((u64)a + (u64)b);
12058 
12059 	if (b < 0)
12060 		return res > a;
12061 	return res < a;
12062 }
12063 
12064 static bool signed_add32_overflows(s32 a, s32 b)
12065 {
12066 	/* Do the add in u32, where overflow is well-defined */
12067 	s32 res = (s32)((u32)a + (u32)b);
12068 
12069 	if (b < 0)
12070 		return res > a;
12071 	return res < a;
12072 }
12073 
12074 static bool signed_sub_overflows(s64 a, s64 b)
12075 {
12076 	/* Do the sub in u64, where overflow is well-defined */
12077 	s64 res = (s64)((u64)a - (u64)b);
12078 
12079 	if (b < 0)
12080 		return res < a;
12081 	return res > a;
12082 }
12083 
12084 static bool signed_sub32_overflows(s32 a, s32 b)
12085 {
12086 	/* Do the sub in u32, where overflow is well-defined */
12087 	s32 res = (s32)((u32)a - (u32)b);
12088 
12089 	if (b < 0)
12090 		return res < a;
12091 	return res > a;
12092 }
12093 
12094 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12095 				  const struct bpf_reg_state *reg,
12096 				  enum bpf_reg_type type)
12097 {
12098 	bool known = tnum_is_const(reg->var_off);
12099 	s64 val = reg->var_off.value;
12100 	s64 smin = reg->smin_value;
12101 
12102 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12103 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12104 			reg_type_str(env, type), val);
12105 		return false;
12106 	}
12107 
12108 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12109 		verbose(env, "%s pointer offset %d is not allowed\n",
12110 			reg_type_str(env, type), reg->off);
12111 		return false;
12112 	}
12113 
12114 	if (smin == S64_MIN) {
12115 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12116 			reg_type_str(env, type));
12117 		return false;
12118 	}
12119 
12120 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12121 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12122 			smin, reg_type_str(env, type));
12123 		return false;
12124 	}
12125 
12126 	return true;
12127 }
12128 
12129 enum {
12130 	REASON_BOUNDS	= -1,
12131 	REASON_TYPE	= -2,
12132 	REASON_PATHS	= -3,
12133 	REASON_LIMIT	= -4,
12134 	REASON_STACK	= -5,
12135 };
12136 
12137 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12138 			      u32 *alu_limit, bool mask_to_left)
12139 {
12140 	u32 max = 0, ptr_limit = 0;
12141 
12142 	switch (ptr_reg->type) {
12143 	case PTR_TO_STACK:
12144 		/* Offset 0 is out-of-bounds, but acceptable start for the
12145 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12146 		 * offset where we would need to deal with min/max bounds is
12147 		 * currently prohibited for unprivileged.
12148 		 */
12149 		max = MAX_BPF_STACK + mask_to_left;
12150 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12151 		break;
12152 	case PTR_TO_MAP_VALUE:
12153 		max = ptr_reg->map_ptr->value_size;
12154 		ptr_limit = (mask_to_left ?
12155 			     ptr_reg->smin_value :
12156 			     ptr_reg->umax_value) + ptr_reg->off;
12157 		break;
12158 	default:
12159 		return REASON_TYPE;
12160 	}
12161 
12162 	if (ptr_limit >= max)
12163 		return REASON_LIMIT;
12164 	*alu_limit = ptr_limit;
12165 	return 0;
12166 }
12167 
12168 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12169 				    const struct bpf_insn *insn)
12170 {
12171 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12172 }
12173 
12174 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12175 				       u32 alu_state, u32 alu_limit)
12176 {
12177 	/* If we arrived here from different branches with different
12178 	 * state or limits to sanitize, then this won't work.
12179 	 */
12180 	if (aux->alu_state &&
12181 	    (aux->alu_state != alu_state ||
12182 	     aux->alu_limit != alu_limit))
12183 		return REASON_PATHS;
12184 
12185 	/* Corresponding fixup done in do_misc_fixups(). */
12186 	aux->alu_state = alu_state;
12187 	aux->alu_limit = alu_limit;
12188 	return 0;
12189 }
12190 
12191 static int sanitize_val_alu(struct bpf_verifier_env *env,
12192 			    struct bpf_insn *insn)
12193 {
12194 	struct bpf_insn_aux_data *aux = cur_aux(env);
12195 
12196 	if (can_skip_alu_sanitation(env, insn))
12197 		return 0;
12198 
12199 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12200 }
12201 
12202 static bool sanitize_needed(u8 opcode)
12203 {
12204 	return opcode == BPF_ADD || opcode == BPF_SUB;
12205 }
12206 
12207 struct bpf_sanitize_info {
12208 	struct bpf_insn_aux_data aux;
12209 	bool mask_to_left;
12210 };
12211 
12212 static struct bpf_verifier_state *
12213 sanitize_speculative_path(struct bpf_verifier_env *env,
12214 			  const struct bpf_insn *insn,
12215 			  u32 next_idx, u32 curr_idx)
12216 {
12217 	struct bpf_verifier_state *branch;
12218 	struct bpf_reg_state *regs;
12219 
12220 	branch = push_stack(env, next_idx, curr_idx, true);
12221 	if (branch && insn) {
12222 		regs = branch->frame[branch->curframe]->regs;
12223 		if (BPF_SRC(insn->code) == BPF_K) {
12224 			mark_reg_unknown(env, regs, insn->dst_reg);
12225 		} else if (BPF_SRC(insn->code) == BPF_X) {
12226 			mark_reg_unknown(env, regs, insn->dst_reg);
12227 			mark_reg_unknown(env, regs, insn->src_reg);
12228 		}
12229 	}
12230 	return branch;
12231 }
12232 
12233 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12234 			    struct bpf_insn *insn,
12235 			    const struct bpf_reg_state *ptr_reg,
12236 			    const struct bpf_reg_state *off_reg,
12237 			    struct bpf_reg_state *dst_reg,
12238 			    struct bpf_sanitize_info *info,
12239 			    const bool commit_window)
12240 {
12241 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12242 	struct bpf_verifier_state *vstate = env->cur_state;
12243 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12244 	bool off_is_neg = off_reg->smin_value < 0;
12245 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12246 	u8 opcode = BPF_OP(insn->code);
12247 	u32 alu_state, alu_limit;
12248 	struct bpf_reg_state tmp;
12249 	bool ret;
12250 	int err;
12251 
12252 	if (can_skip_alu_sanitation(env, insn))
12253 		return 0;
12254 
12255 	/* We already marked aux for masking from non-speculative
12256 	 * paths, thus we got here in the first place. We only care
12257 	 * to explore bad access from here.
12258 	 */
12259 	if (vstate->speculative)
12260 		goto do_sim;
12261 
12262 	if (!commit_window) {
12263 		if (!tnum_is_const(off_reg->var_off) &&
12264 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12265 			return REASON_BOUNDS;
12266 
12267 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12268 				     (opcode == BPF_SUB && !off_is_neg);
12269 	}
12270 
12271 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12272 	if (err < 0)
12273 		return err;
12274 
12275 	if (commit_window) {
12276 		/* In commit phase we narrow the masking window based on
12277 		 * the observed pointer move after the simulated operation.
12278 		 */
12279 		alu_state = info->aux.alu_state;
12280 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12281 	} else {
12282 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12283 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12284 		alu_state |= ptr_is_dst_reg ?
12285 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12286 
12287 		/* Limit pruning on unknown scalars to enable deep search for
12288 		 * potential masking differences from other program paths.
12289 		 */
12290 		if (!off_is_imm)
12291 			env->explore_alu_limits = true;
12292 	}
12293 
12294 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12295 	if (err < 0)
12296 		return err;
12297 do_sim:
12298 	/* If we're in commit phase, we're done here given we already
12299 	 * pushed the truncated dst_reg into the speculative verification
12300 	 * stack.
12301 	 *
12302 	 * Also, when register is a known constant, we rewrite register-based
12303 	 * operation to immediate-based, and thus do not need masking (and as
12304 	 * a consequence, do not need to simulate the zero-truncation either).
12305 	 */
12306 	if (commit_window || off_is_imm)
12307 		return 0;
12308 
12309 	/* Simulate and find potential out-of-bounds access under
12310 	 * speculative execution from truncation as a result of
12311 	 * masking when off was not within expected range. If off
12312 	 * sits in dst, then we temporarily need to move ptr there
12313 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12314 	 * for cases where we use K-based arithmetic in one direction
12315 	 * and truncated reg-based in the other in order to explore
12316 	 * bad access.
12317 	 */
12318 	if (!ptr_is_dst_reg) {
12319 		tmp = *dst_reg;
12320 		copy_register_state(dst_reg, ptr_reg);
12321 	}
12322 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12323 					env->insn_idx);
12324 	if (!ptr_is_dst_reg && ret)
12325 		*dst_reg = tmp;
12326 	return !ret ? REASON_STACK : 0;
12327 }
12328 
12329 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12330 {
12331 	struct bpf_verifier_state *vstate = env->cur_state;
12332 
12333 	/* If we simulate paths under speculation, we don't update the
12334 	 * insn as 'seen' such that when we verify unreachable paths in
12335 	 * the non-speculative domain, sanitize_dead_code() can still
12336 	 * rewrite/sanitize them.
12337 	 */
12338 	if (!vstate->speculative)
12339 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12340 }
12341 
12342 static int sanitize_err(struct bpf_verifier_env *env,
12343 			const struct bpf_insn *insn, int reason,
12344 			const struct bpf_reg_state *off_reg,
12345 			const struct bpf_reg_state *dst_reg)
12346 {
12347 	static const char *err = "pointer arithmetic with it prohibited for !root";
12348 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12349 	u32 dst = insn->dst_reg, src = insn->src_reg;
12350 
12351 	switch (reason) {
12352 	case REASON_BOUNDS:
12353 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12354 			off_reg == dst_reg ? dst : src, err);
12355 		break;
12356 	case REASON_TYPE:
12357 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12358 			off_reg == dst_reg ? src : dst, err);
12359 		break;
12360 	case REASON_PATHS:
12361 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12362 			dst, op, err);
12363 		break;
12364 	case REASON_LIMIT:
12365 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12366 			dst, op, err);
12367 		break;
12368 	case REASON_STACK:
12369 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12370 			dst, err);
12371 		break;
12372 	default:
12373 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12374 			reason);
12375 		break;
12376 	}
12377 
12378 	return -EACCES;
12379 }
12380 
12381 /* check that stack access falls within stack limits and that 'reg' doesn't
12382  * have a variable offset.
12383  *
12384  * Variable offset is prohibited for unprivileged mode for simplicity since it
12385  * requires corresponding support in Spectre masking for stack ALU.  See also
12386  * retrieve_ptr_limit().
12387  *
12388  *
12389  * 'off' includes 'reg->off'.
12390  */
12391 static int check_stack_access_for_ptr_arithmetic(
12392 				struct bpf_verifier_env *env,
12393 				int regno,
12394 				const struct bpf_reg_state *reg,
12395 				int off)
12396 {
12397 	if (!tnum_is_const(reg->var_off)) {
12398 		char tn_buf[48];
12399 
12400 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12401 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12402 			regno, tn_buf, off);
12403 		return -EACCES;
12404 	}
12405 
12406 	if (off >= 0 || off < -MAX_BPF_STACK) {
12407 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12408 			"prohibited for !root; off=%d\n", regno, off);
12409 		return -EACCES;
12410 	}
12411 
12412 	return 0;
12413 }
12414 
12415 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12416 				 const struct bpf_insn *insn,
12417 				 const struct bpf_reg_state *dst_reg)
12418 {
12419 	u32 dst = insn->dst_reg;
12420 
12421 	/* For unprivileged we require that resulting offset must be in bounds
12422 	 * in order to be able to sanitize access later on.
12423 	 */
12424 	if (env->bypass_spec_v1)
12425 		return 0;
12426 
12427 	switch (dst_reg->type) {
12428 	case PTR_TO_STACK:
12429 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12430 					dst_reg->off + dst_reg->var_off.value))
12431 			return -EACCES;
12432 		break;
12433 	case PTR_TO_MAP_VALUE:
12434 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12435 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12436 				"prohibited for !root\n", dst);
12437 			return -EACCES;
12438 		}
12439 		break;
12440 	default:
12441 		break;
12442 	}
12443 
12444 	return 0;
12445 }
12446 
12447 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12448  * Caller should also handle BPF_MOV case separately.
12449  * If we return -EACCES, caller may want to try again treating pointer as a
12450  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12451  */
12452 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12453 				   struct bpf_insn *insn,
12454 				   const struct bpf_reg_state *ptr_reg,
12455 				   const struct bpf_reg_state *off_reg)
12456 {
12457 	struct bpf_verifier_state *vstate = env->cur_state;
12458 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12459 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12460 	bool known = tnum_is_const(off_reg->var_off);
12461 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12462 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12463 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12464 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12465 	struct bpf_sanitize_info info = {};
12466 	u8 opcode = BPF_OP(insn->code);
12467 	u32 dst = insn->dst_reg;
12468 	int ret;
12469 
12470 	dst_reg = &regs[dst];
12471 
12472 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12473 	    smin_val > smax_val || umin_val > umax_val) {
12474 		/* Taint dst register if offset had invalid bounds derived from
12475 		 * e.g. dead branches.
12476 		 */
12477 		__mark_reg_unknown(env, dst_reg);
12478 		return 0;
12479 	}
12480 
12481 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12482 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12483 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12484 			__mark_reg_unknown(env, dst_reg);
12485 			return 0;
12486 		}
12487 
12488 		verbose(env,
12489 			"R%d 32-bit pointer arithmetic prohibited\n",
12490 			dst);
12491 		return -EACCES;
12492 	}
12493 
12494 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12495 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12496 			dst, reg_type_str(env, ptr_reg->type));
12497 		return -EACCES;
12498 	}
12499 
12500 	switch (base_type(ptr_reg->type)) {
12501 	case PTR_TO_FLOW_KEYS:
12502 		if (known)
12503 			break;
12504 		fallthrough;
12505 	case CONST_PTR_TO_MAP:
12506 		/* smin_val represents the known value */
12507 		if (known && smin_val == 0 && opcode == BPF_ADD)
12508 			break;
12509 		fallthrough;
12510 	case PTR_TO_PACKET_END:
12511 	case PTR_TO_SOCKET:
12512 	case PTR_TO_SOCK_COMMON:
12513 	case PTR_TO_TCP_SOCK:
12514 	case PTR_TO_XDP_SOCK:
12515 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12516 			dst, reg_type_str(env, ptr_reg->type));
12517 		return -EACCES;
12518 	default:
12519 		break;
12520 	}
12521 
12522 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12523 	 * The id may be overwritten later if we create a new variable offset.
12524 	 */
12525 	dst_reg->type = ptr_reg->type;
12526 	dst_reg->id = ptr_reg->id;
12527 
12528 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12529 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12530 		return -EINVAL;
12531 
12532 	/* pointer types do not carry 32-bit bounds at the moment. */
12533 	__mark_reg32_unbounded(dst_reg);
12534 
12535 	if (sanitize_needed(opcode)) {
12536 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12537 				       &info, false);
12538 		if (ret < 0)
12539 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12540 	}
12541 
12542 	switch (opcode) {
12543 	case BPF_ADD:
12544 		/* We can take a fixed offset as long as it doesn't overflow
12545 		 * the s32 'off' field
12546 		 */
12547 		if (known && (ptr_reg->off + smin_val ==
12548 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12549 			/* pointer += K.  Accumulate it into fixed offset */
12550 			dst_reg->smin_value = smin_ptr;
12551 			dst_reg->smax_value = smax_ptr;
12552 			dst_reg->umin_value = umin_ptr;
12553 			dst_reg->umax_value = umax_ptr;
12554 			dst_reg->var_off = ptr_reg->var_off;
12555 			dst_reg->off = ptr_reg->off + smin_val;
12556 			dst_reg->raw = ptr_reg->raw;
12557 			break;
12558 		}
12559 		/* A new variable offset is created.  Note that off_reg->off
12560 		 * == 0, since it's a scalar.
12561 		 * dst_reg gets the pointer type and since some positive
12562 		 * integer value was added to the pointer, give it a new 'id'
12563 		 * if it's a PTR_TO_PACKET.
12564 		 * this creates a new 'base' pointer, off_reg (variable) gets
12565 		 * added into the variable offset, and we copy the fixed offset
12566 		 * from ptr_reg.
12567 		 */
12568 		if (signed_add_overflows(smin_ptr, smin_val) ||
12569 		    signed_add_overflows(smax_ptr, smax_val)) {
12570 			dst_reg->smin_value = S64_MIN;
12571 			dst_reg->smax_value = S64_MAX;
12572 		} else {
12573 			dst_reg->smin_value = smin_ptr + smin_val;
12574 			dst_reg->smax_value = smax_ptr + smax_val;
12575 		}
12576 		if (umin_ptr + umin_val < umin_ptr ||
12577 		    umax_ptr + umax_val < umax_ptr) {
12578 			dst_reg->umin_value = 0;
12579 			dst_reg->umax_value = U64_MAX;
12580 		} else {
12581 			dst_reg->umin_value = umin_ptr + umin_val;
12582 			dst_reg->umax_value = umax_ptr + umax_val;
12583 		}
12584 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12585 		dst_reg->off = ptr_reg->off;
12586 		dst_reg->raw = ptr_reg->raw;
12587 		if (reg_is_pkt_pointer(ptr_reg)) {
12588 			dst_reg->id = ++env->id_gen;
12589 			/* something was added to pkt_ptr, set range to zero */
12590 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12591 		}
12592 		break;
12593 	case BPF_SUB:
12594 		if (dst_reg == off_reg) {
12595 			/* scalar -= pointer.  Creates an unknown scalar */
12596 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12597 				dst);
12598 			return -EACCES;
12599 		}
12600 		/* We don't allow subtraction from FP, because (according to
12601 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12602 		 * be able to deal with it.
12603 		 */
12604 		if (ptr_reg->type == PTR_TO_STACK) {
12605 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12606 				dst);
12607 			return -EACCES;
12608 		}
12609 		if (known && (ptr_reg->off - smin_val ==
12610 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12611 			/* pointer -= K.  Subtract it from fixed offset */
12612 			dst_reg->smin_value = smin_ptr;
12613 			dst_reg->smax_value = smax_ptr;
12614 			dst_reg->umin_value = umin_ptr;
12615 			dst_reg->umax_value = umax_ptr;
12616 			dst_reg->var_off = ptr_reg->var_off;
12617 			dst_reg->id = ptr_reg->id;
12618 			dst_reg->off = ptr_reg->off - smin_val;
12619 			dst_reg->raw = ptr_reg->raw;
12620 			break;
12621 		}
12622 		/* A new variable offset is created.  If the subtrahend is known
12623 		 * nonnegative, then any reg->range we had before is still good.
12624 		 */
12625 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12626 		    signed_sub_overflows(smax_ptr, smin_val)) {
12627 			/* Overflow possible, we know nothing */
12628 			dst_reg->smin_value = S64_MIN;
12629 			dst_reg->smax_value = S64_MAX;
12630 		} else {
12631 			dst_reg->smin_value = smin_ptr - smax_val;
12632 			dst_reg->smax_value = smax_ptr - smin_val;
12633 		}
12634 		if (umin_ptr < umax_val) {
12635 			/* Overflow possible, we know nothing */
12636 			dst_reg->umin_value = 0;
12637 			dst_reg->umax_value = U64_MAX;
12638 		} else {
12639 			/* Cannot overflow (as long as bounds are consistent) */
12640 			dst_reg->umin_value = umin_ptr - umax_val;
12641 			dst_reg->umax_value = umax_ptr - umin_val;
12642 		}
12643 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12644 		dst_reg->off = ptr_reg->off;
12645 		dst_reg->raw = ptr_reg->raw;
12646 		if (reg_is_pkt_pointer(ptr_reg)) {
12647 			dst_reg->id = ++env->id_gen;
12648 			/* something was added to pkt_ptr, set range to zero */
12649 			if (smin_val < 0)
12650 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12651 		}
12652 		break;
12653 	case BPF_AND:
12654 	case BPF_OR:
12655 	case BPF_XOR:
12656 		/* bitwise ops on pointers are troublesome, prohibit. */
12657 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12658 			dst, bpf_alu_string[opcode >> 4]);
12659 		return -EACCES;
12660 	default:
12661 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12662 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12663 			dst, bpf_alu_string[opcode >> 4]);
12664 		return -EACCES;
12665 	}
12666 
12667 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12668 		return -EINVAL;
12669 	reg_bounds_sync(dst_reg);
12670 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12671 		return -EACCES;
12672 	if (sanitize_needed(opcode)) {
12673 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12674 				       &info, true);
12675 		if (ret < 0)
12676 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12677 	}
12678 
12679 	return 0;
12680 }
12681 
12682 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12683 				 struct bpf_reg_state *src_reg)
12684 {
12685 	s32 smin_val = src_reg->s32_min_value;
12686 	s32 smax_val = src_reg->s32_max_value;
12687 	u32 umin_val = src_reg->u32_min_value;
12688 	u32 umax_val = src_reg->u32_max_value;
12689 
12690 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12691 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12692 		dst_reg->s32_min_value = S32_MIN;
12693 		dst_reg->s32_max_value = S32_MAX;
12694 	} else {
12695 		dst_reg->s32_min_value += smin_val;
12696 		dst_reg->s32_max_value += smax_val;
12697 	}
12698 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12699 	    dst_reg->u32_max_value + umax_val < umax_val) {
12700 		dst_reg->u32_min_value = 0;
12701 		dst_reg->u32_max_value = U32_MAX;
12702 	} else {
12703 		dst_reg->u32_min_value += umin_val;
12704 		dst_reg->u32_max_value += umax_val;
12705 	}
12706 }
12707 
12708 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12709 			       struct bpf_reg_state *src_reg)
12710 {
12711 	s64 smin_val = src_reg->smin_value;
12712 	s64 smax_val = src_reg->smax_value;
12713 	u64 umin_val = src_reg->umin_value;
12714 	u64 umax_val = src_reg->umax_value;
12715 
12716 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12717 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12718 		dst_reg->smin_value = S64_MIN;
12719 		dst_reg->smax_value = S64_MAX;
12720 	} else {
12721 		dst_reg->smin_value += smin_val;
12722 		dst_reg->smax_value += smax_val;
12723 	}
12724 	if (dst_reg->umin_value + umin_val < umin_val ||
12725 	    dst_reg->umax_value + umax_val < umax_val) {
12726 		dst_reg->umin_value = 0;
12727 		dst_reg->umax_value = U64_MAX;
12728 	} else {
12729 		dst_reg->umin_value += umin_val;
12730 		dst_reg->umax_value += umax_val;
12731 	}
12732 }
12733 
12734 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12735 				 struct bpf_reg_state *src_reg)
12736 {
12737 	s32 smin_val = src_reg->s32_min_value;
12738 	s32 smax_val = src_reg->s32_max_value;
12739 	u32 umin_val = src_reg->u32_min_value;
12740 	u32 umax_val = src_reg->u32_max_value;
12741 
12742 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12743 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12744 		/* Overflow possible, we know nothing */
12745 		dst_reg->s32_min_value = S32_MIN;
12746 		dst_reg->s32_max_value = S32_MAX;
12747 	} else {
12748 		dst_reg->s32_min_value -= smax_val;
12749 		dst_reg->s32_max_value -= smin_val;
12750 	}
12751 	if (dst_reg->u32_min_value < umax_val) {
12752 		/* Overflow possible, we know nothing */
12753 		dst_reg->u32_min_value = 0;
12754 		dst_reg->u32_max_value = U32_MAX;
12755 	} else {
12756 		/* Cannot overflow (as long as bounds are consistent) */
12757 		dst_reg->u32_min_value -= umax_val;
12758 		dst_reg->u32_max_value -= umin_val;
12759 	}
12760 }
12761 
12762 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12763 			       struct bpf_reg_state *src_reg)
12764 {
12765 	s64 smin_val = src_reg->smin_value;
12766 	s64 smax_val = src_reg->smax_value;
12767 	u64 umin_val = src_reg->umin_value;
12768 	u64 umax_val = src_reg->umax_value;
12769 
12770 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12771 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12772 		/* Overflow possible, we know nothing */
12773 		dst_reg->smin_value = S64_MIN;
12774 		dst_reg->smax_value = S64_MAX;
12775 	} else {
12776 		dst_reg->smin_value -= smax_val;
12777 		dst_reg->smax_value -= smin_val;
12778 	}
12779 	if (dst_reg->umin_value < umax_val) {
12780 		/* Overflow possible, we know nothing */
12781 		dst_reg->umin_value = 0;
12782 		dst_reg->umax_value = U64_MAX;
12783 	} else {
12784 		/* Cannot overflow (as long as bounds are consistent) */
12785 		dst_reg->umin_value -= umax_val;
12786 		dst_reg->umax_value -= umin_val;
12787 	}
12788 }
12789 
12790 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12791 				 struct bpf_reg_state *src_reg)
12792 {
12793 	s32 smin_val = src_reg->s32_min_value;
12794 	u32 umin_val = src_reg->u32_min_value;
12795 	u32 umax_val = src_reg->u32_max_value;
12796 
12797 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12798 		/* Ain't nobody got time to multiply that sign */
12799 		__mark_reg32_unbounded(dst_reg);
12800 		return;
12801 	}
12802 	/* Both values are positive, so we can work with unsigned and
12803 	 * copy the result to signed (unless it exceeds S32_MAX).
12804 	 */
12805 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12806 		/* Potential overflow, we know nothing */
12807 		__mark_reg32_unbounded(dst_reg);
12808 		return;
12809 	}
12810 	dst_reg->u32_min_value *= umin_val;
12811 	dst_reg->u32_max_value *= umax_val;
12812 	if (dst_reg->u32_max_value > S32_MAX) {
12813 		/* Overflow possible, we know nothing */
12814 		dst_reg->s32_min_value = S32_MIN;
12815 		dst_reg->s32_max_value = S32_MAX;
12816 	} else {
12817 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12818 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12819 	}
12820 }
12821 
12822 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12823 			       struct bpf_reg_state *src_reg)
12824 {
12825 	s64 smin_val = src_reg->smin_value;
12826 	u64 umin_val = src_reg->umin_value;
12827 	u64 umax_val = src_reg->umax_value;
12828 
12829 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12830 		/* Ain't nobody got time to multiply that sign */
12831 		__mark_reg64_unbounded(dst_reg);
12832 		return;
12833 	}
12834 	/* Both values are positive, so we can work with unsigned and
12835 	 * copy the result to signed (unless it exceeds S64_MAX).
12836 	 */
12837 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12838 		/* Potential overflow, we know nothing */
12839 		__mark_reg64_unbounded(dst_reg);
12840 		return;
12841 	}
12842 	dst_reg->umin_value *= umin_val;
12843 	dst_reg->umax_value *= umax_val;
12844 	if (dst_reg->umax_value > S64_MAX) {
12845 		/* Overflow possible, we know nothing */
12846 		dst_reg->smin_value = S64_MIN;
12847 		dst_reg->smax_value = S64_MAX;
12848 	} else {
12849 		dst_reg->smin_value = dst_reg->umin_value;
12850 		dst_reg->smax_value = dst_reg->umax_value;
12851 	}
12852 }
12853 
12854 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12855 				 struct bpf_reg_state *src_reg)
12856 {
12857 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12858 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12859 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12860 	s32 smin_val = src_reg->s32_min_value;
12861 	u32 umax_val = src_reg->u32_max_value;
12862 
12863 	if (src_known && dst_known) {
12864 		__mark_reg32_known(dst_reg, var32_off.value);
12865 		return;
12866 	}
12867 
12868 	/* We get our minimum from the var_off, since that's inherently
12869 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12870 	 */
12871 	dst_reg->u32_min_value = var32_off.value;
12872 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12873 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12874 		/* Lose signed bounds when ANDing negative numbers,
12875 		 * ain't nobody got time for that.
12876 		 */
12877 		dst_reg->s32_min_value = S32_MIN;
12878 		dst_reg->s32_max_value = S32_MAX;
12879 	} else {
12880 		/* ANDing two positives gives a positive, so safe to
12881 		 * cast result into s64.
12882 		 */
12883 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12884 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12885 	}
12886 }
12887 
12888 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12889 			       struct bpf_reg_state *src_reg)
12890 {
12891 	bool src_known = tnum_is_const(src_reg->var_off);
12892 	bool dst_known = tnum_is_const(dst_reg->var_off);
12893 	s64 smin_val = src_reg->smin_value;
12894 	u64 umax_val = src_reg->umax_value;
12895 
12896 	if (src_known && dst_known) {
12897 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12898 		return;
12899 	}
12900 
12901 	/* We get our minimum from the var_off, since that's inherently
12902 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12903 	 */
12904 	dst_reg->umin_value = dst_reg->var_off.value;
12905 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12906 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12907 		/* Lose signed bounds when ANDing negative numbers,
12908 		 * ain't nobody got time for that.
12909 		 */
12910 		dst_reg->smin_value = S64_MIN;
12911 		dst_reg->smax_value = S64_MAX;
12912 	} else {
12913 		/* ANDing two positives gives a positive, so safe to
12914 		 * cast result into s64.
12915 		 */
12916 		dst_reg->smin_value = dst_reg->umin_value;
12917 		dst_reg->smax_value = dst_reg->umax_value;
12918 	}
12919 	/* We may learn something more from the var_off */
12920 	__update_reg_bounds(dst_reg);
12921 }
12922 
12923 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12924 				struct bpf_reg_state *src_reg)
12925 {
12926 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12927 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12928 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12929 	s32 smin_val = src_reg->s32_min_value;
12930 	u32 umin_val = src_reg->u32_min_value;
12931 
12932 	if (src_known && dst_known) {
12933 		__mark_reg32_known(dst_reg, var32_off.value);
12934 		return;
12935 	}
12936 
12937 	/* We get our maximum from the var_off, and our minimum is the
12938 	 * maximum of the operands' minima
12939 	 */
12940 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12941 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12942 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12943 		/* Lose signed bounds when ORing negative numbers,
12944 		 * ain't nobody got time for that.
12945 		 */
12946 		dst_reg->s32_min_value = S32_MIN;
12947 		dst_reg->s32_max_value = S32_MAX;
12948 	} else {
12949 		/* ORing two positives gives a positive, so safe to
12950 		 * cast result into s64.
12951 		 */
12952 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12953 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12954 	}
12955 }
12956 
12957 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12958 			      struct bpf_reg_state *src_reg)
12959 {
12960 	bool src_known = tnum_is_const(src_reg->var_off);
12961 	bool dst_known = tnum_is_const(dst_reg->var_off);
12962 	s64 smin_val = src_reg->smin_value;
12963 	u64 umin_val = src_reg->umin_value;
12964 
12965 	if (src_known && dst_known) {
12966 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12967 		return;
12968 	}
12969 
12970 	/* We get our maximum from the var_off, and our minimum is the
12971 	 * maximum of the operands' minima
12972 	 */
12973 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12974 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12975 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12976 		/* Lose signed bounds when ORing negative numbers,
12977 		 * ain't nobody got time for that.
12978 		 */
12979 		dst_reg->smin_value = S64_MIN;
12980 		dst_reg->smax_value = S64_MAX;
12981 	} else {
12982 		/* ORing two positives gives a positive, so safe to
12983 		 * cast result into s64.
12984 		 */
12985 		dst_reg->smin_value = dst_reg->umin_value;
12986 		dst_reg->smax_value = dst_reg->umax_value;
12987 	}
12988 	/* We may learn something more from the var_off */
12989 	__update_reg_bounds(dst_reg);
12990 }
12991 
12992 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12993 				 struct bpf_reg_state *src_reg)
12994 {
12995 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12996 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12997 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12998 	s32 smin_val = src_reg->s32_min_value;
12999 
13000 	if (src_known && dst_known) {
13001 		__mark_reg32_known(dst_reg, var32_off.value);
13002 		return;
13003 	}
13004 
13005 	/* We get both minimum and maximum from the var32_off. */
13006 	dst_reg->u32_min_value = var32_off.value;
13007 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13008 
13009 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13010 		/* XORing two positive sign numbers gives a positive,
13011 		 * so safe to cast u32 result into s32.
13012 		 */
13013 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13014 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13015 	} else {
13016 		dst_reg->s32_min_value = S32_MIN;
13017 		dst_reg->s32_max_value = S32_MAX;
13018 	}
13019 }
13020 
13021 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13022 			       struct bpf_reg_state *src_reg)
13023 {
13024 	bool src_known = tnum_is_const(src_reg->var_off);
13025 	bool dst_known = tnum_is_const(dst_reg->var_off);
13026 	s64 smin_val = src_reg->smin_value;
13027 
13028 	if (src_known && dst_known) {
13029 		/* dst_reg->var_off.value has been updated earlier */
13030 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13031 		return;
13032 	}
13033 
13034 	/* We get both minimum and maximum from the var_off. */
13035 	dst_reg->umin_value = dst_reg->var_off.value;
13036 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13037 
13038 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13039 		/* XORing two positive sign numbers gives a positive,
13040 		 * so safe to cast u64 result into s64.
13041 		 */
13042 		dst_reg->smin_value = dst_reg->umin_value;
13043 		dst_reg->smax_value = dst_reg->umax_value;
13044 	} else {
13045 		dst_reg->smin_value = S64_MIN;
13046 		dst_reg->smax_value = S64_MAX;
13047 	}
13048 
13049 	__update_reg_bounds(dst_reg);
13050 }
13051 
13052 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13053 				   u64 umin_val, u64 umax_val)
13054 {
13055 	/* We lose all sign bit information (except what we can pick
13056 	 * up from var_off)
13057 	 */
13058 	dst_reg->s32_min_value = S32_MIN;
13059 	dst_reg->s32_max_value = S32_MAX;
13060 	/* If we might shift our top bit out, then we know nothing */
13061 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13062 		dst_reg->u32_min_value = 0;
13063 		dst_reg->u32_max_value = U32_MAX;
13064 	} else {
13065 		dst_reg->u32_min_value <<= umin_val;
13066 		dst_reg->u32_max_value <<= umax_val;
13067 	}
13068 }
13069 
13070 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13071 				 struct bpf_reg_state *src_reg)
13072 {
13073 	u32 umax_val = src_reg->u32_max_value;
13074 	u32 umin_val = src_reg->u32_min_value;
13075 	/* u32 alu operation will zext upper bits */
13076 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13077 
13078 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13079 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13080 	/* Not required but being careful mark reg64 bounds as unknown so
13081 	 * that we are forced to pick them up from tnum and zext later and
13082 	 * if some path skips this step we are still safe.
13083 	 */
13084 	__mark_reg64_unbounded(dst_reg);
13085 	__update_reg32_bounds(dst_reg);
13086 }
13087 
13088 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13089 				   u64 umin_val, u64 umax_val)
13090 {
13091 	/* Special case <<32 because it is a common compiler pattern to sign
13092 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13093 	 * positive we know this shift will also be positive so we can track
13094 	 * bounds correctly. Otherwise we lose all sign bit information except
13095 	 * what we can pick up from var_off. Perhaps we can generalize this
13096 	 * later to shifts of any length.
13097 	 */
13098 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13099 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13100 	else
13101 		dst_reg->smax_value = S64_MAX;
13102 
13103 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13104 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13105 	else
13106 		dst_reg->smin_value = S64_MIN;
13107 
13108 	/* If we might shift our top bit out, then we know nothing */
13109 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13110 		dst_reg->umin_value = 0;
13111 		dst_reg->umax_value = U64_MAX;
13112 	} else {
13113 		dst_reg->umin_value <<= umin_val;
13114 		dst_reg->umax_value <<= umax_val;
13115 	}
13116 }
13117 
13118 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13119 			       struct bpf_reg_state *src_reg)
13120 {
13121 	u64 umax_val = src_reg->umax_value;
13122 	u64 umin_val = src_reg->umin_value;
13123 
13124 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13125 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13126 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13127 
13128 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13129 	/* We may learn something more from the var_off */
13130 	__update_reg_bounds(dst_reg);
13131 }
13132 
13133 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13134 				 struct bpf_reg_state *src_reg)
13135 {
13136 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13137 	u32 umax_val = src_reg->u32_max_value;
13138 	u32 umin_val = src_reg->u32_min_value;
13139 
13140 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13141 	 * be negative, then either:
13142 	 * 1) src_reg might be zero, so the sign bit of the result is
13143 	 *    unknown, so we lose our signed bounds
13144 	 * 2) it's known negative, thus the unsigned bounds capture the
13145 	 *    signed bounds
13146 	 * 3) the signed bounds cross zero, so they tell us nothing
13147 	 *    about the result
13148 	 * If the value in dst_reg is known nonnegative, then again the
13149 	 * unsigned bounds capture the signed bounds.
13150 	 * Thus, in all cases it suffices to blow away our signed bounds
13151 	 * and rely on inferring new ones from the unsigned bounds and
13152 	 * var_off of the result.
13153 	 */
13154 	dst_reg->s32_min_value = S32_MIN;
13155 	dst_reg->s32_max_value = S32_MAX;
13156 
13157 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13158 	dst_reg->u32_min_value >>= umax_val;
13159 	dst_reg->u32_max_value >>= umin_val;
13160 
13161 	__mark_reg64_unbounded(dst_reg);
13162 	__update_reg32_bounds(dst_reg);
13163 }
13164 
13165 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13166 			       struct bpf_reg_state *src_reg)
13167 {
13168 	u64 umax_val = src_reg->umax_value;
13169 	u64 umin_val = src_reg->umin_value;
13170 
13171 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13172 	 * be negative, then either:
13173 	 * 1) src_reg might be zero, so the sign bit of the result is
13174 	 *    unknown, so we lose our signed bounds
13175 	 * 2) it's known negative, thus the unsigned bounds capture the
13176 	 *    signed bounds
13177 	 * 3) the signed bounds cross zero, so they tell us nothing
13178 	 *    about the result
13179 	 * If the value in dst_reg is known nonnegative, then again the
13180 	 * unsigned bounds capture the signed bounds.
13181 	 * Thus, in all cases it suffices to blow away our signed bounds
13182 	 * and rely on inferring new ones from the unsigned bounds and
13183 	 * var_off of the result.
13184 	 */
13185 	dst_reg->smin_value = S64_MIN;
13186 	dst_reg->smax_value = S64_MAX;
13187 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13188 	dst_reg->umin_value >>= umax_val;
13189 	dst_reg->umax_value >>= umin_val;
13190 
13191 	/* Its not easy to operate on alu32 bounds here because it depends
13192 	 * on bits being shifted in. Take easy way out and mark unbounded
13193 	 * so we can recalculate later from tnum.
13194 	 */
13195 	__mark_reg32_unbounded(dst_reg);
13196 	__update_reg_bounds(dst_reg);
13197 }
13198 
13199 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13200 				  struct bpf_reg_state *src_reg)
13201 {
13202 	u64 umin_val = src_reg->u32_min_value;
13203 
13204 	/* Upon reaching here, src_known is true and
13205 	 * umax_val is equal to umin_val.
13206 	 */
13207 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13208 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13209 
13210 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13211 
13212 	/* blow away the dst_reg umin_value/umax_value and rely on
13213 	 * dst_reg var_off to refine the result.
13214 	 */
13215 	dst_reg->u32_min_value = 0;
13216 	dst_reg->u32_max_value = U32_MAX;
13217 
13218 	__mark_reg64_unbounded(dst_reg);
13219 	__update_reg32_bounds(dst_reg);
13220 }
13221 
13222 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13223 				struct bpf_reg_state *src_reg)
13224 {
13225 	u64 umin_val = src_reg->umin_value;
13226 
13227 	/* Upon reaching here, src_known is true and umax_val is equal
13228 	 * to umin_val.
13229 	 */
13230 	dst_reg->smin_value >>= umin_val;
13231 	dst_reg->smax_value >>= umin_val;
13232 
13233 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13234 
13235 	/* blow away the dst_reg umin_value/umax_value and rely on
13236 	 * dst_reg var_off to refine the result.
13237 	 */
13238 	dst_reg->umin_value = 0;
13239 	dst_reg->umax_value = U64_MAX;
13240 
13241 	/* Its not easy to operate on alu32 bounds here because it depends
13242 	 * on bits being shifted in from upper 32-bits. Take easy way out
13243 	 * and mark unbounded so we can recalculate later from tnum.
13244 	 */
13245 	__mark_reg32_unbounded(dst_reg);
13246 	__update_reg_bounds(dst_reg);
13247 }
13248 
13249 /* WARNING: This function does calculations on 64-bit values, but the actual
13250  * execution may occur on 32-bit values. Therefore, things like bitshifts
13251  * need extra checks in the 32-bit case.
13252  */
13253 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13254 				      struct bpf_insn *insn,
13255 				      struct bpf_reg_state *dst_reg,
13256 				      struct bpf_reg_state src_reg)
13257 {
13258 	struct bpf_reg_state *regs = cur_regs(env);
13259 	u8 opcode = BPF_OP(insn->code);
13260 	bool src_known;
13261 	s64 smin_val, smax_val;
13262 	u64 umin_val, umax_val;
13263 	s32 s32_min_val, s32_max_val;
13264 	u32 u32_min_val, u32_max_val;
13265 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13266 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13267 	int ret;
13268 
13269 	smin_val = src_reg.smin_value;
13270 	smax_val = src_reg.smax_value;
13271 	umin_val = src_reg.umin_value;
13272 	umax_val = src_reg.umax_value;
13273 
13274 	s32_min_val = src_reg.s32_min_value;
13275 	s32_max_val = src_reg.s32_max_value;
13276 	u32_min_val = src_reg.u32_min_value;
13277 	u32_max_val = src_reg.u32_max_value;
13278 
13279 	if (alu32) {
13280 		src_known = tnum_subreg_is_const(src_reg.var_off);
13281 		if ((src_known &&
13282 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13283 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13284 			/* Taint dst register if offset had invalid bounds
13285 			 * derived from e.g. dead branches.
13286 			 */
13287 			__mark_reg_unknown(env, dst_reg);
13288 			return 0;
13289 		}
13290 	} else {
13291 		src_known = tnum_is_const(src_reg.var_off);
13292 		if ((src_known &&
13293 		     (smin_val != smax_val || umin_val != umax_val)) ||
13294 		    smin_val > smax_val || umin_val > umax_val) {
13295 			/* Taint dst register if offset had invalid bounds
13296 			 * derived from e.g. dead branches.
13297 			 */
13298 			__mark_reg_unknown(env, dst_reg);
13299 			return 0;
13300 		}
13301 	}
13302 
13303 	if (!src_known &&
13304 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13305 		__mark_reg_unknown(env, dst_reg);
13306 		return 0;
13307 	}
13308 
13309 	if (sanitize_needed(opcode)) {
13310 		ret = sanitize_val_alu(env, insn);
13311 		if (ret < 0)
13312 			return sanitize_err(env, insn, ret, NULL, NULL);
13313 	}
13314 
13315 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13316 	 * There are two classes of instructions: The first class we track both
13317 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13318 	 * greatest amount of precision when alu operations are mixed with jmp32
13319 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13320 	 * and BPF_OR. This is possible because these ops have fairly easy to
13321 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13322 	 * See alu32 verifier tests for examples. The second class of
13323 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13324 	 * with regards to tracking sign/unsigned bounds because the bits may
13325 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13326 	 * the reg unbounded in the subreg bound space and use the resulting
13327 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13328 	 */
13329 	switch (opcode) {
13330 	case BPF_ADD:
13331 		scalar32_min_max_add(dst_reg, &src_reg);
13332 		scalar_min_max_add(dst_reg, &src_reg);
13333 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13334 		break;
13335 	case BPF_SUB:
13336 		scalar32_min_max_sub(dst_reg, &src_reg);
13337 		scalar_min_max_sub(dst_reg, &src_reg);
13338 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13339 		break;
13340 	case BPF_MUL:
13341 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13342 		scalar32_min_max_mul(dst_reg, &src_reg);
13343 		scalar_min_max_mul(dst_reg, &src_reg);
13344 		break;
13345 	case BPF_AND:
13346 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13347 		scalar32_min_max_and(dst_reg, &src_reg);
13348 		scalar_min_max_and(dst_reg, &src_reg);
13349 		break;
13350 	case BPF_OR:
13351 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13352 		scalar32_min_max_or(dst_reg, &src_reg);
13353 		scalar_min_max_or(dst_reg, &src_reg);
13354 		break;
13355 	case BPF_XOR:
13356 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13357 		scalar32_min_max_xor(dst_reg, &src_reg);
13358 		scalar_min_max_xor(dst_reg, &src_reg);
13359 		break;
13360 	case BPF_LSH:
13361 		if (umax_val >= insn_bitness) {
13362 			/* Shifts greater than 31 or 63 are undefined.
13363 			 * This includes shifts by a negative number.
13364 			 */
13365 			mark_reg_unknown(env, regs, insn->dst_reg);
13366 			break;
13367 		}
13368 		if (alu32)
13369 			scalar32_min_max_lsh(dst_reg, &src_reg);
13370 		else
13371 			scalar_min_max_lsh(dst_reg, &src_reg);
13372 		break;
13373 	case BPF_RSH:
13374 		if (umax_val >= insn_bitness) {
13375 			/* Shifts greater than 31 or 63 are undefined.
13376 			 * This includes shifts by a negative number.
13377 			 */
13378 			mark_reg_unknown(env, regs, insn->dst_reg);
13379 			break;
13380 		}
13381 		if (alu32)
13382 			scalar32_min_max_rsh(dst_reg, &src_reg);
13383 		else
13384 			scalar_min_max_rsh(dst_reg, &src_reg);
13385 		break;
13386 	case BPF_ARSH:
13387 		if (umax_val >= insn_bitness) {
13388 			/* Shifts greater than 31 or 63 are undefined.
13389 			 * This includes shifts by a negative number.
13390 			 */
13391 			mark_reg_unknown(env, regs, insn->dst_reg);
13392 			break;
13393 		}
13394 		if (alu32)
13395 			scalar32_min_max_arsh(dst_reg, &src_reg);
13396 		else
13397 			scalar_min_max_arsh(dst_reg, &src_reg);
13398 		break;
13399 	default:
13400 		mark_reg_unknown(env, regs, insn->dst_reg);
13401 		break;
13402 	}
13403 
13404 	/* ALU32 ops are zero extended into 64bit register */
13405 	if (alu32)
13406 		zext_32_to_64(dst_reg);
13407 	reg_bounds_sync(dst_reg);
13408 	return 0;
13409 }
13410 
13411 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13412  * and var_off.
13413  */
13414 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13415 				   struct bpf_insn *insn)
13416 {
13417 	struct bpf_verifier_state *vstate = env->cur_state;
13418 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13419 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13420 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13421 	u8 opcode = BPF_OP(insn->code);
13422 	int err;
13423 
13424 	dst_reg = &regs[insn->dst_reg];
13425 	src_reg = NULL;
13426 	if (dst_reg->type != SCALAR_VALUE)
13427 		ptr_reg = dst_reg;
13428 	else
13429 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13430 		 * incorrectly propagated into other registers by find_equal_scalars()
13431 		 */
13432 		dst_reg->id = 0;
13433 	if (BPF_SRC(insn->code) == BPF_X) {
13434 		src_reg = &regs[insn->src_reg];
13435 		if (src_reg->type != SCALAR_VALUE) {
13436 			if (dst_reg->type != SCALAR_VALUE) {
13437 				/* Combining two pointers by any ALU op yields
13438 				 * an arbitrary scalar. Disallow all math except
13439 				 * pointer subtraction
13440 				 */
13441 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13442 					mark_reg_unknown(env, regs, insn->dst_reg);
13443 					return 0;
13444 				}
13445 				verbose(env, "R%d pointer %s pointer prohibited\n",
13446 					insn->dst_reg,
13447 					bpf_alu_string[opcode >> 4]);
13448 				return -EACCES;
13449 			} else {
13450 				/* scalar += pointer
13451 				 * This is legal, but we have to reverse our
13452 				 * src/dest handling in computing the range
13453 				 */
13454 				err = mark_chain_precision(env, insn->dst_reg);
13455 				if (err)
13456 					return err;
13457 				return adjust_ptr_min_max_vals(env, insn,
13458 							       src_reg, dst_reg);
13459 			}
13460 		} else if (ptr_reg) {
13461 			/* pointer += scalar */
13462 			err = mark_chain_precision(env, insn->src_reg);
13463 			if (err)
13464 				return err;
13465 			return adjust_ptr_min_max_vals(env, insn,
13466 						       dst_reg, src_reg);
13467 		} else if (dst_reg->precise) {
13468 			/* if dst_reg is precise, src_reg should be precise as well */
13469 			err = mark_chain_precision(env, insn->src_reg);
13470 			if (err)
13471 				return err;
13472 		}
13473 	} else {
13474 		/* Pretend the src is a reg with a known value, since we only
13475 		 * need to be able to read from this state.
13476 		 */
13477 		off_reg.type = SCALAR_VALUE;
13478 		__mark_reg_known(&off_reg, insn->imm);
13479 		src_reg = &off_reg;
13480 		if (ptr_reg) /* pointer += K */
13481 			return adjust_ptr_min_max_vals(env, insn,
13482 						       ptr_reg, src_reg);
13483 	}
13484 
13485 	/* Got here implies adding two SCALAR_VALUEs */
13486 	if (WARN_ON_ONCE(ptr_reg)) {
13487 		print_verifier_state(env, state, true);
13488 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13489 		return -EINVAL;
13490 	}
13491 	if (WARN_ON(!src_reg)) {
13492 		print_verifier_state(env, state, true);
13493 		verbose(env, "verifier internal error: no src_reg\n");
13494 		return -EINVAL;
13495 	}
13496 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13497 }
13498 
13499 /* check validity of 32-bit and 64-bit arithmetic operations */
13500 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13501 {
13502 	struct bpf_reg_state *regs = cur_regs(env);
13503 	u8 opcode = BPF_OP(insn->code);
13504 	int err;
13505 
13506 	if (opcode == BPF_END || opcode == BPF_NEG) {
13507 		if (opcode == BPF_NEG) {
13508 			if (BPF_SRC(insn->code) != BPF_K ||
13509 			    insn->src_reg != BPF_REG_0 ||
13510 			    insn->off != 0 || insn->imm != 0) {
13511 				verbose(env, "BPF_NEG uses reserved fields\n");
13512 				return -EINVAL;
13513 			}
13514 		} else {
13515 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13516 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13517 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13518 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13519 				verbose(env, "BPF_END uses reserved fields\n");
13520 				return -EINVAL;
13521 			}
13522 		}
13523 
13524 		/* check src operand */
13525 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13526 		if (err)
13527 			return err;
13528 
13529 		if (is_pointer_value(env, insn->dst_reg)) {
13530 			verbose(env, "R%d pointer arithmetic prohibited\n",
13531 				insn->dst_reg);
13532 			return -EACCES;
13533 		}
13534 
13535 		/* check dest operand */
13536 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13537 		if (err)
13538 			return err;
13539 
13540 	} else if (opcode == BPF_MOV) {
13541 
13542 		if (BPF_SRC(insn->code) == BPF_X) {
13543 			if (insn->imm != 0) {
13544 				verbose(env, "BPF_MOV uses reserved fields\n");
13545 				return -EINVAL;
13546 			}
13547 
13548 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13549 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13550 					verbose(env, "BPF_MOV uses reserved fields\n");
13551 					return -EINVAL;
13552 				}
13553 			} else {
13554 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13555 				    insn->off != 32) {
13556 					verbose(env, "BPF_MOV uses reserved fields\n");
13557 					return -EINVAL;
13558 				}
13559 			}
13560 
13561 			/* check src operand */
13562 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13563 			if (err)
13564 				return err;
13565 		} else {
13566 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13567 				verbose(env, "BPF_MOV uses reserved fields\n");
13568 				return -EINVAL;
13569 			}
13570 		}
13571 
13572 		/* check dest operand, mark as required later */
13573 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13574 		if (err)
13575 			return err;
13576 
13577 		if (BPF_SRC(insn->code) == BPF_X) {
13578 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13579 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13580 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13581 				       !tnum_is_const(src_reg->var_off);
13582 
13583 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13584 				if (insn->off == 0) {
13585 					/* case: R1 = R2
13586 					 * copy register state to dest reg
13587 					 */
13588 					if (need_id)
13589 						/* Assign src and dst registers the same ID
13590 						 * that will be used by find_equal_scalars()
13591 						 * to propagate min/max range.
13592 						 */
13593 						src_reg->id = ++env->id_gen;
13594 					copy_register_state(dst_reg, src_reg);
13595 					dst_reg->live |= REG_LIVE_WRITTEN;
13596 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13597 				} else {
13598 					/* case: R1 = (s8, s16 s32)R2 */
13599 					if (is_pointer_value(env, insn->src_reg)) {
13600 						verbose(env,
13601 							"R%d sign-extension part of pointer\n",
13602 							insn->src_reg);
13603 						return -EACCES;
13604 					} else if (src_reg->type == SCALAR_VALUE) {
13605 						bool no_sext;
13606 
13607 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13608 						if (no_sext && need_id)
13609 							src_reg->id = ++env->id_gen;
13610 						copy_register_state(dst_reg, src_reg);
13611 						if (!no_sext)
13612 							dst_reg->id = 0;
13613 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13614 						dst_reg->live |= REG_LIVE_WRITTEN;
13615 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13616 					} else {
13617 						mark_reg_unknown(env, regs, insn->dst_reg);
13618 					}
13619 				}
13620 			} else {
13621 				/* R1 = (u32) R2 */
13622 				if (is_pointer_value(env, insn->src_reg)) {
13623 					verbose(env,
13624 						"R%d partial copy of pointer\n",
13625 						insn->src_reg);
13626 					return -EACCES;
13627 				} else if (src_reg->type == SCALAR_VALUE) {
13628 					if (insn->off == 0) {
13629 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13630 
13631 						if (is_src_reg_u32 && need_id)
13632 							src_reg->id = ++env->id_gen;
13633 						copy_register_state(dst_reg, src_reg);
13634 						/* Make sure ID is cleared if src_reg is not in u32
13635 						 * range otherwise dst_reg min/max could be incorrectly
13636 						 * propagated into src_reg by find_equal_scalars()
13637 						 */
13638 						if (!is_src_reg_u32)
13639 							dst_reg->id = 0;
13640 						dst_reg->live |= REG_LIVE_WRITTEN;
13641 						dst_reg->subreg_def = env->insn_idx + 1;
13642 					} else {
13643 						/* case: W1 = (s8, s16)W2 */
13644 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13645 
13646 						if (no_sext && need_id)
13647 							src_reg->id = ++env->id_gen;
13648 						copy_register_state(dst_reg, src_reg);
13649 						if (!no_sext)
13650 							dst_reg->id = 0;
13651 						dst_reg->live |= REG_LIVE_WRITTEN;
13652 						dst_reg->subreg_def = env->insn_idx + 1;
13653 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13654 					}
13655 				} else {
13656 					mark_reg_unknown(env, regs,
13657 							 insn->dst_reg);
13658 				}
13659 				zext_32_to_64(dst_reg);
13660 				reg_bounds_sync(dst_reg);
13661 			}
13662 		} else {
13663 			/* case: R = imm
13664 			 * remember the value we stored into this reg
13665 			 */
13666 			/* clear any state __mark_reg_known doesn't set */
13667 			mark_reg_unknown(env, regs, insn->dst_reg);
13668 			regs[insn->dst_reg].type = SCALAR_VALUE;
13669 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13670 				__mark_reg_known(regs + insn->dst_reg,
13671 						 insn->imm);
13672 			} else {
13673 				__mark_reg_known(regs + insn->dst_reg,
13674 						 (u32)insn->imm);
13675 			}
13676 		}
13677 
13678 	} else if (opcode > BPF_END) {
13679 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13680 		return -EINVAL;
13681 
13682 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13683 
13684 		if (BPF_SRC(insn->code) == BPF_X) {
13685 			if (insn->imm != 0 || insn->off > 1 ||
13686 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13687 				verbose(env, "BPF_ALU uses reserved fields\n");
13688 				return -EINVAL;
13689 			}
13690 			/* check src1 operand */
13691 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13692 			if (err)
13693 				return err;
13694 		} else {
13695 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13696 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13697 				verbose(env, "BPF_ALU uses reserved fields\n");
13698 				return -EINVAL;
13699 			}
13700 		}
13701 
13702 		/* check src2 operand */
13703 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13704 		if (err)
13705 			return err;
13706 
13707 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13708 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13709 			verbose(env, "div by zero\n");
13710 			return -EINVAL;
13711 		}
13712 
13713 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13714 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13715 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13716 
13717 			if (insn->imm < 0 || insn->imm >= size) {
13718 				verbose(env, "invalid shift %d\n", insn->imm);
13719 				return -EINVAL;
13720 			}
13721 		}
13722 
13723 		/* check dest operand */
13724 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13725 		if (err)
13726 			return err;
13727 
13728 		return adjust_reg_min_max_vals(env, insn);
13729 	}
13730 
13731 	return 0;
13732 }
13733 
13734 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13735 				   struct bpf_reg_state *dst_reg,
13736 				   enum bpf_reg_type type,
13737 				   bool range_right_open)
13738 {
13739 	struct bpf_func_state *state;
13740 	struct bpf_reg_state *reg;
13741 	int new_range;
13742 
13743 	if (dst_reg->off < 0 ||
13744 	    (dst_reg->off == 0 && range_right_open))
13745 		/* This doesn't give us any range */
13746 		return;
13747 
13748 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13749 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13750 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13751 		 * than pkt_end, but that's because it's also less than pkt.
13752 		 */
13753 		return;
13754 
13755 	new_range = dst_reg->off;
13756 	if (range_right_open)
13757 		new_range++;
13758 
13759 	/* Examples for register markings:
13760 	 *
13761 	 * pkt_data in dst register:
13762 	 *
13763 	 *   r2 = r3;
13764 	 *   r2 += 8;
13765 	 *   if (r2 > pkt_end) goto <handle exception>
13766 	 *   <access okay>
13767 	 *
13768 	 *   r2 = r3;
13769 	 *   r2 += 8;
13770 	 *   if (r2 < pkt_end) goto <access okay>
13771 	 *   <handle exception>
13772 	 *
13773 	 *   Where:
13774 	 *     r2 == dst_reg, pkt_end == src_reg
13775 	 *     r2=pkt(id=n,off=8,r=0)
13776 	 *     r3=pkt(id=n,off=0,r=0)
13777 	 *
13778 	 * pkt_data in src register:
13779 	 *
13780 	 *   r2 = r3;
13781 	 *   r2 += 8;
13782 	 *   if (pkt_end >= r2) goto <access okay>
13783 	 *   <handle exception>
13784 	 *
13785 	 *   r2 = r3;
13786 	 *   r2 += 8;
13787 	 *   if (pkt_end <= r2) goto <handle exception>
13788 	 *   <access okay>
13789 	 *
13790 	 *   Where:
13791 	 *     pkt_end == dst_reg, r2 == src_reg
13792 	 *     r2=pkt(id=n,off=8,r=0)
13793 	 *     r3=pkt(id=n,off=0,r=0)
13794 	 *
13795 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13796 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13797 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13798 	 * the check.
13799 	 */
13800 
13801 	/* If our ids match, then we must have the same max_value.  And we
13802 	 * don't care about the other reg's fixed offset, since if it's too big
13803 	 * the range won't allow anything.
13804 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13805 	 */
13806 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13807 		if (reg->type == type && reg->id == dst_reg->id)
13808 			/* keep the maximum range already checked */
13809 			reg->range = max(reg->range, new_range);
13810 	}));
13811 }
13812 
13813 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13814 {
13815 	struct tnum subreg = tnum_subreg(reg->var_off);
13816 	s32 sval = (s32)val;
13817 
13818 	switch (opcode) {
13819 	case BPF_JEQ:
13820 		if (tnum_is_const(subreg))
13821 			return !!tnum_equals_const(subreg, val);
13822 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13823 			return 0;
13824 		break;
13825 	case BPF_JNE:
13826 		if (tnum_is_const(subreg))
13827 			return !tnum_equals_const(subreg, val);
13828 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13829 			return 1;
13830 		break;
13831 	case BPF_JSET:
13832 		if ((~subreg.mask & subreg.value) & val)
13833 			return 1;
13834 		if (!((subreg.mask | subreg.value) & val))
13835 			return 0;
13836 		break;
13837 	case BPF_JGT:
13838 		if (reg->u32_min_value > val)
13839 			return 1;
13840 		else if (reg->u32_max_value <= val)
13841 			return 0;
13842 		break;
13843 	case BPF_JSGT:
13844 		if (reg->s32_min_value > sval)
13845 			return 1;
13846 		else if (reg->s32_max_value <= sval)
13847 			return 0;
13848 		break;
13849 	case BPF_JLT:
13850 		if (reg->u32_max_value < val)
13851 			return 1;
13852 		else if (reg->u32_min_value >= val)
13853 			return 0;
13854 		break;
13855 	case BPF_JSLT:
13856 		if (reg->s32_max_value < sval)
13857 			return 1;
13858 		else if (reg->s32_min_value >= sval)
13859 			return 0;
13860 		break;
13861 	case BPF_JGE:
13862 		if (reg->u32_min_value >= val)
13863 			return 1;
13864 		else if (reg->u32_max_value < val)
13865 			return 0;
13866 		break;
13867 	case BPF_JSGE:
13868 		if (reg->s32_min_value >= sval)
13869 			return 1;
13870 		else if (reg->s32_max_value < sval)
13871 			return 0;
13872 		break;
13873 	case BPF_JLE:
13874 		if (reg->u32_max_value <= val)
13875 			return 1;
13876 		else if (reg->u32_min_value > val)
13877 			return 0;
13878 		break;
13879 	case BPF_JSLE:
13880 		if (reg->s32_max_value <= sval)
13881 			return 1;
13882 		else if (reg->s32_min_value > sval)
13883 			return 0;
13884 		break;
13885 	}
13886 
13887 	return -1;
13888 }
13889 
13890 
13891 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13892 {
13893 	s64 sval = (s64)val;
13894 
13895 	switch (opcode) {
13896 	case BPF_JEQ:
13897 		if (tnum_is_const(reg->var_off))
13898 			return !!tnum_equals_const(reg->var_off, val);
13899 		else if (val < reg->umin_value || val > reg->umax_value)
13900 			return 0;
13901 		break;
13902 	case BPF_JNE:
13903 		if (tnum_is_const(reg->var_off))
13904 			return !tnum_equals_const(reg->var_off, val);
13905 		else if (val < reg->umin_value || val > reg->umax_value)
13906 			return 1;
13907 		break;
13908 	case BPF_JSET:
13909 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13910 			return 1;
13911 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13912 			return 0;
13913 		break;
13914 	case BPF_JGT:
13915 		if (reg->umin_value > val)
13916 			return 1;
13917 		else if (reg->umax_value <= val)
13918 			return 0;
13919 		break;
13920 	case BPF_JSGT:
13921 		if (reg->smin_value > sval)
13922 			return 1;
13923 		else if (reg->smax_value <= sval)
13924 			return 0;
13925 		break;
13926 	case BPF_JLT:
13927 		if (reg->umax_value < val)
13928 			return 1;
13929 		else if (reg->umin_value >= val)
13930 			return 0;
13931 		break;
13932 	case BPF_JSLT:
13933 		if (reg->smax_value < sval)
13934 			return 1;
13935 		else if (reg->smin_value >= sval)
13936 			return 0;
13937 		break;
13938 	case BPF_JGE:
13939 		if (reg->umin_value >= val)
13940 			return 1;
13941 		else if (reg->umax_value < val)
13942 			return 0;
13943 		break;
13944 	case BPF_JSGE:
13945 		if (reg->smin_value >= sval)
13946 			return 1;
13947 		else if (reg->smax_value < sval)
13948 			return 0;
13949 		break;
13950 	case BPF_JLE:
13951 		if (reg->umax_value <= val)
13952 			return 1;
13953 		else if (reg->umin_value > val)
13954 			return 0;
13955 		break;
13956 	case BPF_JSLE:
13957 		if (reg->smax_value <= sval)
13958 			return 1;
13959 		else if (reg->smin_value > sval)
13960 			return 0;
13961 		break;
13962 	}
13963 
13964 	return -1;
13965 }
13966 
13967 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13968  * and return:
13969  *  1 - branch will be taken and "goto target" will be executed
13970  *  0 - branch will not be taken and fall-through to next insn
13971  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13972  *      range [0,10]
13973  */
13974 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13975 			   bool is_jmp32)
13976 {
13977 	if (__is_pointer_value(false, reg)) {
13978 		if (!reg_not_null(reg))
13979 			return -1;
13980 
13981 		/* If pointer is valid tests against zero will fail so we can
13982 		 * use this to direct branch taken.
13983 		 */
13984 		if (val != 0)
13985 			return -1;
13986 
13987 		switch (opcode) {
13988 		case BPF_JEQ:
13989 			return 0;
13990 		case BPF_JNE:
13991 			return 1;
13992 		default:
13993 			return -1;
13994 		}
13995 	}
13996 
13997 	if (is_jmp32)
13998 		return is_branch32_taken(reg, val, opcode);
13999 	return is_branch64_taken(reg, val, opcode);
14000 }
14001 
14002 static int flip_opcode(u32 opcode)
14003 {
14004 	/* How can we transform "a <op> b" into "b <op> a"? */
14005 	static const u8 opcode_flip[16] = {
14006 		/* these stay the same */
14007 		[BPF_JEQ  >> 4] = BPF_JEQ,
14008 		[BPF_JNE  >> 4] = BPF_JNE,
14009 		[BPF_JSET >> 4] = BPF_JSET,
14010 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14011 		[BPF_JGE  >> 4] = BPF_JLE,
14012 		[BPF_JGT  >> 4] = BPF_JLT,
14013 		[BPF_JLE  >> 4] = BPF_JGE,
14014 		[BPF_JLT  >> 4] = BPF_JGT,
14015 		[BPF_JSGE >> 4] = BPF_JSLE,
14016 		[BPF_JSGT >> 4] = BPF_JSLT,
14017 		[BPF_JSLE >> 4] = BPF_JSGE,
14018 		[BPF_JSLT >> 4] = BPF_JSGT
14019 	};
14020 	return opcode_flip[opcode >> 4];
14021 }
14022 
14023 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14024 				   struct bpf_reg_state *src_reg,
14025 				   u8 opcode)
14026 {
14027 	struct bpf_reg_state *pkt;
14028 
14029 	if (src_reg->type == PTR_TO_PACKET_END) {
14030 		pkt = dst_reg;
14031 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14032 		pkt = src_reg;
14033 		opcode = flip_opcode(opcode);
14034 	} else {
14035 		return -1;
14036 	}
14037 
14038 	if (pkt->range >= 0)
14039 		return -1;
14040 
14041 	switch (opcode) {
14042 	case BPF_JLE:
14043 		/* pkt <= pkt_end */
14044 		fallthrough;
14045 	case BPF_JGT:
14046 		/* pkt > pkt_end */
14047 		if (pkt->range == BEYOND_PKT_END)
14048 			/* pkt has at last one extra byte beyond pkt_end */
14049 			return opcode == BPF_JGT;
14050 		break;
14051 	case BPF_JLT:
14052 		/* pkt < pkt_end */
14053 		fallthrough;
14054 	case BPF_JGE:
14055 		/* pkt >= pkt_end */
14056 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14057 			return opcode == BPF_JGE;
14058 		break;
14059 	}
14060 	return -1;
14061 }
14062 
14063 /* Adjusts the register min/max values in the case that the dst_reg is the
14064  * variable register that we are working on, and src_reg is a constant or we're
14065  * simply doing a BPF_K check.
14066  * In JEQ/JNE cases we also adjust the var_off values.
14067  */
14068 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14069 			    struct bpf_reg_state *false_reg,
14070 			    u64 val, u32 val32,
14071 			    u8 opcode, bool is_jmp32)
14072 {
14073 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14074 	struct tnum false_64off = false_reg->var_off;
14075 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14076 	struct tnum true_64off = true_reg->var_off;
14077 	s64 sval = (s64)val;
14078 	s32 sval32 = (s32)val32;
14079 
14080 	/* If the dst_reg is a pointer, we can't learn anything about its
14081 	 * variable offset from the compare (unless src_reg were a pointer into
14082 	 * the same object, but we don't bother with that.
14083 	 * Since false_reg and true_reg have the same type by construction, we
14084 	 * only need to check one of them for pointerness.
14085 	 */
14086 	if (__is_pointer_value(false, false_reg))
14087 		return;
14088 
14089 	switch (opcode) {
14090 	/* JEQ/JNE comparison doesn't change the register equivalence.
14091 	 *
14092 	 * r1 = r2;
14093 	 * if (r1 == 42) goto label;
14094 	 * ...
14095 	 * label: // here both r1 and r2 are known to be 42.
14096 	 *
14097 	 * Hence when marking register as known preserve it's ID.
14098 	 */
14099 	case BPF_JEQ:
14100 		if (is_jmp32) {
14101 			__mark_reg32_known(true_reg, val32);
14102 			true_32off = tnum_subreg(true_reg->var_off);
14103 		} else {
14104 			___mark_reg_known(true_reg, val);
14105 			true_64off = true_reg->var_off;
14106 		}
14107 		break;
14108 	case BPF_JNE:
14109 		if (is_jmp32) {
14110 			__mark_reg32_known(false_reg, val32);
14111 			false_32off = tnum_subreg(false_reg->var_off);
14112 		} else {
14113 			___mark_reg_known(false_reg, val);
14114 			false_64off = false_reg->var_off;
14115 		}
14116 		break;
14117 	case BPF_JSET:
14118 		if (is_jmp32) {
14119 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14120 			if (is_power_of_2(val32))
14121 				true_32off = tnum_or(true_32off,
14122 						     tnum_const(val32));
14123 		} else {
14124 			false_64off = tnum_and(false_64off, tnum_const(~val));
14125 			if (is_power_of_2(val))
14126 				true_64off = tnum_or(true_64off,
14127 						     tnum_const(val));
14128 		}
14129 		break;
14130 	case BPF_JGE:
14131 	case BPF_JGT:
14132 	{
14133 		if (is_jmp32) {
14134 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14135 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14136 
14137 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14138 						       false_umax);
14139 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14140 						      true_umin);
14141 		} else {
14142 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14143 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14144 
14145 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14146 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14147 		}
14148 		break;
14149 	}
14150 	case BPF_JSGE:
14151 	case BPF_JSGT:
14152 	{
14153 		if (is_jmp32) {
14154 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14155 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14156 
14157 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14158 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14159 		} else {
14160 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14161 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14162 
14163 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14164 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14165 		}
14166 		break;
14167 	}
14168 	case BPF_JLE:
14169 	case BPF_JLT:
14170 	{
14171 		if (is_jmp32) {
14172 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14173 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14174 
14175 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14176 						       false_umin);
14177 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14178 						      true_umax);
14179 		} else {
14180 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14181 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14182 
14183 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14184 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14185 		}
14186 		break;
14187 	}
14188 	case BPF_JSLE:
14189 	case BPF_JSLT:
14190 	{
14191 		if (is_jmp32) {
14192 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14193 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14194 
14195 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14196 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14197 		} else {
14198 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14199 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14200 
14201 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14202 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14203 		}
14204 		break;
14205 	}
14206 	default:
14207 		return;
14208 	}
14209 
14210 	if (is_jmp32) {
14211 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14212 					     tnum_subreg(false_32off));
14213 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14214 					    tnum_subreg(true_32off));
14215 		__reg_combine_32_into_64(false_reg);
14216 		__reg_combine_32_into_64(true_reg);
14217 	} else {
14218 		false_reg->var_off = false_64off;
14219 		true_reg->var_off = true_64off;
14220 		__reg_combine_64_into_32(false_reg);
14221 		__reg_combine_64_into_32(true_reg);
14222 	}
14223 }
14224 
14225 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14226  * the variable reg.
14227  */
14228 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14229 				struct bpf_reg_state *false_reg,
14230 				u64 val, u32 val32,
14231 				u8 opcode, bool is_jmp32)
14232 {
14233 	opcode = flip_opcode(opcode);
14234 	/* This uses zero as "not present in table"; luckily the zero opcode,
14235 	 * BPF_JA, can't get here.
14236 	 */
14237 	if (opcode)
14238 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14239 }
14240 
14241 /* Regs are known to be equal, so intersect their min/max/var_off */
14242 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14243 				  struct bpf_reg_state *dst_reg)
14244 {
14245 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14246 							dst_reg->umin_value);
14247 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14248 							dst_reg->umax_value);
14249 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14250 							dst_reg->smin_value);
14251 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14252 							dst_reg->smax_value);
14253 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14254 							     dst_reg->var_off);
14255 	reg_bounds_sync(src_reg);
14256 	reg_bounds_sync(dst_reg);
14257 }
14258 
14259 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14260 				struct bpf_reg_state *true_dst,
14261 				struct bpf_reg_state *false_src,
14262 				struct bpf_reg_state *false_dst,
14263 				u8 opcode)
14264 {
14265 	switch (opcode) {
14266 	case BPF_JEQ:
14267 		__reg_combine_min_max(true_src, true_dst);
14268 		break;
14269 	case BPF_JNE:
14270 		__reg_combine_min_max(false_src, false_dst);
14271 		break;
14272 	}
14273 }
14274 
14275 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14276 				 struct bpf_reg_state *reg, u32 id,
14277 				 bool is_null)
14278 {
14279 	if (type_may_be_null(reg->type) && reg->id == id &&
14280 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14281 		/* Old offset (both fixed and variable parts) should have been
14282 		 * known-zero, because we don't allow pointer arithmetic on
14283 		 * pointers that might be NULL. If we see this happening, don't
14284 		 * convert the register.
14285 		 *
14286 		 * But in some cases, some helpers that return local kptrs
14287 		 * advance offset for the returned pointer. In those cases, it
14288 		 * is fine to expect to see reg->off.
14289 		 */
14290 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14291 			return;
14292 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14293 		    WARN_ON_ONCE(reg->off))
14294 			return;
14295 
14296 		if (is_null) {
14297 			reg->type = SCALAR_VALUE;
14298 			/* We don't need id and ref_obj_id from this point
14299 			 * onwards anymore, thus we should better reset it,
14300 			 * so that state pruning has chances to take effect.
14301 			 */
14302 			reg->id = 0;
14303 			reg->ref_obj_id = 0;
14304 
14305 			return;
14306 		}
14307 
14308 		mark_ptr_not_null_reg(reg);
14309 
14310 		if (!reg_may_point_to_spin_lock(reg)) {
14311 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14312 			 * in release_reference().
14313 			 *
14314 			 * reg->id is still used by spin_lock ptr. Other
14315 			 * than spin_lock ptr type, reg->id can be reset.
14316 			 */
14317 			reg->id = 0;
14318 		}
14319 	}
14320 }
14321 
14322 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14323  * be folded together at some point.
14324  */
14325 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14326 				  bool is_null)
14327 {
14328 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14329 	struct bpf_reg_state *regs = state->regs, *reg;
14330 	u32 ref_obj_id = regs[regno].ref_obj_id;
14331 	u32 id = regs[regno].id;
14332 
14333 	if (ref_obj_id && ref_obj_id == id && is_null)
14334 		/* regs[regno] is in the " == NULL" branch.
14335 		 * No one could have freed the reference state before
14336 		 * doing the NULL check.
14337 		 */
14338 		WARN_ON_ONCE(release_reference_state(state, id));
14339 
14340 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14341 		mark_ptr_or_null_reg(state, reg, id, is_null);
14342 	}));
14343 }
14344 
14345 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14346 				   struct bpf_reg_state *dst_reg,
14347 				   struct bpf_reg_state *src_reg,
14348 				   struct bpf_verifier_state *this_branch,
14349 				   struct bpf_verifier_state *other_branch)
14350 {
14351 	if (BPF_SRC(insn->code) != BPF_X)
14352 		return false;
14353 
14354 	/* Pointers are always 64-bit. */
14355 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14356 		return false;
14357 
14358 	switch (BPF_OP(insn->code)) {
14359 	case BPF_JGT:
14360 		if ((dst_reg->type == PTR_TO_PACKET &&
14361 		     src_reg->type == PTR_TO_PACKET_END) ||
14362 		    (dst_reg->type == PTR_TO_PACKET_META &&
14363 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14364 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14365 			find_good_pkt_pointers(this_branch, dst_reg,
14366 					       dst_reg->type, false);
14367 			mark_pkt_end(other_branch, insn->dst_reg, true);
14368 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14369 			    src_reg->type == PTR_TO_PACKET) ||
14370 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14371 			    src_reg->type == PTR_TO_PACKET_META)) {
14372 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14373 			find_good_pkt_pointers(other_branch, src_reg,
14374 					       src_reg->type, true);
14375 			mark_pkt_end(this_branch, insn->src_reg, false);
14376 		} else {
14377 			return false;
14378 		}
14379 		break;
14380 	case BPF_JLT:
14381 		if ((dst_reg->type == PTR_TO_PACKET &&
14382 		     src_reg->type == PTR_TO_PACKET_END) ||
14383 		    (dst_reg->type == PTR_TO_PACKET_META &&
14384 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14385 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14386 			find_good_pkt_pointers(other_branch, dst_reg,
14387 					       dst_reg->type, true);
14388 			mark_pkt_end(this_branch, insn->dst_reg, false);
14389 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14390 			    src_reg->type == PTR_TO_PACKET) ||
14391 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14392 			    src_reg->type == PTR_TO_PACKET_META)) {
14393 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14394 			find_good_pkt_pointers(this_branch, src_reg,
14395 					       src_reg->type, false);
14396 			mark_pkt_end(other_branch, insn->src_reg, true);
14397 		} else {
14398 			return false;
14399 		}
14400 		break;
14401 	case BPF_JGE:
14402 		if ((dst_reg->type == PTR_TO_PACKET &&
14403 		     src_reg->type == PTR_TO_PACKET_END) ||
14404 		    (dst_reg->type == PTR_TO_PACKET_META &&
14405 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14406 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14407 			find_good_pkt_pointers(this_branch, dst_reg,
14408 					       dst_reg->type, true);
14409 			mark_pkt_end(other_branch, insn->dst_reg, false);
14410 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14411 			    src_reg->type == PTR_TO_PACKET) ||
14412 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14413 			    src_reg->type == PTR_TO_PACKET_META)) {
14414 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14415 			find_good_pkt_pointers(other_branch, src_reg,
14416 					       src_reg->type, false);
14417 			mark_pkt_end(this_branch, insn->src_reg, true);
14418 		} else {
14419 			return false;
14420 		}
14421 		break;
14422 	case BPF_JLE:
14423 		if ((dst_reg->type == PTR_TO_PACKET &&
14424 		     src_reg->type == PTR_TO_PACKET_END) ||
14425 		    (dst_reg->type == PTR_TO_PACKET_META &&
14426 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14427 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14428 			find_good_pkt_pointers(other_branch, dst_reg,
14429 					       dst_reg->type, false);
14430 			mark_pkt_end(this_branch, insn->dst_reg, true);
14431 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14432 			    src_reg->type == PTR_TO_PACKET) ||
14433 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14434 			    src_reg->type == PTR_TO_PACKET_META)) {
14435 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14436 			find_good_pkt_pointers(this_branch, src_reg,
14437 					       src_reg->type, true);
14438 			mark_pkt_end(other_branch, insn->src_reg, false);
14439 		} else {
14440 			return false;
14441 		}
14442 		break;
14443 	default:
14444 		return false;
14445 	}
14446 
14447 	return true;
14448 }
14449 
14450 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14451 			       struct bpf_reg_state *known_reg)
14452 {
14453 	struct bpf_func_state *state;
14454 	struct bpf_reg_state *reg;
14455 
14456 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14457 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14458 			copy_register_state(reg, known_reg);
14459 	}));
14460 }
14461 
14462 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14463 			     struct bpf_insn *insn, int *insn_idx)
14464 {
14465 	struct bpf_verifier_state *this_branch = env->cur_state;
14466 	struct bpf_verifier_state *other_branch;
14467 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14468 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14469 	struct bpf_reg_state *eq_branch_regs;
14470 	u8 opcode = BPF_OP(insn->code);
14471 	bool is_jmp32;
14472 	int pred = -1;
14473 	int err;
14474 
14475 	/* Only conditional jumps are expected to reach here. */
14476 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14477 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14478 		return -EINVAL;
14479 	}
14480 
14481 	/* check src2 operand */
14482 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14483 	if (err)
14484 		return err;
14485 
14486 	dst_reg = &regs[insn->dst_reg];
14487 	if (BPF_SRC(insn->code) == BPF_X) {
14488 		if (insn->imm != 0) {
14489 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14490 			return -EINVAL;
14491 		}
14492 
14493 		/* check src1 operand */
14494 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14495 		if (err)
14496 			return err;
14497 
14498 		src_reg = &regs[insn->src_reg];
14499 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14500 		    is_pointer_value(env, insn->src_reg)) {
14501 			verbose(env, "R%d pointer comparison prohibited\n",
14502 				insn->src_reg);
14503 			return -EACCES;
14504 		}
14505 	} else {
14506 		if (insn->src_reg != BPF_REG_0) {
14507 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14508 			return -EINVAL;
14509 		}
14510 	}
14511 
14512 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14513 
14514 	if (BPF_SRC(insn->code) == BPF_K) {
14515 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14516 	} else if (src_reg->type == SCALAR_VALUE &&
14517 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14518 		pred = is_branch_taken(dst_reg,
14519 				       tnum_subreg(src_reg->var_off).value,
14520 				       opcode,
14521 				       is_jmp32);
14522 	} else if (src_reg->type == SCALAR_VALUE &&
14523 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14524 		pred = is_branch_taken(dst_reg,
14525 				       src_reg->var_off.value,
14526 				       opcode,
14527 				       is_jmp32);
14528 	} else if (dst_reg->type == SCALAR_VALUE &&
14529 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14530 		pred = is_branch_taken(src_reg,
14531 				       tnum_subreg(dst_reg->var_off).value,
14532 				       flip_opcode(opcode),
14533 				       is_jmp32);
14534 	} else if (dst_reg->type == SCALAR_VALUE &&
14535 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14536 		pred = is_branch_taken(src_reg,
14537 				       dst_reg->var_off.value,
14538 				       flip_opcode(opcode),
14539 				       is_jmp32);
14540 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14541 		   reg_is_pkt_pointer_any(src_reg) &&
14542 		   !is_jmp32) {
14543 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14544 	}
14545 
14546 	if (pred >= 0) {
14547 		/* If we get here with a dst_reg pointer type it is because
14548 		 * above is_branch_taken() special cased the 0 comparison.
14549 		 */
14550 		if (!__is_pointer_value(false, dst_reg))
14551 			err = mark_chain_precision(env, insn->dst_reg);
14552 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14553 		    !__is_pointer_value(false, src_reg))
14554 			err = mark_chain_precision(env, insn->src_reg);
14555 		if (err)
14556 			return err;
14557 	}
14558 
14559 	if (pred == 1) {
14560 		/* Only follow the goto, ignore fall-through. If needed, push
14561 		 * the fall-through branch for simulation under speculative
14562 		 * execution.
14563 		 */
14564 		if (!env->bypass_spec_v1 &&
14565 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14566 					       *insn_idx))
14567 			return -EFAULT;
14568 		if (env->log.level & BPF_LOG_LEVEL)
14569 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14570 		*insn_idx += insn->off;
14571 		return 0;
14572 	} else if (pred == 0) {
14573 		/* Only follow the fall-through branch, since that's where the
14574 		 * program will go. If needed, push the goto branch for
14575 		 * simulation under speculative execution.
14576 		 */
14577 		if (!env->bypass_spec_v1 &&
14578 		    !sanitize_speculative_path(env, insn,
14579 					       *insn_idx + insn->off + 1,
14580 					       *insn_idx))
14581 			return -EFAULT;
14582 		if (env->log.level & BPF_LOG_LEVEL)
14583 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14584 		return 0;
14585 	}
14586 
14587 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14588 				  false);
14589 	if (!other_branch)
14590 		return -EFAULT;
14591 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14592 
14593 	/* detect if we are comparing against a constant value so we can adjust
14594 	 * our min/max values for our dst register.
14595 	 * this is only legit if both are scalars (or pointers to the same
14596 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14597 	 * because otherwise the different base pointers mean the offsets aren't
14598 	 * comparable.
14599 	 */
14600 	if (BPF_SRC(insn->code) == BPF_X) {
14601 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14602 
14603 		if (dst_reg->type == SCALAR_VALUE &&
14604 		    src_reg->type == SCALAR_VALUE) {
14605 			if (tnum_is_const(src_reg->var_off) ||
14606 			    (is_jmp32 &&
14607 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14608 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14609 						dst_reg,
14610 						src_reg->var_off.value,
14611 						tnum_subreg(src_reg->var_off).value,
14612 						opcode, is_jmp32);
14613 			else if (tnum_is_const(dst_reg->var_off) ||
14614 				 (is_jmp32 &&
14615 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14616 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14617 						    src_reg,
14618 						    dst_reg->var_off.value,
14619 						    tnum_subreg(dst_reg->var_off).value,
14620 						    opcode, is_jmp32);
14621 			else if (!is_jmp32 &&
14622 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14623 				/* Comparing for equality, we can combine knowledge */
14624 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14625 						    &other_branch_regs[insn->dst_reg],
14626 						    src_reg, dst_reg, opcode);
14627 			if (src_reg->id &&
14628 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14629 				find_equal_scalars(this_branch, src_reg);
14630 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14631 			}
14632 
14633 		}
14634 	} else if (dst_reg->type == SCALAR_VALUE) {
14635 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14636 					dst_reg, insn->imm, (u32)insn->imm,
14637 					opcode, is_jmp32);
14638 	}
14639 
14640 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14641 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14642 		find_equal_scalars(this_branch, dst_reg);
14643 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14644 	}
14645 
14646 	/* if one pointer register is compared to another pointer
14647 	 * register check if PTR_MAYBE_NULL could be lifted.
14648 	 * E.g. register A - maybe null
14649 	 *      register B - not null
14650 	 * for JNE A, B, ... - A is not null in the false branch;
14651 	 * for JEQ A, B, ... - A is not null in the true branch.
14652 	 *
14653 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14654 	 * not need to be null checked by the BPF program, i.e.,
14655 	 * could be null even without PTR_MAYBE_NULL marking, so
14656 	 * only propagate nullness when neither reg is that type.
14657 	 */
14658 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14659 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14660 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14661 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14662 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14663 		eq_branch_regs = NULL;
14664 		switch (opcode) {
14665 		case BPF_JEQ:
14666 			eq_branch_regs = other_branch_regs;
14667 			break;
14668 		case BPF_JNE:
14669 			eq_branch_regs = regs;
14670 			break;
14671 		default:
14672 			/* do nothing */
14673 			break;
14674 		}
14675 		if (eq_branch_regs) {
14676 			if (type_may_be_null(src_reg->type))
14677 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14678 			else
14679 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14680 		}
14681 	}
14682 
14683 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14684 	 * NOTE: these optimizations below are related with pointer comparison
14685 	 *       which will never be JMP32.
14686 	 */
14687 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14688 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14689 	    type_may_be_null(dst_reg->type)) {
14690 		/* Mark all identical registers in each branch as either
14691 		 * safe or unknown depending R == 0 or R != 0 conditional.
14692 		 */
14693 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14694 				      opcode == BPF_JNE);
14695 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14696 				      opcode == BPF_JEQ);
14697 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14698 					   this_branch, other_branch) &&
14699 		   is_pointer_value(env, insn->dst_reg)) {
14700 		verbose(env, "R%d pointer comparison prohibited\n",
14701 			insn->dst_reg);
14702 		return -EACCES;
14703 	}
14704 	if (env->log.level & BPF_LOG_LEVEL)
14705 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14706 	return 0;
14707 }
14708 
14709 /* verify BPF_LD_IMM64 instruction */
14710 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14711 {
14712 	struct bpf_insn_aux_data *aux = cur_aux(env);
14713 	struct bpf_reg_state *regs = cur_regs(env);
14714 	struct bpf_reg_state *dst_reg;
14715 	struct bpf_map *map;
14716 	int err;
14717 
14718 	if (BPF_SIZE(insn->code) != BPF_DW) {
14719 		verbose(env, "invalid BPF_LD_IMM insn\n");
14720 		return -EINVAL;
14721 	}
14722 	if (insn->off != 0) {
14723 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14724 		return -EINVAL;
14725 	}
14726 
14727 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14728 	if (err)
14729 		return err;
14730 
14731 	dst_reg = &regs[insn->dst_reg];
14732 	if (insn->src_reg == 0) {
14733 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14734 
14735 		dst_reg->type = SCALAR_VALUE;
14736 		__mark_reg_known(&regs[insn->dst_reg], imm);
14737 		return 0;
14738 	}
14739 
14740 	/* All special src_reg cases are listed below. From this point onwards
14741 	 * we either succeed and assign a corresponding dst_reg->type after
14742 	 * zeroing the offset, or fail and reject the program.
14743 	 */
14744 	mark_reg_known_zero(env, regs, insn->dst_reg);
14745 
14746 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14747 		dst_reg->type = aux->btf_var.reg_type;
14748 		switch (base_type(dst_reg->type)) {
14749 		case PTR_TO_MEM:
14750 			dst_reg->mem_size = aux->btf_var.mem_size;
14751 			break;
14752 		case PTR_TO_BTF_ID:
14753 			dst_reg->btf = aux->btf_var.btf;
14754 			dst_reg->btf_id = aux->btf_var.btf_id;
14755 			break;
14756 		default:
14757 			verbose(env, "bpf verifier is misconfigured\n");
14758 			return -EFAULT;
14759 		}
14760 		return 0;
14761 	}
14762 
14763 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14764 		struct bpf_prog_aux *aux = env->prog->aux;
14765 		u32 subprogno = find_subprog(env,
14766 					     env->insn_idx + insn->imm + 1);
14767 
14768 		if (!aux->func_info) {
14769 			verbose(env, "missing btf func_info\n");
14770 			return -EINVAL;
14771 		}
14772 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14773 			verbose(env, "callback function not static\n");
14774 			return -EINVAL;
14775 		}
14776 
14777 		dst_reg->type = PTR_TO_FUNC;
14778 		dst_reg->subprogno = subprogno;
14779 		return 0;
14780 	}
14781 
14782 	map = env->used_maps[aux->map_index];
14783 	dst_reg->map_ptr = map;
14784 
14785 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14786 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14787 		dst_reg->type = PTR_TO_MAP_VALUE;
14788 		dst_reg->off = aux->map_off;
14789 		WARN_ON_ONCE(map->max_entries != 1);
14790 		/* We want reg->id to be same (0) as map_value is not distinct */
14791 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14792 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14793 		dst_reg->type = CONST_PTR_TO_MAP;
14794 	} else {
14795 		verbose(env, "bpf verifier is misconfigured\n");
14796 		return -EINVAL;
14797 	}
14798 
14799 	return 0;
14800 }
14801 
14802 static bool may_access_skb(enum bpf_prog_type type)
14803 {
14804 	switch (type) {
14805 	case BPF_PROG_TYPE_SOCKET_FILTER:
14806 	case BPF_PROG_TYPE_SCHED_CLS:
14807 	case BPF_PROG_TYPE_SCHED_ACT:
14808 		return true;
14809 	default:
14810 		return false;
14811 	}
14812 }
14813 
14814 /* verify safety of LD_ABS|LD_IND instructions:
14815  * - they can only appear in the programs where ctx == skb
14816  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14817  *   preserve R6-R9, and store return value into R0
14818  *
14819  * Implicit input:
14820  *   ctx == skb == R6 == CTX
14821  *
14822  * Explicit input:
14823  *   SRC == any register
14824  *   IMM == 32-bit immediate
14825  *
14826  * Output:
14827  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14828  */
14829 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14830 {
14831 	struct bpf_reg_state *regs = cur_regs(env);
14832 	static const int ctx_reg = BPF_REG_6;
14833 	u8 mode = BPF_MODE(insn->code);
14834 	int i, err;
14835 
14836 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14837 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14838 		return -EINVAL;
14839 	}
14840 
14841 	if (!env->ops->gen_ld_abs) {
14842 		verbose(env, "bpf verifier is misconfigured\n");
14843 		return -EINVAL;
14844 	}
14845 
14846 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14847 	    BPF_SIZE(insn->code) == BPF_DW ||
14848 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14849 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14850 		return -EINVAL;
14851 	}
14852 
14853 	/* check whether implicit source operand (register R6) is readable */
14854 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14855 	if (err)
14856 		return err;
14857 
14858 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14859 	 * gen_ld_abs() may terminate the program at runtime, leading to
14860 	 * reference leak.
14861 	 */
14862 	err = check_reference_leak(env);
14863 	if (err) {
14864 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14865 		return err;
14866 	}
14867 
14868 	if (env->cur_state->active_lock.ptr) {
14869 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14870 		return -EINVAL;
14871 	}
14872 
14873 	if (env->cur_state->active_rcu_lock) {
14874 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14875 		return -EINVAL;
14876 	}
14877 
14878 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14879 		verbose(env,
14880 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14881 		return -EINVAL;
14882 	}
14883 
14884 	if (mode == BPF_IND) {
14885 		/* check explicit source operand */
14886 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14887 		if (err)
14888 			return err;
14889 	}
14890 
14891 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14892 	if (err < 0)
14893 		return err;
14894 
14895 	/* reset caller saved regs to unreadable */
14896 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14897 		mark_reg_not_init(env, regs, caller_saved[i]);
14898 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14899 	}
14900 
14901 	/* mark destination R0 register as readable, since it contains
14902 	 * the value fetched from the packet.
14903 	 * Already marked as written above.
14904 	 */
14905 	mark_reg_unknown(env, regs, BPF_REG_0);
14906 	/* ld_abs load up to 32-bit skb data. */
14907 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14908 	return 0;
14909 }
14910 
14911 static int check_return_code(struct bpf_verifier_env *env)
14912 {
14913 	struct tnum enforce_attach_type_range = tnum_unknown;
14914 	const struct bpf_prog *prog = env->prog;
14915 	struct bpf_reg_state *reg;
14916 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14917 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14918 	int err;
14919 	struct bpf_func_state *frame = env->cur_state->frame[0];
14920 	const bool is_subprog = frame->subprogno;
14921 
14922 	/* LSM and struct_ops func-ptr's return type could be "void" */
14923 	if (!is_subprog) {
14924 		switch (prog_type) {
14925 		case BPF_PROG_TYPE_LSM:
14926 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14927 				/* See below, can be 0 or 0-1 depending on hook. */
14928 				break;
14929 			fallthrough;
14930 		case BPF_PROG_TYPE_STRUCT_OPS:
14931 			if (!prog->aux->attach_func_proto->type)
14932 				return 0;
14933 			break;
14934 		default:
14935 			break;
14936 		}
14937 	}
14938 
14939 	/* eBPF calling convention is such that R0 is used
14940 	 * to return the value from eBPF program.
14941 	 * Make sure that it's readable at this time
14942 	 * of bpf_exit, which means that program wrote
14943 	 * something into it earlier
14944 	 */
14945 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14946 	if (err)
14947 		return err;
14948 
14949 	if (is_pointer_value(env, BPF_REG_0)) {
14950 		verbose(env, "R0 leaks addr as return value\n");
14951 		return -EACCES;
14952 	}
14953 
14954 	reg = cur_regs(env) + BPF_REG_0;
14955 
14956 	if (frame->in_async_callback_fn) {
14957 		/* enforce return zero from async callbacks like timer */
14958 		if (reg->type != SCALAR_VALUE) {
14959 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14960 				reg_type_str(env, reg->type));
14961 			return -EINVAL;
14962 		}
14963 
14964 		if (!tnum_in(const_0, reg->var_off)) {
14965 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14966 			return -EINVAL;
14967 		}
14968 		return 0;
14969 	}
14970 
14971 	if (is_subprog) {
14972 		if (reg->type != SCALAR_VALUE) {
14973 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14974 				reg_type_str(env, reg->type));
14975 			return -EINVAL;
14976 		}
14977 		return 0;
14978 	}
14979 
14980 	switch (prog_type) {
14981 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14982 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14983 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14984 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14985 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14986 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14987 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14988 			range = tnum_range(1, 1);
14989 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14990 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14991 			range = tnum_range(0, 3);
14992 		break;
14993 	case BPF_PROG_TYPE_CGROUP_SKB:
14994 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14995 			range = tnum_range(0, 3);
14996 			enforce_attach_type_range = tnum_range(2, 3);
14997 		}
14998 		break;
14999 	case BPF_PROG_TYPE_CGROUP_SOCK:
15000 	case BPF_PROG_TYPE_SOCK_OPS:
15001 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15002 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15003 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15004 		break;
15005 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15006 		if (!env->prog->aux->attach_btf_id)
15007 			return 0;
15008 		range = tnum_const(0);
15009 		break;
15010 	case BPF_PROG_TYPE_TRACING:
15011 		switch (env->prog->expected_attach_type) {
15012 		case BPF_TRACE_FENTRY:
15013 		case BPF_TRACE_FEXIT:
15014 			range = tnum_const(0);
15015 			break;
15016 		case BPF_TRACE_RAW_TP:
15017 		case BPF_MODIFY_RETURN:
15018 			return 0;
15019 		case BPF_TRACE_ITER:
15020 			break;
15021 		default:
15022 			return -ENOTSUPP;
15023 		}
15024 		break;
15025 	case BPF_PROG_TYPE_SK_LOOKUP:
15026 		range = tnum_range(SK_DROP, SK_PASS);
15027 		break;
15028 
15029 	case BPF_PROG_TYPE_LSM:
15030 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15031 			/* Regular BPF_PROG_TYPE_LSM programs can return
15032 			 * any value.
15033 			 */
15034 			return 0;
15035 		}
15036 		if (!env->prog->aux->attach_func_proto->type) {
15037 			/* Make sure programs that attach to void
15038 			 * hooks don't try to modify return value.
15039 			 */
15040 			range = tnum_range(1, 1);
15041 		}
15042 		break;
15043 
15044 	case BPF_PROG_TYPE_NETFILTER:
15045 		range = tnum_range(NF_DROP, NF_ACCEPT);
15046 		break;
15047 	case BPF_PROG_TYPE_EXT:
15048 		/* freplace program can return anything as its return value
15049 		 * depends on the to-be-replaced kernel func or bpf program.
15050 		 */
15051 	default:
15052 		return 0;
15053 	}
15054 
15055 	if (reg->type != SCALAR_VALUE) {
15056 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15057 			reg_type_str(env, reg->type));
15058 		return -EINVAL;
15059 	}
15060 
15061 	if (!tnum_in(range, reg->var_off)) {
15062 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15063 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15064 		    prog_type == BPF_PROG_TYPE_LSM &&
15065 		    !prog->aux->attach_func_proto->type)
15066 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15067 		return -EINVAL;
15068 	}
15069 
15070 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15071 	    tnum_in(enforce_attach_type_range, reg->var_off))
15072 		env->prog->enforce_expected_attach_type = 1;
15073 	return 0;
15074 }
15075 
15076 /* non-recursive DFS pseudo code
15077  * 1  procedure DFS-iterative(G,v):
15078  * 2      label v as discovered
15079  * 3      let S be a stack
15080  * 4      S.push(v)
15081  * 5      while S is not empty
15082  * 6            t <- S.peek()
15083  * 7            if t is what we're looking for:
15084  * 8                return t
15085  * 9            for all edges e in G.adjacentEdges(t) do
15086  * 10               if edge e is already labelled
15087  * 11                   continue with the next edge
15088  * 12               w <- G.adjacentVertex(t,e)
15089  * 13               if vertex w is not discovered and not explored
15090  * 14                   label e as tree-edge
15091  * 15                   label w as discovered
15092  * 16                   S.push(w)
15093  * 17                   continue at 5
15094  * 18               else if vertex w is discovered
15095  * 19                   label e as back-edge
15096  * 20               else
15097  * 21                   // vertex w is explored
15098  * 22                   label e as forward- or cross-edge
15099  * 23           label t as explored
15100  * 24           S.pop()
15101  *
15102  * convention:
15103  * 0x10 - discovered
15104  * 0x11 - discovered and fall-through edge labelled
15105  * 0x12 - discovered and fall-through and branch edges labelled
15106  * 0x20 - explored
15107  */
15108 
15109 enum {
15110 	DISCOVERED = 0x10,
15111 	EXPLORED = 0x20,
15112 	FALLTHROUGH = 1,
15113 	BRANCH = 2,
15114 };
15115 
15116 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15117 {
15118 	env->insn_aux_data[idx].prune_point = true;
15119 }
15120 
15121 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15122 {
15123 	return env->insn_aux_data[insn_idx].prune_point;
15124 }
15125 
15126 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15127 {
15128 	env->insn_aux_data[idx].force_checkpoint = true;
15129 }
15130 
15131 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15132 {
15133 	return env->insn_aux_data[insn_idx].force_checkpoint;
15134 }
15135 
15136 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15137 {
15138 	env->insn_aux_data[idx].calls_callback = true;
15139 }
15140 
15141 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15142 {
15143 	return env->insn_aux_data[insn_idx].calls_callback;
15144 }
15145 
15146 enum {
15147 	DONE_EXPLORING = 0,
15148 	KEEP_EXPLORING = 1,
15149 };
15150 
15151 /* t, w, e - match pseudo-code above:
15152  * t - index of current instruction
15153  * w - next instruction
15154  * e - edge
15155  */
15156 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15157 {
15158 	int *insn_stack = env->cfg.insn_stack;
15159 	int *insn_state = env->cfg.insn_state;
15160 
15161 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15162 		return DONE_EXPLORING;
15163 
15164 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15165 		return DONE_EXPLORING;
15166 
15167 	if (w < 0 || w >= env->prog->len) {
15168 		verbose_linfo(env, t, "%d: ", t);
15169 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15170 		return -EINVAL;
15171 	}
15172 
15173 	if (e == BRANCH) {
15174 		/* mark branch target for state pruning */
15175 		mark_prune_point(env, w);
15176 		mark_jmp_point(env, w);
15177 	}
15178 
15179 	if (insn_state[w] == 0) {
15180 		/* tree-edge */
15181 		insn_state[t] = DISCOVERED | e;
15182 		insn_state[w] = DISCOVERED;
15183 		if (env->cfg.cur_stack >= env->prog->len)
15184 			return -E2BIG;
15185 		insn_stack[env->cfg.cur_stack++] = w;
15186 		return KEEP_EXPLORING;
15187 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15188 		if (env->bpf_capable)
15189 			return DONE_EXPLORING;
15190 		verbose_linfo(env, t, "%d: ", t);
15191 		verbose_linfo(env, w, "%d: ", w);
15192 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15193 		return -EINVAL;
15194 	} else if (insn_state[w] == EXPLORED) {
15195 		/* forward- or cross-edge */
15196 		insn_state[t] = DISCOVERED | e;
15197 	} else {
15198 		verbose(env, "insn state internal bug\n");
15199 		return -EFAULT;
15200 	}
15201 	return DONE_EXPLORING;
15202 }
15203 
15204 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15205 				struct bpf_verifier_env *env,
15206 				bool visit_callee)
15207 {
15208 	int ret, insn_sz;
15209 
15210 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15211 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15212 	if (ret)
15213 		return ret;
15214 
15215 	mark_prune_point(env, t + insn_sz);
15216 	/* when we exit from subprog, we need to record non-linear history */
15217 	mark_jmp_point(env, t + insn_sz);
15218 
15219 	if (visit_callee) {
15220 		mark_prune_point(env, t);
15221 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15222 	}
15223 	return ret;
15224 }
15225 
15226 /* Visits the instruction at index t and returns one of the following:
15227  *  < 0 - an error occurred
15228  *  DONE_EXPLORING - the instruction was fully explored
15229  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15230  */
15231 static int visit_insn(int t, struct bpf_verifier_env *env)
15232 {
15233 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15234 	int ret, off, insn_sz;
15235 
15236 	if (bpf_pseudo_func(insn))
15237 		return visit_func_call_insn(t, insns, env, true);
15238 
15239 	/* All non-branch instructions have a single fall-through edge. */
15240 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15241 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15242 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15243 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15244 	}
15245 
15246 	switch (BPF_OP(insn->code)) {
15247 	case BPF_EXIT:
15248 		return DONE_EXPLORING;
15249 
15250 	case BPF_CALL:
15251 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15252 			/* Mark this call insn as a prune point to trigger
15253 			 * is_state_visited() check before call itself is
15254 			 * processed by __check_func_call(). Otherwise new
15255 			 * async state will be pushed for further exploration.
15256 			 */
15257 			mark_prune_point(env, t);
15258 		/* For functions that invoke callbacks it is not known how many times
15259 		 * callback would be called. Verifier models callback calling functions
15260 		 * by repeatedly visiting callback bodies and returning to origin call
15261 		 * instruction.
15262 		 * In order to stop such iteration verifier needs to identify when a
15263 		 * state identical some state from a previous iteration is reached.
15264 		 * Check below forces creation of checkpoint before callback calling
15265 		 * instruction to allow search for such identical states.
15266 		 */
15267 		if (is_sync_callback_calling_insn(insn)) {
15268 			mark_calls_callback(env, t);
15269 			mark_force_checkpoint(env, t);
15270 			mark_prune_point(env, t);
15271 			mark_jmp_point(env, t);
15272 		}
15273 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15274 			struct bpf_kfunc_call_arg_meta meta;
15275 
15276 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15277 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15278 				mark_prune_point(env, t);
15279 				/* Checking and saving state checkpoints at iter_next() call
15280 				 * is crucial for fast convergence of open-coded iterator loop
15281 				 * logic, so we need to force it. If we don't do that,
15282 				 * is_state_visited() might skip saving a checkpoint, causing
15283 				 * unnecessarily long sequence of not checkpointed
15284 				 * instructions and jumps, leading to exhaustion of jump
15285 				 * history buffer, and potentially other undesired outcomes.
15286 				 * It is expected that with correct open-coded iterators
15287 				 * convergence will happen quickly, so we don't run a risk of
15288 				 * exhausting memory.
15289 				 */
15290 				mark_force_checkpoint(env, t);
15291 			}
15292 		}
15293 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15294 
15295 	case BPF_JA:
15296 		if (BPF_SRC(insn->code) != BPF_K)
15297 			return -EINVAL;
15298 
15299 		if (BPF_CLASS(insn->code) == BPF_JMP)
15300 			off = insn->off;
15301 		else
15302 			off = insn->imm;
15303 
15304 		/* unconditional jump with single edge */
15305 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15306 		if (ret)
15307 			return ret;
15308 
15309 		mark_prune_point(env, t + off + 1);
15310 		mark_jmp_point(env, t + off + 1);
15311 
15312 		return ret;
15313 
15314 	default:
15315 		/* conditional jump with two edges */
15316 		mark_prune_point(env, t);
15317 
15318 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15319 		if (ret)
15320 			return ret;
15321 
15322 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15323 	}
15324 }
15325 
15326 /* non-recursive depth-first-search to detect loops in BPF program
15327  * loop == back-edge in directed graph
15328  */
15329 static int check_cfg(struct bpf_verifier_env *env)
15330 {
15331 	int insn_cnt = env->prog->len;
15332 	int *insn_stack, *insn_state;
15333 	int ret = 0;
15334 	int i;
15335 
15336 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15337 	if (!insn_state)
15338 		return -ENOMEM;
15339 
15340 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15341 	if (!insn_stack) {
15342 		kvfree(insn_state);
15343 		return -ENOMEM;
15344 	}
15345 
15346 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15347 	insn_stack[0] = 0; /* 0 is the first instruction */
15348 	env->cfg.cur_stack = 1;
15349 
15350 	while (env->cfg.cur_stack > 0) {
15351 		int t = insn_stack[env->cfg.cur_stack - 1];
15352 
15353 		ret = visit_insn(t, env);
15354 		switch (ret) {
15355 		case DONE_EXPLORING:
15356 			insn_state[t] = EXPLORED;
15357 			env->cfg.cur_stack--;
15358 			break;
15359 		case KEEP_EXPLORING:
15360 			break;
15361 		default:
15362 			if (ret > 0) {
15363 				verbose(env, "visit_insn internal bug\n");
15364 				ret = -EFAULT;
15365 			}
15366 			goto err_free;
15367 		}
15368 	}
15369 
15370 	if (env->cfg.cur_stack < 0) {
15371 		verbose(env, "pop stack internal bug\n");
15372 		ret = -EFAULT;
15373 		goto err_free;
15374 	}
15375 
15376 	for (i = 0; i < insn_cnt; i++) {
15377 		struct bpf_insn *insn = &env->prog->insnsi[i];
15378 
15379 		if (insn_state[i] != EXPLORED) {
15380 			verbose(env, "unreachable insn %d\n", i);
15381 			ret = -EINVAL;
15382 			goto err_free;
15383 		}
15384 		if (bpf_is_ldimm64(insn)) {
15385 			if (insn_state[i + 1] != 0) {
15386 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15387 				ret = -EINVAL;
15388 				goto err_free;
15389 			}
15390 			i++; /* skip second half of ldimm64 */
15391 		}
15392 	}
15393 	ret = 0; /* cfg looks good */
15394 
15395 err_free:
15396 	kvfree(insn_state);
15397 	kvfree(insn_stack);
15398 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15399 	return ret;
15400 }
15401 
15402 static int check_abnormal_return(struct bpf_verifier_env *env)
15403 {
15404 	int i;
15405 
15406 	for (i = 1; i < env->subprog_cnt; i++) {
15407 		if (env->subprog_info[i].has_ld_abs) {
15408 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15409 			return -EINVAL;
15410 		}
15411 		if (env->subprog_info[i].has_tail_call) {
15412 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15413 			return -EINVAL;
15414 		}
15415 	}
15416 	return 0;
15417 }
15418 
15419 /* The minimum supported BTF func info size */
15420 #define MIN_BPF_FUNCINFO_SIZE	8
15421 #define MAX_FUNCINFO_REC_SIZE	252
15422 
15423 static int check_btf_func(struct bpf_verifier_env *env,
15424 			  const union bpf_attr *attr,
15425 			  bpfptr_t uattr)
15426 {
15427 	const struct btf_type *type, *func_proto, *ret_type;
15428 	u32 i, nfuncs, urec_size, min_size;
15429 	u32 krec_size = sizeof(struct bpf_func_info);
15430 	struct bpf_func_info *krecord;
15431 	struct bpf_func_info_aux *info_aux = NULL;
15432 	struct bpf_prog *prog;
15433 	const struct btf *btf;
15434 	bpfptr_t urecord;
15435 	u32 prev_offset = 0;
15436 	bool scalar_return;
15437 	int ret = -ENOMEM;
15438 
15439 	nfuncs = attr->func_info_cnt;
15440 	if (!nfuncs) {
15441 		if (check_abnormal_return(env))
15442 			return -EINVAL;
15443 		return 0;
15444 	}
15445 
15446 	if (nfuncs != env->subprog_cnt) {
15447 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15448 		return -EINVAL;
15449 	}
15450 
15451 	urec_size = attr->func_info_rec_size;
15452 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15453 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15454 	    urec_size % sizeof(u32)) {
15455 		verbose(env, "invalid func info rec size %u\n", urec_size);
15456 		return -EINVAL;
15457 	}
15458 
15459 	prog = env->prog;
15460 	btf = prog->aux->btf;
15461 
15462 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15463 	min_size = min_t(u32, krec_size, urec_size);
15464 
15465 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15466 	if (!krecord)
15467 		return -ENOMEM;
15468 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15469 	if (!info_aux)
15470 		goto err_free;
15471 
15472 	for (i = 0; i < nfuncs; i++) {
15473 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15474 		if (ret) {
15475 			if (ret == -E2BIG) {
15476 				verbose(env, "nonzero tailing record in func info");
15477 				/* set the size kernel expects so loader can zero
15478 				 * out the rest of the record.
15479 				 */
15480 				if (copy_to_bpfptr_offset(uattr,
15481 							  offsetof(union bpf_attr, func_info_rec_size),
15482 							  &min_size, sizeof(min_size)))
15483 					ret = -EFAULT;
15484 			}
15485 			goto err_free;
15486 		}
15487 
15488 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15489 			ret = -EFAULT;
15490 			goto err_free;
15491 		}
15492 
15493 		/* check insn_off */
15494 		ret = -EINVAL;
15495 		if (i == 0) {
15496 			if (krecord[i].insn_off) {
15497 				verbose(env,
15498 					"nonzero insn_off %u for the first func info record",
15499 					krecord[i].insn_off);
15500 				goto err_free;
15501 			}
15502 		} else if (krecord[i].insn_off <= prev_offset) {
15503 			verbose(env,
15504 				"same or smaller insn offset (%u) than previous func info record (%u)",
15505 				krecord[i].insn_off, prev_offset);
15506 			goto err_free;
15507 		}
15508 
15509 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15510 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15511 			goto err_free;
15512 		}
15513 
15514 		/* check type_id */
15515 		type = btf_type_by_id(btf, krecord[i].type_id);
15516 		if (!type || !btf_type_is_func(type)) {
15517 			verbose(env, "invalid type id %d in func info",
15518 				krecord[i].type_id);
15519 			goto err_free;
15520 		}
15521 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15522 
15523 		func_proto = btf_type_by_id(btf, type->type);
15524 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15525 			/* btf_func_check() already verified it during BTF load */
15526 			goto err_free;
15527 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15528 		scalar_return =
15529 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15530 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15531 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15532 			goto err_free;
15533 		}
15534 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15535 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15536 			goto err_free;
15537 		}
15538 
15539 		prev_offset = krecord[i].insn_off;
15540 		bpfptr_add(&urecord, urec_size);
15541 	}
15542 
15543 	prog->aux->func_info = krecord;
15544 	prog->aux->func_info_cnt = nfuncs;
15545 	prog->aux->func_info_aux = info_aux;
15546 	return 0;
15547 
15548 err_free:
15549 	kvfree(krecord);
15550 	kfree(info_aux);
15551 	return ret;
15552 }
15553 
15554 static void adjust_btf_func(struct bpf_verifier_env *env)
15555 {
15556 	struct bpf_prog_aux *aux = env->prog->aux;
15557 	int i;
15558 
15559 	if (!aux->func_info)
15560 		return;
15561 
15562 	for (i = 0; i < env->subprog_cnt; i++)
15563 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15564 }
15565 
15566 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15567 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15568 
15569 static int check_btf_line(struct bpf_verifier_env *env,
15570 			  const union bpf_attr *attr,
15571 			  bpfptr_t uattr)
15572 {
15573 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15574 	struct bpf_subprog_info *sub;
15575 	struct bpf_line_info *linfo;
15576 	struct bpf_prog *prog;
15577 	const struct btf *btf;
15578 	bpfptr_t ulinfo;
15579 	int err;
15580 
15581 	nr_linfo = attr->line_info_cnt;
15582 	if (!nr_linfo)
15583 		return 0;
15584 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15585 		return -EINVAL;
15586 
15587 	rec_size = attr->line_info_rec_size;
15588 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15589 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15590 	    rec_size & (sizeof(u32) - 1))
15591 		return -EINVAL;
15592 
15593 	/* Need to zero it in case the userspace may
15594 	 * pass in a smaller bpf_line_info object.
15595 	 */
15596 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15597 			 GFP_KERNEL | __GFP_NOWARN);
15598 	if (!linfo)
15599 		return -ENOMEM;
15600 
15601 	prog = env->prog;
15602 	btf = prog->aux->btf;
15603 
15604 	s = 0;
15605 	sub = env->subprog_info;
15606 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15607 	expected_size = sizeof(struct bpf_line_info);
15608 	ncopy = min_t(u32, expected_size, rec_size);
15609 	for (i = 0; i < nr_linfo; i++) {
15610 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15611 		if (err) {
15612 			if (err == -E2BIG) {
15613 				verbose(env, "nonzero tailing record in line_info");
15614 				if (copy_to_bpfptr_offset(uattr,
15615 							  offsetof(union bpf_attr, line_info_rec_size),
15616 							  &expected_size, sizeof(expected_size)))
15617 					err = -EFAULT;
15618 			}
15619 			goto err_free;
15620 		}
15621 
15622 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15623 			err = -EFAULT;
15624 			goto err_free;
15625 		}
15626 
15627 		/*
15628 		 * Check insn_off to ensure
15629 		 * 1) strictly increasing AND
15630 		 * 2) bounded by prog->len
15631 		 *
15632 		 * The linfo[0].insn_off == 0 check logically falls into
15633 		 * the later "missing bpf_line_info for func..." case
15634 		 * because the first linfo[0].insn_off must be the
15635 		 * first sub also and the first sub must have
15636 		 * subprog_info[0].start == 0.
15637 		 */
15638 		if ((i && linfo[i].insn_off <= prev_offset) ||
15639 		    linfo[i].insn_off >= prog->len) {
15640 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15641 				i, linfo[i].insn_off, prev_offset,
15642 				prog->len);
15643 			err = -EINVAL;
15644 			goto err_free;
15645 		}
15646 
15647 		if (!prog->insnsi[linfo[i].insn_off].code) {
15648 			verbose(env,
15649 				"Invalid insn code at line_info[%u].insn_off\n",
15650 				i);
15651 			err = -EINVAL;
15652 			goto err_free;
15653 		}
15654 
15655 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15656 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15657 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15658 			err = -EINVAL;
15659 			goto err_free;
15660 		}
15661 
15662 		if (s != env->subprog_cnt) {
15663 			if (linfo[i].insn_off == sub[s].start) {
15664 				sub[s].linfo_idx = i;
15665 				s++;
15666 			} else if (sub[s].start < linfo[i].insn_off) {
15667 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15668 				err = -EINVAL;
15669 				goto err_free;
15670 			}
15671 		}
15672 
15673 		prev_offset = linfo[i].insn_off;
15674 		bpfptr_add(&ulinfo, rec_size);
15675 	}
15676 
15677 	if (s != env->subprog_cnt) {
15678 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15679 			env->subprog_cnt - s, s);
15680 		err = -EINVAL;
15681 		goto err_free;
15682 	}
15683 
15684 	prog->aux->linfo = linfo;
15685 	prog->aux->nr_linfo = nr_linfo;
15686 
15687 	return 0;
15688 
15689 err_free:
15690 	kvfree(linfo);
15691 	return err;
15692 }
15693 
15694 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15695 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15696 
15697 static int check_core_relo(struct bpf_verifier_env *env,
15698 			   const union bpf_attr *attr,
15699 			   bpfptr_t uattr)
15700 {
15701 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15702 	struct bpf_core_relo core_relo = {};
15703 	struct bpf_prog *prog = env->prog;
15704 	const struct btf *btf = prog->aux->btf;
15705 	struct bpf_core_ctx ctx = {
15706 		.log = &env->log,
15707 		.btf = btf,
15708 	};
15709 	bpfptr_t u_core_relo;
15710 	int err;
15711 
15712 	nr_core_relo = attr->core_relo_cnt;
15713 	if (!nr_core_relo)
15714 		return 0;
15715 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15716 		return -EINVAL;
15717 
15718 	rec_size = attr->core_relo_rec_size;
15719 	if (rec_size < MIN_CORE_RELO_SIZE ||
15720 	    rec_size > MAX_CORE_RELO_SIZE ||
15721 	    rec_size % sizeof(u32))
15722 		return -EINVAL;
15723 
15724 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15725 	expected_size = sizeof(struct bpf_core_relo);
15726 	ncopy = min_t(u32, expected_size, rec_size);
15727 
15728 	/* Unlike func_info and line_info, copy and apply each CO-RE
15729 	 * relocation record one at a time.
15730 	 */
15731 	for (i = 0; i < nr_core_relo; i++) {
15732 		/* future proofing when sizeof(bpf_core_relo) changes */
15733 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15734 		if (err) {
15735 			if (err == -E2BIG) {
15736 				verbose(env, "nonzero tailing record in core_relo");
15737 				if (copy_to_bpfptr_offset(uattr,
15738 							  offsetof(union bpf_attr, core_relo_rec_size),
15739 							  &expected_size, sizeof(expected_size)))
15740 					err = -EFAULT;
15741 			}
15742 			break;
15743 		}
15744 
15745 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15746 			err = -EFAULT;
15747 			break;
15748 		}
15749 
15750 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15751 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15752 				i, core_relo.insn_off, prog->len);
15753 			err = -EINVAL;
15754 			break;
15755 		}
15756 
15757 		err = bpf_core_apply(&ctx, &core_relo, i,
15758 				     &prog->insnsi[core_relo.insn_off / 8]);
15759 		if (err)
15760 			break;
15761 		bpfptr_add(&u_core_relo, rec_size);
15762 	}
15763 	return err;
15764 }
15765 
15766 static int check_btf_info(struct bpf_verifier_env *env,
15767 			  const union bpf_attr *attr,
15768 			  bpfptr_t uattr)
15769 {
15770 	struct btf *btf;
15771 	int err;
15772 
15773 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15774 		if (check_abnormal_return(env))
15775 			return -EINVAL;
15776 		return 0;
15777 	}
15778 
15779 	btf = btf_get_by_fd(attr->prog_btf_fd);
15780 	if (IS_ERR(btf))
15781 		return PTR_ERR(btf);
15782 	if (btf_is_kernel(btf)) {
15783 		btf_put(btf);
15784 		return -EACCES;
15785 	}
15786 	env->prog->aux->btf = btf;
15787 
15788 	err = check_btf_func(env, attr, uattr);
15789 	if (err)
15790 		return err;
15791 
15792 	err = check_btf_line(env, attr, uattr);
15793 	if (err)
15794 		return err;
15795 
15796 	err = check_core_relo(env, attr, uattr);
15797 	if (err)
15798 		return err;
15799 
15800 	return 0;
15801 }
15802 
15803 /* check %cur's range satisfies %old's */
15804 static bool range_within(struct bpf_reg_state *old,
15805 			 struct bpf_reg_state *cur)
15806 {
15807 	return old->umin_value <= cur->umin_value &&
15808 	       old->umax_value >= cur->umax_value &&
15809 	       old->smin_value <= cur->smin_value &&
15810 	       old->smax_value >= cur->smax_value &&
15811 	       old->u32_min_value <= cur->u32_min_value &&
15812 	       old->u32_max_value >= cur->u32_max_value &&
15813 	       old->s32_min_value <= cur->s32_min_value &&
15814 	       old->s32_max_value >= cur->s32_max_value;
15815 }
15816 
15817 /* If in the old state two registers had the same id, then they need to have
15818  * the same id in the new state as well.  But that id could be different from
15819  * the old state, so we need to track the mapping from old to new ids.
15820  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15821  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15822  * regs with a different old id could still have new id 9, we don't care about
15823  * that.
15824  * So we look through our idmap to see if this old id has been seen before.  If
15825  * so, we require the new id to match; otherwise, we add the id pair to the map.
15826  */
15827 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15828 {
15829 	struct bpf_id_pair *map = idmap->map;
15830 	unsigned int i;
15831 
15832 	/* either both IDs should be set or both should be zero */
15833 	if (!!old_id != !!cur_id)
15834 		return false;
15835 
15836 	if (old_id == 0) /* cur_id == 0 as well */
15837 		return true;
15838 
15839 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15840 		if (!map[i].old) {
15841 			/* Reached an empty slot; haven't seen this id before */
15842 			map[i].old = old_id;
15843 			map[i].cur = cur_id;
15844 			return true;
15845 		}
15846 		if (map[i].old == old_id)
15847 			return map[i].cur == cur_id;
15848 		if (map[i].cur == cur_id)
15849 			return false;
15850 	}
15851 	/* We ran out of idmap slots, which should be impossible */
15852 	WARN_ON_ONCE(1);
15853 	return false;
15854 }
15855 
15856 /* Similar to check_ids(), but allocate a unique temporary ID
15857  * for 'old_id' or 'cur_id' of zero.
15858  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15859  */
15860 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15861 {
15862 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15863 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15864 
15865 	return check_ids(old_id, cur_id, idmap);
15866 }
15867 
15868 static void clean_func_state(struct bpf_verifier_env *env,
15869 			     struct bpf_func_state *st)
15870 {
15871 	enum bpf_reg_liveness live;
15872 	int i, j;
15873 
15874 	for (i = 0; i < BPF_REG_FP; i++) {
15875 		live = st->regs[i].live;
15876 		/* liveness must not touch this register anymore */
15877 		st->regs[i].live |= REG_LIVE_DONE;
15878 		if (!(live & REG_LIVE_READ))
15879 			/* since the register is unused, clear its state
15880 			 * to make further comparison simpler
15881 			 */
15882 			__mark_reg_not_init(env, &st->regs[i]);
15883 	}
15884 
15885 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15886 		live = st->stack[i].spilled_ptr.live;
15887 		/* liveness must not touch this stack slot anymore */
15888 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15889 		if (!(live & REG_LIVE_READ)) {
15890 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15891 			for (j = 0; j < BPF_REG_SIZE; j++)
15892 				st->stack[i].slot_type[j] = STACK_INVALID;
15893 		}
15894 	}
15895 }
15896 
15897 static void clean_verifier_state(struct bpf_verifier_env *env,
15898 				 struct bpf_verifier_state *st)
15899 {
15900 	int i;
15901 
15902 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15903 		/* all regs in this state in all frames were already marked */
15904 		return;
15905 
15906 	for (i = 0; i <= st->curframe; i++)
15907 		clean_func_state(env, st->frame[i]);
15908 }
15909 
15910 /* the parentage chains form a tree.
15911  * the verifier states are added to state lists at given insn and
15912  * pushed into state stack for future exploration.
15913  * when the verifier reaches bpf_exit insn some of the verifer states
15914  * stored in the state lists have their final liveness state already,
15915  * but a lot of states will get revised from liveness point of view when
15916  * the verifier explores other branches.
15917  * Example:
15918  * 1: r0 = 1
15919  * 2: if r1 == 100 goto pc+1
15920  * 3: r0 = 2
15921  * 4: exit
15922  * when the verifier reaches exit insn the register r0 in the state list of
15923  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15924  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15925  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15926  *
15927  * Since the verifier pushes the branch states as it sees them while exploring
15928  * the program the condition of walking the branch instruction for the second
15929  * time means that all states below this branch were already explored and
15930  * their final liveness marks are already propagated.
15931  * Hence when the verifier completes the search of state list in is_state_visited()
15932  * we can call this clean_live_states() function to mark all liveness states
15933  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15934  * will not be used.
15935  * This function also clears the registers and stack for states that !READ
15936  * to simplify state merging.
15937  *
15938  * Important note here that walking the same branch instruction in the callee
15939  * doesn't meant that the states are DONE. The verifier has to compare
15940  * the callsites
15941  */
15942 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15943 			      struct bpf_verifier_state *cur)
15944 {
15945 	struct bpf_verifier_state_list *sl;
15946 
15947 	sl = *explored_state(env, insn);
15948 	while (sl) {
15949 		if (sl->state.branches)
15950 			goto next;
15951 		if (sl->state.insn_idx != insn ||
15952 		    !same_callsites(&sl->state, cur))
15953 			goto next;
15954 		clean_verifier_state(env, &sl->state);
15955 next:
15956 		sl = sl->next;
15957 	}
15958 }
15959 
15960 static bool regs_exact(const struct bpf_reg_state *rold,
15961 		       const struct bpf_reg_state *rcur,
15962 		       struct bpf_idmap *idmap)
15963 {
15964 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15965 	       check_ids(rold->id, rcur->id, idmap) &&
15966 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15967 }
15968 
15969 /* Returns true if (rold safe implies rcur safe) */
15970 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15971 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15972 {
15973 	if (exact)
15974 		return regs_exact(rold, rcur, idmap);
15975 
15976 	if (!(rold->live & REG_LIVE_READ))
15977 		/* explored state didn't use this */
15978 		return true;
15979 	if (rold->type == NOT_INIT)
15980 		/* explored state can't have used this */
15981 		return true;
15982 	if (rcur->type == NOT_INIT)
15983 		return false;
15984 
15985 	/* Enforce that register types have to match exactly, including their
15986 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15987 	 * rule.
15988 	 *
15989 	 * One can make a point that using a pointer register as unbounded
15990 	 * SCALAR would be technically acceptable, but this could lead to
15991 	 * pointer leaks because scalars are allowed to leak while pointers
15992 	 * are not. We could make this safe in special cases if root is
15993 	 * calling us, but it's probably not worth the hassle.
15994 	 *
15995 	 * Also, register types that are *not* MAYBE_NULL could technically be
15996 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15997 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15998 	 * to the same map).
15999 	 * However, if the old MAYBE_NULL register then got NULL checked,
16000 	 * doing so could have affected others with the same id, and we can't
16001 	 * check for that because we lost the id when we converted to
16002 	 * a non-MAYBE_NULL variant.
16003 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16004 	 * non-MAYBE_NULL registers as well.
16005 	 */
16006 	if (rold->type != rcur->type)
16007 		return false;
16008 
16009 	switch (base_type(rold->type)) {
16010 	case SCALAR_VALUE:
16011 		if (env->explore_alu_limits) {
16012 			/* explore_alu_limits disables tnum_in() and range_within()
16013 			 * logic and requires everything to be strict
16014 			 */
16015 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16016 			       check_scalar_ids(rold->id, rcur->id, idmap);
16017 		}
16018 		if (!rold->precise)
16019 			return true;
16020 		/* Why check_ids() for scalar registers?
16021 		 *
16022 		 * Consider the following BPF code:
16023 		 *   1: r6 = ... unbound scalar, ID=a ...
16024 		 *   2: r7 = ... unbound scalar, ID=b ...
16025 		 *   3: if (r6 > r7) goto +1
16026 		 *   4: r6 = r7
16027 		 *   5: if (r6 > X) goto ...
16028 		 *   6: ... memory operation using r7 ...
16029 		 *
16030 		 * First verification path is [1-6]:
16031 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16032 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16033 		 *   r7 <= X, because r6 and r7 share same id.
16034 		 * Next verification path is [1-4, 6].
16035 		 *
16036 		 * Instruction (6) would be reached in two states:
16037 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16038 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16039 		 *
16040 		 * Use check_ids() to distinguish these states.
16041 		 * ---
16042 		 * Also verify that new value satisfies old value range knowledge.
16043 		 */
16044 		return range_within(rold, rcur) &&
16045 		       tnum_in(rold->var_off, rcur->var_off) &&
16046 		       check_scalar_ids(rold->id, rcur->id, idmap);
16047 	case PTR_TO_MAP_KEY:
16048 	case PTR_TO_MAP_VALUE:
16049 	case PTR_TO_MEM:
16050 	case PTR_TO_BUF:
16051 	case PTR_TO_TP_BUFFER:
16052 		/* If the new min/max/var_off satisfy the old ones and
16053 		 * everything else matches, we are OK.
16054 		 */
16055 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16056 		       range_within(rold, rcur) &&
16057 		       tnum_in(rold->var_off, rcur->var_off) &&
16058 		       check_ids(rold->id, rcur->id, idmap) &&
16059 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16060 	case PTR_TO_PACKET_META:
16061 	case PTR_TO_PACKET:
16062 		/* We must have at least as much range as the old ptr
16063 		 * did, so that any accesses which were safe before are
16064 		 * still safe.  This is true even if old range < old off,
16065 		 * since someone could have accessed through (ptr - k), or
16066 		 * even done ptr -= k in a register, to get a safe access.
16067 		 */
16068 		if (rold->range > rcur->range)
16069 			return false;
16070 		/* If the offsets don't match, we can't trust our alignment;
16071 		 * nor can we be sure that we won't fall out of range.
16072 		 */
16073 		if (rold->off != rcur->off)
16074 			return false;
16075 		/* id relations must be preserved */
16076 		if (!check_ids(rold->id, rcur->id, idmap))
16077 			return false;
16078 		/* new val must satisfy old val knowledge */
16079 		return range_within(rold, rcur) &&
16080 		       tnum_in(rold->var_off, rcur->var_off);
16081 	case PTR_TO_STACK:
16082 		/* two stack pointers are equal only if they're pointing to
16083 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16084 		 */
16085 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16086 	default:
16087 		return regs_exact(rold, rcur, idmap);
16088 	}
16089 }
16090 
16091 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16092 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16093 {
16094 	int i, spi;
16095 
16096 	/* walk slots of the explored stack and ignore any additional
16097 	 * slots in the current stack, since explored(safe) state
16098 	 * didn't use them
16099 	 */
16100 	for (i = 0; i < old->allocated_stack; i++) {
16101 		struct bpf_reg_state *old_reg, *cur_reg;
16102 
16103 		spi = i / BPF_REG_SIZE;
16104 
16105 		if (exact &&
16106 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16107 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16108 			return false;
16109 
16110 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16111 			i += BPF_REG_SIZE - 1;
16112 			/* explored state didn't use this */
16113 			continue;
16114 		}
16115 
16116 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16117 			continue;
16118 
16119 		if (env->allow_uninit_stack &&
16120 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16121 			continue;
16122 
16123 		/* explored stack has more populated slots than current stack
16124 		 * and these slots were used
16125 		 */
16126 		if (i >= cur->allocated_stack)
16127 			return false;
16128 
16129 		/* if old state was safe with misc data in the stack
16130 		 * it will be safe with zero-initialized stack.
16131 		 * The opposite is not true
16132 		 */
16133 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16134 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16135 			continue;
16136 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16137 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16138 			/* Ex: old explored (safe) state has STACK_SPILL in
16139 			 * this stack slot, but current has STACK_MISC ->
16140 			 * this verifier states are not equivalent,
16141 			 * return false to continue verification of this path
16142 			 */
16143 			return false;
16144 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16145 			continue;
16146 		/* Both old and cur are having same slot_type */
16147 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16148 		case STACK_SPILL:
16149 			/* when explored and current stack slot are both storing
16150 			 * spilled registers, check that stored pointers types
16151 			 * are the same as well.
16152 			 * Ex: explored safe path could have stored
16153 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16154 			 * but current path has stored:
16155 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16156 			 * such verifier states are not equivalent.
16157 			 * return false to continue verification of this path
16158 			 */
16159 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16160 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16161 				return false;
16162 			break;
16163 		case STACK_DYNPTR:
16164 			old_reg = &old->stack[spi].spilled_ptr;
16165 			cur_reg = &cur->stack[spi].spilled_ptr;
16166 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16167 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16168 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16169 				return false;
16170 			break;
16171 		case STACK_ITER:
16172 			old_reg = &old->stack[spi].spilled_ptr;
16173 			cur_reg = &cur->stack[spi].spilled_ptr;
16174 			/* iter.depth is not compared between states as it
16175 			 * doesn't matter for correctness and would otherwise
16176 			 * prevent convergence; we maintain it only to prevent
16177 			 * infinite loop check triggering, see
16178 			 * iter_active_depths_differ()
16179 			 */
16180 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16181 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16182 			    old_reg->iter.state != cur_reg->iter.state ||
16183 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16184 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16185 				return false;
16186 			break;
16187 		case STACK_MISC:
16188 		case STACK_ZERO:
16189 		case STACK_INVALID:
16190 			continue;
16191 		/* Ensure that new unhandled slot types return false by default */
16192 		default:
16193 			return false;
16194 		}
16195 	}
16196 	return true;
16197 }
16198 
16199 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16200 		    struct bpf_idmap *idmap)
16201 {
16202 	int i;
16203 
16204 	if (old->acquired_refs != cur->acquired_refs)
16205 		return false;
16206 
16207 	for (i = 0; i < old->acquired_refs; i++) {
16208 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16209 			return false;
16210 	}
16211 
16212 	return true;
16213 }
16214 
16215 /* compare two verifier states
16216  *
16217  * all states stored in state_list are known to be valid, since
16218  * verifier reached 'bpf_exit' instruction through them
16219  *
16220  * this function is called when verifier exploring different branches of
16221  * execution popped from the state stack. If it sees an old state that has
16222  * more strict register state and more strict stack state then this execution
16223  * branch doesn't need to be explored further, since verifier already
16224  * concluded that more strict state leads to valid finish.
16225  *
16226  * Therefore two states are equivalent if register state is more conservative
16227  * and explored stack state is more conservative than the current one.
16228  * Example:
16229  *       explored                   current
16230  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16231  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16232  *
16233  * In other words if current stack state (one being explored) has more
16234  * valid slots than old one that already passed validation, it means
16235  * the verifier can stop exploring and conclude that current state is valid too
16236  *
16237  * Similarly with registers. If explored state has register type as invalid
16238  * whereas register type in current state is meaningful, it means that
16239  * the current state will reach 'bpf_exit' instruction safely
16240  */
16241 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16242 			      struct bpf_func_state *cur, bool exact)
16243 {
16244 	int i;
16245 
16246 	if (old->callback_depth > cur->callback_depth)
16247 		return false;
16248 
16249 	for (i = 0; i < MAX_BPF_REG; i++)
16250 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16251 			     &env->idmap_scratch, exact))
16252 			return false;
16253 
16254 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16255 		return false;
16256 
16257 	if (!refsafe(old, cur, &env->idmap_scratch))
16258 		return false;
16259 
16260 	return true;
16261 }
16262 
16263 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16264 {
16265 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16266 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16267 }
16268 
16269 static bool states_equal(struct bpf_verifier_env *env,
16270 			 struct bpf_verifier_state *old,
16271 			 struct bpf_verifier_state *cur,
16272 			 bool exact)
16273 {
16274 	int i;
16275 
16276 	if (old->curframe != cur->curframe)
16277 		return false;
16278 
16279 	reset_idmap_scratch(env);
16280 
16281 	/* Verification state from speculative execution simulation
16282 	 * must never prune a non-speculative execution one.
16283 	 */
16284 	if (old->speculative && !cur->speculative)
16285 		return false;
16286 
16287 	if (old->active_lock.ptr != cur->active_lock.ptr)
16288 		return false;
16289 
16290 	/* Old and cur active_lock's have to be either both present
16291 	 * or both absent.
16292 	 */
16293 	if (!!old->active_lock.id != !!cur->active_lock.id)
16294 		return false;
16295 
16296 	if (old->active_lock.id &&
16297 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16298 		return false;
16299 
16300 	if (old->active_rcu_lock != cur->active_rcu_lock)
16301 		return false;
16302 
16303 	/* for states to be equal callsites have to be the same
16304 	 * and all frame states need to be equivalent
16305 	 */
16306 	for (i = 0; i <= old->curframe; i++) {
16307 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16308 			return false;
16309 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16310 			return false;
16311 	}
16312 	return true;
16313 }
16314 
16315 /* Return 0 if no propagation happened. Return negative error code if error
16316  * happened. Otherwise, return the propagated bit.
16317  */
16318 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16319 				  struct bpf_reg_state *reg,
16320 				  struct bpf_reg_state *parent_reg)
16321 {
16322 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16323 	u8 flag = reg->live & REG_LIVE_READ;
16324 	int err;
16325 
16326 	/* When comes here, read flags of PARENT_REG or REG could be any of
16327 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16328 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16329 	 */
16330 	if (parent_flag == REG_LIVE_READ64 ||
16331 	    /* Or if there is no read flag from REG. */
16332 	    !flag ||
16333 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16334 	    parent_flag == flag)
16335 		return 0;
16336 
16337 	err = mark_reg_read(env, reg, parent_reg, flag);
16338 	if (err)
16339 		return err;
16340 
16341 	return flag;
16342 }
16343 
16344 /* A write screens off any subsequent reads; but write marks come from the
16345  * straight-line code between a state and its parent.  When we arrive at an
16346  * equivalent state (jump target or such) we didn't arrive by the straight-line
16347  * code, so read marks in the state must propagate to the parent regardless
16348  * of the state's write marks. That's what 'parent == state->parent' comparison
16349  * in mark_reg_read() is for.
16350  */
16351 static int propagate_liveness(struct bpf_verifier_env *env,
16352 			      const struct bpf_verifier_state *vstate,
16353 			      struct bpf_verifier_state *vparent)
16354 {
16355 	struct bpf_reg_state *state_reg, *parent_reg;
16356 	struct bpf_func_state *state, *parent;
16357 	int i, frame, err = 0;
16358 
16359 	if (vparent->curframe != vstate->curframe) {
16360 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16361 		     vparent->curframe, vstate->curframe);
16362 		return -EFAULT;
16363 	}
16364 	/* Propagate read liveness of registers... */
16365 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16366 	for (frame = 0; frame <= vstate->curframe; frame++) {
16367 		parent = vparent->frame[frame];
16368 		state = vstate->frame[frame];
16369 		parent_reg = parent->regs;
16370 		state_reg = state->regs;
16371 		/* We don't need to worry about FP liveness, it's read-only */
16372 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16373 			err = propagate_liveness_reg(env, &state_reg[i],
16374 						     &parent_reg[i]);
16375 			if (err < 0)
16376 				return err;
16377 			if (err == REG_LIVE_READ64)
16378 				mark_insn_zext(env, &parent_reg[i]);
16379 		}
16380 
16381 		/* Propagate stack slots. */
16382 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16383 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16384 			parent_reg = &parent->stack[i].spilled_ptr;
16385 			state_reg = &state->stack[i].spilled_ptr;
16386 			err = propagate_liveness_reg(env, state_reg,
16387 						     parent_reg);
16388 			if (err < 0)
16389 				return err;
16390 		}
16391 	}
16392 	return 0;
16393 }
16394 
16395 /* find precise scalars in the previous equivalent state and
16396  * propagate them into the current state
16397  */
16398 static int propagate_precision(struct bpf_verifier_env *env,
16399 			       const struct bpf_verifier_state *old)
16400 {
16401 	struct bpf_reg_state *state_reg;
16402 	struct bpf_func_state *state;
16403 	int i, err = 0, fr;
16404 	bool first;
16405 
16406 	for (fr = old->curframe; fr >= 0; fr--) {
16407 		state = old->frame[fr];
16408 		state_reg = state->regs;
16409 		first = true;
16410 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16411 			if (state_reg->type != SCALAR_VALUE ||
16412 			    !state_reg->precise ||
16413 			    !(state_reg->live & REG_LIVE_READ))
16414 				continue;
16415 			if (env->log.level & BPF_LOG_LEVEL2) {
16416 				if (first)
16417 					verbose(env, "frame %d: propagating r%d", fr, i);
16418 				else
16419 					verbose(env, ",r%d", i);
16420 			}
16421 			bt_set_frame_reg(&env->bt, fr, i);
16422 			first = false;
16423 		}
16424 
16425 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16426 			if (!is_spilled_reg(&state->stack[i]))
16427 				continue;
16428 			state_reg = &state->stack[i].spilled_ptr;
16429 			if (state_reg->type != SCALAR_VALUE ||
16430 			    !state_reg->precise ||
16431 			    !(state_reg->live & REG_LIVE_READ))
16432 				continue;
16433 			if (env->log.level & BPF_LOG_LEVEL2) {
16434 				if (first)
16435 					verbose(env, "frame %d: propagating fp%d",
16436 						fr, (-i - 1) * BPF_REG_SIZE);
16437 				else
16438 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16439 			}
16440 			bt_set_frame_slot(&env->bt, fr, i);
16441 			first = false;
16442 		}
16443 		if (!first)
16444 			verbose(env, "\n");
16445 	}
16446 
16447 	err = mark_chain_precision_batch(env);
16448 	if (err < 0)
16449 		return err;
16450 
16451 	return 0;
16452 }
16453 
16454 static bool states_maybe_looping(struct bpf_verifier_state *old,
16455 				 struct bpf_verifier_state *cur)
16456 {
16457 	struct bpf_func_state *fold, *fcur;
16458 	int i, fr = cur->curframe;
16459 
16460 	if (old->curframe != fr)
16461 		return false;
16462 
16463 	fold = old->frame[fr];
16464 	fcur = cur->frame[fr];
16465 	for (i = 0; i < MAX_BPF_REG; i++)
16466 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16467 			   offsetof(struct bpf_reg_state, parent)))
16468 			return false;
16469 	return true;
16470 }
16471 
16472 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16473 {
16474 	return env->insn_aux_data[insn_idx].is_iter_next;
16475 }
16476 
16477 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16478  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16479  * states to match, which otherwise would look like an infinite loop. So while
16480  * iter_next() calls are taken care of, we still need to be careful and
16481  * prevent erroneous and too eager declaration of "ininite loop", when
16482  * iterators are involved.
16483  *
16484  * Here's a situation in pseudo-BPF assembly form:
16485  *
16486  *   0: again:                          ; set up iter_next() call args
16487  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16488  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16489  *   3:   if r0 == 0 goto done
16490  *   4:   ... something useful here ...
16491  *   5:   goto again                    ; another iteration
16492  *   6: done:
16493  *   7:   r1 = &it
16494  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16495  *   9:   exit
16496  *
16497  * This is a typical loop. Let's assume that we have a prune point at 1:,
16498  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16499  * again`, assuming other heuristics don't get in a way).
16500  *
16501  * When we first time come to 1:, let's say we have some state X. We proceed
16502  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16503  * Now we come back to validate that forked ACTIVE state. We proceed through
16504  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16505  * are converging. But the problem is that we don't know that yet, as this
16506  * convergence has to happen at iter_next() call site only. So if nothing is
16507  * done, at 1: verifier will use bounded loop logic and declare infinite
16508  * looping (and would be *technically* correct, if not for iterator's
16509  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16510  * don't want that. So what we do in process_iter_next_call() when we go on
16511  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16512  * a different iteration. So when we suspect an infinite loop, we additionally
16513  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16514  * pretend we are not looping and wait for next iter_next() call.
16515  *
16516  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16517  * loop, because that would actually mean infinite loop, as DRAINED state is
16518  * "sticky", and so we'll keep returning into the same instruction with the
16519  * same state (at least in one of possible code paths).
16520  *
16521  * This approach allows to keep infinite loop heuristic even in the face of
16522  * active iterator. E.g., C snippet below is and will be detected as
16523  * inifintely looping:
16524  *
16525  *   struct bpf_iter_num it;
16526  *   int *p, x;
16527  *
16528  *   bpf_iter_num_new(&it, 0, 10);
16529  *   while ((p = bpf_iter_num_next(&t))) {
16530  *       x = p;
16531  *       while (x--) {} // <<-- infinite loop here
16532  *   }
16533  *
16534  */
16535 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16536 {
16537 	struct bpf_reg_state *slot, *cur_slot;
16538 	struct bpf_func_state *state;
16539 	int i, fr;
16540 
16541 	for (fr = old->curframe; fr >= 0; fr--) {
16542 		state = old->frame[fr];
16543 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16544 			if (state->stack[i].slot_type[0] != STACK_ITER)
16545 				continue;
16546 
16547 			slot = &state->stack[i].spilled_ptr;
16548 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16549 				continue;
16550 
16551 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16552 			if (cur_slot->iter.depth != slot->iter.depth)
16553 				return true;
16554 		}
16555 	}
16556 	return false;
16557 }
16558 
16559 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16560 {
16561 	struct bpf_verifier_state_list *new_sl;
16562 	struct bpf_verifier_state_list *sl, **pprev;
16563 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16564 	int i, j, n, err, states_cnt = 0;
16565 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16566 	bool add_new_state = force_new_state;
16567 	bool force_exact;
16568 
16569 	/* bpf progs typically have pruning point every 4 instructions
16570 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16571 	 * Do not add new state for future pruning if the verifier hasn't seen
16572 	 * at least 2 jumps and at least 8 instructions.
16573 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16574 	 * In tests that amounts to up to 50% reduction into total verifier
16575 	 * memory consumption and 20% verifier time speedup.
16576 	 */
16577 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16578 	    env->insn_processed - env->prev_insn_processed >= 8)
16579 		add_new_state = true;
16580 
16581 	pprev = explored_state(env, insn_idx);
16582 	sl = *pprev;
16583 
16584 	clean_live_states(env, insn_idx, cur);
16585 
16586 	while (sl) {
16587 		states_cnt++;
16588 		if (sl->state.insn_idx != insn_idx)
16589 			goto next;
16590 
16591 		if (sl->state.branches) {
16592 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16593 
16594 			if (frame->in_async_callback_fn &&
16595 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16596 				/* Different async_entry_cnt means that the verifier is
16597 				 * processing another entry into async callback.
16598 				 * Seeing the same state is not an indication of infinite
16599 				 * loop or infinite recursion.
16600 				 * But finding the same state doesn't mean that it's safe
16601 				 * to stop processing the current state. The previous state
16602 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16603 				 * Checking in_async_callback_fn alone is not enough either.
16604 				 * Since the verifier still needs to catch infinite loops
16605 				 * inside async callbacks.
16606 				 */
16607 				goto skip_inf_loop_check;
16608 			}
16609 			/* BPF open-coded iterators loop detection is special.
16610 			 * states_maybe_looping() logic is too simplistic in detecting
16611 			 * states that *might* be equivalent, because it doesn't know
16612 			 * about ID remapping, so don't even perform it.
16613 			 * See process_iter_next_call() and iter_active_depths_differ()
16614 			 * for overview of the logic. When current and one of parent
16615 			 * states are detected as equivalent, it's a good thing: we prove
16616 			 * convergence and can stop simulating further iterations.
16617 			 * It's safe to assume that iterator loop will finish, taking into
16618 			 * account iter_next() contract of eventually returning
16619 			 * sticky NULL result.
16620 			 *
16621 			 * Note, that states have to be compared exactly in this case because
16622 			 * read and precision marks might not be finalized inside the loop.
16623 			 * E.g. as in the program below:
16624 			 *
16625 			 *     1. r7 = -16
16626 			 *     2. r6 = bpf_get_prandom_u32()
16627 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16628 			 *     4.   if (r6 != 42) {
16629 			 *     5.     r7 = -32
16630 			 *     6.     r6 = bpf_get_prandom_u32()
16631 			 *     7.     continue
16632 			 *     8.   }
16633 			 *     9.   r0 = r10
16634 			 *    10.   r0 += r7
16635 			 *    11.   r8 = *(u64 *)(r0 + 0)
16636 			 *    12.   r6 = bpf_get_prandom_u32()
16637 			 *    13. }
16638 			 *
16639 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16640 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16641 			 * not have read or precision mark for r7 yet, thus inexact states
16642 			 * comparison would discard current state with r7=-32
16643 			 * => unsafe memory access at 11 would not be caught.
16644 			 */
16645 			if (is_iter_next_insn(env, insn_idx)) {
16646 				if (states_equal(env, &sl->state, cur, true)) {
16647 					struct bpf_func_state *cur_frame;
16648 					struct bpf_reg_state *iter_state, *iter_reg;
16649 					int spi;
16650 
16651 					cur_frame = cur->frame[cur->curframe];
16652 					/* btf_check_iter_kfuncs() enforces that
16653 					 * iter state pointer is always the first arg
16654 					 */
16655 					iter_reg = &cur_frame->regs[BPF_REG_1];
16656 					/* current state is valid due to states_equal(),
16657 					 * so we can assume valid iter and reg state,
16658 					 * no need for extra (re-)validations
16659 					 */
16660 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16661 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16662 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16663 						update_loop_entry(cur, &sl->state);
16664 						goto hit;
16665 					}
16666 				}
16667 				goto skip_inf_loop_check;
16668 			}
16669 			if (calls_callback(env, insn_idx)) {
16670 				if (states_equal(env, &sl->state, cur, true))
16671 					goto hit;
16672 				goto skip_inf_loop_check;
16673 			}
16674 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16675 			if (states_maybe_looping(&sl->state, cur) &&
16676 			    states_equal(env, &sl->state, cur, false) &&
16677 			    !iter_active_depths_differ(&sl->state, cur) &&
16678 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16679 				verbose_linfo(env, insn_idx, "; ");
16680 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16681 				verbose(env, "cur state:");
16682 				print_verifier_state(env, cur->frame[cur->curframe], true);
16683 				verbose(env, "old state:");
16684 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16685 				return -EINVAL;
16686 			}
16687 			/* if the verifier is processing a loop, avoid adding new state
16688 			 * too often, since different loop iterations have distinct
16689 			 * states and may not help future pruning.
16690 			 * This threshold shouldn't be too low to make sure that
16691 			 * a loop with large bound will be rejected quickly.
16692 			 * The most abusive loop will be:
16693 			 * r1 += 1
16694 			 * if r1 < 1000000 goto pc-2
16695 			 * 1M insn_procssed limit / 100 == 10k peak states.
16696 			 * This threshold shouldn't be too high either, since states
16697 			 * at the end of the loop are likely to be useful in pruning.
16698 			 */
16699 skip_inf_loop_check:
16700 			if (!force_new_state &&
16701 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16702 			    env->insn_processed - env->prev_insn_processed < 100)
16703 				add_new_state = false;
16704 			goto miss;
16705 		}
16706 		/* If sl->state is a part of a loop and this loop's entry is a part of
16707 		 * current verification path then states have to be compared exactly.
16708 		 * 'force_exact' is needed to catch the following case:
16709 		 *
16710 		 *                initial     Here state 'succ' was processed first,
16711 		 *                  |         it was eventually tracked to produce a
16712 		 *                  V         state identical to 'hdr'.
16713 		 *     .---------> hdr        All branches from 'succ' had been explored
16714 		 *     |            |         and thus 'succ' has its .branches == 0.
16715 		 *     |            V
16716 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16717 		 *     |    |       |         to the same instruction + callsites.
16718 		 *     |    V       V         In such case it is necessary to check
16719 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16720 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16721 		 *     |    V       V         same loop exact flag has to be set.
16722 		 *     |   succ <- cur        To check if that is the case, verify
16723 		 *     |    |                 if loop entry of 'succ' is in current
16724 		 *     |    V                 DFS path.
16725 		 *     |   ...
16726 		 *     |    |
16727 		 *     '----'
16728 		 *
16729 		 * Additional details are in the comment before get_loop_entry().
16730 		 */
16731 		loop_entry = get_loop_entry(&sl->state);
16732 		force_exact = loop_entry && loop_entry->branches > 0;
16733 		if (states_equal(env, &sl->state, cur, force_exact)) {
16734 			if (force_exact)
16735 				update_loop_entry(cur, loop_entry);
16736 hit:
16737 			sl->hit_cnt++;
16738 			/* reached equivalent register/stack state,
16739 			 * prune the search.
16740 			 * Registers read by the continuation are read by us.
16741 			 * If we have any write marks in env->cur_state, they
16742 			 * will prevent corresponding reads in the continuation
16743 			 * from reaching our parent (an explored_state).  Our
16744 			 * own state will get the read marks recorded, but
16745 			 * they'll be immediately forgotten as we're pruning
16746 			 * this state and will pop a new one.
16747 			 */
16748 			err = propagate_liveness(env, &sl->state, cur);
16749 
16750 			/* if previous state reached the exit with precision and
16751 			 * current state is equivalent to it (except precsion marks)
16752 			 * the precision needs to be propagated back in
16753 			 * the current state.
16754 			 */
16755 			err = err ? : push_jmp_history(env, cur);
16756 			err = err ? : propagate_precision(env, &sl->state);
16757 			if (err)
16758 				return err;
16759 			return 1;
16760 		}
16761 miss:
16762 		/* when new state is not going to be added do not increase miss count.
16763 		 * Otherwise several loop iterations will remove the state
16764 		 * recorded earlier. The goal of these heuristics is to have
16765 		 * states from some iterations of the loop (some in the beginning
16766 		 * and some at the end) to help pruning.
16767 		 */
16768 		if (add_new_state)
16769 			sl->miss_cnt++;
16770 		/* heuristic to determine whether this state is beneficial
16771 		 * to keep checking from state equivalence point of view.
16772 		 * Higher numbers increase max_states_per_insn and verification time,
16773 		 * but do not meaningfully decrease insn_processed.
16774 		 * 'n' controls how many times state could miss before eviction.
16775 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16776 		 * too early would hinder iterator convergence.
16777 		 */
16778 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16779 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16780 			/* the state is unlikely to be useful. Remove it to
16781 			 * speed up verification
16782 			 */
16783 			*pprev = sl->next;
16784 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16785 			    !sl->state.used_as_loop_entry) {
16786 				u32 br = sl->state.branches;
16787 
16788 				WARN_ONCE(br,
16789 					  "BUG live_done but branches_to_explore %d\n",
16790 					  br);
16791 				free_verifier_state(&sl->state, false);
16792 				kfree(sl);
16793 				env->peak_states--;
16794 			} else {
16795 				/* cannot free this state, since parentage chain may
16796 				 * walk it later. Add it for free_list instead to
16797 				 * be freed at the end of verification
16798 				 */
16799 				sl->next = env->free_list;
16800 				env->free_list = sl;
16801 			}
16802 			sl = *pprev;
16803 			continue;
16804 		}
16805 next:
16806 		pprev = &sl->next;
16807 		sl = *pprev;
16808 	}
16809 
16810 	if (env->max_states_per_insn < states_cnt)
16811 		env->max_states_per_insn = states_cnt;
16812 
16813 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16814 		return 0;
16815 
16816 	if (!add_new_state)
16817 		return 0;
16818 
16819 	/* There were no equivalent states, remember the current one.
16820 	 * Technically the current state is not proven to be safe yet,
16821 	 * but it will either reach outer most bpf_exit (which means it's safe)
16822 	 * or it will be rejected. When there are no loops the verifier won't be
16823 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16824 	 * again on the way to bpf_exit.
16825 	 * When looping the sl->state.branches will be > 0 and this state
16826 	 * will not be considered for equivalence until branches == 0.
16827 	 */
16828 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16829 	if (!new_sl)
16830 		return -ENOMEM;
16831 	env->total_states++;
16832 	env->peak_states++;
16833 	env->prev_jmps_processed = env->jmps_processed;
16834 	env->prev_insn_processed = env->insn_processed;
16835 
16836 	/* forget precise markings we inherited, see __mark_chain_precision */
16837 	if (env->bpf_capable)
16838 		mark_all_scalars_imprecise(env, cur);
16839 
16840 	/* add new state to the head of linked list */
16841 	new = &new_sl->state;
16842 	err = copy_verifier_state(new, cur);
16843 	if (err) {
16844 		free_verifier_state(new, false);
16845 		kfree(new_sl);
16846 		return err;
16847 	}
16848 	new->insn_idx = insn_idx;
16849 	WARN_ONCE(new->branches != 1,
16850 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16851 
16852 	cur->parent = new;
16853 	cur->first_insn_idx = insn_idx;
16854 	cur->dfs_depth = new->dfs_depth + 1;
16855 	clear_jmp_history(cur);
16856 	new_sl->next = *explored_state(env, insn_idx);
16857 	*explored_state(env, insn_idx) = new_sl;
16858 	/* connect new state to parentage chain. Current frame needs all
16859 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16860 	 * to the stack implicitly by JITs) so in callers' frames connect just
16861 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16862 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16863 	 * from callee with its full parentage chain, anyway.
16864 	 */
16865 	/* clear write marks in current state: the writes we did are not writes
16866 	 * our child did, so they don't screen off its reads from us.
16867 	 * (There are no read marks in current state, because reads always mark
16868 	 * their parent and current state never has children yet.  Only
16869 	 * explored_states can get read marks.)
16870 	 */
16871 	for (j = 0; j <= cur->curframe; j++) {
16872 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16873 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16874 		for (i = 0; i < BPF_REG_FP; i++)
16875 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16876 	}
16877 
16878 	/* all stack frames are accessible from callee, clear them all */
16879 	for (j = 0; j <= cur->curframe; j++) {
16880 		struct bpf_func_state *frame = cur->frame[j];
16881 		struct bpf_func_state *newframe = new->frame[j];
16882 
16883 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16884 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16885 			frame->stack[i].spilled_ptr.parent =
16886 						&newframe->stack[i].spilled_ptr;
16887 		}
16888 	}
16889 	return 0;
16890 }
16891 
16892 /* Return true if it's OK to have the same insn return a different type. */
16893 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16894 {
16895 	switch (base_type(type)) {
16896 	case PTR_TO_CTX:
16897 	case PTR_TO_SOCKET:
16898 	case PTR_TO_SOCK_COMMON:
16899 	case PTR_TO_TCP_SOCK:
16900 	case PTR_TO_XDP_SOCK:
16901 	case PTR_TO_BTF_ID:
16902 		return false;
16903 	default:
16904 		return true;
16905 	}
16906 }
16907 
16908 /* If an instruction was previously used with particular pointer types, then we
16909  * need to be careful to avoid cases such as the below, where it may be ok
16910  * for one branch accessing the pointer, but not ok for the other branch:
16911  *
16912  * R1 = sock_ptr
16913  * goto X;
16914  * ...
16915  * R1 = some_other_valid_ptr;
16916  * goto X;
16917  * ...
16918  * R2 = *(u32 *)(R1 + 0);
16919  */
16920 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16921 {
16922 	return src != prev && (!reg_type_mismatch_ok(src) ||
16923 			       !reg_type_mismatch_ok(prev));
16924 }
16925 
16926 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16927 			     bool allow_trust_missmatch)
16928 {
16929 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16930 
16931 	if (*prev_type == NOT_INIT) {
16932 		/* Saw a valid insn
16933 		 * dst_reg = *(u32 *)(src_reg + off)
16934 		 * save type to validate intersecting paths
16935 		 */
16936 		*prev_type = type;
16937 	} else if (reg_type_mismatch(type, *prev_type)) {
16938 		/* Abuser program is trying to use the same insn
16939 		 * dst_reg = *(u32*) (src_reg + off)
16940 		 * with different pointer types:
16941 		 * src_reg == ctx in one branch and
16942 		 * src_reg == stack|map in some other branch.
16943 		 * Reject it.
16944 		 */
16945 		if (allow_trust_missmatch &&
16946 		    base_type(type) == PTR_TO_BTF_ID &&
16947 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16948 			/*
16949 			 * Have to support a use case when one path through
16950 			 * the program yields TRUSTED pointer while another
16951 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16952 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16953 			 */
16954 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16955 		} else {
16956 			verbose(env, "same insn cannot be used with different pointers\n");
16957 			return -EINVAL;
16958 		}
16959 	}
16960 
16961 	return 0;
16962 }
16963 
16964 static int do_check(struct bpf_verifier_env *env)
16965 {
16966 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16967 	struct bpf_verifier_state *state = env->cur_state;
16968 	struct bpf_insn *insns = env->prog->insnsi;
16969 	struct bpf_reg_state *regs;
16970 	int insn_cnt = env->prog->len;
16971 	bool do_print_state = false;
16972 	int prev_insn_idx = -1;
16973 
16974 	for (;;) {
16975 		struct bpf_insn *insn;
16976 		u8 class;
16977 		int err;
16978 
16979 		env->prev_insn_idx = prev_insn_idx;
16980 		if (env->insn_idx >= insn_cnt) {
16981 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
16982 				env->insn_idx, insn_cnt);
16983 			return -EFAULT;
16984 		}
16985 
16986 		insn = &insns[env->insn_idx];
16987 		class = BPF_CLASS(insn->code);
16988 
16989 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16990 			verbose(env,
16991 				"BPF program is too large. Processed %d insn\n",
16992 				env->insn_processed);
16993 			return -E2BIG;
16994 		}
16995 
16996 		state->last_insn_idx = env->prev_insn_idx;
16997 
16998 		if (is_prune_point(env, env->insn_idx)) {
16999 			err = is_state_visited(env, env->insn_idx);
17000 			if (err < 0)
17001 				return err;
17002 			if (err == 1) {
17003 				/* found equivalent state, can prune the search */
17004 				if (env->log.level & BPF_LOG_LEVEL) {
17005 					if (do_print_state)
17006 						verbose(env, "\nfrom %d to %d%s: safe\n",
17007 							env->prev_insn_idx, env->insn_idx,
17008 							env->cur_state->speculative ?
17009 							" (speculative execution)" : "");
17010 					else
17011 						verbose(env, "%d: safe\n", env->insn_idx);
17012 				}
17013 				goto process_bpf_exit;
17014 			}
17015 		}
17016 
17017 		if (is_jmp_point(env, env->insn_idx)) {
17018 			err = push_jmp_history(env, state);
17019 			if (err)
17020 				return err;
17021 		}
17022 
17023 		if (signal_pending(current))
17024 			return -EAGAIN;
17025 
17026 		if (need_resched())
17027 			cond_resched();
17028 
17029 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17030 			verbose(env, "\nfrom %d to %d%s:",
17031 				env->prev_insn_idx, env->insn_idx,
17032 				env->cur_state->speculative ?
17033 				" (speculative execution)" : "");
17034 			print_verifier_state(env, state->frame[state->curframe], true);
17035 			do_print_state = false;
17036 		}
17037 
17038 		if (env->log.level & BPF_LOG_LEVEL) {
17039 			const struct bpf_insn_cbs cbs = {
17040 				.cb_call	= disasm_kfunc_name,
17041 				.cb_print	= verbose,
17042 				.private_data	= env,
17043 			};
17044 
17045 			if (verifier_state_scratched(env))
17046 				print_insn_state(env, state->frame[state->curframe]);
17047 
17048 			verbose_linfo(env, env->insn_idx, "; ");
17049 			env->prev_log_pos = env->log.end_pos;
17050 			verbose(env, "%d: ", env->insn_idx);
17051 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17052 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17053 			env->prev_log_pos = env->log.end_pos;
17054 		}
17055 
17056 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17057 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17058 							   env->prev_insn_idx);
17059 			if (err)
17060 				return err;
17061 		}
17062 
17063 		regs = cur_regs(env);
17064 		sanitize_mark_insn_seen(env);
17065 		prev_insn_idx = env->insn_idx;
17066 
17067 		if (class == BPF_ALU || class == BPF_ALU64) {
17068 			err = check_alu_op(env, insn);
17069 			if (err)
17070 				return err;
17071 
17072 		} else if (class == BPF_LDX) {
17073 			enum bpf_reg_type src_reg_type;
17074 
17075 			/* check for reserved fields is already done */
17076 
17077 			/* check src operand */
17078 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17079 			if (err)
17080 				return err;
17081 
17082 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17083 			if (err)
17084 				return err;
17085 
17086 			src_reg_type = regs[insn->src_reg].type;
17087 
17088 			/* check that memory (src_reg + off) is readable,
17089 			 * the state of dst_reg will be updated by this func
17090 			 */
17091 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17092 					       insn->off, BPF_SIZE(insn->code),
17093 					       BPF_READ, insn->dst_reg, false,
17094 					       BPF_MODE(insn->code) == BPF_MEMSX);
17095 			if (err)
17096 				return err;
17097 
17098 			err = save_aux_ptr_type(env, src_reg_type, true);
17099 			if (err)
17100 				return err;
17101 		} else if (class == BPF_STX) {
17102 			enum bpf_reg_type dst_reg_type;
17103 
17104 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17105 				err = check_atomic(env, env->insn_idx, insn);
17106 				if (err)
17107 					return err;
17108 				env->insn_idx++;
17109 				continue;
17110 			}
17111 
17112 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17113 				verbose(env, "BPF_STX uses reserved fields\n");
17114 				return -EINVAL;
17115 			}
17116 
17117 			/* check src1 operand */
17118 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17119 			if (err)
17120 				return err;
17121 			/* check src2 operand */
17122 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17123 			if (err)
17124 				return err;
17125 
17126 			dst_reg_type = regs[insn->dst_reg].type;
17127 
17128 			/* check that memory (dst_reg + off) is writeable */
17129 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17130 					       insn->off, BPF_SIZE(insn->code),
17131 					       BPF_WRITE, insn->src_reg, false, false);
17132 			if (err)
17133 				return err;
17134 
17135 			err = save_aux_ptr_type(env, dst_reg_type, false);
17136 			if (err)
17137 				return err;
17138 		} else if (class == BPF_ST) {
17139 			enum bpf_reg_type dst_reg_type;
17140 
17141 			if (BPF_MODE(insn->code) != BPF_MEM ||
17142 			    insn->src_reg != BPF_REG_0) {
17143 				verbose(env, "BPF_ST uses reserved fields\n");
17144 				return -EINVAL;
17145 			}
17146 			/* check src operand */
17147 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17148 			if (err)
17149 				return err;
17150 
17151 			dst_reg_type = regs[insn->dst_reg].type;
17152 
17153 			/* check that memory (dst_reg + off) is writeable */
17154 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17155 					       insn->off, BPF_SIZE(insn->code),
17156 					       BPF_WRITE, -1, false, false);
17157 			if (err)
17158 				return err;
17159 
17160 			err = save_aux_ptr_type(env, dst_reg_type, false);
17161 			if (err)
17162 				return err;
17163 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17164 			u8 opcode = BPF_OP(insn->code);
17165 
17166 			env->jmps_processed++;
17167 			if (opcode == BPF_CALL) {
17168 				if (BPF_SRC(insn->code) != BPF_K ||
17169 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17170 				     && insn->off != 0) ||
17171 				    (insn->src_reg != BPF_REG_0 &&
17172 				     insn->src_reg != BPF_PSEUDO_CALL &&
17173 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17174 				    insn->dst_reg != BPF_REG_0 ||
17175 				    class == BPF_JMP32) {
17176 					verbose(env, "BPF_CALL uses reserved fields\n");
17177 					return -EINVAL;
17178 				}
17179 
17180 				if (env->cur_state->active_lock.ptr) {
17181 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17182 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17183 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17184 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17185 						verbose(env, "function calls are not allowed while holding a lock\n");
17186 						return -EINVAL;
17187 					}
17188 				}
17189 				if (insn->src_reg == BPF_PSEUDO_CALL)
17190 					err = check_func_call(env, insn, &env->insn_idx);
17191 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17192 					err = check_kfunc_call(env, insn, &env->insn_idx);
17193 				else
17194 					err = check_helper_call(env, insn, &env->insn_idx);
17195 				if (err)
17196 					return err;
17197 
17198 				mark_reg_scratched(env, BPF_REG_0);
17199 			} else if (opcode == BPF_JA) {
17200 				if (BPF_SRC(insn->code) != BPF_K ||
17201 				    insn->src_reg != BPF_REG_0 ||
17202 				    insn->dst_reg != BPF_REG_0 ||
17203 				    (class == BPF_JMP && insn->imm != 0) ||
17204 				    (class == BPF_JMP32 && insn->off != 0)) {
17205 					verbose(env, "BPF_JA uses reserved fields\n");
17206 					return -EINVAL;
17207 				}
17208 
17209 				if (class == BPF_JMP)
17210 					env->insn_idx += insn->off + 1;
17211 				else
17212 					env->insn_idx += insn->imm + 1;
17213 				continue;
17214 
17215 			} else if (opcode == BPF_EXIT) {
17216 				if (BPF_SRC(insn->code) != BPF_K ||
17217 				    insn->imm != 0 ||
17218 				    insn->src_reg != BPF_REG_0 ||
17219 				    insn->dst_reg != BPF_REG_0 ||
17220 				    class == BPF_JMP32) {
17221 					verbose(env, "BPF_EXIT uses reserved fields\n");
17222 					return -EINVAL;
17223 				}
17224 
17225 				if (env->cur_state->active_lock.ptr &&
17226 				    !in_rbtree_lock_required_cb(env)) {
17227 					verbose(env, "bpf_spin_unlock is missing\n");
17228 					return -EINVAL;
17229 				}
17230 
17231 				if (env->cur_state->active_rcu_lock &&
17232 				    !in_rbtree_lock_required_cb(env)) {
17233 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17234 					return -EINVAL;
17235 				}
17236 
17237 				/* We must do check_reference_leak here before
17238 				 * prepare_func_exit to handle the case when
17239 				 * state->curframe > 0, it may be a callback
17240 				 * function, for which reference_state must
17241 				 * match caller reference state when it exits.
17242 				 */
17243 				err = check_reference_leak(env);
17244 				if (err)
17245 					return err;
17246 
17247 				if (state->curframe) {
17248 					/* exit from nested function */
17249 					err = prepare_func_exit(env, &env->insn_idx);
17250 					if (err)
17251 						return err;
17252 					do_print_state = true;
17253 					continue;
17254 				}
17255 
17256 				err = check_return_code(env);
17257 				if (err)
17258 					return err;
17259 process_bpf_exit:
17260 				mark_verifier_state_scratched(env);
17261 				update_branch_counts(env, env->cur_state);
17262 				err = pop_stack(env, &prev_insn_idx,
17263 						&env->insn_idx, pop_log);
17264 				if (err < 0) {
17265 					if (err != -ENOENT)
17266 						return err;
17267 					break;
17268 				} else {
17269 					do_print_state = true;
17270 					continue;
17271 				}
17272 			} else {
17273 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17274 				if (err)
17275 					return err;
17276 			}
17277 		} else if (class == BPF_LD) {
17278 			u8 mode = BPF_MODE(insn->code);
17279 
17280 			if (mode == BPF_ABS || mode == BPF_IND) {
17281 				err = check_ld_abs(env, insn);
17282 				if (err)
17283 					return err;
17284 
17285 			} else if (mode == BPF_IMM) {
17286 				err = check_ld_imm(env, insn);
17287 				if (err)
17288 					return err;
17289 
17290 				env->insn_idx++;
17291 				sanitize_mark_insn_seen(env);
17292 			} else {
17293 				verbose(env, "invalid BPF_LD mode\n");
17294 				return -EINVAL;
17295 			}
17296 		} else {
17297 			verbose(env, "unknown insn class %d\n", class);
17298 			return -EINVAL;
17299 		}
17300 
17301 		env->insn_idx++;
17302 	}
17303 
17304 	return 0;
17305 }
17306 
17307 static int find_btf_percpu_datasec(struct btf *btf)
17308 {
17309 	const struct btf_type *t;
17310 	const char *tname;
17311 	int i, n;
17312 
17313 	/*
17314 	 * Both vmlinux and module each have their own ".data..percpu"
17315 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17316 	 * types to look at only module's own BTF types.
17317 	 */
17318 	n = btf_nr_types(btf);
17319 	if (btf_is_module(btf))
17320 		i = btf_nr_types(btf_vmlinux);
17321 	else
17322 		i = 1;
17323 
17324 	for(; i < n; i++) {
17325 		t = btf_type_by_id(btf, i);
17326 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17327 			continue;
17328 
17329 		tname = btf_name_by_offset(btf, t->name_off);
17330 		if (!strcmp(tname, ".data..percpu"))
17331 			return i;
17332 	}
17333 
17334 	return -ENOENT;
17335 }
17336 
17337 /* replace pseudo btf_id with kernel symbol address */
17338 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17339 			       struct bpf_insn *insn,
17340 			       struct bpf_insn_aux_data *aux)
17341 {
17342 	const struct btf_var_secinfo *vsi;
17343 	const struct btf_type *datasec;
17344 	struct btf_mod_pair *btf_mod;
17345 	const struct btf_type *t;
17346 	const char *sym_name;
17347 	bool percpu = false;
17348 	u32 type, id = insn->imm;
17349 	struct btf *btf;
17350 	s32 datasec_id;
17351 	u64 addr;
17352 	int i, btf_fd, err;
17353 
17354 	btf_fd = insn[1].imm;
17355 	if (btf_fd) {
17356 		btf = btf_get_by_fd(btf_fd);
17357 		if (IS_ERR(btf)) {
17358 			verbose(env, "invalid module BTF object FD specified.\n");
17359 			return -EINVAL;
17360 		}
17361 	} else {
17362 		if (!btf_vmlinux) {
17363 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17364 			return -EINVAL;
17365 		}
17366 		btf = btf_vmlinux;
17367 		btf_get(btf);
17368 	}
17369 
17370 	t = btf_type_by_id(btf, id);
17371 	if (!t) {
17372 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17373 		err = -ENOENT;
17374 		goto err_put;
17375 	}
17376 
17377 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17378 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17379 		err = -EINVAL;
17380 		goto err_put;
17381 	}
17382 
17383 	sym_name = btf_name_by_offset(btf, t->name_off);
17384 	addr = kallsyms_lookup_name(sym_name);
17385 	if (!addr) {
17386 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17387 			sym_name);
17388 		err = -ENOENT;
17389 		goto err_put;
17390 	}
17391 	insn[0].imm = (u32)addr;
17392 	insn[1].imm = addr >> 32;
17393 
17394 	if (btf_type_is_func(t)) {
17395 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17396 		aux->btf_var.mem_size = 0;
17397 		goto check_btf;
17398 	}
17399 
17400 	datasec_id = find_btf_percpu_datasec(btf);
17401 	if (datasec_id > 0) {
17402 		datasec = btf_type_by_id(btf, datasec_id);
17403 		for_each_vsi(i, datasec, vsi) {
17404 			if (vsi->type == id) {
17405 				percpu = true;
17406 				break;
17407 			}
17408 		}
17409 	}
17410 
17411 	type = t->type;
17412 	t = btf_type_skip_modifiers(btf, type, NULL);
17413 	if (percpu) {
17414 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17415 		aux->btf_var.btf = btf;
17416 		aux->btf_var.btf_id = type;
17417 	} else if (!btf_type_is_struct(t)) {
17418 		const struct btf_type *ret;
17419 		const char *tname;
17420 		u32 tsize;
17421 
17422 		/* resolve the type size of ksym. */
17423 		ret = btf_resolve_size(btf, t, &tsize);
17424 		if (IS_ERR(ret)) {
17425 			tname = btf_name_by_offset(btf, t->name_off);
17426 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17427 				tname, PTR_ERR(ret));
17428 			err = -EINVAL;
17429 			goto err_put;
17430 		}
17431 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17432 		aux->btf_var.mem_size = tsize;
17433 	} else {
17434 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17435 		aux->btf_var.btf = btf;
17436 		aux->btf_var.btf_id = type;
17437 	}
17438 check_btf:
17439 	/* check whether we recorded this BTF (and maybe module) already */
17440 	for (i = 0; i < env->used_btf_cnt; i++) {
17441 		if (env->used_btfs[i].btf == btf) {
17442 			btf_put(btf);
17443 			return 0;
17444 		}
17445 	}
17446 
17447 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17448 		err = -E2BIG;
17449 		goto err_put;
17450 	}
17451 
17452 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17453 	btf_mod->btf = btf;
17454 	btf_mod->module = NULL;
17455 
17456 	/* if we reference variables from kernel module, bump its refcount */
17457 	if (btf_is_module(btf)) {
17458 		btf_mod->module = btf_try_get_module(btf);
17459 		if (!btf_mod->module) {
17460 			err = -ENXIO;
17461 			goto err_put;
17462 		}
17463 	}
17464 
17465 	env->used_btf_cnt++;
17466 
17467 	return 0;
17468 err_put:
17469 	btf_put(btf);
17470 	return err;
17471 }
17472 
17473 static bool is_tracing_prog_type(enum bpf_prog_type type)
17474 {
17475 	switch (type) {
17476 	case BPF_PROG_TYPE_KPROBE:
17477 	case BPF_PROG_TYPE_TRACEPOINT:
17478 	case BPF_PROG_TYPE_PERF_EVENT:
17479 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17480 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17481 		return true;
17482 	default:
17483 		return false;
17484 	}
17485 }
17486 
17487 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17488 					struct bpf_map *map,
17489 					struct bpf_prog *prog)
17490 
17491 {
17492 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17493 
17494 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17495 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17496 		if (is_tracing_prog_type(prog_type)) {
17497 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17498 			return -EINVAL;
17499 		}
17500 	}
17501 
17502 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17503 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17504 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17505 			return -EINVAL;
17506 		}
17507 
17508 		if (is_tracing_prog_type(prog_type)) {
17509 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17510 			return -EINVAL;
17511 		}
17512 	}
17513 
17514 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17515 		if (is_tracing_prog_type(prog_type)) {
17516 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17517 			return -EINVAL;
17518 		}
17519 	}
17520 
17521 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17522 	    !bpf_offload_prog_map_match(prog, map)) {
17523 		verbose(env, "offload device mismatch between prog and map\n");
17524 		return -EINVAL;
17525 	}
17526 
17527 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17528 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17529 		return -EINVAL;
17530 	}
17531 
17532 	if (prog->aux->sleepable)
17533 		switch (map->map_type) {
17534 		case BPF_MAP_TYPE_HASH:
17535 		case BPF_MAP_TYPE_LRU_HASH:
17536 		case BPF_MAP_TYPE_ARRAY:
17537 		case BPF_MAP_TYPE_PERCPU_HASH:
17538 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17539 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17540 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17541 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17542 		case BPF_MAP_TYPE_RINGBUF:
17543 		case BPF_MAP_TYPE_USER_RINGBUF:
17544 		case BPF_MAP_TYPE_INODE_STORAGE:
17545 		case BPF_MAP_TYPE_SK_STORAGE:
17546 		case BPF_MAP_TYPE_TASK_STORAGE:
17547 		case BPF_MAP_TYPE_CGRP_STORAGE:
17548 			break;
17549 		default:
17550 			verbose(env,
17551 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17552 			return -EINVAL;
17553 		}
17554 
17555 	return 0;
17556 }
17557 
17558 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17559 {
17560 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17561 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17562 }
17563 
17564 /* find and rewrite pseudo imm in ld_imm64 instructions:
17565  *
17566  * 1. if it accesses map FD, replace it with actual map pointer.
17567  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17568  *
17569  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17570  */
17571 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17572 {
17573 	struct bpf_insn *insn = env->prog->insnsi;
17574 	int insn_cnt = env->prog->len;
17575 	int i, j, err;
17576 
17577 	err = bpf_prog_calc_tag(env->prog);
17578 	if (err)
17579 		return err;
17580 
17581 	for (i = 0; i < insn_cnt; i++, insn++) {
17582 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17583 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17584 		    insn->imm != 0)) {
17585 			verbose(env, "BPF_LDX uses reserved fields\n");
17586 			return -EINVAL;
17587 		}
17588 
17589 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17590 			struct bpf_insn_aux_data *aux;
17591 			struct bpf_map *map;
17592 			struct fd f;
17593 			u64 addr;
17594 			u32 fd;
17595 
17596 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17597 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17598 			    insn[1].off != 0) {
17599 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17600 				return -EINVAL;
17601 			}
17602 
17603 			if (insn[0].src_reg == 0)
17604 				/* valid generic load 64-bit imm */
17605 				goto next_insn;
17606 
17607 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17608 				aux = &env->insn_aux_data[i];
17609 				err = check_pseudo_btf_id(env, insn, aux);
17610 				if (err)
17611 					return err;
17612 				goto next_insn;
17613 			}
17614 
17615 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17616 				aux = &env->insn_aux_data[i];
17617 				aux->ptr_type = PTR_TO_FUNC;
17618 				goto next_insn;
17619 			}
17620 
17621 			/* In final convert_pseudo_ld_imm64() step, this is
17622 			 * converted into regular 64-bit imm load insn.
17623 			 */
17624 			switch (insn[0].src_reg) {
17625 			case BPF_PSEUDO_MAP_VALUE:
17626 			case BPF_PSEUDO_MAP_IDX_VALUE:
17627 				break;
17628 			case BPF_PSEUDO_MAP_FD:
17629 			case BPF_PSEUDO_MAP_IDX:
17630 				if (insn[1].imm == 0)
17631 					break;
17632 				fallthrough;
17633 			default:
17634 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17635 				return -EINVAL;
17636 			}
17637 
17638 			switch (insn[0].src_reg) {
17639 			case BPF_PSEUDO_MAP_IDX_VALUE:
17640 			case BPF_PSEUDO_MAP_IDX:
17641 				if (bpfptr_is_null(env->fd_array)) {
17642 					verbose(env, "fd_idx without fd_array is invalid\n");
17643 					return -EPROTO;
17644 				}
17645 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17646 							    insn[0].imm * sizeof(fd),
17647 							    sizeof(fd)))
17648 					return -EFAULT;
17649 				break;
17650 			default:
17651 				fd = insn[0].imm;
17652 				break;
17653 			}
17654 
17655 			f = fdget(fd);
17656 			map = __bpf_map_get(f);
17657 			if (IS_ERR(map)) {
17658 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
17659 					insn[0].imm);
17660 				return PTR_ERR(map);
17661 			}
17662 
17663 			err = check_map_prog_compatibility(env, map, env->prog);
17664 			if (err) {
17665 				fdput(f);
17666 				return err;
17667 			}
17668 
17669 			aux = &env->insn_aux_data[i];
17670 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17671 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17672 				addr = (unsigned long)map;
17673 			} else {
17674 				u32 off = insn[1].imm;
17675 
17676 				if (off >= BPF_MAX_VAR_OFF) {
17677 					verbose(env, "direct value offset of %u is not allowed\n", off);
17678 					fdput(f);
17679 					return -EINVAL;
17680 				}
17681 
17682 				if (!map->ops->map_direct_value_addr) {
17683 					verbose(env, "no direct value access support for this map type\n");
17684 					fdput(f);
17685 					return -EINVAL;
17686 				}
17687 
17688 				err = map->ops->map_direct_value_addr(map, &addr, off);
17689 				if (err) {
17690 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17691 						map->value_size, off);
17692 					fdput(f);
17693 					return err;
17694 				}
17695 
17696 				aux->map_off = off;
17697 				addr += off;
17698 			}
17699 
17700 			insn[0].imm = (u32)addr;
17701 			insn[1].imm = addr >> 32;
17702 
17703 			/* check whether we recorded this map already */
17704 			for (j = 0; j < env->used_map_cnt; j++) {
17705 				if (env->used_maps[j] == map) {
17706 					aux->map_index = j;
17707 					fdput(f);
17708 					goto next_insn;
17709 				}
17710 			}
17711 
17712 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17713 				fdput(f);
17714 				return -E2BIG;
17715 			}
17716 
17717 			/* hold the map. If the program is rejected by verifier,
17718 			 * the map will be released by release_maps() or it
17719 			 * will be used by the valid program until it's unloaded
17720 			 * and all maps are released in free_used_maps()
17721 			 */
17722 			bpf_map_inc(map);
17723 
17724 			aux->map_index = env->used_map_cnt;
17725 			env->used_maps[env->used_map_cnt++] = map;
17726 
17727 			if (bpf_map_is_cgroup_storage(map) &&
17728 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17729 				verbose(env, "only one cgroup storage of each type is allowed\n");
17730 				fdput(f);
17731 				return -EBUSY;
17732 			}
17733 
17734 			fdput(f);
17735 next_insn:
17736 			insn++;
17737 			i++;
17738 			continue;
17739 		}
17740 
17741 		/* Basic sanity check before we invest more work here. */
17742 		if (!bpf_opcode_in_insntable(insn->code)) {
17743 			verbose(env, "unknown opcode %02x\n", insn->code);
17744 			return -EINVAL;
17745 		}
17746 	}
17747 
17748 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17749 	 * 'struct bpf_map *' into a register instead of user map_fd.
17750 	 * These pointers will be used later by verifier to validate map access.
17751 	 */
17752 	return 0;
17753 }
17754 
17755 /* drop refcnt of maps used by the rejected program */
17756 static void release_maps(struct bpf_verifier_env *env)
17757 {
17758 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17759 			     env->used_map_cnt);
17760 }
17761 
17762 /* drop refcnt of maps used by the rejected program */
17763 static void release_btfs(struct bpf_verifier_env *env)
17764 {
17765 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17766 			     env->used_btf_cnt);
17767 }
17768 
17769 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17770 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17771 {
17772 	struct bpf_insn *insn = env->prog->insnsi;
17773 	int insn_cnt = env->prog->len;
17774 	int i;
17775 
17776 	for (i = 0; i < insn_cnt; i++, insn++) {
17777 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17778 			continue;
17779 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17780 			continue;
17781 		insn->src_reg = 0;
17782 	}
17783 }
17784 
17785 /* single env->prog->insni[off] instruction was replaced with the range
17786  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17787  * [0, off) and [off, end) to new locations, so the patched range stays zero
17788  */
17789 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17790 				 struct bpf_insn_aux_data *new_data,
17791 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17792 {
17793 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17794 	struct bpf_insn *insn = new_prog->insnsi;
17795 	u32 old_seen = old_data[off].seen;
17796 	u32 prog_len;
17797 	int i;
17798 
17799 	/* aux info at OFF always needs adjustment, no matter fast path
17800 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17801 	 * original insn at old prog.
17802 	 */
17803 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17804 
17805 	if (cnt == 1)
17806 		return;
17807 	prog_len = new_prog->len;
17808 
17809 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17810 	memcpy(new_data + off + cnt - 1, old_data + off,
17811 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17812 	for (i = off; i < off + cnt - 1; i++) {
17813 		/* Expand insni[off]'s seen count to the patched range. */
17814 		new_data[i].seen = old_seen;
17815 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17816 	}
17817 	env->insn_aux_data = new_data;
17818 	vfree(old_data);
17819 }
17820 
17821 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17822 {
17823 	int i;
17824 
17825 	if (len == 1)
17826 		return;
17827 	/* NOTE: fake 'exit' subprog should be updated as well. */
17828 	for (i = 0; i <= env->subprog_cnt; i++) {
17829 		if (env->subprog_info[i].start <= off)
17830 			continue;
17831 		env->subprog_info[i].start += len - 1;
17832 	}
17833 }
17834 
17835 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17836 {
17837 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17838 	int i, sz = prog->aux->size_poke_tab;
17839 	struct bpf_jit_poke_descriptor *desc;
17840 
17841 	for (i = 0; i < sz; i++) {
17842 		desc = &tab[i];
17843 		if (desc->insn_idx <= off)
17844 			continue;
17845 		desc->insn_idx += len - 1;
17846 	}
17847 }
17848 
17849 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17850 					    const struct bpf_insn *patch, u32 len)
17851 {
17852 	struct bpf_prog *new_prog;
17853 	struct bpf_insn_aux_data *new_data = NULL;
17854 
17855 	if (len > 1) {
17856 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17857 					      sizeof(struct bpf_insn_aux_data)));
17858 		if (!new_data)
17859 			return NULL;
17860 	}
17861 
17862 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17863 	if (IS_ERR(new_prog)) {
17864 		if (PTR_ERR(new_prog) == -ERANGE)
17865 			verbose(env,
17866 				"insn %d cannot be patched due to 16-bit range\n",
17867 				env->insn_aux_data[off].orig_idx);
17868 		vfree(new_data);
17869 		return NULL;
17870 	}
17871 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17872 	adjust_subprog_starts(env, off, len);
17873 	adjust_poke_descs(new_prog, off, len);
17874 	return new_prog;
17875 }
17876 
17877 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17878 					      u32 off, u32 cnt)
17879 {
17880 	int i, j;
17881 
17882 	/* find first prog starting at or after off (first to remove) */
17883 	for (i = 0; i < env->subprog_cnt; i++)
17884 		if (env->subprog_info[i].start >= off)
17885 			break;
17886 	/* find first prog starting at or after off + cnt (first to stay) */
17887 	for (j = i; j < env->subprog_cnt; j++)
17888 		if (env->subprog_info[j].start >= off + cnt)
17889 			break;
17890 	/* if j doesn't start exactly at off + cnt, we are just removing
17891 	 * the front of previous prog
17892 	 */
17893 	if (env->subprog_info[j].start != off + cnt)
17894 		j--;
17895 
17896 	if (j > i) {
17897 		struct bpf_prog_aux *aux = env->prog->aux;
17898 		int move;
17899 
17900 		/* move fake 'exit' subprog as well */
17901 		move = env->subprog_cnt + 1 - j;
17902 
17903 		memmove(env->subprog_info + i,
17904 			env->subprog_info + j,
17905 			sizeof(*env->subprog_info) * move);
17906 		env->subprog_cnt -= j - i;
17907 
17908 		/* remove func_info */
17909 		if (aux->func_info) {
17910 			move = aux->func_info_cnt - j;
17911 
17912 			memmove(aux->func_info + i,
17913 				aux->func_info + j,
17914 				sizeof(*aux->func_info) * move);
17915 			aux->func_info_cnt -= j - i;
17916 			/* func_info->insn_off is set after all code rewrites,
17917 			 * in adjust_btf_func() - no need to adjust
17918 			 */
17919 		}
17920 	} else {
17921 		/* convert i from "first prog to remove" to "first to adjust" */
17922 		if (env->subprog_info[i].start == off)
17923 			i++;
17924 	}
17925 
17926 	/* update fake 'exit' subprog as well */
17927 	for (; i <= env->subprog_cnt; i++)
17928 		env->subprog_info[i].start -= cnt;
17929 
17930 	return 0;
17931 }
17932 
17933 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17934 				      u32 cnt)
17935 {
17936 	struct bpf_prog *prog = env->prog;
17937 	u32 i, l_off, l_cnt, nr_linfo;
17938 	struct bpf_line_info *linfo;
17939 
17940 	nr_linfo = prog->aux->nr_linfo;
17941 	if (!nr_linfo)
17942 		return 0;
17943 
17944 	linfo = prog->aux->linfo;
17945 
17946 	/* find first line info to remove, count lines to be removed */
17947 	for (i = 0; i < nr_linfo; i++)
17948 		if (linfo[i].insn_off >= off)
17949 			break;
17950 
17951 	l_off = i;
17952 	l_cnt = 0;
17953 	for (; i < nr_linfo; i++)
17954 		if (linfo[i].insn_off < off + cnt)
17955 			l_cnt++;
17956 		else
17957 			break;
17958 
17959 	/* First live insn doesn't match first live linfo, it needs to "inherit"
17960 	 * last removed linfo.  prog is already modified, so prog->len == off
17961 	 * means no live instructions after (tail of the program was removed).
17962 	 */
17963 	if (prog->len != off && l_cnt &&
17964 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17965 		l_cnt--;
17966 		linfo[--i].insn_off = off + cnt;
17967 	}
17968 
17969 	/* remove the line info which refer to the removed instructions */
17970 	if (l_cnt) {
17971 		memmove(linfo + l_off, linfo + i,
17972 			sizeof(*linfo) * (nr_linfo - i));
17973 
17974 		prog->aux->nr_linfo -= l_cnt;
17975 		nr_linfo = prog->aux->nr_linfo;
17976 	}
17977 
17978 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
17979 	for (i = l_off; i < nr_linfo; i++)
17980 		linfo[i].insn_off -= cnt;
17981 
17982 	/* fix up all subprogs (incl. 'exit') which start >= off */
17983 	for (i = 0; i <= env->subprog_cnt; i++)
17984 		if (env->subprog_info[i].linfo_idx > l_off) {
17985 			/* program may have started in the removed region but
17986 			 * may not be fully removed
17987 			 */
17988 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17989 				env->subprog_info[i].linfo_idx -= l_cnt;
17990 			else
17991 				env->subprog_info[i].linfo_idx = l_off;
17992 		}
17993 
17994 	return 0;
17995 }
17996 
17997 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17998 {
17999 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18000 	unsigned int orig_prog_len = env->prog->len;
18001 	int err;
18002 
18003 	if (bpf_prog_is_offloaded(env->prog->aux))
18004 		bpf_prog_offload_remove_insns(env, off, cnt);
18005 
18006 	err = bpf_remove_insns(env->prog, off, cnt);
18007 	if (err)
18008 		return err;
18009 
18010 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18011 	if (err)
18012 		return err;
18013 
18014 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18015 	if (err)
18016 		return err;
18017 
18018 	memmove(aux_data + off,	aux_data + off + cnt,
18019 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18020 
18021 	return 0;
18022 }
18023 
18024 /* The verifier does more data flow analysis than llvm and will not
18025  * explore branches that are dead at run time. Malicious programs can
18026  * have dead code too. Therefore replace all dead at-run-time code
18027  * with 'ja -1'.
18028  *
18029  * Just nops are not optimal, e.g. if they would sit at the end of the
18030  * program and through another bug we would manage to jump there, then
18031  * we'd execute beyond program memory otherwise. Returning exception
18032  * code also wouldn't work since we can have subprogs where the dead
18033  * code could be located.
18034  */
18035 static void sanitize_dead_code(struct bpf_verifier_env *env)
18036 {
18037 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18038 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18039 	struct bpf_insn *insn = env->prog->insnsi;
18040 	const int insn_cnt = env->prog->len;
18041 	int i;
18042 
18043 	for (i = 0; i < insn_cnt; i++) {
18044 		if (aux_data[i].seen)
18045 			continue;
18046 		memcpy(insn + i, &trap, sizeof(trap));
18047 		aux_data[i].zext_dst = false;
18048 	}
18049 }
18050 
18051 static bool insn_is_cond_jump(u8 code)
18052 {
18053 	u8 op;
18054 
18055 	op = BPF_OP(code);
18056 	if (BPF_CLASS(code) == BPF_JMP32)
18057 		return op != BPF_JA;
18058 
18059 	if (BPF_CLASS(code) != BPF_JMP)
18060 		return false;
18061 
18062 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18063 }
18064 
18065 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18066 {
18067 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18068 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18069 	struct bpf_insn *insn = env->prog->insnsi;
18070 	const int insn_cnt = env->prog->len;
18071 	int i;
18072 
18073 	for (i = 0; i < insn_cnt; i++, insn++) {
18074 		if (!insn_is_cond_jump(insn->code))
18075 			continue;
18076 
18077 		if (!aux_data[i + 1].seen)
18078 			ja.off = insn->off;
18079 		else if (!aux_data[i + 1 + insn->off].seen)
18080 			ja.off = 0;
18081 		else
18082 			continue;
18083 
18084 		if (bpf_prog_is_offloaded(env->prog->aux))
18085 			bpf_prog_offload_replace_insn(env, i, &ja);
18086 
18087 		memcpy(insn, &ja, sizeof(ja));
18088 	}
18089 }
18090 
18091 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18092 {
18093 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18094 	int insn_cnt = env->prog->len;
18095 	int i, err;
18096 
18097 	for (i = 0; i < insn_cnt; i++) {
18098 		int j;
18099 
18100 		j = 0;
18101 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18102 			j++;
18103 		if (!j)
18104 			continue;
18105 
18106 		err = verifier_remove_insns(env, i, j);
18107 		if (err)
18108 			return err;
18109 		insn_cnt = env->prog->len;
18110 	}
18111 
18112 	return 0;
18113 }
18114 
18115 static int opt_remove_nops(struct bpf_verifier_env *env)
18116 {
18117 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18118 	struct bpf_insn *insn = env->prog->insnsi;
18119 	int insn_cnt = env->prog->len;
18120 	int i, err;
18121 
18122 	for (i = 0; i < insn_cnt; i++) {
18123 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18124 			continue;
18125 
18126 		err = verifier_remove_insns(env, i, 1);
18127 		if (err)
18128 			return err;
18129 		insn_cnt--;
18130 		i--;
18131 	}
18132 
18133 	return 0;
18134 }
18135 
18136 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18137 					 const union bpf_attr *attr)
18138 {
18139 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18140 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18141 	int i, patch_len, delta = 0, len = env->prog->len;
18142 	struct bpf_insn *insns = env->prog->insnsi;
18143 	struct bpf_prog *new_prog;
18144 	bool rnd_hi32;
18145 
18146 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18147 	zext_patch[1] = BPF_ZEXT_REG(0);
18148 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18149 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18150 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18151 	for (i = 0; i < len; i++) {
18152 		int adj_idx = i + delta;
18153 		struct bpf_insn insn;
18154 		int load_reg;
18155 
18156 		insn = insns[adj_idx];
18157 		load_reg = insn_def_regno(&insn);
18158 		if (!aux[adj_idx].zext_dst) {
18159 			u8 code, class;
18160 			u32 imm_rnd;
18161 
18162 			if (!rnd_hi32)
18163 				continue;
18164 
18165 			code = insn.code;
18166 			class = BPF_CLASS(code);
18167 			if (load_reg == -1)
18168 				continue;
18169 
18170 			/* NOTE: arg "reg" (the fourth one) is only used for
18171 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18172 			 *       here.
18173 			 */
18174 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18175 				if (class == BPF_LD &&
18176 				    BPF_MODE(code) == BPF_IMM)
18177 					i++;
18178 				continue;
18179 			}
18180 
18181 			/* ctx load could be transformed into wider load. */
18182 			if (class == BPF_LDX &&
18183 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18184 				continue;
18185 
18186 			imm_rnd = get_random_u32();
18187 			rnd_hi32_patch[0] = insn;
18188 			rnd_hi32_patch[1].imm = imm_rnd;
18189 			rnd_hi32_patch[3].dst_reg = load_reg;
18190 			patch = rnd_hi32_patch;
18191 			patch_len = 4;
18192 			goto apply_patch_buffer;
18193 		}
18194 
18195 		/* Add in an zero-extend instruction if a) the JIT has requested
18196 		 * it or b) it's a CMPXCHG.
18197 		 *
18198 		 * The latter is because: BPF_CMPXCHG always loads a value into
18199 		 * R0, therefore always zero-extends. However some archs'
18200 		 * equivalent instruction only does this load when the
18201 		 * comparison is successful. This detail of CMPXCHG is
18202 		 * orthogonal to the general zero-extension behaviour of the
18203 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18204 		 */
18205 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18206 			continue;
18207 
18208 		/* Zero-extension is done by the caller. */
18209 		if (bpf_pseudo_kfunc_call(&insn))
18210 			continue;
18211 
18212 		if (WARN_ON(load_reg == -1)) {
18213 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18214 			return -EFAULT;
18215 		}
18216 
18217 		zext_patch[0] = insn;
18218 		zext_patch[1].dst_reg = load_reg;
18219 		zext_patch[1].src_reg = load_reg;
18220 		patch = zext_patch;
18221 		patch_len = 2;
18222 apply_patch_buffer:
18223 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18224 		if (!new_prog)
18225 			return -ENOMEM;
18226 		env->prog = new_prog;
18227 		insns = new_prog->insnsi;
18228 		aux = env->insn_aux_data;
18229 		delta += patch_len - 1;
18230 	}
18231 
18232 	return 0;
18233 }
18234 
18235 /* convert load instructions that access fields of a context type into a
18236  * sequence of instructions that access fields of the underlying structure:
18237  *     struct __sk_buff    -> struct sk_buff
18238  *     struct bpf_sock_ops -> struct sock
18239  */
18240 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18241 {
18242 	const struct bpf_verifier_ops *ops = env->ops;
18243 	int i, cnt, size, ctx_field_size, delta = 0;
18244 	const int insn_cnt = env->prog->len;
18245 	struct bpf_insn insn_buf[16], *insn;
18246 	u32 target_size, size_default, off;
18247 	struct bpf_prog *new_prog;
18248 	enum bpf_access_type type;
18249 	bool is_narrower_load;
18250 
18251 	if (ops->gen_prologue || env->seen_direct_write) {
18252 		if (!ops->gen_prologue) {
18253 			verbose(env, "bpf verifier is misconfigured\n");
18254 			return -EINVAL;
18255 		}
18256 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18257 					env->prog);
18258 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18259 			verbose(env, "bpf verifier is misconfigured\n");
18260 			return -EINVAL;
18261 		} else if (cnt) {
18262 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18263 			if (!new_prog)
18264 				return -ENOMEM;
18265 
18266 			env->prog = new_prog;
18267 			delta += cnt - 1;
18268 		}
18269 	}
18270 
18271 	if (bpf_prog_is_offloaded(env->prog->aux))
18272 		return 0;
18273 
18274 	insn = env->prog->insnsi + delta;
18275 
18276 	for (i = 0; i < insn_cnt; i++, insn++) {
18277 		bpf_convert_ctx_access_t convert_ctx_access;
18278 		u8 mode;
18279 
18280 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18281 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18282 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18283 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18284 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18285 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18286 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18287 			type = BPF_READ;
18288 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18289 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18290 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18291 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18292 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18293 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18294 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18295 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18296 			type = BPF_WRITE;
18297 		} else {
18298 			continue;
18299 		}
18300 
18301 		if (type == BPF_WRITE &&
18302 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18303 			struct bpf_insn patch[] = {
18304 				*insn,
18305 				BPF_ST_NOSPEC(),
18306 			};
18307 
18308 			cnt = ARRAY_SIZE(patch);
18309 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18310 			if (!new_prog)
18311 				return -ENOMEM;
18312 
18313 			delta    += cnt - 1;
18314 			env->prog = new_prog;
18315 			insn      = new_prog->insnsi + i + delta;
18316 			continue;
18317 		}
18318 
18319 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18320 		case PTR_TO_CTX:
18321 			if (!ops->convert_ctx_access)
18322 				continue;
18323 			convert_ctx_access = ops->convert_ctx_access;
18324 			break;
18325 		case PTR_TO_SOCKET:
18326 		case PTR_TO_SOCK_COMMON:
18327 			convert_ctx_access = bpf_sock_convert_ctx_access;
18328 			break;
18329 		case PTR_TO_TCP_SOCK:
18330 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18331 			break;
18332 		case PTR_TO_XDP_SOCK:
18333 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18334 			break;
18335 		case PTR_TO_BTF_ID:
18336 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18337 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18338 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18339 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18340 		 * any faults for loads into such types. BPF_WRITE is disallowed
18341 		 * for this case.
18342 		 */
18343 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18344 			if (type == BPF_READ) {
18345 				if (BPF_MODE(insn->code) == BPF_MEM)
18346 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18347 						     BPF_SIZE((insn)->code);
18348 				else
18349 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18350 						     BPF_SIZE((insn)->code);
18351 				env->prog->aux->num_exentries++;
18352 			}
18353 			continue;
18354 		default:
18355 			continue;
18356 		}
18357 
18358 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18359 		size = BPF_LDST_BYTES(insn);
18360 		mode = BPF_MODE(insn->code);
18361 
18362 		/* If the read access is a narrower load of the field,
18363 		 * convert to a 4/8-byte load, to minimum program type specific
18364 		 * convert_ctx_access changes. If conversion is successful,
18365 		 * we will apply proper mask to the result.
18366 		 */
18367 		is_narrower_load = size < ctx_field_size;
18368 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18369 		off = insn->off;
18370 		if (is_narrower_load) {
18371 			u8 size_code;
18372 
18373 			if (type == BPF_WRITE) {
18374 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18375 				return -EINVAL;
18376 			}
18377 
18378 			size_code = BPF_H;
18379 			if (ctx_field_size == 4)
18380 				size_code = BPF_W;
18381 			else if (ctx_field_size == 8)
18382 				size_code = BPF_DW;
18383 
18384 			insn->off = off & ~(size_default - 1);
18385 			insn->code = BPF_LDX | BPF_MEM | size_code;
18386 		}
18387 
18388 		target_size = 0;
18389 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18390 					 &target_size);
18391 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18392 		    (ctx_field_size && !target_size)) {
18393 			verbose(env, "bpf verifier is misconfigured\n");
18394 			return -EINVAL;
18395 		}
18396 
18397 		if (is_narrower_load && size < target_size) {
18398 			u8 shift = bpf_ctx_narrow_access_offset(
18399 				off, size, size_default) * 8;
18400 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18401 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18402 				return -EINVAL;
18403 			}
18404 			if (ctx_field_size <= 4) {
18405 				if (shift)
18406 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18407 									insn->dst_reg,
18408 									shift);
18409 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18410 								(1 << size * 8) - 1);
18411 			} else {
18412 				if (shift)
18413 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18414 									insn->dst_reg,
18415 									shift);
18416 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18417 								(1ULL << size * 8) - 1);
18418 			}
18419 		}
18420 		if (mode == BPF_MEMSX)
18421 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18422 						       insn->dst_reg, insn->dst_reg,
18423 						       size * 8, 0);
18424 
18425 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18426 		if (!new_prog)
18427 			return -ENOMEM;
18428 
18429 		delta += cnt - 1;
18430 
18431 		/* keep walking new program and skip insns we just inserted */
18432 		env->prog = new_prog;
18433 		insn      = new_prog->insnsi + i + delta;
18434 	}
18435 
18436 	return 0;
18437 }
18438 
18439 static int jit_subprogs(struct bpf_verifier_env *env)
18440 {
18441 	struct bpf_prog *prog = env->prog, **func, *tmp;
18442 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18443 	struct bpf_map *map_ptr;
18444 	struct bpf_insn *insn;
18445 	void *old_bpf_func;
18446 	int err, num_exentries;
18447 
18448 	if (env->subprog_cnt <= 1)
18449 		return 0;
18450 
18451 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18452 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18453 			continue;
18454 
18455 		/* Upon error here we cannot fall back to interpreter but
18456 		 * need a hard reject of the program. Thus -EFAULT is
18457 		 * propagated in any case.
18458 		 */
18459 		subprog = find_subprog(env, i + insn->imm + 1);
18460 		if (subprog < 0) {
18461 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18462 				  i + insn->imm + 1);
18463 			return -EFAULT;
18464 		}
18465 		/* temporarily remember subprog id inside insn instead of
18466 		 * aux_data, since next loop will split up all insns into funcs
18467 		 */
18468 		insn->off = subprog;
18469 		/* remember original imm in case JIT fails and fallback
18470 		 * to interpreter will be needed
18471 		 */
18472 		env->insn_aux_data[i].call_imm = insn->imm;
18473 		/* point imm to __bpf_call_base+1 from JITs point of view */
18474 		insn->imm = 1;
18475 		if (bpf_pseudo_func(insn))
18476 			/* jit (e.g. x86_64) may emit fewer instructions
18477 			 * if it learns a u32 imm is the same as a u64 imm.
18478 			 * Force a non zero here.
18479 			 */
18480 			insn[1].imm = 1;
18481 	}
18482 
18483 	err = bpf_prog_alloc_jited_linfo(prog);
18484 	if (err)
18485 		goto out_undo_insn;
18486 
18487 	err = -ENOMEM;
18488 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18489 	if (!func)
18490 		goto out_undo_insn;
18491 
18492 	for (i = 0; i < env->subprog_cnt; i++) {
18493 		subprog_start = subprog_end;
18494 		subprog_end = env->subprog_info[i + 1].start;
18495 
18496 		len = subprog_end - subprog_start;
18497 		/* bpf_prog_run() doesn't call subprogs directly,
18498 		 * hence main prog stats include the runtime of subprogs.
18499 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18500 		 * func[i]->stats will never be accessed and stays NULL
18501 		 */
18502 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18503 		if (!func[i])
18504 			goto out_free;
18505 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18506 		       len * sizeof(struct bpf_insn));
18507 		func[i]->type = prog->type;
18508 		func[i]->len = len;
18509 		if (bpf_prog_calc_tag(func[i]))
18510 			goto out_free;
18511 		func[i]->is_func = 1;
18512 		func[i]->aux->func_idx = i;
18513 		/* Below members will be freed only at prog->aux */
18514 		func[i]->aux->btf = prog->aux->btf;
18515 		func[i]->aux->func_info = prog->aux->func_info;
18516 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18517 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18518 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18519 
18520 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18521 			struct bpf_jit_poke_descriptor *poke;
18522 
18523 			poke = &prog->aux->poke_tab[j];
18524 			if (poke->insn_idx < subprog_end &&
18525 			    poke->insn_idx >= subprog_start)
18526 				poke->aux = func[i]->aux;
18527 		}
18528 
18529 		func[i]->aux->name[0] = 'F';
18530 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18531 		func[i]->jit_requested = 1;
18532 		func[i]->blinding_requested = prog->blinding_requested;
18533 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18534 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18535 		func[i]->aux->linfo = prog->aux->linfo;
18536 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18537 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18538 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18539 		num_exentries = 0;
18540 		insn = func[i]->insnsi;
18541 		for (j = 0; j < func[i]->len; j++, insn++) {
18542 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18543 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18544 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18545 				num_exentries++;
18546 		}
18547 		func[i]->aux->num_exentries = num_exentries;
18548 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18549 		func[i] = bpf_int_jit_compile(func[i]);
18550 		if (!func[i]->jited) {
18551 			err = -ENOTSUPP;
18552 			goto out_free;
18553 		}
18554 		cond_resched();
18555 	}
18556 
18557 	/* at this point all bpf functions were successfully JITed
18558 	 * now populate all bpf_calls with correct addresses and
18559 	 * run last pass of JIT
18560 	 */
18561 	for (i = 0; i < env->subprog_cnt; i++) {
18562 		insn = func[i]->insnsi;
18563 		for (j = 0; j < func[i]->len; j++, insn++) {
18564 			if (bpf_pseudo_func(insn)) {
18565 				subprog = insn->off;
18566 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18567 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18568 				continue;
18569 			}
18570 			if (!bpf_pseudo_call(insn))
18571 				continue;
18572 			subprog = insn->off;
18573 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18574 		}
18575 
18576 		/* we use the aux data to keep a list of the start addresses
18577 		 * of the JITed images for each function in the program
18578 		 *
18579 		 * for some architectures, such as powerpc64, the imm field
18580 		 * might not be large enough to hold the offset of the start
18581 		 * address of the callee's JITed image from __bpf_call_base
18582 		 *
18583 		 * in such cases, we can lookup the start address of a callee
18584 		 * by using its subprog id, available from the off field of
18585 		 * the call instruction, as an index for this list
18586 		 */
18587 		func[i]->aux->func = func;
18588 		func[i]->aux->func_cnt = env->subprog_cnt;
18589 	}
18590 	for (i = 0; i < env->subprog_cnt; i++) {
18591 		old_bpf_func = func[i]->bpf_func;
18592 		tmp = bpf_int_jit_compile(func[i]);
18593 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18594 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18595 			err = -ENOTSUPP;
18596 			goto out_free;
18597 		}
18598 		cond_resched();
18599 	}
18600 
18601 	/* finally lock prog and jit images for all functions and
18602 	 * populate kallsysm. Begin at the first subprogram, since
18603 	 * bpf_prog_load will add the kallsyms for the main program.
18604 	 */
18605 	for (i = 1; i < env->subprog_cnt; i++) {
18606 		bpf_prog_lock_ro(func[i]);
18607 		bpf_prog_kallsyms_add(func[i]);
18608 	}
18609 
18610 	/* Last step: make now unused interpreter insns from main
18611 	 * prog consistent for later dump requests, so they can
18612 	 * later look the same as if they were interpreted only.
18613 	 */
18614 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18615 		if (bpf_pseudo_func(insn)) {
18616 			insn[0].imm = env->insn_aux_data[i].call_imm;
18617 			insn[1].imm = insn->off;
18618 			insn->off = 0;
18619 			continue;
18620 		}
18621 		if (!bpf_pseudo_call(insn))
18622 			continue;
18623 		insn->off = env->insn_aux_data[i].call_imm;
18624 		subprog = find_subprog(env, i + insn->off + 1);
18625 		insn->imm = subprog;
18626 	}
18627 
18628 	prog->jited = 1;
18629 	prog->bpf_func = func[0]->bpf_func;
18630 	prog->jited_len = func[0]->jited_len;
18631 	prog->aux->extable = func[0]->aux->extable;
18632 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18633 	prog->aux->func = func;
18634 	prog->aux->func_cnt = env->subprog_cnt;
18635 	bpf_prog_jit_attempt_done(prog);
18636 	return 0;
18637 out_free:
18638 	/* We failed JIT'ing, so at this point we need to unregister poke
18639 	 * descriptors from subprogs, so that kernel is not attempting to
18640 	 * patch it anymore as we're freeing the subprog JIT memory.
18641 	 */
18642 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18643 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18644 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18645 	}
18646 	/* At this point we're guaranteed that poke descriptors are not
18647 	 * live anymore. We can just unlink its descriptor table as it's
18648 	 * released with the main prog.
18649 	 */
18650 	for (i = 0; i < env->subprog_cnt; i++) {
18651 		if (!func[i])
18652 			continue;
18653 		func[i]->aux->poke_tab = NULL;
18654 		bpf_jit_free(func[i]);
18655 	}
18656 	kfree(func);
18657 out_undo_insn:
18658 	/* cleanup main prog to be interpreted */
18659 	prog->jit_requested = 0;
18660 	prog->blinding_requested = 0;
18661 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18662 		if (!bpf_pseudo_call(insn))
18663 			continue;
18664 		insn->off = 0;
18665 		insn->imm = env->insn_aux_data[i].call_imm;
18666 	}
18667 	bpf_prog_jit_attempt_done(prog);
18668 	return err;
18669 }
18670 
18671 static int fixup_call_args(struct bpf_verifier_env *env)
18672 {
18673 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18674 	struct bpf_prog *prog = env->prog;
18675 	struct bpf_insn *insn = prog->insnsi;
18676 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18677 	int i, depth;
18678 #endif
18679 	int err = 0;
18680 
18681 	if (env->prog->jit_requested &&
18682 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18683 		err = jit_subprogs(env);
18684 		if (err == 0)
18685 			return 0;
18686 		if (err == -EFAULT)
18687 			return err;
18688 	}
18689 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18690 	if (has_kfunc_call) {
18691 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18692 		return -EINVAL;
18693 	}
18694 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18695 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18696 		 * have to be rejected, since interpreter doesn't support them yet.
18697 		 */
18698 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18699 		return -EINVAL;
18700 	}
18701 	for (i = 0; i < prog->len; i++, insn++) {
18702 		if (bpf_pseudo_func(insn)) {
18703 			/* When JIT fails the progs with callback calls
18704 			 * have to be rejected, since interpreter doesn't support them yet.
18705 			 */
18706 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18707 			return -EINVAL;
18708 		}
18709 
18710 		if (!bpf_pseudo_call(insn))
18711 			continue;
18712 		depth = get_callee_stack_depth(env, insn, i);
18713 		if (depth < 0)
18714 			return depth;
18715 		bpf_patch_call_args(insn, depth);
18716 	}
18717 	err = 0;
18718 #endif
18719 	return err;
18720 }
18721 
18722 /* replace a generic kfunc with a specialized version if necessary */
18723 static void specialize_kfunc(struct bpf_verifier_env *env,
18724 			     u32 func_id, u16 offset, unsigned long *addr)
18725 {
18726 	struct bpf_prog *prog = env->prog;
18727 	bool seen_direct_write;
18728 	void *xdp_kfunc;
18729 	bool is_rdonly;
18730 
18731 	if (bpf_dev_bound_kfunc_id(func_id)) {
18732 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18733 		if (xdp_kfunc) {
18734 			*addr = (unsigned long)xdp_kfunc;
18735 			return;
18736 		}
18737 		/* fallback to default kfunc when not supported by netdev */
18738 	}
18739 
18740 	if (offset)
18741 		return;
18742 
18743 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18744 		seen_direct_write = env->seen_direct_write;
18745 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18746 
18747 		if (is_rdonly)
18748 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18749 
18750 		/* restore env->seen_direct_write to its original value, since
18751 		 * may_access_direct_pkt_data mutates it
18752 		 */
18753 		env->seen_direct_write = seen_direct_write;
18754 	}
18755 }
18756 
18757 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18758 					    u16 struct_meta_reg,
18759 					    u16 node_offset_reg,
18760 					    struct bpf_insn *insn,
18761 					    struct bpf_insn *insn_buf,
18762 					    int *cnt)
18763 {
18764 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18765 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18766 
18767 	insn_buf[0] = addr[0];
18768 	insn_buf[1] = addr[1];
18769 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18770 	insn_buf[3] = *insn;
18771 	*cnt = 4;
18772 }
18773 
18774 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18775 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18776 {
18777 	const struct bpf_kfunc_desc *desc;
18778 
18779 	if (!insn->imm) {
18780 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18781 		return -EINVAL;
18782 	}
18783 
18784 	*cnt = 0;
18785 
18786 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18787 	 * __bpf_call_base, unless the JIT needs to call functions that are
18788 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18789 	 */
18790 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18791 	if (!desc) {
18792 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18793 			insn->imm);
18794 		return -EFAULT;
18795 	}
18796 
18797 	if (!bpf_jit_supports_far_kfunc_call())
18798 		insn->imm = BPF_CALL_IMM(desc->addr);
18799 	if (insn->off)
18800 		return 0;
18801 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18802 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18803 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18804 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18805 
18806 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18807 		insn_buf[1] = addr[0];
18808 		insn_buf[2] = addr[1];
18809 		insn_buf[3] = *insn;
18810 		*cnt = 4;
18811 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18812 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18813 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18814 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18815 
18816 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18817 		    !kptr_struct_meta) {
18818 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18819 				insn_idx);
18820 			return -EFAULT;
18821 		}
18822 
18823 		insn_buf[0] = addr[0];
18824 		insn_buf[1] = addr[1];
18825 		insn_buf[2] = *insn;
18826 		*cnt = 3;
18827 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18828 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18829 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18830 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18831 		int struct_meta_reg = BPF_REG_3;
18832 		int node_offset_reg = BPF_REG_4;
18833 
18834 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18835 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18836 			struct_meta_reg = BPF_REG_4;
18837 			node_offset_reg = BPF_REG_5;
18838 		}
18839 
18840 		if (!kptr_struct_meta) {
18841 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18842 				insn_idx);
18843 			return -EFAULT;
18844 		}
18845 
18846 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18847 						node_offset_reg, insn, insn_buf, cnt);
18848 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18849 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18850 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18851 		*cnt = 1;
18852 	}
18853 	return 0;
18854 }
18855 
18856 /* Do various post-verification rewrites in a single program pass.
18857  * These rewrites simplify JIT and interpreter implementations.
18858  */
18859 static int do_misc_fixups(struct bpf_verifier_env *env)
18860 {
18861 	struct bpf_prog *prog = env->prog;
18862 	enum bpf_attach_type eatype = prog->expected_attach_type;
18863 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18864 	struct bpf_insn *insn = prog->insnsi;
18865 	const struct bpf_func_proto *fn;
18866 	const int insn_cnt = prog->len;
18867 	const struct bpf_map_ops *ops;
18868 	struct bpf_insn_aux_data *aux;
18869 	struct bpf_insn insn_buf[16];
18870 	struct bpf_prog *new_prog;
18871 	struct bpf_map *map_ptr;
18872 	int i, ret, cnt, delta = 0;
18873 
18874 	for (i = 0; i < insn_cnt; i++, insn++) {
18875 		/* Make divide-by-zero exceptions impossible. */
18876 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18877 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18878 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18879 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18880 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18881 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18882 			struct bpf_insn *patchlet;
18883 			struct bpf_insn chk_and_div[] = {
18884 				/* [R,W]x div 0 -> 0 */
18885 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18886 					     BPF_JNE | BPF_K, insn->src_reg,
18887 					     0, 2, 0),
18888 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18889 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18890 				*insn,
18891 			};
18892 			struct bpf_insn chk_and_mod[] = {
18893 				/* [R,W]x mod 0 -> [R,W]x */
18894 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18895 					     BPF_JEQ | BPF_K, insn->src_reg,
18896 					     0, 1 + (is64 ? 0 : 1), 0),
18897 				*insn,
18898 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18899 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18900 			};
18901 
18902 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18903 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18904 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18905 
18906 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18907 			if (!new_prog)
18908 				return -ENOMEM;
18909 
18910 			delta    += cnt - 1;
18911 			env->prog = prog = new_prog;
18912 			insn      = new_prog->insnsi + i + delta;
18913 			continue;
18914 		}
18915 
18916 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18917 		if (BPF_CLASS(insn->code) == BPF_LD &&
18918 		    (BPF_MODE(insn->code) == BPF_ABS ||
18919 		     BPF_MODE(insn->code) == BPF_IND)) {
18920 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18921 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18922 				verbose(env, "bpf verifier is misconfigured\n");
18923 				return -EINVAL;
18924 			}
18925 
18926 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18927 			if (!new_prog)
18928 				return -ENOMEM;
18929 
18930 			delta    += cnt - 1;
18931 			env->prog = prog = new_prog;
18932 			insn      = new_prog->insnsi + i + delta;
18933 			continue;
18934 		}
18935 
18936 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18937 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18938 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18939 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18940 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18941 			struct bpf_insn *patch = &insn_buf[0];
18942 			bool issrc, isneg, isimm;
18943 			u32 off_reg;
18944 
18945 			aux = &env->insn_aux_data[i + delta];
18946 			if (!aux->alu_state ||
18947 			    aux->alu_state == BPF_ALU_NON_POINTER)
18948 				continue;
18949 
18950 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18951 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18952 				BPF_ALU_SANITIZE_SRC;
18953 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18954 
18955 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18956 			if (isimm) {
18957 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18958 			} else {
18959 				if (isneg)
18960 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18961 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18962 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18963 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18964 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18965 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18966 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18967 			}
18968 			if (!issrc)
18969 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18970 			insn->src_reg = BPF_REG_AX;
18971 			if (isneg)
18972 				insn->code = insn->code == code_add ?
18973 					     code_sub : code_add;
18974 			*patch++ = *insn;
18975 			if (issrc && isneg && !isimm)
18976 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18977 			cnt = patch - insn_buf;
18978 
18979 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18980 			if (!new_prog)
18981 				return -ENOMEM;
18982 
18983 			delta    += cnt - 1;
18984 			env->prog = prog = new_prog;
18985 			insn      = new_prog->insnsi + i + delta;
18986 			continue;
18987 		}
18988 
18989 		if (insn->code != (BPF_JMP | BPF_CALL))
18990 			continue;
18991 		if (insn->src_reg == BPF_PSEUDO_CALL)
18992 			continue;
18993 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18994 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18995 			if (ret)
18996 				return ret;
18997 			if (cnt == 0)
18998 				continue;
18999 
19000 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19001 			if (!new_prog)
19002 				return -ENOMEM;
19003 
19004 			delta	 += cnt - 1;
19005 			env->prog = prog = new_prog;
19006 			insn	  = new_prog->insnsi + i + delta;
19007 			continue;
19008 		}
19009 
19010 		if (insn->imm == BPF_FUNC_get_route_realm)
19011 			prog->dst_needed = 1;
19012 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19013 			bpf_user_rnd_init_once();
19014 		if (insn->imm == BPF_FUNC_override_return)
19015 			prog->kprobe_override = 1;
19016 		if (insn->imm == BPF_FUNC_tail_call) {
19017 			/* If we tail call into other programs, we
19018 			 * cannot make any assumptions since they can
19019 			 * be replaced dynamically during runtime in
19020 			 * the program array.
19021 			 */
19022 			prog->cb_access = 1;
19023 			if (!allow_tail_call_in_subprogs(env))
19024 				prog->aux->stack_depth = MAX_BPF_STACK;
19025 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19026 
19027 			/* mark bpf_tail_call as different opcode to avoid
19028 			 * conditional branch in the interpreter for every normal
19029 			 * call and to prevent accidental JITing by JIT compiler
19030 			 * that doesn't support bpf_tail_call yet
19031 			 */
19032 			insn->imm = 0;
19033 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19034 
19035 			aux = &env->insn_aux_data[i + delta];
19036 			if (env->bpf_capable && !prog->blinding_requested &&
19037 			    prog->jit_requested &&
19038 			    !bpf_map_key_poisoned(aux) &&
19039 			    !bpf_map_ptr_poisoned(aux) &&
19040 			    !bpf_map_ptr_unpriv(aux)) {
19041 				struct bpf_jit_poke_descriptor desc = {
19042 					.reason = BPF_POKE_REASON_TAIL_CALL,
19043 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19044 					.tail_call.key = bpf_map_key_immediate(aux),
19045 					.insn_idx = i + delta,
19046 				};
19047 
19048 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19049 				if (ret < 0) {
19050 					verbose(env, "adding tail call poke descriptor failed\n");
19051 					return ret;
19052 				}
19053 
19054 				insn->imm = ret + 1;
19055 				continue;
19056 			}
19057 
19058 			if (!bpf_map_ptr_unpriv(aux))
19059 				continue;
19060 
19061 			/* instead of changing every JIT dealing with tail_call
19062 			 * emit two extra insns:
19063 			 * if (index >= max_entries) goto out;
19064 			 * index &= array->index_mask;
19065 			 * to avoid out-of-bounds cpu speculation
19066 			 */
19067 			if (bpf_map_ptr_poisoned(aux)) {
19068 				verbose(env, "tail_call abusing map_ptr\n");
19069 				return -EINVAL;
19070 			}
19071 
19072 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19073 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19074 						  map_ptr->max_entries, 2);
19075 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19076 						    container_of(map_ptr,
19077 								 struct bpf_array,
19078 								 map)->index_mask);
19079 			insn_buf[2] = *insn;
19080 			cnt = 3;
19081 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19082 			if (!new_prog)
19083 				return -ENOMEM;
19084 
19085 			delta    += cnt - 1;
19086 			env->prog = prog = new_prog;
19087 			insn      = new_prog->insnsi + i + delta;
19088 			continue;
19089 		}
19090 
19091 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19092 			/* The verifier will process callback_fn as many times as necessary
19093 			 * with different maps and the register states prepared by
19094 			 * set_timer_callback_state will be accurate.
19095 			 *
19096 			 * The following use case is valid:
19097 			 *   map1 is shared by prog1, prog2, prog3.
19098 			 *   prog1 calls bpf_timer_init for some map1 elements
19099 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19100 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19101 			 *   prog3 calls bpf_timer_start for some map1 elements.
19102 			 *     Those that were not both bpf_timer_init-ed and
19103 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19104 			 */
19105 			struct bpf_insn ld_addrs[2] = {
19106 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19107 			};
19108 
19109 			insn_buf[0] = ld_addrs[0];
19110 			insn_buf[1] = ld_addrs[1];
19111 			insn_buf[2] = *insn;
19112 			cnt = 3;
19113 
19114 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19115 			if (!new_prog)
19116 				return -ENOMEM;
19117 
19118 			delta    += cnt - 1;
19119 			env->prog = prog = new_prog;
19120 			insn      = new_prog->insnsi + i + delta;
19121 			goto patch_call_imm;
19122 		}
19123 
19124 		if (is_storage_get_function(insn->imm)) {
19125 			if (!env->prog->aux->sleepable ||
19126 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19127 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19128 			else
19129 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19130 			insn_buf[1] = *insn;
19131 			cnt = 2;
19132 
19133 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19134 			if (!new_prog)
19135 				return -ENOMEM;
19136 
19137 			delta += cnt - 1;
19138 			env->prog = prog = new_prog;
19139 			insn = new_prog->insnsi + i + delta;
19140 			goto patch_call_imm;
19141 		}
19142 
19143 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19144 		 * and other inlining handlers are currently limited to 64 bit
19145 		 * only.
19146 		 */
19147 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19148 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19149 		     insn->imm == BPF_FUNC_map_update_elem ||
19150 		     insn->imm == BPF_FUNC_map_delete_elem ||
19151 		     insn->imm == BPF_FUNC_map_push_elem   ||
19152 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19153 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19154 		     insn->imm == BPF_FUNC_redirect_map    ||
19155 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19156 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19157 			aux = &env->insn_aux_data[i + delta];
19158 			if (bpf_map_ptr_poisoned(aux))
19159 				goto patch_call_imm;
19160 
19161 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19162 			ops = map_ptr->ops;
19163 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19164 			    ops->map_gen_lookup) {
19165 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19166 				if (cnt == -EOPNOTSUPP)
19167 					goto patch_map_ops_generic;
19168 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19169 					verbose(env, "bpf verifier is misconfigured\n");
19170 					return -EINVAL;
19171 				}
19172 
19173 				new_prog = bpf_patch_insn_data(env, i + delta,
19174 							       insn_buf, cnt);
19175 				if (!new_prog)
19176 					return -ENOMEM;
19177 
19178 				delta    += cnt - 1;
19179 				env->prog = prog = new_prog;
19180 				insn      = new_prog->insnsi + i + delta;
19181 				continue;
19182 			}
19183 
19184 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19185 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19186 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19187 				     (long (*)(struct bpf_map *map, void *key))NULL));
19188 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19189 				     (long (*)(struct bpf_map *map, void *key, void *value,
19190 					      u64 flags))NULL));
19191 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19192 				     (long (*)(struct bpf_map *map, void *value,
19193 					      u64 flags))NULL));
19194 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19195 				     (long (*)(struct bpf_map *map, void *value))NULL));
19196 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19197 				     (long (*)(struct bpf_map *map, void *value))NULL));
19198 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19199 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19200 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19201 				     (long (*)(struct bpf_map *map,
19202 					      bpf_callback_t callback_fn,
19203 					      void *callback_ctx,
19204 					      u64 flags))NULL));
19205 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19206 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19207 
19208 patch_map_ops_generic:
19209 			switch (insn->imm) {
19210 			case BPF_FUNC_map_lookup_elem:
19211 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19212 				continue;
19213 			case BPF_FUNC_map_update_elem:
19214 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19215 				continue;
19216 			case BPF_FUNC_map_delete_elem:
19217 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19218 				continue;
19219 			case BPF_FUNC_map_push_elem:
19220 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19221 				continue;
19222 			case BPF_FUNC_map_pop_elem:
19223 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19224 				continue;
19225 			case BPF_FUNC_map_peek_elem:
19226 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19227 				continue;
19228 			case BPF_FUNC_redirect_map:
19229 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19230 				continue;
19231 			case BPF_FUNC_for_each_map_elem:
19232 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19233 				continue;
19234 			case BPF_FUNC_map_lookup_percpu_elem:
19235 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19236 				continue;
19237 			}
19238 
19239 			goto patch_call_imm;
19240 		}
19241 
19242 		/* Implement bpf_jiffies64 inline. */
19243 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19244 		    insn->imm == BPF_FUNC_jiffies64) {
19245 			struct bpf_insn ld_jiffies_addr[2] = {
19246 				BPF_LD_IMM64(BPF_REG_0,
19247 					     (unsigned long)&jiffies),
19248 			};
19249 
19250 			insn_buf[0] = ld_jiffies_addr[0];
19251 			insn_buf[1] = ld_jiffies_addr[1];
19252 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19253 						  BPF_REG_0, 0);
19254 			cnt = 3;
19255 
19256 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19257 						       cnt);
19258 			if (!new_prog)
19259 				return -ENOMEM;
19260 
19261 			delta    += cnt - 1;
19262 			env->prog = prog = new_prog;
19263 			insn      = new_prog->insnsi + i + delta;
19264 			continue;
19265 		}
19266 
19267 		/* Implement bpf_get_func_arg inline. */
19268 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19269 		    insn->imm == BPF_FUNC_get_func_arg) {
19270 			/* Load nr_args from ctx - 8 */
19271 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19272 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19273 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19274 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19275 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19276 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19277 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19278 			insn_buf[7] = BPF_JMP_A(1);
19279 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19280 			cnt = 9;
19281 
19282 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19283 			if (!new_prog)
19284 				return -ENOMEM;
19285 
19286 			delta    += cnt - 1;
19287 			env->prog = prog = new_prog;
19288 			insn      = new_prog->insnsi + i + delta;
19289 			continue;
19290 		}
19291 
19292 		/* Implement bpf_get_func_ret inline. */
19293 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19294 		    insn->imm == BPF_FUNC_get_func_ret) {
19295 			if (eatype == BPF_TRACE_FEXIT ||
19296 			    eatype == BPF_MODIFY_RETURN) {
19297 				/* Load nr_args from ctx - 8 */
19298 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19299 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19300 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19301 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19302 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19303 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19304 				cnt = 6;
19305 			} else {
19306 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19307 				cnt = 1;
19308 			}
19309 
19310 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19311 			if (!new_prog)
19312 				return -ENOMEM;
19313 
19314 			delta    += cnt - 1;
19315 			env->prog = prog = new_prog;
19316 			insn      = new_prog->insnsi + i + delta;
19317 			continue;
19318 		}
19319 
19320 		/* Implement get_func_arg_cnt inline. */
19321 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19322 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19323 			/* Load nr_args from ctx - 8 */
19324 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19325 
19326 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19327 			if (!new_prog)
19328 				return -ENOMEM;
19329 
19330 			env->prog = prog = new_prog;
19331 			insn      = new_prog->insnsi + i + delta;
19332 			continue;
19333 		}
19334 
19335 		/* Implement bpf_get_func_ip inline. */
19336 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19337 		    insn->imm == BPF_FUNC_get_func_ip) {
19338 			/* Load IP address from ctx - 16 */
19339 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19340 
19341 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19342 			if (!new_prog)
19343 				return -ENOMEM;
19344 
19345 			env->prog = prog = new_prog;
19346 			insn      = new_prog->insnsi + i + delta;
19347 			continue;
19348 		}
19349 
19350 patch_call_imm:
19351 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19352 		/* all functions that have prototype and verifier allowed
19353 		 * programs to call them, must be real in-kernel functions
19354 		 */
19355 		if (!fn->func) {
19356 			verbose(env,
19357 				"kernel subsystem misconfigured func %s#%d\n",
19358 				func_id_name(insn->imm), insn->imm);
19359 			return -EFAULT;
19360 		}
19361 		insn->imm = fn->func - __bpf_call_base;
19362 	}
19363 
19364 	/* Since poke tab is now finalized, publish aux to tracker. */
19365 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19366 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19367 		if (!map_ptr->ops->map_poke_track ||
19368 		    !map_ptr->ops->map_poke_untrack ||
19369 		    !map_ptr->ops->map_poke_run) {
19370 			verbose(env, "bpf verifier is misconfigured\n");
19371 			return -EINVAL;
19372 		}
19373 
19374 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19375 		if (ret < 0) {
19376 			verbose(env, "tracking tail call prog failed\n");
19377 			return ret;
19378 		}
19379 	}
19380 
19381 	sort_kfunc_descs_by_imm_off(env->prog);
19382 
19383 	return 0;
19384 }
19385 
19386 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19387 					int position,
19388 					s32 stack_base,
19389 					u32 callback_subprogno,
19390 					u32 *cnt)
19391 {
19392 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19393 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19394 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19395 	int reg_loop_max = BPF_REG_6;
19396 	int reg_loop_cnt = BPF_REG_7;
19397 	int reg_loop_ctx = BPF_REG_8;
19398 
19399 	struct bpf_prog *new_prog;
19400 	u32 callback_start;
19401 	u32 call_insn_offset;
19402 	s32 callback_offset;
19403 
19404 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19405 	 * be careful to modify this code in sync.
19406 	 */
19407 	struct bpf_insn insn_buf[] = {
19408 		/* Return error and jump to the end of the patch if
19409 		 * expected number of iterations is too big.
19410 		 */
19411 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19412 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19413 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19414 		/* spill R6, R7, R8 to use these as loop vars */
19415 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19416 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19417 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19418 		/* initialize loop vars */
19419 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19420 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19421 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19422 		/* loop header,
19423 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19424 		 */
19425 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19426 		/* callback call,
19427 		 * correct callback offset would be set after patching
19428 		 */
19429 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19430 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19431 		BPF_CALL_REL(0),
19432 		/* increment loop counter */
19433 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19434 		/* jump to loop header if callback returned 0 */
19435 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19436 		/* return value of bpf_loop,
19437 		 * set R0 to the number of iterations
19438 		 */
19439 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19440 		/* restore original values of R6, R7, R8 */
19441 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19442 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19443 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19444 	};
19445 
19446 	*cnt = ARRAY_SIZE(insn_buf);
19447 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19448 	if (!new_prog)
19449 		return new_prog;
19450 
19451 	/* callback start is known only after patching */
19452 	callback_start = env->subprog_info[callback_subprogno].start;
19453 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19454 	call_insn_offset = position + 12;
19455 	callback_offset = callback_start - call_insn_offset - 1;
19456 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19457 
19458 	return new_prog;
19459 }
19460 
19461 static bool is_bpf_loop_call(struct bpf_insn *insn)
19462 {
19463 	return insn->code == (BPF_JMP | BPF_CALL) &&
19464 		insn->src_reg == 0 &&
19465 		insn->imm == BPF_FUNC_loop;
19466 }
19467 
19468 /* For all sub-programs in the program (including main) check
19469  * insn_aux_data to see if there are bpf_loop calls that require
19470  * inlining. If such calls are found the calls are replaced with a
19471  * sequence of instructions produced by `inline_bpf_loop` function and
19472  * subprog stack_depth is increased by the size of 3 registers.
19473  * This stack space is used to spill values of the R6, R7, R8.  These
19474  * registers are used to store the loop bound, counter and context
19475  * variables.
19476  */
19477 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19478 {
19479 	struct bpf_subprog_info *subprogs = env->subprog_info;
19480 	int i, cur_subprog = 0, cnt, delta = 0;
19481 	struct bpf_insn *insn = env->prog->insnsi;
19482 	int insn_cnt = env->prog->len;
19483 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19484 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19485 	u16 stack_depth_extra = 0;
19486 
19487 	for (i = 0; i < insn_cnt; i++, insn++) {
19488 		struct bpf_loop_inline_state *inline_state =
19489 			&env->insn_aux_data[i + delta].loop_inline_state;
19490 
19491 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19492 			struct bpf_prog *new_prog;
19493 
19494 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19495 			new_prog = inline_bpf_loop(env,
19496 						   i + delta,
19497 						   -(stack_depth + stack_depth_extra),
19498 						   inline_state->callback_subprogno,
19499 						   &cnt);
19500 			if (!new_prog)
19501 				return -ENOMEM;
19502 
19503 			delta     += cnt - 1;
19504 			env->prog  = new_prog;
19505 			insn       = new_prog->insnsi + i + delta;
19506 		}
19507 
19508 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19509 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19510 			cur_subprog++;
19511 			stack_depth = subprogs[cur_subprog].stack_depth;
19512 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19513 			stack_depth_extra = 0;
19514 		}
19515 	}
19516 
19517 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19518 
19519 	return 0;
19520 }
19521 
19522 static void free_states(struct bpf_verifier_env *env)
19523 {
19524 	struct bpf_verifier_state_list *sl, *sln;
19525 	int i;
19526 
19527 	sl = env->free_list;
19528 	while (sl) {
19529 		sln = sl->next;
19530 		free_verifier_state(&sl->state, false);
19531 		kfree(sl);
19532 		sl = sln;
19533 	}
19534 	env->free_list = NULL;
19535 
19536 	if (!env->explored_states)
19537 		return;
19538 
19539 	for (i = 0; i < state_htab_size(env); i++) {
19540 		sl = env->explored_states[i];
19541 
19542 		while (sl) {
19543 			sln = sl->next;
19544 			free_verifier_state(&sl->state, false);
19545 			kfree(sl);
19546 			sl = sln;
19547 		}
19548 		env->explored_states[i] = NULL;
19549 	}
19550 }
19551 
19552 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19553 {
19554 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19555 	struct bpf_verifier_state *state;
19556 	struct bpf_reg_state *regs;
19557 	int ret, i;
19558 
19559 	env->prev_linfo = NULL;
19560 	env->pass_cnt++;
19561 
19562 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19563 	if (!state)
19564 		return -ENOMEM;
19565 	state->curframe = 0;
19566 	state->speculative = false;
19567 	state->branches = 1;
19568 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19569 	if (!state->frame[0]) {
19570 		kfree(state);
19571 		return -ENOMEM;
19572 	}
19573 	env->cur_state = state;
19574 	init_func_state(env, state->frame[0],
19575 			BPF_MAIN_FUNC /* callsite */,
19576 			0 /* frameno */,
19577 			subprog);
19578 	state->first_insn_idx = env->subprog_info[subprog].start;
19579 	state->last_insn_idx = -1;
19580 
19581 	regs = state->frame[state->curframe]->regs;
19582 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19583 		ret = btf_prepare_func_args(env, subprog, regs);
19584 		if (ret)
19585 			goto out;
19586 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19587 			if (regs[i].type == PTR_TO_CTX)
19588 				mark_reg_known_zero(env, regs, i);
19589 			else if (regs[i].type == SCALAR_VALUE)
19590 				mark_reg_unknown(env, regs, i);
19591 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19592 				const u32 mem_size = regs[i].mem_size;
19593 
19594 				mark_reg_known_zero(env, regs, i);
19595 				regs[i].mem_size = mem_size;
19596 				regs[i].id = ++env->id_gen;
19597 			}
19598 		}
19599 	} else {
19600 		/* 1st arg to a function */
19601 		regs[BPF_REG_1].type = PTR_TO_CTX;
19602 		mark_reg_known_zero(env, regs, BPF_REG_1);
19603 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19604 		if (ret == -EFAULT)
19605 			/* unlikely verifier bug. abort.
19606 			 * ret == 0 and ret < 0 are sadly acceptable for
19607 			 * main() function due to backward compatibility.
19608 			 * Like socket filter program may be written as:
19609 			 * int bpf_prog(struct pt_regs *ctx)
19610 			 * and never dereference that ctx in the program.
19611 			 * 'struct pt_regs' is a type mismatch for socket
19612 			 * filter that should be using 'struct __sk_buff'.
19613 			 */
19614 			goto out;
19615 	}
19616 
19617 	ret = do_check(env);
19618 out:
19619 	/* check for NULL is necessary, since cur_state can be freed inside
19620 	 * do_check() under memory pressure.
19621 	 */
19622 	if (env->cur_state) {
19623 		free_verifier_state(env->cur_state, true);
19624 		env->cur_state = NULL;
19625 	}
19626 	while (!pop_stack(env, NULL, NULL, false));
19627 	if (!ret && pop_log)
19628 		bpf_vlog_reset(&env->log, 0);
19629 	free_states(env);
19630 	return ret;
19631 }
19632 
19633 /* Verify all global functions in a BPF program one by one based on their BTF.
19634  * All global functions must pass verification. Otherwise the whole program is rejected.
19635  * Consider:
19636  * int bar(int);
19637  * int foo(int f)
19638  * {
19639  *    return bar(f);
19640  * }
19641  * int bar(int b)
19642  * {
19643  *    ...
19644  * }
19645  * foo() will be verified first for R1=any_scalar_value. During verification it
19646  * will be assumed that bar() already verified successfully and call to bar()
19647  * from foo() will be checked for type match only. Later bar() will be verified
19648  * independently to check that it's safe for R1=any_scalar_value.
19649  */
19650 static int do_check_subprogs(struct bpf_verifier_env *env)
19651 {
19652 	struct bpf_prog_aux *aux = env->prog->aux;
19653 	int i, ret;
19654 
19655 	if (!aux->func_info)
19656 		return 0;
19657 
19658 	for (i = 1; i < env->subprog_cnt; i++) {
19659 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19660 			continue;
19661 		env->insn_idx = env->subprog_info[i].start;
19662 		WARN_ON_ONCE(env->insn_idx == 0);
19663 		ret = do_check_common(env, i);
19664 		if (ret) {
19665 			return ret;
19666 		} else if (env->log.level & BPF_LOG_LEVEL) {
19667 			verbose(env,
19668 				"Func#%d is safe for any args that match its prototype\n",
19669 				i);
19670 		}
19671 	}
19672 	return 0;
19673 }
19674 
19675 static int do_check_main(struct bpf_verifier_env *env)
19676 {
19677 	int ret;
19678 
19679 	env->insn_idx = 0;
19680 	ret = do_check_common(env, 0);
19681 	if (!ret)
19682 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19683 	return ret;
19684 }
19685 
19686 
19687 static void print_verification_stats(struct bpf_verifier_env *env)
19688 {
19689 	int i;
19690 
19691 	if (env->log.level & BPF_LOG_STATS) {
19692 		verbose(env, "verification time %lld usec\n",
19693 			div_u64(env->verification_time, 1000));
19694 		verbose(env, "stack depth ");
19695 		for (i = 0; i < env->subprog_cnt; i++) {
19696 			u32 depth = env->subprog_info[i].stack_depth;
19697 
19698 			verbose(env, "%d", depth);
19699 			if (i + 1 < env->subprog_cnt)
19700 				verbose(env, "+");
19701 		}
19702 		verbose(env, "\n");
19703 	}
19704 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19705 		"total_states %d peak_states %d mark_read %d\n",
19706 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19707 		env->max_states_per_insn, env->total_states,
19708 		env->peak_states, env->longest_mark_read_walk);
19709 }
19710 
19711 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19712 {
19713 	const struct btf_type *t, *func_proto;
19714 	const struct bpf_struct_ops *st_ops;
19715 	const struct btf_member *member;
19716 	struct bpf_prog *prog = env->prog;
19717 	u32 btf_id, member_idx;
19718 	const char *mname;
19719 
19720 	if (!prog->gpl_compatible) {
19721 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19722 		return -EINVAL;
19723 	}
19724 
19725 	btf_id = prog->aux->attach_btf_id;
19726 	st_ops = bpf_struct_ops_find(btf_id);
19727 	if (!st_ops) {
19728 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19729 			btf_id);
19730 		return -ENOTSUPP;
19731 	}
19732 
19733 	t = st_ops->type;
19734 	member_idx = prog->expected_attach_type;
19735 	if (member_idx >= btf_type_vlen(t)) {
19736 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19737 			member_idx, st_ops->name);
19738 		return -EINVAL;
19739 	}
19740 
19741 	member = &btf_type_member(t)[member_idx];
19742 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19743 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19744 					       NULL);
19745 	if (!func_proto) {
19746 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19747 			mname, member_idx, st_ops->name);
19748 		return -EINVAL;
19749 	}
19750 
19751 	if (st_ops->check_member) {
19752 		int err = st_ops->check_member(t, member, prog);
19753 
19754 		if (err) {
19755 			verbose(env, "attach to unsupported member %s of struct %s\n",
19756 				mname, st_ops->name);
19757 			return err;
19758 		}
19759 	}
19760 
19761 	prog->aux->attach_func_proto = func_proto;
19762 	prog->aux->attach_func_name = mname;
19763 	env->ops = st_ops->verifier_ops;
19764 
19765 	return 0;
19766 }
19767 #define SECURITY_PREFIX "security_"
19768 
19769 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19770 {
19771 	if (within_error_injection_list(addr) ||
19772 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19773 		return 0;
19774 
19775 	return -EINVAL;
19776 }
19777 
19778 /* list of non-sleepable functions that are otherwise on
19779  * ALLOW_ERROR_INJECTION list
19780  */
19781 BTF_SET_START(btf_non_sleepable_error_inject)
19782 /* Three functions below can be called from sleepable and non-sleepable context.
19783  * Assume non-sleepable from bpf safety point of view.
19784  */
19785 BTF_ID(func, __filemap_add_folio)
19786 BTF_ID(func, should_fail_alloc_page)
19787 BTF_ID(func, should_failslab)
19788 BTF_SET_END(btf_non_sleepable_error_inject)
19789 
19790 static int check_non_sleepable_error_inject(u32 btf_id)
19791 {
19792 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19793 }
19794 
19795 int bpf_check_attach_target(struct bpf_verifier_log *log,
19796 			    const struct bpf_prog *prog,
19797 			    const struct bpf_prog *tgt_prog,
19798 			    u32 btf_id,
19799 			    struct bpf_attach_target_info *tgt_info)
19800 {
19801 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19802 	const char prefix[] = "btf_trace_";
19803 	int ret = 0, subprog = -1, i;
19804 	const struct btf_type *t;
19805 	bool conservative = true;
19806 	const char *tname;
19807 	struct btf *btf;
19808 	long addr = 0;
19809 	struct module *mod = NULL;
19810 
19811 	if (!btf_id) {
19812 		bpf_log(log, "Tracing programs must provide btf_id\n");
19813 		return -EINVAL;
19814 	}
19815 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19816 	if (!btf) {
19817 		bpf_log(log,
19818 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19819 		return -EINVAL;
19820 	}
19821 	t = btf_type_by_id(btf, btf_id);
19822 	if (!t) {
19823 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19824 		return -EINVAL;
19825 	}
19826 	tname = btf_name_by_offset(btf, t->name_off);
19827 	if (!tname) {
19828 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19829 		return -EINVAL;
19830 	}
19831 	if (tgt_prog) {
19832 		struct bpf_prog_aux *aux = tgt_prog->aux;
19833 
19834 		if (bpf_prog_is_dev_bound(prog->aux) &&
19835 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19836 			bpf_log(log, "Target program bound device mismatch");
19837 			return -EINVAL;
19838 		}
19839 
19840 		for (i = 0; i < aux->func_info_cnt; i++)
19841 			if (aux->func_info[i].type_id == btf_id) {
19842 				subprog = i;
19843 				break;
19844 			}
19845 		if (subprog == -1) {
19846 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19847 			return -EINVAL;
19848 		}
19849 		conservative = aux->func_info_aux[subprog].unreliable;
19850 		if (prog_extension) {
19851 			if (conservative) {
19852 				bpf_log(log,
19853 					"Cannot replace static functions\n");
19854 				return -EINVAL;
19855 			}
19856 			if (!prog->jit_requested) {
19857 				bpf_log(log,
19858 					"Extension programs should be JITed\n");
19859 				return -EINVAL;
19860 			}
19861 		}
19862 		if (!tgt_prog->jited) {
19863 			bpf_log(log, "Can attach to only JITed progs\n");
19864 			return -EINVAL;
19865 		}
19866 		if (tgt_prog->type == prog->type) {
19867 			/* Cannot fentry/fexit another fentry/fexit program.
19868 			 * Cannot attach program extension to another extension.
19869 			 * It's ok to attach fentry/fexit to extension program.
19870 			 */
19871 			bpf_log(log, "Cannot recursively attach\n");
19872 			return -EINVAL;
19873 		}
19874 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19875 		    prog_extension &&
19876 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19877 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19878 			/* Program extensions can extend all program types
19879 			 * except fentry/fexit. The reason is the following.
19880 			 * The fentry/fexit programs are used for performance
19881 			 * analysis, stats and can be attached to any program
19882 			 * type except themselves. When extension program is
19883 			 * replacing XDP function it is necessary to allow
19884 			 * performance analysis of all functions. Both original
19885 			 * XDP program and its program extension. Hence
19886 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19887 			 * allowed. If extending of fentry/fexit was allowed it
19888 			 * would be possible to create long call chain
19889 			 * fentry->extension->fentry->extension beyond
19890 			 * reasonable stack size. Hence extending fentry is not
19891 			 * allowed.
19892 			 */
19893 			bpf_log(log, "Cannot extend fentry/fexit\n");
19894 			return -EINVAL;
19895 		}
19896 	} else {
19897 		if (prog_extension) {
19898 			bpf_log(log, "Cannot replace kernel functions\n");
19899 			return -EINVAL;
19900 		}
19901 	}
19902 
19903 	switch (prog->expected_attach_type) {
19904 	case BPF_TRACE_RAW_TP:
19905 		if (tgt_prog) {
19906 			bpf_log(log,
19907 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19908 			return -EINVAL;
19909 		}
19910 		if (!btf_type_is_typedef(t)) {
19911 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19912 				btf_id);
19913 			return -EINVAL;
19914 		}
19915 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19916 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19917 				btf_id, tname);
19918 			return -EINVAL;
19919 		}
19920 		tname += sizeof(prefix) - 1;
19921 		t = btf_type_by_id(btf, t->type);
19922 		if (!btf_type_is_ptr(t))
19923 			/* should never happen in valid vmlinux build */
19924 			return -EINVAL;
19925 		t = btf_type_by_id(btf, t->type);
19926 		if (!btf_type_is_func_proto(t))
19927 			/* should never happen in valid vmlinux build */
19928 			return -EINVAL;
19929 
19930 		break;
19931 	case BPF_TRACE_ITER:
19932 		if (!btf_type_is_func(t)) {
19933 			bpf_log(log, "attach_btf_id %u is not a function\n",
19934 				btf_id);
19935 			return -EINVAL;
19936 		}
19937 		t = btf_type_by_id(btf, t->type);
19938 		if (!btf_type_is_func_proto(t))
19939 			return -EINVAL;
19940 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19941 		if (ret)
19942 			return ret;
19943 		break;
19944 	default:
19945 		if (!prog_extension)
19946 			return -EINVAL;
19947 		fallthrough;
19948 	case BPF_MODIFY_RETURN:
19949 	case BPF_LSM_MAC:
19950 	case BPF_LSM_CGROUP:
19951 	case BPF_TRACE_FENTRY:
19952 	case BPF_TRACE_FEXIT:
19953 		if (!btf_type_is_func(t)) {
19954 			bpf_log(log, "attach_btf_id %u is not a function\n",
19955 				btf_id);
19956 			return -EINVAL;
19957 		}
19958 		if (prog_extension &&
19959 		    btf_check_type_match(log, prog, btf, t))
19960 			return -EINVAL;
19961 		t = btf_type_by_id(btf, t->type);
19962 		if (!btf_type_is_func_proto(t))
19963 			return -EINVAL;
19964 
19965 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19966 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19967 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19968 			return -EINVAL;
19969 
19970 		if (tgt_prog && conservative)
19971 			t = NULL;
19972 
19973 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19974 		if (ret < 0)
19975 			return ret;
19976 
19977 		if (tgt_prog) {
19978 			if (subprog == 0)
19979 				addr = (long) tgt_prog->bpf_func;
19980 			else
19981 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19982 		} else {
19983 			if (btf_is_module(btf)) {
19984 				mod = btf_try_get_module(btf);
19985 				if (mod)
19986 					addr = find_kallsyms_symbol_value(mod, tname);
19987 				else
19988 					addr = 0;
19989 			} else {
19990 				addr = kallsyms_lookup_name(tname);
19991 			}
19992 			if (!addr) {
19993 				module_put(mod);
19994 				bpf_log(log,
19995 					"The address of function %s cannot be found\n",
19996 					tname);
19997 				return -ENOENT;
19998 			}
19999 		}
20000 
20001 		if (prog->aux->sleepable) {
20002 			ret = -EINVAL;
20003 			switch (prog->type) {
20004 			case BPF_PROG_TYPE_TRACING:
20005 
20006 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20007 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20008 				 */
20009 				if (!check_non_sleepable_error_inject(btf_id) &&
20010 				    within_error_injection_list(addr))
20011 					ret = 0;
20012 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20013 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20014 				 */
20015 				else {
20016 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20017 										prog);
20018 
20019 					if (flags && (*flags & KF_SLEEPABLE))
20020 						ret = 0;
20021 				}
20022 				break;
20023 			case BPF_PROG_TYPE_LSM:
20024 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20025 				 * Only some of them are sleepable.
20026 				 */
20027 				if (bpf_lsm_is_sleepable_hook(btf_id))
20028 					ret = 0;
20029 				break;
20030 			default:
20031 				break;
20032 			}
20033 			if (ret) {
20034 				module_put(mod);
20035 				bpf_log(log, "%s is not sleepable\n", tname);
20036 				return ret;
20037 			}
20038 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20039 			if (tgt_prog) {
20040 				module_put(mod);
20041 				bpf_log(log, "can't modify return codes of BPF programs\n");
20042 				return -EINVAL;
20043 			}
20044 			ret = -EINVAL;
20045 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20046 			    !check_attach_modify_return(addr, tname))
20047 				ret = 0;
20048 			if (ret) {
20049 				module_put(mod);
20050 				bpf_log(log, "%s() is not modifiable\n", tname);
20051 				return ret;
20052 			}
20053 		}
20054 
20055 		break;
20056 	}
20057 	tgt_info->tgt_addr = addr;
20058 	tgt_info->tgt_name = tname;
20059 	tgt_info->tgt_type = t;
20060 	tgt_info->tgt_mod = mod;
20061 	return 0;
20062 }
20063 
20064 BTF_SET_START(btf_id_deny)
20065 BTF_ID_UNUSED
20066 #ifdef CONFIG_SMP
20067 BTF_ID(func, migrate_disable)
20068 BTF_ID(func, migrate_enable)
20069 #endif
20070 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20071 BTF_ID(func, rcu_read_unlock_strict)
20072 #endif
20073 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20074 BTF_ID(func, preempt_count_add)
20075 BTF_ID(func, preempt_count_sub)
20076 #endif
20077 #ifdef CONFIG_PREEMPT_RCU
20078 BTF_ID(func, __rcu_read_lock)
20079 BTF_ID(func, __rcu_read_unlock)
20080 #endif
20081 BTF_SET_END(btf_id_deny)
20082 
20083 static bool can_be_sleepable(struct bpf_prog *prog)
20084 {
20085 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20086 		switch (prog->expected_attach_type) {
20087 		case BPF_TRACE_FENTRY:
20088 		case BPF_TRACE_FEXIT:
20089 		case BPF_MODIFY_RETURN:
20090 		case BPF_TRACE_ITER:
20091 			return true;
20092 		default:
20093 			return false;
20094 		}
20095 	}
20096 	return prog->type == BPF_PROG_TYPE_LSM ||
20097 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20098 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20099 }
20100 
20101 static int check_attach_btf_id(struct bpf_verifier_env *env)
20102 {
20103 	struct bpf_prog *prog = env->prog;
20104 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20105 	struct bpf_attach_target_info tgt_info = {};
20106 	u32 btf_id = prog->aux->attach_btf_id;
20107 	struct bpf_trampoline *tr;
20108 	int ret;
20109 	u64 key;
20110 
20111 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20112 		if (prog->aux->sleepable)
20113 			/* attach_btf_id checked to be zero already */
20114 			return 0;
20115 		verbose(env, "Syscall programs can only be sleepable\n");
20116 		return -EINVAL;
20117 	}
20118 
20119 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20120 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20121 		return -EINVAL;
20122 	}
20123 
20124 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20125 		return check_struct_ops_btf_id(env);
20126 
20127 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20128 	    prog->type != BPF_PROG_TYPE_LSM &&
20129 	    prog->type != BPF_PROG_TYPE_EXT)
20130 		return 0;
20131 
20132 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20133 	if (ret)
20134 		return ret;
20135 
20136 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20137 		/* to make freplace equivalent to their targets, they need to
20138 		 * inherit env->ops and expected_attach_type for the rest of the
20139 		 * verification
20140 		 */
20141 		env->ops = bpf_verifier_ops[tgt_prog->type];
20142 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20143 	}
20144 
20145 	/* store info about the attachment target that will be used later */
20146 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20147 	prog->aux->attach_func_name = tgt_info.tgt_name;
20148 	prog->aux->mod = tgt_info.tgt_mod;
20149 
20150 	if (tgt_prog) {
20151 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20152 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20153 	}
20154 
20155 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20156 		prog->aux->attach_btf_trace = true;
20157 		return 0;
20158 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20159 		if (!bpf_iter_prog_supported(prog))
20160 			return -EINVAL;
20161 		return 0;
20162 	}
20163 
20164 	if (prog->type == BPF_PROG_TYPE_LSM) {
20165 		ret = bpf_lsm_verify_prog(&env->log, prog);
20166 		if (ret < 0)
20167 			return ret;
20168 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20169 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20170 		return -EINVAL;
20171 	}
20172 
20173 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20174 	tr = bpf_trampoline_get(key, &tgt_info);
20175 	if (!tr)
20176 		return -ENOMEM;
20177 
20178 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20179 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20180 
20181 	prog->aux->dst_trampoline = tr;
20182 	return 0;
20183 }
20184 
20185 struct btf *bpf_get_btf_vmlinux(void)
20186 {
20187 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20188 		mutex_lock(&bpf_verifier_lock);
20189 		if (!btf_vmlinux)
20190 			btf_vmlinux = btf_parse_vmlinux();
20191 		mutex_unlock(&bpf_verifier_lock);
20192 	}
20193 	return btf_vmlinux;
20194 }
20195 
20196 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20197 {
20198 	u64 start_time = ktime_get_ns();
20199 	struct bpf_verifier_env *env;
20200 	int i, len, ret = -EINVAL, err;
20201 	u32 log_true_size;
20202 	bool is_priv;
20203 
20204 	/* no program is valid */
20205 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20206 		return -EINVAL;
20207 
20208 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20209 	 * allocate/free it every time bpf_check() is called
20210 	 */
20211 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20212 	if (!env)
20213 		return -ENOMEM;
20214 
20215 	env->bt.env = env;
20216 
20217 	len = (*prog)->len;
20218 	env->insn_aux_data =
20219 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20220 	ret = -ENOMEM;
20221 	if (!env->insn_aux_data)
20222 		goto err_free_env;
20223 	for (i = 0; i < len; i++)
20224 		env->insn_aux_data[i].orig_idx = i;
20225 	env->prog = *prog;
20226 	env->ops = bpf_verifier_ops[env->prog->type];
20227 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20228 	is_priv = bpf_capable();
20229 
20230 	bpf_get_btf_vmlinux();
20231 
20232 	/* grab the mutex to protect few globals used by verifier */
20233 	if (!is_priv)
20234 		mutex_lock(&bpf_verifier_lock);
20235 
20236 	/* user could have requested verbose verifier output
20237 	 * and supplied buffer to store the verification trace
20238 	 */
20239 	ret = bpf_vlog_init(&env->log, attr->log_level,
20240 			    (char __user *) (unsigned long) attr->log_buf,
20241 			    attr->log_size);
20242 	if (ret)
20243 		goto err_unlock;
20244 
20245 	mark_verifier_state_clean(env);
20246 
20247 	if (IS_ERR(btf_vmlinux)) {
20248 		/* Either gcc or pahole or kernel are broken. */
20249 		verbose(env, "in-kernel BTF is malformed\n");
20250 		ret = PTR_ERR(btf_vmlinux);
20251 		goto skip_full_check;
20252 	}
20253 
20254 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20255 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20256 		env->strict_alignment = true;
20257 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20258 		env->strict_alignment = false;
20259 
20260 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20261 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20262 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20263 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20264 	env->bpf_capable = bpf_capable();
20265 
20266 	if (is_priv)
20267 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20268 
20269 	env->explored_states = kvcalloc(state_htab_size(env),
20270 				       sizeof(struct bpf_verifier_state_list *),
20271 				       GFP_USER);
20272 	ret = -ENOMEM;
20273 	if (!env->explored_states)
20274 		goto skip_full_check;
20275 
20276 	ret = add_subprog_and_kfunc(env);
20277 	if (ret < 0)
20278 		goto skip_full_check;
20279 
20280 	ret = check_subprogs(env);
20281 	if (ret < 0)
20282 		goto skip_full_check;
20283 
20284 	ret = check_btf_info(env, attr, uattr);
20285 	if (ret < 0)
20286 		goto skip_full_check;
20287 
20288 	ret = check_attach_btf_id(env);
20289 	if (ret)
20290 		goto skip_full_check;
20291 
20292 	ret = resolve_pseudo_ldimm64(env);
20293 	if (ret < 0)
20294 		goto skip_full_check;
20295 
20296 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20297 		ret = bpf_prog_offload_verifier_prep(env->prog);
20298 		if (ret)
20299 			goto skip_full_check;
20300 	}
20301 
20302 	ret = check_cfg(env);
20303 	if (ret < 0)
20304 		goto skip_full_check;
20305 
20306 	ret = do_check_subprogs(env);
20307 	ret = ret ?: do_check_main(env);
20308 
20309 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20310 		ret = bpf_prog_offload_finalize(env);
20311 
20312 skip_full_check:
20313 	kvfree(env->explored_states);
20314 
20315 	if (ret == 0)
20316 		ret = check_max_stack_depth(env);
20317 
20318 	/* instruction rewrites happen after this point */
20319 	if (ret == 0)
20320 		ret = optimize_bpf_loop(env);
20321 
20322 	if (is_priv) {
20323 		if (ret == 0)
20324 			opt_hard_wire_dead_code_branches(env);
20325 		if (ret == 0)
20326 			ret = opt_remove_dead_code(env);
20327 		if (ret == 0)
20328 			ret = opt_remove_nops(env);
20329 	} else {
20330 		if (ret == 0)
20331 			sanitize_dead_code(env);
20332 	}
20333 
20334 	if (ret == 0)
20335 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20336 		ret = convert_ctx_accesses(env);
20337 
20338 	if (ret == 0)
20339 		ret = do_misc_fixups(env);
20340 
20341 	/* do 32-bit optimization after insn patching has done so those patched
20342 	 * insns could be handled correctly.
20343 	 */
20344 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20345 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20346 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20347 								     : false;
20348 	}
20349 
20350 	if (ret == 0)
20351 		ret = fixup_call_args(env);
20352 
20353 	env->verification_time = ktime_get_ns() - start_time;
20354 	print_verification_stats(env);
20355 	env->prog->aux->verified_insns = env->insn_processed;
20356 
20357 	/* preserve original error even if log finalization is successful */
20358 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20359 	if (err)
20360 		ret = err;
20361 
20362 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20363 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20364 				  &log_true_size, sizeof(log_true_size))) {
20365 		ret = -EFAULT;
20366 		goto err_release_maps;
20367 	}
20368 
20369 	if (ret)
20370 		goto err_release_maps;
20371 
20372 	if (env->used_map_cnt) {
20373 		/* if program passed verifier, update used_maps in bpf_prog_info */
20374 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20375 							  sizeof(env->used_maps[0]),
20376 							  GFP_KERNEL);
20377 
20378 		if (!env->prog->aux->used_maps) {
20379 			ret = -ENOMEM;
20380 			goto err_release_maps;
20381 		}
20382 
20383 		memcpy(env->prog->aux->used_maps, env->used_maps,
20384 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20385 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20386 	}
20387 	if (env->used_btf_cnt) {
20388 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20389 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20390 							  sizeof(env->used_btfs[0]),
20391 							  GFP_KERNEL);
20392 		if (!env->prog->aux->used_btfs) {
20393 			ret = -ENOMEM;
20394 			goto err_release_maps;
20395 		}
20396 
20397 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20398 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20399 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20400 	}
20401 	if (env->used_map_cnt || env->used_btf_cnt) {
20402 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20403 		 * bpf_ld_imm64 instructions
20404 		 */
20405 		convert_pseudo_ld_imm64(env);
20406 	}
20407 
20408 	adjust_btf_func(env);
20409 
20410 err_release_maps:
20411 	if (!env->prog->aux->used_maps)
20412 		/* if we didn't copy map pointers into bpf_prog_info, release
20413 		 * them now. Otherwise free_used_maps() will release them.
20414 		 */
20415 		release_maps(env);
20416 	if (!env->prog->aux->used_btfs)
20417 		release_btfs(env);
20418 
20419 	/* extension progs temporarily inherit the attach_type of their targets
20420 	   for verification purposes, so set it back to zero before returning
20421 	 */
20422 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20423 		env->prog->expected_attach_type = 0;
20424 
20425 	*prog = env->prog;
20426 err_unlock:
20427 	if (!is_priv)
20428 		mutex_unlock(&bpf_verifier_lock);
20429 	vfree(env->insn_aux_data);
20430 err_free_env:
20431 	kfree(env);
20432 	return ret;
20433 }
20434